summaryrefslogtreecommitdiffstats
path: root/chromium/chrome/browser
diff options
context:
space:
mode:
authorAllan Sandfeld Jensen <allan.jensen@qt.io>2019-08-30 10:22:43 +0200
committerAllan Sandfeld Jensen <allan.jensen@qt.io>2019-08-30 12:36:28 +0000
commit271a6c3487a14599023a9106329505597638d793 (patch)
treee040d58ffc86c1480b79ca8528020ca9ec919bf8 /chromium/chrome/browser
parent7b2ffa587235a47d4094787d72f38102089f402a (diff)
BASELINE: Update Chromium to 77.0.3865.59
Change-Id: I1e89a5f3b009a9519a6705102ad65c92fe736f21 Reviewed-by: Michael BrĂ¼ning <michael.bruning@qt.io>
Diffstat (limited to 'chromium/chrome/browser')
-rw-r--r--chromium/chrome/browser/BUILD.gn429
-rw-r--r--chromium/chrome/browser/accessibility/accessibility_extension_api.cc149
-rw-r--r--chromium/chrome/browser/accessibility/accessibility_extension_api.h28
-rw-r--r--chromium/chrome/browser/accessibility/accessibility_extension_api_browsertest.cc66
-rw-r--r--chromium/chrome/browser/accessibility/accessibility_labels_service.cc2
-rw-r--r--chromium/chrome/browser/accessibility/accessibility_labels_service.h2
-rw-r--r--chromium/chrome/browser/accessibility/caption_settings_dialog.h25
-rw-r--r--chromium/chrome/browser/accessibility/caption_settings_dialog_mac.mm20
-rw-r--r--chromium/chrome/browser/accessibility/caption_settings_dialog_win.cc34
-rw-r--r--chromium/chrome/browser/accessibility/image_annotation_browsertest.cc4
-rw-r--r--chromium/chrome/browser/accessibility/interstitial_accessibility_browsertest.cc42
-rw-r--r--chromium/chrome/browser/android/metrics/BUILD.gn1
-rw-r--r--chromium/chrome/browser/android/thin_webview/BUILD.gn43
-rw-r--r--chromium/chrome/browser/android/thin_webview/internal/BUILD.gn50
-rw-r--r--chromium/chrome/browser/android/vr/BUILD.gn20
-rw-r--r--chromium/chrome/browser/apps/app_shim/BUILD.gn3
-rw-r--r--chromium/chrome/browser/browser_resources.grd200
-rw-r--r--chromium/chrome/browser/browser_switcher/bho/BUILD.gn75
-rw-r--r--chromium/chrome/browser/chrome_notification_types.h108
-rw-r--r--chromium/chrome/browser/chromeos/BUILD.gn184
-rw-r--r--chromium/chrome/browser/chromeos/kiosk_next_home/mojom/BUILD.gn18
-rw-r--r--chromium/chrome/browser/chromeos/kiosk_next_home/mojom/app_controller.mojom62
-rw-r--r--chromium/chrome/browser/chromeos/kiosk_next_home/mojom/identity_controller.mojom15
-rw-r--r--chromium/chrome/browser/chromeos/kiosk_next_home/mojom/kiosk_next_home_interface_broker.mojom24
-rw-r--r--chromium/chrome/browser/chromeos/supervision/mojom/onboarding_controller.mojom68
-rw-r--r--chromium/chrome/browser/custom_handlers/OWNERS3
-rw-r--r--chromium/chrome/browser/custom_handlers/protocol_handler_registry.cc130
-rw-r--r--chromium/chrome/browser/custom_handlers/protocol_handler_registry.h69
-rw-r--r--chromium/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc158
-rw-r--r--chromium/chrome/browser/devtools/DEPS4
-rw-r--r--chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.cc2
-rw-r--r--chromium/chrome/browser/devtools/chrome_devtools_session.cc83
-rw-r--r--chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc10
-rw-r--r--chromium/chrome/browser/devtools/device/android_device_manager.cc5
-rw-r--r--chromium/chrome/browser/devtools/device/android_device_manager.h6
-rw-r--r--chromium/chrome/browser/devtools/device/android_web_socket.cc8
-rw-r--r--chromium/chrome/browser/devtools/device/cast_device_provider.cc2
-rw-r--r--chromium/chrome/browser/devtools/device/cast_device_provider.h2
-rw-r--r--chromium/chrome/browser/devtools/device/devtools_android_bridge.cc6
-rw-r--r--chromium/chrome/browser/devtools/device/devtools_android_bridge.h2
-rw-r--r--chromium/chrome/browser/devtools/device/devtools_device_discovery.cc3
-rw-r--r--chromium/chrome/browser/devtools/device/devtools_device_discovery.h2
-rw-r--r--chromium/chrome/browser/devtools/device/port_forwarding_controller.cc4
-rw-r--r--chromium/chrome/browser/devtools/device/tcp_device_provider.cc2
-rw-r--r--chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc2
-rw-r--r--chromium/chrome/browser/devtools/device/usb/android_usb_device.cc5
-rw-r--r--chromium/chrome/browser/devtools/device/usb/android_usb_device.h2
-rw-r--r--chromium/chrome/browser/devtools/device/usb/android_usb_socket.cc3
-rw-r--r--chromium/chrome/browser/devtools/device/usb/android_usb_socket.h2
-rw-r--r--chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.cc11
-rw-r--r--chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.h2
-rw-r--r--chromium/chrome/browser/devtools/devtools_browser_context_manager.cc3
-rw-r--r--chromium/chrome/browser/devtools/devtools_browser_context_manager.h2
-rw-r--r--chromium/chrome/browser/devtools/devtools_eye_dropper.cc7
-rw-r--r--chromium/chrome/browser/devtools/devtools_eye_dropper.h2
-rw-r--r--chromium/chrome/browser/devtools/devtools_file_helper.cc3
-rw-r--r--chromium/chrome/browser/devtools/devtools_file_helper.h2
-rw-r--r--chromium/chrome/browser/devtools/devtools_file_system_indexer.cc2
-rw-r--r--chromium/chrome/browser/devtools/devtools_file_watcher.cc2
-rw-r--r--chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc74
-rw-r--r--chromium/chrome/browser/devtools/devtools_sanity_interactive_browsertest.cc4
-rw-r--r--chromium/chrome/browser/devtools/devtools_targets_ui.cc10
-rw-r--r--chromium/chrome/browser/devtools/devtools_ui_bindings.cc31
-rw-r--r--chromium/chrome/browser/devtools/devtools_ui_bindings.h2
-rw-r--r--chromium/chrome/browser/devtools/devtools_ui_bindings_unittest.cc6
-rw-r--r--chromium/chrome/browser/devtools/devtools_window.cc7
-rw-r--r--chromium/chrome/browser/devtools/global_confirm_info_bar.cc5
-rw-r--r--chromium/chrome/browser/devtools/global_confirm_info_bar.h2
-rw-r--r--chromium/chrome/browser/devtools/inspector_protocol_config.json6
-rw-r--r--chromium/chrome/browser/devtools/protocol/browser_handler.cc9
-rw-r--r--chromium/chrome/browser/devtools/protocol/cast_handler.cc9
-rw-r--r--chromium/chrome/browser/devtools/protocol/cast_handler.h2
-rw-r--r--chromium/chrome/browser/devtools/protocol/page_handler.cc8
-rw-r--r--chromium/chrome/browser/devtools/protocol/target_handler.cc5
-rw-r--r--chromium/chrome/browser/devtools/protocol/window_manager_handler.cc8
-rw-r--r--chromium/chrome/browser/extensions/BUILD.gn42
-rw-r--r--chromium/chrome/browser/extensions/api/BUILD.gn1
-rw-r--r--chromium/chrome/browser/extensions/api/activity_log_private/OWNERS1
-rw-r--r--chromium/chrome/browser/extensions/api/automation/automation_apitest.cc19
-rw-r--r--chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc38
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc57
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h8
-rw-r--r--chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc21
-rw-r--r--chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc53
-rw-r--r--chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h12
-rw-r--r--chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc403
-rw-r--r--chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc130
-rw-r--r--chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h4
-rw-r--r--chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/cookies/cookies_api.cc126
-rw-r--r--chromium/chrome/browser/extensions/api/cookies/cookies_api.h65
-rw-r--r--chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc15
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.cc12
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.h4
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc170
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc182
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc51
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc94
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc15
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h4
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.h2
-rw-r--r--chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc12
-rw-r--r--chromium/chrome/browser/extensions/api/downloads/downloads_api.cc44
-rw-r--r--chromium/chrome/browser/extensions/api/downloads/downloads_api.h13
-rw-r--r--chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc45
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h5
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc30
-rw-r--r--chromium/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc53
-rw-r--r--chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc36
-rw-r--r--chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h96
-rw-r--r--chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc768
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc15
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc106
-rw-r--r--chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/gcm/gcm_api.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_api.h8
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_apitest.cc42
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc36
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h33
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_mint_queue.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h2
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc9
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc61
-rw-r--r--chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_unittest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc18
-rw-r--r--chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc148
-rw-r--r--chromium/chrome/browser/extensions/api/management/management_apitest.cc163
-rw-r--r--chromium/chrome/browser/extensions/api/management/management_browsertest.cc12
-rw-r--r--chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc25
-rw-r--r--chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h5
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/OWNERS1
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h1
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/incognito_connectability.cc7
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/incognito_connectability.h2
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_message_port.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_message_port.h2
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc26
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h2
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc147
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc130
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h4
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc123
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc126
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h44
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc236
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.cc17
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.h2
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc96
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h10
-rw-r--r--chromium/chrome/browser/extensions/api/module/OWNERS1
-rw-r--r--chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc54
-rw-r--r--chromium/chrome/browser/extensions/api/notifications/notifications_api.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/omnibox/omnibox_api_browsertest.cc261
-rw-r--r--chromium/chrome/browser/extensions/api/omnibox/omnibox_api_interactive_test.cc294
-rw-r--r--chromium/chrome/browser/extensions/api/omnibox/omnibox_api_testbase.h62
-rw-r--r--chromium/chrome/browser/extensions/api/page_capture/page_capture_api.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc15
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/preference/preference_api.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/resources_private/resources_private_api.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc13
-rw-r--r--chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc300
-rw-r--r--chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h61
-rw-r--r--chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc112
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.cc16
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h3
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc88
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc28
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc57
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc12
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.h2
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.cc38
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h18
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc63
-rw-r--r--chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/storage/settings_apitest.cc75
-rw-r--r--chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/storage/settings_sync_util.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/storage/settings_sync_util.h6
-rw-r--r--chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h2
-rw-r--r--chromium/chrome/browser/extensions/api/streams_private/streams_private_api.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h8
-rw-r--r--chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/tab_capture/offscreen_tabs_owner.cc22
-rw-r--r--chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h2
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/app_base_window.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/app_base_window.h4
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/tabs_api.cc83
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/tabs_api.h31
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc16
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/virtual_keyboard_private/OWNERS2
-rw-r--r--chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc44
-rw-r--r--chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc89
-rw-r--r--chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc1405
-rw-r--r--chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc206
-rw-r--r--chromium/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc19
-rw-r--r--chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc174
-rw-r--r--chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc136
-rw-r--r--chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h10
-rw-r--r--chromium/chrome/browser/extensions/api/webstore_private/OWNERS3
-rw-r--r--chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc2
-rw-r--r--chromium/chrome/browser/flag-metadata.json557
-rw-r--r--chromium/chrome/browser/flag-never-expire-list.json3
-rw-r--r--chromium/chrome/browser/lookalikes/safety_tips/BUILD.gn (renamed from chromium/chrome/browser/chromeos/supervision/mojom/BUILD.gn)10
-rw-r--r--chromium/chrome/browser/media/BUILD.gn3
-rw-r--r--chromium/chrome/browser/media/router/BUILD.gn15
-rw-r--r--chromium/chrome/browser/media/router/discovery/BUILD.gn43
-rw-r--r--chromium/chrome/browser/media_router_resources.grdp40
-rw-r--r--chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc90
-rw-r--r--chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.h14
-rw-r--r--chromium/chrome/browser/notifications/scheduler/BUILD.gn127
-rw-r--r--chromium/chrome/browser/notifications/scheduler/internal/BUILD.gn96
-rw-r--r--chromium/chrome/browser/notifications/scheduler/public/BUILD.gn45
-rw-r--r--chromium/chrome/browser/notifications/scheduler/test/BUILD.gn29
-rw-r--r--chromium/chrome/browser/printing/background_printing_manager.cc2
-rw-r--r--chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.cc14
-rw-r--r--chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.h2
-rw-r--r--chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service_unittest.cc5
-rw-r--r--chromium/chrome/browser/printing/cloud_print/gcd_api_flow.cc2
-rw-r--r--chromium/chrome/browser/printing/cloud_print/gcd_api_flow.h4
-rw-r--r--chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc15
-rw-r--r--chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.h15
-rw-r--r--chromium/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc14
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow.cc19
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow.h5
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow_unittest.cc8
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_device_lister_unittest.cc15
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_http.h35
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_http_impl.cc45
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_http_impl.h12
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc5
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_local_printer_lister.cc6
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_notifications.cc53
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc15
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.h7
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc3
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_url_loader.h2
-rw-r--r--chromium/chrome/browser/printing/pdf_nup_converter_client.cc11
-rw-r--r--chromium/chrome/browser/printing/pdf_to_emf_converter.cc15
-rw-r--r--chromium/chrome/browser/printing/pdf_to_emf_converter.h3
-rw-r--r--chromium/chrome/browser/printing/pdf_to_emf_converter_browsertest.cc12
-rw-r--r--chromium/chrome/browser/printing/print_browsertest.cc4
-rw-r--r--chromium/chrome/browser/printing/print_dialog_cloud.cc9
-rw-r--r--chromium/chrome/browser/printing/print_dialog_cloud_win.cc6
-rw-r--r--chromium/chrome/browser/printing/print_job.cc48
-rw-r--r--chromium/chrome/browser/printing/print_job.h9
-rw-r--r--chromium/chrome/browser/printing/print_job_manager.cc20
-rw-r--r--chromium/chrome/browser/printing/print_job_manager.h11
-rw-r--r--chromium/chrome/browser/printing/print_job_unittest.cc17
-rw-r--r--chromium/chrome/browser/printing/print_job_worker.cc126
-rw-r--r--chromium/chrome/browser/printing/print_job_worker.h44
-rw-r--r--chromium/chrome/browser/printing/print_preview_data_service.cc2
-rw-r--r--chromium/chrome/browser/printing/print_preview_dialog_controller.cc201
-rw-r--r--chromium/chrome/browser/printing/print_preview_dialog_controller.h51
-rw-r--r--chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc15
-rw-r--r--chromium/chrome/browser/printing/print_preview_message_handler.cc10
-rw-r--r--chromium/chrome/browser/printing/print_preview_message_handler.h4
-rw-r--r--chromium/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc14
-rw-r--r--chromium/chrome/browser/printing/print_view_manager.cc12
-rw-r--r--chromium/chrome/browser/printing/print_view_manager_base.cc66
-rw-r--r--chromium/chrome/browser/printing/print_view_manager_base.h10
-rw-r--r--chromium/chrome/browser/printing/print_view_manager_unittest.cc4
-rw-r--r--chromium/chrome/browser/printing/printer_manager_dialog.h4
-rw-r--r--chromium/chrome/browser/printing/printer_manager_dialog_linux.cc2
-rw-r--r--chromium/chrome/browser/printing/printer_manager_dialog_mac.mm2
-rw-r--r--chromium/chrome/browser/printing/printer_manager_dialog_win.cc15
-rw-r--r--chromium/chrome/browser/printing/printer_query.cc76
-rw-r--r--chromium/chrome/browser/printing/printer_query.h33
-rw-r--r--chromium/chrome/browser/printing/printing_message_filter.cc66
-rw-r--r--chromium/chrome/browser/printing/printing_message_filter.h9
-rw-r--r--chromium/chrome/browser/printing/pwg_raster_converter.cc13
-rw-r--r--chromium/chrome/browser/printing/pwg_raster_converter_browsertest.cc4
-rw-r--r--chromium/chrome/browser/printing/test_print_job.cc4
-rw-r--r--chromium/chrome/browser/printing/test_print_job.h2
-rw-r--r--chromium/chrome/browser/printing/test_printer_query.cc10
-rw-r--r--chromium/chrome/browser/printing/test_printer_query.h8
-rw-r--r--chromium/chrome/browser/profiling_host/BUILD.gn1
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc23
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h2
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc6
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc3
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.h2
-rw-r--r--chromium/chrome/browser/resources/BUILD.gn45
-rw-r--r--chromium/chrome/browser/resources/about_nacl/about_nacl.html2
-rw-r--r--chromium/chrome/browser/resources/app_management/BUILD.gn19
-rw-r--r--chromium/chrome/browser/resources/app_management/actions.js12
-rw-r--r--chromium/chrome/browser/resources/app_management/api_listener.js8
-rw-r--r--chromium/chrome/browser/resources/app_management/arc_permission_view.html59
-rw-r--r--chromium/chrome/browser/resources/app_management/arc_permission_view.js8
-rw-r--r--chromium/chrome/browser/resources/app_management/browser_proxy.js51
-rw-r--r--chromium/chrome/browser/resources/app_management/chrome_app_permission_view.html73
-rw-r--r--chromium/chrome/browser/resources/app_management/chrome_app_permission_view.js2
-rw-r--r--chromium/chrome/browser/resources/app_management/expandable_app_list.html15
-rw-r--r--chromium/chrome/browser/resources/app_management/expandable_app_list.js7
-rw-r--r--chromium/chrome/browser/resources/app_management/fake_page_handler.js48
-rw-r--r--chromium/chrome/browser/resources/app_management/icons.html17
-rw-r--r--chromium/chrome/browser/resources/app_management/main_view.js9
-rw-r--r--chromium/chrome/browser/resources/app_management/metadata_view.html18
-rw-r--r--chromium/chrome/browser/resources/app_management/metadata_view.js4
-rw-r--r--chromium/chrome/browser/resources/app_management/notifications_view.html3
-rw-r--r--chromium/chrome/browser/resources/app_management/permission_item.js5
-rw-r--r--chromium/chrome/browser/resources/app_management/permission_toggle.html27
-rw-r--r--chromium/chrome/browser/resources/app_management/permission_toggle.js30
-rw-r--r--chromium/chrome/browser/resources/app_management/permission_view_header.html18
-rw-r--r--chromium/chrome/browser/resources/app_management/pin_to_shelf_item.html19
-rw-r--r--chromium/chrome/browser/resources/app_management/pin_to_shelf_item.js95
-rw-r--r--chromium/chrome/browser/resources/app_management/pwa_permission_view.html18
-rw-r--r--chromium/chrome/browser/resources/app_management/reducers.js18
-rw-r--r--chromium/chrome/browser/resources/app_management/shared_style.html31
-rw-r--r--chromium/chrome/browser/resources/app_management/shared_vars.html4
-rw-r--r--chromium/chrome/browser/resources/app_management/toggle_row.html55
-rw-r--r--chromium/chrome/browser/resources/app_management/toggle_row.js34
-rw-r--r--chromium/chrome/browser/resources/app_management/types.js1
-rw-r--r--chromium/chrome/browser/resources/app_management/util.js33
-rw-r--r--chromium/chrome/browser/resources/bluetooth_internals/adapter_broker.js2
-rw-r--r--chromium/chrome/browser/resources/bookmarks/BUILD.gn1
-rw-r--r--chromium/chrome/browser/resources/bookmarks/app.html8
-rw-r--r--chromium/chrome/browser/resources/bookmarks/bookmarks.html4
-rw-r--r--chromium/chrome/browser/resources/bookmarks/command_manager.html12
-rw-r--r--chromium/chrome/browser/resources/bookmarks/dnd_manager.js27
-rw-r--r--chromium/chrome/browser/resources/bookmarks/edit_dialog.html13
-rw-r--r--chromium/chrome/browser/resources/bookmarks/folder_node.html10
-rw-r--r--chromium/chrome/browser/resources/bookmarks/images/folder.svg1
-rw-r--r--chromium/chrome/browser/resources/bookmarks/item.html27
-rw-r--r--chromium/chrome/browser/resources/bookmarks/item.js27
-rw-r--r--chromium/chrome/browser/resources/bookmarks/list.js9
-rw-r--r--chromium/chrome/browser/resources/bookmarks/shared_style.html30
-rw-r--r--chromium/chrome/browser/resources/bookmarks/shared_vars.html12
-rw-r--r--chromium/chrome/browser/resources/bookmarks/toolbar.html6
-rw-r--r--chromium/chrome/browser/resources/browser_switch/browser_switch.html2
-rw-r--r--chromium/chrome/browser/resources/browser_switch/internals/browser_switch_internals.html48
-rw-r--r--chromium/chrome/browser/resources/browser_switch/internals/browser_switch_internals.js134
-rw-r--r--chromium/chrome/browser/resources/certificate_viewer.css2
-rw-r--r--chromium/chrome/browser/resources/certificate_viewer.html44
-rw-r--r--chromium/chrome/browser/resources/chromeos/BUILD.gn28
-rw-r--r--chromium/chrome/browser/resources/chromeos/autoclick/BUILD.gn137
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/BUILD.gn33
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd125
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/manifest.json18
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/_locales/en/messages.json4
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/BUILD.gn41
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/browser_proxy/BUILD.gn20
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/device/BUILD.gn35
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn28
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/mojo/BUILD.gn19
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd3
-rw-r--r--chromium/chrome/browser/resources/chromeos/chromevox/BUILD.gn2
-rw-r--r--chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd5
-rw-r--r--chromium/chrome/browser/resources/chromeos/internet_detail_dialog/BUILD.gn2
-rw-r--r--chromium/chrome/browser/resources/chromeos/kiosk_next_home/BUILD.gn29
-rw-r--r--chromium/chrome/browser/resources/chromeos/kiosk_next_home/kiosk_next_resources.grdp18
-rw-r--r--chromium/chrome/browser/resources/chromeos/kiosk_next_home/manifest.json23
-rw-r--r--chromium/chrome/browser/resources/chromeos/login/BUILD.gn36
-rw-r--r--chromium/chrome/browser/resources/chromeos/network_ui/BUILD.gn3
-rw-r--r--chromium/chrome/browser/resources/chromeos/select_to_speak/BUILD.gn2
-rw-r--r--chromium/chrome/browser/resources/chromeos/switch_access/BUILD.gn24
-rw-r--r--chromium/chrome/browser/resources/chromeos/switch_access/strings/switch_access_strings.grd32
-rw-r--r--chromium/chrome/browser/resources/component_extension_resources.grd3
-rw-r--r--chromium/chrome/browser/resources/cryptotoken/enroller.js8
-rw-r--r--chromium/chrome/browser/resources/default_apps/OWNERS1
-rw-r--r--chromium/chrome/browser/resources/device_log_ui/device_log_ui.html1
-rw-r--r--chromium/chrome/browser/resources/device_log_ui/device_log_ui.js13
-rw-r--r--chromium/chrome/browser/resources/discards/database_tab.js23
-rw-r--r--chromium/chrome/browser/resources/discards/discards.js16
-rw-r--r--chromium/chrome/browser/resources/discards/discards_tab.html2
-rw-r--r--chromium/chrome/browser/resources/discards/discards_tab.js36
-rw-r--r--chromium/chrome/browser/resources/discards/graph_tab.js14
-rw-r--r--chromium/chrome/browser/resources/domain_reliability_internals/domain_reliability_internals.html2
-rw-r--r--chromium/chrome/browser/resources/downloads/browser_proxy.js9
-rw-r--r--chromium/chrome/browser/resources/downloads/downloads.html4
-rw-r--r--chromium/chrome/browser/resources/downloads/item.html108
-rw-r--r--chromium/chrome/browser/resources/downloads/manager.html24
-rw-r--r--chromium/chrome/browser/resources/downloads/manager.js2
-rw-r--r--chromium/chrome/browser/resources/downloads/toolbar.html6
-rw-r--r--chromium/chrome/browser/resources/engagement/site_engagement.js19
-rw-r--r--chromium/chrome/browser/resources/eoc_internals/BUILD.gn18
-rw-r--r--chromium/chrome/browser/resources/eoc_internals/eoc_internals.html138
-rw-r--r--chromium/chrome/browser/resources/eoc_internals/eoc_internals.js155
-rw-r--r--chromium/chrome/browser/resources/explore_sites_internals/explore_sites_internals.js2
-rw-r--r--chromium/chrome/browser/resources/extensions/BUILD.gn2
-rw-r--r--chromium/chrome/browser/resources/extensions/activity_log/activity_log.html9
-rw-r--r--chromium/chrome/browser/resources/extensions/activity_log/activity_log.js8
-rw-r--r--chromium/chrome/browser/resources/extensions/activity_log/activity_log_history.html10
-rw-r--r--chromium/chrome/browser/resources/extensions/activity_log/activity_log_history.js28
-rw-r--r--chromium/chrome/browser/resources/extensions/activity_log/activity_log_stream.html15
-rw-r--r--chromium/chrome/browser/resources/extensions/code_section.html42
-rw-r--r--chromium/chrome/browser/resources/extensions/detail_view.html43
-rw-r--r--chromium/chrome/browser/resources/extensions/detail_view.js4
-rw-r--r--chromium/chrome/browser/resources/extensions/drag_and_drop_handler.html1
-rw-r--r--chromium/chrome/browser/resources/extensions/drag_and_drop_handler.js17
-rw-r--r--chromium/chrome/browser/resources/extensions/drop_overlay.html8
-rw-r--r--chromium/chrome/browser/resources/extensions/error_page.html17
-rw-r--r--chromium/chrome/browser/resources/extensions/error_page.js2
-rw-r--r--chromium/chrome/browser/resources/extensions/extensions.html17
-rw-r--r--chromium/chrome/browser/resources/extensions/install_warnings_dialog.html19
-rw-r--r--chromium/chrome/browser/resources/extensions/item.html31
-rw-r--r--chromium/chrome/browser/resources/extensions/item.js6
-rw-r--r--chromium/chrome/browser/resources/extensions/item_list.html6
-rw-r--r--chromium/chrome/browser/resources/extensions/keyboard_shortcuts.html7
-rw-r--r--chromium/chrome/browser/resources/extensions/kiosk_dialog.html29
-rw-r--r--chromium/chrome/browser/resources/extensions/load_error.html13
-rw-r--r--chromium/chrome/browser/resources/extensions/manager.js45
-rw-r--r--chromium/chrome/browser/resources/extensions/navigation_helper.js76
-rw-r--r--chromium/chrome/browser/resources/extensions/options_dialog.html52
-rw-r--r--chromium/chrome/browser/resources/extensions/options_dialog.js16
-rw-r--r--chromium/chrome/browser/resources/extensions/pack_dialog.html23
-rw-r--r--chromium/chrome/browser/resources/extensions/pack_dialog_alert.html13
-rw-r--r--chromium/chrome/browser/resources/extensions/runtime_host_permissions.html9
-rw-r--r--chromium/chrome/browser/resources/extensions/runtime_hosts_dialog.html13
-rw-r--r--chromium/chrome/browser/resources/extensions/service.js40
-rw-r--r--chromium/chrome/browser/resources/extensions/shared_vars.html6
-rw-r--r--chromium/chrome/browser/resources/extensions/sidebar.html6
-rw-r--r--chromium/chrome/browser/resources/extensions/sidebar.js6
-rw-r--r--chromium/chrome/browser/resources/extensions/toolbar.html44
-rw-r--r--chromium/chrome/browser/resources/extensions/toolbar.js2
-rw-r--r--chromium/chrome/browser/resources/feed_internals/feed_internals.js4
-rw-r--r--chromium/chrome/browser/resources/gaia_auth_host/authenticator.js227
-rw-r--r--chromium/chrome/browser/resources/hats/hats.html80
-rw-r--r--chromium/chrome/browser/resources/hats/hats.js27
-rw-r--r--chromium/chrome/browser/resources/history/app.html9
-rw-r--r--chromium/chrome/browser/resources/history/externs.js1
-rw-r--r--chromium/chrome/browser/resources/history/history.html9
-rw-r--r--chromium/chrome/browser/resources/history/history_item.html6
-rw-r--r--chromium/chrome/browser/resources/history/history_item.js3
-rw-r--r--chromium/chrome/browser/resources/history/history_list.html13
-rw-r--r--chromium/chrome/browser/resources/history/history_toolbar.html1
-rw-r--r--chromium/chrome/browser/resources/history/lazy_load.html2
-rw-r--r--chromium/chrome/browser/resources/history/shared_vars.html16
-rw-r--r--chromium/chrome/browser/resources/history/synced_device_card.js5
-rw-r--r--chromium/chrome/browser/resources/history/synced_device_manager.html15
-rw-r--r--chromium/chrome/browser/resources/identity_internals/identity_internals.css1
-rw-r--r--chromium/chrome/browser/resources/identity_internals/identity_internals.html8
-rw-r--r--chromium/chrome/browser/resources/identity_internals/identity_internals.js18
-rw-r--r--chromium/chrome/browser/resources/interventions_internals/BUILD.gn (renamed from chromium/chrome/browser/resources/media_router/elements/media_router_header/BUILD.gn)11
-rw-r--r--chromium/chrome/browser/resources/interventions_internals/index.js46
-rw-r--r--chromium/chrome/browser/resources/kiosk_next_internal_resources.grd16
-rw-r--r--chromium/chrome/browser/resources/local_discovery/local_discovery.js44
-rw-r--r--chromium/chrome/browser/resources/local_ntp/BUILD.gn2
-rw-r--r--chromium/chrome/browser/resources/local_ntp/OWNERS8
-rw-r--r--chromium/chrome/browser/resources/local_ntp/animations.css112
-rw-r--r--chromium/chrome/browser/resources/local_ntp/animations.js5
-rw-r--r--chromium/chrome/browser/resources/local_ntp/custom_backgrounds.js1489
-rw-r--r--chromium/chrome/browser/resources/local_ntp/custom_links_edit.css73
-rw-r--r--chromium/chrome/browser/resources/local_ntp/custom_links_edit.js40
-rw-r--r--chromium/chrome/browser/resources/local_ntp/customize.css (renamed from chromium/chrome/browser/resources/local_ntp/custom_backgrounds.css)210
-rw-r--r--chromium/chrome/browser/resources/local_ntp/customize.js2432
-rw-r--r--chromium/chrome/browser/resources/local_ntp/doodles.css53
-rw-r--r--chromium/chrome/browser/resources/local_ntp/doodles.js107
-rw-r--r--chromium/chrome/browser/resources/local_ntp/externs.js78
-rw-r--r--chromium/chrome/browser/resources/local_ntp/icons/brush.svg1
-rw-r--r--chromium/chrome/browser/resources/local_ntp/icons/check_circle.svg1
-rw-r--r--chromium/chrome/browser/resources/local_ntp/icons/colored_header.svg96
-rw-r--r--chromium/chrome/browser/resources/local_ntp/icons/colorize.svg1
-rw-r--r--chromium/chrome/browser/resources/local_ntp/icons/default_theme.svg1
-rw-r--r--chromium/chrome/browser/resources/local_ntp/icons/default_theme_dark.svg1
-rw-r--r--chromium/chrome/browser/resources/local_ntp/local_ntp.css1203
-rw-r--r--chromium/chrome/browser/resources/local_ntp/local_ntp.html213
-rw-r--r--chromium/chrome/browser/resources/local_ntp/local_ntp.js462
-rw-r--r--chromium/chrome/browser/resources/local_ntp/local_ntp_common.css6
-rw-r--r--chromium/chrome/browser/resources/local_ntp/local_ntp_resources.grd4
-rw-r--r--chromium/chrome/browser/resources/local_ntp/most_visited_single.css159
-rw-r--r--chromium/chrome/browser/resources/local_ntp/most_visited_single.js427
-rw-r--r--chromium/chrome/browser/resources/local_ntp/most_visited_title.js1
-rw-r--r--chromium/chrome/browser/resources/local_ntp/most_visited_util.js11
-rw-r--r--chromium/chrome/browser/resources/local_ntp/utils.js5
-rw-r--r--chromium/chrome/browser/resources/local_ntp/voice.css121
-rw-r--r--chromium/chrome/browser/resources/local_ntp/voice.js126
-rw-r--r--chromium/chrome/browser/resources/management/icons.html1
-rw-r--r--chromium/chrome/browser/resources/management/management.html3
-rw-r--r--chromium/chrome/browser/resources/management/management_browser_proxy.js134
-rw-r--r--chromium/chrome/browser/resources/management/management_ui.html25
-rw-r--r--chromium/chrome/browser/resources/management/management_ui.js474
-rw-r--r--chromium/chrome/browser/resources/media_router/BUILD.gn58
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/issue_banner/BUILD.gn18
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.css61
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.html31
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.js145
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_container/BUILD.gn39
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.css283
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.html240
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js2624
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container_interface.js176
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_container/pseudo_sink_search_state.js73
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.css83
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.html43
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.js233
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/BUILD.gn17
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.css7
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.html8
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.js79
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/route_controls/BUILD.gn28
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.css114
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.html114
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.js547
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls_interface.js20
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/route_details/BUILD.gn21
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/route_details/route_details.css26
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/route_details/route_details.html34
-rw-r--r--chromium/chrome/browser/resources/media_router/elements/route_details/route_details.js221
-rw-r--r--chromium/chrome/browser/resources/media_router/externs.js59
-rw-r--r--chromium/chrome/browser/resources/media_router/icons/media_router_icons.html29
-rw-r--r--chromium/chrome/browser/resources/media_router/media_router.css24
-rw-r--r--chromium/chrome/browser/resources/media_router/media_router.html20
-rw-r--r--chromium/chrome/browser/resources/media_router/media_router.js397
-rw-r--r--chromium/chrome/browser/resources/media_router/media_router_browser_api.js359
-rw-r--r--chromium/chrome/browser/resources/media_router/media_router_common.css36
-rw-r--r--chromium/chrome/browser/resources/media_router/media_router_data.js355
-rw-r--r--chromium/chrome/browser/resources/media_router/media_router_ui_interface.js234
-rw-r--r--chromium/chrome/browser/resources/notifications_internals/BUILD.gn27
-rw-r--r--chromium/chrome/browser/resources/notifications_internals/notifications_internals.css (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome.css)8
-rw-r--r--chromium/chrome/browser/resources/notifications_internals/notifications_internals.html42
-rw-r--r--chromium/chrome/browser/resources/notifications_internals/notifications_internals.js28
-rw-r--r--chromium/chrome/browser/resources/notifications_internals/notifications_internals_browser_proxy.js34
-rw-r--r--chromium/chrome/browser/resources/ntp4/BUILD.gn1
-rw-r--r--chromium/chrome/browser/resources/ntp4/apps_page.js8
-rw-r--r--chromium/chrome/browser/resources/ntp4/guest_tab.html2
-rw-r--r--chromium/chrome/browser/resources/ntp4/images/2x/disclosure_triangle_mask.pngbin197 -> 0 bytes
-rw-r--r--chromium/chrome/browser/resources/ntp4/images/disclosure_triangle_mask.pngbin90 -> 0 bytes
-rw-r--r--chromium/chrome/browser/resources/ntp4/images/trash.pngbin0 -> 150 bytes
-rw-r--r--chromium/chrome/browser/resources/ntp4/incognito_and_guest_tab.css14
-rw-r--r--chromium/chrome/browser/resources/ntp4/incognito_tab.css89
-rw-r--r--chromium/chrome/browser/resources/ntp4/incognito_tab.html5
-rw-r--r--chromium/chrome/browser/resources/ntp4/incognito_tab.js36
-rw-r--r--chromium/chrome/browser/resources/ntp4/new_tab.html3
-rw-r--r--chromium/chrome/browser/resources/ntp4/new_tab.js2
-rw-r--r--chromium/chrome/browser/resources/ntp4/trash.css59
-rw-r--r--chromium/chrome/browser/resources/omnibox/BUILD.gn1
-rw-r--r--chromium/chrome/browser/resources/omnibox/omnibox.html84
-rw-r--r--chromium/chrome/browser/resources/omnibox/omnibox.js48
-rw-r--r--chromium/chrome/browser/resources/omnibox/omnibox_input.css8
-rw-r--r--chromium/chrome/browser/resources/omnibox/omnibox_input.js5
-rw-r--r--chromium/chrome/browser/resources/omnibox/omnibox_output.js100
-rw-r--r--chromium/chrome/browser/resources/omnibox/output_results_group.css42
-rw-r--r--chromium/chrome/browser/resources/page_not_available_for_guest/app.html3
-rw-r--r--chromium/chrome/browser/resources/pdf/browser_api.js9
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.html3
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-error-screen/viewer-error-screen.html9
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-form-warning/viewer-form-warning.html13
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.html1
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js12
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.html68
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.js7
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-password-screen/viewer-password-screen.html9
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.html4
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js8
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.html49
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.html14
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js41
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf_viewer.js15
-rw-r--r--chromium/chrome/browser/resources/pdf/toolbar_manager.js6
-rw-r--r--chromium/chrome/browser/resources/policy/policy.html8
-rw-r--r--chromium/chrome/browser/resources/policy/policy_base.js24
-rw-r--r--chromium/chrome/browser/resources/print_preview/BUILD.gn10
-rw-r--r--chromium/chrome/browser/resources/print_preview/cloud_print_interface.js132
-rw-r--r--chromium/chrome/browser/resources/print_preview/cloud_print_interface_js.js51
-rw-r--r--chromium/chrome/browser/resources/print_preview/cloud_print_interface_manager.js6
-rw-r--r--chromium/chrome/browser/resources/print_preview/cloud_print_interface_native.js3
-rw-r--r--chromium/chrome/browser/resources/print_preview/dark_mode_behavior.html4
-rw-r--r--chromium/chrome/browser/resources/print_preview/dark_mode_behavior.js39
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/destination_store.html1
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/destination_store.js59
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/document_info.js29
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/model.js97
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/user_manager.js20
-rw-r--r--chromium/chrome/browser/resources/print_preview/native_layer.js208
-rw-r--r--chromium/chrome/browser/resources/print_preview/polymer3/demo.js2
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview.html23
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview_resources.grd6
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview_utils.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview_utils.js5
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/BUILD.gn4
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/advanced_options_settings.html11
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.html23
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.js15
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/advanced_settings_item.html11
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/app.html6
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/app.js29
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/button_strip.html27
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/button_strip.js9
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/color_settings.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/copies_settings.js3
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_dialog.html74
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_dialog.js44
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_list.html6
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_list.js4
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_list_item.html6
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_select.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_settings.html1
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_settings.js89
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/duplex_settings.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/header.html27
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/header.js17
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/header_new.html8
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/header_new.js29
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/input_behavior.js7
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/layout_settings.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/margin_control.html118
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/margin_control.js124
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/margin_control_container.html7
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/margin_control_container.js56
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/margins_settings.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/pages_per_sheet_settings.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/pages_settings.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/pages_settings.js10
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/pin_settings.js3
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/plugin_proxy.js15
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/preview_area.html3
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/preview_area.js43
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/print_preview_search_box.html11
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/print_preview_search_box.js4
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/print_preview_shared_css.html40
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/print_preview_vars_css.html17
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/provisional_destination_resolver.html23
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/scaling_settings.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/scaling_settings.js3
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/settings_behavior.js12
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/settings_select.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/sidebar.html22
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/sidebar.js19
-rw-r--r--chromium/chrome/browser/resources/quota_internals/main.css6
-rw-r--r--chromium/chrome/browser/resources/quota_internals/main.html2
-rw-r--r--chromium/chrome/browser/resources/safety_tips/BUILD.gn50
-rw-r--r--chromium/chrome/browser/resources/safety_tips/OWNERS1
-rwxr-xr-xchromium/chrome/browser/resources/safety_tips/gen_safety_tips_proto.py72
-rw-r--r--chromium/chrome/browser/resources/safety_tips/safety_tips.asciipb17
-rw-r--r--chromium/chrome/browser/resources/settings/BUILD.gn2
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/BUILD.gn28
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html72
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/a11y_page.js39
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/captions_browser_proxy.html2
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/captions_browser_proxy.js35
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.html91
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.js217
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html31
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.html74
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.js168
-rw-r--r--chromium/chrome/browser/resources/settings/a11y_page/tts_subpage.html38
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/about_page.html80
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/about_page.js49
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js43
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.html18
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/detailed_build_info.html6
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/detailed_build_info.js2
-rw-r--r--chromium/chrome/browser/resources/settings/about_page/update_warning_dialog.html12
-rw-r--r--chromium/chrome/browser/resources/settings/android_apps_page/android_apps_page.html10
-rw-r--r--chromium/chrome/browser/resources/settings/android_apps_page/android_apps_subpage.html10
-rw-r--r--chromium/chrome/browser/resources/settings/app_management_page/BUILD.gn5
-rw-r--r--chromium/chrome/browser/resources/settings/app_management_page/app_management_page.html7
-rw-r--r--chromium/chrome/browser/resources/settings/app_management_page/app_management_page.js6
-rw-r--r--chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.html24
-rw-r--r--chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js16
-rw-r--r--chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html40
-rw-r--r--chromium/chrome/browser/resources/settings/appearance_page/home_url_input.html4
-rw-r--r--chromium/chrome/browser/resources/settings/autofill_page/address_edit_dialog.html38
-rw-r--r--chromium/chrome/browser/resources/settings/autofill_page/autofill_section.html6
-rw-r--r--chromium/chrome/browser/resources/settings/autofill_page/blocking_request_manager.js8
-rw-r--r--chromium/chrome/browser/resources/settings/autofill_page/credit_card_edit_dialog.html35
-rw-r--r--chromium/chrome/browser/resources/settings/autofill_page/password_edit_dialog.html23
-rw-r--r--chromium/chrome/browser/resources/settings/autofill_page/passwords_export_dialog.html37
-rw-r--r--chromium/chrome/browser/resources/settings/autofill_page/passwords_section.html5
-rw-r--r--chromium/chrome/browser/resources/settings/autofill_page/passwords_section.js12
-rw-r--r--chromium/chrome/browser/resources/settings/autofill_page/payments_section.html6
-rw-r--r--chromium/chrome/browser/resources/settings/basic_page/basic_page.html29
-rw-r--r--chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js8
-rw-r--r--chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.html44
-rw-r--r--chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.js46
-rw-r--r--chromium/chrome/browser/resources/settings/change_password_page/change_password_page.html8
-rw-r--r--chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html6
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/BUILD.gn3
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_a11y_page/BUILD.gn1
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_about_page/BUILD.gn26
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_files_page/BUILD.gn (renamed from chromium/chrome/browser/resources/settings/chromeos/os_downloads_page/BUILD.gn)4
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_languages_page/BUILD.gn58
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_printing_page/BUILD.gn27
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_settings_menu/BUILD.gn1
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_settings_page/BUILD.gn1
-rw-r--r--chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html43
-rw-r--r--chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js13
-rw-r--r--chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.html5
-rw-r--r--chromium/chrome/browser/resources/settings/controls/controlled_button.html6
-rw-r--r--chromium/chrome/browser/resources/settings/controls/controlled_button.js4
-rw-r--r--chromium/chrome/browser/resources/settings/controls/extension_controlled_indicator.html6
-rw-r--r--chromium/chrome/browser/resources/settings/controls/password_prompt_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_dropdown_menu.html2
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_radio_group.html4
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_radio_group.js2
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_slider.html6
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_textarea.html17
-rw-r--r--chromium/chrome/browser/resources/settings/controls/settings_textarea.js42
-rw-r--r--chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.html16
-rw-r--r--chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.js15
-rw-r--r--chromium/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.html26
-rw-r--r--chromium/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.js28
-rw-r--r--chromium/chrome/browser/resources/settings/crostini_page/crostini_page.html6
-rw-r--r--chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.html6
-rw-r--r--chromium/chrome/browser/resources/settings/date_time_page/date_time_page.js25
-rw-r--r--chromium/chrome/browser/resources/settings/default_browser_page/default_browser_page.html18
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/display.html28
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/display.js4
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/display_overscan_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/drive_cache_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/keyboard.js4
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/power.html2
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/storage.js12
-rw-r--r--chromium/chrome/browser/resources/settings/device_page/stylus.html6
-rw-r--r--chromium/chrome/browser/resources/settings/downloads_page/downloads_page.html9
-rw-r--r--chromium/chrome/browser/resources/settings/downloads_page/smb_shares_page.html8
-rw-r--r--chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.html16
-rw-r--r--chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.js18
-rw-r--r--chromium/chrome/browser/resources/settings/icons.html12
-rw-r--r--chromium/chrome/browser/resources/settings/incompatible_applications_page/incompatible_application_item.html6
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/BUILD.gn12
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_config.html20
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_config.js1
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.html44
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.js237
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.html19
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js71
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_page.html14
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_page.js207
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html6
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js278
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html13
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_summary.html10
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_summary.js288
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_summary_item.html12
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js251
-rw-r--r--chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/kiosk_next_shell_page/BUILD.gn27
-rw-r--r--chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.html34
-rw-r--r--chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.js95
-rw-r--r--chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_page.html36
-rw-r--r--chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_page.js65
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/BUILD.gn1
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.html34
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.html19
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js116
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/languages_page.html76
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/languages_page.js169
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/manage_input_methods_page.html1
-rw-r--r--chromium/chrome/browser/resources/settings/languages_page/manage_input_methods_page.js3
-rw-r--r--chromium/chrome/browser/resources/settings/multidevice_page/BUILD.gn157
-rw-r--r--chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_item.html47
-rw-r--r--chromium/chrome/browser/resources/settings/multidevice_page/multidevice_page.html66
-rw-r--r--chromium/chrome/browser/resources/settings/multidevice_page/multidevice_radio_button.html10
-rw-r--r--chromium/chrome/browser/resources/settings/multidevice_page/multidevice_smartlock_subpage.html12
-rw-r--r--chromium/chrome/browser/resources/settings/multidevice_page/multidevice_subpage.html18
-rw-r--r--chromium/chrome/browser/resources/settings/multidevice_page/multidevice_subpage.js36
-rw-r--r--chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.html2
-rw-r--r--chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.js149
-rw-r--r--chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.html3
-rw-r--r--chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html2
-rw-r--r--chromium/chrome/browser/resources/settings/os_settings_manifest.json13
-rw-r--r--chromium/chrome/browser/resources/settings/os_settings_resources.grd179
-rw-r--r--chromium/chrome/browser/resources/settings/os_settings_resources_vulcanized.grd5
-rw-r--r--chromium/chrome/browser/resources/settings/page_visibility.js26
-rw-r--r--chromium/chrome/browser/resources/settings/parental_controls_page/BUILD.gn27
-rw-r--r--chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_browser_proxy.html2
-rw-r--r--chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_browser_proxy.js45
-rw-r--r--chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.html56
-rw-r--r--chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.js87
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/BUILD.gn2
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/account_manager.html17
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/account_manager.js23
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js10
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/change_picture.html4
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/change_picture.js21
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/fingerprint_list.html6
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/import_data_dialog.html16
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.html101
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.js79
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/kerberos_accounts_browser_proxy.js78
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.html144
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.js287
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/lock_screen.html62
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/lock_screen.js13
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/people_page.html105
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/people_page.js9
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html34
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js48
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.js2
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/signout_dialog.html24
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/sync_account_control.html69
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/sync_page.html39
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/sync_page.js2
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/user_list.html5
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/user_list.js1
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/users_add_user_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/people_page/users_page.html11
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/BUILD.gn162
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.html123
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js336
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_elements.html4
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_elements.js10
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.html56
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.js121
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.html17
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.js127
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printer_dialog_util.js47
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html27
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.html2
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.js23
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printers.html130
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printers.js157
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printers_browser_proxy.js12
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.html47
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.js68
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.html32
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.js80
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.html4
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.js10
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.html27
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.js130
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/printing_page.html5
-rw-r--r--chromium/chrome/browser/resources/settings/printing_page/printing_page.js12
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/BUILD.gn16
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/personalization_options.html6
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html24
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js11
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/security_keys_browser_proxy.js139
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.html128
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.js268
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/security_keys_pin_field.html34
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/security_keys_pin_field.js161
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/security_keys_reset_dialog.html9
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/security_keys_reset_dialog.js15
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.html73
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.js330
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.html15
-rw-r--r--chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.js26
-rw-r--r--chromium/chrome/browser/resources/settings/reset_page/powerwash_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/reset_page/reset_profile_banner.html10
-rw-r--r--chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html22
-rw-r--r--chromium/chrome/browser/resources/settings/route.js76
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.html7
-rw-r--r--chromium/chrome/browser/resources/settings/search_page/search_page.html24
-rw-r--r--chromium/chrome/browser/resources/settings/settings.html4
-rw-r--r--chromium/chrome/browser/resources/settings/settings_main/settings_main.html3
-rw-r--r--chromium/chrome/browser/resources/settings/settings_main/settings_main.js2
-rw-r--r--chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html32
-rw-r--r--chromium/chrome/browser/resources/settings/settings_menu/settings_menu.js6
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/main_page_behavior.js7
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/settings_animated_pages.js3
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/settings_section.html9
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html9
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/settings_subpage.js9
-rw-r--r--chromium/chrome/browser/resources/settings/settings_resources.grd86
-rw-r--r--chromium/chrome/browser/resources/settings/settings_shared_css.html21
-rw-r--r--chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html17
-rw-r--r--chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js18
-rw-r--r--chromium/chrome/browser/resources/settings/settings_vars_css.html12
-rw-r--r--chromium/chrome/browser/resources/settings/site_favicon.js4
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/all_sites.html19
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/chooser_exception_list.js4
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.html10
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/media_picker.html2
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_data.html14
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_data.js3
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_details.html97
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_details.js28
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_details_permission.html2
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_list.html6
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_list.js6
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_list_entry.html6
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/site_list_entry.js10
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings/zoom_levels.js2
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html20
-rw-r--r--chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.js8
-rw-r--r--chromium/chrome/browser/resources/settings/system_page/system_page.html21
-rw-r--r--chromium/chrome/browser/resources/settings/system_page/system_page.js19
-rw-r--r--chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration.svg1
-rw-r--r--chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.html26
-rw-r--r--chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.js32
-rw-r--r--chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.html13
-rw-r--r--chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.js2
-rw-r--r--chromium/chrome/browser/resources/signin/signin_error/signin_error.html17
-rw-r--r--chromium/chrome/browser/resources/signin/signin_error/signin_error.js2
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/BUILD.gn (renamed from chromium/chrome/browser/resources/signin/dice_sync_confirmation/BUILD.gn)0
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/images/ic_google.png (renamed from chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/ic_google.png)bin481 -> 481 bytes
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/images/ic_google_2x.png (renamed from chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/ic_google_2x.png)bin857 -> 857 bytes
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration.svg1
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration_dark.svg (renamed from chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration_dark.svg)0
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html428
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js93
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.html (renamed from chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.html)42
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.js (renamed from chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.js)2
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.html (renamed from chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.html)0
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.js (renamed from chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.js)4
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.html73
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.js77
-rw-r--r--chromium/chrome/browser/resources/snippets_internals/snippets_internals.js2
-rw-r--r--chromium/chrome/browser/resources/sync_file_system_internals/main.html2
-rw-r--r--chromium/chrome/browser/resources/usb_internals/descriptor_panel.js1694
-rw-r--r--chromium/chrome/browser/resources/usb_internals/devices_page.js135
-rw-r--r--chromium/chrome/browser/resources/usb_internals/usb_internals.css42
-rw-r--r--chromium/chrome/browser/resources/usb_internals/usb_internals.html80
-rw-r--r--chromium/chrome/browser/resources/user_manager/control_bar.html16
-rw-r--r--chromium/chrome/browser/resources/user_manager/create_profile.html31
-rw-r--r--chromium/chrome/browser/resources/user_manager/create_profile.js11
-rw-r--r--chromium/chrome/browser/resources/user_manager/shared_styles.html23
-rw-r--r--chromium/chrome/browser/resources/user_manager/user_manager.html72
-rw-r--r--chromium/chrome/browser/resources/user_manager/user_manager_tutorial.html41
-rw-r--r--chromium/chrome/browser/resources/user_manager/user_manager_tutorial.js6
-rw-r--r--chromium/chrome/browser/resources/webapks/BUILD.gn4
-rw-r--r--chromium/chrome/browser/resources/webapks/about_webapks.html7
-rw-r--r--chromium/chrome/browser/resources/webapks/about_webapks.js73
-rw-r--r--chromium/chrome/browser/resources/welcome/BUILD.gn (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/BUILD.gn)1
-rw-r--r--chromium/chrome/browser/resources/welcome/default.webpbin28802 -> 0 bytes
-rw-r--r--chromium/chrome/browser/resources/welcome/dice_welcome/BUILD.gn27
-rw-r--r--chromium/chrome/browser/resources/welcome/dice_welcome/welcome.css42
-rw-r--r--chromium/chrome/browser/resources/welcome/dice_welcome/welcome.html22
-rw-r--r--chromium/chrome/browser/resources/welcome/dice_welcome/welcome_app.html181
-rw-r--r--chromium/chrome/browser/resources/welcome/dice_welcome/welcome_app.js36
-rw-r--r--chromium/chrome/browser/resources/welcome/dice_welcome/welcome_browser_proxy.js37
-rw-r--r--chromium/chrome/browser/resources/welcome/google_apps/BUILD.gn (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/BUILD.gn)11
-rw-r--r--chromium/chrome/browser/resources/welcome/google_apps/google_app_proxy.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_app_proxy.html)1
-rw-r--r--chromium/chrome/browser/resources/welcome/google_apps/google_app_proxy.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_app_proxy.js)27
-rw-r--r--chromium/chrome/browser/resources/welcome/google_apps/google_apps_metrics_proxy.html3
-rw-r--r--chromium/chrome/browser/resources/welcome/google_apps/google_apps_metrics_proxy.js19
-rw-r--r--chromium/chrome/browser/resources/welcome/google_apps/nux_google_apps.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.html)21
-rw-r--r--chromium/chrome/browser/resources/welcome/google_apps/nux_google_apps.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.js)36
-rw-r--r--chromium/chrome/browser/resources/welcome/images/background_svgs/blue_circle.svg (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/blue_circle.svg)0
-rw-r--r--chromium/chrome/browser/resources/welcome/images/background_svgs/green_rectangle.svg (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/green_rectangle.svg)0
-rw-r--r--chromium/chrome/browser/resources/welcome/images/background_svgs/grey_oval.svg (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/grey_oval.svg)0
-rw-r--r--chromium/chrome/browser/resources/welcome/images/background_svgs/grey_rounded_rectangle.svg (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/grey_rounded_rectangle.svg)0
-rw-r--r--chromium/chrome/browser/resources/welcome/images/background_svgs/red_triangle.svg (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/red_triangle.svg)0
-rw-r--r--chromium/chrome/browser/resources/welcome/images/background_svgs/yellow_dots.svg (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/yellow_dots.svg)0
-rw-r--r--chromium/chrome/browser/resources/welcome/images/background_svgs/yellow_semicircle.svg (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/yellow_semicircle.svg)0
-rw-r--r--chromium/chrome/browser/resources/welcome/landing_view.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view.html)11
-rw-r--r--chromium/chrome/browser/resources/welcome/landing_view.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view.js)4
-rw-r--r--chromium/chrome/browser/resources/welcome/landing_view_proxy.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view_proxy.html)0
-rw-r--r--chromium/chrome/browser/resources/welcome/landing_view_proxy.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view_proxy.js)4
-rw-r--r--chromium/chrome/browser/resources/welcome/navigation_behavior.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/navigation_behavior.html)0
-rw-r--r--chromium/chrome/browser/resources/welcome/navigation_behavior.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/navigation_behavior.js)0
-rw-r--r--chromium/chrome/browser/resources/welcome/ntp_background/BUILD.gn (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/BUILD.gn)10
-rw-r--r--chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_metrics_proxy.html3
-rw-r--r--chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_metrics_proxy.js23
-rw-r--r--chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_proxy.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_proxy.html)0
-rw-r--r--chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_proxy.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_proxy.js)10
-rw-r--r--chromium/chrome/browser/resources/welcome/ntp_background/nux_ntp_background.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.html)22
-rw-r--r--chromium/chrome/browser/resources/welcome/ntp_background/nux_ntp_background.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.js)20
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/google_dark.svg1
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/google_light.svg1
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/set_default_dark.svg1
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/set_default_light.svg1
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/wallpaper_dark.svg1
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/wallpaper_light.svg1
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/art.jpgbin8685 -> 0 bytes
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/cityscape.jpgbin9059 -> 0 bytes
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/earth.jpgbin3271 -> 0 bytes
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/geometric_shapes.jpgbin7695 -> 0 bytes
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/landscape.jpgbin10468 -> 0 bytes
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/set_default_dark.svg1
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/images/set_default_light.svg1
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/app_proxy.js31
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/navi_colors_css.html53
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome.html21
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome.js15
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_browser_proxy.html2
-rw-r--r--chromium/chrome/browser/resources/welcome/onboarding_welcome_resources.grd (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/onboarding_welcome_resources.grd)63
-rw-r--r--chromium/chrome/browser/resources/welcome/pin.webpbin4584 -> 0 bytes
-rw-r--r--chromium/chrome/browser/resources/welcome/set_as_default/BUILD.gn (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/BUILD.gn)0
-rw-r--r--chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default.html)27
-rw-r--r--chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default.js)8
-rw-r--r--chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default_proxy.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default_proxy.html)0
-rw-r--r--chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default_proxy.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default_proxy.js)6
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/BUILD.gn (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/BUILD.gn)7
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/action_link_style.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/action_link_style.js)0
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/action_link_style_css.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/action_link_style_css.html)2
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/animations_css.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/animations_css.html)0
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/bookmark_proxy.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/bookmark_proxy.html)0
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/bookmark_proxy.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/bookmark_proxy.js)6
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/chooser_shared_css.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/chooser_shared_css.html)2
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/i18n_setup.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/i18n_setup.html)0
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/module_metrics_proxy.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/module_metrics_proxy.html)0
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/module_metrics_proxy.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/module_metrics_proxy.js)121
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/navi_colors_css.html51
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/nux_types.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/nux_types.js)10
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/onboarding_background.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/onboarding_background.html)6
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/onboarding_background.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/onboarding_background.js)0
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/splash_pages_shared_css.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/splash_pages_shared_css.html)2
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/step_indicator.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/step_indicator.html)2
-rw-r--r--chromium/chrome/browser/resources/welcome/shared/step_indicator.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/step_indicator.js)4
-rw-r--r--chromium/chrome/browser/resources/welcome/signin_view.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view.html)11
-rw-r--r--chromium/chrome/browser/resources/welcome/signin_view.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view.js)4
-rw-r--r--chromium/chrome/browser/resources/welcome/signin_view_proxy.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view_proxy.html)0
-rw-r--r--chromium/chrome/browser/resources/welcome/signin_view_proxy.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view_proxy.js)4
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome.css37
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome.html260
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome.js39
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome_app.html (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_app.html)4
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome_app.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_app.js)4
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome_browser_proxy.html (renamed from chromium/chrome/browser/resources/welcome/dice_welcome/welcome_browser_proxy.html)0
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome_browser_proxy.js (renamed from chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_browser_proxy.js)1
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome_win10.css15
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome_win10.html356
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome_win10.js86
-rw-r--r--chromium/chrome/browser/safe_browsing/BUILD.gn21
-rw-r--r--chromium/chrome/browser/safe_browsing/chrome_cleaner/BUILD.gn9
-rw-r--r--chromium/chrome/browser/search/BUILD.gn6
-rw-r--r--chromium/chrome/browser/sharing/proto/BUILD.gn1
-rw-r--r--chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc81
-rw-r--r--chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h20
-rw-r--r--chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_mac.cc272
-rw-r--r--chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_unittest.cc4
-rw-r--r--chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_win_browsertest.cc97
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc9
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.h2
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc47
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h7
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_service.cc81
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_service.h15
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc15
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc2
-rw-r--r--chromium/chrome/browser/spellchecker/spelling_request.cc144
-rw-r--r--chromium/chrome/browser/spellchecker/spelling_request.h83
-rw-r--r--chromium/chrome/browser/supervised_user/kids_chrome_management/BUILD.gn12
-rw-r--r--chromium/chrome/browser/ui/BUILD.gn288
-rw-r--r--chromium/chrome/browser/ui/app_list/search/search_result_ranker/BUILD.gn6
-rw-r--r--chromium/chrome/browser/ui/views/BUILD.gn1
-rw-r--r--chromium/chrome/browser/ui/webui/OWNERS1
-rw-r--r--chromium/chrome/browser/ui/webui/about_ui.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/about_ui.h8
-rw-r--r--chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc17
-rw-r--r--chromium/chrome/browser/ui/webui/app_launcher_page_ui.h14
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/app_management.mojom6
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc32
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h1
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.cc10
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.h2
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc114
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/app_management_ui.h24
-rw-r--r--chromium/chrome/browser/ui/webui/autofill_internals_ui.cc119
-rw-r--r--chromium/chrome/browser/ui/webui/autofill_internals_ui.h11
-rw-r--r--chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn3
-rw-r--r--chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc12
-rw-r--r--chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc146
-rw-r--r--chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.h1
-rw-r--r--chromium/chrome/browser/ui/webui/browsing_history_handler.cc40
-rw-r--r--chromium/chrome/browser/ui/webui/certificates_handler.cc49
-rw-r--r--chromium/chrome/browser/ui/webui/certificates_handler.h15
-rw-r--r--chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc93
-rw-r--r--chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h8
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn3
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision.mojom12
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc47
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h37
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc167
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h43
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc90
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.h40
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.cc15
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.cc60
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.h2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc85
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.h27
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc12
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc141
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/image_source.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/image_source.h4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/OWNERS2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc58
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h39
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.cc76
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.h36
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc357
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h113
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.cc58
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.h37
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/insession_password_change_handler_chromeos.cc104
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/insession_password_change_handler_chromeos.h42
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/insession_password_change_ui.cc135
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/insession_password_change_ui.h44
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc16
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.h6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/arc_terms_of_service_screen_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc94
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc96
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc11
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.cc23
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc160
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h23
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc26
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc10
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc45
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h3
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc63
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/supervision_onboarding_screen_handler.cc80
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/supervision_onboarding_screen_handler.h82
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn3
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.cc26
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/network_ui.cc61
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/network_ui.h8
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc37
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc19
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h3
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_shares_localized_strings_provider.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_browsertest.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc17
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h9
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/terminal/OWNERS4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc61
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h32
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_ui.cc16
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_ui.h19
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/user_image_source.h4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/video_source.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/video_source.h4
-rw-r--r--chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc104
-rw-r--r--chromium/chrome/browser/ui/webui/cookies_tree_model_util.cc43
-rw-r--r--chromium/chrome/browser/ui/webui/cookies_tree_model_util.h8
-rw-r--r--chromium/chrome/browser/ui/webui/dark_mode_handler.cc76
-rw-r--r--chromium/chrome/browser/ui/webui/dark_mode_handler.h81
-rw-r--r--chromium/chrome/browser/ui/webui/dark_mode_handler_unittest.cc212
-rw-r--r--chromium/chrome/browser/ui/webui/device_log_ui.cc10
-rw-r--r--chromium/chrome/browser/ui/webui/devtools_ui.cc20
-rw-r--r--chromium/chrome/browser/ui/webui/discards/DEPS5
-rw-r--r--chromium/chrome/browser/ui/webui/discards/discards.mojom3
-rw-r--r--chromium/chrome/browser/ui/webui/discards/discards_ui.cc9
-rw-r--r--chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.h2
-rw-r--r--chromium/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.h3
-rw-r--r--chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.cc49
-rw-r--r--chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_page_handler.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h6
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc154
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h4
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/extensions_internals_unittest.cc227
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc61
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/extensions_ui.h3
-rw-r--r--chromium/chrome/browser/ui/webui/favicon_source.cc188
-rw-r--r--chromium/chrome/browser/ui/webui/favicon_source.h80
-rw-r--r--chromium/chrome/browser/ui/webui/favicon_source_unittest.cc214
-rw-r--r--chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/fileicon_source.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/fileicon_source.h6
-rw-r--r--chromium/chrome/browser/ui/webui/flags_ui.cc222
-rw-r--r--chromium/chrome/browser/ui/webui/flags_ui.h2
-rw-r--r--chromium/chrome/browser/ui/webui/flags_ui_handler.cc169
-rw-r--r--chromium/chrome/browser/ui/webui/flags_ui_handler.h55
-rw-r--r--chromium/chrome/browser/ui/webui/gcm_internals_ui.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/hats/hats_handler.cc24
-rw-r--r--chromium/chrome/browser/ui/webui/hats/hats_handler.h39
-rw-r--r--chromium/chrome/browser/ui/webui/hats/hats_ui.cc38
-rw-r--r--chromium/chrome/browser/ui/webui/hats/hats_ui.h25
-rw-r--r--chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc20
-rw-r--r--chromium/chrome/browser/ui/webui/history_login_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/history_ui.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/identity_internals_ui.cc68
-rw-r--r--chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc30
-rw-r--r--chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.cc31
-rw-r--r--chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc111
-rw-r--r--chromium/chrome/browser/ui/webui/invalidations_message_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/invalidations_message_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_browsertest.cc18
-rw-r--r--chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc15
-rw-r--r--chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h7
-rw-r--r--chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/management_ui.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/management_ui_handler.cc32
-rw-r--r--chromium/chrome/browser/ui/webui/management_ui_handler.h22
-rw-r--r--chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.cc321
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h77
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_browsertest.cc142
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_unittest.cc278
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_internals_ui.h2
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.cc109
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.h21
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_resources_provider.cc96
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_resources_provider.h19
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc411
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_ui.h237
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc852
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_web_ui_test.cc67
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_web_ui_test.h30
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc1165
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h181
-rw-r--r--chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc691
-rw-r--r--chromium/chrome/browser/ui/webui/memory_internals_ui.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/nacl_ui.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/net_export_ui.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/net_internals/net_internals_ui.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc158
-rw-r--r--chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.h2
-rw-r--r--chromium/chrome/browser/ui/webui/notifications_internals/OWNERS2
-rw-r--r--chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.cc36
-rw-r--r--chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.h25
-rw-r--r--chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc48
-rw-r--r--chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.h41
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc19
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc51
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h19
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc16
-rw-r--r--chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc1
-rw-r--r--chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc23
-rw-r--r--chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom1
-rw-r--r--chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/page_not_available_for_guest/page_not_available_for_guest_ui.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.cc169
-rw-r--r--chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h24
-rw-r--r--chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui_browsertest.cc91
-rw-r--r--chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/policy_ui.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc81
-rw-r--r--chromium/chrome/browser/ui/webui/policy_ui_handler.cc237
-rw-r--r--chromium/chrome/browser/ui/webui/policy_ui_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/prefs_internals_source.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/prefs_internals_source.h4
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc14
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc37
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h2
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.h2
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc23
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.cc115
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.h15
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.cc13
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.h2
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.h2
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/printer_handler.h5
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc19
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h7
-rw-r--r--chromium/chrome/browser/ui/webui/profile_helper_browsertest.cc31
-rw-r--r--chromium/chrome/browser/ui/webui/profile_info_watcher.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/profile_info_watcher.h4
-rw-r--r--chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h2
-rw-r--r--chromium/chrome/browser/ui/webui/reset_password/BUILD.gn3
-rw-r--r--chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc24
-rw-r--r--chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/about_handler.cc79
-rw-r--r--chromium/chrome/browser/ui/webui/settings/about_handler.h14
-rw-r--r--chromium/chrome/browser/ui/webui/settings/appearance_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/appearance_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/captions_handler.cc34
-rw-r--r--chromium/chrome/browser/ui/webui/settings/captions_handler.h34
-rw-r--r--chromium/chrome/browser/ui/webui/settings/change_password_handler.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc73
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h15
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc26
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc198
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h23
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc32
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.cc13
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler.h4
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_keyboard_handler_unittest.cc23
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.h4
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc9
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc50
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h12
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc163
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h18
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc74
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h20
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc100
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h43
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/settings/font_handler.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/settings/font_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/people_handler.cc47
-rw-r--r--chromium/chrome/browser/ui/webui/settings/people_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc14
-rw-r--r--chromium/chrome/browser/ui/webui/settings/printing_handler.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/settings/profile_info_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/settings/profile_info_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc66
-rw-r--r--chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.h14
-rw-r--r--chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/settings/reset_settings_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/search_engines_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc11
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc67
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h10
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc480
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc389
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h128
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_ui.cc161
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_ui.h31
-rw-r--r--chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc35
-rw-r--r--chromium/chrome/browser/ui/webui/settings/site_settings_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/settings_utils_win.cc17
-rw-r--r--chromium/chrome/browser/ui/webui/signin/OWNERS1
-rw-r--r--chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc30
-rw-r--r--chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h10
-rw-r--r--chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_unittest.cc23
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h3
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc23
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.h2
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_ui.h2
-rw-r--r--chromium/chrome/browser/ui/webui/signin/login_ui_service.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.h2
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc20
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc18
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_utils_desktop.cc16
-rw-r--r--chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc59
-rw-r--r--chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.h16
-rw-r--r--chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc139
-rw-r--r--chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc96
-rw-r--r--chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.h2
-rw-r--r--chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc1
-rw-r--r--chromium/chrome/browser/ui/webui/signin_internals_ui.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/site_settings_helper.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn3
-rw-r--r--chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h3
-rw-r--r--chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/sync_internals_browsertest.js5
-rw-r--r--chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/sync_internals_message_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/system_info_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/test_data_source.cc103
-rw-r--r--chromium/chrome/browser/ui/webui/test_data_source.h48
-rw-r--r--chromium/chrome/browser/ui/webui/theme_source.cc13
-rw-r--r--chromium/chrome/browser/ui/webui/theme_source.h10
-rw-r--r--chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn3
-rw-r--r--chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc12
-rw-r--r--chromium/chrome/browser/ui/webui/version_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/version_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/version_handler_chromeos.cc11
-rw-r--r--chromium/chrome/browser/ui/webui/version_handler_win.cc73
-rw-r--r--chromium/chrome/browser/ui/webui/version_ui.cc162
-rw-r--r--chromium/chrome/browser/ui/webui/version_ui.h5
-rw-r--r--chromium/chrome/browser/ui/webui/version_util_win.cc88
-rw-r--r--chromium/chrome/browser/ui/webui/version_util_win.h27
-rw-r--r--chromium/chrome/browser/ui/webui/webapks_handler.cc82
-rw-r--r--chromium/chrome/browser/ui/webui/webapks_handler.h17
-rw-r--r--chromium/chrome/browser/ui/webui/webui_load_timer.cc65
-rw-r--r--chromium/chrome/browser/ui/webui/webui_load_timer.h43
-rw-r--r--chromium/chrome/browser/ui/webui/webui_load_timer_browsertest.cc38
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.cc22
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/nux_helper.cc77
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/nux_helper.h16
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc185
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/welcome_ui.h2
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/welcome_win10_handler.cc198
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/welcome_win10_handler.h67
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/welcome_win10_ui.cc108
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/welcome_win10_ui.h21
-rw-r--r--chromium/chrome/browser/vr/BUILD.gn24
-rw-r--r--chromium/chrome/browser/web_applications/BUILD.gn26
-rw-r--r--chromium/chrome/browser/web_applications/bookmark_apps/BUILD.gn1
-rw-r--r--chromium/chrome/browser/web_applications/components/BUILD.gn31
-rw-r--r--chromium/chrome/browser/web_applications/extensions/BUILD.gn3
1450 files changed, 33526 insertions, 34697 deletions
diff --git a/chromium/chrome/browser/BUILD.gn b/chromium/chrome/browser/BUILD.gn
index 4f9844f6f85..c00a09a5ec2 100644
--- a/chromium/chrome/browser/BUILD.gn
+++ b/chromium/chrome/browser/BUILD.gn
@@ -38,10 +38,6 @@ if (is_android) {
import("//tools/grit/grit_rule.gni")
}
-if (is_chromeos) {
- import("//chrome/browser/chromeos/kiosk_next_home/kiosk_next.gni")
-}
-
additional_modules_list_file =
"$root_gen_dir/chrome/browser/internal/additional_modules_list.txt"
@@ -115,20 +111,18 @@ jumbo_split_static_library("browser") {
"autocomplete/chrome_autocomplete_provider_client.h",
"autocomplete/chrome_autocomplete_scheme_classifier.cc",
"autocomplete/chrome_autocomplete_scheme_classifier.h",
- "autocomplete/contextual_suggestions_service_factory.cc",
- "autocomplete/contextual_suggestions_service_factory.h",
"autocomplete/document_suggestions_service_factory.cc",
"autocomplete/document_suggestions_service_factory.h",
"autocomplete/in_memory_url_index_factory.cc",
"autocomplete/in_memory_url_index_factory.h",
+ "autocomplete/remote_suggestions_service_factory.cc",
+ "autocomplete/remote_suggestions_service_factory.h",
"autocomplete/shortcuts_backend_factory.cc",
"autocomplete/shortcuts_backend_factory.h",
"autofill/address_normalizer_factory.cc",
"autofill/address_normalizer_factory.h",
"autofill/autocomplete_history_manager_factory.cc",
"autofill/autocomplete_history_manager_factory.h",
- "autofill/autofill_internals_logging_impl.cc",
- "autofill/autofill_internals_logging_impl.h",
"autofill/autofill_profile_validator_factory.cc",
"autofill/autofill_profile_validator_factory.h",
"autofill/personal_data_manager_factory.cc",
@@ -139,6 +133,8 @@ jumbo_split_static_library("browser") {
"autofill/strike_database_factory.h",
"autofill/validation_rules_storage_factory.cc",
"autofill/validation_rules_storage_factory.h",
+ "availability/availability_prober.cc",
+ "availability/availability_prober.h",
"background_fetch/background_fetch_delegate_factory.cc",
"background_fetch/background_fetch_delegate_factory.h",
"background_fetch/background_fetch_delegate_impl.cc",
@@ -280,8 +276,6 @@ jumbo_split_static_library("browser") {
"chrome_browser_main_mac.mm",
"chrome_browser_main_win.cc",
"chrome_browser_main_win.h",
- "chrome_child_process_watcher.cc",
- "chrome_child_process_watcher.h",
"chrome_content_browser_client.cc",
"chrome_content_browser_client.h",
"chrome_content_browser_client_parts.h",
@@ -313,8 +307,6 @@ jumbo_split_static_library("browser") {
"component_updater/chrome_component_updater_configurator.h",
"component_updater/component_updater_prefs.cc",
"component_updater/component_updater_prefs.h",
- "component_updater/component_updater_resource_throttle.cc",
- "component_updater/component_updater_resource_throttle.h",
"component_updater/component_updater_utils.cc",
"component_updater/component_updater_utils.h",
"component_updater/crl_set_component_installer.cc",
@@ -323,6 +315,8 @@ jumbo_split_static_library("browser") {
"component_updater/file_type_policies_component_installer.h",
"component_updater/mei_preload_component_installer.cc",
"component_updater/mei_preload_component_installer.h",
+ "component_updater/on_device_head_suggest_component_installer.cc",
+ "component_updater/on_device_head_suggest_component_installer.h",
"component_updater/optimization_hints_component_installer.cc",
"component_updater/optimization_hints_component_installer.h",
"component_updater/origin_trials_component_installer.cc",
@@ -333,16 +327,20 @@ jumbo_split_static_library("browser") {
"component_updater/recovery_component_installer.h",
"component_updater/recovery_improved_component_installer.cc",
"component_updater/recovery_improved_component_installer.h",
+ "component_updater/safety_tips_component_installer.cc",
+ "component_updater/safety_tips_component_installer.h",
"component_updater/sth_set_component_remover.cc",
"component_updater/sth_set_component_remover.h",
"component_updater/subresource_filter_component_installer.cc",
"component_updater/subresource_filter_component_installer.h",
- "component_updater/supervised_user_whitelist_installer.cc",
- "component_updater/supervised_user_whitelist_installer.h",
"component_updater/sw_reporter_installer_win.cc",
"component_updater/sw_reporter_installer_win.h",
"consent_auditor/consent_auditor_factory.cc",
"consent_auditor/consent_auditor_factory.h",
+ "content_index/content_index_provider_factory.cc",
+ "content_index/content_index_provider_factory.h",
+ "content_index/content_index_provider_impl.cc",
+ "content_index/content_index_provider_impl.h",
"content_settings/chrome_content_settings_utils.cc",
"content_settings/chrome_content_settings_utils.h",
"content_settings/cookie_settings_factory.cc",
@@ -375,18 +373,8 @@ jumbo_split_static_library("browser") {
"data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h",
"data_reduction_proxy/data_reduction_proxy_tab_helper.cc",
"data_reduction_proxy/data_reduction_proxy_tab_helper.h",
- "data_use_measurement/chrome_data_use_ascriber.cc",
- "data_use_measurement/chrome_data_use_ascriber.h",
- "data_use_measurement/chrome_data_use_ascriber_service.cc",
- "data_use_measurement/chrome_data_use_ascriber_service.h",
- "data_use_measurement/chrome_data_use_ascriber_service_factory.cc",
- "data_use_measurement/chrome_data_use_ascriber_service_factory.h",
"data_use_measurement/chrome_data_use_measurement.cc",
"data_use_measurement/chrome_data_use_measurement.h",
- "data_use_measurement/chrome_data_use_recorder.cc",
- "data_use_measurement/chrome_data_use_recorder.h",
- "data_use_measurement/data_use_web_contents_observer.cc",
- "data_use_measurement/data_use_web_contents_observer.h",
"defaults.cc",
"defaults.h",
"dom_distiller/dom_distiller_service_factory.cc",
@@ -424,6 +412,8 @@ jumbo_split_static_library("browser") {
"download/download_manager_utils.h",
"download/download_offline_content_provider.cc",
"download/download_offline_content_provider.h",
+ "download/download_offline_content_provider_factory.cc",
+ "download/download_offline_content_provider_factory.h",
"download/download_permission_request.cc",
"download/download_permission_request.h",
"download/download_prefs.cc",
@@ -433,8 +423,6 @@ jumbo_split_static_library("browser") {
"download/download_query.h",
"download/download_request_limiter.cc",
"download/download_request_limiter.h",
- "download/download_resource_throttle.cc",
- "download/download_resource_throttle.h",
"download/download_service_factory.cc",
"download/download_service_factory.h",
"download/download_started_animation.h",
@@ -504,6 +492,8 @@ jumbo_split_static_library("browser") {
"favicon/favicon_service_factory.h",
"favicon/favicon_utils.cc",
"favicon/favicon_utils.h",
+ "favicon/history_ui_favicon_request_handler_factory.cc",
+ "favicon/history_ui_favicon_request_handler_factory.h",
"favicon/large_icon_service_factory.cc",
"favicon/large_icon_service_factory.h",
"feature_engagement/tracker_factory.cc",
@@ -619,8 +609,6 @@ jumbo_split_static_library("browser") {
"invalidation/deprecated_profile_invalidation_provider_factory.h",
"invalidation/profile_invalidation_provider_factory.cc",
"invalidation/profile_invalidation_provider_factory.h",
- "io_thread.cc",
- "io_thread.h",
"language/language_model_manager_factory.cc",
"language/language_model_manager_factory.h",
"language/translate_frame_binder.cc",
@@ -632,10 +620,6 @@ jumbo_split_static_library("browser") {
"lifetime/application_lifetime_mac.mm",
"lifetime/browser_shutdown.cc",
"lifetime/browser_shutdown.h",
- "loader/chrome_navigation_data.cc",
- "loader/chrome_navigation_data.h",
- "loader/chrome_resource_dispatcher_host_delegate.cc",
- "loader/chrome_resource_dispatcher_host_delegate.h",
"lookalikes/lookalike_url_allowlist.cc",
"lookalikes/lookalike_url_allowlist.h",
"lookalikes/lookalike_url_controller_client.cc",
@@ -646,6 +630,9 @@ jumbo_split_static_library("browser") {
"lookalikes/lookalike_url_navigation_throttle.h",
"lookalikes/lookalike_url_service.cc",
"lookalikes/lookalike_url_service.h",
+ "lookalikes/safety_tips/safety_tip_ui.h",
+ "lookalikes/safety_tips/safety_tips_config.cc",
+ "lookalikes/safety_tips/safety_tips_config.h",
"mac/bluetooth_utility.h",
"mac/bluetooth_utility.mm",
"mac/dock.h",
@@ -826,20 +813,22 @@ jumbo_split_static_library("browser") {
"metrics/ukm_background_recorder_service.h",
"metrics/variations/chrome_variations_service_client.cc",
"metrics/variations/chrome_variations_service_client.h",
+ "native_file_system/chrome_native_file_system_permission_context.cc",
+ "native_file_system/chrome_native_file_system_permission_context.h",
+ "native_file_system/native_file_system_permission_context_factory.cc",
+ "native_file_system/native_file_system_permission_context_factory.h",
+ "native_file_system/native_file_system_permission_request_manager.cc",
+ "native_file_system/native_file_system_permission_request_manager.h",
"native_window_notification_source.h",
"navigation_predictor/navigation_predictor.cc",
"navigation_predictor/navigation_predictor.h",
"net/chrome_cookie_notification_details.h",
- "net/chrome_extensions_network_delegate.cc",
- "net/chrome_extensions_network_delegate.h",
"net/chrome_mojo_proxy_resolver_factory.cc",
"net/chrome_mojo_proxy_resolver_factory.h",
"net/chrome_network_delegate.cc",
"net/chrome_network_delegate.h",
"net/chrome_report_sender.cc",
"net/chrome_report_sender.h",
- "net/chrome_url_request_context_getter.cc",
- "net/chrome_url_request_context_getter.h",
"net/dns_probe_runner.cc",
"net/dns_probe_runner.h",
"net/dns_probe_service.h",
@@ -867,8 +856,6 @@ jumbo_split_static_library("browser") {
"net/proxy_service_factory.h",
"net/referrer.cc",
"net/referrer.h",
- "net/reporting_permissions_checker.cc",
- "net/reporting_permissions_checker.h",
"net/service_providers_win.cc",
"net/service_providers_win.h",
"net/system_network_context_manager.cc",
@@ -931,6 +918,7 @@ jumbo_split_static_library("browser") {
"ntp_tiles/chrome_popular_sites_factory.h",
"offline_items_collection/offline_content_aggregator_factory.cc",
"offline_items_collection/offline_content_aggregator_factory.h",
+ "omnibox/common/omnibox_features.h",
"page_load_metrics/metrics_navigation_throttle.cc",
"page_load_metrics/metrics_navigation_throttle.h",
"page_load_metrics/metrics_web_contents_observer.cc",
@@ -943,8 +931,6 @@ jumbo_split_static_library("browser") {
"page_load_metrics/observers/ad_metrics/frame_data.h",
"page_load_metrics/observers/amp_page_load_metrics_observer.cc",
"page_load_metrics/observers/amp_page_load_metrics_observer.h",
- "page_load_metrics/observers/amp_ukm_observer.cc",
- "page_load_metrics/observers/amp_ukm_observer.h",
"page_load_metrics/observers/core_page_load_metrics_observer.cc",
"page_load_metrics/observers/core_page_load_metrics_observer.h",
"page_load_metrics/observers/data_reduction_proxy_metrics_observer.cc",
@@ -977,8 +963,6 @@ jumbo_split_static_library("browser") {
"page_load_metrics/observers/loading_predictor_page_load_metrics_observer.h",
"page_load_metrics/observers/local_network_requests_page_load_metrics_observer.cc",
"page_load_metrics/observers/local_network_requests_page_load_metrics_observer.h",
- "page_load_metrics/observers/lofi_page_load_metrics_observer.cc",
- "page_load_metrics/observers/lofi_page_load_metrics_observer.h",
"page_load_metrics/observers/media_page_load_metrics_observer.cc",
"page_load_metrics/observers/media_page_load_metrics_observer.h",
"page_load_metrics/observers/multi_tab_loading_page_load_metrics_observer.cc",
@@ -1009,6 +993,8 @@ jumbo_split_static_library("browser") {
"page_load_metrics/observers/signed_exchange_page_load_metrics_observer.h",
"page_load_metrics/observers/tab_restore_page_load_metrics_observer.cc",
"page_load_metrics/observers/tab_restore_page_load_metrics_observer.h",
+ "page_load_metrics/observers/third_party_metrics_observer.cc",
+ "page_load_metrics/observers/third_party_metrics_observer.h",
"page_load_metrics/observers/ukm_page_load_metrics_observer.cc",
"page_load_metrics/observers/ukm_page_load_metrics_observer.h",
"page_load_metrics/observers/use_counter/ukm_features.cc",
@@ -1040,8 +1026,6 @@ jumbo_split_static_library("browser") {
"password_manager/password_manager_util_win.h",
"password_manager/password_store_factory.cc",
"password_manager/password_store_factory.h",
- "password_manager/password_store_mac.cc",
- "password_manager/password_store_mac.h",
"password_manager/reauth_purpose.h",
"payments/payment_handler_permission_context.cc",
"payments/payment_handler_permission_context.h",
@@ -1056,12 +1040,17 @@ jumbo_split_static_library("browser") {
"performance_manager/decorators/frozen_frame_aggregator.h",
"performance_manager/decorators/page_almost_idle_decorator.cc",
"performance_manager/decorators/page_almost_idle_decorator.h",
+ "performance_manager/frame_priority/frame_priority.cc",
"performance_manager/graph/frame_node.cc",
"performance_manager/graph/frame_node_impl.cc",
"performance_manager/graph/frame_node_impl.h",
"performance_manager/graph/graph.cc",
"performance_manager/graph/graph_impl.cc",
"performance_manager/graph/graph_impl.h",
+ "performance_manager/graph/graph_impl_operations.cc",
+ "performance_manager/graph/graph_impl_operations.h",
+ "performance_manager/graph/graph_operations.cc",
+ "performance_manager/graph/node.cc",
"performance_manager/graph/node_attached_data.cc",
"performance_manager/graph/node_attached_data.h",
"performance_manager/graph/node_attached_data_impl.h",
@@ -1078,6 +1067,12 @@ jumbo_split_static_library("browser") {
"performance_manager/graph/system_node.cc",
"performance_manager/graph/system_node_impl.cc",
"performance_manager/graph/system_node_impl.h",
+ "performance_manager/mechanisms/working_set_trimmer.cc",
+ "performance_manager/mechanisms/working_set_trimmer.h",
+ "performance_manager/mechanisms/working_set_trimmer_chromeos.cc",
+ "performance_manager/mechanisms/working_set_trimmer_chromeos.h",
+ "performance_manager/mechanisms/working_set_trimmer_win.cc",
+ "performance_manager/mechanisms/working_set_trimmer_win.h",
"performance_manager/observers/background_metrics_reporter.h",
"performance_manager/observers/graph_observer.cc",
"performance_manager/observers/graph_observer.h",
@@ -1085,8 +1080,8 @@ jumbo_split_static_library("browser") {
"performance_manager/observers/isolation_context_metrics.h",
"performance_manager/observers/metrics_collector.cc",
"performance_manager/observers/metrics_collector.h",
- "performance_manager/observers/working_set_trimmer_win.cc",
- "performance_manager/observers/working_set_trimmer_win.h",
+ "performance_manager/observers/working_set_trimmer_observer_win.cc",
+ "performance_manager/observers/working_set_trimmer_observer_win.h",
"performance_manager/performance_manager.cc",
"performance_manager/performance_manager.h",
"performance_manager/performance_manager_clock.cc",
@@ -1098,8 +1093,20 @@ jumbo_split_static_library("browser") {
"performance_manager/persistence/site_data/feature_usage.h",
"performance_manager/persistence/site_data/leveldb_site_data_store.cc",
"performance_manager/persistence/site_data/leveldb_site_data_store.h",
+ "performance_manager/persistence/site_data/non_recording_site_data_cache.cc",
+ "performance_manager/persistence/site_data/non_recording_site_data_cache.h",
"performance_manager/persistence/site_data/noop_site_data_writer.cc",
"performance_manager/persistence/site_data/noop_site_data_writer.h",
+ "performance_manager/persistence/site_data/site_data_cache.h",
+ "performance_manager/persistence/site_data/site_data_cache_facade.cc",
+ "performance_manager/persistence/site_data/site_data_cache_facade.h",
+ "performance_manager/persistence/site_data/site_data_cache_facade_factory.cc",
+ "performance_manager/persistence/site_data/site_data_cache_facade_factory.h",
+ "performance_manager/persistence/site_data/site_data_cache_factory.cc",
+ "performance_manager/persistence/site_data/site_data_cache_factory.h",
+ "performance_manager/persistence/site_data/site_data_cache_impl.cc",
+ "performance_manager/persistence/site_data/site_data_cache_impl.h",
+ "performance_manager/persistence/site_data/site_data_cache_inspector.h",
"performance_manager/persistence/site_data/site_data_impl.cc",
"performance_manager/persistence/site_data/site_data_impl.h",
"performance_manager/persistence/site_data/site_data_reader.cc",
@@ -1108,8 +1115,11 @@ jumbo_split_static_library("browser") {
"performance_manager/persistence/site_data/site_data_writer.cc",
"performance_manager/persistence/site_data/site_data_writer.h",
"performance_manager/persistence/site_data/tab_visibility.h",
+ "performance_manager/public/frame_priority/frame_priority.h",
"performance_manager/public/graph/frame_node.h",
"performance_manager/public/graph/graph.h",
+ "performance_manager/public/graph/graph_operations.h",
+ "performance_manager/public/graph/node.h",
"performance_manager/public/graph/node_attached_data.h",
"performance_manager/public/graph/page_node.h",
"performance_manager/public/graph/process_node.h",
@@ -1181,10 +1191,8 @@ jumbo_split_static_library("browser") {
"policy/chrome_browser_policy_connector.h",
"policy/cloud/cloud_policy_invalidator.cc",
"policy/cloud/cloud_policy_invalidator.h",
- "policy/cloud/policy_header_navigation_throttle.cc",
- "policy/cloud/policy_header_navigation_throttle.h",
- "policy/cloud/policy_header_service_factory.cc",
- "policy/cloud/policy_header_service_factory.h",
+ "policy/cloud/policy_invalidation_util.cc",
+ "policy/cloud/policy_invalidation_util.h",
"policy/cloud/remote_commands_invalidator.cc",
"policy/cloud/remote_commands_invalidator.h",
"policy/cloud/remote_commands_invalidator_impl.cc",
@@ -1252,6 +1260,8 @@ jumbo_split_static_library("browser") {
"predictors/predictor_database_factory.h",
"predictors/predictor_table_base.cc",
"predictors/predictor_table_base.h",
+ "predictors/predictors_features.cc",
+ "predictors/predictors_features.h",
"predictors/proxy_lookup_client_impl.cc",
"predictors/proxy_lookup_client_impl.h",
"predictors/resolve_host_client_impl.cc",
@@ -1324,6 +1334,8 @@ jumbo_split_static_library("browser") {
"previews/previews_lite_page_navigation_throttle.cc",
"previews/previews_lite_page_navigation_throttle.h",
"previews/previews_lite_page_navigation_throttle_manager.h",
+ "previews/previews_lite_page_predictor.cc",
+ "previews/previews_lite_page_predictor.h",
"previews/previews_lite_page_redirect_url_loader.cc",
"previews/previews_lite_page_redirect_url_loader.h",
"previews/previews_lite_page_serving_url_loader.cc",
@@ -1336,8 +1348,8 @@ jumbo_split_static_library("browser") {
"previews/previews_service.h",
"previews/previews_service_factory.cc",
"previews/previews_service_factory.h",
- "previews/previews_top_host_provider_impl.cc",
- "previews/previews_top_host_provider_impl.h",
+ "previews/previews_top_host_provider.cc",
+ "previews/previews_top_host_provider.h",
"previews/previews_ui_tab_helper.cc",
"previews/previews_ui_tab_helper.h",
"previews/resource_loading_hints/resource_loading_hints_web_contents_observer.cc",
@@ -1514,13 +1526,38 @@ jumbo_split_static_library("browser") {
"sessions/session_tab_helper.h",
"sessions/tab_restore_service_factory.cc",
"sessions/tab_restore_service_factory.h",
+ "sharing/ack_message_handler.cc",
+ "sharing/ack_message_handler.h",
+ "sharing/click_to_call/click_to_call_message_handler_android.cc",
+ "sharing/click_to_call/click_to_call_message_handler_android.h",
+ "sharing/click_to_call/feature.cc",
+ "sharing/click_to_call/feature.h",
+ "sharing/features.cc",
+ "sharing/features.h",
+ "sharing/ping_message_handler.cc",
+ "sharing/ping_message_handler.h",
+ "sharing/sharing_constants.cc",
+ "sharing/sharing_constants.h",
"sharing/sharing_device_info.cc",
"sharing/sharing_device_info.h",
+ "sharing/sharing_device_registration.cc",
+ "sharing/sharing_device_registration.h",
+ "sharing/sharing_device_registration_result.h",
+ "sharing/sharing_fcm_handler.cc",
+ "sharing/sharing_fcm_handler.h",
+ "sharing/sharing_fcm_sender.cc",
+ "sharing/sharing_fcm_sender.h",
"sharing/sharing_message_handler.h",
+ "sharing/sharing_metrics.cc",
+ "sharing/sharing_metrics.h",
"sharing/sharing_service.cc",
"sharing/sharing_service.h",
"sharing/sharing_service_factory.cc",
"sharing/sharing_service_factory.h",
+ "sharing/sharing_sync_preference.cc",
+ "sharing/sharing_sync_preference.h",
+ "sharing/vapid_key_manager.cc",
+ "sharing/vapid_key_manager.h",
"shell_integration.cc",
"shell_integration.h",
"shell_integration_android.cc",
@@ -1534,6 +1571,8 @@ jumbo_split_static_library("browser") {
"signin/account_consistency_mode_manager.h",
"signin/account_consistency_mode_manager_factory.cc",
"signin/account_consistency_mode_manager_factory.h",
+ "signin/account_id_from_account_info.cc",
+ "signin/account_id_from_account_info.h",
"signin/account_investigator_factory.cc",
"signin/account_investigator_factory.h",
"signin/account_reconcilor_factory.cc",
@@ -1551,16 +1590,16 @@ jumbo_split_static_library("browser") {
"signin/chrome_signin_url_loader_throttle.cc",
"signin/chrome_signin_url_loader_throttle.h",
"signin/header_modification_delegate.h",
- "signin/header_modification_delegate_impl.cc",
- "signin/header_modification_delegate_impl.h",
+ "signin/header_modification_delegate_on_io_thread_impl.cc",
+ "signin/header_modification_delegate_on_io_thread_impl.h",
+ "signin/header_modification_delegate_on_ui_thread_impl.cc",
+ "signin/header_modification_delegate_on_ui_thread_impl.h",
"signin/identity_manager_factory.cc",
"signin/identity_manager_factory.h",
"signin/investigator_dependency_provider.cc",
"signin/investigator_dependency_provider.h",
"signin/local_auth.cc",
"signin/local_auth.h",
- "signin/profile_oauth2_token_service_builder.cc",
- "signin/profile_oauth2_token_service_builder.h",
"signin/signin_error_controller_factory.cc",
"signin/signin_error_controller_factory.h",
"signin/signin_profile_attributes_updater.cc",
@@ -1579,10 +1618,6 @@ jumbo_split_static_library("browser") {
"site_isolation/site_details.h",
"site_isolation/site_isolation_policy.cc",
"site_isolation/site_isolation_policy.h",
- "sms/sms_keyed_service.cc",
- "sms/sms_keyed_service.h",
- "sms/sms_service_factory.cc",
- "sms/sms_service_factory.h",
"speech/chrome_speech_recognition_manager_delegate.cc",
"speech/chrome_speech_recognition_manager_delegate.h",
"speech/speech_recognizer.cc",
@@ -1756,6 +1791,8 @@ jumbo_split_static_library("browser") {
"vr/ui_suppressed_element.h",
"vr/vr_tab_helper.cc",
"vr/vr_tab_helper.h",
+ "wake_lock/wake_lock_permission_context.cc",
+ "wake_lock/wake_lock_permission_context.h",
"web_data_service_factory.cc",
"web_data_service_factory.h",
"webauthn/authenticator_list_observer.h",
@@ -1832,6 +1869,7 @@ jumbo_split_static_library("browser") {
public_deps = [
"//base",
"//chrome/common",
+ "//components/account_id",
"//components/autofill/core/browser",
"//components/nacl/common:buildflags",
"//components/payments/core",
@@ -1843,11 +1881,13 @@ jumbo_split_static_library("browser") {
]
deps = [
":active_use_util",
+ ":availability_protos",
":ntp_background_proto",
":resource_prefetch_predictor_proto",
"//base:i18n",
"//base/allocator:buildflags",
"//base/util/values:values_util",
+ "//build:branding_buildflags",
"//cc",
"//chrome:extra_resources",
"//chrome:resources",
@@ -1856,6 +1896,7 @@ jumbo_split_static_library("browser") {
"//chrome/app/resources:platform_locale_settings",
"//chrome/app/theme:theme_resources",
"//chrome/browser/devtools",
+ "//chrome/browser/lookalikes/safety_tips:proto",
"//chrome/browser/media:media_engagement_preload_proto",
"//chrome/browser/media:mojo_bindings",
"//chrome/browser/media/router",
@@ -1877,9 +1918,6 @@ jumbo_split_static_library("browser") {
"//chrome/common:channel_info",
"//chrome/common/net",
"//chrome/installer/util:with_no_strings",
- "//chrome/services/noop/public/cpp",
- "//chrome/services/noop/public/mojom",
- "//components/about_handler",
"//components/app_modal",
"//components/assist_ranker",
"//components/autofill/content/browser",
@@ -1908,7 +1946,6 @@ jumbo_split_static_library("browser") {
"//components/data_reduction_proxy/content/browser",
"//components/data_reduction_proxy/content/common",
"//components/data_reduction_proxy/core/browser",
- "//components/data_use_measurement/content",
"//components/data_use_measurement/core:ascriber",
"//components/device_event_log",
"//components/dom_distiller/content/browser",
@@ -1929,7 +1966,6 @@ jumbo_split_static_library("browser") {
"//components/history/content/browser",
"//components/history/core/browser",
"//components/history/core/common",
- "//components/image_fetcher/core",
"//components/infobars/core",
"//components/invalidation/impl",
"//components/keyed_service/content",
@@ -1940,6 +1976,7 @@ jumbo_split_static_library("browser") {
"//components/leveldb_proto/content:factory",
"//components/metrics:call_stack_profile_collector",
"//components/metrics:component_metrics",
+ "//components/metrics:demographic_metrics_provider",
"//components/metrics:gpu",
"//components/metrics:net",
"//components/metrics:ui",
@@ -1955,7 +1992,6 @@ jumbo_split_static_library("browser") {
"//components/network_hints/common",
"//components/network_session_configurator/browser",
"//components/network_time",
- "//components/ntp_snippets",
"//components/ntp_tiles",
"//components/offline_items_collection/core",
"//components/offline_pages/buildflags",
@@ -1992,13 +2028,15 @@ jumbo_split_static_library("browser") {
"//components/security_state/core",
"//components/send_tab_to_self",
"//components/services/heap_profiling",
- "//components/services/patch/public/interfaces",
+ "//components/services/patch/public/mojom",
"//components/services/quarantine",
"//components/services/quarantine/public/mojom",
- "//components/services/unzip/public/interfaces",
+ "//components/services/unzip/public/mojom",
"//components/sessions",
"//components/signin/core/browser",
- "//components/signin/core/browser:signin_buildflags",
+ "//components/signin/public/base:signin_buildflags",
+ "//components/signin/public/identity_manager",
+ "//components/signin/public/webdata",
"//components/spellcheck:buildflags",
"//components/ssl_errors",
"//components/startup_metric_utils/browser:host",
@@ -2084,7 +2122,7 @@ jumbo_split_static_library("browser") {
"//services/device/public/mojom",
"//services/device/public/mojom:usb",
"//services/identity:lib",
- "//services/identity/public/cpp",
+ "//services/identity/public/cpp:cpp_types",
"//services/image_annotation:service",
"//services/image_annotation/public/mojom",
"//services/metrics/public/cpp:ukm_builders",
@@ -2236,7 +2274,6 @@ jumbo_split_static_library("browser") {
"android/compositor/navigation_glow.cc",
"android/compositor/navigation_glow.h",
"android/compositor/resources/resource_factory.cc",
- "android/compositor/resources/resource_factory.h",
"android/compositor/resources/toolbar_resource.cc",
"android/compositor/resources/toolbar_resource.h",
"android/compositor/scene_layer/contextual_search_scene_layer.cc",
@@ -2324,12 +2361,12 @@ jumbo_split_static_library("browser") {
"android/download/download_media_parser.h",
"android/download/download_media_parser_bridge.cc",
"android/download/download_media_parser_bridge.h",
+ "android/download/download_startup_utils.cc",
+ "android/download/download_startup_utils.h",
"android/download/download_utils.cc",
"android/download/download_utils.h",
"android/download/duplicate_download_infobar_delegate.cc",
"android/download/duplicate_download_infobar_delegate.h",
- "android/download/intercept_download_resource_throttle.cc",
- "android/download/intercept_download_resource_throttle.h",
"android/download/intercept_oma_download_navigation_throttle.cc",
"android/download/intercept_oma_download_navigation_throttle.h",
"android/download/items/offline_content_aggregator_factory_android.cc",
@@ -2558,10 +2595,13 @@ jumbo_split_static_library("browser") {
"android/shortcut_helper.h",
"android/shortcut_info.cc",
"android/shortcut_info.h",
+ "android/signin/chrome_signin_manager_delegate.cc",
+ "android/signin/chrome_signin_manager_delegate.h",
"android/signin/signin_investigator_android.cc",
"android/signin/signin_investigator_android.h",
"android/signin/signin_manager_android.cc",
"android/signin/signin_manager_android.h",
+ "android/signin/signin_manager_delegate.h",
"android/signin/signin_promo_util_android.cc",
"android/signin/signin_promo_util_android.h",
"android/signin/signin_utils.cc",
@@ -2589,17 +2629,20 @@ jumbo_split_static_library("browser") {
"android/thumbnail/thumbnail_cache.h",
"android/trusted_cdn.cc",
"android/trusted_cdn.h",
- "android/url_utilities.cc",
+ "android/usage_stats/notification_suspender.cc",
"android/usage_stats/usage_stats_bridge.cc",
"android/usage_stats/usage_stats_bridge.h",
"android/usage_stats/usage_stats_database.cc",
"android/usage_stats/usage_stats_database.h",
"android/usb/web_usb_chooser_android.cc",
"android/usb/web_usb_chooser_android.h",
+ "android/util/url_utilities.cc",
"android/warmup_manager.cc",
"android/web_contents_factory.cc",
"android/webapk/chrome_webapk_host.cc",
"android/webapk/chrome_webapk_host.h",
+ "android/webapk/webapk_handler_delegate.cc",
+ "android/webapk/webapk_handler_delegate.h",
"android/webapk/webapk_icon_hasher.cc",
"android/webapk/webapk_icon_hasher.h",
"android/webapk/webapk_info.cc",
@@ -2703,12 +2746,15 @@ jumbo_split_static_library("browser") {
"media/webrtc/screen_capture_infobar_delegate_android.h",
"metrics/android_metrics_provider.cc",
"metrics/android_metrics_provider.h",
+ "metrics/incognito_observer_android.cc",
"metrics/page_load_metrics_provider.cc",
"metrics/page_load_metrics_provider.h",
"notifications/notification_platform_bridge_android.cc",
"notifications/notification_platform_bridge_android.h",
"notifications/notification_trigger_scheduler_android.cc",
"notifications/notification_trigger_scheduler_android.h",
+ "notifications/scheduler/display_agent_android.cc",
+ "notifications/scheduler/display_agent_android.h",
"notifications/scheduler/notification_background_task_scheduler_android.cc",
"notifications/scheduler/notification_background_task_scheduler_android.h",
"page_load_metrics/observers/android_page_load_metrics_observer.cc",
@@ -2733,6 +2779,8 @@ jumbo_split_static_library("browser") {
"password_manager/password_manager_infobar_delegate_android.h",
"password_manager/save_password_infobar_delegate_android.cc",
"password_manager/save_password_infobar_delegate_android.h",
+ "password_manager/touch_to_fill_controller.cc",
+ "password_manager/touch_to_fill_controller.h",
"password_manager/update_password_infobar_delegate_android.cc",
"password_manager/update_password_infobar_delegate_android.h",
"payments/android/can_make_payment_query_android.cc",
@@ -2758,13 +2806,15 @@ jumbo_split_static_library("browser") {
"previews/android/previews_android_bridge.h",
"profiles/profile_android.cc",
"profiles/profile_android.h",
+ "profiles/profile_key_android.cc",
+ "profiles/profile_key_android.h",
"search/contextual_search_policy_handler_android.cc",
"search/contextual_search_policy_handler_android.h",
- "search_engines/template_url_android.cc",
- "search_engines/template_url_android.h",
- "search_engines/template_url_service_android.cc",
- "search_engines/template_url_service_android.h",
+ "search_engines/template_url_service_factory_android.cc",
+ "search_engines/template_url_service_factory_android.h",
"signin/identity_services_provider_android.cc",
+ "signin/signin_manager_android_factory.cc",
+ "signin/signin_manager_android_factory.h",
"ssl/security_state_model_android.cc",
"sync/glue/synced_tab_delegate_android.cc",
"sync/glue/synced_tab_delegate_android.h",
@@ -2776,12 +2826,17 @@ jumbo_split_static_library("browser") {
"sync/profile_sync_service_android.h",
"translate/android/translate_bridge.cc",
]
+ public_deps += [
+ "//components/image_fetcher/core",
+ "//components/ntp_snippets",
+ ]
deps += [
":client_discourse_context_proto",
":delta_file_proto",
":explore_sites_proto",
":usage_stats_proto",
"//chrome/android:jni_headers",
+ "//chrome/browser/android/thin_webview/internal",
"//chrome/browser/android/webapk:proto",
"//chrome/services/media_gallery_util/public/cpp",
"//components/autofill_assistant/browser",
@@ -2797,12 +2852,12 @@ jumbo_split_static_library("browser") {
"//components/payments/content/android",
"//components/resources:components_resources",
"//components/send_tab_to_self",
+ "//components/signin/internal/identity_manager", # see android/signin/DEPS
"//media/mojo/clients",
"//media/mojo/interfaces:constants",
"//rlz:rlz_utils",
"//sandbox",
"//sandbox:sandbox_buildflags",
- "//services/identity/public/cpp",
"//services/proxy_resolver:lib",
"//third_party/android_opengl/etc1",
"//third_party/android_sdk:cpu_features",
@@ -2830,10 +2885,12 @@ jumbo_split_static_library("browser") {
"apps/app_service/app_icon_factory.h",
"apps/app_service/app_icon_source.cc",
"apps/app_service/app_icon_source.h",
+ "apps/app_service/app_launch_params.cc",
+ "apps/app_service/app_launch_params.h",
+ "apps/app_service/app_service_proxy.cc",
+ "apps/app_service/app_service_proxy.h",
"apps/app_service/app_service_proxy_factory.cc",
"apps/app_service/app_service_proxy_factory.h",
- "apps/app_service/app_service_proxy_impl.cc",
- "apps/app_service/app_service_proxy_impl.h",
"apps/app_service/dip_px_util.cc",
"apps/app_service/dip_px_util.h",
"apps/intent_helper/apps_navigation_throttle.cc",
@@ -2848,15 +2905,22 @@ jumbo_split_static_library("browser") {
"apps/intent_helper/intent_picker_auto_display_service_factory.h",
"apps/intent_helper/page_transition_util.cc",
"apps/intent_helper/page_transition_util.h",
+ "apps/launch_service/extension_app_launch_manager.cc",
+ "apps/launch_service/extension_app_launch_manager.h",
+ "apps/launch_service/launch_manager.cc",
+ "apps/launch_service/launch_manager.h",
+ "apps/launch_service/launch_service.cc",
+ "apps/launch_service/launch_service.h",
+ "apps/launch_service/launch_service_factory.cc",
+ "apps/launch_service/launch_service_factory.h",
"background/background_contents.cc",
"background/background_contents.h",
+ "background/background_contents_service_observer.h",
"badging/badge_manager.cc",
"badging/badge_manager.h",
"badging/badge_manager_delegate.h",
"badging/badge_manager_factory.cc",
"badging/badge_manager_factory.h",
- "badging/badge_service_impl.cc",
- "badging/badge_service_impl.h",
"banners/app_banner_manager_desktop.cc",
"banners/app_banner_manager_desktop.h",
"bookmarks/bookmark_html_writer.cc",
@@ -2904,8 +2968,18 @@ jumbo_split_static_library("browser") {
"download/download_shelf_context_menu.h",
"download/download_shelf_controller.cc",
"download/download_shelf_controller.h",
+ "enterprise_reporting/extension_info.cc",
+ "enterprise_reporting/extension_info.h",
+ "enterprise_reporting/policy_info.cc",
+ "enterprise_reporting/policy_info.h",
"enterprise_reporting/prefs.cc",
"enterprise_reporting/prefs.h",
+ "enterprise_reporting/profile_report_generator.cc",
+ "enterprise_reporting/profile_report_generator.h",
+ "enterprise_reporting/report_generator.cc",
+ "enterprise_reporting/report_generator.h",
+ "enterprise_reporting/report_scheduler.cc",
+ "enterprise_reporting/report_scheduler.h",
"enterprise_reporting/report_uploader.cc",
"enterprise_reporting/report_uploader.h",
"enterprise_reporting/request_timer.cc",
@@ -2943,6 +3017,8 @@ jumbo_split_static_library("browser") {
"first_run/upgrade_util_win.h",
"font_family_cache.cc",
"font_family_cache.h",
+ "hid/chrome_hid_delegate.cc",
+ "hid/chrome_hid_delegate.h",
"hid/hid_chooser_context.cc",
"hid/hid_chooser_context.h",
"hid/hid_chooser_context_factory.cc",
@@ -3059,6 +3135,10 @@ jumbo_split_static_library("browser") {
"memory/swap_thrashing_monitor_delegate.h",
"memory/swap_thrashing_monitor_delegate_win.cc",
"memory/swap_thrashing_monitor_delegate_win.h",
+ "metrics/browser_activity_watcher.cc",
+ "metrics/browser_activity_watcher.h",
+ "metrics/desktop_platform_features_metrics_provider.cc",
+ "metrics/desktop_platform_features_metrics_provider.h",
"metrics/desktop_session_duration/audible_contents_tracker.cc",
"metrics/desktop_session_duration/audible_contents_tracker.h",
"metrics/desktop_session_duration/chrome_visibility_observer.cc",
@@ -3073,6 +3153,7 @@ jumbo_split_static_library("browser") {
"metrics/desktop_session_duration/desktop_session_duration_tracker.h",
"metrics/first_web_contents_profiler.cc",
"metrics/first_web_contents_profiler.h",
+ "metrics/incognito_observer_desktop.cc",
"metrics/tab_reactivation_tracker.cc",
"metrics/tab_reactivation_tracker.h",
"metrics/tab_stats_data_store.cc",
@@ -3211,18 +3292,16 @@ jumbo_split_static_library("browser") {
"search/background/ntp_background_service_observer.h",
"search/background/onboarding_ntp_backgrounds.cc",
"search/background/onboarding_ntp_backgrounds.h",
- "search/iframe_source.cc",
- "search/iframe_source.h",
+ "search/chrome_colors/chrome_colors_factory.cc",
+ "search/chrome_colors/chrome_colors_factory.h",
+ "search/chrome_colors/chrome_colors_service.cc",
+ "search/chrome_colors/chrome_colors_service.h",
"search/instant_service.cc",
"search/instant_service.h",
"search/instant_service_factory.cc",
"search/instant_service_factory.h",
"search/instant_service_observer.cc",
"search/instant_service_observer.h",
- "search/local_ntp_first_run_field_trial_handler.cc",
- "search/local_ntp_first_run_field_trial_handler.h",
- "search/local_ntp_first_run_field_trials.cc",
- "search/local_ntp_first_run_field_trials.h",
"search/local_ntp_source.cc",
"search/local_ntp_source.h",
"search/most_visited_iframe_source.cc",
@@ -3248,6 +3327,8 @@ jumbo_split_static_library("browser") {
"search/promos/promo_service_observer.h",
"search/search_engine_base_url_tracker.cc",
"search/search_engine_base_url_tracker.h",
+ "search/search_provider_observer.cc",
+ "search/search_provider_observer.h",
"search/search_suggest/search_suggest_data.cc",
"search/search_suggest/search_suggest_data.h",
"search/search_suggest/search_suggest_loader.h",
@@ -3268,6 +3349,16 @@ jumbo_split_static_library("browser") {
"serial/serial_chooser_context.h",
"serial/serial_chooser_context_factory.cc",
"serial/serial_chooser_context_factory.h",
+ "sharing/click_to_call/click_to_call_constants.h",
+ "sharing/click_to_call/click_to_call_context_menu_observer.cc",
+ "sharing/click_to_call/click_to_call_context_menu_observer.h",
+ "sharing/click_to_call/click_to_call_dialog.h",
+ "sharing/click_to_call/click_to_call_sharing_dialog_controller.cc",
+ "sharing/click_to_call/click_to_call_sharing_dialog_controller.h",
+ "sharing/click_to_call/click_to_call_utils.cc",
+ "sharing/click_to_call/click_to_call_utils.h",
+ "sharing/sharing_dialog_controller.cc",
+ "sharing/sharing_dialog_controller.h",
"signin/signin_promo.cc",
"signin/signin_promo.h",
"signin/signin_ui_util.cc",
@@ -3354,8 +3445,6 @@ jumbo_split_static_library("browser") {
"task_manager/sampling/task_group_sampler.h",
"task_manager/sampling/task_manager_impl.cc",
"task_manager/sampling/task_manager_impl.h",
- "task_manager/sampling/task_manager_io_thread_helper.cc",
- "task_manager/sampling/task_manager_io_thread_helper.h",
"task_manager/task_manager_interface.cc",
"task_manager/task_manager_interface.h",
"task_manager/task_manager_observer.cc",
@@ -3380,6 +3469,8 @@ jumbo_split_static_library("browser") {
"usb/web_usb_chooser_desktop.h",
"usb/web_usb_detector.cc",
"usb/web_usb_detector.h",
+ "web_launch/web_launch_files_helper.cc",
+ "web_launch/web_launch_files_helper.h",
]
deps += [
":theme_properties",
@@ -3392,12 +3483,15 @@ jumbo_split_static_library("browser") {
"//chrome/browser/resources:component_extension_resources",
"//chrome/browser/search:generated",
"//chrome/common/importer:interfaces",
+ "//chrome/common/search:generate_chrome_colors_info",
+ "//chrome/common/themes:autogenerated_theme_util",
"//chrome/services/app_service:lib",
- "//chrome/services/app_service/public/cpp:app_service_proxy",
"//chrome/services/app_service/public/cpp:app_update",
"//chrome/services/app_service/public/cpp:icon_loader",
"//components/feedback",
+ "//components/image_fetcher/core",
"//components/keep_alive_registry",
+ "//components/ntp_snippets",
"//components/vector_icons",
"//components/web_modal",
"//components/zoom",
@@ -3521,9 +3615,11 @@ jumbo_split_static_library("browser") {
deps += [
"//ash/public/cpp",
"//chrome/browser/chromeos",
- "//chrome/browser/chromeos/kiosk_next_home/mojom",
"//chrome/services/cups_proxy",
+ "//chrome/services/cups_proxy/public/mojom",
+ "//chromeos/components/account_manager",
"//chromeos/services/assistant/public:feature_flags",
+ "//chromeos/services/assistant/public/cpp:prefs",
"//chromeos/services/cellular_setup",
"//chromeos/services/device_sync",
"//chromeos/services/device_sync/public/mojom",
@@ -3537,10 +3633,7 @@ jumbo_split_static_library("browser") {
"//chromeos/services/secure_channel/public/mojom",
"//chromeos/strings",
"//components/services/font:lib",
- "//components/services/font/public/interfaces",
- "//services/ws/public/cpp/input_devices",
- "//services/ws/public/cpp/input_devices:input_device_controller",
- "//services/ws/public/mojom",
+ "//components/services/font/public/mojom",
"//ui/ozone",
]
allow_circular_includes_from += [ "//chrome/browser/chromeos" ]
@@ -3567,7 +3660,7 @@ jumbo_split_static_library("browser") {
]
}
- if (is_chromeos || enable_extensions) {
+ if (is_chromeos || enable_extensions || is_android) {
sources += [
"metrics/cached_metrics_profile.cc",
"metrics/cached_metrics_profile.h",
@@ -3593,8 +3686,11 @@ jumbo_split_static_library("browser") {
"performance_monitor/wmi_refresher.h",
"taskbar/taskbar_decorator_win.cc",
"taskbar/taskbar_decorator_win.h",
+ "win/util_win_service.cc",
+ "win/util_win_service.h",
]
public_deps += [
+ "//chrome/services/util_win/public/mojom",
"//ui/views",
"//ui/views/controls/webview",
]
@@ -3748,15 +3844,13 @@ jumbo_split_static_library("browser") {
"first_run/upgrade_util_linux.cc",
"first_run/upgrade_util_linux.h",
"icon_loader_auralinux.cc",
- "password_manager/native_backend_kwallet_x.cc",
- "password_manager/native_backend_kwallet_x.h",
"platform_util_linux.cc",
"shell_integration_linux.cc",
"shell_integration_linux.h",
]
if (use_dbus) {
- deps += [ "//components/dbus:dbus_thread_linux" ]
+ deps += [ "//components/dbus/thread_linux" ]
}
if (enable_native_notifications) {
@@ -3781,16 +3875,6 @@ jumbo_split_static_library("browser") {
]
}
- # libsecret hard depends on GLib.
- if (use_glib) {
- sources += [
- "password_manager/native_backend_libsecret.cc",
- "password_manager/native_backend_libsecret.h",
- ]
- defines += [ "USE_LIBSECRET" ]
- deps += [ "//third_party/libsecret" ]
- }
-
if (use_ozone) {
sources += [
"fullscreen_ozone.cc",
@@ -3830,6 +3914,20 @@ jumbo_split_static_library("browser") {
]
}
+ if (is_mac) {
+ sources += [
+ "accessibility/caption_settings_dialog.h",
+ "accessibility/caption_settings_dialog_mac.mm",
+ ]
+ }
+
+ if (is_win) {
+ sources += [
+ "accessibility/caption_settings_dialog.h",
+ "accessibility/caption_settings_dialog_win.cc",
+ ]
+ }
+
if (is_win || is_mac || is_desktop_linux) {
sources += [
"browser_switcher/alternative_browser_driver.h",
@@ -4049,7 +4147,7 @@ jumbo_split_static_library("browser") {
]
deps += [
"//components/printing/browser",
- "//components/services/pdf_compositor/public/interfaces",
+ "//components/services/pdf_compositor/public/mojom",
"//printing",
]
@@ -4138,7 +4236,7 @@ jumbo_split_static_library("browser") {
]
}
- if (enable_desktop_in_product_help) {
+ if (enable_legacy_desktop_in_product_help) {
sources += [
"feature_engagement/bookmark/bookmark_tracker.cc",
"feature_engagement/bookmark/bookmark_tracker.h",
@@ -4413,10 +4511,6 @@ jumbo_split_static_library("browser") {
deps += [ "//components/feed/content:feed_content" ]
}
- if (enable_isolated_xr_service) {
- deps += [ "//device/vr/public/mojom" ]
- }
-
if (enable_library_cdms) {
sources += [
"media/output_protection_impl.cc",
@@ -4491,8 +4585,6 @@ jumbo_split_static_library("browser") {
"offline_pages/background_loader_offliner.h",
"offline_pages/download_archive_manager.cc",
"offline_pages/download_archive_manager.h",
- "offline_pages/downloads/resource_throttle.cc",
- "offline_pages/downloads/resource_throttle.h",
"offline_pages/fresh_offline_content_observer.cc",
"offline_pages/fresh_offline_content_observer.h",
"offline_pages/offline_page_bookmark_observer.cc",
@@ -4505,10 +4597,6 @@ jumbo_split_static_library("browser") {
"offline_pages/offline_page_origin_utils.h",
"offline_pages/offline_page_request_handler.cc",
"offline_pages/offline_page_request_handler.h",
- "offline_pages/offline_page_request_interceptor.cc",
- "offline_pages/offline_page_request_interceptor.h",
- "offline_pages/offline_page_request_job.cc",
- "offline_pages/offline_page_request_job.h",
"offline_pages/offline_page_tab_helper.cc",
"offline_pages/offline_page_tab_helper.h",
"offline_pages/offline_page_url_loader.cc",
@@ -4563,6 +4651,8 @@ jumbo_split_static_library("browser") {
"offline_pages/android/downloads/offline_page_share_helper.h",
"offline_pages/android/load_termination_listener_impl.cc",
"offline_pages/android/load_termination_listener_impl.h",
+ "offline_pages/android/offline_page_archive_publisher_impl.cc",
+ "offline_pages/android/offline_page_archive_publisher_impl.h",
"offline_pages/android/offline_page_auto_fetcher.cc",
"offline_pages/android/offline_page_auto_fetcher.h",
"offline_pages/android/offline_page_auto_fetcher_service.cc",
@@ -4574,24 +4664,28 @@ jumbo_split_static_library("browser") {
"offline_pages/android/offline_page_model_factory.cc",
"offline_pages/android/offline_page_origin_utils_android.cc",
"offline_pages/android/offline_page_utils_android.cc",
- "offline_pages/android/offline_pages_download_manager_bridge.cc",
- "offline_pages/android/offline_pages_download_manager_bridge.h",
"offline_pages/android/prefetch_background_task_android.cc",
"offline_pages/android/prefetch_background_task_android.h",
"offline_pages/android/prefetch_background_task_scheduler_android.cc",
"offline_pages/android/prefetch_configuration_impl_android.cc",
"offline_pages/android/prefetched_pages_notifier_android.cc",
+ "offline_pages/android/request_coordinator_bridge.cc",
+ "offline_pages/android/request_coordinator_bridge.h",
"offline_pages/android/request_coordinator_factory.cc",
]
}
+
+ public_deps += [
+ "//components/offline_pages/core",
+ "//components/offline_pages/core/background:background_offliner",
+ "//components/offline_pages/core/prefetch",
+ ]
+
deps += [
"//chrome/common:offline_page_auto_fetcher_mojom",
"//components/offline_pages/content/background_loader",
"//components/offline_pages/content/renovations",
- "//components/offline_pages/core",
- "//components/offline_pages/core/background:background_offliner",
"//components/offline_pages/core/downloads:offline_pages_ui_adapter",
- "//components/offline_pages/core/prefetch",
"//components/offline_pages/core/renovations",
"//components/offline_pages/core/request_header:request_header",
]
@@ -4673,8 +4767,6 @@ jumbo_split_static_library("browser") {
"plugins/plugin_prefs_factory.h",
"plugins/plugin_response_interceptor_url_loader_throttle.cc",
"plugins/plugin_response_interceptor_url_loader_throttle.h",
- "plugins/plugin_status_pref_setter.cc",
- "plugins/plugin_status_pref_setter.h",
"plugins/plugin_utils.cc",
"plugins/plugin_utils.h",
"plugins/plugins_resource_service.cc",
@@ -4820,7 +4912,6 @@ jumbo_split_static_library("browser") {
sources += [
"spellchecker/spell_check_host_chrome_impl.cc",
"spellchecker/spell_check_host_chrome_impl.h",
- "spellchecker/spell_check_host_chrome_impl_mac.cc",
"spellchecker/spellcheck_custom_dictionary.cc",
"spellchecker/spellcheck_custom_dictionary.h",
"spellchecker/spellcheck_factory.cc",
@@ -4835,6 +4926,13 @@ jumbo_split_static_library("browser") {
"spellchecker/spellcheck_service.h",
]
+ if (use_browser_spellchecker) {
+ sources += [
+ "spellchecker/spelling_request.cc",
+ "spellchecker/spelling_request.h",
+ ]
+ }
+
if (has_spellcheck_panel) {
sources += [
"spellchecker/spell_check_panel_host_impl.cc",
@@ -4854,6 +4952,8 @@ jumbo_split_static_library("browser") {
if (enable_supervised_users) {
sources += [
+ "component_updater/supervised_user_whitelist_installer.cc",
+ "component_updater/supervised_user_whitelist_installer.h",
"content_settings/content_settings_supervised_provider.cc",
"content_settings/content_settings_supervised_provider.h",
"supervised_user/child_accounts/child_account_service.cc",
@@ -4870,6 +4970,10 @@ jumbo_split_static_library("browser") {
"supervised_user/experimental/supervised_user_blacklist.h",
"supervised_user/experimental/supervised_user_filtering_switches.cc",
"supervised_user/experimental/supervised_user_filtering_switches.h",
+ "supervised_user/kids_chrome_management/kids_chrome_management_client.cc",
+ "supervised_user/kids_chrome_management/kids_chrome_management_client.h",
+ "supervised_user/kids_chrome_management/kids_chrome_management_client_factory.cc",
+ "supervised_user/kids_chrome_management/kids_chrome_management_client_factory.h",
"supervised_user/kids_management_url_checker_client.cc",
"supervised_user/kids_management_url_checker_client.h",
"supervised_user/permission_request_creator.h",
@@ -4906,7 +5010,10 @@ jumbo_split_static_library("browser") {
"supervised_user/supervised_user_whitelist_service.h",
"supervised_user/supervised_users.h",
]
- deps += [ "//chrome/common:supervised_user_commands_mojom" ]
+ deps += [
+ "//chrome/browser/supervised_user/kids_chrome_management:proto",
+ "//chrome/common:supervised_user_commands_mojom",
+ ]
}
if (enable_supervised_users && !is_android) {
sources += [
@@ -4921,23 +5028,20 @@ jumbo_split_static_library("browser") {
if (enable_vr) {
if (enable_gvr_services) {
- deps += [ "android/vr:vr_android" ]
+ public_deps += [ "android/vr:vr_android" ]
configs += [ "//third_party/gvr-android-sdk:libgvr_config" ]
allow_circular_includes_from += [ "android/vr:vr_android" ]
}
if (is_win) {
- # TODO(https://crbug.com/916322): Switch to a "is_desktop_vr" or
- # "is_external_display_vr" build conditional since these files aren't
- # inherently Windows-specific. At this time, desktop VR where the browser
- # window shows alongside the head-mounted display is only supported on
- # Windows, and that's the only situation where we need the UI host.
sources += [
"vr/service/xr_session_request_consent_manager_impl.cc",
"vr/service/xr_session_request_consent_manager_impl.h",
"vr/ui_host/vr_ui_host_impl.cc",
"vr/ui_host/vr_ui_host_impl.h",
]
+
+ deps += [ "//device/vr/public/mojom" ]
}
sources += [
@@ -4959,25 +5063,10 @@ jumbo_split_static_library("browser") {
]
}
- if (!is_chrome_branded && !is_android) {
- sources += [
- "search/local_files_ntp_source.cc",
- "search/local_files_ntp_source.h",
- ]
- }
-
if (use_cups) {
configs += [ "//printing:cups" ]
}
- if (use_gnome_keyring) {
- sources += [
- "password_manager/native_backend_gnome_x.cc",
- "password_manager/native_backend_gnome_x.h",
- ]
- configs += [ "//components/os_crypt:gnome_keyring" ]
- }
-
if (use_nss_certs) {
sources += [
"certificate_manager_model.cc",
@@ -5080,6 +5169,12 @@ source_set("theme_properties") {
]
}
+proto_library("availability_protos") {
+ sources = [
+ "availability/proto/availability_prober_cache_entry.proto",
+ ]
+}
+
proto_library("resource_prefetch_predictor_proto") {
sources = [
"predictors/resource_prefetch_predictor.proto",
@@ -5097,10 +5192,6 @@ grit("resources") {
defines += [ "enable_hangout_services_extension" ]
}
- if (is_chromeos && enable_kiosk_next) {
- defines += [ "_kiosk_next" ]
- }
-
output_dir = "$root_gen_dir/chrome"
outputs = [
"grit/browser_resources.h",
@@ -5120,6 +5211,7 @@ grit("resources") {
"//chrome/browser/engagement:mojo_bindings_js",
"//chrome/browser/media:mojo_bindings_js",
"//chrome/browser/performance_manager:mojo_bindings_js",
+ "//chrome/browser/resources/safety_tips:make_safety_tips_protobuf",
"//chrome/browser/resources/ssl/ssl_error_assistant:make_ssl_error_assistant_protobuf",
"//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_js",
"//chrome/browser/ui/webui/interventions_internals:mojo_bindings_js",
@@ -5164,10 +5256,6 @@ grit("resources") {
]
}
- if (is_chromeos) {
- deps += [ "//chrome/browser/chromeos/supervision/mojom:mojom_js" ]
- }
-
if (is_android) {
deps += [
"//chrome/browser/ui/webui/explore_sites_internals:mojo_bindings_js",
@@ -5278,8 +5366,6 @@ static_library("test_support") {
"media/webrtc/fake_desktop_media_picker_factory.h",
"net/dns_probe_test_util.cc",
"net/dns_probe_test_util.h",
- "net/url_request_mock_util.cc",
- "net/url_request_mock_util.h",
"notifications/metrics/mock_notification_metrics_logger.cc",
"notifications/metrics/mock_notification_metrics_logger.h",
"notifications/notification_display_service_tester.cc",
@@ -5335,6 +5421,7 @@ static_library("test_support") {
"//components/safe_browsing:csd_proto",
"//components/search_engines:test_support",
"//components/sessions:test_support",
+ "//components/signin/public/identity_manager:test_support",
"//components/subresource_filter/core/browser:test_support",
"//components/subresource_filter/core/common:test_support",
"//components/sync_preferences:test_support",
@@ -5342,7 +5429,6 @@ static_library("test_support") {
"//content/test:test_support",
"//google_apis:test_support",
"//net:test_support",
- "//services/identity/public/cpp:test_support",
"//services/preferences/public/cpp/tracked:test_support",
"//skia",
"//testing/gmock",
@@ -5351,16 +5437,21 @@ static_library("test_support") {
]
if (!is_android && !is_fuchsia) {
- sources += [
- "policy/test/local_policy_test_server.cc",
- "policy/test/local_policy_test_server.h",
- ]
+ deps += [ "//components/policy/test_support" ]
}
if (is_android) {
sources += [
"android/download/mock_download_controller.cc",
"android/download/mock_download_controller.h",
+ "autofill/mock_address_accessory_controller.cc",
+ "autofill/mock_address_accessory_controller.h",
+ "autofill/mock_credit_card_accessory_controller.cc",
+ "autofill/mock_credit_card_accessory_controller.h",
+ "autofill/mock_manual_filling_view.cc",
+ "autofill/mock_manual_filling_view.h",
+ "autofill/mock_password_accessory_controller.cc",
+ "autofill/mock_password_accessory_controller.h",
]
deps += [ "//chrome/android:test_support_jni_headers" ]
} else {
@@ -5555,6 +5646,8 @@ if (!is_android) {
"signin/token_revoker_test_utils.h",
"ui/webui/signin/login_ui_test_utils.cc",
"ui/webui/signin/login_ui_test_utils.h",
+ "ui/webui/test_data_source.cc",
+ "ui/webui/test_data_source.h",
"ui/webui/web_ui_test_handler.cc",
"ui/webui/web_ui_test_handler.h",
]
diff --git a/chromium/chrome/browser/accessibility/accessibility_extension_api.cc b/chromium/chrome/browser/accessibility/accessibility_extension_api.cc
index b4050e9f4f5..55e9b36fc5f 100644
--- a/chromium/chrome/browser/accessibility/accessibility_extension_api.cc
+++ b/chromium/chrome/browser/accessibility/accessibility_extension_api.cc
@@ -20,26 +20,32 @@
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/chrome_pages.h"
+#include "chrome/browser/ui/settings_window_manager_chromeos.h"
#include "chrome/common/extensions/api/accessibility_private.h"
#include "chrome/common/extensions/extension_constants.h"
+#include "chrome/common/webui_url_constants.h"
#include "components/infobars/core/confirm_infobar_delegate.h"
#include "components/infobars/core/infobar.h"
#include "content/public/browser/browser_accessibility_state.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_system.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/image_util.h"
#include "extensions/common/manifest_handlers/background_info.h"
#include "services/service_manager/public/cpp/connector.h"
+#include "ui/accessibility/accessibility_switches.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/keycodes/keyboard_codes.h"
#if defined(OS_CHROMEOS)
+#include "ash/public/cpp/accessibility_controller.h"
+#include "ash/public/cpp/accessibility_controller_enums.h"
+#include "ash/public/cpp/accessibility_focus_ring_info.h"
+#include "ash/public/cpp/event_rewriter_controller.h"
#include "ash/public/cpp/window_tree_host_lookup.h"
-#include "ash/public/interfaces/accessibility_focus_ring_controller.mojom.h"
#include "ash/public/interfaces/constants.mojom.h"
-#include "ash/public/interfaces/event_rewriter_controller.mojom.h"
#include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
#include "chrome/browser/chromeos/arc/accessibility/arc_accessibility_helper_bridge.h"
#include "ui/aura/window_tree_host.h"
@@ -57,15 +63,6 @@ const char kErrorNotSupported[] = "This API is not supported on this platform.";
#if defined(OS_CHROMEOS)
constexpr int kBackButtonWidth = 45;
constexpr int kBackButtonHeight = 45;
-
-ash::mojom::AccessibilityControllerPtr GetAccessibilityController() {
- // Connect to the accessibility mojo interface in ash.
- ash::mojom::AccessibilityControllerPtr accessibility_controller;
- content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->BindInterface(ash::mojom::kServiceName, &accessibility_controller);
- return accessibility_controller;
-}
#endif
} // namespace
@@ -85,6 +82,27 @@ AccessibilityPrivateSetNativeAccessibilityEnabledFunction::Run() {
}
ExtensionFunction::ResponseAction
+AccessibilityPrivateOpenSettingsSubpageFunction::Run() {
+ using extensions::api::accessibility_private::OpenSettingsSubpage::Params;
+ const std::unique_ptr<Params> params(Params::Create(*args_));
+ EXTENSION_FUNCTION_VALIDATE(params);
+
+#if defined(OS_CHROMEOS)
+ Profile* profile = chromeos::AccessibilityManager::Get()->profile();
+ if (chrome::IsOSSettingsSubPage(params->subpage)) {
+ chrome::SettingsWindowManager::GetInstance()->ShowOSSettings(
+ profile, params->subpage);
+ } else {
+ chrome::ShowSettingsSubPageForProfile(profile, params->subpage);
+ }
+#else
+ // This function should only be available on ChromeOS.
+ EXTENSION_FUNCTION_VALIDATE(false);
+#endif // OS_CHROMEOS
+ return RespondNow(NoArguments());
+}
+
+ExtensionFunction::ResponseAction
AccessibilityPrivateSetFocusRingsFunction::Run() {
#if defined(OS_CHROMEOS)
std::unique_ptr<accessibility_private::SetFocusRings::Params> params(
@@ -95,42 +113,41 @@ AccessibilityPrivateSetFocusRingsFunction::Run() {
for (const accessibility_private::FocusRingInfo& focus_ring_info :
params->focus_rings) {
- ash::mojom::FocusRingPtr focus_ring_ptr = ash::mojom::FocusRing::New();
- focus_ring_ptr->behavior =
- ash::mojom::FocusRingBehavior::PERSIST_FOCUS_RING;
+ auto focus_ring = std::make_unique<ash::AccessibilityFocusRingInfo>();
+ focus_ring->behavior = ash::FocusRingBehavior::PERSIST;
// Convert the given rects into gfx::Rect objects.
for (const accessibility_private::ScreenRect& rect :
focus_ring_info.rects) {
- focus_ring_ptr->rects_in_screen.push_back(
+ focus_ring->rects_in_screen.push_back(
gfx::Rect(rect.left, rect.top, rect.width, rect.height));
}
const std::string id = accessibility_manager->GetFocusRingId(
extension_id(), focus_ring_info.id ? *(focus_ring_info.id) : "");
- if (!extensions::image_util::ParseHexColorString(
- focus_ring_info.color, &(focus_ring_ptr->color))) {
+ if (!extensions::image_util::ParseHexColorString(focus_ring_info.color,
+ &(focus_ring->color))) {
return RespondNow(Error("Could not parse hex color"));
}
if (focus_ring_info.secondary_color) {
if (!extensions::image_util::ParseHexColorString(
*(focus_ring_info.secondary_color),
- &(focus_ring_ptr->secondary_color))) {
+ &(focus_ring->secondary_color))) {
return RespondNow(Error("Could not parse secondary hex color"));
}
}
switch (focus_ring_info.type) {
case accessibility_private::FOCUS_TYPE_SOLID:
- focus_ring_ptr->type = ash::mojom::FocusRingType::SOLID;
+ focus_ring->type = ash::FocusRingType::SOLID;
break;
case accessibility_private::FOCUS_TYPE_DASHED:
- focus_ring_ptr->type = ash::mojom::FocusRingType::DASHED;
+ focus_ring->type = ash::FocusRingType::DASHED;
break;
case accessibility_private::FOCUS_TYPE_GLOW:
- focus_ring_ptr->type = ash::mojom::FocusRingType::GLOW;
+ focus_ring->type = ash::FocusRingType::GLOW;
break;
default:
NOTREACHED();
@@ -140,13 +157,13 @@ AccessibilityPrivateSetFocusRingsFunction::Run() {
// are anchored within the focused object.
// NOTE: The final anchor point will be determined by the first rect of the
// final focus ring.
- if (!focus_ring_ptr->rects_in_screen.empty()) {
+ if (!focus_ring->rects_in_screen.empty()) {
accessibility_manager->SetTouchAccessibilityAnchorPoint(
- focus_ring_ptr->rects_in_screen[0].CenterPoint());
+ focus_ring->rects_in_screen[0].CenterPoint());
}
// Set the focus ring.
- accessibility_manager->SetFocusRing(id, std::move(focus_ring_ptr));
+ accessibility_manager->SetFocusRing(id, std::move(focus_ring));
}
return RespondNow(NoArguments());
@@ -201,13 +218,8 @@ AccessibilityPrivateSetKeyboardListenerFunction::Run() {
manager->SetKeyboardListenerExtensionId(
enabled ? extension()->id() : std::string(), details.GetProfile());
- ash::mojom::EventRewriterControllerPtr event_rewriter_controller_ptr;
- content::ServiceManagerConnection* connection =
- content::ServiceManagerConnection::GetForProcess();
- connection->GetConnector()->BindInterface(ash::mojom::kServiceName,
- &event_rewriter_controller_ptr);
- event_rewriter_controller_ptr->CaptureAllKeysForSpokenFeedback(enabled &&
- capture);
+ ash::EventRewriterController::Get()->CaptureAllKeysForSpokenFeedback(
+ enabled && capture);
return RespondNow(NoArguments());
#endif // defined OS_CHROMEOS
@@ -233,7 +245,8 @@ AccessibilityPrivateSetSwitchAccessKeysFunction::Run() {
accessibility_private::SetSwitchAccessKeys::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params);
- GetAccessibilityController()->SetSwitchAccessKeysToCapture(params->key_codes);
+ ash::AccessibilityController::Get()->SetSwitchAccessKeysToCapture(
+ params->key_codes);
return RespondNow(NoArguments());
}
@@ -298,12 +311,7 @@ ExtensionFunction::ResponseAction
AccessibilityPrivateEnableChromeVoxMouseEventsFunction::Run() {
bool enabled = false;
EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(0, &enabled));
- ash::mojom::EventRewriterControllerPtr event_rewriter_controller_ptr;
- content::ServiceManagerConnection* connection =
- content::ServiceManagerConnection::GetForProcess();
- connection->GetConnector()->BindInterface(ash::mojom::kServiceName,
- &event_rewriter_controller_ptr);
- event_rewriter_controller_ptr->SetSendMouseEventsToDelegate(enabled);
+ ash::EventRewriterController::Get()->SetSendMouseEventsToDelegate(enabled);
return RespondNow(NoArguments());
}
@@ -371,20 +379,20 @@ AccessibilityPrivateOnSelectToSpeakStateChangedFunction::Run() {
*args_);
EXTENSION_FUNCTION_VALIDATE(params);
accessibility_private::SelectToSpeakState params_state = params->state;
- ash::mojom::SelectToSpeakState state;
+ ash::SelectToSpeakState state;
switch (params_state) {
case accessibility_private::SelectToSpeakState::
SELECT_TO_SPEAK_STATE_SELECTING:
- state = ash::mojom::SelectToSpeakState::kSelectToSpeakStateSelecting;
+ state = ash::SelectToSpeakState::kSelectToSpeakStateSelecting;
break;
case accessibility_private::SelectToSpeakState::
SELECT_TO_SPEAK_STATE_SPEAKING:
- state = ash::mojom::SelectToSpeakState::kSelectToSpeakStateSpeaking;
+ state = ash::SelectToSpeakState::kSelectToSpeakStateSpeaking;
break;
case accessibility_private::SelectToSpeakState::
SELECT_TO_SPEAK_STATE_INACTIVE:
case accessibility_private::SelectToSpeakState::SELECT_TO_SPEAK_STATE_NONE:
- state = ash::mojom::SelectToSpeakState::kSelectToSpeakStateInactive;
+ state = ash::SelectToSpeakState::kSelectToSpeakStateInactive;
}
auto* accessibility_manager = chromeos::AccessibilityManager::Get();
@@ -394,17 +402,29 @@ AccessibilityPrivateOnSelectToSpeakStateChangedFunction::Run() {
}
ExtensionFunction::ResponseAction
+AccessibilityPrivateOnScrollableBoundsForPointFoundFunction::Run() {
+ std::unique_ptr<
+ accessibility_private::OnScrollableBoundsForPointFound::Params>
+ params = accessibility_private::OnScrollableBoundsForPointFound::Params::
+ Create(*args_);
+ EXTENSION_FUNCTION_VALIDATE(params);
+ accessibility_private::ScreenRect rect = std::move(params->rect);
+ gfx::Rect bounds(rect.left, rect.top, rect.width, rect.height);
+ ash::AccessibilityController::Get()->OnAutoclickScrollableBoundsFound(bounds);
+ return RespondNow(NoArguments());
+}
+
+ExtensionFunction::ResponseAction
AccessibilityPrivateToggleDictationFunction::Run() {
- ash::mojom::DictationToggleSource source =
- ash::mojom::DictationToggleSource::kChromevox;
+ ash::DictationToggleSource source = ash::DictationToggleSource::kChromevox;
if (extension()->id() == extension_misc::kSwitchAccessExtensionId)
- source = ash::mojom::DictationToggleSource::kSwitchAccess;
+ source = ash::DictationToggleSource::kSwitchAccess;
else if (extension()->id() == extension_misc::kChromeVoxExtensionId)
- source = ash::mojom::DictationToggleSource::kChromevox;
+ source = ash::DictationToggleSource::kChromevox;
else
NOTREACHED();
- GetAccessibilityController()->ToggleDictationFromSource(source);
+ ash::AccessibilityController::Get()->ToggleDictationFromSource(source);
return RespondNow(NoArguments());
}
@@ -438,7 +458,13 @@ AccessibilityPrivateSetSwitchAccessMenuStateFunction::Run() {
int padding = 40;
int item_width = 88;
- int item_height = 60;
+
+ int item_height;
+ if (::switches::IsExperimentalAccessibilitySwitchAccessTextEnabled()) {
+ item_height = 85;
+ } else {
+ item_height = 60;
+ }
// TODO(anastasi): This should be a preference that the user can change.
int max_cols = 3;
@@ -461,7 +487,7 @@ AccessibilityPrivateForwardKeyEventsToSwitchAccessFunction::Run() {
*args_);
EXTENSION_FUNCTION_VALIDATE(params);
- GetAccessibilityController()->ForwardKeyEventsToSwitchAccess(
+ ash::AccessibilityController::Get()->ForwardKeyEventsToSwitchAccess(
params->should_forward);
return RespondNow(NoArguments());
@@ -475,24 +501,8 @@ AccessibilityPrivateGetBatteryDescriptionFunction::
ExtensionFunction::ResponseAction
AccessibilityPrivateGetBatteryDescriptionFunction::Run() {
- // Get AccessibilityControllerPtr; needs to exist for lifetime of this
- // function and its callback.
- controller_ = GetAccessibilityController();
-
- // Get battery description from ash and return it via callback.
- controller_->GetBatteryDescription(
- base::BindOnce(&AccessibilityPrivateGetBatteryDescriptionFunction::
- OnGotBatteryDescription,
- this));
-
- return RespondLater();
-}
-
-void AccessibilityPrivateGetBatteryDescriptionFunction::OnGotBatteryDescription(
- const base::string16& battery_description) {
- // Send battery description to extension.
- Respond(OneArgument(std::make_unique<base::Value>(battery_description)));
- controller_.reset();
+ return RespondNow(OneArgument(std::make_unique<base::Value>(
+ ash::AccessibilityController::Get()->GetBatteryDescription())));
}
ExtensionFunction::ResponseAction
@@ -502,7 +512,8 @@ AccessibilityPrivateSetVirtualKeyboardVisibleFunction::Run() {
*args_);
EXTENSION_FUNCTION_VALIDATE(params);
- GetAccessibilityController()->SetVirtualKeyboardVisible(params->is_visible);
+ ash::AccessibilityController::Get()->SetVirtualKeyboardVisible(
+ params->is_visible);
return RespondNow(NoArguments());
}
diff --git a/chromium/chrome/browser/accessibility/accessibility_extension_api.h b/chromium/chrome/browser/accessibility/accessibility_extension_api.h
index 36bb5d7b992..0d21dd303dc 100644
--- a/chromium/chrome/browser/accessibility/accessibility_extension_api.h
+++ b/chromium/chrome/browser/accessibility/accessibility_extension_api.h
@@ -12,10 +12,6 @@
#include "extensions/browser/extension_function.h"
#include "ui/accessibility/ax_enums.mojom.h"
-#if defined(OS_CHROMEOS)
-#include "ash/public/interfaces/accessibility_controller.mojom.h"
-#endif
-
// API function that enables or disables web content accessibility support.
class AccessibilityPrivateSetNativeAccessibilityEnabledFunction
: public UIThreadExtensionFunction {
@@ -62,8 +58,17 @@ class AccessibilityPrivateDarkenScreenFunction
ACCESSIBILITY_PRIVATE_DARKENSCREEN)
};
-// API function that sets the keys to be captured by Switch Access.
+// Opens a specified subpage in Chrome settings.
+class AccessibilityPrivateOpenSettingsSubpageFunction
+ : public UIThreadExtensionFunction {
+ ~AccessibilityPrivateOpenSettingsSubpageFunction() override {}
+ ResponseAction Run() override;
+ DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.openSettingsSubpage",
+ ACCESSIBILITY_PRIVATE_OPENSETTINGSSUBPAGE)
+};
+
#if defined(OS_CHROMEOS)
+// API function that sets the keys to be captured by Switch Access.
class AccessibilityPrivateSetSwitchAccessKeysFunction
: public UIThreadExtensionFunction {
~AccessibilityPrivateSetSwitchAccessKeysFunction() override {}
@@ -119,6 +124,17 @@ class AccessibilityPrivateOnSelectToSpeakStateChangedFunction
ACCESSIBILITY_PRIVATE_ONSELECTTOSPEAKSTATECHANGED)
};
+// API function that is called when the Autoclick extension finds scrollable
+// bounds.
+class AccessibilityPrivateOnScrollableBoundsForPointFoundFunction
+ : public UIThreadExtensionFunction {
+ ~AccessibilityPrivateOnScrollableBoundsForPointFoundFunction() override {}
+ ResponseAction Run() override;
+ DECLARE_EXTENSION_FUNCTION(
+ "accessibilityPrivate.onScrollableBoundsForPointFound",
+ ACCESSIBILITY_PRIVATE_ONSCROLLABLEBOUNDSFORPOINTFOUND)
+};
+
// API function that is called when a user toggles Dictation from another
// acessibility feature.
class AccessibilityPrivateToggleDictationFunction
@@ -155,13 +171,11 @@ class AccessibilityPrivateGetBatteryDescriptionFunction
public:
AccessibilityPrivateGetBatteryDescriptionFunction();
ResponseAction Run() override;
- void OnGotBatteryDescription(const base::string16& battery_description);
DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.getBatteryDescription",
ACCESSIBILITY_PRIVATE_GETBATTERYDESCRIPTION)
private:
~AccessibilityPrivateGetBatteryDescriptionFunction() override;
- ash::mojom::AccessibilityControllerPtr controller_ = nullptr;
};
// API function that opens or closes the virtual keyboard.
diff --git a/chromium/chrome/browser/accessibility/accessibility_extension_api_browsertest.cc b/chromium/chrome/browser/accessibility/accessibility_extension_api_browsertest.cc
index 890b578fc7c..68771079c80 100644
--- a/chromium/chrome/browser/accessibility/accessibility_extension_api_browsertest.cc
+++ b/chromium/chrome/browser/accessibility/accessibility_extension_api_browsertest.cc
@@ -2,8 +2,14 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
#include "chrome/browser/extensions/extension_apitest.h"
+#include "chrome/browser/ui/browser_list.h"
+#include "chrome/browser/ui/settings_window_manager_chromeos.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
+#include "chrome/browser/web_applications/system_web_app_manager.h"
+#include "chrome/browser/web_applications/web_app_provider.h"
+#include "chrome/common/webui_url_constants.h"
#include "ui/base/ui_base_features.h"
namespace extensions {
@@ -16,4 +22,64 @@ IN_PROC_BROWSER_TEST_F(AccessibilityPrivateApiTest, SendSyntheticKeyEvent) {
<< message_;
}
+IN_PROC_BROWSER_TEST_F(AccessibilityPrivateApiTest, GetDisplayLanguageTest) {
+ ASSERT_TRUE(
+ RunExtensionSubtest("accessibility_private/", "display_language.html"))
+ << message_;
+}
+
+IN_PROC_BROWSER_TEST_F(AccessibilityPrivateApiTest, OpenSettingsSubpage) {
+ Profile* profile = chromeos::AccessibilityManager::Get()->profile();
+
+ // Install the Settings App.
+ web_app::WebAppProvider::Get(profile)
+ ->system_web_app_manager()
+ .InstallSystemAppsForTesting();
+
+ ASSERT_TRUE(RunExtensionSubtest("accessibility_private/",
+ "open_settings_subpage.html"))
+ << message_;
+
+ chrome::SettingsWindowManager* settings_manager =
+ chrome::SettingsWindowManager::GetInstance();
+
+ Browser* settings_browser = settings_manager->FindBrowserForProfile(profile);
+ EXPECT_NE(nullptr, settings_browser);
+
+ content::WebContents* web_contents =
+ settings_browser->tab_strip_model()->GetWebContentsAt(0);
+
+ WaitForLoadStop(web_contents);
+
+ EXPECT_EQ(GURL("chrome://settings/manageAccessibility/tts"),
+ web_contents->GetLastCommittedURL());
+}
+
+IN_PROC_BROWSER_TEST_F(AccessibilityPrivateApiTest,
+ OpenSettingsSubpage_InvalidSubpage) {
+ Profile* profile = chromeos::AccessibilityManager::Get()->profile();
+
+ // Install the Settings App.
+ web_app::WebAppProvider::Get(profile)
+ ->system_web_app_manager()
+ .InstallSystemAppsForTesting();
+
+ ASSERT_TRUE(RunExtensionSubtest("accessibility_private/",
+ "open_settings_subpage_invalid_subpage.html"))
+ << message_;
+
+ chrome::SettingsWindowManager* settings_manager =
+ chrome::SettingsWindowManager::GetInstance();
+
+ Browser* settings_browser = settings_manager->FindBrowserForProfile(profile);
+ EXPECT_NE(nullptr, settings_browser);
+
+ content::WebContents* web_contents =
+ settings_browser->tab_strip_model()->GetWebContentsAt(0);
+
+ WaitForLoadStop(web_contents);
+
+ EXPECT_EQ(GURL("chrome://settings"), web_contents->GetLastCommittedURL());
+}
+
} // namespace extensions
diff --git a/chromium/chrome/browser/accessibility/accessibility_labels_service.cc b/chromium/chrome/browser/accessibility/accessibility_labels_service.cc
index ca18fd018c4..87859f2f990 100644
--- a/chromium/chrome/browser/accessibility/accessibility_labels_service.cc
+++ b/chromium/chrome/browser/accessibility/accessibility_labels_service.cc
@@ -67,7 +67,7 @@ void AccessibilityLabelsService::Init() {
}
AccessibilityLabelsService::AccessibilityLabelsService(Profile* profile)
- : profile_(profile), weak_factory_(this) {}
+ : profile_(profile) {}
ui::AXMode AccessibilityLabelsService::GetAXMode() {
ui::AXMode ax_mode =
diff --git a/chromium/chrome/browser/accessibility/accessibility_labels_service.h b/chromium/chrome/browser/accessibility/accessibility_labels_service.h
index 8213c14630f..dfb0b174ec1 100644
--- a/chromium/chrome/browser/accessibility/accessibility_labels_service.h
+++ b/chromium/chrome/browser/accessibility/accessibility_labels_service.h
@@ -51,7 +51,7 @@ class AccessibilityLabelsService : public KeyedService {
PrefChangeRegistrar pref_change_registrar_;
- base::WeakPtrFactory<AccessibilityLabelsService> weak_factory_;
+ base::WeakPtrFactory<AccessibilityLabelsService> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(AccessibilityLabelsService);
};
diff --git a/chromium/chrome/browser/accessibility/caption_settings_dialog.h b/chromium/chrome/browser/accessibility/caption_settings_dialog.h
new file mode 100644
index 00000000000..d6f08fa0dbf
--- /dev/null
+++ b/chromium/chrome/browser/accessibility/caption_settings_dialog.h
@@ -0,0 +1,25 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_ACCESSIBILITY_CAPTION_SETTINGS_DIALOG_H_
+#define CHROME_BROWSER_ACCESSIBILITY_CAPTION_SETTINGS_DIALOG_H_
+
+#include "base/macros.h"
+
+namespace captions {
+
+// An abstraction of a caption settings dialog. This is used for the captions
+// sub-section of Settings.
+class CaptionSettingsDialog {
+ public:
+ // Displays the native captions manager dialog.
+ static void ShowCaptionSettingsDialog();
+
+ private:
+ DISALLOW_IMPLICIT_CONSTRUCTORS(CaptionSettingsDialog);
+};
+
+} // namespace captions
+
+#endif // CHROME_BROWSER_ACCESSIBILITY_CAPTION_SETTINGS_DIALOG_H_
diff --git a/chromium/chrome/browser/accessibility/caption_settings_dialog_mac.mm b/chromium/chrome/browser/accessibility/caption_settings_dialog_mac.mm
new file mode 100644
index 00000000000..ae9c4aae2b1
--- /dev/null
+++ b/chromium/chrome/browser/accessibility/caption_settings_dialog_mac.mm
@@ -0,0 +1,20 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/accessibility/caption_settings_dialog.h"
+
+#import <AppKit/AppKit.h>
+
+namespace captions {
+
+static NSString* kCaptionSettingsUrlString =
+ @"x-apple.systempreferences:com.apple.preference.universalaccess?"
+ @"Captioning";
+
+void CaptionSettingsDialog::ShowCaptionSettingsDialog() {
+ [[NSWorkspace sharedWorkspace]
+ openURL:[NSURL URLWithString:kCaptionSettingsUrlString]];
+}
+
+} // namespace captions
diff --git a/chromium/chrome/browser/accessibility/caption_settings_dialog_win.cc b/chromium/chrome/browser/accessibility/caption_settings_dialog_win.cc
new file mode 100644
index 00000000000..aef787a1068
--- /dev/null
+++ b/chromium/chrome/browser/accessibility/caption_settings_dialog_win.cc
@@ -0,0 +1,34 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/accessibility/caption_settings_dialog.h"
+
+#include <windows.h>
+#include <shellapi.h>
+
+#include "base/bind.h"
+#include "base/task/post_task.h"
+#include "base/win/windows_version.h"
+
+namespace {
+
+// A helper callback that opens the caption settings dialog.
+void CaptionSettingsDialogCallback() {
+ if (base::win::GetVersion() >= base::win::Version::WIN10) {
+ ShellExecute(NULL, L"open", L"ms-settings:easeofaccess-closedcaptioning",
+ NULL, NULL, SW_SHOWNORMAL);
+ }
+}
+
+} // namespace
+
+namespace captions {
+
+void CaptionSettingsDialog::ShowCaptionSettingsDialog() {
+ base::PostTaskWithTraits(
+ FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
+ base::BindOnce(CaptionSettingsDialogCallback));
+}
+
+} // namespace captions
diff --git a/chromium/chrome/browser/accessibility/image_annotation_browsertest.cc b/chromium/chrome/browser/accessibility/image_annotation_browsertest.cc
index 2cff729f98a..c150bc9728a 100644
--- a/chromium/chrome/browser/accessibility/image_annotation_browsertest.cc
+++ b/chromium/chrome/browser/accessibility/image_annotation_browsertest.cc
@@ -401,7 +401,9 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, ImageWithSrcSet) {
"Appears to say: red.png Annotation. Appears to be: red.png 'en' Label");
}
-IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, AnnotationLanguages) {
+// Disabled due to flakiness. http://crbug.com/983404
+IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest,
+ DISABLED_AnnotationLanguages) {
FakeAnnotator::SetReturnOcrResults(true);
FakeAnnotator::SetReturnLabelResults(true);
diff --git a/chromium/chrome/browser/accessibility/interstitial_accessibility_browsertest.cc b/chromium/chrome/browser/accessibility/interstitial_accessibility_browsertest.cc
index b6088ffd705..bd453ac2df2 100644
--- a/chromium/chrome/browser/accessibility/interstitial_accessibility_browsertest.cc
+++ b/chromium/chrome/browser/accessibility/interstitial_accessibility_browsertest.cc
@@ -2,11 +2,9 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "base/feature_list.h"
#include "chrome/browser/ssl/ssl_blocking_page.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
-#include "chrome/common/chrome_features.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/security_interstitials/content/security_interstitial_tab_helper.h"
@@ -38,38 +36,22 @@ class InterstitialAccessibilityBrowserTest : public InProcessBrowserTest {
net::EmbeddedTestServer https_server_mismatched_;
bool IsShowingInterstitial(content::WebContents* tab) {
- if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) {
- security_interstitials::SecurityInterstitialTabHelper* helper =
- security_interstitials::SecurityInterstitialTabHelper::
- FromWebContents(tab);
- if (!helper) {
- return false;
- }
- return helper
- ->GetBlockingPageForCurrentlyCommittedNavigationForTesting() !=
- nullptr;
+ security_interstitials::SecurityInterstitialTabHelper* helper =
+ security_interstitials::SecurityInterstitialTabHelper::FromWebContents(
+ tab);
+ if (!helper) {
+ return false;
}
- return tab->ShowingInterstitialPage();
+ return helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting() !=
+ nullptr;
}
void ProceedThroughInterstitial(content::WebContents* web_contents) {
- if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) {
- content::TestNavigationObserver nav_observer(web_contents, 1);
- std::string javascript =
- "window.certificateErrorPageController.proceed();";
- ASSERT_TRUE(content::ExecuteScript(web_contents, javascript));
- nav_observer.Wait();
- return;
- }
- content::InterstitialPage* interstitial_page =
- web_contents->GetInterstitialPage();
- ASSERT_TRUE(interstitial_page);
- ASSERT_EQ(SSLBlockingPage::kTypeForTesting,
- interstitial_page->GetDelegateForTesting()->GetTypeForTesting());
- SSLBlockingPage* ssl_interstitial = static_cast<SSLBlockingPage*>(
- interstitial_page->GetDelegateForTesting());
- ssl_interstitial->CommandReceived(
- base::NumberToString(security_interstitials::CMD_PROCEED));
+ content::TestNavigationObserver nav_observer(web_contents, 1);
+ std::string javascript = "window.certificateErrorPageController.proceed();";
+ ASSERT_TRUE(content::ExecuteScript(web_contents, javascript));
+ nav_observer.Wait();
+ return;
}
};
diff --git a/chromium/chrome/browser/android/metrics/BUILD.gn b/chromium/chrome/browser/android/metrics/BUILD.gn
index 7c005ea7598..cdb8fca1868 100644
--- a/chromium/chrome/browser/android/metrics/BUILD.gn
+++ b/chromium/chrome/browser/android/metrics/BUILD.gn
@@ -22,7 +22,6 @@ if (is_android) {
sources = [
"../../../android/java/src/org/chromium/chrome/browser/metrics/UkmUtilsForTest.java",
]
- jni_package = "chrome"
}
android_library("ukm_utils_java") {
diff --git a/chromium/chrome/browser/android/thin_webview/BUILD.gn b/chromium/chrome/browser/android/thin_webview/BUILD.gn
new file mode 100644
index 00000000000..dfb1f698cbc
--- /dev/null
+++ b/chromium/chrome/browser/android/thin_webview/BUILD.gn
@@ -0,0 +1,43 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//build/config/android/config.gni")
+import("//build/config/android/rules.gni")
+
+source_set("thin_webview") {
+ sources = [
+ "compositor_view.h",
+ ]
+ public_deps = [
+ "//base",
+ ]
+}
+
+android_library("java") {
+ java_files = [
+ "java/src/org/chromium/chrome/browser/thinwebview/CompositorView.java",
+ "java/src/org/chromium/chrome/browser/thinwebview/ThinWebView.java",
+ ]
+
+ deps = [
+ "//base:base_java",
+ "//content/public/android:content_java",
+ "//ui/android:ui_java",
+ ]
+}
+
+android_library("factory_java") {
+ java_files = [
+ "java/src/org/chromium/chrome/browser/thinwebview/CompositorViewFactory.java",
+ "java/src/org/chromium/chrome/browser/thinwebview/ThinWebViewFactory.java",
+ ]
+
+ deps = [
+ ":java",
+ "internal:internal_java",
+ "//base:base_java",
+ "//content/public/android:content_java",
+ "//ui/android:ui_java",
+ ]
+}
diff --git a/chromium/chrome/browser/android/thin_webview/internal/BUILD.gn b/chromium/chrome/browser/android/thin_webview/internal/BUILD.gn
new file mode 100644
index 00000000000..e4257ce9521
--- /dev/null
+++ b/chromium/chrome/browser/android/thin_webview/internal/BUILD.gn
@@ -0,0 +1,50 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//build/config/android/config.gni")
+import("//build/config/android/rules.gni")
+
+static_library("internal") {
+ sources = [
+ "compositor_view_impl.cc",
+ "compositor_view_impl.h",
+ "thin_webview.cc",
+ "thin_webview.h",
+ ]
+
+ deps = [
+ ":jni_headers",
+ "//cc",
+ "//skia",
+ ]
+
+ public_deps = [
+ "//base",
+ "//chrome/browser/android/thin_webview",
+ "//content/public/browser",
+ "//ui/android",
+ ]
+}
+
+android_library("internal_java") {
+ java_files = [
+ "java/src/org/chromium/chrome/browser/thinwebview/internal/CompositorViewImpl.java",
+ "java/src/org/chromium/chrome/browser/thinwebview/internal/ThinWebViewImpl.java",
+ ]
+
+ deps = [
+ "//base:base_java",
+ "//chrome/browser/android/thin_webview:java",
+ "//content/public/android:content_java",
+ "//ui/android:ui_java",
+ ]
+}
+
+generate_jni("jni_headers") {
+ visibility = [ ":*" ]
+ sources = [
+ "java/src/org/chromium/chrome/browser/thinwebview/internal/CompositorViewImpl.java",
+ "java/src/org/chromium/chrome/browser/thinwebview/internal/ThinWebViewImpl.java",
+ ]
+}
diff --git a/chromium/chrome/browser/android/vr/BUILD.gn b/chromium/chrome/browser/android/vr/BUILD.gn
index cb2da4c1901..3deba2912d9 100644
--- a/chromium/chrome/browser/android/vr/BUILD.gn
+++ b/chromium/chrome/browser/android/vr/BUILD.gn
@@ -71,6 +71,8 @@ static_library("vr_android") {
"arcore_device/ar_renderer.cc",
"arcore_device/ar_renderer.h",
"arcore_device/arcore.h",
+ "arcore_device/arcore_consent_prompt.cc",
+ "arcore_device/arcore_consent_prompt.h",
"arcore_device/arcore_device.cc",
"arcore_device/arcore_device.h",
"arcore_device/arcore_device_provider.cc",
@@ -81,9 +83,10 @@ static_library("vr_android") {
"arcore_device/arcore_gl_thread.h",
"arcore_device/arcore_impl.cc",
"arcore_device/arcore_impl.h",
- "arcore_device/arcore_install_utils.h",
"arcore_device/arcore_java_utils.cc",
"arcore_device/arcore_java_utils.h",
+ "arcore_device/arcore_sdk.h",
+ "arcore_device/arcore_session_utils.h",
"arcore_device/arcore_shim.cc",
"arcore_device/arcore_shim.h",
"arcore_device/type_converters.cc",
@@ -111,7 +114,7 @@ static_library("vr_android") {
"//device/vr/buildflags:buildflags",
"//services/device/public/mojom",
"//services/metrics/public/cpp:ukm_builders",
- "//services/ws/public/cpp/gpu",
+ "//services/viz/public/cpp/gpu",
"//third_party/gvr-android-sdk:gvr_shim",
"//ui/android",
"//ui/base",
@@ -201,16 +204,13 @@ loadable_module("vr_ui_dummy_lib") {
android_library("ar_java") {
deps = [
- "//third_party/android_deps:com_google_ar_core_java",
- ]
-
- java_files = [ "//chrome/android/java/src/org/chromium/chrome/browser/vr/ArCoreShimImpl.java" ]
-
- classpath_deps = [
"//base:base_java",
"//chrome/android:chrome_java",
+ "//third_party/arcore-android-sdk-client:com_google_ar_core_java",
]
+ java_files = [ "//chrome/android/java/src/org/chromium/chrome/browser/vr/ArCoreShimImpl.java" ]
+
# TODO(crbug.com/938909): chromium_code.flags is not used as a proguard
# config when proguarding asynchronously. This results in AR crashing
# chrome when AR is an async DFM. Should implement a more scalable
@@ -223,15 +223,15 @@ android_library("ar_java") {
if (enable_arcore) {
generate_jni("ar_jni_headers") {
sources = [
+ "//chrome/android/java/src/org/chromium/chrome/browser/vr/ArCoreInstallUtils.java",
"//chrome/android/java/src/org/chromium/chrome/browser/vr/ArCoreJavaUtils.java",
]
- jni_package = "vr"
}
}
if (current_toolchain == default_toolchain) {
generate_jni_registration("jni_registration") {
- target = "//chrome/android/features/vr:java"
+ target = "//chrome/android:chrome_modern_public_bundle_vr_bundle_module"
header_output = "$target_gen_dir/${target_name}.h"
namespace = "vr"
}
diff --git a/chromium/chrome/browser/apps/app_shim/BUILD.gn b/chromium/chrome/browser/apps/app_shim/BUILD.gn
index 380edca554b..bcc8043ddf0 100644
--- a/chromium/chrome/browser/apps/app_shim/BUILD.gn
+++ b/chromium/chrome/browser/apps/app_shim/BUILD.gn
@@ -20,8 +20,6 @@ source_set("app_shim") {
"extension_app_shim_handler_mac.h",
"mach_bootstrap_acceptor.cc",
"mach_bootstrap_acceptor.h",
- "unix_domain_socket_acceptor.cc",
- "unix_domain_socket_acceptor.h",
]
deps = [
@@ -36,6 +34,7 @@ source_set("app_shim") {
"//chrome/common:mojo_bindings",
"//chrome/common:non_code_constants",
"//components/crx_file",
+ "//components/remote_cocoa/browser",
"//components/version_info",
"//content/public/browser",
"//content/public/common",
diff --git a/chromium/chrome/browser/browser_resources.grd b/chromium/chrome/browser/browser_resources.grd
index c34b713e178..c0cef303f4a 100644
--- a/chromium/chrome/browser/browser_resources.grd
+++ b/chromium/chrome/browser/browser_resources.grd
@@ -8,24 +8,70 @@
</outputs>
<release seq="1">
<structures>
- <if expr="chromeos">
- <structure name="IDR_FIRST_RUN_HTML" file="resources\chromeos\first_run\first_run.html" flattenhtml="true" type="chrome_html"/>
- <structure name="IDR_FIRST_RUN_JS" file="resources\chromeos\first_run\first_run.js" flattenhtml="true" type="chrome_html" />
- </if>
+ <structure name="IDR_SIGNIN_SHARED_CSS_HTML" file="resources\signin\signin_shared_css.html" preprocess="true" allowexternalscript="true" type="chrome_html" />
<if expr="not is_android">
<structure name="IDR_INCOGNITO_TAB_HTML" file="resources\ntp4\incognito_tab.html" flattenhtml="true" type="chrome_html" />
<structure name="IDR_GUEST_TAB_HTML" file="resources\ntp4\guest_tab.html" flattenhtml="true" type="chrome_html" />
- </if>
- <if expr="chromeos">
- <structure name="IDR_MD_LOGIN_HTML" file="resources\chromeos\login\md_login.html" flattenhtml="true" type="chrome_html" variables="OOBE=md_login" expand_variables="true"/>
- <structure name="IDR_MD_LOGIN_JS" file="resources\chromeos\login\md_login.js" flattenhtml="true" type="chrome_html" />
- </if>
- <if expr="not is_android">
<structure name="IDR_NEW_INCOGNITO_TAB_THEME_CSS" file="resources\ntp4\new_incognito_tab_theme.css" flattenhtml="true" type="chrome_html" />
<structure name="IDR_NEW_TAB_4_HTML" file="resources\ntp4\new_tab.html" flattenhtml="true" type="chrome_html" />
<structure name="IDR_NEW_TAB_4_THEME_CSS" file="resources\ntp4\new_tab_theme.css" flattenhtml="true" type="chrome_html" />
+ <!-- Bookmarks WebUI. -->
+ <if expr="optimize_webui">
+ <then>
+ <structure name="IDR_BOOKMARKS_VULCANIZED_HTML" file="${root_gen_dir}\chrome\browser\resources\bookmarks\vulcanized.html" use_base_dir="false" preprocess="true" type="chrome_html" compress="gzip" />
+ <structure name="IDR_BOOKMARKS_CRISPER_JS" file="${root_gen_dir}\chrome\browser\resources\bookmarks\crisper.js" use_base_dir="false" preprocess="true" type="chrome_html" compress="gzip" />
+ </then>
+ <else>
+ <structure name="IDR_BOOKMARKS_ACTIONS_HTML" file="resources\bookmarks\actions.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_ACTIONS_JS" file="resources\bookmarks\actions.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_API_LISTENER_HTML" file="resources\bookmarks\api_listener.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_API_LISTENER_JS" file="resources\bookmarks\api_listener.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_APP_HTML" file="resources\bookmarks\app.html" type="chrome_html" preprocess="true" />
+ <structure name="IDR_BOOKMARKS_APP_JS" file="resources\bookmarks\app.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_BOOKMARKS_HTML" file="resources\bookmarks\bookmarks.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_COMMAND_MANAGER_HTML" file="resources\bookmarks\command_manager.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_COMMAND_MANAGER_JS" file="resources\bookmarks\command_manager.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_CONSTANTS_HTML" file="resources\bookmarks\constants.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_CONSTANTS_JS" file="resources\bookmarks\constants.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_DEBOUNCER_HTML" file="resources\bookmarks\debouncer.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_DEBOUNCER_JS" file="resources\bookmarks\debouncer.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_DIALOG_FOCUS_MANAGER_HTML" file="resources\bookmarks\dialog_focus_manager.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_DIALOG_FOCUS_MANAGER_JS" file="resources\bookmarks\dialog_focus_manager.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_DND_MANAGER_HTML" file="resources\bookmarks\dnd_manager.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_DND_MANAGER_JS" file="resources\bookmarks\dnd_manager.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_EDIT_DIALOG_HTML" file="resources\bookmarks\edit_dialog.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_EDIT_DIALOG_JS" file="resources\bookmarks\edit_dialog.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_FOLDER_NODE_HTML" file="resources\bookmarks\folder_node.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_FOLDER_NODE_JS" file="resources\bookmarks\folder_node.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_ITEM_HTML" file="resources\bookmarks\item.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_ITEM_JS" file="resources\bookmarks\item.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_LIST_HTML" file="resources\bookmarks\list.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_LIST_JS" file="resources\bookmarks\list.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_MOUSE_FOCUS_BEHAVIOR_HTML" file="resources\bookmarks\mouse_focus_behavior.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_MOUSE_FOCUS_BEHAVIOR_JS" file="resources\bookmarks\mouse_focus_behavior.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_REDUCERS_HTML" file="resources\bookmarks\reducers.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_REDUCERS_JS" file="resources\bookmarks\reducers.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_ROUTER_HTML" file="resources\bookmarks\router.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_ROUTER_JS" file="resources\bookmarks\router.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_SHARED_STYLE_HTML" file="resources\bookmarks\shared_style.html" preprocess="true" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_SHARED_VARS_HTML" file="resources\bookmarks\shared_vars.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_STORE_CLIENT_HTML" file="resources\bookmarks\store_client.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_STORE_CLIENT_JS" file="resources\bookmarks\store_client.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_STORE_HTML" file="resources\bookmarks\store.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_STORE_JS" file="resources\bookmarks\store.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_STRINGS_HTML" file="resources\bookmarks\strings.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_TOOLBAR_HTML" file="resources\bookmarks\toolbar.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_TOOLBAR_JS" file="resources\bookmarks\toolbar.js" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_UTIL_HTML" file="resources\bookmarks\util.html" type="chrome_html" />
+ <structure name="IDR_BOOKMARKS_UTIL_JS" file="resources\bookmarks\util.js" type="chrome_html" />
+ </else>
+ </if>
</if>
<if expr="chromeos">
+ <structure name="IDR_FIRST_RUN_HTML" file="resources\chromeos\first_run\first_run.html" flattenhtml="true" type="chrome_html"/>
+ <structure name="IDR_FIRST_RUN_JS" file="resources\chromeos\first_run\first_run.js" flattenhtml="true" type="chrome_html" />
+ <structure name="IDR_MD_LOGIN_HTML" file="resources\chromeos\login\md_login.html" flattenhtml="true" type="chrome_html" variables="OOBE=md_login" expand_variables="true"/>
+ <structure name="IDR_MD_LOGIN_JS" file="resources\chromeos\login\md_login.js" flattenhtml="true" type="chrome_html" />
<structure name="IDR_OOBE_HTML" file="resources\chromeos\login\oobe.html" flattenhtml="true" type="chrome_html" variables="OOBE=oobe" expand_variables="true"/>
<structure name="IDR_OOBE_JS" file="resources\chromeos\login\oobe.js" flattenhtml="true" type="chrome_html" />
<structure name="IDR_KEYBOARD_UTILS_JS" file="resources\chromeos\keyboard\keyboard_utils.js" flattenhtml="true" type="chrome_html" />
@@ -39,23 +85,6 @@
<structure name="IDR_ASSISTANT_OPTIN_HTML" file="resources\chromeos\assistant_optin\assistant_optin.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
<structure name="IDR_ASSISTANT_OPTIN_JS" file="resources\chromeos\assistant_optin\assistant_optin.js" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
</if>
- <structure name="IDR_SIGNIN_SHARED_CSS_HTML" file="resources\signin\signin_shared_css.html" preprocess="true" allowexternalscript="true" type="chrome_html" />
- <if expr="not is_android and not chromeos">
- <structure name="IDR_WELCOME_CSS" file="resources\welcome\welcome.css" type="chrome_html" preprocess="true"/>
- <structure name="IDR_WELCOME_HTML" file="resources\welcome\welcome.html" type="chrome_html" preprocess="true"/>
- <structure name="IDR_WELCOME_JS" file="resources\welcome\welcome.js" type="chrome_html" preprocess="true"/>
- <structure name="IDR_DICE_WELCOME_CSS" file="resources\welcome\dice_welcome\welcome.css" type="chrome_html" preprocess="true"/>
- <structure name="IDR_DICE_WELCOME_HTML" file="resources\welcome\dice_welcome\welcome.html" type="chrome_html" preprocess="true"/>
- <structure name="IDR_DICE_WELCOME_BROWSER_PROXY_HTML" file="resources\welcome\dice_welcome\welcome_browser_proxy.html" type="chrome_html" preprocess="true"/>
- <structure name="IDR_DICE_WELCOME_BROWSER_PROXY_JS" file="resources\welcome\dice_welcome\welcome_browser_proxy.js" type="chrome_html" preprocess="true"/>
- <structure name="IDR_DICE_WELCOME_APP_HTML" file="resources\welcome\dice_welcome\welcome_app.html" type="chrome_html" preprocess="true"/>
- <structure name="IDR_DICE_WELCOME_APP_JS" file="resources\welcome\dice_welcome\welcome_app.js" type="chrome_html" preprocess="true"/>
- </if>
- <if expr="is_win">
- <structure name="IDR_WELCOME_WIN10_CSS" file="resources\welcome\welcome_win10.css" type="chrome_html" />
- <structure name="IDR_WELCOME_WIN10_HTML" file="resources\welcome\welcome_win10.html" type="chrome_html" />
- <structure name="IDR_WELCOME_WIN10_JS" file="resources\welcome\welcome_win10.js" type="chrome_html" />
- </if>
</structures>
<includes>
<if expr="is_win or is_macosx or desktop_linux or chromeos">
@@ -153,6 +182,10 @@
<include name="IDR_DOWNLOAD_INTERNALS_JS" file="resources\download_internals\download_internals.js" type="BINDATA" compress="gzip" />
<include name="IDR_DOWNLOAD_INTERNALS_BROWSER_PROXY_JS" file="resources\download_internals\download_internals_browser_proxy.js" type="BINDATA" compress="gzip" />
<include name="IDR_DOWNLOAD_INTERNALS_VISUALS_JS" file="resources\download_internals\download_internals_visuals.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_NOTIFICATIONS_INTERNALS_HTML" file="resources\notifications_internals\notifications_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
+ <include name="IDR_NOTIFICATIONS_INTERNALS_CSS" file="resources\notifications_internals\notifications_internals.css" type="BINDATA" compress="gzip" />
+ <include name="IDR_NOTIFICATIONS_INTERNALS_JS" file="resources\notifications_internals\notifications_internals.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_NOTIFICATIONS_INTERNALS_BROWSER_PROXY_JS" file="resources\notifications_internals\notifications_internals_browser_proxy.js" type="BINDATA" compress="gzip" />
<include name="IDR_UKM_INTERNALS_HTML" file="../../components/ukm/debug/ukm_internals.html" flattenhtml="true" allowexternalscript="true" compress="gzip" type="BINDATA" />
<include name="IDR_UKM_INTERNALS_JS" file="../../components/ukm/debug/ukm_internals.js" flattenhtml="true" compress="gzip" type="BINDATA" />
<include name="IDR_UKM_INTERNALS_CSS" file="../../components/ukm/debug/ukm_internals.css" flattenhtml="true" compress="gzip" type="BINDATA" />
@@ -185,15 +218,6 @@
<include name="IDR_HANGOUT_SERVICES_MANIFEST" file="resources\hangout_services\manifest.json" type="BINDATA" />
</if>
- <!-- Chrome OS Supervised users. -->
- <if expr="chromeos">
- <include name="IDR_SUPERVISION_ONBOARDING_CONTROLLER_MOJOM_LITE_JS"
- file="${root_gen_dir}/chrome/browser/chromeos/supervision/mojom/onboarding_controller.mojom-lite.js"
- use_base_dir="false"
- type="BINDATA"
- compress="gzip" />
- </if>
-
<!-- App Management. -->
<if expr="not is_android">
<include name="IDR_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS" file="${root_gen_dir}\skia\public\interfaces\bitmap.mojom-lite.js" use_base_dir="false" type="BINDATA" />
@@ -218,11 +242,12 @@
<include name="IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_JS" file="resources\app_management\chrome_app_permission_view.js" type="BINDATA"/>
<include name="IDR_APP_MANAGEMENT_CONSTANTS_HTML" file="resources\app_management\constants.html" type="BINDATA"/>
<include name="IDR_APP_MANAGEMENT_CONSTANTS_JS" file="resources\app_management\constants.js" type="BINDATA"/>
- <include name="IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_HTML" file="resources\app_management\expandable_app_list.html" type="BINDATA"/>
- <include name="IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_JS" file="resources\app_management\expandable_app_list.js" type="BINDATA"/>
<include name="IDR_APP_MANAGEMENT_DOM_SWITCH_HTML" file="resources\app_management\dom_switch.html" type="BINDATA"/>
<include name="IDR_APP_MANAGEMENT_DOM_SWITCH_JS" file="resources\app_management\dom_switch.js" type="BINDATA"/>
+ <include name="IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_HTML" file="resources\app_management\expandable_app_list.html" type="BINDATA"/>
+ <include name="IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_JS" file="resources\app_management\expandable_app_list.js" type="BINDATA"/>
<include name="IDR_APP_MANAGEMENT_FAKE_PAGE_HANDLER_JS" file="resources\app_management\fake_page_handler.js" type="BINDATA" />
+ <include name="IDR_APP_MANAGEMENT_ICONS_HTML" file="resources\app_management\icons.html" type="BINDATA" />
<include name="IDR_APP_MANAGEMENT_INDEX_HTML" file="resources\app_management\index.html" type="BINDATA" />
<include name="IDR_APP_MANAGEMENT_MAIN_VIEW_HTML" file="resources\app_management\main_view.html" type="BINDATA" />
<include name="IDR_APP_MANAGEMENT_MAIN_VIEW_JS" file="resources\app_management\main_view.js" type="BINDATA" />
@@ -236,6 +261,8 @@
<include name="IDR_APP_MANAGEMENT_PERMISSION_TOGGLE_JS" file="resources\app_management\permission_toggle.js" type="BINDATA"/>
<include name="IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_HTML" file="resources\app_management\permission_view_header.html" type="BINDATA"/>
<include name="IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_JS" file="resources\app_management\permission_view_header.js" type="BINDATA"/>
+ <include name="IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_HTML" file="resources\app_management\pin_to_shelf_item.html" type="BINDATA"/>
+ <include name="IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_JS" file="resources\app_management\pin_to_shelf_item.js" type="BINDATA"/>
<include name="IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_HTML" file="resources\app_management\pwa_permission_view.html" type="BINDATA"/>
<include name="IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_JS" file="resources\app_management\pwa_permission_view.js" type="BINDATA"/>
<include name="IDR_APP_MANAGEMENT_REDUCERS_HTML" file="resources\app_management\reducers.html" type="BINDATA" />
@@ -250,67 +277,14 @@
<include name="IDR_APP_MANAGEMENT_STORE_CLIENT_JS" file="resources\app_management\store_client.js" type="BINDATA" />
<include name="IDR_APP_MANAGEMENT_STORE_HTML" file="resources\app_management\store.html" type="BINDATA" />
<include name="IDR_APP_MANAGEMENT_STORE_JS" file="resources\app_management\store.js" type="BINDATA" />
+ <include name="IDR_APP_MANAGEMENT_TOGGLE_ROW_HTML" file="resources\app_management\toggle_row.html" type="BINDATA"/>
+ <include name="IDR_APP_MANAGEMENT_TOGGLE_ROW_JS" file="resources\app_management\toggle_row.js" type="BINDATA"/>
<include name="IDR_APP_MANAGEMENT_TYPES_JS" file="resources\app_management\types.js" type="BINDATA" />
<include name="IDR_APP_MANAGEMENT_UTIL_HTML" file="resources\app_management\util.html" type="BINDATA" />
<include name="IDR_APP_MANAGEMENT_UTIL_JS" file="resources\app_management\util.js" type="BINDATA" />
</if>
<if expr="not is_android">
- <!-- Bookmarks WebUI. -->
- <include name="IDR_BOOKMARKS_IMAGES_FOLDER_OPEN_SVG" file="resources\bookmarks\images\folder_open.svg" type="BINDATA" />
- <include name="IDR_BOOKMARKS_IMAGES_FOLDER_SVG" file="resources\bookmarks\images\folder.svg" type="BINDATA" />
- <if expr="optimize_webui">
- <then>
- <include name="IDR_BOOKMARKS_VULCANIZED_HTML" file="${root_gen_dir}\chrome\browser\resources\bookmarks\vulcanized.html" use_base_dir="false" preprocess="true" type="BINDATA" compress="gzip" />
- <include name="IDR_BOOKMARKS_CRISPER_JS" file="${root_gen_dir}\chrome\browser\resources\bookmarks\crisper.js" use_base_dir="false" preprocess="true" type="BINDATA" compress="gzip" />
- </then>
- <else>
- <include name="IDR_BOOKMARKS_ACTIONS_HTML" file="resources\bookmarks\actions.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_ACTIONS_JS" file="resources\bookmarks\actions.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_API_LISTENER_HTML" file="resources\bookmarks\api_listener.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_API_LISTENER_JS" file="resources\bookmarks\api_listener.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_APP_HTML" file="resources\bookmarks\app.html" type="BINDATA" preprocess="true" />
- <include name="IDR_BOOKMARKS_APP_JS" file="resources\bookmarks\app.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_BOOKMARKS_HTML" file="resources\bookmarks\bookmarks.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_COMMAND_MANAGER_HTML" file="resources\bookmarks\command_manager.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_COMMAND_MANAGER_JS" file="resources\bookmarks\command_manager.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_CONSTANTS_HTML" file="resources\bookmarks\constants.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_CONSTANTS_JS" file="resources\bookmarks\constants.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_DEBOUNCER_HTML" file="resources\bookmarks\debouncer.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_DEBOUNCER_JS" file="resources\bookmarks\debouncer.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_DIALOG_FOCUS_MANAGER_HTML" file="resources\bookmarks\dialog_focus_manager.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_DIALOG_FOCUS_MANAGER_JS" file="resources\bookmarks\dialog_focus_manager.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_DND_MANAGER_HTML" file="resources\bookmarks\dnd_manager.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_DND_MANAGER_JS" file="resources\bookmarks\dnd_manager.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_EDIT_DIALOG_HTML" file="resources\bookmarks\edit_dialog.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_EDIT_DIALOG_JS" file="resources\bookmarks\edit_dialog.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_FOLDER_NODE_HTML" file="resources\bookmarks\folder_node.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_FOLDER_NODE_JS" file="resources\bookmarks\folder_node.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_ITEM_HTML" file="resources\bookmarks\item.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_ITEM_JS" file="resources\bookmarks\item.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_LIST_HTML" file="resources\bookmarks\list.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_LIST_JS" file="resources\bookmarks\list.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_MOUSE_FOCUS_BEHAVIOR_HTML" file="resources\bookmarks\mouse_focus_behavior.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_MOUSE_FOCUS_BEHAVIOR_JS" file="resources\bookmarks\mouse_focus_behavior.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_REDUCERS_HTML" file="resources\bookmarks\reducers.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_REDUCERS_JS" file="resources\bookmarks\reducers.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_ROUTER_HTML" file="resources\bookmarks\router.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_ROUTER_JS" file="resources\bookmarks\router.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_SHARED_STYLE_HTML" file="resources\bookmarks\shared_style.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_SHARED_VARS_HTML" file="resources\bookmarks\shared_vars.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_STORE_CLIENT_HTML" file="resources\bookmarks\store_client.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_STORE_CLIENT_JS" file="resources\bookmarks\store_client.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_STORE_HTML" file="resources\bookmarks\store.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_STORE_JS" file="resources\bookmarks\store.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_STRINGS_HTML" file="resources\bookmarks\strings.html" type="BINDATA" />
-
- <include name="IDR_BOOKMARKS_TOOLBAR_HTML" file="resources\bookmarks\toolbar.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_TOOLBAR_JS" file="resources\bookmarks\toolbar.js" type="BINDATA" />
- <include name="IDR_BOOKMARKS_UTIL_HTML" file="resources\bookmarks\util.html" type="BINDATA" />
- <include name="IDR_BOOKMARKS_UTIL_JS" file="resources\bookmarks\util.js" type="BINDATA" />
- </else>
- </if>
-
<!-- History. -->
<include name="IDR_HISTORY_CONSTANTS_HTML" file="resources\history\constants.html" type="BINDATA" />
<include name="IDR_HISTORY_CONSTANTS_JS" file="resources\history\constants.js" type="BINDATA" />
@@ -384,7 +358,6 @@
<include name="IDR_LOCAL_STATE_HTML" file="resources\local_state\local_state.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
<include name="IDR_LOCAL_STATE_JS" file="resources\local_state\local_state.js" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
<include name="IDR_DESKTOP_HATS_HTML" file="resources\hats\hats.html" type="BINDATA" />
- <include name="IDR_DESKTOP_HATS_JS" file="resources\hats\hats.js" type="BINDATA" />
<include name="IDR_OMNIBOX_HTML" file="resources\omnibox\omnibox.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
<include name="IDR_OMNIBOX_CSS" file="resources\omnibox\omnibox.css" type="BINDATA" compress="gzip" />
<include name="IDR_OMNIBOX_INPUT_CSS" file="resources\omnibox\omnibox_input.css" type="BINDATA" compress="gzip" />
@@ -431,14 +404,14 @@
<include name="IDR_SITE_ENGAGEMENT_JS" file="resources\engagement\site_engagement.js" flattenhtml="true" type="BINDATA" compress="gzip" />
<include name="IDR_SITE_ENGAGEMENT_DETAILS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\engagement\site_engagement_details.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
<include name="IDR_URL_MOJOM_LITE_JS" file="${root_gen_dir}\url\mojom\url.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
+ <include name="IDR_SYNC_DISABLED_CONFIRMATION_HTML" file="resources\signin\sync_confirmation\sync_disabled_confirmation.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_SYNC_DISABLED_CONFIRMATION_JS" file="resources\signin\sync_confirmation\sync_disabled_confirmation.js" type="BINDATA" />
<include name="IDR_SYNC_CONFIRMATION_HTML" file="resources\signin\sync_confirmation\sync_confirmation.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
<include name="IDR_SYNC_CONFIRMATION_JS" file="resources\signin\sync_confirmation\sync_confirmation.js" type="BINDATA" />
- <include name="IDR_DICE_SYNC_CONFIRMATION_HTML" file="resources\signin\dice_sync_confirmation\sync_confirmation.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
- <include name="IDR_DICE_SYNC_CONFIRMATION_JS" file="resources\signin\dice_sync_confirmation\sync_confirmation.js" type="BINDATA" />
- <include name="IDR_DICE_SYNC_CONFIRMATION_BROWSER_PROXY_HTML" file="resources\signin\dice_sync_confirmation\sync_confirmation_browser_proxy.html" type="BINDATA" />
- <include name="IDR_DICE_SYNC_CONFIRMATION_BROWSER_PROXY_JS" file="resources\signin\dice_sync_confirmation\sync_confirmation_browser_proxy.js" type="BINDATA" />
- <include name="IDR_DICE_SYNC_CONFIRMATION_APP_HTML" file="resources\signin\dice_sync_confirmation\sync_confirmation_app.html" type="BINDATA" flattenhtml="true" allowexternalscript="true" />
- <include name="IDR_DICE_SYNC_CONFIRMATION_APP_JS" file="resources\signin\dice_sync_confirmation\sync_confirmation_app.js" type="BINDATA" />
+ <include name="IDR_SYNC_CONFIRMATION_BROWSER_PROXY_HTML" file="resources\signin\sync_confirmation\sync_confirmation_browser_proxy.html" type="BINDATA" />
+ <include name="IDR_SYNC_CONFIRMATION_BROWSER_PROXY_JS" file="resources\signin\sync_confirmation\sync_confirmation_browser_proxy.js" type="BINDATA" />
+ <include name="IDR_SYNC_CONFIRMATION_APP_HTML" file="resources\signin\sync_confirmation\sync_confirmation_app.html" type="BINDATA" flattenhtml="true" allowexternalscript="true" />
+ <include name="IDR_SYNC_CONFIRMATION_APP_JS" file="resources\signin\sync_confirmation\sync_confirmation_app.js" type="BINDATA" />
<include name="IDR_SIGNIN_EMAIL_CONFIRMATION_HTML" file="resources\signin\signin_email_confirmation\signin_email_confirmation.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
<include name="IDR_SIGNIN_EMAIL_CONFIRMATION_JS" file="resources\signin\signin_email_confirmation\signin_email_confirmation.js" type="BINDATA" />
<include name="IDR_SIGNIN_ERROR_HTML" file="resources\signin\signin_error\signin_error.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
@@ -486,6 +459,10 @@
<include name="IDR_PASSWORD_CHANGE_JS" file="resources\chromeos\password_change\password_change.js" flattenhtml="true" type="BINDATA" />
<include name="IDR_PASSWORD_CHANGE_CSS" file="resources\chromeos\password_change\password_change.css" flattenhtml="true" type="BINDATA" />
<include name="IDR_PASSWORD_CHANGE_AUTHENTICATOR_JS" file="resources\gaia_auth_host\password_change_authenticator.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_CONFIRM_PASSWORD_CHANGE_HTML" file="resources\chromeos\password_change\confirm_password_change.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
+ <include name="IDR_CONFIRM_PASSWORD_CHANGE_JS" file="resources\chromeos\password_change\confirm_password_change.js" type="chrome_html" />
+ <include name="IDR_URGENT_PASSWORD_EXPIRY_NOTIFICATION_HTML" file="resources\chromeos\password_change\urgent_password_expiry_notification.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
+ <include name="IDR_URGENT_PASSWORD_EXPIRY_NOTIFICATION_JS" file="resources\chromeos\password_change\urgent_password_expiry_notification.js" type="chrome_html" />
<include name="IDR_CROSH_BUILTIN_MANIFEST" file="resources\chromeos\crosh_builtin\manifest.json" type="BINDATA" />
<include name="IDR_CRYPTOHOME_HTML" file="resources\chromeos\cryptohome.html" flattenhtml="true" type="BINDATA" />
@@ -532,16 +509,6 @@
<include name="IDR_QUICKOFFICE_MANIFEST" file="resources\chromeos\quickoffice\manifest.json" type="BINDATA" />
<include name="IDR_PRODUCT_CHROMEOS_SYNC_CONSENT_SCREEN_ICONS" file="internal\resources\chromeos-sync-consent-icons.html" type="BINDATA" />
</if>
- <if expr="_kiosk_next">
- <if expr="_google_chrome">
- <then>
- <include name="IDR_KIOSK_NEXT_HOME_MANIFEST" file="resources\chromeos\kiosk_next_home\internal\manifest.json" type="BINDATA" />
- </then>
- <else>
- <include name="IDR_KIOSK_NEXT_HOME_MANIFEST" file="resources\chromeos\kiosk_next_home\manifest.json" type="BINDATA" />
- </else>
- </if>
- </if>
<if expr="is_win">
<include name="IDR_SET_AS_DEFAULT_BROWSER_JS" file="resources\set_as_default_browser.js" flattenhtml="true" type="BINDATA" />
<include name="IDR_SET_AS_DEFAULT_BROWSER_HTML" file="resources\set_as_default_browser.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
@@ -649,7 +616,11 @@
</if>
<include name="IDR_BRAILLE_MANIFEST" file="resources\chromeos\braille_ime\manifest.json" type="BINDATA" />
</if>
- <part file="media_router_resources.grdp" />
+ <if expr="not is_android">
+ <include name="IDR_MEDIA_ROUTER_INTERNALS_HTML" file="resources\media_router\media_router_internals.html" type="BINDATA" />
+ <include name="IDR_MEDIA_ROUTER_INTERNALS_CSS" file="resources\media_router\media_router_internals.css" type="BINDATA" />
+ <include name="IDR_MEDIA_ROUTER_INTERNALS_JS" file="resources\media_router\media_router_internals.js" type="BINDATA" />
+ </if>
<if expr="chromeos or is_win or is_macosx">
<include name="IDR_CAST_HTML" file="resources\cast\cast.html" type="BINDATA" />
<include name="IDR_CAST_CSS" file="resources\cast\cast.css" type="BINDATA" />
@@ -661,10 +632,6 @@
<include name="IDR_IME_WINDOW_CLOSE_C" file="resources\input_ime\ime_window_close_click.png" type="BINDATA" />
<include name="IDR_IME_WINDOW_CLOSE_H" file="resources\input_ime\ime_window_close_hover.png" type="BINDATA" />
</if>
- <if expr="is_win">
- <include name="IDR_WELCOME_WIN10_DEFAULT_WEBP" file="resources\welcome\default.webp" type="BINDATA" />
- <include name="IDR_WELCOME_WIN10_PIN_WEBP" file="resources\welcome\pin.webp" type="BINDATA" />
- </if>
<include name="IDR_SSL_ERROR_ASSISTANT_PB" file="${root_gen_dir}/chrome/browser/resources/ssl/ssl_error_assistant/ssl_error_assistant.pb" use_base_dir="false" type="BINDATA" />
<if expr="is_android or is_linux">
<include name="IDR_SANDBOX_INTERNALS_HTML" file="resources\sandbox_internals\sandbox_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
@@ -692,7 +659,8 @@
<include name="IDR_SYS_INTERNALS_IMAGE_CPU_SVG" file="resources\chromeos\sys_internals\img\cpu.svg" type="BINDATA" />
<include name="IDR_SYS_INTERNALS_IMAGE_MEMORY_SVG" file="resources\chromeos\sys_internals\img\memory.svg" type="BINDATA" />
<include name="IDR_SYS_INTERNALS_IMAGE_ZRAM_SVG" file="resources\chromeos\sys_internals\img\zram.svg" type="BINDATA" />
- <include name="IDR_ADD_SUPERVISION_HTML" file="resources\chromeos\add_supervision\add_supervision.html" compress="gzip" type="BINDATA" />
+ <include name="IDR_ADD_SUPERVISION_HTML" file="resources\chromeos\add_supervision\add_supervision.html" compress="gzip" type="chrome_html" />
+ <include name="IDR_ADD_SUPERVISION_NETWORK_UNAVAILABLE_SVG" file="resources\chromeos\add_supervision\images\network_unavailable.svg" compress="gzip" type="BINDATA" />
<include name="IDR_ADD_SUPERVISION_JS" file="resources\chromeos\add_supervision\add_supervision.js" compress="gzip" type="BINDATA" />
<include name="IDR_ADD_SUPERVISION_API_SERVER_JS" file="resources\chromeos\add_supervision\add_supervision_api_server.js" compress="gzip" type="BINDATA" />
<include name="IDR_ADD_SUPERVISION_POST_MESSAGE_API_JS" file="resources\chromeos\add_supervision\post_message_api.js" compress="gzip" type="BINDATA" />
diff --git a/chromium/chrome/browser/browser_switcher/bho/BUILD.gn b/chromium/chrome/browser/browser_switcher/bho/BUILD.gn
index beeeaec81fc..f81f61e2282 100644
--- a/chromium/chrome/browser/browser_switcher/bho/BUILD.gn
+++ b/chromium/chrome/browser/browser_switcher/bho/BUILD.gn
@@ -2,11 +2,29 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+import("//build/config/compiler/compiler.gni")
import("//build/toolchain/win/midl.gni")
assert(is_win)
+assert(target_cpu == "x86" || target_cpu == "x64")
shared_library("browser_switcher_bho") {
+ if (current_cpu == "x64") {
+ # Name the 32-bit and 64-bit output differently, since they'll be copied to
+ # the same directory.
+ output_name = "browser_switcher_bho_64"
+ }
+
+ visibility = [
+ ":browser_switcher_dlls",
+ ":copy_browser_switcher_binaries",
+ ]
+
+ defines = [
+ # Needed to build COM objects that will be hosted in a DLL.
+ "_WINDLL",
+ ]
+
# TODO(nicolaso): Reduce binary size as much as possible.
#
# TODO(nicolaso): Use ie_bho.def and ie_bho.rc.
@@ -19,6 +37,9 @@ shared_library("browser_switcher_bho") {
"bho.h",
"browser_switcher_core.cc",
"browser_switcher_core.h",
+ "ie_bho.cc",
+ "ie_bho.def",
+ "ie_bho.h",
"logging.cc",
"logging.h",
"resource.h",
@@ -28,8 +49,62 @@ shared_library("browser_switcher_bho") {
]
}
+if (is_clang) {
+ browser_switcher_x64_toolchain = "//build/toolchain/win:win_clang_x64"
+ browser_switcher_x86_toolchain = "//build/toolchain/win:win_clang_x86"
+} else {
+ browser_switcher_x64_toolchain = "//build/toolchain/win:x64"
+ browser_switcher_x86_toolchain = "//build/toolchain/win:x86"
+}
+
+browser_switcher_x64_label =
+ ":browser_switcher_bho($browser_switcher_x64_toolchain)"
+browser_switcher_x86_label =
+ ":browser_switcher_bho($browser_switcher_x86_toolchain)"
+
+copy("copy_browser_switcher_binaries") {
+ # Make sure we have both bitnesses in the root out directory.
+ if (target_cpu == "x86") {
+ cross_build_label = browser_switcher_x64_label
+ cross_build_dll = "browser_switcher_bho_64.dll"
+ } else if (target_cpu == "x64") {
+ cross_build_label = browser_switcher_x86_label
+ cross_build_dll = "browser_switcher_bho.dll"
+ }
+
+ cross_build_out_dir = get_label_info(cross_build_label, "root_out_dir")
+
+ sources = [
+ "$cross_build_out_dir/$cross_build_dll",
+ ]
+ if (symbol_level > 0) {
+ sources += [ "$cross_build_out_dir/$cross_build_dll.pdb" ]
+ }
+
+ outputs = [
+ "$root_out_dir/{{source_file_part}}",
+ ]
+ deps = [
+ browser_switcher_x64_label,
+ browser_switcher_x86_label,
+ ]
+}
+
+group("browser_switcher_dlls") {
+ # Build a DLL for each bitness, and put them in the root out dir.
+ deps = [
+ ":copy_browser_switcher_binaries",
+ browser_switcher_x64_label,
+ browser_switcher_x86_label,
+ ]
+}
+
midl("ie_bho_idl") {
sources = [
"ie_bho_idl.idl",
]
+
+ # We have a custom output directory (that excludes the toolchain details).
+ generated_dir =
+ "//third_party/win_build_output/midl/chrome/browser/browser_switcher/bho"
}
diff --git a/chromium/chrome/browser/chrome_notification_types.h b/chromium/chrome/browser/chrome_notification_types.h
index ba9365391c4..e2df7f6556d 100644
--- a/chromium/chrome/browser/chrome_notification_types.h
+++ b/chromium/chrome/browser/chrome_notification_types.h
@@ -44,11 +44,6 @@ enum NotificationType {
// DEPRECATED: Use BrowserListObserver::OnBrowserAdded()
NOTIFICATION_BROWSER_OPENED = NOTIFICATION_CHROME_START,
- // This message is sent after a window has been closed. The source is a
- // Source<Browser> containing the affected Browser. No details are expected.
- // DEPRECATED: Use BrowserListObserver::OnBrowserRemoved()
- NOTIFICATION_BROWSER_CLOSED,
-
// This message is sent when closing a browser has been cancelled, either by
// the user cancelling a beforeunload dialog, or IsClosingPermitted()
// disallowing closing. This notification implies that no BROWSER_CLOSING or
@@ -72,10 +67,6 @@ enum NotificationType {
// Source<ThemeService>. There are no details.
NOTIFICATION_BROWSER_THEME_CHANGED,
- // Sent when the renderer returns focus to the browser, as part of focus
- // traversal. The source is the browser, there are no details.
- NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
-
// Application-wide ----------------------------------------------------------
// This message is sent when the application is terminating (the last
@@ -122,49 +113,7 @@ enum NotificationType {
// the WebContents containing the NavigationController is destroyed.
NOTIFICATION_TAB_CLOSING,
- // Stuff inside the tabs ---------------------------------------------------
-
- // This notification is sent when the result of a find-in-page search is
- // available with the browser process. The source is a Source<WebContents>.
- // Details encompass a FindNotificationDetail object that tells whether the
- // match was found or not found.
- NOTIFICATION_FIND_RESULT_AVAILABLE,
-
- // BackgroundContents ------------------------------------------------------
-
- // A new background contents was opened by script. The source is the parent
- // profile and the details are BackgroundContentsOpenedDetails.
- NOTIFICATION_BACKGROUND_CONTENTS_OPENED,
-
- // The background contents navigated to a new location. The source is the
- // parent Profile, and the details are the BackgroundContents that was
- // navigated.
- NOTIFICATION_BACKGROUND_CONTENTS_NAVIGATED,
-
- // The background contents were closed by someone invoking window.close()
- // or the parent application was uninstalled.
- // The source is the parent profile, and the details are the
- // BackgroundContents.
- NOTIFICATION_BACKGROUND_CONTENTS_CLOSED,
-
- // The background contents is being deleted. The source is the
- // parent Profile, and the details are the BackgroundContents being deleted.
- NOTIFICATION_BACKGROUND_CONTENTS_DELETED,
-
- // The background contents has crashed. The source is the parent Profile,
- // and the details are the BackgroundContents.
- NOTIFICATION_BACKGROUND_CONTENTS_TERMINATED,
-
- // The background contents associated with a hosted app has changed (either
- // a new background contents has been created, or an existing background
- // contents has closed). The source is the parent Profile, and the details
- // are the BackgroundContentsService.
- NOTIFICATION_BACKGROUND_CONTENTS_SERVICE_CHANGED,
-
- // Chrome has entered/exited background mode. The source is the
- // BackgroundModeManager and the details are a boolean value which is set to
- // true if Chrome is now in background mode.
- NOTIFICATION_BACKGROUND_MODE_CHANGED,
+ // Authentication ----------------------------------------------------------
// This is sent when a login prompt is shown. The source is the
// Source<NavigationController> for the tab in which the prompt is shown.
@@ -218,17 +167,6 @@ enum NotificationType {
// The details are none and the source is a Profile*.
NOTIFICATION_PROFILE_URL_REQUEST_CONTEXT_GETTER_INITIALIZED,
- // Non-history storage services --------------------------------------------
-
- // Autocomplete ------------------------------------------------------------
-
- // Sent by the autocomplete controller when done. The source is the
- // AutocompleteController, the details not used.
- NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY,
-
- // This is sent from Instant when the omnibox focus state changes.
- NOTIFICATION_OMNIBOX_FOCUS_CHANGED,
-
// Printing ----------------------------------------------------------------
// Notification from PrintJob that an event occurred. It can be that a page
@@ -240,24 +178,6 @@ enum NotificationType {
// Source is the WebContents that holds the print job.
NOTIFICATION_PRINT_JOB_RELEASED,
- // Content Settings --------------------------------------------------------
-
- // Sent when the collect cookies dialog is shown. The source is a
- // TabSpecificContentSettings object, there are no details.
- NOTIFICATION_COLLECTED_COOKIES_SHOWN,
-
- // Sent when content settings change for a tab. The source is a
- // content::WebContents object, the details are None.
- NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
-
- // Cookies -----------------------------------------------------------------
-
-#if BUILDFLAG(ENABLE_EXTENSIONS)
- // Sent when a cookie changes, for consumption by extensions. The source is a
- // Profile object, the details are a ChromeCookieDetails object.
- NOTIFICATION_COOKIE_CHANGED_FOR_EXTENSIONS,
-#endif
-
// Misc --------------------------------------------------------------------
#if defined(OS_CHROMEOS)
@@ -353,32 +273,6 @@ enum NotificationType {
// which was installed.
NOTIFICATION_APP_INSTALLED_TO_NTP,
-#if defined(OS_CHROMEOS)
- // Sent when wallpaper show animation has finished.
- NOTIFICATION_WALLPAPER_ANIMATION_FINISHED,
-#endif
-
- // Protocol Handler Registry -----------------------------------------------
- // Sent when a ProtocolHandlerRegistry is changed. The source is the profile.
- NOTIFICATION_PROTOCOL_HANDLER_REGISTRY_CHANGED,
-
- // Sent when the browser enters or exits fullscreen mode.
- NOTIFICATION_FULLSCREEN_CHANGED,
-
- // Sent when the FullscreenController changes, confirms, or denies mouse lock.
- // The source is the browser's FullscreenController, no details.
- NOTIFICATION_MOUSE_LOCK_CHANGED,
-
- // Sent by the PluginPrefs when there is a change of plugin enable/disable
- // status. The source is the profile.
- NOTIFICATION_PLUGIN_ENABLE_STATUS_CHANGED,
-
- // Sent when a global error has changed and the error UI should update it
- // self. The source is a Source<Profile> containing the profile for the
- // error. The detail is a GlobalError object that has changed or NULL if
- // all error UIs should update.
- NOTIFICATION_GLOBAL_ERRORS_CHANGED,
-
// Note:-
// Currently only Content and Chrome define and use notifications.
// Custom notifications not belonging to Content and Chrome should start
diff --git a/chromium/chrome/browser/chromeos/BUILD.gn b/chromium/chrome/browser/chromeos/BUILD.gn
index 99dd19f0a6c..c6e19a53f41 100644
--- a/chromium/chrome/browser/chromeos/BUILD.gn
+++ b/chromium/chrome/browser/chromeos/BUILD.gn
@@ -4,7 +4,6 @@
import("//build/config/features.gni")
import("//build/config/ui.gni")
-import("//chrome/browser/chromeos/kiosk_next_home/kiosk_next.gni")
import("//extensions/buildflags/buildflags.gni")
import("//media/media_options.gni")
import("//printing/buildflags/buildflags.gni")
@@ -37,6 +36,7 @@ source_set("chromeos") {
"//chromeos/dbus/power:power_manager_proto",
"//chromeos/strings",
"//components/policy/proto",
+ "//components/signin/core/browser",
"//content/app/resources",
"//ui/accessibility/mojom",
"//ui/chromeos/resources",
@@ -57,11 +57,10 @@ source_set("chromeos") {
"//ash/public/cpp",
"//ash/system/message_center/arc",
"//chrome/app:command_ids",
+ "//chrome/app/vector_icons",
"//chrome/browser/apps/platform_apps",
"//chrome/browser/apps/platform_apps/api",
- "//chrome/browser/chromeos/kiosk_next_home/mojom",
"//chrome/browser/chromeos/power/ml/smart_dim",
- "//chrome/browser/chromeos/supervision/mojom",
"//chrome/browser/devtools",
"//chrome/browser/extensions",
"//chrome/browser/resource_coordinator:tab_metrics_event_proto",
@@ -73,8 +72,8 @@ source_set("chromeos") {
"//chrome/common",
"//chrome/common/extensions/api",
"//chrome/services/app_service:lib",
- "//chrome/services/app_service/public/cpp:app_service_proxy",
"//chrome/services/app_service/public/cpp:app_update",
+ "//chrome/services/cups_proxy",
"//chrome/services/cups_proxy/public/mojom",
"//chrome/services/file_util/public/cpp",
"//chrome/services/wilco_dtc_supportd/public/mojom",
@@ -101,6 +100,7 @@ source_set("chromeos") {
"//chromeos/dbus/auth_policy:authpolicy_proto",
"//chromeos/dbus/biod",
"//chromeos/dbus/constants",
+ "//chromeos/dbus/cros_healthd",
"//chromeos/dbus/cryptohome",
"//chromeos/dbus/cryptohome:attestation_proto",
"//chromeos/dbus/cryptohome:cryptohome_proto",
@@ -124,7 +124,11 @@ source_set("chromeos") {
"//chromeos/login/login_state",
"//chromeos/login/session",
"//chromeos/network",
+ "//chromeos/services/assistant/public/cpp:prefs",
+ "//chromeos/services/cros_healthd/public/cpp",
+ "//chromeos/services/cros_healthd/public/mojom",
"//chromeos/services/device_sync/public/cpp",
+ "//chromeos/services/ime/public/mojom",
"//chromeos/services/machine_learning/public/cpp",
"//chromeos/services/machine_learning/public/mojom",
"//chromeos/services/multidevice_setup/public/cpp",
@@ -186,7 +190,8 @@ source_set("chromeos") {
"//components/safe_browsing:csd_proto",
"//components/safe_browsing/db:metadata_proto",
"//components/session_manager/core",
- "//components/signin/core/browser",
+ "//components/signin/public/identity_manager",
+ "//components/signin/public/webdata",
"//components/storage_monitor",
"//components/strings",
"//components/sync",
@@ -233,13 +238,12 @@ source_set("chromeos") {
"//services/device/public/cpp/usb",
"//services/device/public/mojom",
"//services/device/public/mojom:usb",
- "//services/identity/public/cpp",
+ "//services/identity/public/cpp:cpp_types",
"//services/identity/public/mojom",
"//services/metrics/public/cpp:ukm_builders",
"//services/preferences/public/mojom",
"//services/resource_coordinator/public/cpp:resource_coordinator_cpp",
"//services/service_manager/public/cpp",
- "//services/ws/public/cpp/input_devices",
"//skia",
"//storage/browser",
"//storage/common",
@@ -430,6 +434,8 @@ source_set("chromeos") {
"arc/app_shortcuts/arc_app_shortcuts_menu_builder.h",
"arc/app_shortcuts/arc_app_shortcuts_request.cc",
"arc/app_shortcuts/arc_app_shortcuts_request.h",
+ "arc/arc_app_id_provider_impl.cc",
+ "arc/arc_app_id_provider_impl.h",
"arc/arc_migration_constants.h",
"arc/arc_migration_guide_notification.cc",
"arc/arc_migration_guide_notification.h",
@@ -614,6 +620,8 @@ source_set("chromeos") {
"arc/tracing/arc_value_event_trimmer.h",
"arc/tts/arc_tts_service.cc",
"arc/tts/arc_tts_service.h",
+ "arc/usb/arc_usb_host_bridge_delegate.cc",
+ "arc/usb/arc_usb_host_bridge_delegate.h",
"arc/user_session/arc_user_session_service.cc",
"arc/user_session/arc_user_session_service.h",
"arc/video/gpu_arc_video_service_host.cc",
@@ -648,6 +656,8 @@ source_set("chromeos") {
"authpolicy/data_pipe_utils.h",
"authpolicy/kerberos_files_handler.cc",
"authpolicy/kerberos_files_handler.h",
+ "backdrop_wallpaper_handlers/backdrop_wallpaper_handlers.cc",
+ "backdrop_wallpaper_handlers/backdrop_wallpaper_handlers.h",
"base/file_flusher.cc",
"base/file_flusher.h",
"base/locale_util.cc",
@@ -734,10 +744,9 @@ source_set("chromeos") {
"crostini/crostini_remover.h",
"crostini/crostini_reporting_util.cc",
"crostini/crostini_reporting_util.h",
- "crostini/crostini_share_path.cc",
- "crostini/crostini_share_path.h",
- "crostini/crostini_share_path_factory.cc",
- "crostini/crostini_share_path_factory.h",
+ "crostini/crostini_simple_types.h",
+ "crostini/crostini_terminal.cc",
+ "crostini/crostini_terminal.h",
"crostini/crostini_util.cc",
"crostini/crostini_util.h",
"crostini/crosvm_metrics.cc",
@@ -762,6 +771,8 @@ source_set("chromeos") {
"dbus/chrome_features_service_provider.h",
"dbus/component_updater_service_provider.cc",
"dbus/component_updater_service_provider.h",
+ "dbus/cryptohome_key_delegate_service_provider.cc",
+ "dbus/cryptohome_key_delegate_service_provider.h",
"dbus/dbus_helper.cc",
"dbus/dbus_helper.h",
"dbus/drive_file_stream_service_provider.cc",
@@ -770,6 +781,8 @@ source_set("chromeos") {
"dbus/kiosk_info_service_provider.h",
"dbus/libvda_service_provider.cc",
"dbus/libvda_service_provider.h",
+ "dbus/machine_learning_decision_service_provider.cc",
+ "dbus/machine_learning_decision_service_provider.h",
"dbus/metrics_event_service_provider.cc",
"dbus/metrics_event_service_provider.h",
"dbus/plugin_vm_service_provider.cc",
@@ -784,10 +797,6 @@ source_set("chromeos") {
"dbus/vm_applications_service_provider.h",
"device_sync/device_sync_client_factory.cc",
"device_sync/device_sync_client_factory.h",
- "display/output_protection_controller_ash.cc",
- "display/output_protection_controller_ash.h",
- "display/output_protection_delegate.cc",
- "display/output_protection_delegate.h",
"display/quirks_manager_delegate_impl.cc",
"display/quirks_manager_delegate_impl.h",
"drive/debug_info_collector.cc",
@@ -1050,6 +1059,12 @@ source_set("chromeos") {
"first_run/steps/app_list_step.h",
"first_run/steps/tray_step.cc",
"first_run/steps/tray_step.h",
+ "guest_os/guest_os_pref_names.cc",
+ "guest_os/guest_os_pref_names.h",
+ "guest_os/guest_os_share_path.cc",
+ "guest_os/guest_os_share_path.h",
+ "guest_os/guest_os_share_path_factory.cc",
+ "guest_os/guest_os_share_path_factory.h",
"hats/hats_dialog.cc",
"hats/hats_dialog.h",
"hats/hats_finch_helper.cc",
@@ -1068,6 +1083,8 @@ source_set("chromeos") {
"input_method/candidate_window_controller_impl.h",
"input_method/component_extension_ime_manager_impl.cc",
"input_method/component_extension_ime_manager_impl.h",
+ "input_method/ime_service_connector.cc",
+ "input_method/ime_service_connector.h",
"input_method/input_method_configuration.cc",
"input_method/input_method_configuration.h",
"input_method/input_method_delegate_impl.cc",
@@ -1082,18 +1099,8 @@ source_set("chromeos") {
"input_method/input_method_syncer.h",
"kerberos/kerberos_credentials_manager.cc",
"kerberos/kerberos_credentials_manager.h",
- "kiosk_next_home/app_controller_service.cc",
- "kiosk_next_home/app_controller_service.h",
- "kiosk_next_home/app_controller_service_factory.cc",
- "kiosk_next_home/app_controller_service_factory.h",
- "kiosk_next_home/identity_controller_impl.cc",
- "kiosk_next_home/identity_controller_impl.h",
- "kiosk_next_home/intent_config_helper.cc",
- "kiosk_next_home/intent_config_helper.h",
- "kiosk_next_home/kiosk_next_home_interface_broker_impl.cc",
- "kiosk_next_home/kiosk_next_home_interface_broker_impl.h",
- "kiosk_next_home/metrics_helper.cc",
- "kiosk_next_home/metrics_helper.h",
+ "kerberos/kerberos_ticket_expiry_notification.cc",
+ "kerberos/kerberos_ticket_expiry_notification.h",
"language_preferences.cc",
"language_preferences.h",
"launcher_search_provider/error_reporter.cc",
@@ -1135,6 +1142,8 @@ source_set("chromeos") {
"login/auth/chrome_cryptohome_authenticator.h",
"login/auth/chrome_login_performer.cc",
"login/auth/chrome_login_performer.h",
+ "login/challenge_response_auth_keys_loader.cc",
+ "login/challenge_response_auth_keys_loader.h",
"login/chrome_restart_request.cc",
"login/chrome_restart_request.h",
"login/configuration_keys.cc",
@@ -1227,6 +1236,8 @@ source_set("chromeos") {
"login/lock_screen_utils.h",
"login/login_auth_recorder.cc",
"login/login_auth_recorder.h",
+ "login/login_client_cert_usage_observer.cc",
+ "login/login_client_cert_usage_observer.h",
"login/login_wizard.h",
"login/mojo_system_info_dispatcher.cc",
"login/mojo_system_info_dispatcher.h",
@@ -1254,12 +1265,14 @@ source_set("chromeos") {
"login/quick_unlock/quick_unlock_utils.h",
"login/reauth_stats.cc",
"login/reauth_stats.h",
+ "login/saml/in_session_password_change_manager.cc",
+ "login/saml/in_session_password_change_manager.h",
+ "login/saml/password_expiry_notification.cc",
+ "login/saml/password_expiry_notification.h",
"login/saml/saml_offline_signin_limiter.cc",
"login/saml/saml_offline_signin_limiter.h",
"login/saml/saml_offline_signin_limiter_factory.cc",
"login/saml/saml_offline_signin_limiter_factory.h",
- "login/saml/saml_password_expiry_notification.cc",
- "login/saml/saml_password_expiry_notification.h",
"login/saml/saml_profile_prefs.cc",
"login/saml/saml_profile_prefs.h",
"login/screen_manager.cc",
@@ -1317,8 +1330,6 @@ source_set("chromeos") {
"login/screens/recommend_apps_screen.h",
"login/screens/reset_screen.cc",
"login/screens/reset_screen.h",
- "login/screens/supervision_onboarding_screen.cc",
- "login/screens/supervision_onboarding_screen.h",
"login/screens/supervision_transition_screen.cc",
"login/screens/supervision_transition_screen.h",
"login/screens/sync_consent_screen.cc",
@@ -1599,8 +1610,6 @@ source_set("chromeos") {
"policy/device_local_account_policy_service.h",
"policy/device_local_account_policy_store.cc",
"policy/device_local_account_policy_store.h",
- "policy/device_native_printers_handler.cc",
- "policy/device_native_printers_handler.h",
"policy/device_network_configuration_updater.cc",
"policy/device_network_configuration_updater.h",
"policy/device_policy_cloud_external_data_manager.cc",
@@ -1608,12 +1617,10 @@ source_set("chromeos") {
"policy/device_policy_decoder_chromeos.cc",
"policy/device_policy_decoder_chromeos.h",
"policy/device_policy_remover.h",
- "policy/device_wallpaper_image_handler.cc",
- "policy/device_wallpaper_image_handler.h",
+ "policy/device_scheduled_update_checker.cc",
+ "policy/device_scheduled_update_checker.h",
"policy/device_wifi_allowed_handler.cc",
"policy/device_wifi_allowed_handler.h",
- "policy/device_wilco_dtc_configuration_handler.cc",
- "policy/device_wilco_dtc_configuration_handler.h",
"policy/display_resolution_handler.cc",
"policy/display_resolution_handler.h",
"policy/display_rotation_default_handler.cc",
@@ -1628,6 +1635,24 @@ source_set("chromeos") {
"policy/enrollment_handler_chromeos.h",
"policy/enrollment_status_chromeos.cc",
"policy/enrollment_status_chromeos.h",
+ "policy/external_data_handlers/cloud_external_data_policy_handler.cc",
+ "policy/external_data_handlers/cloud_external_data_policy_handler.h",
+ "policy/external_data_handlers/device_cloud_external_data_policy_handler.cc",
+ "policy/external_data_handlers/device_cloud_external_data_policy_handler.h",
+ "policy/external_data_handlers/device_native_printers_external_data_handler.cc",
+ "policy/external_data_handlers/device_native_printers_external_data_handler.h",
+ "policy/external_data_handlers/device_wallpaper_image_external_data_handler.cc",
+ "policy/external_data_handlers/device_wallpaper_image_external_data_handler.h",
+ "policy/external_data_handlers/device_wilco_dtc_configuration_external_data_handler.cc",
+ "policy/external_data_handlers/device_wilco_dtc_configuration_external_data_handler.h",
+ "policy/external_data_handlers/native_printers_external_data_handler.cc",
+ "policy/external_data_handlers/native_printers_external_data_handler.h",
+ "policy/external_data_handlers/print_servers_external_data_handler.cc",
+ "policy/external_data_handlers/print_servers_external_data_handler.h",
+ "policy/external_data_handlers/user_avatar_image_external_data_handler.cc",
+ "policy/external_data_handlers/user_avatar_image_external_data_handler.h",
+ "policy/external_data_handlers/wallpaper_image_external_data_handler.cc",
+ "policy/external_data_handlers/wallpaper_image_external_data_handler.h",
"policy/fake_auto_enrollment_client.cc",
"policy/fake_auto_enrollment_client.h",
"policy/heartbeat_scheduler.cc",
@@ -1648,6 +1673,8 @@ source_set("chromeos") {
"policy/off_hours/off_hours_policy_applier.h",
"policy/off_hours/off_hours_proto_parser.cc",
"policy/off_hours/off_hours_proto_parser.h",
+ "policy/os_and_policies_update_checker.cc",
+ "policy/os_and_policies_update_checker.h",
"policy/policy_cert_service.cc",
"policy/policy_cert_service.h",
"policy/policy_cert_service_factory.cc",
@@ -1682,6 +1709,8 @@ source_set("chromeos") {
"policy/remote_commands/user_command_arc_job.h",
"policy/remote_commands/user_commands_factory_chromeos.cc",
"policy/remote_commands/user_commands_factory_chromeos.h",
+ "policy/rsu/lookup_key_uploader.cc",
+ "policy/rsu/lookup_key_uploader.h",
"policy/secondary_google_account_signin_policy_handler.cc",
"policy/secondary_google_account_signin_policy_handler.h",
"policy/server_backed_device_state.cc",
@@ -1708,6 +1737,8 @@ source_set("chromeos") {
"policy/status_uploader.h",
"policy/system_log_uploader.cc",
"policy/system_log_uploader.h",
+ "policy/task_executor_with_retries.cc",
+ "policy/task_executor_with_retries.h",
"policy/tpm_auto_update_mode_policy_handler.cc",
"policy/tpm_auto_update_mode_policy_handler.h",
"policy/upload_job.h",
@@ -1832,8 +1863,12 @@ source_set("chromeos") {
"printing/cups_printers_manager.h",
"printing/cups_printers_manager_factory.cc",
"printing/cups_printers_manager_factory.h",
+ "printing/cups_proxy_service_delegate_impl.cc",
+ "printing/cups_proxy_service_delegate_impl.h",
"printing/cups_proxy_service_manager.cc",
"printing/cups_proxy_service_manager.h",
+ "printing/cups_proxy_service_manager_factory.cc",
+ "printing/cups_proxy_service_manager_factory.h",
"printing/enterprise_printers_provider.cc",
"printing/enterprise_printers_provider.h",
"printing/ppd_provider_factory.cc",
@@ -1842,6 +1877,12 @@ source_set("chromeos") {
"printing/ppd_resolution_state.h",
"printing/ppd_resolution_tracker.cc",
"printing/ppd_resolution_tracker.h",
+ "printing/print_server.cc",
+ "printing/print_server.h",
+ "printing/print_servers_provider.cc",
+ "printing/print_servers_provider.h",
+ "printing/print_servers_provider_factory.cc",
+ "printing/print_servers_provider_factory.h",
"printing/printer_configurer.cc",
"printing/printer_configurer.h",
"printing/printer_detector.h",
@@ -1877,6 +1918,10 @@ source_set("chromeos") {
"profiles/profile_helper.h",
"profiles/profile_util.cc",
"profiles/profile_util.h",
+ "release_notes/release_notes_notification.cc",
+ "release_notes/release_notes_notification.h",
+ "release_notes/release_notes_storage.cc",
+ "release_notes/release_notes_storage.h",
"reset/metrics.h",
"resource_reporter/resource_reporter.cc",
"resource_reporter/resource_reporter.h",
@@ -1894,8 +1939,6 @@ source_set("chromeos") {
"settings/device_identity_provider.h",
"settings/device_oauth2_token_service.cc",
"settings/device_oauth2_token_service.h",
- "settings/device_oauth2_token_service_delegate.cc",
- "settings/device_oauth2_token_service_delegate.h",
"settings/device_oauth2_token_service_factory.cc",
"settings/device_oauth2_token_service_factory.h",
"settings/device_settings_cache.cc",
@@ -1956,10 +1999,6 @@ source_set("chromeos") {
"smb_client/temp_file_manager.h",
"startup_settings_cache.cc",
"startup_settings_cache.h",
- "supervision/onboarding_constants.cc",
- "supervision/onboarding_constants.h",
- "supervision/onboarding_controller_impl.cc",
- "supervision/onboarding_controller_impl.h",
"system/automatic_reboot_manager.cc",
"system/automatic_reboot_manager.h",
"system/automatic_reboot_manager_observer.h",
@@ -2047,14 +2086,14 @@ source_set("chromeos") {
"wilco_dtc_supportd/wilco_dtc_supportd_manager.h",
"wilco_dtc_supportd/wilco_dtc_supportd_messaging.cc",
"wilco_dtc_supportd/wilco_dtc_supportd_messaging.h",
+ "wilco_dtc_supportd/wilco_dtc_supportd_notification_controller.cc",
+ "wilco_dtc_supportd/wilco_dtc_supportd_notification_controller.h",
"wilco_dtc_supportd/wilco_dtc_supportd_web_request_service.cc",
"wilco_dtc_supportd/wilco_dtc_supportd_web_request_service.h",
# Extension API implementations.
"extensions/autotest_private/autotest_private_api.cc",
"extensions/autotest_private/autotest_private_api.h",
- "extensions/backdrop_wallpaper_handlers/backdrop_wallpaper_handlers.cc",
- "extensions/backdrop_wallpaper_handlers/backdrop_wallpaper_handlers.h",
"extensions/echo_private_api.cc",
"extensions/echo_private_api.h",
"extensions/file_manager/device_event_router.cc",
@@ -2090,16 +2129,20 @@ source_set("chromeos") {
"extensions/file_manager/private_api_tasks.h",
"extensions/file_manager/private_api_util.cc",
"extensions/file_manager/private_api_util.h",
+ "extensions/file_manager/select_file_dialog_extension_user_data.cc",
+ "extensions/file_manager/select_file_dialog_extension_user_data.h",
"extensions/file_system_provider/file_system_provider_api.cc",
"extensions/file_system_provider/file_system_provider_api.h",
"extensions/file_system_provider/provider_function.cc",
"extensions/file_system_provider/provider_function.h",
"extensions/input_method_api.cc",
"extensions/input_method_api.h",
- "extensions/login_screen_ui/login_screen_extension_ui_handler.cc",
- "extensions/login_screen_ui/login_screen_extension_ui_handler.h",
- "extensions/login_screen_ui/login_screen_ui_api.cc",
- "extensions/login_screen_ui/login_screen_ui_api.h",
+ "extensions/login_screen/login/login_api.cc",
+ "extensions/login_screen/login/login_api.h",
+ "extensions/login_screen/login_screen_ui/login_screen_extension_ui_handler.cc",
+ "extensions/login_screen/login_screen_ui/login_screen_extension_ui_handler.h",
+ "extensions/login_screen/login_screen_ui/login_screen_ui_api.cc",
+ "extensions/login_screen/login_screen_ui/login_screen_ui_api.h",
"extensions/media_player_api.cc",
"extensions/media_player_api.h",
"extensions/quick_unlock_private/quick_unlock_private_api.cc",
@@ -2135,13 +2178,6 @@ source_set("chromeos") {
if (use_cras) {
defines += [ "USE_CRAS" ]
}
- if (enable_kiosk_next) {
- defines += [ "KIOSK_NEXT" ]
- if (is_chrome_branded) {
- public_deps +=
- [ "//chrome/browser/resources:kiosk_next_internal_resources" ]
- }
- }
}
copy("dbus_service_files") {
@@ -2152,6 +2188,7 @@ copy("dbus_service_files") {
"dbus/org.chromium.DriveFileStreamService.conf",
"dbus/org.chromium.KioskAppService.conf",
"dbus/org.chromium.LibvdaService.conf",
+ "dbus/org.chromium.MachineLearningDecisionService.conf",
"dbus/org.chromium.MetricsEventService.conf",
"dbus/org.chromium.NetworkProxyService.conf",
"dbus/org.chromium.PluginVmService.conf",
@@ -2182,8 +2219,6 @@ static_library("test_support") {
testonly = true
sources = [
- "accessibility/test_accessibility_focus_ring_controller.cc",
- "accessibility/test_accessibility_focus_ring_controller.h",
"android_sms/fake_android_sms_app_manager.cc",
"android_sms/fake_android_sms_app_manager.h",
"android_sms/fake_android_sms_app_setup_controller.cc",
@@ -2196,6 +2231,8 @@ static_library("test_support") {
"attestation/mock_enrollment_certificate_uploader.h",
"attestation/mock_machine_certificate_uploader.cc",
"attestation/mock_machine_certificate_uploader.h",
+ "certificate_provider/test_certificate_provider_extension.cc",
+ "certificate_provider/test_certificate_provider_extension.h",
"crostini/crostini_test_helper.cc",
"crostini/crostini_test_helper.h",
"drive/drivefs_test_support.cc",
@@ -2338,7 +2375,6 @@ source_set("unit_tests") {
"arc/tracing/arc_tracing_model_unittest.cc",
"arc/tracing/arc_value_event_unittest.cc",
"arc/tts/arc_tts_service_unittest.cc",
- "arc/voice_interaction/fake_voice_interaction_controller.cc",
"arc/voice_interaction/voice_interaction_controller_client_unittest.cc",
"arc/wallpaper/arc_wallpaper_service_unittest.cc",
"assistant/assistant_util_unittest.cc",
@@ -2366,10 +2402,10 @@ source_set("unit_tests") {
"crostini/crostini_export_import_unittest.cc",
"crostini/crostini_manager_unittest.cc",
"crostini/crostini_mime_types_service_unittest.cc",
+ "crostini/crostini_package_notification_unittest.cc",
"crostini/crostini_package_service_unittest.cc",
"crostini/crostini_registry_service_unittest.cc",
"crostini/crostini_reporting_util_unittest.cc",
- "crostini/crostini_share_path_unittest.cc",
"crostini/crosvm_metrics_unittest.cc",
"crostini/crosvm_process_list_unittest.cc",
"cryptauth/client_app_metadata_provider_service_unittest.cc",
@@ -2395,7 +2431,8 @@ source_set("unit_tests") {
"extensions/file_manager/job_event_router_unittest.cc",
"extensions/gfx_utils_unittest.cc",
"extensions/install_limiter_unittest.cc",
- "extensions/login_screen_ui/login_screen_extension_ui_handler_unittest.cc",
+ "extensions/login_screen/login/login_api_unittest.cc",
+ "extensions/login_screen/login_screen_ui/login_screen_extension_ui_handler_unittest.cc",
"extensions/permissions_updater_delegate_chromeos_unittest.cc",
"extensions/public_session_permission_helper_unittest.cc",
"extensions/quick_unlock_private/quick_unlock_private_api_unittest.cc",
@@ -2461,6 +2498,7 @@ source_set("unit_tests") {
"fileapi/recent_disk_source_unittest.cc",
"fileapi/recent_model_unittest.cc",
"fileapi/test/fake_recent_source.cc",
+ "guest_os/guest_os_share_path_unittest.cc",
"hats/hats_finch_helper_unittest.cc",
"hats/hats_notification_controller_unittest.cc",
"input_method/browser_state_monitor_unittest.cc",
@@ -2468,9 +2506,7 @@ source_set("unit_tests") {
"input_method/input_method_engine_unittest.cc",
"input_method/input_method_manager_impl_unittest.cc",
"input_method/input_method_persistence_unittest.cc",
- "kiosk_next_home/app_controller_service_unittest.cc",
- "kiosk_next_home/identity_controller_impl_unittest.cc",
- "kiosk_next_home/intent_config_helper_unittest.cc",
+ "kerberos/kerberos_ticket_expiry_notification_test.cc",
"locale_change_guard_unittest.cc",
"lock_screen_apps/app_manager_impl_unittest.cc",
"lock_screen_apps/lock_screen_profile_creator_impl_unittest.cc",
@@ -2496,12 +2532,14 @@ source_set("unit_tests") {
"login/quick_unlock/fingerprint_storage_unittest.cc",
"login/quick_unlock/pin_storage_prefs_unittest.cc",
"login/quick_unlock/quick_unlock_storage_unittest.cc",
+ "login/saml/in_session_password_change_manager_unittest.cc",
+ "login/saml/password_expiry_notification_unittest.cc",
"login/saml/saml_offline_signin_limiter_unittest.cc",
- "login/saml/saml_password_expiry_notification_unittest.cc",
"login/screens/multidevice_setup_screen_unittest.cc",
"login/screens/network_screen_unittest.cc",
"login/screens/recommend_apps/recommend_apps_fetcher_impl_unittest.cc",
"login/screens/update_screen_unittest.cc",
+ "login/session/user_session_manager_test.cc",
"login/signin_partition_manager_unittest.cc",
"login/supervised/supervised_user_authentication_unittest.cc",
"login/ui/login_screen_extension_ui/login_screen_extension_ui_dialog_delegate_unittest.cc",
@@ -2549,10 +2587,11 @@ source_set("unit_tests") {
"policy/device_cloud_policy_manager_chromeos_unittest.cc",
"policy/device_cloud_policy_store_chromeos_unittest.cc",
"policy/device_local_account_policy_service_unittest.cc",
- "policy/device_native_printers_handler_unittest.cc",
"policy/device_policy_decoder_chromeos_unittest.cc",
+ "policy/device_scheduled_update_checker_unittest.cc",
"policy/dm_token_storage_unittest.cc",
"policy/extension_cache_unittest.cc",
+ "policy/external_data_handlers/device_native_printers_external_data_handler_unittest.cc",
"policy/fake_affiliated_invalidation_service_provider.cc",
"policy/fake_affiliated_invalidation_service_provider.h",
"policy/heartbeat_scheduler_unittest.cc",
@@ -2568,6 +2607,7 @@ source_set("unit_tests") {
"policy/remote_commands/device_command_start_crd_session_unittest.cc",
"policy/remote_commands/device_command_wipe_users_job_unittest.cc",
"policy/remote_commands/user_command_arc_job_unittest.cc",
+ "policy/rsu/lookup_key_uploader_unittest.cc",
"policy/secondary_google_account_signin_policy_handler_unittest.cc",
"policy/server_backed_state_keys_broker_unittest.cc",
"policy/single_app_install_event_log_unittest.cc",
@@ -2610,6 +2650,7 @@ source_set("unit_tests") {
"printing/cups_printers_manager_unittest.cc",
"printing/ppd_resolution_state_unittest.cc",
"printing/ppd_resolution_tracker_unittest.cc",
+ "printing/print_servers_provider_unittest.cc",
"printing/printer_detector_test_util.h",
"printing/printer_event_tracker_unittest.cc",
"printing/printers_map_unittest.cc",
@@ -2619,6 +2660,8 @@ source_set("unit_tests") {
"printing/usb_printer_detector_unittest.cc",
"printing/zeroconf_printer_detector_unittest.cc",
"proxy_config_service_impl_unittest.cc",
+ "release_notes/release_notes_notification_unittest.cc",
+ "release_notes/release_notes_storage_unittest.cc",
"resource_reporter/resource_reporter_unittest.cc",
"scheduler_configuration_manager_unittest.cc",
"session_length_limiter_unittest.cc",
@@ -2646,7 +2689,6 @@ source_set("unit_tests") {
"smb_client/smb_url_unittest.cc",
"smb_client/temp_file_manager_unittest.cc",
"startup_settings_cache_unittest.cc",
- "supervision/onboarding_controller_impl_unittest.cc",
"system/automatic_reboot_manager_unittest.cc",
"system/device_disabling_manager_unittest.cc",
"system/procfs_util_unittest.cc",
@@ -2664,6 +2706,7 @@ source_set("unit_tests") {
"wilco_dtc_supportd/wilco_dtc_supportd_bridge_unittest.cc",
"wilco_dtc_supportd/wilco_dtc_supportd_manager_unittest.cc",
"wilco_dtc_supportd/wilco_dtc_supportd_messaging_unittest.cc",
+ "wilco_dtc_supportd/wilco_dtc_supportd_notification_controller_unittest.cc",
"wilco_dtc_supportd/wilco_dtc_supportd_web_request_service_unittest.cc",
# TODO(zturner): Enable this on Windows. See
@@ -2745,7 +2788,6 @@ source_set("unit_tests") {
"//chrome/browser/ui",
"//chrome/browser/ui:ash_test_support",
"//chrome/browser/web_applications/components",
- "//chrome/browser/web_applications/components:test_support",
"//chrome/common",
"//chrome/services/wilco_dtc_supportd/public/mojom",
"//chrome/test:test_support",
@@ -2810,6 +2852,7 @@ source_set("unit_tests") {
"//components/renderer_context_menu",
"//components/resources",
"//components/session_manager/core",
+ "//components/signin/public/identity_manager:test_support",
"//components/sync",
"//components/sync_preferences",
"//components/user_prefs",
@@ -2823,9 +2866,7 @@ source_set("unit_tests") {
"//mojo/public/cpp/system:system",
"//services/data_decoder/public/cpp:test_support",
"//services/device/public/cpp:test_support",
- "//services/identity/public/cpp:test_support",
"//services/service_manager/public/cpp/test:test_support",
- "//services/ws/public/cpp/input_devices:test_support",
"//skia",
"//storage/browser:test_support",
"//testing/gmock",
@@ -2839,6 +2880,7 @@ source_set("unit_tests") {
"//ui/base/ime/init",
"//ui/chromeos/resources",
"//ui/display:test_support",
+ "//ui/events/devices:test_support",
"//ui/shell_dialogs",
]
data = [
@@ -2866,7 +2908,7 @@ proto_library("user_activity_event_proto") {
proto_library("backdrop_wallpaper_proto") {
sources = [
- "extensions/backdrop_wallpaper_handlers/backdrop_wallpaper.proto",
+ "backdrop_wallpaper_handlers/backdrop_wallpaper.proto",
]
generate_python = false
}
diff --git a/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/BUILD.gn b/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/BUILD.gn
deleted file mode 100644
index 171e014fdd1..00000000000
--- a/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/BUILD.gn
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright 2019 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import("//mojo/public/tools/bindings/mojom.gni")
-
-mojom("mojom") {
- sources = [
- "app_controller.mojom",
- "identity_controller.mojom",
- "kiosk_next_home_interface_broker.mojom",
- ]
-
- public_deps = [
- "//chrome/services/app_service/public/mojom:types",
- "//services/identity/public/mojom",
- ]
-}
diff --git a/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/app_controller.mojom b/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/app_controller.mojom
deleted file mode 100644
index bdd17b8f024..00000000000
--- a/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/app_controller.mojom
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-module chromeos.kiosk_next_home.mojom;
-
-import "chrome/services/app_service/public/mojom/types.mojom";
-
-// Represents an app on Chrome OS. This struct has all the information
-// necessary to display the app in the Kiosk Next Home app list/grid, including
-// readiness, thumbnail image, display name, etc.
-struct App {
- // Stable and unique identifier for this app.
- string app_id;
-
- // The type of this app (e.g. ARC, Crostini, extension, etc).
- apps.mojom.AppType type;
-
- // Name used when displaying the app in an app list or grid.
- string display_name;
-
- // Android package name for this app.
- // This field will only be present if this is an ARC app.
- string android_package_name;
-
- // The current state of readiness for this app.
- // It can tell if the app is suspended, uninstalled, etc.
- apps.mojom.Readiness readiness;
-};
-
-// Interface used by AppController clients to receive app related events.
-interface AppControllerClient {
- // Called when any field from the given app changes.
- OnAppChanged(App app);
-};
-
-// Interface for managing Chrome OS apps from the Kiosk Next Home.
-interface AppController {
- // Returns all the local apps installed on this Chrome OS device.
- // It reads from all the app sources, including ARC++ (Android),
- // Crostini (Linux), extensions and PWAs.
- // Note that as soon as this method returns, some of the apps might have
- // changed. To always get the most updated information, attach an app
- // observer through the AddObserver method.
- GetApps() => (array<App> apps);
-
- // Sets the client that will be notified when an app changes.
- SetClient(AppControllerClient client);
-
- // Launches the app with the given app_id.
- LaunchApp(string app_id);
-
- // Shows a prompt to uninstall the app with the given app_id.
- UninstallApp(string app_id);
-
- // Gets the Android ID for the ARC container.
- GetArcAndroidId() => (bool success, string android_id);
-
- // Launches allowed ARC intents.
- // Intents are checked via chromeos::kiosk_next_home::IntentConfigHelper.
- LaunchIntent(string intent) => (bool launched, string? error_message);
-};
diff --git a/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/identity_controller.mojom b/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/identity_controller.mojom
deleted file mode 100644
index 251b52093dc..00000000000
--- a/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/identity_controller.mojom
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-module chromeos.kiosk_next_home.mojom;
-
-struct UserInfo {
- string given_name;
- string display_name;
-};
-
-// Exposes identity-related capabilities to Kiosk Next Home.
-interface IdentityController {
- GetUserInfo() => (UserInfo user_info);
-};
diff --git a/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/kiosk_next_home_interface_broker.mojom b/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/kiosk_next_home_interface_broker.mojom
deleted file mode 100644
index f86e53b2a76..00000000000
--- a/chromium/chrome/browser/chromeos/kiosk_next_home/mojom/kiosk_next_home_interface_broker.mojom
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-module chromeos.kiosk_next_home.mojom;
-
-import "chrome/browser/chromeos/kiosk_next_home/mojom/app_controller.mojom";
-import "chrome/browser/chromeos/kiosk_next_home/mojom/identity_controller.mojom";
-import "services/identity/public/mojom/identity_accessor.mojom";
-
-// Single entry point for any interface requests issued by the Kiosk Next
-// Home app and brokered by the browser for services needed to support
-// its functionality.
-interface KioskNextHomeInterfaceBroker {
- // Binds IdentityAccessor service request.
- // TODO(brunoad): migrate needed methods to IdentityController and remove.
- GetIdentityAccessor(identity.mojom.IdentityAccessor& request);
-
- // Binds the IdentityController service request.
- GetIdentityController(IdentityController& request);
-
- // Binds the AppController service request.
- GetAppController(AppController& request);
-};
diff --git a/chromium/chrome/browser/chromeos/supervision/mojom/onboarding_controller.mojom b/chromium/chrome/browser/chromeos/supervision/mojom/onboarding_controller.mojom
deleted file mode 100644
index 7370e202457..00000000000
--- a/chromium/chrome/browser/chromeos/supervision/mojom/onboarding_controller.mojom
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-module chromeos.supervision.mojom;
-
-import "url/mojom/url.mojom";
-
-// Represents user actions that the OnboardingController can handle.
-enum OnboardingAction {
- // The user has expressed intent to skip the remaining screens of the flow.
- // When receiving this we will most likely perform cleanup functions and
- // order the WebviewHost to exit the flow.
- kSkipFlow,
-
- // The user wants to go back/forward in the flow.
- kShowNextPage,
- kShowPreviousPage,
-};
-
-struct OnboardingPage {
- // Url for the page that needs to be loaded by the webview host.
- url.mojom.Url url;
-
- // Only requests to URLs that pass this pattern should be authenticated
- // or have their custom headers extracted.
- // Documentation on how to write these patterns can be found in:
- // https://developer.chrome.com/extensions/match_patterns
- string url_filter_pattern;
-
- // Access token used to authenticate the flow page requests. Note that this
- // should only be used in requests to URLs that match |url_filter_pattern|.
- string access_token;
-
- // Some flow pages are expected to return a custom header in their HTTP
- // responses. If this field is set, we will extract the given header from
- // responses and return its value when the page fully loads.
- // Note that this should only be used in requests to URLs that match
- // |url_filter_pattern|.
- string? custom_header_name;
-};
-
-// Represents a webview host, responsible for displaying supervision
-// onboarding pages. This will usually be a WebUI page that contains a
-// webview tag and manages its properties.
-// TODO(958995): Complete this interface.
-interface OnboardingWebviewHost {
- // Requests the host to load the given page.
- LoadPage(OnboardingPage page) => (string? custom_header_value);
-
- // Requests that the host exit the flow immediately. This might mean
- // different things depending on the type of host. If we are running in OOBE
- // we will exit the supervision screen and move to the next OOBE step, if we
- // are running in a custom WebUI, we should close it.
- ExitFlow();
-};
-
-// Interface responsible for managing the whole onboarding flow.
-// TODO(958995): Complete this interface.
-interface OnboardingController {
- // Binds the given webview host to this controller. The host will start
- // receiving commands as soon as this is called.
- BindWebviewHost(OnboardingWebviewHost webview_host);
-
- // Requests the controller to handle the given action.
- // The controller will decide the next step to continue/end the flow.
- HandleAction(OnboardingAction action);
-};
diff --git a/chromium/chrome/browser/custom_handlers/OWNERS b/chromium/chrome/browser/custom_handlers/OWNERS
index f4a612fe88c..a3b4a06d367 100644
--- a/chromium/chrome/browser/custom_handlers/OWNERS
+++ b/chromium/chrome/browser/custom_handlers/OWNERS
@@ -1,2 +1,5 @@
benwells@chromium.org
+dominickn@chromium.org
mgiuca@chromium.org
+raymes@chromium.org
+# COMPONENT: UI>Browser>WebAppInstalls
diff --git a/chromium/chrome/browser/custom_handlers/protocol_handler_registry.cc b/chromium/chrome/browser/custom_handlers/protocol_handler_registry.cc
index d3105875900..34273edb807 100644
--- a/chromium/chrome/browser/custom_handlers/protocol_handler_registry.cc
+++ b/chromium/chrome/browser/custom_handlers/protocol_handler_registry.cc
@@ -17,7 +17,6 @@
#include "base/stl_util.h"
#include "base/task/post_task.h"
#include "build/build_config.h"
-#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/profiles/profile_io_data.h"
#include "chrome/common/custom_handlers/protocol_handler.h"
#include "chrome/common/pref_names.h"
@@ -60,6 +59,20 @@ bool ShouldRemoveHandlersNotInOS() {
#endif
}
+GURL TranslateUrl(
+ const ProtocolHandlerRegistry::ProtocolHandlerMap& handler_map,
+ const GURL& url) {
+ const ProtocolHandler& handler = LookupHandler(handler_map, url.scheme());
+ if (handler.IsEmpty())
+ return GURL();
+
+ GURL translated_url(handler.TranslateUrl(url));
+ if (!translated_url.is_valid())
+ return GURL();
+
+ return translated_url;
+}
+
} // namespace
// IOThreadDelegate ------------------------------------------------------------
@@ -90,16 +103,7 @@ void ProtocolHandlerRegistry::IOThreadDelegate::SetDefault(
GURL ProtocolHandlerRegistry::IOThreadDelegate::Translate(
const GURL& url) const {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
-
- ProtocolHandler handler = LookupHandler(default_handlers_, url.scheme());
- if (handler.IsEmpty())
- return GURL();
-
- GURL translated_url(handler.TranslateUrl(url));
- if (!translated_url.is_valid())
- return GURL();
-
- return translated_url;
+ return TranslateUrl(default_handlers_, url);
}
// Create a new job for the supplied |URLRequest| if a default handler
@@ -129,71 +133,6 @@ void ProtocolHandlerRegistry::IOThreadDelegate::Disable() {
enabled_ = false;
}
-// JobInterceptorFactory -------------------------------------------------------
-
-// Instances of JobInterceptorFactory are produced for ownership by the IO
-// thread where it handler URL requests. We should never hold
-// any pointers on this class, only produce them in response to
-// requests via |ProtocolHandlerRegistry::CreateJobInterceptorFactory|.
-ProtocolHandlerRegistry::JobInterceptorFactory::JobInterceptorFactory(
- IOThreadDelegate* io_thread_delegate)
- : io_thread_delegate_(io_thread_delegate) {
- DCHECK(io_thread_delegate_.get());
- DETACH_FROM_THREAD(thread_checker_);
-}
-
-ProtocolHandlerRegistry::JobInterceptorFactory::~JobInterceptorFactory() {
-}
-
-void ProtocolHandlerRegistry::JobInterceptorFactory::Chain(
- std::unique_ptr<net::URLRequestJobFactory> job_factory) {
- job_factory_ = std::move(job_factory);
-}
-
-net::URLRequestJob*
-ProtocolHandlerRegistry::JobInterceptorFactory::
-MaybeCreateJobWithProtocolHandler(
- const std::string& scheme,
- net::URLRequest* request,
- net::NetworkDelegate* network_delegate) const {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
- net::URLRequestJob* job = io_thread_delegate_->MaybeCreateJob(
- request, network_delegate);
- if (job)
- return job;
- return job_factory_->MaybeCreateJobWithProtocolHandler(
- scheme, request, network_delegate);
-}
-
-net::URLRequestJob*
-ProtocolHandlerRegistry::JobInterceptorFactory::MaybeInterceptRedirect(
- net::URLRequest* request,
- net::NetworkDelegate* network_delegate,
- const GURL& location) const {
- return job_factory_->MaybeInterceptRedirect(
- request, network_delegate, location);
-}
-
-net::URLRequestJob*
-ProtocolHandlerRegistry::JobInterceptorFactory::MaybeInterceptResponse(
- net::URLRequest* request,
- net::NetworkDelegate* network_delegate) const {
- return job_factory_->MaybeInterceptResponse(request, network_delegate);
-}
-
-bool ProtocolHandlerRegistry::JobInterceptorFactory::IsHandledProtocol(
- const std::string& scheme) const {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
- return io_thread_delegate_->IsHandledProtocol(scheme) ||
- job_factory_->IsHandledProtocol(scheme);
-}
-
-bool ProtocolHandlerRegistry::JobInterceptorFactory::IsSafeRedirectTarget(
- const GURL& location) const {
- DCHECK_CURRENTLY_ON(BrowserThread::IO);
- return job_factory_->IsSafeRedirectTarget(location);
-}
-
// Delegate --------------------------------------------------------------------
ProtocolHandlerRegistry::Delegate::~Delegate() {}
@@ -249,8 +188,7 @@ ProtocolHandlerRegistry::ProtocolHandlerRegistry(
enabled_(true),
is_loading_(false),
is_loaded_(false),
- io_thread_delegate_(new IOThreadDelegate(enabled_)),
- weak_ptr_factory_(this) {}
+ io_thread_delegate_(new IOThreadDelegate(enabled_)) {}
bool ProtocolHandlerRegistry::SilentlyHandleRegisterHandlerRequest(
const ProtocolHandler& handler) {
@@ -427,7 +365,7 @@ ProtocolHandlerRegistry::GetUserDefinedHandlers(base::Time begin,
ProtocolHandlerRegistry::ProtocolHandlerList result;
for (const auto& entry : user_protocol_handlers_) {
for (const ProtocolHandler& handler : entry.second) {
- if (base::ContainsValue(predefined_protocol_handlers_, handler))
+ if (base::Contains(predefined_protocol_handlers_, handler))
continue;
if (begin <= handler.last_modified() && handler.last_modified() < end)
result.push_back(handler);
@@ -489,7 +427,7 @@ bool ProtocolHandlerRegistry::IsRegistered(
if (!handlers) {
return false;
}
- return base::ContainsValue(*handlers, handler);
+ return base::Contains(*handlers, handler);
}
bool ProtocolHandlerRegistry::IsRegisteredByUser(
@@ -621,6 +559,11 @@ const ProtocolHandler& ProtocolHandlerRegistry::GetHandlerFor(
return LookupHandler(default_handlers_, scheme);
}
+GURL ProtocolHandlerRegistry::Translate(const GURL& url) const {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ return TranslateUrl(default_handlers_, url);
+}
+
void ProtocolHandlerRegistry::Enable() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (enabled_) {
@@ -678,6 +621,14 @@ ProtocolHandlerRegistry::~ProtocolHandlerRegistry() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
}
+void ProtocolHandlerRegistry::AddObserver(Observer* observer) {
+ observers_.AddObserver(observer);
+}
+
+void ProtocolHandlerRegistry::RemoveObserver(Observer* observer) {
+ observers_.RemoveObserver(observer);
+}
+
void ProtocolHandlerRegistry::PromoteHandler(const ProtocolHandler& handler) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(IsRegistered(handler));
@@ -773,11 +724,8 @@ base::Value* ProtocolHandlerRegistry::EncodeIgnoredHandlers() {
}
void ProtocolHandlerRegistry::NotifyChanged() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- content::NotificationService::current()->Notify(
- chrome::NOTIFICATION_PROTOCOL_HANDLER_REGISTRY_CHANGED,
- content::Source<content::BrowserContext>(context_),
- content::NotificationService::NoDetails());
+ for (auto& observer : observers_)
+ observer.OnProtocolHandlerRegistryChanged();
}
void ProtocolHandlerRegistry::RegisterProtocolHandler(
@@ -874,7 +822,7 @@ bool ProtocolHandlerRegistry::HandlerExists(const ProtocolHandler& handler,
bool ProtocolHandlerRegistry::HandlerExists(const ProtocolHandler& handler,
const ProtocolHandlerList& list) {
- return base::ContainsValue(list, handler);
+ return base::Contains(list, handler);
}
void ProtocolHandlerRegistry::EraseHandler(const ProtocolHandler& handler,
@@ -913,13 +861,3 @@ ProtocolHandlerRegistry::GetDefaultWebClientCallback(
&ProtocolHandlerRegistry::OnSetAsDefaultProtocolClientFinished,
weak_ptr_factory_.GetWeakPtr(), protocol);
}
-
-std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
-ProtocolHandlerRegistry::CreateJobInterceptorFactory() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
- // this is always created on the UI thread (in profile_io's
- // InitializeOnUIThread. Any method calls must be done
- // on the IO thread (this is checked).
- return std::unique_ptr<JobInterceptorFactory>(
- new JobInterceptorFactory(io_thread_delegate_.get()));
-}
diff --git a/chromium/chrome/browser/custom_handlers/protocol_handler_registry.h b/chromium/chrome/browser/custom_handlers/protocol_handler_registry.h
index 8c9dce72df6..443488f8546 100644
--- a/chromium/chrome/browser/custom_handlers/protocol_handler_registry.h
+++ b/chromium/chrome/browser/custom_handlers/protocol_handler_registry.h
@@ -12,6 +12,7 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
+#include "base/observer_list.h"
#include "base/sequenced_task_runner_helpers.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
@@ -19,7 +20,6 @@
#include "chrome/common/custom_handlers/protocol_handler.h"
#include "components/keyed_service/core/keyed_service.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/notification_service.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request_job_factory.h"
@@ -60,6 +60,11 @@ class ProtocolHandlerRegistry : public KeyedService {
ProtocolHandlerRegistry* registry);
};
+ class Observer : public base::CheckedObserver {
+ public:
+ virtual void OnProtocolHandlerRegistryChanged() = 0;
+ };
+
// IOThreadDelegate is an IO thread specific object. Access to the class
// should all be done via the IO thread. The registry living on the UI thread
// makes a best effort to update the IO object after local updates are
@@ -82,7 +87,7 @@ class ProtocolHandlerRegistry : public KeyedService {
// Should be called only from the IO thread.
void SetDefault(const ProtocolHandler& handler);
- // Returns a translated url if |url| is handled by a protocol handler,
+ // Returns a translated URL if |url| is handled by a protocol handler,
// otherwise it returns an empty URL.
GURL Translate(const GURL& url) const;
@@ -113,58 +118,12 @@ class ProtocolHandlerRegistry : public KeyedService {
DISALLOW_COPY_AND_ASSIGN(IOThreadDelegate);
};
- // JobInterceptorFactory intercepts URLRequestJob creation for URLRequests the
- // ProtocolHandlerRegistry is registered to handle. When no handler is
- // registered, the URLRequest is passed along to the chained
- // URLRequestJobFactory (set with |JobInterceptorFactory::Chain|).
- // JobInterceptorFactory's are created via
- // |ProtocolHandlerRegistry::CreateJobInterceptorFactory|.
- class JobInterceptorFactory : public net::URLRequestJobFactory {
- public:
- // |io_thread_delegate| is used to perform actual job creation work.
- explicit JobInterceptorFactory(IOThreadDelegate* io_thread_delegate);
- ~JobInterceptorFactory() override;
-
- // |job_factory| is set as the URLRequestJobFactory where requests are
- // forwarded if JobInterceptorFactory decides to pass on them.
- void Chain(std::unique_ptr<net::URLRequestJobFactory> job_factory);
-
- // URLRequestJobFactory implementation.
- net::URLRequestJob* MaybeCreateJobWithProtocolHandler(
- const std::string& scheme,
- net::URLRequest* request,
- net::NetworkDelegate* network_delegate) const override;
-
- net::URLRequestJob* MaybeInterceptRedirect(
- net::URLRequest* request,
- net::NetworkDelegate* network_delegate,
- const GURL& location) const override;
-
- net::URLRequestJob* MaybeInterceptResponse(
- net::URLRequest* request,
- net::NetworkDelegate* network_delegate) const override;
-
- bool IsHandledProtocol(const std::string& scheme) const override;
- bool IsSafeRedirectTarget(const GURL& location) const override;
-
- private:
- // When JobInterceptorFactory decides to pass on particular requests,
- // they're forwarded to the chained URLRequestJobFactory, |job_factory_|.
- std::unique_ptr<URLRequestJobFactory> job_factory_;
- // |io_thread_delegate_| performs the actual job creation decisions by
- // mirroring the ProtocolHandlerRegistry on the IO thread.
- scoped_refptr<IOThreadDelegate> io_thread_delegate_;
-
- DISALLOW_COPY_AND_ASSIGN(JobInterceptorFactory);
- };
-
// Creates a new instance. Assumes ownership of |delegate|.
ProtocolHandlerRegistry(content::BrowserContext* context, Delegate* delegate);
~ProtocolHandlerRegistry() override;
- // Returns a net::URLRequestJobFactory suitable for use on the IO thread, but
- // is initialized on the UI thread.
- std::unique_ptr<JobInterceptorFactory> CreateJobInterceptorFactory();
+ void AddObserver(Observer* observer);
+ void RemoveObserver(Observer* observer);
// Called when a site tries to register as a protocol handler. If the request
// can be handled silently by the registry - either to ignore the request
@@ -265,6 +224,10 @@ class ProtocolHandlerRegistry : public KeyedService {
// exists.
const ProtocolHandler& GetHandlerFor(const std::string& scheme) const;
+ // Returns a translated URL if |url| is handled by a protocol handler,
+ // otherwise it returns an empty URL.
+ GURL Translate(const GURL& url) const;
+
// Puts this registry in the enabled state - registered protocol handlers
// will handle requests.
void Enable();
@@ -335,7 +298,7 @@ class ProtocolHandlerRegistry : public KeyedService {
// responsible for deleting this Value.
base::Value* EncodeIgnoredHandlers();
- // Sends a notification of the given type to the NotificationService.
+ // Notifies observers of a change to the registry.
void NotifyChanged();
// Registers a new protocol handler.
@@ -437,9 +400,11 @@ class ProtocolHandlerRegistry : public KeyedService {
// are posted to the IO thread where updates are applied to this object.
scoped_refptr<IOThreadDelegate> io_thread_delegate_;
+ base::ObserverList<Observer> observers_;
+
// Makes it possible to invalidate the callback for the
// DefaultProtocolClientWorker.
- base::WeakPtrFactory<ProtocolHandlerRegistry> weak_ptr_factory_;
+ base::WeakPtrFactory<ProtocolHandlerRegistry> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ProtocolHandlerRegistry);
};
diff --git a/chromium/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc b/chromium/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc
index 42db890617f..f6fe7772a8e 100644
--- a/chromium/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc
+++ b/chromium/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc
@@ -11,11 +11,11 @@
#include "base/bind.h"
#include "base/run_loop.h"
+#include "base/scoped_observer.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
-#include "chrome/browser/chrome_notification_types.h"
#include "chrome/common/custom_handlers/protocol_handler.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_browser_process.h"
@@ -23,9 +23,6 @@
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/sync_preferences/pref_service_syncable.h"
#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
-#include "content/public/browser/notification_source.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_renderer_host.h"
#include "net/base/request_priority.h"
@@ -38,27 +35,6 @@ using content::BrowserThread;
namespace {
-void AssertInterceptedIO(
- const GURL& url,
- net::URLRequestJobFactory* interceptor) {
- net::URLRequestContext context;
- std::unique_ptr<net::URLRequest> request(context.CreateRequest(
- url, net::DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS));
- std::unique_ptr<net::URLRequestJob> job(
- interceptor->MaybeCreateJobWithProtocolHandler(
- url.scheme(), request.get(), context.network_delegate()));
- ASSERT_TRUE(job.get());
-}
-
-void AssertIntercepted(
- const GURL& url,
- net::URLRequestJobFactory* interceptor) {
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(AssertInterceptedIO, url, base::Unretained(interceptor)));
- base::RunLoop().RunUntilIdle();
-}
-
// FakeURLRequestJobFactory returns NULL for all job creation requests and false
// for all IsHandledProtocol() requests. FakeURLRequestJobFactory can be chained
// to ProtocolHandlerRegistry::JobInterceptorFactory so the result of
@@ -94,26 +70,6 @@ class FakeURLRequestJobFactory : public net::URLRequestJobFactory {
}
};
-void AssertWillHandleIO(
- const std::string& scheme,
- bool expected,
- ProtocolHandlerRegistry::JobInterceptorFactory* interceptor) {
- interceptor->Chain(std::unique_ptr<net::URLRequestJobFactory>(
- new FakeURLRequestJobFactory()));
- ASSERT_EQ(expected, interceptor->IsHandledProtocol(scheme));
- interceptor->Chain(std::unique_ptr<net::URLRequestJobFactory>());
-}
-
-void AssertWillHandle(
- const std::string& scheme,
- bool expected,
- ProtocolHandlerRegistry::JobInterceptorFactory* interceptor) {
- base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
- base::BindOnce(AssertWillHandleIO, scheme, expected,
- base::Unretained(interceptor)));
- base::RunLoop().RunUntilIdle();
-}
-
std::unique_ptr<base::DictionaryValue> GetProtocolHandlerValue(
const std::string& protocol,
const std::string& url) {
@@ -187,53 +143,53 @@ class FakeDelegate : public ProtocolHandlerRegistry::Delegate {
bool force_os_failure_;
};
-class NotificationCounter : public content::NotificationObserver {
+class ProtocolHandlerChangeListener : public ProtocolHandlerRegistry::Observer {
public:
- explicit NotificationCounter(content::BrowserContext* context)
- : events_(0),
- notification_registrar_() {
- notification_registrar_.Add(this,
- chrome::NOTIFICATION_PROTOCOL_HANDLER_REGISTRY_CHANGED,
- content::Source<content::BrowserContext>(context));
+ explicit ProtocolHandlerChangeListener(ProtocolHandlerRegistry* registry) {
+ registry_observer_.Add(registry);
}
+ ~ProtocolHandlerChangeListener() override = default;
int events() { return events_; }
bool notified() { return events_ > 0; }
void Clear() { events_ = 0; }
- void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) override {
- ++events_;
- }
- int events_;
- content::NotificationRegistrar notification_registrar_;
+ // ProtocolHandlerRegistry::Observer:
+ void OnProtocolHandlerRegistryChanged() override { ++events_; }
+
+ private:
+ int events_ = 0;
+
+ ScopedObserver<ProtocolHandlerRegistry, ProtocolHandlerRegistry::Observer>
+ registry_observer_{this};
+
+ DISALLOW_COPY_AND_ASSIGN(ProtocolHandlerChangeListener);
};
-class QueryProtocolHandlerOnChange
- : public content::NotificationObserver {
+class QueryProtocolHandlerOnChange : public ProtocolHandlerRegistry::Observer {
public:
- QueryProtocolHandlerOnChange(content::BrowserContext* context,
- ProtocolHandlerRegistry* registry)
- : local_registry_(registry),
- called_(false),
- notification_registrar_() {
- notification_registrar_.Add(this,
- chrome::NOTIFICATION_PROTOCOL_HANDLER_REGISTRY_CHANGED,
- content::Source<content::BrowserContext>(context));
+ explicit QueryProtocolHandlerOnChange(ProtocolHandlerRegistry* registry)
+ : local_registry_(registry) {
+ registry_observer_.Add(registry);
}
- void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) override {
+ // ProtocolHandlerRegistry::Observer:
+ void OnProtocolHandlerRegistryChanged() override {
std::vector<std::string> output;
local_registry_->GetRegisteredProtocols(&output);
called_ = true;
}
+ bool called() const { return called_; }
+
+ private:
ProtocolHandlerRegistry* local_registry_;
- bool called_;
- content::NotificationRegistrar notification_registrar_;
+ bool called_ = false;
+
+ ScopedObserver<ProtocolHandlerRegistry, ProtocolHandlerRegistry::Observer>
+ registry_observer_{this};
+
+ DISALLOW_COPY_AND_ASSIGN(QueryProtocolHandlerOnChange);
};
} // namespace
@@ -672,9 +628,9 @@ TEST_F(ProtocolHandlerRegistryTest, TestIsHandledProtocol) {
ASSERT_FALSE(registry()->IsHandledProtocol("test"));
}
-TEST_F(ProtocolHandlerRegistryTest, TestNotifications) {
+TEST_F(ProtocolHandlerRegistryTest, TestObserver) {
ProtocolHandler ph1 = CreateProtocolHandler("test", "test1");
- NotificationCounter counter(profile());
+ ProtocolHandlerChangeListener counter(registry());
registry()->OnAcceptRegisterProtocolHandler(ph1);
ASSERT_TRUE(counter.notified());
@@ -693,11 +649,11 @@ TEST_F(ProtocolHandlerRegistryTest, TestNotifications) {
counter.Clear();
}
-TEST_F(ProtocolHandlerRegistryTest, TestReentrantNotifications) {
- QueryProtocolHandlerOnChange queryer(profile(), registry());
+TEST_F(ProtocolHandlerRegistryTest, TestReentrantObserver) {
+ QueryProtocolHandlerOnChange queryer(registry());
ProtocolHandler ph1 = CreateProtocolHandler("test", "test1");
registry()->OnAcceptRegisterProtocolHandler(ph1);
- ASSERT_TRUE(queryer.called_);
+ ASSERT_TRUE(queryer.called());
}
TEST_F(ProtocolHandlerRegistryTest, TestProtocolsWithNoDefaultAreHandled) {
@@ -767,27 +723,6 @@ TEST_F(ProtocolHandlerRegistryTest, MAYBE_TestOSRegistrationFailure) {
ASSERT_EQ(static_cast<size_t>(1), registry()->GetHandlersFor("dont").size());
}
-TEST_F(ProtocolHandlerRegistryTest, TestMaybeCreateTaskWorksFromIOThread) {
- ProtocolHandler ph1 = CreateProtocolHandler("mailto", "test1");
- registry()->OnAcceptRegisterProtocolHandler(ph1);
- GURL url("mailto:someone@something.com");
-
- std::unique_ptr<net::URLRequestJobFactory> interceptor(
- registry()->CreateJobInterceptorFactory());
- AssertIntercepted(url, interceptor.get());
-}
-
-TEST_F(ProtocolHandlerRegistryTest,
- TestIsHandledProtocolWorksOnIOThread) {
- std::string scheme("mailto");
- ProtocolHandler ph1 = CreateProtocolHandler(scheme, "test1");
- registry()->OnAcceptRegisterProtocolHandler(ph1);
-
- std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> interceptor(
- registry()->CreateJobInterceptorFactory());
- AssertWillHandle(scheme, true, interceptor.get());
-}
-
TEST_F(ProtocolHandlerRegistryTest, TestRemovingDefaultFallsBackToOldDefault) {
ProtocolHandler ph1 = CreateProtocolHandler("mailto", "test1");
ProtocolHandler ph2 = CreateProtocolHandler("mailto", "test2");
@@ -824,29 +759,6 @@ TEST_F(ProtocolHandlerRegistryTest, TestRemovingDefaultDoesntChangeHandlers) {
ASSERT_EQ(ph1, handlers[1]);
}
-TEST_F(ProtocolHandlerRegistryTest, TestClearDefaultGetsPropagatedToIO) {
- std::string scheme("mailto");
- ProtocolHandler ph1 = CreateProtocolHandler(scheme, "test1");
- registry()->OnAcceptRegisterProtocolHandler(ph1);
- registry()->ClearDefault(scheme);
-
- std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> interceptor(
- registry()->CreateJobInterceptorFactory());
- AssertWillHandle(scheme, false, interceptor.get());
-}
-
-TEST_F(ProtocolHandlerRegistryTest, TestLoadEnabledGetsPropogatedToIO) {
- std::string mailto("mailto");
- ProtocolHandler ph1 = CreateProtocolHandler(mailto, "MailtoHandler");
- registry()->OnAcceptRegisterProtocolHandler(ph1);
-
- std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> interceptor(
- registry()->CreateJobInterceptorFactory());
- AssertWillHandle(mailto, true, interceptor.get());
- registry()->Disable();
- AssertWillHandle(mailto, false, interceptor.get());
-}
-
TEST_F(ProtocolHandlerRegistryTest, TestReplaceHandler) {
ProtocolHandler ph1 =
CreateProtocolHandler("mailto", GURL("http://test.com/%s"));
diff --git a/chromium/chrome/browser/devtools/DEPS b/chromium/chrome/browser/devtools/DEPS
new file mode 100644
index 00000000000..925300863f1
--- /dev/null
+++ b/chromium/chrome/browser/devtools/DEPS
@@ -0,0 +1,4 @@
+include_rules = [
+ # For converting between JSON and CBOR in devtools_session_encoding.cc.
+ "+third_party/inspector_protocol/encoding",
+]
diff --git a/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.cc b/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.cc
index 0ef34b44437..d34abfa43f3 100644
--- a/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.cc
+++ b/chromium/chrome/browser/devtools/chrome_devtools_manager_delegate.cc
@@ -117,7 +117,7 @@ void ChromeDevToolsManagerDelegate::HandleCommand(
std::string ChromeDevToolsManagerDelegate::GetTargetType(
content::WebContents* web_contents) {
- if (base::ContainsValue(AllTabContentses(), web_contents))
+ if (base::Contains(AllTabContentses(), web_contents))
return DevToolsAgentHost::kTypePage;
std::string extension_name;
diff --git a/chromium/chrome/browser/devtools/chrome_devtools_session.cc b/chromium/chrome/browser/devtools/chrome_devtools_session.cc
index ee7bf903535..4b75e59539e 100644
--- a/chromium/chrome/browser/devtools/chrome_devtools_session.cc
+++ b/chromium/chrome/browser/devtools/chrome_devtools_session.cc
@@ -4,6 +4,8 @@
#include "chrome/browser/devtools/chrome_devtools_session.h"
+#include <memory>
+#include "base/strings/string_number_conversions.h"
#include "chrome/browser/devtools/protocol/browser_handler.h"
#include "chrome/browser/devtools/protocol/cast_handler.h"
#include "chrome/browser/devtools/protocol/page_handler.h"
@@ -11,11 +13,47 @@
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_agent_host_client.h"
#include "content/public/browser/devtools_manager_delegate.h"
+#include "third_party/inspector_protocol/encoding/encoding.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/devtools/protocol/window_manager_handler.h"
#endif
+namespace {
+// TODO(johannes): This is very similar to the code in
+// content/browser/devtools/devtools_protocol_encoding. Once we have
+// the error / status propagation story settled, move the common parts
+// into a content public API.
+
+using ::inspector_protocol_encoding::span;
+using ::inspector_protocol_encoding::SpanFrom;
+using ::inspector_protocol_encoding::json::ConvertCBORToJSON;
+using ::inspector_protocol_encoding::json::ConvertJSONToCBOR;
+using IPEStatus = ::inspector_protocol_encoding::Status;
+
+// Platform allows us to inject the string<->double conversion
+// routines from base:: into the inspector_protocol JSON parser / serializer.
+class Platform : public ::inspector_protocol_encoding::json::Platform {
+ public:
+ bool StrToD(const char* str, double* result) const override {
+ return base::StringToDouble(str, result);
+ }
+
+ // Prints |value| in a format suitable for JSON.
+ std::unique_ptr<char[]> DToStr(double value) const override {
+ std::string str = base::NumberToString(value);
+ std::unique_ptr<char[]> result(new char[str.size() + 1]);
+ memcpy(result.get(), str.c_str(), str.size() + 1);
+ return result;
+ }
+};
+
+IPEStatus ConvertCBORToJSON(span<uint8_t> cbor, std::string* json) {
+ Platform platform;
+ return ConvertCBORToJSON(platform, cbor, json);
+}
+} // namespace
+
ChromeDevToolsSession::ChromeDevToolsSession(
content::DevToolsAgentHost* agent_host,
content::DevToolsAgentHostClient* client)
@@ -44,14 +82,6 @@ ChromeDevToolsSession::ChromeDevToolsSession(
ChromeDevToolsSession::~ChromeDevToolsSession() = default;
-void ChromeDevToolsSession::sendProtocolResponse(
- int call_id,
- std::unique_ptr<protocol::Serializable> message) {
- pending_commands_.erase(call_id);
- bool binary = client_->UsesBinaryProtocol();
- client_->DispatchProtocolMessage(agent_host_, message->serialize(binary));
-}
-
void ChromeDevToolsSession::HandleCommand(
const std::string& method,
const std::string& message,
@@ -72,18 +102,41 @@ void ChromeDevToolsSession::HandleCommand(
dispatcher_->dispatch(call_id, method, std::move(value), message);
}
-void ChromeDevToolsSession::fallThrough(int call_id,
- const std::string& method,
- const std::string& message) {
- auto callback = std::move(pending_commands_[call_id]);
+// The following methods handle responses or notifications coming from
+// the browser to the client.
+static void SendProtocolResponseOrNotification(
+ content::DevToolsAgentHostClient* client,
+ content::DevToolsAgentHost* agent_host,
+ std::unique_ptr<protocol::Serializable> message) {
+ std::string cbor = message->serialize(/*binary=*/true);
+ if (client->UsesBinaryProtocol()) {
+ client->DispatchProtocolMessage(agent_host, cbor);
+ return;
+ }
+ std::string json;
+ IPEStatus status = ConvertCBORToJSON(SpanFrom(cbor), &json);
+ LOG_IF(ERROR, !status.ok()) << status.ToASCIIString();
+ client->DispatchProtocolMessage(agent_host, json);
+}
+
+void ChromeDevToolsSession::sendProtocolResponse(
+ int call_id,
+ std::unique_ptr<protocol::Serializable> message) {
pending_commands_.erase(call_id);
- std::move(callback).Run(message);
+ SendProtocolResponseOrNotification(client_, agent_host_, std::move(message));
}
void ChromeDevToolsSession::sendProtocolNotification(
std::unique_ptr<protocol::Serializable> message) {
- bool binary = client_->UsesBinaryProtocol();
- client_->DispatchProtocolMessage(agent_host_, message->serialize(binary));
+ SendProtocolResponseOrNotification(client_, agent_host_, std::move(message));
}
void ChromeDevToolsSession::flushProtocolNotifications() {}
+
+void ChromeDevToolsSession::fallThrough(int call_id,
+ const std::string& method,
+ const std::string& message) {
+ auto callback = std::move(pending_commands_[call_id]);
+ pending_commands_.erase(call_id);
+ std::move(callback).Run(message);
+}
diff --git a/chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc b/chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc
index 633309f0ed9..758309f7793 100644
--- a/chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc
+++ b/chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc
@@ -221,7 +221,7 @@ class SimpleHttpServer {
SEQUENCE_CHECKER(sequence_checker_);
- base::WeakPtrFactory<Connection> weak_factory_;
+ base::WeakPtrFactory<Connection> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(Connection);
};
@@ -235,7 +235,7 @@ class SimpleHttpServer {
SEQUENCE_CHECKER(sequence_checker_);
- base::WeakPtrFactory<SimpleHttpServer> weak_factory_;
+ base::WeakPtrFactory<SimpleHttpServer> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SimpleHttpServer);
};
@@ -243,8 +243,7 @@ class SimpleHttpServer {
SimpleHttpServer::SimpleHttpServer(const ParserFactory& factory,
net::IPEndPoint endpoint)
: factory_(factory),
- socket_(new net::TCPServerSocket(nullptr, net::NetLogSource())),
- weak_factory_(this) {
+ socket_(new net::TCPServerSocket(nullptr, net::NetLogSource())) {
socket_->Listen(endpoint, 5);
OnConnect();
}
@@ -261,8 +260,7 @@ SimpleHttpServer::Connection::Connection(net::StreamSocket* socket,
input_buffer_(base::MakeRefCounted<net::GrowableIOBuffer>()),
output_buffer_(base::MakeRefCounted<net::GrowableIOBuffer>()),
bytes_to_write_(0),
- read_closed_(false),
- weak_factory_(this) {
+ read_closed_(false) {
input_buffer_->SetCapacity(kBufferSize);
ReadData();
}
diff --git a/chromium/chrome/browser/devtools/device/android_device_manager.cc b/chromium/chrome/browser/devtools/device/android_device_manager.cc
index c8772e6e5e5..ce20fba0441 100644
--- a/chromium/chrome/browser/devtools/device/android_device_manager.cc
+++ b/chromium/chrome/browser/devtools/device/android_device_manager.cc
@@ -491,8 +491,7 @@ AndroidDeviceManager::Device::Device(
: RefCountedDeleteOnSequence<Device>(base::ThreadTaskRunnerHandle::Get()),
task_runner_(device_task_runner),
provider_(provider),
- serial_(serial),
- weak_factory_(this) {}
+ serial_(serial) {}
AndroidDeviceManager::Device::~Device() {
task_runner_->PostTask(
@@ -584,7 +583,7 @@ void AndroidDeviceManager::set_usb_device_manager_for_test(
}
AndroidDeviceManager::AndroidDeviceManager()
- : handler_thread_(HandlerThread::GetInstance()), weak_factory_(this) {}
+ : handler_thread_(HandlerThread::GetInstance()) {}
AndroidDeviceManager::~AndroidDeviceManager() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/chromium/chrome/browser/devtools/device/android_device_manager.h b/chromium/chrome/browser/devtools/device/android_device_manager.h
index 76d82ef9a29..b97c7e6f47b 100644
--- a/chromium/chrome/browser/devtools/device/android_device_manager.h
+++ b/chromium/chrome/browser/devtools/device/android_device_manager.h
@@ -106,7 +106,7 @@ class AndroidDeviceManager {
scoped_refptr<Device> device_;
std::unique_ptr<WebSocketImpl, base::OnTaskRunnerDeleter> socket_impl_;
Delegate* delegate_;
- base::WeakPtrFactory<AndroidWebSocket> weak_factory_;
+ base::WeakPtrFactory<AndroidWebSocket> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(AndroidWebSocket);
};
@@ -149,7 +149,7 @@ class AndroidDeviceManager {
scoped_refptr<DeviceProvider> provider_;
const std::string serial_;
- base::WeakPtrFactory<Device> weak_factory_;
+ base::WeakPtrFactory<Device> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(Device);
};
@@ -254,7 +254,7 @@ class AndroidDeviceManager {
SEQUENCE_CHECKER(sequence_checker_);
- base::WeakPtrFactory<AndroidDeviceManager> weak_factory_;
+ base::WeakPtrFactory<AndroidDeviceManager> weak_factory_{this};
};
#endif // CHROME_BROWSER_DEVTOOLS_DEVICE_ANDROID_DEVICE_MANAGER_H_
diff --git a/chromium/chrome/browser/devtools/device/android_web_socket.cc b/chromium/chrome/browser/devtools/device/android_web_socket.cc
index 0aff0397733..65ef44f4c87 100644
--- a/chromium/chrome/browser/devtools/device/android_web_socket.cc
+++ b/chromium/chrome/browser/devtools/device/android_web_socket.cc
@@ -64,8 +64,7 @@ class AndroidDeviceManager::AndroidWebSocket::WebSocketImpl {
weak_socket_(weak_socket),
socket_(std::move(socket)),
encoder_(net::WebSocketEncoder::CreateClient(extensions)),
- response_buffer_(body_head),
- weak_factory_(this) {
+ response_buffer_(body_head) {
thread_checker_.DetachFromThread();
}
@@ -184,7 +183,7 @@ class AndroidDeviceManager::AndroidWebSocket::WebSocketImpl {
base::ThreadChecker thread_checker_;
DISALLOW_COPY_AND_ASSIGN(WebSocketImpl);
- base::WeakPtrFactory<WebSocketImpl> weak_factory_;
+ base::WeakPtrFactory<WebSocketImpl> weak_factory_{this};
};
AndroidDeviceManager::AndroidWebSocket::AndroidWebSocket(
@@ -194,8 +193,7 @@ AndroidDeviceManager::AndroidWebSocket::AndroidWebSocket(
Delegate* delegate)
: device_(device),
socket_impl_(nullptr, base::OnTaskRunnerDeleter(device->task_runner_)),
- delegate_(delegate),
- weak_factory_(this) {
+ delegate_(delegate) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(delegate_);
DCHECK(device_);
diff --git a/chromium/chrome/browser/devtools/device/cast_device_provider.cc b/chromium/chrome/browser/devtools/device/cast_device_provider.cc
index d61a0aa1d59..e0a6bed0609 100644
--- a/chromium/chrome/browser/devtools/device/cast_device_provider.cc
+++ b/chromium/chrome/browser/devtools/device/cast_device_provider.cc
@@ -148,7 +148,7 @@ class CastDeviceProvider::DeviceListerDelegate
std::unique_ptr<ServiceDiscoveryDeviceLister> device_lister_;
};
-CastDeviceProvider::CastDeviceProvider() : weak_factory_(this) {}
+CastDeviceProvider::CastDeviceProvider() {}
CastDeviceProvider::~CastDeviceProvider() {}
diff --git a/chromium/chrome/browser/devtools/device/cast_device_provider.h b/chromium/chrome/browser/devtools/device/cast_device_provider.h
index f2d81461403..17aa21e6b29 100644
--- a/chromium/chrome/browser/devtools/device/cast_device_provider.h
+++ b/chromium/chrome/browser/devtools/device/cast_device_provider.h
@@ -57,7 +57,7 @@ class CastDeviceProvider
// Maps a service name to the hostname (IP address).
std::map<std::string, std::string> service_hostname_map_;
- base::WeakPtrFactory<CastDeviceProvider> weak_factory_;
+ base::WeakPtrFactory<CastDeviceProvider> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(CastDeviceProvider);
};
diff --git a/chromium/chrome/browser/devtools/device/devtools_android_bridge.cc b/chromium/chrome/browser/devtools/device/devtools_android_bridge.cc
index 93df0773564..2aeaad3f5cd 100644
--- a/chromium/chrome/browser/devtools/device/devtools_android_bridge.cc
+++ b/chromium/chrome/browser/devtools/device/devtools_android_bridge.cc
@@ -150,12 +150,10 @@ void DevToolsAndroidBridge::OpenRemotePage(scoped_refptr<RemoteBrowser> browser,
SendJsonRequest(browser->GetId(), request, base::DoNothing());
}
-DevToolsAndroidBridge::DevToolsAndroidBridge(
- Profile* profile)
+DevToolsAndroidBridge::DevToolsAndroidBridge(Profile* profile)
: profile_(profile),
device_manager_(AndroidDeviceManager::Create()),
- port_forwarding_controller_(new PortForwardingController(profile)),
- weak_factory_(this) {
+ port_forwarding_controller_(new PortForwardingController(profile)) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
pref_change_registrar_.Init(profile_->GetPrefs());
pref_change_registrar_.Add(prefs::kDevToolsDiscoverUsbDevicesEnabled,
diff --git a/chromium/chrome/browser/devtools/device/devtools_android_bridge.h b/chromium/chrome/browser/devtools/device/devtools_android_bridge.h
index 9399bd4d73b..6dede6d0b6f 100644
--- a/chromium/chrome/browser/devtools/device/devtools_android_bridge.h
+++ b/chromium/chrome/browser/devtools/device/devtools_android_bridge.h
@@ -192,7 +192,7 @@ class DevToolsAndroidBridge : public KeyedService {
std::unique_ptr<DevToolsDeviceDiscovery> device_discovery_;
- base::WeakPtrFactory<DevToolsAndroidBridge> weak_factory_;
+ base::WeakPtrFactory<DevToolsAndroidBridge> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DevToolsAndroidBridge);
};
diff --git a/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc b/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc
index 0ca19c508f9..101cddf50a6 100644
--- a/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc
+++ b/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc
@@ -586,8 +586,7 @@ DevToolsDeviceDiscovery::DevToolsDeviceDiscovery(
const DeviceListCallback& callback)
: device_manager_(device_manager),
callback_(callback),
- task_scheduler_(base::Bind(&ScheduleTaskDefault)),
- weak_factory_(this) {
+ task_scheduler_(base::Bind(&ScheduleTaskDefault)) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
RequestDeviceList();
}
diff --git a/chromium/chrome/browser/devtools/device/devtools_device_discovery.h b/chromium/chrome/browser/devtools/device/devtools_device_discovery.h
index 5c8d6b1777e..7b97e2f90e5 100644
--- a/chromium/chrome/browser/devtools/device/devtools_device_discovery.h
+++ b/chromium/chrome/browser/devtools/device/devtools_device_discovery.h
@@ -141,7 +141,7 @@ class DevToolsDeviceDiscovery {
AndroidDeviceManager* device_manager_;
const DeviceListCallback callback_;
base::Callback<void(const base::Closure&)> task_scheduler_;
- base::WeakPtrFactory<DevToolsDeviceDiscovery> weak_factory_;
+ base::WeakPtrFactory<DevToolsDeviceDiscovery> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DevToolsDeviceDiscovery);
};
diff --git a/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc b/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc
index 814533bc137..be43c35de89 100644
--- a/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc
+++ b/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc
@@ -13,13 +13,13 @@
#include "base/json/json_writer.h"
#include "base/macros.h"
#include "base/memory/singleton.h"
-#include "base/message_loop/message_loop_current.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/task/post_task.h"
#include "base/threading/thread_checker.h"
+#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
@@ -228,7 +228,7 @@ class SocketTunnel {
: remote_socket_(std::move(socket)),
pending_writes_(0),
pending_destruction_(false),
- adb_thread_runner_(base::MessageLoopCurrent::Get()->task_runner()) {
+ adb_thread_runner_(base::ThreadTaskRunnerHandle::Get()) {
ResolveHostCallback resolve_host_callback = base::BindOnce(
&SocketTunnel::OnResolveHostComplete, base::Unretained(this));
base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI},
diff --git a/chromium/chrome/browser/devtools/device/tcp_device_provider.cc b/chromium/chrome/browser/devtools/device/tcp_device_provider.cc
index c949036fbbc..48a1ca318db 100644
--- a/chromium/chrome/browser/devtools/device/tcp_device_provider.cc
+++ b/chromium/chrome/browser/devtools/device/tcp_device_provider.cc
@@ -97,7 +97,7 @@ void TCPDeviceProvider::QueryDevices(const SerialsCallback& callback) {
std::vector<std::string> result;
for (const net::HostPortPair& target : targets_) {
const std::string& host = target.host();
- if (base::ContainsValue(result, host))
+ if (base::Contains(result, host))
continue;
result.push_back(host);
}
diff --git a/chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc b/chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc
index b664a3b9c03..8da28afc32a 100644
--- a/chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc
+++ b/chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc
@@ -423,7 +423,7 @@ class FakeAndroidUsbManager : public FakeUsbDeviceManager {
void GetDevice(const std::string& guid,
device::mojom::UsbDeviceRequest device_request,
device::mojom::UsbDeviceClientPtr device_client) override {
- DCHECK(base::ContainsKey(devices(), guid));
+ DCHECK(base::Contains(devices(), guid));
FakeAndroidUsbDevice::Create(devices()[guid], std::move(device_request),
std::move(device_client));
}
diff --git a/chromium/chrome/browser/devtools/device/usb/android_usb_device.cc b/chromium/chrome/browser/devtools/device/usb/android_usb_device.cc
index 7d2d59f20f3..66b9c619609 100644
--- a/chromium/chrome/browser/devtools/device/usb/android_usb_device.cc
+++ b/chromium/chrome/browser/devtools/device/usb/android_usb_device.cc
@@ -166,7 +166,7 @@ void OpenAndroidDevices(crypto::RSAPrivateKey* rsa_key,
base::BindOnce(&OnProbeFinished, callback, devices));
for (const auto& device_info : device_info_list) {
- if (base::ContainsValue(g_open_devices.Get(), device_info.guid)) {
+ if (base::Contains(g_open_devices.Get(), device_info.guid)) {
// This device is already open, do not make parallel attempts to connect
// to it.
barrier.Run();
@@ -208,8 +208,7 @@ AndroidUsbDevice::AndroidUsbDevice(crypto::RSAPrivateKey* rsa_key,
android_device_info_(android_device_info),
is_connected_(false),
signature_sent_(false),
- last_socket_id_(256),
- weak_factory_(this) {
+ last_socket_id_(256) {
DCHECK(device_ptr_);
device_ptr_.set_connection_error_handler(
base::BindOnce(&AndroidUsbDevice::Terminate, weak_factory_.GetWeakPtr()));
diff --git a/chromium/chrome/browser/devtools/device/usb/android_usb_device.h b/chromium/chrome/browser/devtools/device/usb/android_usb_device.h
index 815f13b8c16..cad570fe003 100644
--- a/chromium/chrome/browser/devtools/device/usb/android_usb_device.h
+++ b/chromium/chrome/browser/devtools/device/usb/android_usb_device.h
@@ -152,7 +152,7 @@ class AndroidUsbDevice : public base::RefCountedThreadSafe<AndroidUsbDevice> {
using PendingMessages = std::vector<std::unique_ptr<AdbMessage>>;
PendingMessages pending_messages_;
- base::WeakPtrFactory<AndroidUsbDevice> weak_factory_;
+ base::WeakPtrFactory<AndroidUsbDevice> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(AndroidUsbDevice);
};
diff --git a/chromium/chrome/browser/devtools/device/usb/android_usb_socket.cc b/chromium/chrome/browser/devtools/device/usb/android_usb_socket.cc
index d4ee11b1134..7f00d5ce311 100644
--- a/chromium/chrome/browser/devtools/device/usb/android_usb_socket.cc
+++ b/chromium/chrome/browser/devtools/device/usb/android_usb_socket.cc
@@ -28,8 +28,7 @@ AndroidUsbSocket::AndroidUsbSocket(scoped_refptr<AndroidUsbDevice> device,
local_id_(socket_id),
remote_id_(0),
is_connected_(false),
- delete_callback_(delete_callback),
- weak_factory_(this) {}
+ delete_callback_(delete_callback) {}
AndroidUsbSocket::~AndroidUsbSocket() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/chromium/chrome/browser/devtools/device/usb/android_usb_socket.h b/chromium/chrome/browser/devtools/device/usb/android_usb_socket.h
index 50fcc685b41..e93e6e89ad2 100644
--- a/chromium/chrome/browser/devtools/device/usb/android_usb_socket.h
+++ b/chromium/chrome/browser/devtools/device/usb/android_usb_socket.h
@@ -81,7 +81,7 @@ class AndroidUsbSocket : public net::StreamSocket {
SEQUENCE_CHECKER(sequence_checker_);
- base::WeakPtrFactory<AndroidUsbSocket> weak_factory_;
+ base::WeakPtrFactory<AndroidUsbSocket> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(AndroidUsbSocket);
};
diff --git a/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.cc b/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.cc
index 8703dbc534a..78884250899 100644
--- a/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.cc
+++ b/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.cc
@@ -13,7 +13,7 @@
#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/device/public/mojom/usb_enumeration_options.mojom.h"
@@ -64,7 +64,7 @@ void GetAndroidDeviceInfoList(
std::vector<device::mojom::UsbDeviceInfoPtr> usb_devices) {
std::vector<AndroidDeviceInfo> result;
for (auto& device_info : usb_devices) {
- if (device_info->serial_number->empty())
+ if (!device_info->serial_number || device_info->serial_number->empty())
continue;
auto interface_info = FindAndroidInterface(*device_info);
@@ -107,9 +107,8 @@ void BindDeviceServiceOnUIThread(
device::mojom::UsbDeviceManagerRequest request) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Bind to the DeviceService for USB device manager.
- content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->BindInterface(device::mojom::kServiceName, std::move(request));
+ content::GetSystemConnector()->BindInterface(device::mojom::kServiceName,
+ std::move(request));
}
} // namespace
@@ -152,7 +151,7 @@ void UsbDeviceManagerHelper::SetUsbManagerForTesting(
GetInstance()->SetUsbManagerForTestingInternal(std::move(fake_usb_manager));
}
-UsbDeviceManagerHelper::UsbDeviceManagerHelper() : weak_factory_(this) {}
+UsbDeviceManagerHelper::UsbDeviceManagerHelper() {}
UsbDeviceManagerHelper::~UsbDeviceManagerHelper() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
diff --git a/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.h b/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.h
index 04c6fb452d7..5d7c7d48d2c 100644
--- a/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.h
+++ b/chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.h
@@ -74,7 +74,7 @@ class UsbDeviceManagerHelper {
THREAD_CHECKER(thread_checker_);
- base::WeakPtrFactory<UsbDeviceManagerHelper> weak_factory_;
+ base::WeakPtrFactory<UsbDeviceManagerHelper> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(UsbDeviceManagerHelper);
};
diff --git a/chromium/chrome/browser/devtools/devtools_browser_context_manager.cc b/chromium/chrome/browser/devtools/devtools_browser_context_manager.cc
index d3f52535d68..fddd8e01c52 100644
--- a/chromium/chrome/browser/devtools/devtools_browser_context_manager.cc
+++ b/chromium/chrome/browser/devtools/devtools_browser_context_manager.cc
@@ -10,8 +10,7 @@
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
-DevToolsBrowserContextManager::DevToolsBrowserContextManager()
- : weak_factory_(this) {}
+DevToolsBrowserContextManager::DevToolsBrowserContextManager() {}
DevToolsBrowserContextManager::~DevToolsBrowserContextManager() = default;
diff --git a/chromium/chrome/browser/devtools/devtools_browser_context_manager.h b/chromium/chrome/browser/devtools/devtools_browser_context_manager.h
index 6a001856b68..cf1b24df30a 100644
--- a/chromium/chrome/browser/devtools/devtools_browser_context_manager.h
+++ b/chromium/chrome/browser/devtools/devtools_browser_context_manager.h
@@ -37,7 +37,7 @@ class DevToolsBrowserContextManager : public BrowserListObserver {
base::flat_map<std::string, content::DevToolsManagerDelegate::DisposeCallback>
pending_context_disposals_;
- base::WeakPtrFactory<DevToolsBrowserContextManager> weak_factory_;
+ base::WeakPtrFactory<DevToolsBrowserContextManager> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DevToolsBrowserContextManager);
};
diff --git a/chromium/chrome/browser/devtools/devtools_eye_dropper.cc b/chromium/chrome/browser/devtools/devtools_eye_dropper.cc
index 66528e579e5..a59a23ceb68 100644
--- a/chromium/chrome/browser/devtools/devtools_eye_dropper.cc
+++ b/chromium/chrome/browser/devtools/devtools_eye_dropper.cc
@@ -35,8 +35,7 @@ DevToolsEyeDropper::DevToolsEyeDropper(content::WebContents* web_contents,
callback_(callback),
last_cursor_x_(-1),
last_cursor_y_(-1),
- host_(nullptr),
- weak_factory_(this) {
+ host_(nullptr) {
mouse_event_callback_ =
base::Bind(&DevToolsEyeDropper::HandleMouseEvent, base::Unretained(this));
content::RenderViewHost* rvh = web_contents->GetRenderViewHost();
@@ -81,7 +80,7 @@ void DevToolsEyeDropper::DetachFromHost() {
return;
host_->RemoveMouseEventCallback(mouse_event_callback_);
content::CursorInfo cursor_info;
- cursor_info.type = blink::WebCursorInfo::kTypePointer;
+ cursor_info.type = ui::CursorType::kPointer;
host_->SetCursor(cursor_info);
video_capturer_.reset();
host_ = nullptr;
@@ -255,7 +254,7 @@ void DevToolsEyeDropper::UpdateCursor() {
canvas.drawCircle(kCursorSize / 2, kCursorSize / 2, kDiameter / 2, paint);
content::CursorInfo cursor_info;
- cursor_info.type = blink::WebCursorInfo::kTypeCustom;
+ cursor_info.type = ui::CursorType::kCustom;
cursor_info.image_scale_factor = device_scale_factor;
cursor_info.custom_image = result;
cursor_info.hotspot = gfx::Point(kHotspotOffset * device_scale_factor,
diff --git a/chromium/chrome/browser/devtools/devtools_eye_dropper.h b/chromium/chrome/browser/devtools/devtools_eye_dropper.h
index 8aa5b6cf8f4..3ba7601f9f0 100644
--- a/chromium/chrome/browser/devtools/devtools_eye_dropper.h
+++ b/chromium/chrome/browser/devtools/devtools_eye_dropper.h
@@ -57,7 +57,7 @@ class DevToolsEyeDropper : public content::WebContentsObserver,
content::RenderWidgetHost::MouseEventCallback mouse_event_callback_;
content::RenderWidgetHost* host_;
std::unique_ptr<viz::ClientFrameSinkVideoCapturer> video_capturer_;
- base::WeakPtrFactory<DevToolsEyeDropper> weak_factory_;
+ base::WeakPtrFactory<DevToolsEyeDropper> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DevToolsEyeDropper);
};
diff --git a/chromium/chrome/browser/devtools/devtools_file_helper.cc b/chromium/chrome/browser/devtools/devtools_file_helper.cc
index b9a627cfeb2..546d65f0860 100644
--- a/chromium/chrome/browser/devtools/devtools_file_helper.cc
+++ b/chromium/chrome/browser/devtools/devtools_file_helper.cc
@@ -218,8 +218,7 @@ DevToolsFileHelper::DevToolsFileHelper(WebContents* web_contents,
profile_(profile),
delegate_(delegate),
file_task_runner_(
- base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})),
- weak_factory_(this) {
+ base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})) {
pref_change_registrar_.Init(profile_->GetPrefs());
}
diff --git a/chromium/chrome/browser/devtools/devtools_file_helper.h b/chromium/chrome/browser/devtools/devtools_file_helper.h
index 9b8695962a5..550844e1e54 100644
--- a/chromium/chrome/browser/devtools/devtools_file_helper.h
+++ b/chromium/chrome/browser/devtools/devtools_file_helper.h
@@ -155,7 +155,7 @@ class DevToolsFileHelper {
std::unique_ptr<DevToolsFileWatcher, DevToolsFileWatcher::Deleter>
file_watcher_;
scoped_refptr<base::SequencedTaskRunner> file_task_runner_;
- base::WeakPtrFactory<DevToolsFileHelper> weak_factory_;
+ base::WeakPtrFactory<DevToolsFileHelper> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DevToolsFileHelper);
};
diff --git a/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc b/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc
index 0152dfb6ac6..96079b9f876 100644
--- a/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc
+++ b/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc
@@ -43,7 +43,7 @@ using std::set;
base::SequencedTaskRunner* impl_task_runner() {
constexpr base::TaskTraits kBlockingTraits = {
- base::MayBlock(), base::TaskPriority::BEST_EFFORT};
+ base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT};
static base::LazySequencedTaskRunner s_sequenced_task_task_runner =
LAZY_SEQUENCED_TASK_RUNNER_INITIALIZER(kBlockingTraits);
return s_sequenced_task_task_runner.Get().get();
diff --git a/chromium/chrome/browser/devtools/devtools_file_watcher.cc b/chromium/chrome/browser/devtools/devtools_file_watcher.cc
index 6bef7d96754..d0445ad346e 100644
--- a/chromium/chrome/browser/devtools/devtools_file_watcher.cc
+++ b/chromium/chrome/browser/devtools/devtools_file_watcher.cc
@@ -225,7 +225,7 @@ void DevToolsFileWatcher::SharedFileWatcher::DispatchNotifications() {
namespace {
base::SequencedTaskRunner* impl_task_runner() {
constexpr base::TaskTraits kImplTaskTraits = {
- base::MayBlock(), base::TaskPriority::BEST_EFFORT};
+ base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT};
static base::LazySequencedTaskRunner s_file_task_runner =
LAZY_SEQUENCED_TASK_RUNNER_INITIALIZER(kImplTaskTraits);
return s_file_task_runner.Get().get();
diff --git a/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc b/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc
index c314e103e1e..250a9ade9f3 100644
--- a/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc
+++ b/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc
@@ -358,13 +358,10 @@ class DevToolsBeforeUnloadTest: public DevToolsSanityTest {
before_unload_observer.Wait();
}
{
- content::WindowedNotificationObserver close_observer(
- chrome::NOTIFICATION_BROWSER_CLOSED,
- content::Source<Browser>(browser()));
close_method.Run();
AcceptModalDialog();
if (wait_for_browser_close)
- close_observer.Wait();
+ ui_test_utils::WaitForBrowserToClose(browser());
}
runner->Run();
}
@@ -808,13 +805,10 @@ IN_PROC_BROWSER_TEST_F(DevToolsBeforeUnloadTest,
}
// Try to exit application.
{
- content::WindowedNotificationObserver close_observer(
- chrome::NOTIFICATION_BROWSER_CLOSED,
- content::Source<Browser>(browser()));
chrome::CloseAllBrowsers();
AcceptModalDialog();
AcceptModalDialog();
- close_observer.Wait();
+ ui_test_utils::WaitForBrowserToClose(browser());
}
for (auto& close_observer : close_observers)
close_observer->Wait();
@@ -1777,7 +1771,14 @@ IN_PROC_BROWSER_TEST_F(DevToolsAutoOpenerTest, TestAutoOpenForTabs) {
observer_->CloseAllSync();
}
-class DevToolsReattachAfterCrashTest : public DevToolsSanityTest {
+// Flaky timeouts on Win7 Tests (dbg)(1); see https://crbug.com/985255.
+#if defined(OS_WIN) && !defined(NDEBUG)
+#define MAYBE_DevToolsReattachAfterCrashTest \
+ DISABLED_DevToolsReattachAfterCrashTest
+#else
+#define MAYBE_DevToolsReattachAfterCrashTest DevToolsReattachAfterCrashTest
+#endif
+class MAYBE_DevToolsReattachAfterCrashTest : public DevToolsSanityTest {
protected:
void RunTestWithPanel(const char* panel_name) {
OpenDevToolsWindow("about:blank", false);
@@ -1795,12 +1796,12 @@ class DevToolsReattachAfterCrashTest : public DevToolsSanityTest {
}
};
-IN_PROC_BROWSER_TEST_F(DevToolsReattachAfterCrashTest,
+IN_PROC_BROWSER_TEST_F(MAYBE_DevToolsReattachAfterCrashTest,
TestReattachAfterCrashOnTimeline) {
RunTestWithPanel("timeline");
}
-IN_PROC_BROWSER_TEST_F(DevToolsReattachAfterCrashTest,
+IN_PROC_BROWSER_TEST_F(MAYBE_DevToolsReattachAfterCrashTest,
TestReattachAfterCrashOnNetwork) {
RunTestWithPanel("network");
}
@@ -2116,7 +2117,7 @@ class StaticURLDataSource : public content::URLDataSource {
~StaticURLDataSource() override = default;
// content::URLDataSource:
- std::string GetSource() const override { return source_; }
+ std::string GetSource() override { return source_; }
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
@@ -2124,10 +2125,10 @@ class StaticURLDataSource : public content::URLDataSource {
std::string data(content_);
callback.Run(base::RefCountedString::TakeString(&data));
}
- std::string GetMimeType(const std::string& path) const override {
+ std::string GetMimeType(const std::string& path) override {
return "text/html";
}
- bool ShouldAddContentSecurityPolicy() const override { return false; }
+ bool ShouldAddContentSecurityPolicy() override { return false; }
private:
const std::string source_;
@@ -2185,15 +2186,6 @@ IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
content::WebUIControllerFactory::UnregisterFactoryForTesting(&test_factory);
}
-void AddHSTSHost(scoped_refptr<net::URLRequestContextGetter> context,
- std::string host) {
- net::TransportSecurityState* transport_security_state =
- context->GetURLRequestContext()->transport_security_state();
- base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
- bool include_subdomains = false;
- transport_security_state->AddHSTS(host, expiry, include_subdomains);
-}
-
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestRawHeadersWithRedirectAndHSTS) {
net::EmbeddedTestServer https_test_server(
net::EmbeddedTestServer::TYPE_HTTPS);
@@ -2202,25 +2194,16 @@ IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestRawHeadersWithRedirectAndHSTS) {
https_test_server.ServeFilesFromSourceDirectory(GetChromeTestDataDir());
ASSERT_TRUE(https_test_server.Start());
GURL https_url = https_test_server.GetURL("localhost", "/devtools/image.png");
- if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(
- AddHSTSHost,
- base::RetainedRef(browser()->profile()->GetRequestContext()),
- https_url.host()));
- } else {
- base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
- bool include_subdomains = false;
- mojo::ScopedAllowSyncCallForTesting allow_sync_call;
- content::StoragePartition* partition =
- content::BrowserContext::GetDefaultStoragePartition(
- browser()->profile());
- base::RunLoop run_loop;
- partition->GetNetworkContext()->AddHSTS(
- https_url.host(), expiry, include_subdomains, run_loop.QuitClosure());
- run_loop.Run();
- }
+ base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
+ bool include_subdomains = false;
+ mojo::ScopedAllowSyncCallForTesting allow_sync_call;
+ content::StoragePartition* partition =
+ content::BrowserContext::GetDefaultStoragePartition(browser()->profile());
+ base::RunLoop run_loop;
+ partition->GetNetworkContext()->AddHSTS(
+ https_url.host(), expiry, include_subdomains, run_loop.QuitClosure());
+ run_loop.Run();
+
ASSERT_TRUE(embedded_test_server()->Start());
OpenDevToolsWindow(std::string(), false);
@@ -2359,11 +2342,9 @@ IN_PROC_BROWSER_TEST_F(InProcessBrowserTest, BrowserCloseWithBeforeUnload) {
"window.addEventListener('beforeunload',"
"function(event) { event.returnValue = 'Foo'; });"));
content::PrepContentsForBeforeUnloadTest(tab);
- content::WindowedNotificationObserver close_observer(
- chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(browser()));
BrowserHandler handler(nullptr, std::string());
handler.Close();
- close_observer.Wait();
+ ui_test_utils::WaitForBrowserToClose(browser());
}
// Flaky on Mus. See https://crbug.com/819285.
@@ -2395,8 +2376,9 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessDevToolsSanityTest,
DevToolsWindowTesting::CloseDevToolsWindowSync(window);
}
+// See https://crbug.com/971241
IN_PROC_BROWSER_TEST_F(DevToolsExtensionTest,
- ExtensionWebSocketUserAgentOverride) {
+ DISABLED_ExtensionWebSocketUserAgentOverride) {
net::SpawnedTestServer websocket_server(
net::SpawnedTestServer::TYPE_WS,
base::FilePath(FILE_PATH_LITERAL("net/data/websocket")));
diff --git a/chromium/chrome/browser/devtools/devtools_sanity_interactive_browsertest.cc b/chromium/chrome/browser/devtools/devtools_sanity_interactive_browsertest.cc
index 781ca08ead9..08f6eeead21 100644
--- a/chromium/chrome/browser/devtools/devtools_sanity_interactive_browsertest.cc
+++ b/chromium/chrome/browser/devtools/devtools_sanity_interactive_browsertest.cc
@@ -6,8 +6,8 @@
#include "base/bind.h"
#include "base/macros.h"
-#include "base/message_loop/message_loop_current.h"
#include "base/run_loop.h"
+#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
#include "chrome/browser/devtools/protocol/browser_handler.h"
@@ -45,7 +45,7 @@ class CheckWaiter {
bool Check() {
if (callback_.Run() != expected_ &&
base::Time::NowFromSystemTime() < timeout_) {
- base::MessageLoopCurrent::Get()->task_runner()->PostTask(
+ base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(base::IgnoreResult(&CheckWaiter::Check),
base::Unretained(this)));
return false;
diff --git a/chromium/chrome/browser/devtools/devtools_targets_ui.cc b/chromium/chrome/browser/devtools/devtools_targets_ui.cc
index 2ad22002da9..b61a455f00b 100644
--- a/chromium/chrome/browser/devtools/devtools_targets_ui.cc
+++ b/chromium/chrome/browser/devtools/devtools_targets_ui.cc
@@ -66,8 +66,7 @@ const char kPortForwardingBrowserId[] = "browserId";
class CancelableTimer {
public:
CancelableTimer(base::Closure callback, base::TimeDelta delay)
- : callback_(callback),
- weak_factory_(this) {
+ : callback_(callback) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&CancelableTimer::Fire, weak_factory_.GetWeakPtr()),
@@ -78,7 +77,7 @@ class CancelableTimer {
void Fire() { callback_.Run(); }
base::Closure callback_;
- base::WeakPtrFactory<CancelableTimer> weak_factory_;
+ base::WeakPtrFactory<CancelableTimer> weak_factory_{this};
};
// LocalTargetsUIHandler ---------------------------------------------
@@ -103,14 +102,13 @@ private:
Profile* profile_;
std::unique_ptr<CancelableTimer> timer_;
- base::WeakPtrFactory<LocalTargetsUIHandler> weak_factory_;
+ base::WeakPtrFactory<LocalTargetsUIHandler> weak_factory_{this};
};
LocalTargetsUIHandler::LocalTargetsUIHandler(const Callback& callback,
Profile* profile)
: DevToolsTargetsUIHandler(kTargetSourceLocal, callback),
- profile_(profile),
- weak_factory_(this) {
+ profile_(profile) {
DevToolsAgentHost::AddObserver(this);
UpdateTargets();
}
diff --git a/chromium/chrome/browser/devtools/devtools_ui_bindings.cc b/chromium/chrome/browser/devtools/devtools_ui_bindings.cc
index 113d9bd32e2..1acc82d6f38 100644
--- a/chromium/chrome/browser/devtools/devtools_ui_bindings.cc
+++ b/chromium/chrome/browser/devtools/devtools_ui_bindings.cc
@@ -293,6 +293,19 @@ std::string SanitizeRemoteFrontendURL(const std::string& value) {
return net::EscapeQueryParamValue(sanitized, false);
}
+std::string SanitizeEnabledExperiments(const std::string& value) {
+ bool valid = std::find_if_not(value.begin(), value.end(), [](char ch) {
+ if (base::IsAsciiAlpha(ch) || base::IsAsciiDigit(ch) ||
+ ch == ';' || ch == '_')
+ return true;
+ return false;
+ }) == value.end();
+ if (!valid) {
+ return std::string();
+ }
+ return value;
+}
+
std::string SanitizeFrontendQueryParam(
const std::string& key,
const std::string& value) {
@@ -323,6 +336,9 @@ std::string SanitizeFrontendQueryParam(
if (key == "remoteVersion")
return SanitizeRemoteVersion(value);
+ if (key == "enabledExperiments")
+ return SanitizeEnabledExperiments(value);
+
return std::string();
}
@@ -531,8 +547,7 @@ DevToolsUIBindings::DevToolsUIBindings(content::WebContents* web_contents)
web_contents_(web_contents),
delegate_(new DefaultBindingsDelegate(web_contents_)),
devices_updates_enabled_(false),
- frontend_loaded_(false),
- weak_factory_(this) {
+ frontend_loaded_(false) {
g_devtools_ui_bindings_instances.Get().push_back(this);
frontend_contents_observer_.reset(new FrontendWebContentsObserver(this));
web_contents_->GetMutableRendererPrefs()->can_accept_load_drops = false;
@@ -740,11 +755,12 @@ void DevToolsUIBindings::LoadNetworkResource(const DispatchCallback& callback,
nullptr /* shared_cors_origin_access_list */);
url_loader_factory = file_url_loader_factory.get();
} else if (content::HasWebUIScheme(gurl)) {
+ content::WebContents* target_tab;
#ifndef NDEBUG
- // In debug builds, allow retrieving files from the chrome:// scheme
- content::WebContents* target_tab =
- DevToolsWindow::AsDevToolsWindow(web_contents_)
- ->GetInspectedWebContents();
+ // In debug builds, allow retrieving files from the chrome:// and
+ // devtools:// schemes
+ target_tab = DevToolsWindow::AsDevToolsWindow(web_contents_)
+ ->GetInspectedWebContents();
const bool allow_web_ui_scheme =
target_tab && content::HasWebUIScheme(target_tab->GetURL());
#else
@@ -754,7 +770,8 @@ void DevToolsUIBindings::LoadNetworkResource(const DispatchCallback& callback,
std::vector<std::string> allowed_webui_hosts;
content::RenderFrameHost* frame_host = web_contents()->GetMainFrame();
webui_url_loader_factory = content::CreateWebUIURLLoader(
- frame_host, content::kChromeUIScheme, std::move(allowed_webui_hosts));
+ frame_host, target_tab->GetURL().scheme(),
+ std::move(allowed_webui_hosts));
url_loader_factory = webui_url_loader_factory.get();
} else {
base::DictionaryValue response;
diff --git a/chromium/chrome/browser/devtools/devtools_ui_bindings.h b/chromium/chrome/browser/devtools/devtools_ui_bindings.h
index f8320694192..cc7e57e6c2e 100644
--- a/chromium/chrome/browser/devtools/devtools_ui_bindings.h
+++ b/chromium/chrome/browser/devtools/devtools_ui_bindings.h
@@ -254,7 +254,7 @@ class DevToolsUIBindings : public DevToolsEmbedderMessageDispatcher::Delegate,
using ExtensionsAPIs = std::map<std::string, std::string>;
ExtensionsAPIs extensions_api_;
- base::WeakPtrFactory<DevToolsUIBindings> weak_factory_;
+ base::WeakPtrFactory<DevToolsUIBindings> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DevToolsUIBindings);
};
diff --git a/chromium/chrome/browser/devtools/devtools_ui_bindings_unittest.cc b/chromium/chrome/browser/devtools/devtools_ui_bindings_unittest.cc
index ff9dc6881e7..2e27ec76906 100644
--- a/chromium/chrome/browser/devtools/devtools_ui_bindings_unittest.cc
+++ b/chromium/chrome/browser/devtools/devtools_ui_bindings_unittest.cc
@@ -95,6 +95,12 @@ TEST_F(DevToolsUIBindingsTest, SanitizeFrontendURL) {
"devtools://devtools/?remoteFrontendUrl="
"https%3A%2F%2Fchrome-devtools-frontend.appspot.com%2Fserve_rev"
"%2F%4012345%2Finspector.html"},
+ {"devtools://devtools/"
+ "?enabledExperiments=explosionsWhileTyping;newA11yTool",
+ "devtools://devtools/"
+ "?enabledExperiments=explosionsWhileTyping;newA11yTool"},
+ {"devtools://devtools/?enabledExperiments=invalidExperiment$",
+ "devtools://devtools/"},
};
for (const auto& pair : tests) {
diff --git a/chromium/chrome/browser/devtools/devtools_window.cc b/chromium/chrome/browser/devtools/devtools_window.cc
index be0c8603874..3dbd95ca379 100644
--- a/chromium/chrome/browser/devtools/devtools_window.cc
+++ b/chromium/chrome/browser/devtools/devtools_window.cc
@@ -17,7 +17,6 @@
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/certificate_viewer.h"
-#include "chrome/browser/data_use_measurement/data_use_web_contents_observer.h"
#include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
#include "chrome/browser/devtools/devtools_eye_dropper.h"
#include "chrome/browser/file_select_helper.h"
@@ -398,7 +397,7 @@ void DevToolsWindow::AddCreationCallbackForTest(
void DevToolsWindow::RemoveCreationCallbackForTest(
const CreationCallback& callback) {
for (size_t i = 0; i < g_creation_callbacks.Get().size(); ++i) {
- if (g_creation_callbacks.Get().at(i).Equals(callback)) {
+ if (g_creation_callbacks.Get().at(i) == callback) {
g_creation_callbacks.Get().erase(g_creation_callbacks.Get().begin() + i);
return;
}
@@ -942,8 +941,6 @@ DevToolsWindow::DevToolsWindow(FrontendType frontend_type,
main_web_contents_->SetDelegate(this);
// Bindings take ownership over devtools as its delegate.
bindings_->SetDelegate(this);
- data_use_measurement::DataUseWebContentsObserver::CreateForWebContents(
- main_web_contents_);
// DevTools uses PageZoom::Zoom(), so main_web_contents_ requires a
// ZoomController.
zoom::ZoomController::CreateForWebContents(main_web_contents_);
@@ -1194,8 +1191,6 @@ void DevToolsWindow::WebContentsCreated(WebContents* source_contents,
// UserData so that it shows up in the task manager.
task_manager::WebContentsTags::CreateForDevToolsContents(
toolbox_web_contents_);
- data_use_measurement::DataUseWebContentsObserver::CreateForWebContents(
- toolbox_web_contents_);
// The toolbox holds a placeholder for the inspected WebContents. When the
// placeholder is resized, a frame is requested. The inspected WebContents
diff --git a/chromium/chrome/browser/devtools/global_confirm_info_bar.cc b/chromium/chrome/browser/devtools/global_confirm_info_bar.cc
index efc8ae349c1..106733e746e 100644
--- a/chromium/chrome/browser/devtools/global_confirm_info_bar.cc
+++ b/chromium/chrome/browser/devtools/global_confirm_info_bar.cc
@@ -163,8 +163,7 @@ GlobalConfirmInfoBar::GlobalConfirmInfoBar(
std::unique_ptr<ConfirmInfoBarDelegate> delegate)
: delegate_(std::move(delegate)),
browser_tab_strip_tracker_(this, nullptr, nullptr),
- is_closing_(false),
- weak_factory_(this) {
+ is_closing_(false) {
browser_tab_strip_tracker_.Init();
}
@@ -216,7 +215,7 @@ void GlobalConfirmInfoBar::MaybeAddInfoBar(content::WebContents* web_contents) {
InfoBarService::FromWebContents(web_contents);
// WebContents from the tab strip must have the infobar service.
DCHECK(infobar_service);
- if (ContainsKey(proxies_, infobar_service))
+ if (base::Contains(proxies_, infobar_service))
return;
std::unique_ptr<GlobalConfirmInfoBar::DelegateProxy> proxy(
diff --git a/chromium/chrome/browser/devtools/global_confirm_info_bar.h b/chromium/chrome/browser/devtools/global_confirm_info_bar.h
index 6410931d60f..82afbd73967 100644
--- a/chromium/chrome/browser/devtools/global_confirm_info_bar.h
+++ b/chromium/chrome/browser/devtools/global_confirm_info_bar.h
@@ -62,7 +62,7 @@ class GlobalConfirmInfoBar : public TabStripModelObserver,
// down.
bool is_closing_;
- base::WeakPtrFactory<GlobalConfirmInfoBar> weak_factory_;
+ base::WeakPtrFactory<GlobalConfirmInfoBar> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(GlobalConfirmInfoBar);
};
diff --git a/chromium/chrome/browser/devtools/inspector_protocol_config.json b/chromium/chrome/browser/devtools/inspector_protocol_config.json
index 2c2d6292abb..ae2a2d80704 100644
--- a/chromium/chrome/browser/devtools/inspector_protocol_config.json
+++ b/chromium/chrome/browser/devtools/inspector_protocol_config.json
@@ -38,7 +38,9 @@
},
"encoding_lib": {
- "header": "third_party/inspector_protocol/encoding/encoding.h",
- "namespace": ["inspector_protocol_encoding"]
+ "namespace": "inspector_protocol_encoding"
+ },
+ "bindings_lib": {
+ "namespace": "inspector_protocol_bindings"
}
}
diff --git a/chromium/chrome/browser/devtools/protocol/browser_handler.cc b/chromium/chrome/browser/devtools/protocol/browser_handler.cc
index 6e81fd4a74c..2bc97efa18c 100644
--- a/chromium/chrome/browser/devtools/protocol/browser_handler.cc
+++ b/chromium/chrome/browser/devtools/protocol/browser_handler.cc
@@ -100,6 +100,10 @@ Response FromProtocolPermissionType(
*out_type = content::PermissionType::PAYMENT_HANDLER;
} else if (type == protocol::Browser::PermissionTypeEnum::BackgroundFetch) {
*out_type = content::PermissionType::BACKGROUND_FETCH;
+ } else if (type == protocol::Browser::PermissionTypeEnum::WakeLockScreen) {
+ *out_type = content::PermissionType::WAKE_LOCK_SCREEN;
+ } else if (type == protocol::Browser::PermissionTypeEnum::WakeLockSystem) {
+ *out_type = content::PermissionType::WAKE_LOCK_SYSTEM;
} else {
return Response::InvalidParams("Unknown permission type: " + type);
}
@@ -252,10 +256,9 @@ Response BrowserHandler::GrantPermissions(
return response;
PermissionOverrides overrides;
- for (size_t i = 0; i < permissions->length(); ++i) {
+ for (const std::string& permission : *permissions) {
content::PermissionType type;
- Response type_response =
- FromProtocolPermissionType(permissions->get(i), &type);
+ Response type_response = FromProtocolPermissionType(permission, &type);
if (!type_response.isSuccess())
return type_response;
overrides.insert(type);
diff --git a/chromium/chrome/browser/devtools/protocol/cast_handler.cc b/chromium/chrome/browser/devtools/protocol/cast_handler.cc
index f77cfa56224..a437d4b68ef 100644
--- a/chromium/chrome/browser/devtools/protocol/cast_handler.cc
+++ b/chromium/chrome/browser/devtools/protocol/cast_handler.cc
@@ -150,9 +150,7 @@ void CastHandler::OnResultsUpdated(
}
CastHandler::CastHandler(content::WebContents* web_contents)
- : web_contents_(web_contents),
- router_(GetMediaRouter(web_contents)),
- weak_factory_(this) {}
+ : web_contents_(web_contents), router_(GetMediaRouter(web_contents)) {}
void CastHandler::EnsureInitialized() {
if (query_result_manager_)
@@ -238,8 +236,7 @@ void CastHandler::SendSinkUpdate() {
if (!frontend_)
return;
- std::unique_ptr<protocol::Array<Sink>> protocol_sinks =
- protocol::Array<Sink>::create();
+ auto protocol_sinks = std::make_unique<protocol::Array<Sink>>();
for (const media_router::MediaSinkWithCastModes& sink_with_modes : sinks_) {
auto route_it = std::find_if(
routes_observer_->routes().begin(), routes_observer_->routes().end(),
@@ -256,7 +253,7 @@ void CastHandler::SendSinkUpdate() {
if (!session.empty())
sink->SetSession(session);
- protocol_sinks->addItem(std::move(sink));
+ protocol_sinks->emplace_back(std::move(sink));
}
frontend_->SinksUpdated(std::move(protocol_sinks));
}
diff --git a/chromium/chrome/browser/devtools/protocol/cast_handler.h b/chromium/chrome/browser/devtools/protocol/cast_handler.h
index 7bba8888c81..cb14c6fa013 100644
--- a/chromium/chrome/browser/devtools/protocol/cast_handler.h
+++ b/chromium/chrome/browser/devtools/protocol/cast_handler.h
@@ -99,7 +99,7 @@ class CastHandler : public protocol::Cast::Backend,
std::unique_ptr<protocol::Cast::Frontend> frontend_;
- base::WeakPtrFactory<CastHandler> weak_factory_;
+ base::WeakPtrFactory<CastHandler> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(CastHandler);
};
diff --git a/chromium/chrome/browser/devtools/protocol/page_handler.cc b/chromium/chrome/browser/devtools/protocol/page_handler.cc
index eea7f9cee10..5dcd7d129d7 100644
--- a/chromium/chrome/browser/devtools/protocol/page_handler.cc
+++ b/chromium/chrome/browser/devtools/protocol/page_handler.cc
@@ -51,7 +51,7 @@ protocol::Response PageHandler::SetAdBlockingEnabled(bool enabled) {
void PageHandler::GetInstallabilityErrors(
std::unique_ptr<GetInstallabilityErrorsCallback> callback) {
- auto errors = protocol::Array<std::string>::create();
+ auto errors = std::make_unique<protocol::Array<std::string>>();
InstallableManager* manager =
web_contents() ? InstallableManager::FromWebContents(web_contents())
: nullptr;
@@ -68,8 +68,6 @@ void PageHandler::GetInstallabilityErrors(
void PageHandler::GotInstallabilityErrors(
std::unique_ptr<GetInstallabilityErrorsCallback> callback,
std::vector<std::string> errors) {
- auto result = protocol::Array<std::string>::create();
- for (const auto& error : errors)
- result->addItem(error);
- callback->sendSuccess(std::move(result));
+ callback->sendSuccess(
+ std::make_unique<protocol::Array<std::string>>(std::move(errors)));
}
diff --git a/chromium/chrome/browser/devtools/protocol/target_handler.cc b/chromium/chrome/browser/devtools/protocol/target_handler.cc
index cee0c2e196c..6947f168e23 100644
--- a/chromium/chrome/browser/devtools/protocol/target_handler.cc
+++ b/chromium/chrome/browser/devtools/protocol/target_handler.cc
@@ -53,10 +53,9 @@ protocol::Response TargetHandler::SetRemoteLocations(
if (!locations)
return protocol::Response::OK();
- for (size_t i = 0; i < locations->length(); ++i) {
- auto* item = locations->get(i);
+ for (const auto& location : *locations) {
remote_locations_.insert(
- net::HostPortPair(item->GetHost(), item->GetPort()));
+ net::HostPortPair(location->GetHost(), location->GetPort()));
}
ChromeDevToolsManagerDelegate* delegate =
diff --git a/chromium/chrome/browser/devtools/protocol/window_manager_handler.cc b/chromium/chrome/browser/devtools/protocol/window_manager_handler.cc
index 2db21878f24..3e8fce9c9ab 100644
--- a/chromium/chrome/browser/devtools/protocol/window_manager_handler.cc
+++ b/chromium/chrome/browser/devtools/protocol/window_manager_handler.cc
@@ -17,14 +17,14 @@ WindowManagerHandler::~WindowManagerHandler() = default;
protocol::Response WindowManagerHandler::EnterOverviewMode() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- bool toggled = ash::Shell::Get()->overview_controller()->ToggleOverview();
- return toggled ? protocol::Response::OK()
+ bool success = ash::Shell::Get()->overview_controller()->StartOverview();
+ return success ? protocol::Response::OK()
: protocol::Response::Error("Overview failed");
}
protocol::Response WindowManagerHandler::ExitOverviewMode() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- bool toggled = ash::Shell::Get()->overview_controller()->ToggleOverview();
- return toggled ? protocol::Response::OK()
+ bool success = ash::Shell::Get()->overview_controller()->EndOverview();
+ return success ? protocol::Response::OK()
: protocol::Response::Error("Overview failed");
}
diff --git a/chromium/chrome/browser/extensions/BUILD.gn b/chromium/chrome/browser/extensions/BUILD.gn
index 343d9631726..e26b2ba3fb5 100644
--- a/chromium/chrome/browser/extensions/BUILD.gn
+++ b/chromium/chrome/browser/extensions/BUILD.gn
@@ -12,10 +12,6 @@ import("//mojo/public/tools/bindings/mojom.gni")
import("//pdf/features.gni")
import("//rlz/buildflags/buildflags.gni")
-if (is_chromeos) {
- import("//chrome/browser/chromeos/kiosk_next_home/kiosk_next.gni")
-}
-
assert(enable_extensions)
jumbo_static_library("extensions") {
@@ -426,16 +422,10 @@ jumbo_static_library("extensions") {
"blacklist_factory.h",
"blacklist_state_fetcher.cc",
"blacklist_state_fetcher.h",
- "bookmark_app_experimental_navigation_throttle.cc",
- "bookmark_app_experimental_navigation_throttle.h",
"bookmark_app_extension_util.cc",
"bookmark_app_extension_util.h",
"bookmark_app_helper.cc",
"bookmark_app_helper.h",
- "bookmark_app_navigation_throttle.cc",
- "bookmark_app_navigation_throttle.h",
- "bookmark_app_navigation_throttle_utils.cc",
- "bookmark_app_navigation_throttle_utils.h",
"browser_context_keyed_service_factories.cc",
"browser_context_keyed_service_factories.h",
"browser_extension_window_controller.cc",
@@ -462,6 +452,10 @@ jumbo_static_library("extensions") {
"chrome_extension_browser_constants.cc",
"chrome_extension_browser_constants.h",
"chrome_extension_chooser_dialog.h",
+ "chrome_extension_cookies.cc",
+ "chrome_extension_cookies.h",
+ "chrome_extension_cookies_factory.cc",
+ "chrome_extension_cookies_factory.h",
"chrome_extension_function.cc",
"chrome_extension_function.h",
"chrome_extension_function_details.cc",
@@ -525,12 +519,12 @@ jumbo_static_library("extensions") {
"extension_assets_manager.h",
"extension_assets_manager_chromeos.cc",
"extension_assets_manager_chromeos.h",
+ "extension_browser_window_helper.cc",
+ "extension_browser_window_helper.h",
"extension_commands_global_registry.cc",
"extension_commands_global_registry.h",
"extension_context_menu_model.cc",
"extension_context_menu_model.h",
- "extension_cookie_notifier.cc",
- "extension_cookie_notifier.h",
"extension_disabled_ui.cc",
"extension_disabled_ui.h",
"extension_error_controller.cc",
@@ -691,6 +685,7 @@ jumbo_static_library("extensions") {
"suspicious_extension_bubble_delegate.h",
"sync_bundle.cc",
"sync_bundle.h",
+ "system_display/display_info_provider.h",
"system_display/display_info_provider_chromeos.cc",
"system_display/display_info_provider_chromeos.h",
"system_display/display_info_provider_mac.cc",
@@ -766,13 +761,16 @@ jumbo_static_library("extensions") {
# browser, then we can clean up these dependencies.
public_deps = [
"//chrome/browser/extensions/api:api_registration",
+ "//chrome/common",
"//chrome/common/extensions/api",
"//components/safe_browsing:csd_proto",
"//components/safe_browsing/db:util",
+ "//components/signin/core/browser",
"//content/public/browser",
]
deps = [
"//apps",
+ "//build:branding_buildflags",
"//chrome:extra_resources",
"//chrome:resources",
"//chrome:strings",
@@ -790,7 +788,6 @@ jumbo_static_library("extensions") {
"//chrome/browser/safe_browsing",
"//chrome/browser/web_applications/components",
"//chrome/browser/web_applications/extensions",
- "//chrome/common",
"//chrome/common/extensions/api:extensions_features",
"//chrome/common/safe_browsing:proto",
"//chrome/services/removable_storage_writer/public/mojom",
@@ -802,6 +799,7 @@ jumbo_static_library("extensions") {
"//components/browsing_data/core",
"//components/bubble",
"//components/content_settings/core/browser",
+ "//components/cookie_config:cookie_config",
"//components/crx_file",
"//components/data_reduction_proxy/core/browser",
"//components/dom_distiller/core",
@@ -823,6 +821,7 @@ jumbo_static_library("extensions") {
"//components/omnibox/browser",
"//components/onc",
"//components/password_manager/core/browser",
+ "//components/password_manager/core/browser:affiliation",
"//components/payments/core",
"//components/pdf/browser",
"//components/policy:generated",
@@ -838,14 +837,14 @@ jumbo_static_library("extensions") {
"//components/search_engines",
"//components/services/unzip/public/cpp",
"//components/sessions",
- "//components/signin/core/browser",
+ "//components/signin/public/identity_manager",
"//components/spellcheck/browser",
"//components/storage_monitor",
"//components/strings",
"//components/sync",
"//components/sync_preferences",
"//components/sync_sessions",
- "//components/translate/core/browser",
+ "//components/translate/content/browser",
"//components/undo",
"//components/unified_consent",
"//components/update_client",
@@ -876,7 +875,7 @@ jumbo_static_library("extensions") {
"//services/audio/public/cpp",
"//services/data_decoder/public/cpp",
"//services/device/public/mojom",
- "//services/identity/public/cpp",
+ "//services/identity/public/cpp:cpp_types",
"//services/identity/public/mojom",
"//services/network/public/mojom",
"//services/service_manager/public/cpp",
@@ -982,8 +981,10 @@ jumbo_static_library("extensions") {
"//chromeos/dbus/cryptohome",
"//chromeos/dbus/power",
"//chromeos/disks",
+ "//chromeos/login/auth",
"//chromeos/login/login_state",
"//chromeos/network",
+ "//chromeos/services/assistant/public/cpp:prefs",
"//chromeos/services/ime/public/mojom",
"//chromeos/services/machine_learning/public/cpp",
"//chromeos/services/machine_learning/public/mojom",
@@ -1008,13 +1009,6 @@ jumbo_static_library("extensions") {
"//ui/ozone",
"//ui/views",
]
- if (enable_kiosk_next) {
- defines += [ "KIOSK_NEXT" ]
- deps += [ "//chrome/browser/chromeos/kiosk_next_home/mojom" ]
- if (is_chrome_branded) {
- deps += [ "//chrome/browser/resources:kiosk_next_internal_resources" ]
- }
- }
if (enable_nacl) {
deps += [ "//chrome/browser/resources/chromeos/zip_archiver" ]
}
@@ -1030,6 +1024,8 @@ jumbo_static_library("extensions") {
"api/image_writer_private/removable_storage_provider_linux.cc",
"api/messaging/native_message_process_host.cc",
"api/messaging/native_message_process_host.h",
+ "api/messaging/native_messaging_launch_from_native.cc",
+ "api/messaging/native_messaging_launch_from_native.h",
"api/messaging/native_process_launcher.cc",
"api/messaging/native_process_launcher.h",
"api/messaging/native_process_launcher_win.cc",
diff --git a/chromium/chrome/browser/extensions/api/BUILD.gn b/chromium/chrome/browser/extensions/api/BUILD.gn
index d6ca561c0b3..96fe20b67da 100644
--- a/chromium/chrome/browser/extensions/api/BUILD.gn
+++ b/chromium/chrome/browser/extensions/api/BUILD.gn
@@ -21,6 +21,7 @@ function_registration("api_registration") {
deps = [
# Different APIs include headers from these targets.
+ "//chrome/common:mojo_bindings",
"//content/public/browser",
"//extensions/browser",
diff --git a/chromium/chrome/browser/extensions/api/activity_log_private/OWNERS b/chromium/chrome/browser/extensions/api/activity_log_private/OWNERS
index e3ff774e42d..d0a8779743c 100644
--- a/chromium/chrome/browser/extensions/api/activity_log_private/OWNERS
+++ b/chromium/chrome/browser/extensions/api/activity_log_private/OWNERS
@@ -1,4 +1,3 @@
# If you are editing this file, please also update
# chrome/browser/extensions/activity_log/OWNERS
rdevlin.cronin@chromium.org
-asargent@chromium.org
diff --git a/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc b/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc
index bb1a099e82a..bca9fda86c7 100644
--- a/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc
@@ -89,6 +89,16 @@ class AutomationApiTest : public ExtensionApiTest {
base::test::ScopedFeatureList scoped_feature_list_;
};
+// Canvas tests rely on the harness producing pixel output in order to read back
+// pixels from a canvas element. So we have to override the setup function.
+class AutomationApiCanvasTest : public AutomationApiTest {
+ public:
+ void SetUp() override {
+ EnablePixelOutput();
+ ExtensionApiTest::SetUp();
+ }
+};
+
IN_PROC_BROWSER_TEST_F(AutomationApiTest, TestRendererAccessibilityEnabled) {
StartEmbeddedTestServer();
const GURL url = GetURLForPath(kDomain, "/index.html");
@@ -189,7 +199,7 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, LineStartOffsets) {
<< message_;
}
-IN_PROC_BROWSER_TEST_F(AutomationApiTest, ImageData) {
+IN_PROC_BROWSER_TEST_F(AutomationApiCanvasTest, ImageData) {
StartEmbeddedTestServer();
ASSERT_TRUE(RunExtensionSubtest("automation/tests/tabs", "image_data.html"))
<< message_;
@@ -380,6 +390,13 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, HitTest) {
<< message_;
}
+IN_PROC_BROWSER_TEST_F(AutomationApiTest, WordBoundaries) {
+ StartEmbeddedTestServer();
+ ASSERT_TRUE(
+ RunExtensionSubtest("automation/tests/tabs", "word_boundaries.html"))
+ << message_;
+}
+
class AutomationApiTestWithLanguageDetection : public AutomationApiTest {
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
diff --git a/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc
index 54c5f9eeacc..42aa452c796 100644
--- a/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc
@@ -36,6 +36,7 @@
#include "components/undo/bookmark_undo_service.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/render_view_host.h"
+#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "extensions/browser/extension_function_dispatcher.h"
@@ -110,9 +111,8 @@ CreateNodeDataElementFromBookmarkNode(const BookmarkNode& node) {
element.url.reset(new std::string(node.url().spec()));
element.title = base::UTF16ToUTF8(node.GetTitle());
- for (int i = 0; i < node.child_count(); ++i) {
- element.children.push_back(
- CreateNodeDataElementFromBookmarkNode(*node.GetChild(i)));
+ for (const auto& child : node.children()) {
+ element.children.push_back(CreateNodeDataElementFromBookmarkNode(*child));
}
return element;
@@ -354,15 +354,18 @@ bool BookmarkManagerPrivatePasteFunction::RunOnReady() {
// No need to test return value, if we got an empty list, we insert at end.
if (params->selected_id_list)
GetNodesFromVector(model, *params->selected_id_list, &nodes);
- int highest_index = -1; // -1 means insert at end of list.
+ int highest_index = -1;
for (size_t i = 0; i < nodes.size(); ++i) {
// + 1 so that we insert after the selection.
int index = parent_node->GetIndexOf(nodes[i]) + 1;
if (index > highest_index)
highest_index = index;
}
+ size_t insertion_index = (highest_index == -1)
+ ? parent_node->children().size()
+ : size_t{highest_index};
- bookmarks::PasteFromClipboard(model, parent_node, highest_index);
+ bookmarks::PasteFromClipboard(model, parent_node, insertion_index);
return true;
}
@@ -408,12 +411,9 @@ bool BookmarkManagerPrivateStartDragFunction::RunOnReady() {
source = ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
chrome::DragBookmarks(GetProfile(),
- {
- std::move(nodes), params->drag_node_index,
- platform_util::GetViewForWindow(
- web_contents->GetTopLevelNativeWindow()),
- source,
- });
+ {std::move(nodes), params->drag_node_index,
+ web_contents->GetContentNativeView(), source,
+ gfx::Point(params->x, params->y)});
return true;
}
@@ -433,26 +433,20 @@ bool BookmarkManagerPrivateDropFunction::RunOnReady() {
return false;
content::WebContents* web_contents = GetSenderWebContents();
- if (GetViewType(web_contents) != VIEW_TYPE_TAB_CONTENTS) {
- NOTREACHED();
- return false;
- }
+ DCHECK_EQ(VIEW_TYPE_TAB_CONTENTS, GetViewType(web_contents));
- int drop_index;
+ size_t drop_index;
if (params->index)
- drop_index = *params->index;
+ drop_index = size_t{*params->index};
else
- drop_index = drop_parent->child_count();
+ drop_index = drop_parent->children().size();
BookmarkManagerPrivateDragEventRouter* router =
BookmarkManagerPrivateDragEventRouter::FromWebContents(web_contents);
DCHECK(router);
const BookmarkNodeData* drag_data = router->GetBookmarkNodeData();
- if (drag_data == NULL) {
- NOTREACHED() <<"Somehow we're dropping null bookmark data";
- return false;
- }
+ DCHECK_NE(nullptr, drag_data) << "Somehow we're dropping null bookmark data";
const bool copy = false;
chrome::DropBookmarks(
GetProfile(), *drag_data, drop_parent, drop_index, copy);
diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers.cc
index 4a0be820b9b..f358ee31131 100644
--- a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers.cc
+++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers.cc
@@ -93,11 +93,10 @@ void PopulateBookmarkTreeNode(
if (recurse && node->is_folder()) {
std::vector<BookmarkTreeNode> children;
- for (int i = 0; i < node->child_count(); ++i) {
- const BookmarkNode* child = node->GetChild(i);
+ for (const auto& child : node->children()) {
if (child->IsVisible() && (!only_folders || child->is_folder())) {
children.push_back(
- GetBookmarkTreeNode(managed, child, true, only_folders));
+ GetBookmarkTreeNode(managed, child.get(), true, only_folders));
}
}
out_bookmark_tree_node->children.reset(
@@ -162,9 +161,8 @@ void GetMetaInfo(const BookmarkNode& node,
id_to_meta_info_map->Set(base::NumberToString(node.id()), std::move(value));
if (node.is_folder()) {
- for (int i = 0; i < node.child_count(); ++i) {
- GetMetaInfo(*(node.GetChild(i)), id_to_meta_info_map);
- }
+ for (const auto& child : node.children())
+ GetMetaInfo(*child, id_to_meta_info_map);
}
}
diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc
index b0e82903da9..81209a9ac4b 100644
--- a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc
@@ -165,10 +165,10 @@ TEST_F(ExtensionBookmarksTest, RemoveNodeNotRecursive) {
}
TEST_F(ExtensionBookmarksTest, RemoveNodeRecursive) {
- EXPECT_EQ(3, model_->other_node()->child_count());
+ EXPECT_EQ(3u, model_->other_node()->children().size());
std::string error;
EXPECT_TRUE(RemoveNode(model_, managed_, folder_->id(), true, &error));
- EXPECT_EQ(2, model_->other_node()->child_count());
+ EXPECT_EQ(2u, model_->other_node()->children().size());
}
TEST_F(ExtensionBookmarksTest, GetMetaInfo) {
diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc
index 51335d49624..5d4a47cb64b 100644
--- a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc
@@ -42,7 +42,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Bookmarks) {
node->Set("children", std::make_unique<base::ListValue>());
list.Append(std::move(node));
profile->GetPrefs()->Set(bookmarks::prefs::kManagedBookmarks, list);
- ASSERT_EQ(2, managed->managed_node()->child_count());
+ ASSERT_EQ(2u, managed->managed_node()->children().size());
ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_;
}
diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc
index 2739f25014e..3ee926982f7 100644
--- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc
+++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc
@@ -148,21 +148,22 @@ const BookmarkNode* BookmarksFunction::CreateBookmarkNode(
parentId = model->other_node()->id();
} else {
if (!GetBookmarkIdAsInt64(*details.parent_id, &parentId))
- return NULL;
+ return nullptr;
}
const BookmarkNode* parent = bookmarks::GetBookmarkNodeByID(model, parentId);
if (!CanBeModified(parent))
- return NULL;
+ return nullptr;
- int index;
+ size_t index;
if (!details.index.get()) { // Optional (defaults to end).
- index = parent->child_count();
+ index = parent->children().size();
} else {
- index = *details.index;
- if (index > parent->child_count() || index < 0) {
+ if (*details.index < 0 ||
+ size_t{*details.index} > parent->children().size()) {
error_ = bookmark_api_constants::kInvalidIndexError;
- return NULL;
+ return nullptr;
}
+ index = size_t{*details.index};
}
base::string16 title; // Optional.
@@ -176,7 +177,7 @@ const BookmarkNode* BookmarksFunction::CreateBookmarkNode(
GURL url(url_string);
if (!url_string.empty() && !url.is_valid()) {
error_ = bookmark_api_constants::kInvalidUrlError;
- return NULL;
+ return nullptr;
}
const BookmarkNode* node;
@@ -275,15 +276,15 @@ void BookmarkEventRouter::BookmarkModelBeingDeleted(BookmarkModel* model) {
void BookmarkEventRouter::BookmarkNodeMoved(BookmarkModel* model,
const BookmarkNode* old_parent,
- int old_index,
+ size_t old_index,
const BookmarkNode* new_parent,
- int new_index) {
- const BookmarkNode* node = new_parent->GetChild(new_index);
+ size_t new_index) {
+ const BookmarkNode* node = new_parent->children()[new_index].get();
api::bookmarks::OnMoved::MoveInfo move_info;
move_info.parent_id = base::NumberToString(new_parent->id());
- move_info.index = new_index;
+ move_info.index = int{new_index};
move_info.old_parent_id = base::NumberToString(old_parent->id());
- move_info.old_index = old_index;
+ move_info.old_index = int{old_index};
DispatchEvent(events::BOOKMARKS_ON_MOVED, api::bookmarks::OnMoved::kEventName,
api::bookmarks::OnMoved::Create(
@@ -292,8 +293,8 @@ void BookmarkEventRouter::BookmarkNodeMoved(BookmarkModel* model,
void BookmarkEventRouter::BookmarkNodeAdded(BookmarkModel* model,
const BookmarkNode* parent,
- int index) {
- const BookmarkNode* node = parent->GetChild(index);
+ size_t index) {
+ const BookmarkNode* node = parent->children()[index].get();
BookmarkTreeNode tree_node =
bookmark_api_helpers::GetBookmarkTreeNode(managed_, node, false, false);
DispatchEvent(events::BOOKMARKS_ON_CREATED,
@@ -305,12 +306,12 @@ void BookmarkEventRouter::BookmarkNodeAdded(BookmarkModel* model,
void BookmarkEventRouter::BookmarkNodeRemoved(
BookmarkModel* model,
const BookmarkNode* parent,
- int index,
+ size_t index,
const BookmarkNode* node,
const std::set<GURL>& removed_urls) {
api::bookmarks::OnRemoved::RemoveInfo remove_info;
remove_info.parent_id = base::NumberToString(parent->id());
- remove_info.index = index;
+ remove_info.index = int{index};
bookmark_api_helpers::PopulateBookmarkTreeNode(managed_, node, true, false,
&remove_info.node);
@@ -356,11 +357,8 @@ void BookmarkEventRouter::BookmarkNodeChildrenReordered(
BookmarkModel* model,
const BookmarkNode* node) {
api::bookmarks::OnChildrenReordered::ReorderInfo reorder_info;
- int childCount = node->child_count();
- for (int i = 0; i < childCount; ++i) {
- const BookmarkNode* child = node->GetChild(i);
+ for (const auto& child : node->children())
reorder_info.child_ids.push_back(base::NumberToString(child->id()));
- }
DispatchEvent(events::BOOKMARKS_ON_CHILDREN_REORDERED,
api::bookmarks::OnChildrenReordered::kEventName,
@@ -457,11 +455,9 @@ bool BookmarksGetChildrenFunction::RunOnReady() {
return false;
std::vector<BookmarkTreeNode> nodes;
- int child_count = node->child_count();
- for (int i = 0; i < child_count; ++i) {
- const BookmarkNode* child = node->GetChild(i);
- bookmark_api_helpers::AddNode(GetManagedBookmarkService(), child, &nodes,
- false);
+ for (const auto& child : node->children()) {
+ bookmark_api_helpers::AddNode(GetManagedBookmarkService(), child.get(),
+ &nodes, false);
}
results_ = api::bookmarks::GetChildren::Results::Create(nodes);
@@ -640,15 +636,16 @@ bool BookmarksMoveFunction::RunOnReady() {
if (!CanBeModified(parent) || !CanBeModified(node))
return false;
- int index;
+ size_t index;
if (params->destination.index.get()) { // Optional (defaults to end).
- index = *params->destination.index;
- if (index > parent->child_count() || index < 0) {
+ if (*params->destination.index < 0 ||
+ size_t{*params->destination.index} > parent->children().size()) {
error_ = bookmark_api_constants::kInvalidIndexError;
return false;
}
+ index = size_t{*params->destination.index};
} else {
- index = parent->child_count();
+ index = parent->children().size();
}
model->Move(node, parent, index);
diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h
index 52cde39d952..f832d8fc254 100644
--- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h
+++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h
@@ -56,15 +56,15 @@ class BookmarkEventRouter : public bookmarks::BookmarkModelObserver {
void BookmarkModelBeingDeleted(bookmarks::BookmarkModel* model) override;
void BookmarkNodeMoved(bookmarks::BookmarkModel* model,
const bookmarks::BookmarkNode* old_parent,
- int old_index,
+ size_t old_index,
const bookmarks::BookmarkNode* new_parent,
- int new_index) override;
+ size_t new_index) override;
void BookmarkNodeAdded(bookmarks::BookmarkModel* model,
const bookmarks::BookmarkNode* parent,
- int index) override;
+ size_t index) override;
void BookmarkNodeRemoved(bookmarks::BookmarkModel* model,
const bookmarks::BookmarkNode* parent,
- int old_index,
+ size_t old_index,
const bookmarks::BookmarkNode* node,
const std::set<GURL>& removed_urls) override;
void BookmarkAllUserNodesRemoved(bookmarks::BookmarkModel* model,
diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc
index e8fe2049f54..cd22764d64c 100644
--- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc
+++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc
@@ -27,6 +27,7 @@
#include "chrome/common/chrome_features.h"
#include "chrome/common/pref_names.h"
#include "components/browsing_data/core/pref_names.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/browsing_data_filter_builder.h"
@@ -34,7 +35,6 @@
#include "extensions/common/error_utils.h"
#include "extensions/common/extension.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
-#include "services/identity/public/cpp/identity_manager.h"
using content::BrowserThread;
using browsing_data::ClearBrowsingDataTab;
diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc
index 5868403c777..e72b5ae5c9b 100644
--- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc
+++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc
@@ -19,8 +19,9 @@
#include "chrome/browser/sync/sync_ui_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
-#include "components/signin/core/browser/account_reconcilor.h"
-#include "components/signin/core/browser/signin_buildflags.h"
+#include "components/signin/public/base/signin_buildflags.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/sync/driver/sync_service.h"
#include "components/sync/driver/sync_user_settings.h"
#include "content/public/browser/storage_partition.h"
@@ -28,8 +29,6 @@
#include "google_apis/gaia/google_service_auth_error.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "net/cookies/canonical_cookie.h"
-#include "services/identity/public/cpp/identity_manager.h"
-#include "services/identity/public/cpp/identity_test_utils.h"
#include "url/gurl.h"
using extension_function_test_utils::RunFunctionAndReturnSingleResult;
@@ -96,12 +95,12 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, Syncing) {
const char kPrimaryAccountEmail[] = "primary@email.com";
const char kSecondaryAccountEmail[] = "secondary@email.com";
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
- AccountInfo primary_account_info = identity::MakePrimaryAccountAvailable(
+ AccountInfo primary_account_info = signin::MakePrimaryAccountAvailable(
identity_manager, kPrimaryAccountEmail);
AccountInfo secondary_account_info =
- identity::MakeAccountAvailable(identity_manager, kSecondaryAccountEmail);
+ signin::MakeAccountAvailable(identity_manager, kSecondaryAccountEmail);
// Sync is running.
syncer::SyncService* sync_service =
@@ -133,11 +132,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SyncError) {
ASSERT_TRUE(SetGaiaCookieForProfile(profile));
// Set a Sync account with authentication error.
const char kAccountEmail[] = "account@email.com";
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
AccountInfo account_info =
- identity::MakePrimaryAccountAvailable(identity_manager, kAccountEmail);
- identity::UpdatePersistentErrorOfRefreshTokenForAccount(
+ signin::MakePrimaryAccountAvailable(identity_manager, kAccountEmail);
+ signin::UpdatePersistentErrorOfRefreshTokenForAccount(
identity_manager, account_info.account_id,
GoogleServiceAuthError::FromInvalidGaiaCredentialsReason(
GoogleServiceAuthError::InvalidGaiaCredentialsReason::
@@ -169,7 +168,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, NotSyncing) {
const char kAccountEmail[] = "account@email.com";
auto* identity_manager = IdentityManagerFactory::GetForProfile(profile);
AccountInfo account_info =
- identity::MakeAccountAvailable(identity_manager, kAccountEmail);
+ signin::MakeAccountAvailable(identity_manager, kAccountEmail);
// Clear browsing data.
auto function = base::MakeRefCounted<BrowsingDataRemoveFunction>();
EXPECT_EQ(NULL, RunFunctionAndReturnSingleResult(
diff --git a/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc b/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc
index 9148d2dc8cd..a94ea2115e3 100644
--- a/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc
@@ -434,9 +434,13 @@ IN_PROC_BROWSER_TEST_P(CastStreamingApiTestWithPixelOutput,
// removed after launch. Note: CastStreamingApiTestWithPixelOutput.EndToEnd is
// the only integration test exercising audio service loopback streams, so it's
// a very important test to have.
-#if (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_MACOSX) || \
- defined(OS_WIN)
-// Supported platforms.
+#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
+// Platforms launched on.
+INSTANTIATE_TEST_SUITE_P(,
+ CastStreamingApiTestWithPixelOutput,
+ ::testing::Values(true));
+#elif defined(OS_MACOSX) || defined(OS_WIN)
+// Supported platforms but not launched on.
INSTANTIATE_TEST_SUITE_P(,
CastStreamingApiTestWithPixelOutput,
::testing::Bool());
diff --git a/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc b/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc
index d06ede354bc..13f5fbcb8f1 100644
--- a/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc
+++ b/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc
@@ -659,7 +659,8 @@ const char CastV2PerformanceTest::kTestName[] = "CastV2Performance";
} // namespace
-IN_PROC_BROWSER_TEST_P(CastV2PerformanceTest, Performance) {
+// TODO(https://crbug.com/974427) Disabled due to flakiness.
+IN_PROC_BROWSER_TEST_P(CastV2PerformanceTest, DISABLED_Performance) {
net::IPEndPoint receiver_end_point = media::cast::test::GetFreeLocalPort();
VLOG(1) << "Got local UDP port for testing: "
<< receiver_end_point.ToString();
diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc
index 26a9d407d94..42b5813d2a5 100644
--- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc
+++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc
@@ -14,6 +14,7 @@
#include "base/logging.h"
#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h"
#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h"
+#include "chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h"
#include "chrome/common/extensions/api/certificate_provider.h"
#include "chrome/common/extensions/api/certificate_provider_internal.h"
#include "net/cert/x509_certificate.h"
@@ -66,6 +67,7 @@ const char kCertificateProviderErrorTimeout[] =
const char kCertificateProviderNoActiveDialog[] =
"No active dialog from extension.";
const char kCertificateProviderInvalidId[] = "Invalid signRequestId";
+const char kCertificateProviderInvalidAttemptsLeft[] = "Invalid attemptsLeft";
const char kCertificateProviderOtherFlowInProgress[] = "Other flow in progress";
const char kCertificateProviderPreviousDialogActive[] =
"Previous request not finished";
@@ -216,18 +218,18 @@ CertificateProviderStopPinRequestFunction::Run() {
// the error and not allow any more input.
chromeos::RequestPinView::RequestPinErrorType error_type =
GetErrorTypeForView(params->details.error_type);
- chromeos::PinDialogManager::StopPinRequestResponse update_response =
- service->pin_dialog_manager()->UpdatePinDialog(
+ const chromeos::PinDialogManager::StopPinRequestResult stop_request_result =
+ service->pin_dialog_manager()->StopPinRequestWithError(
extension()->id(), error_type,
- false, // Don't accept any input.
- base::Bind(&CertificateProviderStopPinRequestFunction::DialogClosed,
- this));
- switch (update_response) {
- case chromeos::PinDialogManager::StopPinRequestResponse::NO_ACTIVE_DIALOG:
+ base::BindOnce(
+ &CertificateProviderStopPinRequestFunction::OnPinRequestStopped,
+ this));
+ switch (stop_request_result) {
+ case chromeos::PinDialogManager::StopPinRequestResult::kNoActiveDialog:
return RespondNow(Error(kCertificateProviderNoActiveDialog));
- case chromeos::PinDialogManager::StopPinRequestResponse::NO_USER_INPUT:
+ case chromeos::PinDialogManager::StopPinRequestResult::kNoUserInput:
return RespondNow(Error(kCertificateProviderNoUserInput));
- case chromeos::PinDialogManager::StopPinRequestResponse::STOPPED:
+ case chromeos::PinDialogManager::StopPinRequestResult::kSuccess:
return RespondLater();
}
@@ -235,8 +237,7 @@ CertificateProviderStopPinRequestFunction::Run() {
return RespondLater();
}
-void CertificateProviderStopPinRequestFunction::DialogClosed(
- const base::string16& value) {
+void CertificateProviderStopPinRequestFunction::OnPinRequestStopped() {
chromeos::CertificateProviderService* const service =
chromeos::CertificateProviderServiceFactory::GetForBrowserContext(
browser_context());
@@ -292,23 +293,27 @@ ExtensionFunction::ResponseAction CertificateProviderRequestPinFunction::Run() {
browser_context());
DCHECK(service);
- int attempts_left =
- params->details.attempts_left ? *params->details.attempts_left : -1;
- chromeos::PinDialogManager::RequestPinResponse result =
- service->pin_dialog_manager()->ShowPinDialog(
+ int attempts_left = -1;
+ if (params->details.attempts_left) {
+ if (*params->details.attempts_left < 0)
+ return RespondNow(Error(kCertificateProviderInvalidAttemptsLeft));
+ attempts_left = *params->details.attempts_left;
+ }
+
+ const chromeos::PinDialogManager::RequestPinResult result =
+ service->pin_dialog_manager()->RequestPin(
extension()->id(), extension()->name(),
params->details.sign_request_id, code_type, error_type, attempts_left,
- base::Bind(&CertificateProviderRequestPinFunction::OnInputReceived,
- this));
+ base::BindOnce(
+ &CertificateProviderRequestPinFunction::OnInputReceived, this));
switch (result) {
- case chromeos::PinDialogManager::RequestPinResponse::SUCCESS:
+ case chromeos::PinDialogManager::RequestPinResult::kSuccess:
return RespondLater();
- case chromeos::PinDialogManager::RequestPinResponse::INVALID_ID:
+ case chromeos::PinDialogManager::RequestPinResult::kInvalidId:
return RespondNow(Error(kCertificateProviderInvalidId));
- case chromeos::PinDialogManager::RequestPinResponse::OTHER_FLOW_IN_PROGRESS:
+ case chromeos::PinDialogManager::RequestPinResult::kOtherFlowInProgress:
return RespondNow(Error(kCertificateProviderOtherFlowInProgress));
- case chromeos::PinDialogManager::RequestPinResponse::
- DIALOG_DISPLAYED_ALREADY:
+ case chromeos::PinDialogManager::RequestPinResult::kDialogDisplayedAlready:
return RespondNow(Error(kCertificateProviderPreviousDialogActive));
}
@@ -317,7 +322,7 @@ ExtensionFunction::ResponseAction CertificateProviderRequestPinFunction::Run() {
}
void CertificateProviderRequestPinFunction::OnInputReceived(
- const base::string16& value) {
+ const std::string& value) {
std::unique_ptr<base::ListValue> create_results(new base::ListValue());
chromeos::CertificateProviderService* const service =
chromeos::CertificateProviderServiceFactory::GetForBrowserContext(
@@ -325,7 +330,7 @@ void CertificateProviderRequestPinFunction::OnInputReceived(
DCHECK(service);
if (!value.empty()) {
api::certificate_provider::PinResponseDetails details;
- details.user_input.reset(new std::string(value.begin(), value.end()));
+ details.user_input = std::make_unique<std::string>(value);
create_results->Append(details.ToValue());
}
diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h
index 62af83e13bf..67b8ee0eabb 100644
--- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h
+++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h
@@ -5,6 +5,8 @@
#ifndef CHROME_BROWSER_EXTENSIONS_API_CERTIFICATE_PROVIDER_CERTIFICATE_PROVIDER_API_H_
#define CHROME_BROWSER_EXTENSIONS_API_CERTIFICATE_PROVIDER_CERTIFICATE_PROVIDER_API_H_
+#include <string>
+
#include "extensions/browser/extension_function.h"
namespace chromeos {
@@ -28,6 +30,7 @@ struct CertificateInfo;
class CertificateProviderInternalReportCertificatesFunction
: public UIThreadExtensionFunction {
private:
+ // UIThreadExtensionFunction:
~CertificateProviderInternalReportCertificatesFunction() override;
ResponseAction Run() override;
@@ -42,6 +45,7 @@ class CertificateProviderInternalReportCertificatesFunction
class CertificateProviderInternalReportSignatureFunction
: public UIThreadExtensionFunction {
private:
+ // UIThreadExtensionFunction:
~CertificateProviderInternalReportSignatureFunction() override;
ResponseAction Run() override;
@@ -51,12 +55,14 @@ class CertificateProviderInternalReportSignatureFunction
class CertificateProviderRequestPinFunction : public UIThreadExtensionFunction {
private:
+ // UIThreadExtensionFunction:
~CertificateProviderRequestPinFunction() override;
ResponseAction Run() override;
bool ShouldSkipQuotaLimiting() const override;
void GetQuotaLimitHeuristics(
extensions::QuotaLimitHeuristics* heuristics) const override;
- void OnInputReceived(const base::string16& value);
+
+ void OnInputReceived(const std::string& value);
DECLARE_EXTENSION_FUNCTION("certificateProvider.requestPin",
CERTIFICATEPROVIDER_REQUESTPIN)
@@ -65,9 +71,11 @@ class CertificateProviderRequestPinFunction : public UIThreadExtensionFunction {
class CertificateProviderStopPinRequestFunction
: public UIThreadExtensionFunction {
private:
+ // UIThreadExtensionFunction:
~CertificateProviderStopPinRequestFunction() override;
ResponseAction Run() override;
- void DialogClosed(const base::string16& value);
+
+ void OnPinRequestStopped();
DECLARE_EXTENSION_FUNCTION("certificateProvider.stopPinRequest",
CERTIFICATEPROVIDER_STOPPINREQUEST)
diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc
index b88a6a08cd4..2a266152d46 100644
--- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc
@@ -16,10 +16,12 @@
#include "base/files/file_util.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
+#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h"
#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h"
+#include "chrome/browser/chromeos/ui/request_pin_view.h"
#include "chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
@@ -107,42 +109,6 @@ std::string JsUint8Array(const std::vector<uint8_t>& bytes) {
return res;
}
-// Enters the code in the ShowPinDialog window and pushes the OK event.
-void EnterCode(chromeos::CertificateProviderService* service,
- const base::string16& code) {
- chromeos::RequestPinView* view =
- service->pin_dialog_manager()->active_view_for_testing();
- view->textfield_for_testing()->SetText(code);
- view->Accept();
- base::RunLoop().RunUntilIdle();
-}
-
-// Enters the valid code for extensions from local example folders, in the
-// ShowPinDialog window and waits for the window to close. The extension code
-// is expected to send "Success" message after the validation and request to
-// stopPinRequest is done.
-void EnterCorrectPin(chromeos::CertificateProviderService* service) {
- ExtensionTestMessageListener listener("Success", false);
- EnterCode(service, base::ASCIIToUTF16("1234"));
- ASSERT_TRUE(listener.WaitUntilSatisfied());
-}
-
-// Enters an invalid code for extensions from local example folders, in the
-// ShowPinDialog window and waits for the window to update with the error. The
-// extension code is expected to send "Invalid PIN" message after the validation
-// and the new requestPin (with the error) is done.
-void EnterWrongPin(chromeos::CertificateProviderService* service) {
- ExtensionTestMessageListener listener("Invalid PIN", false);
- EnterCode(service, base::ASCIIToUTF16("567"));
- ASSERT_TRUE(listener.WaitUntilSatisfied());
-
- // Check that we have an error message displayed.
- chromeos::RequestPinView* view =
- service->pin_dialog_manager()->active_view_for_testing();
- EXPECT_EQ(gfx::kGoogleRed600,
- view->error_label_for_testing()->enabled_color());
-}
-
class CertificateProviderApiTest : public extensions::ExtensionApiTest {
public:
CertificateProviderApiTest() {}
@@ -180,24 +146,111 @@ class CertificateProviderApiTest : public extensions::ExtensionApiTest {
};
class CertificateProviderRequestPinTest : public CertificateProviderApiTest {
- public:
- // Loads certificate_provider extension from |folder| and |file_name|.
- // Returns the CertificateProviderService object from browser context.
- chromeos::CertificateProviderService* LoadRequestPinExtension(
- const std::string& folder,
- const std::string& file_name) {
- const base::FilePath extension_path =
- test_data_dir_.AppendASCII("certificate_provider/" + folder);
- const extensions::Extension* const extension =
- LoadExtension(extension_path);
- chromeos::CertificateProviderService* service =
+ protected:
+ static constexpr int kFakeSignRequestId = 123;
+ static constexpr int kWrongPinAttemptsLimit = 3;
+ static constexpr const char* kCorrectPin = "1234";
+ static constexpr const char* kWrongPin = "567";
+
+ void SetUpOnMainThread() override {
+ CertificateProviderApiTest::SetUpOnMainThread();
+ cert_provider_service_ =
chromeos::CertificateProviderServiceFactory::GetForBrowserContext(
profile());
- service->pin_dialog_manager()->AddSignRequestId(extension->id(), 123);
- ui_test_utils::NavigateToURL(browser(),
- extension->GetResourceURL(file_name));
- return service;
+ command_request_listener_ = std::make_unique<ExtensionTestMessageListener>(
+ "GetCommand", /*will_reply=*/true);
+ LoadRequestPinExtension();
+ }
+
+ void TearDownOnMainThread() override {
+ if (command_request_listener_->was_satisfied()) {
+ // Avoid destroying a non-replied extension function without.
+ command_request_listener_->Reply(/*message=*/std::string());
+ }
+ command_request_listener_.reset();
+ CertificateProviderApiTest::TearDownOnMainThread();
+ }
+
+ void AddFakeSignRequest() {
+ cert_provider_service_->pin_dialog_manager()->AddSignRequestId(
+ extension_->id(), kFakeSignRequestId);
+ }
+
+ void NavigateTo(const std::string& test_page_file_name) {
+ ui_test_utils::NavigateToURL(
+ browser(), extension_->GetResourceURL(test_page_file_name));
+ }
+
+ chromeos::RequestPinView* GetActivePinDialogView() {
+ return cert_provider_service_->pin_dialog_manager()
+ ->active_view_for_testing();
}
+
+ views::Widget* GetActivePinDialogWindow() {
+ return cert_provider_service_->pin_dialog_manager()
+ ->active_window_for_testing();
+ }
+
+ // Enters the code in the ShowPinDialog window and pushes the OK event.
+ void EnterCode(const std::string& code) {
+ GetActivePinDialogView()->textfield_for_testing()->SetText(
+ base::ASCIIToUTF16(code));
+ GetActivePinDialogView()->Accept();
+ base::RunLoop().RunUntilIdle();
+ }
+
+ // Enters the valid code for extensions from local example folders, in the
+ // ShowPinDialog window and waits for the window to close. The extension code
+ // is expected to send "Success" message after the validation and request to
+ // stopPinRequest is done.
+ void EnterCorrectPinAndWaitForMessage() {
+ ExtensionTestMessageListener listener("Success", false);
+ EnterCode(kCorrectPin);
+ ASSERT_TRUE(listener.WaitUntilSatisfied());
+ }
+
+ // Enters an invalid code for extensions from local example folders, in the
+ // ShowPinDialog window and waits for the window to update with the error. The
+ // extension code is expected to send "Invalid PIN" message after the
+ // validation and the new requestPin (with the error) is done.
+ void EnterWrongPinAndWaitForMessage() {
+ ExtensionTestMessageListener listener("Invalid PIN", false);
+ EnterCode(kWrongPin);
+ ASSERT_TRUE(listener.WaitUntilSatisfied());
+
+ // Check that we have an error message displayed.
+ EXPECT_EQ(
+ gfx::kGoogleRed600,
+ GetActivePinDialogView()->error_label_for_testing()->GetEnabledColor());
+ }
+
+ bool SendCommand(const std::string& command) {
+ if (!command_request_listener_->WaitUntilSatisfied())
+ return false;
+ command_request_listener_->Reply(command);
+ command_request_listener_->Reset();
+ return true;
+ }
+
+ bool SendCommandAndWaitForMessage(const std::string& command,
+ const std::string& expected_message) {
+ ExtensionTestMessageListener listener(expected_message,
+ /*will_reply=*/false);
+ if (!SendCommand(command))
+ return false;
+ return listener.WaitUntilSatisfied();
+ }
+
+ private:
+ void LoadRequestPinExtension() {
+ const base::FilePath extension_path =
+ test_data_dir_.AppendASCII("certificate_provider/request_pin");
+ extension_ = LoadExtension(extension_path);
+ }
+
+ chromeos::CertificateProviderService* cert_provider_service_ = nullptr;
+ const extensions::Extension* extension_ = nullptr;
+ std::unique_ptr<ExtensionTestMessageListener> command_request_listener_;
};
} // namespace
@@ -298,7 +351,7 @@ IN_PROC_BROWSER_TEST_F(CertificateProviderApiTest, Basic) {
// chrome/test/data/extensions/api_test/certificate_provider/l1_leaf.der
ASSERT_EQ(
"got client cert with fingerprint: "
- "2ab3f55e06eb8b36a741fe285a769da45edb2695",
+ "edeb84ab3b5a36dd09a3203c74794b25efa8f126",
https_reply);
}
@@ -317,96 +370,268 @@ IN_PROC_BROWSER_TEST_F(CertificateProviderApiTest, Basic) {
// User enters the correct PIN.
IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, ShowPinDialogAccept) {
- chromeos::CertificateProviderService* service =
- LoadRequestPinExtension("request_pin", "basic.html");
+ AddFakeSignRequest();
+ NavigateTo("basic.html");
// Enter the valid PIN.
- EnterCorrectPin(service);
+ EnterCorrectPinAndWaitForMessage();
// The view should be set to nullptr when the window is closed.
- EXPECT_EQ(service->pin_dialog_manager()->active_view_for_testing(), nullptr);
+ EXPECT_FALSE(GetActivePinDialogView());
}
// User closes the dialog kMaxClosedDialogsPer10Mins times, and the extension
// should be blocked from showing it again.
IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, ShowPinDialogClose) {
- chromeos::CertificateProviderService* service =
- LoadRequestPinExtension("request_pin", "basic.html");
+ AddFakeSignRequest();
+ NavigateTo("basic.html");
- views::Widget* window =
- service->pin_dialog_manager()->active_window_for_testing();
for (int i = 0;
i < extensions::api::certificate_provider::kMaxClosedDialogsPer10Mins;
i++) {
ExtensionTestMessageListener listener("User closed the dialog", false);
- window->Close();
+ GetActivePinDialogWindow()->Close();
ASSERT_TRUE(listener.WaitUntilSatisfied());
- window = service->pin_dialog_manager()->active_window_for_testing();
}
ExtensionTestMessageListener close_listener("User closed the dialog", true);
- window->Close();
+ GetActivePinDialogWindow()->Close();
ASSERT_TRUE(close_listener.WaitUntilSatisfied());
close_listener.Reply("GetLastError");
ExtensionTestMessageListener last_error_listener(
"This request exceeds the MAX_PIN_DIALOGS_CLOSED_PER_10_MINUTES quota.",
false);
ASSERT_TRUE(last_error_listener.WaitUntilSatisfied());
- EXPECT_EQ(service->pin_dialog_manager()->active_view_for_testing(), nullptr);
+ EXPECT_FALSE(GetActivePinDialogView());
}
// User enters a wrong PIN first and a correct PIN on the second try.
IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest,
ShowPinDialogWrongPin) {
- chromeos::CertificateProviderService* service =
- LoadRequestPinExtension("request_pin", "basic.html");
- EnterWrongPin(service);
+ AddFakeSignRequest();
+ NavigateTo("basic.html");
+ EnterWrongPinAndWaitForMessage();
// The window should be active.
- EXPECT_EQ(
- service->pin_dialog_manager()->active_window_for_testing()->IsVisible(),
- true);
- EXPECT_NE(service->pin_dialog_manager()->active_view_for_testing(), nullptr);
+ EXPECT_TRUE(GetActivePinDialogWindow()->IsVisible());
+ EXPECT_TRUE(GetActivePinDialogView());
// Enter the valid PIN.
- EnterCorrectPin(service);
+ EnterCorrectPinAndWaitForMessage();
// The view should be set to nullptr when the window is closed.
- EXPECT_EQ(service->pin_dialog_manager()->active_view_for_testing(), nullptr);
+ EXPECT_FALSE(GetActivePinDialogView());
}
// User enters wrong PIN three times.
IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest,
ShowPinDialogWrongPinThreeTimes) {
- chromeos::CertificateProviderService* service =
- LoadRequestPinExtension("request_pin", "basic.html");
- for (int i = 0; i < 3; i++) {
- EnterWrongPin(service);
- }
-
- chromeos::RequestPinView* view =
- service->pin_dialog_manager()->active_view_for_testing();
+ AddFakeSignRequest();
+ NavigateTo("basic.html");
+ for (int i = 0; i < kWrongPinAttemptsLimit; i++)
+ EnterWrongPinAndWaitForMessage();
// The textfield has to be disabled, as extension does not allow input now.
- EXPECT_EQ(view->textfield_for_testing()->GetEnabled(), false);
+ EXPECT_FALSE(GetActivePinDialogView()->textfield_for_testing()->GetEnabled());
// Close the dialog.
ExtensionTestMessageListener listener("No attempt left", false);
- service->pin_dialog_manager()->active_window_for_testing()->Close();
+ GetActivePinDialogWindow()->Close();
ASSERT_TRUE(listener.WaitUntilSatisfied());
- EXPECT_EQ(service->pin_dialog_manager()->active_view_for_testing(), nullptr);
+ EXPECT_FALSE(GetActivePinDialogView());
}
// User closes the dialog while the extension is processing the request.
IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest,
ShowPinDialogCloseWhileProcessing) {
- chromeos::CertificateProviderService* service =
- LoadRequestPinExtension("request_pin", "basic_lock.html");
+ AddFakeSignRequest();
+ NavigateTo("operated.html");
+
+ EXPECT_TRUE(SendCommandAndWaitForMessage("Request", "request1:begun"));
+ ExtensionTestMessageListener listener(
+ base::StringPrintf("request1:success:%s", kWrongPin), false);
+ EnterCode(kWrongPin);
+ EXPECT_TRUE(listener.WaitUntilSatisfied());
- EnterCode(service, base::ASCIIToUTF16("123"));
- service->pin_dialog_manager()->active_window_for_testing()->Close();
+ GetActivePinDialogWindow()->Close();
base::RunLoop().RunUntilIdle();
// The view should be set to nullptr when the window is closed.
- EXPECT_EQ(service->pin_dialog_manager()->active_view_for_testing(), nullptr);
+ EXPECT_FALSE(GetActivePinDialogView());
+}
+
+// Extension closes the dialog kMaxClosedDialogsPer10Mins times after the user
+// inputs some value, and it should be blocked from showing it again.
+IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest,
+ RepeatedProgrammaticCloseAfterInput) {
+ NavigateTo("operated.html");
+
+ for (int i = 0;
+ i <
+ extensions::api::certificate_provider::kMaxClosedDialogsPer10Mins + 1;
+ i++) {
+ AddFakeSignRequest();
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "Request", base::StringPrintf("request%d:begun", i + 1)));
+
+ EnterCode(kCorrectPin);
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "Stop", base::StringPrintf("stop%d:success", i + 1)));
+ EXPECT_FALSE(GetActivePinDialogView());
+ }
+
+ AddFakeSignRequest();
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "Request",
+ base::StringPrintf(
+ "request%d:error:This request exceeds the "
+ "MAX_PIN_DIALOGS_CLOSED_PER_10_MINUTES quota.",
+ extensions::api::certificate_provider::kMaxClosedDialogsPer10Mins +
+ 2)));
+ EXPECT_FALSE(GetActivePinDialogView());
+}
+
+// Extension erroneously attempts to close the PIN dialog twice.
+IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, DoubleClose) {
+ AddFakeSignRequest();
+ NavigateTo("operated.html");
+
+ EXPECT_TRUE(SendCommand("Request"));
+ EXPECT_TRUE(SendCommandAndWaitForMessage("Stop", "stop1:success"));
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "Stop", "stop2:error:No active dialog from extension."));
+ EXPECT_FALSE(GetActivePinDialogView());
+}
+
+// Extension closes the dialog kMaxClosedDialogsPer10Mins times before the user
+// inputs anything, and it should be blocked from showing it again.
+IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest,
+ RepeatedProgrammaticCloseBeforeInput) {
+ NavigateTo("operated.html");
+
+ for (int i = 0;
+ i <
+ extensions::api::certificate_provider::kMaxClosedDialogsPer10Mins + 1;
+ i++) {
+ AddFakeSignRequest();
+ EXPECT_TRUE(SendCommand("Request"));
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "Stop", base::StringPrintf("stop%d:success", i + 1)));
+ EXPECT_FALSE(GetActivePinDialogView());
+ }
+
+ AddFakeSignRequest();
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "Request",
+ base::StringPrintf(
+ "request%d:error:This request exceeds the "
+ "MAX_PIN_DIALOGS_CLOSED_PER_10_MINUTES quota.",
+ extensions::api::certificate_provider::kMaxClosedDialogsPer10Mins +
+ 2)));
+ EXPECT_FALSE(GetActivePinDialogView());
+}
+
+// Extension erroneously attempts to stop the PIN request with an error before
+// the user provided any input.
+IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest,
+ StopWithErrorBeforeInput) {
+ AddFakeSignRequest();
+ NavigateTo("operated.html");
+
+ EXPECT_TRUE(SendCommand("Request"));
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "StopWithUnknownError", "stop1:error:No user input received"));
+ EXPECT_TRUE(GetActivePinDialogView()->textfield_for_testing()->GetEnabled());
+}
+
+// Extension erroneously uses an invalid sign request ID.
+IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, InvalidRequestId) {
+ NavigateTo("operated.html");
+
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "Request", "request1:error:Invalid signRequestId"));
+ EXPECT_FALSE(GetActivePinDialogView());
+}
+
+// Extension specifies zero left attempts in the very first PIN request.
+IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, ZeroAttemptsAtStart) {
+ AddFakeSignRequest();
+ NavigateTo("operated.html");
+
+ EXPECT_TRUE(SendCommandAndWaitForMessage("RequestWithZeroAttempts",
+ "request1:begun"));
+
+ // The textfield has to be disabled, as there are no attempts left.
+ EXPECT_FALSE(GetActivePinDialogView()->textfield_for_testing()->GetEnabled());
+
+ ExtensionTestMessageListener listener("request1:empty", false);
+ GetActivePinDialogWindow()->Close();
+ EXPECT_TRUE(listener.WaitUntilSatisfied());
+}
+
+// Extension erroneously passes a negative attempts left count.
+IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, NegativeAttempts) {
+ AddFakeSignRequest();
+ NavigateTo("operated.html");
+
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "RequestWithNegativeAttempts", "request1:error:Invalid attemptsLeft"));
+ EXPECT_FALSE(GetActivePinDialogView());
+}
+
+// Extension erroneously attempts to close a non-existing dialog.
+IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, CloseNonExisting) {
+ AddFakeSignRequest();
+ NavigateTo("operated.html");
+
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "Stop", "stop1:error:No active dialog from extension."));
+ EXPECT_FALSE(GetActivePinDialogView());
+}
+
+// Extension erroneously attempts to stop a non-existing dialog with an error.
+IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, StopNonExisting) {
+ AddFakeSignRequest();
+ NavigateTo("operated.html");
+
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "StopWithUnknownError", "stop1:error:No active dialog from extension."));
+ EXPECT_FALSE(GetActivePinDialogView());
+}
+
+// Extension erroneously attempts to start or stop the PIN request before the
+// user closed the previously stopped with an error PIN request.
+IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest,
+ UpdateAlreadyStopped) {
+ AddFakeSignRequest();
+ NavigateTo("operated.html");
+
+ EXPECT_TRUE(SendCommandAndWaitForMessage("Request", "request1:begun"));
+ EnterCode(kWrongPin);
+ EXPECT_TRUE(SendCommand("StopWithUnknownError"));
+
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "StopWithUnknownError", "stop2:error:No user input received"));
+ EXPECT_TRUE(SendCommandAndWaitForMessage(
+ "Request", "request2:error:Previous request not finished"));
+ EXPECT_FALSE(GetActivePinDialogView()->textfield_for_testing()->GetEnabled());
+}
+
+// Extension starts a new PIN request after it stopped the previous one with an
+// error.
+IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, StartAfterStop) {
+ AddFakeSignRequest();
+ NavigateTo("operated.html");
+
+ EXPECT_TRUE(SendCommandAndWaitForMessage("Request", "request1:begun"));
+ EnterCode(kWrongPin);
+ EXPECT_TRUE(SendCommandAndWaitForMessage("Stop", "stop1:success"));
+ EXPECT_FALSE(GetActivePinDialogView());
+
+ EXPECT_TRUE(SendCommandAndWaitForMessage("Request", "request2:begun"));
+ ExtensionTestMessageListener listener(
+ base::StringPrintf("request2:success:%s", kCorrectPin), false);
+ EnterCode(kCorrectPin);
+ EXPECT_TRUE(listener.WaitUntilSatisfied());
+ EXPECT_FALSE(GetActivePinDialogView()->textfield_for_testing()->GetEnabled());
}
diff --git a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc
index 4b71741d26c..b8070abbf3d 100644
--- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc
+++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc
@@ -12,7 +12,6 @@
#include "base/strings/string_util.h"
#include "base/task/post_task.h"
#include "build/build_config.h"
-#include "chrome/browser/data_use_measurement/data_use_web_contents_observer.h"
#include "chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.h"
#include "chrome/browser/extensions/api/chrome_device_permissions_prompt.h"
#include "chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h"
@@ -27,6 +26,7 @@
#include "chrome/browser/extensions/api/storage/sync_value_store_cache.h"
#include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
#include "chrome/browser/extensions/extension_action_runner.h"
+#include "chrome/browser/extensions/system_display/display_info_provider.h"
#include "chrome/browser/favicon/favicon_utils.h"
#include "chrome/browser/guest_view/app_view/chrome_app_view_guest_delegate.h"
#include "chrome/browser/guest_view/chrome_guest_view_manager_delegate.h"
@@ -36,7 +36,8 @@
#include "chrome/browser/guest_view/web_view/chrome_web_view_permission_helper_delegate.h"
#include "chrome/browser/performance_manager/performance_manager.h"
#include "chrome/browser/performance_manager/performance_manager_tab_helper.h"
-#include "chrome/browser/search/instant_io_context.h"
+#include "chrome/browser/search/instant_service.h"
+#include "chrome/browser/search/instant_service_factory.h"
#include "chrome/browser/ui/pdf/chrome_pdf_web_contents_helper_client.h"
#include "chrome/browser/ui/webui/devtools_ui.h"
#include "chrome/common/url_constants.h"
@@ -48,6 +49,7 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
+#include "extensions/browser/api/system_display/display_info_provider.h"
#include "extensions/browser/api/virtual_keyboard_private/virtual_keyboard_delegate.h"
#include "extensions/browser/api/web_request/web_request_info.h"
#include "extensions/browser/extension_registry.h"
@@ -99,8 +101,6 @@ void ChromeExtensionsAPIClient::AttachWebContentsHelpers(
pdf::PDFWebContentsHelper::CreateForWebContentsWithClient(
web_contents, std::make_unique<ChromePDFWebContentsHelperClient>());
- data_use_measurement::DataUseWebContentsObserver::CreateForWebContents(
- web_contents);
extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
web_contents);
if (performance_manager::PerformanceManager::GetInstance()) {
@@ -124,8 +124,9 @@ bool ChromeExtensionsAPIClient::ShouldHideResponseHeader(
}
bool ChromeExtensionsAPIClient::ShouldHideBrowserNetworkRequest(
+ content::BrowserContext* context,
const WebRequestInfo& request) const {
- DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Note: browser initiated non-navigation requests are hidden from extensions.
// But we do still need to protect some sensitive sub-frame navigation
@@ -151,8 +152,12 @@ bool ChromeExtensionsAPIClient::ShouldHideBrowserNetworkRequest(
url::Origin::Create(GURL(chrome::kChromeSearchLocalNtpUrl)));
// Hide requests made by the NTP Instant renderer.
- is_sensitive_request |= InstantIOContext::IsInstantProcess(
- request.resource_context, request.render_process_id);
+ auto* instant_service =
+ InstantServiceFactory::GetForProfile(static_cast<Profile*>(context));
+ if (instant_service) {
+ is_sensitive_request |=
+ instant_service->IsInstantProcess(request.render_process_id);
+ }
return is_sensitive_request;
}
@@ -161,62 +166,51 @@ void ChromeExtensionsAPIClient::NotifyWebRequestWithheld(
int render_process_id,
int render_frame_id,
const ExtensionId& extension_id) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
-
- auto notify_web_request_withheld_on_ui = [](int render_process_id,
- int render_frame_id,
- const ExtensionId& extension_id) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
-
- // Track down the ExtensionActionRunner and the extension. Since this is
- // asynchronous, we could hit a null anywhere along the path.
- content::RenderFrameHost* rfh =
- content::RenderFrameHost::FromID(render_process_id, render_frame_id);
- if (!rfh)
- return;
- // We don't count subframe blocked actions as yet, since there's no way to
- // surface this to the user. Ignore these (which is also what we do for
- // content scripts).
- if (rfh->GetParent())
- return;
- content::WebContents* web_contents =
- content::WebContents::FromRenderFrameHost(rfh);
- if (!web_contents)
- return;
- extensions::ExtensionActionRunner* runner =
- extensions::ExtensionActionRunner::GetForWebContents(web_contents);
- if (!runner)
- return;
-
- const extensions::Extension* extension =
- extensions::ExtensionRegistry::Get(web_contents->GetBrowserContext())
- ->enabled_extensions()
- .GetByID(extension_id);
- if (!extension)
- return;
-
- // If the extension doesn't request access to the tab, return. The user
- // invoking the extension on a site grants access to the tab's origin if
- // and only if the extension requested it; without requesting the tab,
- // clicking on the extension won't grant access to the resource.
- // https://crbug.com/891586.
- // TODO(https://157736): We can remove this if extensions require host
- // permissions to the initiator, since then we'll never get into this type
- // of circumstance (the request would be blocked, rather than withheld).
- if (!extension->permissions_data()
- ->withheld_permissions()
- .explicit_hosts()
- .MatchesURL(rfh->GetLastCommittedURL())) {
- return;
- }
-
- runner->OnWebRequestBlocked(extension);
- };
-
- base::PostTaskWithTraits(
- FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(std::move(notify_web_request_withheld_on_ui),
- render_process_id, render_frame_id, extension_id));
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+
+ // Track down the ExtensionActionRunner and the extension. Since this is
+ // asynchronous, we could hit a null anywhere along the path.
+ content::RenderFrameHost* rfh =
+ content::RenderFrameHost::FromID(render_process_id, render_frame_id);
+ if (!rfh)
+ return;
+ // We don't count subframe blocked actions as yet, since there's no way to
+ // surface this to the user. Ignore these (which is also what we do for
+ // content scripts).
+ if (rfh->GetParent())
+ return;
+ content::WebContents* web_contents =
+ content::WebContents::FromRenderFrameHost(rfh);
+ if (!web_contents)
+ return;
+ extensions::ExtensionActionRunner* runner =
+ extensions::ExtensionActionRunner::GetForWebContents(web_contents);
+ if (!runner)
+ return;
+
+ const extensions::Extension* extension =
+ extensions::ExtensionRegistry::Get(web_contents->GetBrowserContext())
+ ->enabled_extensions()
+ .GetByID(extension_id);
+ if (!extension)
+ return;
+
+ // If the extension doesn't request access to the tab, return. The user
+ // invoking the extension on a site grants access to the tab's origin if
+ // and only if the extension requested it; without requesting the tab,
+ // clicking on the extension won't grant access to the resource.
+ // https://crbug.com/891586.
+ // TODO(https://157736): We can remove this if extensions require host
+ // permissions to the initiator, since then we'll never get into this type
+ // of circumstance (the request would be blocked, rather than withheld).
+ if (!extension->permissions_data()
+ ->withheld_permissions()
+ .explicit_hosts()
+ .MatchesURL(rfh->GetLastCommittedURL())) {
+ return;
+ }
+
+ runner->OnWebRequestBlocked(extension);
}
AppViewGuestDelegate* ChromeExtensionsAPIClient::CreateAppViewGuestDelegate()
@@ -286,6 +280,11 @@ ManagementAPIDelegate* ChromeExtensionsAPIClient::CreateManagementAPIDelegate()
return new ChromeManagementAPIDelegate;
}
+std::unique_ptr<DisplayInfoProvider>
+ChromeExtensionsAPIClient::CreateDisplayInfoProvider() const {
+ return CreateChromeDisplayInfoProvider();
+}
+
MetricsPrivateDelegate* ChromeExtensionsAPIClient::GetMetricsPrivateDelegate() {
if (!metrics_private_delegate_)
metrics_private_delegate_.reset(new ChromeMetricsPrivateDelegate());
@@ -365,4 +364,9 @@ ChromeExtensionsAPIClient::GetAutomationInternalApiDelegate() {
return extensions_automation_api_delegate_.get();
}
+std::vector<KeyedServiceBaseFactory*>
+ChromeExtensionsAPIClient::GetFactoryDependencies() {
+ return {InstantServiceFactory::GetInstance()};
+}
+
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h
index 15b684a4a6d..a4837bf2e18 100644
--- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h
+++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h
@@ -34,6 +34,7 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient {
bool ShouldHideResponseHeader(const GURL& url,
const std::string& header_name) const override;
bool ShouldHideBrowserNetworkRequest(
+ content::BrowserContext* context,
const WebRequestInfo& request) const override;
void NotifyWebRequestWithheld(int render_process_id,
int render_frame_id,
@@ -59,6 +60,8 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient {
std::unique_ptr<VirtualKeyboardDelegate> CreateVirtualKeyboardDelegate(
content::BrowserContext* browser_context) const override;
ManagementAPIDelegate* CreateManagementAPIDelegate() const override;
+ std::unique_ptr<DisplayInfoProvider> CreateDisplayInfoProvider()
+ const override;
MetricsPrivateDelegate* GetMetricsPrivateDelegate() override;
NetworkingCastPrivateDelegate* GetNetworkingCastPrivateDelegate() override;
FileSystemDelegate* GetFileSystemDelegate() override;
@@ -78,6 +81,7 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient {
#endif
AutomationInternalApiDelegate* GetAutomationInternalApiDelegate() override;
+ std::vector<KeyedServiceBaseFactory*> GetFactoryDependencies() override;
private:
std::unique_ptr<ChromeMetricsPrivateDelegate> metrics_private_delegate_;
diff --git a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc
index c5290bab04e..73d0c21d940 100644
--- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc
@@ -51,10 +51,12 @@ TEST_F(ChromeExtensionsAPIClientTest, ShouldHideBrowserNetworkRequest) {
// Requests made by the browser with chrome://newtab as its initiator should
// not be visible to extensions.
EXPECT_TRUE(client.ShouldHideBrowserNetworkRequest(
+ nullptr /* context */,
WebRequestInfo(create_params(content::ResourceType::kScript))));
// Main frame requests should always be visible to extensions.
EXPECT_FALSE(client.ShouldHideBrowserNetworkRequest(
+ nullptr /* context */,
WebRequestInfo(create_params(content::ResourceType::kMainFrame))));
// Similar requests made by the renderer should be visible to extensions.
@@ -62,7 +64,7 @@ TEST_F(ChromeExtensionsAPIClientTest, ShouldHideBrowserNetworkRequest) {
create_params(content::ResourceType::kScript);
params.render_process_id = 2;
EXPECT_FALSE(client.ShouldHideBrowserNetworkRequest(
- WebRequestInfo(std::move(params))));
+ nullptr /* context */, WebRequestInfo(std::move(params))));
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc
index 279f9164e0d..9a1e1967385 100644
--- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc
+++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc
@@ -88,79 +88,129 @@ network::mojom::CookieManager* ParseStoreCookieManager(
} // namespace
+CookiesEventRouter::CookieChangeListener::CookieChangeListener(
+ CookiesEventRouter* router,
+ bool otr)
+ : router_(router), otr_(otr) {}
+CookiesEventRouter::CookieChangeListener::~CookieChangeListener() = default;
+
+void CookiesEventRouter::CookieChangeListener::OnCookieChange(
+ const net::CanonicalCookie& canonical_cookie,
+ network::mojom::CookieChangeCause cause) {
+ router_->OnCookieChange(otr_, canonical_cookie, cause);
+}
+
CookiesEventRouter::CookiesEventRouter(content::BrowserContext* context)
: profile_(Profile::FromBrowserContext(context)) {
- CHECK(registrar_.IsEmpty());
- registrar_.Add(this,
- chrome::NOTIFICATION_COOKIE_CHANGED_FOR_EXTENSIONS,
- content::NotificationService::AllBrowserContextsAndSources());
+ MaybeStartListening();
+ BrowserList::AddObserver(this);
}
CookiesEventRouter::~CookiesEventRouter() {
+ BrowserList::RemoveObserver(this);
}
-void CookiesEventRouter::Observe(
- int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) {
- DCHECK_EQ(chrome::NOTIFICATION_COOKIE_CHANGED_FOR_EXTENSIONS, type);
-
- Profile* profile = content::Source<Profile>(source).ptr();
- if (!profile_->IsSameProfile(profile))
- return;
+void CookiesEventRouter::OnCookieChange(
+ bool otr,
+ const net::CanonicalCookie& canonical_cookie,
+ network::mojom::CookieChangeCause cause) {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- CookieChanged(profile, content::Details<ChromeCookieDetails>(details).ptr());
-}
-
-void CookiesEventRouter::CookieChanged(
- Profile* profile,
- ChromeCookieDetails* details) {
std::unique_ptr<base::ListValue> args(new base::ListValue());
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
- dict->SetBoolean(cookies_api_constants::kRemovedKey, details->removed);
+ dict->SetBoolean(cookies_api_constants::kRemovedKey,
+ cause != network::mojom::CookieChangeCause::INSERTED);
+ Profile* profile =
+ otr ? profile_->GetOffTheRecordProfile() : profile_->GetOriginalProfile();
api::cookies::Cookie cookie = cookies_helpers::CreateCookie(
- *details->cookie, cookies_helpers::GetStoreIdFromProfile(profile));
+ canonical_cookie, cookies_helpers::GetStoreIdFromProfile(profile));
dict->Set(cookies_api_constants::kCookieKey, cookie.ToValue());
// Map the internal cause to an external string.
- std::string cause;
- switch (details->cause) {
+ std::string cause_dict_entry;
+ switch (cause) {
// Report an inserted cookie as an "explicit" change cause. All other causes
// only make sense for deletions.
case network::mojom::CookieChangeCause::INSERTED:
case network::mojom::CookieChangeCause::EXPLICIT:
- cause = cookies_api_constants::kExplicitChangeCause;
+ cause_dict_entry = cookies_api_constants::kExplicitChangeCause;
break;
case network::mojom::CookieChangeCause::OVERWRITE:
- cause = cookies_api_constants::kOverwriteChangeCause;
+ cause_dict_entry = cookies_api_constants::kOverwriteChangeCause;
break;
case network::mojom::CookieChangeCause::EXPIRED:
- cause = cookies_api_constants::kExpiredChangeCause;
+ cause_dict_entry = cookies_api_constants::kExpiredChangeCause;
break;
case network::mojom::CookieChangeCause::EVICTED:
- cause = cookies_api_constants::kEvictedChangeCause;
+ cause_dict_entry = cookies_api_constants::kEvictedChangeCause;
break;
case network::mojom::CookieChangeCause::EXPIRED_OVERWRITE:
- cause = cookies_api_constants::kExpiredOverwriteChangeCause;
+ cause_dict_entry = cookies_api_constants::kExpiredOverwriteChangeCause;
break;
case network::mojom::CookieChangeCause::UNKNOWN_DELETION:
NOTREACHED();
}
- dict->SetString(cookies_api_constants::kCauseKey, cause);
+ dict->SetString(cookies_api_constants::kCauseKey, cause_dict_entry);
args->Append(std::move(dict));
- GURL cookie_domain =
- cookies_helpers::GetURLFromCanonicalCookie(*details->cookie);
DispatchEvent(profile, events::COOKIES_ON_CHANGED,
api::cookies::OnChanged::kEventName, std::move(args),
- cookie_domain);
+ cookies_helpers::GetURLFromCanonicalCookie(canonical_cookie));
+}
+
+void CookiesEventRouter::OnBrowserAdded(Browser* browser) {
+ // The new browser may be associated with a profile that is the OTR spinoff
+ // of |profile_|, in which case we need to start listening to cookie changes
+ // there. If this is any other kind of new browser, MaybeStartListening() will
+ // be a no op.
+ MaybeStartListening();
+}
+
+void CookiesEventRouter::MaybeStartListening() {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ DCHECK(profile_);
+
+ Profile* original_profile = profile_->GetOriginalProfile();
+ Profile* otr_profile = original_profile->HasOffTheRecordProfile()
+ ? original_profile->GetOffTheRecordProfile()
+ : nullptr;
+
+ if (!binding_)
+ BindToCookieManager(&binding_, original_profile);
+ if (!otr_binding_.is_bound() && otr_profile)
+ BindToCookieManager(&otr_binding_, otr_profile);
+}
+
+void CookiesEventRouter::BindToCookieManager(
+ mojo::Binding<network::mojom::CookieChangeListener>* binding,
+ Profile* profile) {
+ network::mojom::CookieManager* cookie_manager =
+ content::BrowserContext::GetDefaultStoragePartition(profile)
+ ->GetCookieManagerForBrowserProcess();
+ if (!cookie_manager)
+ return;
+
+ network::mojom::CookieChangeListenerPtr listener_ptr;
+ binding->Bind(mojo::MakeRequest(&listener_ptr));
+ binding->set_connection_error_handler(base::BindOnce(
+ &CookiesEventRouter::OnConnectionError, base::Unretained(this), binding));
+
+ cookie_manager->AddGlobalChangeListener(std::move(listener_ptr));
+}
+
+void CookiesEventRouter::OnConnectionError(
+ mojo::Binding<network::mojom::CookieChangeListener>* binding) {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+
+ binding->Close();
+ MaybeStartListening();
}
void CookiesEventRouter::DispatchEvent(
@@ -168,7 +218,7 @@ void CookiesEventRouter::DispatchEvent(
events::HistogramValue histogram_value,
const std::string& event_name,
std::unique_ptr<base::ListValue> event_args,
- GURL& cookie_domain) {
+ const GURL& cookie_domain) {
EventRouter* router = context ? EventRouter::Get(context) : NULL;
if (!router)
return;
@@ -178,11 +228,8 @@ void CookiesEventRouter::DispatchEvent(
router->BroadcastEvent(std::move(event));
}
-CookiesGetFunction::CookiesGetFunction() {
-}
-
-CookiesGetFunction::~CookiesGetFunction() {
-}
+CookiesGetFunction::CookiesGetFunction() = default;
+CookiesGetFunction::~CookiesGetFunction() = default;
ExtensionFunction::ResponseAction CookiesGetFunction::Run() {
parsed_args_ = api::cookies::Get::Params::Create(*args_);
@@ -532,8 +579,7 @@ CookiesAPI::CookiesAPI(content::BrowserContext* context)
->RegisterObserver(this, api::cookies::OnChanged::kEventName);
}
-CookiesAPI::~CookiesAPI() {
-}
+CookiesAPI::~CookiesAPI() = default;
void CookiesAPI::Shutdown() {
EventRouter::Get(browser_context_)->UnregisterObserver(this);
diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h
index f149cb5fcd7..fbd37d66f00 100644
--- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h
+++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h
@@ -15,47 +15,78 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "chrome/browser/extensions/chrome_extension_function.h"
-#include "chrome/browser/net/chrome_cookie_notification_details.h"
+#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/common/extensions/api/cookies.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
#include "extensions/browser/browser_context_keyed_api_factory.h"
#include "extensions/browser/event_router.h"
+#include "mojo/public/cpp/bindings/binding.h"
#include "net/cookies/canonical_cookie.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
#include "url/gurl.h"
namespace extensions {
-// Observes CookieMonster notifications and routes them as events to the
+// Observes CookieManager Mojo messages and routes them as events to the
// extension system.
-class CookiesEventRouter : public content::NotificationObserver {
+class CookiesEventRouter : public BrowserListObserver {
public:
explicit CookiesEventRouter(content::BrowserContext* context);
~CookiesEventRouter() override;
- private:
- // content::NotificationObserver implementation.
- void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) override;
+ // BrowserListObserver:
+ void OnBrowserAdded(Browser* browser) override;
- // Handler for the COOKIE_CHANGED event. The method takes the details of such
- // an event and constructs a suitable JSON formatted extension event from it.
- void CookieChanged(Profile* profile, ChromeCookieDetails* details);
+ private:
+ // This helper class connects to the CookieMonster over Mojo, and relays Mojo
+ // messages to the owning CookiesEventRouter. This rather clumsy arrangement
+ // is necessary to differentiate which CookieMonster the Mojo message comes
+ // from (that associated with the incognito profile vs the original profile),
+ // since it's not possible to tell the source from inside OnCookieChange().
+ class CookieChangeListener : public network::mojom::CookieChangeListener {
+ public:
+ CookieChangeListener(CookiesEventRouter* router, bool otr);
+ ~CookieChangeListener() override;
+
+ // network::mojom::CookieChangeListener:
+ void OnCookieChange(const net::CanonicalCookie& canonical_cookie,
+ network::mojom::CookieChangeCause cause) override;
+
+ private:
+ CookiesEventRouter* router_;
+ bool otr_;
+
+ DISALLOW_COPY_AND_ASSIGN(CookieChangeListener);
+ };
+
+ void MaybeStartListening();
+ void BindToCookieManager(
+ mojo::Binding<network::mojom::CookieChangeListener>* binding,
+ Profile* profile);
+ void OnConnectionError(
+ mojo::Binding<network::mojom::CookieChangeListener>* binding);
+ void OnCookieChange(bool otr,
+ const net::CanonicalCookie& canonical_cookie,
+ network::mojom::CookieChangeCause cause);
// This method dispatches events to the extension message service.
void DispatchEvent(content::BrowserContext* context,
events::HistogramValue histogram_value,
const std::string& event_name,
std::unique_ptr<base::ListValue> event_args,
- GURL& cookie_domain);
-
- // Used for tracking registrations to CookieMonster notifications.
- content::NotificationRegistrar registrar_;
+ const GURL& cookie_domain);
Profile* profile_;
+ // To listen to cookie changes in both the original and the off the record
+ // profiles, we need a pair of bindings, as well as a pair of
+ // CookieChangeListener instances.
+ CookieChangeListener listener_{this, false};
+ mojo::Binding<network::mojom::CookieChangeListener> binding_{&listener_};
+
+ CookieChangeListener otr_listener_{this, true};
+ mojo::Binding<network::mojom::CookieChangeListener> otr_binding_{
+ &otr_listener_};
+
DISALLOW_COPY_AND_ASSIGN(CookiesEventRouter);
};
diff --git a/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc b/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc
index e4fb1181164..b84087e0e01 100644
--- a/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc
@@ -10,15 +10,11 @@
#include "base/command_line.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
-#include "base/test/thread_test_helper.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/ui_test_utils.h"
-#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "extensions/browser/api/declarative/rules_registry_service.h"
#include "extensions/browser/api/declarative_webrequest/webrequest_constants.h"
@@ -28,8 +24,6 @@
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/test_extension_dir.h"
-using content::BrowserThread;
-
namespace extensions {
namespace {
@@ -120,14 +114,7 @@ class DeclarativeApiTest : public ExtensionApiTest {
extensions::declarative_webrequest_constants::kOnRequest);
std::vector<const api::events::Rule*> rules;
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&RulesRegistry::GetAllRules, rules_registry,
- extension_id, &rules));
- scoped_refptr<base::ThreadTestHelper> io_helper(new base::ThreadTestHelper(
- base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})
- .get()));
- EXPECT_TRUE(io_helper->Run());
+ rules_registry->GetAllRules(extension_id, &rules);
return rules.size();
}
};
diff --git a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc
index 0d28bb39337..599e2a6536a 100644
--- a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc
@@ -136,7 +136,7 @@ void ChromeContentRulesRegistry::MonitorWebContentsForRuleEvaluation(
void ChromeContentRulesRegistry::DidFinishNavigation(
content::WebContents* contents,
content::NavigationHandle* navigation_handle) {
- if (base::ContainsKey(active_rules_, contents)) {
+ if (base::Contains(active_rules_, contents)) {
EvaluationScope evaluation_scope(this);
for (const std::unique_ptr<ContentPredicateEvaluator>& evaluator :
evaluators_)
@@ -321,7 +321,7 @@ std::string ChromeContentRulesRegistry::RemoveRulesImpl(
// Remove the ContentRule from active_rules_.
for (auto& tab_rules_pair : active_rules_) {
- if (base::ContainsKey(tab_rules_pair.second, rule)) {
+ if (base::Contains(tab_rules_pair.second, rule)) {
ContentAction::ApplyInfo apply_info =
{rule->extension, browser_context(), tab_rules_pair.first,
rule->priority};
@@ -363,14 +363,14 @@ std::string ChromeContentRulesRegistry::RemoveAllRulesImpl(
void ChromeContentRulesRegistry::EvaluateConditionsForTab(
content::WebContents* tab) {
std::set<const ContentRule*> matching_rules = GetMatchingRules(tab);
- if (matching_rules.empty() && !base::ContainsKey(active_rules_, tab))
+ if (matching_rules.empty() && !base::Contains(active_rules_, tab))
return;
std::set<const ContentRule*>& prev_matching_rules = active_rules_[tab];
for (const ContentRule* rule : matching_rules) {
ContentAction::ApplyInfo apply_info =
{rule->extension, browser_context(), tab, rule->priority};
- if (!base::ContainsKey(prev_matching_rules, rule)) {
+ if (!base::Contains(prev_matching_rules, rule)) {
for (const std::unique_ptr<const ContentAction>& action : rule->actions)
action->Apply(apply_info);
} else {
@@ -379,7 +379,7 @@ void ChromeContentRulesRegistry::EvaluateConditionsForTab(
}
}
for (const ContentRule* rule : prev_matching_rules) {
- if (!base::ContainsKey(matching_rules, rule)) {
+ if (!base::Contains(matching_rules, rule)) {
ContentAction::ApplyInfo apply_info =
{rule->extension, browser_context(), tab, rule->priority};
for (const std::unique_ptr<const ContentAction>& action : rule->actions)
diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc
index f2faeddf3c4..b43cb47ab7b 100644
--- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc
@@ -231,7 +231,7 @@ void DeclarativeContentCssConditionTracker::TrackForWebContents(
void DeclarativeContentCssConditionTracker::OnWebContentsNavigation(
content::WebContents* contents,
content::NavigationHandle* navigation_handle) {
- DCHECK(base::ContainsKey(per_web_contents_tracker_, contents));
+ DCHECK(base::Contains(per_web_contents_tracker_, contents));
per_web_contents_tracker_[contents]->OnWebContentsNavigation(
navigation_handle);
}
@@ -248,7 +248,7 @@ bool DeclarativeContentCssConditionTracker::EvaluatePredicate(
loc->second->matching_css_selectors();
for (const std::string& predicate_css_selector :
typed_predicate->css_selectors()) {
- if (!base::ContainsKey(matching_css_selectors, predicate_css_selector))
+ if (!base::Contains(matching_css_selectors, predicate_css_selector))
return false;
}
@@ -302,7 +302,7 @@ InstructRenderProcessIfManagingBrowserContext(
void DeclarativeContentCssConditionTracker::DeletePerWebContentsTracker(
content::WebContents* contents) {
- DCHECK(base::ContainsKey(per_web_contents_tracker_, contents));
+ DCHECK(base::Contains(per_web_contents_tracker_, contents));
per_web_contents_tracker_.erase(contents);
}
diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.cc
index faef055ed2f..5d8e60d10c6 100644
--- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.cc
@@ -111,7 +111,7 @@ BookmarkAddedForUrl(const GURL& url) {
void DeclarativeContentIsBookmarkedConditionTracker::PerWebContentsTracker::
BookmarkRemovedForUrls(const std::set<GURL>& urls) {
- if (base::ContainsKey(urls, web_contents()->GetVisibleURL())) {
+ if (base::Contains(urls, web_contents()->GetVisibleURL())) {
is_url_bookmarked_ = false;
request_evaluation_.Run(web_contents());
}
@@ -201,7 +201,7 @@ void DeclarativeContentIsBookmarkedConditionTracker::TrackForWebContents(
void DeclarativeContentIsBookmarkedConditionTracker::OnWebContentsNavigation(
content::WebContents* contents,
content::NavigationHandle* navigation_handle) {
- DCHECK(base::ContainsKey(per_web_contents_tracker_, contents));
+ DCHECK(base::Contains(per_web_contents_tracker_, contents));
per_web_contents_tracker_[contents]->UpdateState(true);
}
@@ -221,11 +221,11 @@ void DeclarativeContentIsBookmarkedConditionTracker::BookmarkModelChanged() {}
void DeclarativeContentIsBookmarkedConditionTracker::BookmarkNodeAdded(
bookmarks::BookmarkModel* model,
const bookmarks::BookmarkNode* parent,
- int index) {
+ size_t index) {
if (!extensive_bookmark_changes_in_progress_) {
for (const auto& web_contents_tracker_pair : per_web_contents_tracker_) {
web_contents_tracker_pair.second->BookmarkAddedForUrl(
- parent->GetChild(index)->url());
+ parent->children()[index]->url());
}
}
}
@@ -233,7 +233,7 @@ void DeclarativeContentIsBookmarkedConditionTracker::BookmarkNodeAdded(
void DeclarativeContentIsBookmarkedConditionTracker::BookmarkNodeRemoved(
bookmarks::BookmarkModel* model,
const bookmarks::BookmarkNode* parent,
- int old_index,
+ size_t old_index,
const bookmarks::BookmarkNode* node,
const std::set<GURL>& no_longer_bookmarked) {
if (!extensive_bookmark_changes_in_progress_) {
@@ -273,7 +273,7 @@ DeclarativeContentIsBookmarkedConditionTracker::GroupedBookmarkChangesEnded(
void
DeclarativeContentIsBookmarkedConditionTracker::DeletePerWebContentsTracker(
content::WebContents* contents) {
- DCHECK(base::ContainsKey(per_web_contents_tracker_, contents));
+ DCHECK(base::Contains(per_web_contents_tracker_, contents));
per_web_contents_tracker_.erase(contents);
}
diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.h b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.h
index ab38810cf3a..7cbc0b2fa56 100644
--- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.h
+++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.h
@@ -124,10 +124,10 @@ class DeclarativeContentIsBookmarkedConditionTracker
void BookmarkModelChanged() override;
void BookmarkNodeAdded(bookmarks::BookmarkModel* model,
const bookmarks::BookmarkNode* parent,
- int index) override;
+ size_t index) override;
void BookmarkNodeRemoved(bookmarks::BookmarkModel* model,
const bookmarks::BookmarkNode* parent,
- int old_index,
+ size_t old_index,
const bookmarks::BookmarkNode* node,
const std::set<GURL>& no_longer_bookmarked) override;
void ExtensiveBookmarkChangesBeginning(
diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc
index 8c8917c2719..d8776afb347 100644
--- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc
@@ -82,7 +82,7 @@ class DeclarativeContentIsBookmarkedConditionTrackerTest
// ContentPredicateEvaluator::Delegate:
void RequestEvaluation(content::WebContents* contents) override {
- EXPECT_FALSE(base::ContainsKey(evaluation_requests_, contents));
+ EXPECT_FALSE(base::Contains(evaluation_requests_, contents));
evaluation_requests_.insert(contents);
}
diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.cc
index 78586f81879..0b3db15632f 100644
--- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.cc
@@ -192,7 +192,7 @@ void DeclarativeContentPageUrlConditionTracker::TrackForWebContents(
void DeclarativeContentPageUrlConditionTracker::OnWebContentsNavigation(
content::WebContents* contents,
content::NavigationHandle* navigation_handle) {
- DCHECK(base::ContainsKey(per_web_contents_tracker_, contents));
+ DCHECK(base::Contains(per_web_contents_tracker_, contents));
per_web_contents_tracker_[contents]->UpdateMatchesForCurrentUrl(true);
}
@@ -206,8 +206,8 @@ bool DeclarativeContentPageUrlConditionTracker::EvaluatePredicate(
DCHECK(loc != per_web_contents_tracker_.end());
const std::set<url_matcher::URLMatcherConditionSet::ID>&
web_contents_id_matches = loc->second->matches();
- return base::ContainsKey(web_contents_id_matches,
- typed_predicate->url_matcher_condition_set()->id());
+ return base::Contains(web_contents_id_matches,
+ typed_predicate->url_matcher_condition_set()->id());
}
bool DeclarativeContentPageUrlConditionTracker::IsEmpty() const {
@@ -216,7 +216,7 @@ bool DeclarativeContentPageUrlConditionTracker::IsEmpty() const {
void DeclarativeContentPageUrlConditionTracker::DeletePerWebContentsTracker(
content::WebContents* contents) {
- DCHECK(base::ContainsKey(per_web_contents_tracker_, contents));
+ DCHECK(base::Contains(per_web_contents_tracker_, contents));
per_web_contents_tracker_.erase(contents);
}
diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc
index 075716ea48f..1b9227cd3d6 100644
--- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc
@@ -38,7 +38,7 @@ class DeclarativeContentPageUrlConditionTrackerTest
// ContentPredicateEvaluator::Delegate:
void RequestEvaluation(content::WebContents* contents) override {
- EXPECT_FALSE(base::ContainsKey(evaluation_requests_, contents));
+ EXPECT_FALSE(base::Contains(evaluation_requests_, contents));
evaluation_requests_.insert(contents);
}
diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc
index 38ba6dbacab..d9b1b058ecd 100644
--- a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc
@@ -197,8 +197,8 @@ class RulesetCountWaiter : public RulesetManager::TestObserver {
class ScopedRulesetManagerTestObserver {
public:
ScopedRulesetManagerTestObserver(RulesetManager::TestObserver* observer,
- scoped_refptr<InfoMap> info_map)
- : info_map_(std::move(info_map)) {
+ content::BrowserContext* browser_context)
+ : browser_context_(browser_context) {
SetRulesetManagerTestObserver(observer);
}
@@ -208,17 +208,12 @@ class ScopedRulesetManagerTestObserver {
private:
void SetRulesetManagerTestObserver(RulesetManager::TestObserver* observer) {
- base::PostTaskWithTraits(
- FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(
- [](RulesetManager::TestObserver* observer, InfoMap* info_map) {
- info_map->GetRulesetManager()->SetObserverForTest(observer);
- },
- observer, base::RetainedRef(info_map_)));
- content::RunAllTasksUntilIdle();
+ declarative_net_request::RulesMonitorService::Get(browser_context_)
+ ->ruleset_manager()
+ ->SetObserverForTest(observer);
}
- scoped_refptr<InfoMap> info_map_;
+ content::BrowserContext* browser_context_;
DISALLOW_COPY_AND_ASSIGN(ScopedRulesetManagerTestObserver);
};
@@ -239,7 +234,7 @@ class WarningServiceObserver : public WarningService::Observer {
// WarningService::TestObserver override:
void ExtensionWarningsChanged(
const ExtensionIdSet& affected_extensions) override {
- if (!base::ContainsKey(affected_extensions, extension_id_))
+ if (!base::Contains(affected_extensions, extension_id_))
return;
run_loop_.Quit();
@@ -1337,6 +1332,100 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RedirectPriority) {
}
}
+// Test that upgradeScheme rules will change the scheme of matching requests to
+// https.
+IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, UpgradeRules) {
+ auto get_url_for_host = [this](std::string hostname, const char* scheme) {
+ GURL url = embedded_test_server()->GetURL(hostname,
+ "/pages_with_script/index.html");
+
+ url::Replacements<char> replacements;
+ replacements.SetScheme(scheme, url::Component(0, strlen(scheme)));
+
+ return url.ReplaceComponents(replacements);
+ };
+
+ GURL google_url = get_url_for_host("google.com", url::kHttpScheme);
+ struct {
+ std::string url_filter;
+ int id;
+ int priority;
+ std::string action_type;
+ base::Optional<std::string> redirect_url;
+ } rules_data[] = {
+ {"exa*", 1, 4, "upgradeScheme", base::nullopt},
+ {"|http:*yahoo", 2, 100, "redirect", "http://other.com"},
+ // Since the test server can only display http requests, redirect all
+ // https requests to google.com in the end.
+ // TODO(crbug.com/985104): Add a https test server to display https pages
+ // so this redirect rule can be removed.
+ {"|https*", 3, 6, "redirect", google_url.spec()},
+ {"exact.com", 4, 1, "block", base::nullopt},
+ };
+
+ // Load the extension.
+ std::vector<TestRule> rules;
+ for (const auto& rule_data : rules_data) {
+ TestRule rule = CreateGenericRule();
+ rule.condition->url_filter = rule_data.url_filter;
+ rule.id = rule_data.id;
+ rule.priority = rule_data.priority;
+ rule.condition->resource_types = std::vector<std::string>({"main_frame"});
+ rule.action->type = rule_data.action_type;
+ rule.action->redirect_url = rule_data.redirect_url;
+ rules.push_back(rule);
+ }
+
+ ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
+ rules, "test_extension", {URLPattern::kAllUrlsPattern}));
+
+ // Now load an extension with another ruleset, except this extension has no
+ // host permissions.
+ TestRule upgrade_rule = CreateGenericRule();
+ upgrade_rule.condition->url_filter = "yahoo";
+ upgrade_rule.id = kMinValidID;
+ upgrade_rule.priority = kMinValidPriority;
+ upgrade_rule.condition->resource_types =
+ std::vector<std::string>({"main_frame"});
+ upgrade_rule.action->type = "upgradeScheme";
+
+ ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
+ std::vector<TestRule>({upgrade_rule}), "test_extension_2", {}));
+
+ struct {
+ std::string hostname;
+ const char* scheme;
+ // |expected_final_url| is null if the request is expected to be blocked.
+ base::Optional<GURL> expected_final_url;
+ } test_cases[] = {
+ {"exact.com", url::kHttpScheme, base::nullopt},
+ // http://example.com -> https://example.com/ -> http://google.com
+ {"example.com", url::kHttpScheme, google_url},
+ // test_extension_2 should upgrade the scheme for http://yahoo.com
+ // despite having no host permissions. Note that this request is not
+ // matched with test_extension_1's ruleset as test_extension_2 is
+ // installed more recently.
+ // http://yahoo.com -> https://yahoo.com/ -> http://google.com
+ {"yahoo.com", url::kHttpScheme, google_url},
+ };
+
+ for (const auto& test_case : test_cases) {
+ GURL url = get_url_for_host(test_case.hostname, test_case.scheme);
+ SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str()));
+
+ ui_test_utils::NavigateToURL(browser(), url);
+
+ if (!test_case.expected_final_url) {
+ EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType());
+ } else {
+ EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
+
+ const GURL& final_url = web_contents()->GetLastCommittedURL();
+ EXPECT_EQ(*test_case.expected_final_url, final_url);
+ }
+ }
+}
+
// Tests that only extensions enabled in incognito mode affect network requests
// from an incognito context.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
@@ -1466,9 +1555,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RendererCacheCleared) {
// script.js.
URLRequestMonitor script_monitor(
embedded_test_server()->GetURL("example.com", "/cached/script.js"));
- ScopedRulesetManagerTestObserver scoped_observer(
- &script_monitor,
- base::WrapRefCounted(ExtensionSystem::Get(profile())->info_map()));
+ ScopedRulesetManagerTestObserver scoped_observer(&script_monitor, profile());
GURL url = embedded_test_server()->GetURL(
"example.com", "/cached/page_with_cacheable_script.html");
@@ -1478,10 +1565,9 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RendererCacheCleared) {
EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType());
EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame()));
- // NOTE: When the Network Service is enabled, the RulesetMatcher will not see
- // network requests if no rulesets are active.
+ // NOTE: RulesetMatcher will not see network requests if no rulesets are
+ // active.
bool expect_request_seen =
- !base::FeatureList::IsEnabled(network::features::kNetworkService) ||
base::FeatureList::IsEnabled(
extensions_features::kForceWebRequestProxyForTest);
EXPECT_EQ(expect_request_seen, script_monitor.GetAndResetRequestSeen(false));
@@ -1689,7 +1775,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
// The EmbeddedTestServer sees requests after the hostname has been
// resolved.
bool did_see_script_request =
- base::ContainsKey(GetAndResetRequestsToServer(), script_url);
+ base::Contains(GetAndResetRequestsToServer(), script_url);
EXPECT_EQ(expect_script_load, did_see_script_request);
};
@@ -1788,11 +1874,11 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
// Request to |expected_requested_url| should be seen by the server iff we
// expect the page to load.
if (expect_load) {
- EXPECT_TRUE(base::ContainsKey(requests_seen, expected_request_url))
+ EXPECT_TRUE(base::Contains(requests_seen, expected_request_url))
<< expected_request_url.spec()
<< " was not requested from the server.";
} else {
- EXPECT_FALSE(base::ContainsKey(requests_seen, expected_request_url))
+ EXPECT_FALSE(base::Contains(requests_seen, expected_request_url))
<< expected_request_url.spec() << " request seen unexpectedly.";
}
}
@@ -1935,9 +2021,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
// Set-up an observer for RulesetMatcher to monitor the number of extension
// rulesets.
RulesetCountWaiter ruleset_count_waiter;
- ScopedRulesetManagerTestObserver scoped_observer(
- &ruleset_count_waiter,
- base::WrapRefCounted(ExtensionSystem::Get(profile())->info_map()));
+ ScopedRulesetManagerTestObserver scoped_observer(&ruleset_count_waiter,
+ profile());
set_has_background_script(true);
@@ -2083,8 +2168,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
const ExtensionId extension_id = last_loaded_extension_id();
- const auto* rules_monitor_service = BrowserContextKeyedAPIFactory<
- declarative_net_request::RulesMonitorService>::Get(profile());
+ const auto* rules_monitor_service =
+ declarative_net_request::RulesMonitorService::Get(profile());
EXPECT_TRUE(rules_monitor_service->HasRegisteredRuleset(extension_id));
// Mimic extension prefs corruption by overwriting the indexed ruleset
@@ -2134,9 +2219,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
// Set up an observer for RulesetMatcher to monitor the number of extension
// rulesets.
RulesetCountWaiter ruleset_count_waiter;
- ScopedRulesetManagerTestObserver scoped_observer(
- &ruleset_count_waiter,
- base::WrapRefCounted(ExtensionSystem::Get(profile())->info_map()));
+ ScopedRulesetManagerTestObserver scoped_observer(&ruleset_count_waiter,
+ profile());
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("*");
@@ -2144,8 +2228,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
ruleset_count_waiter.WaitForRulesetCount(1);
const ExtensionId extension_id = last_loaded_extension_id();
- const auto* rules_monitor_service = BrowserContextKeyedAPIFactory<
- declarative_net_request::RulesMonitorService>::Get(profile());
+ const auto* rules_monitor_service =
+ declarative_net_request::RulesMonitorService::Get(profile());
EXPECT_TRUE(rules_monitor_service->HasRegisteredRuleset(extension_id));
// Add a dynamic rule.
@@ -2228,9 +2312,9 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
std::set<GURL> seen_requests = GetAndResetRequestsToServer();
EXPECT_EQ(!expect_script_redirected,
- base::ContainsKey(seen_requests, requested_script_url));
+ base::Contains(seen_requests, requested_script_url));
EXPECT_EQ(expect_script_redirected,
- base::ContainsKey(seen_requests, redirected_script_url));
+ base::Contains(seen_requests, redirected_script_url));
ExtensionActionRunner* runner =
ExtensionActionRunner::GetForWebContents(web_contents());
@@ -2464,24 +2548,26 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
// Set up an observer for RulesetMatcher to monitor the number of extension
// rulesets.
RulesetCountWaiter ruleset_count_waiter;
- ScopedRulesetManagerTestObserver scoped_observer(
- &ruleset_count_waiter,
- base::WrapRefCounted(ExtensionSystem::Get(profile())->info_map()));
+ ScopedRulesetManagerTestObserver scoped_observer(&ruleset_count_waiter,
+ profile());
- EXPECT_FALSE(ExtensionWebRequestEventRouter::GetInstance()
- ->HasAnyExtraHeadersListenerOnUI(profile()));
+ EXPECT_FALSE(
+ ExtensionWebRequestEventRouter::GetInstance()->HasAnyExtraHeadersListener(
+ profile()));
ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}));
ruleset_count_waiter.WaitForRulesetCount(1);
content::RunAllTasksUntilIdle();
- EXPECT_TRUE(ExtensionWebRequestEventRouter::GetInstance()
- ->HasAnyExtraHeadersListenerOnUI(profile()));
+ EXPECT_TRUE(
+ ExtensionWebRequestEventRouter::GetInstance()->HasAnyExtraHeadersListener(
+ profile()));
test_referrer_blocked(true);
DisableExtension(last_loaded_extension_id());
ruleset_count_waiter.WaitForRulesetCount(0);
content::RunAllTasksUntilIdle();
- EXPECT_FALSE(ExtensionWebRequestEventRouter::GetInstance()
- ->HasAnyExtraHeadersListenerOnUI(profile()));
+ EXPECT_FALSE(
+ ExtensionWebRequestEventRouter::GetInstance()->HasAnyExtraHeadersListener(
+ profile()));
test_referrer_blocked(false);
}
diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc
index 3bd99e54abd..d2648003e57 100644
--- a/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc
@@ -20,9 +20,9 @@
#include "extensions/browser/api/declarative_net_request/test_utils.h"
#include "extensions/browser/api/web_request/web_request_info.h"
#include "extensions/browser/extension_prefs.h"
+#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extension_util.h"
-#include "extensions/browser/info_map.h"
#include "extensions/common/api/declarative_net_request/constants.h"
#include "extensions/common/api/declarative_net_request/test_utils.h"
#include "extensions/common/file_util.h"
@@ -39,21 +39,21 @@ namespace declarative_net_request {
// with gtest.
bool operator==(const RulesetManager::Action& lhs,
const RulesetManager::Action& rhs) {
- static_assert(flat::ActionIndex_count == 6,
- "Modify this method to ensure it stays updated as new actions "
- "are added.");
-
- auto are_vectors_equal = [](std::vector<const char*> a,
- std::vector<const char*> b) {
- return std::set<base::StringPiece>(a.begin(), a.end()) ==
- std::set<base::StringPiece>(b.begin(), b.end());
- };
-
- return lhs.type == rhs.type && lhs.redirect_url == rhs.redirect_url &&
- are_vectors_equal(lhs.request_headers_to_remove,
- rhs.request_headers_to_remove) &&
- are_vectors_equal(lhs.response_headers_to_remove,
- rhs.response_headers_to_remove);
+ static_assert(flat::ActionIndex_count == 7,
+ "Modify this method to ensure it stays updated as new actions "
+ "are added.");
+
+ auto are_vectors_equal = [](std::vector<const char*> a,
+ std::vector<const char*> b) {
+ return std::set<base::StringPiece>(a.begin(), a.end()) ==
+ std::set<base::StringPiece>(b.begin(), b.end());
+ };
+
+ return lhs.type == rhs.type && lhs.redirect_url == rhs.redirect_url &&
+ are_vectors_equal(lhs.request_headers_to_remove,
+ rhs.request_headers_to_remove) &&
+ are_vectors_equal(lhs.response_headers_to_remove,
+ rhs.response_headers_to_remove);
}
namespace {
@@ -66,6 +66,11 @@ class RulesetManagerTest : public DNRTestBase {
public:
RulesetManagerTest() {}
+ void SetUp() override {
+ DNRTestBase::SetUp();
+ manager_ = std::make_unique<RulesetManager>(browser_context());
+ }
+
protected:
using Action = RulesetManager::Action;
using ActionType = Action::Type;
@@ -90,9 +95,8 @@ class RulesetManagerTest : public DNRTestBase {
CreateExtensionLoader()->LoadExtension(extension_dir);
ASSERT_TRUE(last_loaded_extension_);
- // This is required since we mock ExtensionSystem in our tests.
- SimulateAddExtensionOnIOThread(last_loaded_extension(),
- false /*incognito_enabled*/);
+ ExtensionRegistry::Get(browser_context())
+ ->AddEnabled(last_loaded_extension_);
int expected_checksum;
EXPECT_TRUE(ExtensionPrefs::Get(browser_context())
@@ -110,13 +114,7 @@ class RulesetManagerTest : public DNRTestBase {
void SetIncognitoEnabled(const Extension* extension, bool incognito_enabled) {
util::SetIsIncognitoEnabled(extension->id(), browser_context(),
incognito_enabled);
-
- // This is required since we mock ExtensionSystem in our tests.
- SimulateAddExtensionOnIOThread(extension, incognito_enabled);
- }
-
- InfoMap* info_map() {
- return ExtensionSystem::Get(browser_context())->info_map();
+ ExtensionRegistry::Get(browser_context())->AddEnabled(extension);
}
const Extension* last_loaded_extension() const {
@@ -135,14 +133,11 @@ class RulesetManagerTest : public DNRTestBase {
return info;
}
- private:
- void SimulateAddExtensionOnIOThread(const Extension* extension,
- bool incognito_enabled) {
- info_map()->AddExtension(extension, base::Time(), incognito_enabled,
- false /*notifications_disabled*/);
- }
+ RulesetManager* manager() { return manager_.get(); }
+ private:
scoped_refptr<const Extension> last_loaded_extension_;
+ std::unique_ptr<RulesetManager> manager_;
DISALLOW_COPY_AND_ASSIGN(RulesetManagerTest);
};
@@ -160,18 +155,16 @@ TEST_P(RulesetManagerTest, MultipleRulesets) {
TestRule rule_two = CreateGenericRule();
rule_two.condition->url_filter = std::string("two.com");
- RulesetManager* manager = info_map()->GetRulesetManager();
- ASSERT_TRUE(manager);
-
- auto should_block_request = [manager](const WebRequestInfo& request) {
- return manager->EvaluateRequest(request, false /*is_incognito_context*/) ==
+ auto should_block_request = [this](const WebRequestInfo& request) {
+ return manager()->EvaluateRequest(request,
+ false /*is_incognito_context*/) ==
Action(ActionType::BLOCK);
};
for (int mask = 0; mask < 4; mask++) {
SCOPED_TRACE(base::StringPrintf("Testing ruleset mask %d", mask));
- ASSERT_EQ(0u, manager->GetMatcherCountForTest());
+ ASSERT_EQ(0u, manager()->GetMatcherCountForTest());
std::string extension_id_one, extension_id_two;
size_t expected_matcher_count = 0;
@@ -183,8 +176,8 @@ TEST_P(RulesetManagerTest, MultipleRulesets) {
ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules(
{rule_one}, std::to_string(mask) + "_one", &matcher));
extension_id_one = last_loaded_extension()->id();
- manager->AddRuleset(extension_id_one, std::move(matcher),
- URLPatternSet());
+ manager()->AddRuleset(extension_id_one, std::move(matcher),
+ URLPatternSet());
}
if (mask & kEnableRulesetTwo) {
++expected_matcher_count;
@@ -192,11 +185,11 @@ TEST_P(RulesetManagerTest, MultipleRulesets) {
ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules(
{rule_two}, std::to_string(mask) + "_two", &matcher));
extension_id_two = last_loaded_extension()->id();
- manager->AddRuleset(extension_id_two, std::move(matcher),
- URLPatternSet());
+ manager()->AddRuleset(extension_id_two, std::move(matcher),
+ URLPatternSet());
}
- ASSERT_EQ(expected_matcher_count, manager->GetMatcherCountForTest());
+ ASSERT_EQ(expected_matcher_count, manager()->GetMatcherCountForTest());
WebRequestInfo request_one_info(GetRequestParamsForURL("http://one.com"));
WebRequestInfo request_two_info(GetRequestParamsForURL("http://two.com"));
@@ -211,26 +204,23 @@ TEST_P(RulesetManagerTest, MultipleRulesets) {
// Remove the rulesets.
if (mask & kEnableRulesetOne)
- manager->RemoveRuleset(extension_id_one);
+ manager()->RemoveRuleset(extension_id_one);
if (mask & kEnableRulesetTwo)
- manager->RemoveRuleset(extension_id_two);
+ manager()->RemoveRuleset(extension_id_two);
}
}
// Tests that only extensions enabled in incognito mode can modify requests made
// from the incognito context.
TEST_P(RulesetManagerTest, IncognitoRequests) {
- RulesetManager* manager = info_map()->GetRulesetManager();
- ASSERT_TRUE(manager);
-
// Add an extension ruleset blocking "example.com".
TestRule rule_one = CreateGenericRule();
rule_one.condition->url_filter = std::string("example.com");
std::unique_ptr<CompositeMatcher> matcher;
ASSERT_NO_FATAL_FAILURE(
CreateMatcherForRules({rule_one}, "test_extension", &matcher));
- manager->AddRuleset(last_loaded_extension()->id(), std::move(matcher),
- URLPatternSet());
+ manager()->AddRuleset(last_loaded_extension()->id(), std::move(matcher),
+ URLPatternSet());
WebRequestInfo request_info(GetRequestParamsForURL("http://example.com"));
@@ -240,11 +230,11 @@ TEST_P(RulesetManagerTest, IncognitoRequests) {
browser_context()));
EXPECT_EQ(
Action(ActionType::NONE),
- manager->EvaluateRequest(request_info, true /*is_incognito_context*/));
+ manager()->EvaluateRequest(request_info, true /*is_incognito_context*/));
request_info.dnr_action.reset();
EXPECT_EQ(
Action(ActionType::BLOCK),
- manager->EvaluateRequest(request_info, false /*is_incognito_context*/));
+ manager()->EvaluateRequest(request_info, false /*is_incognito_context*/));
request_info.dnr_action.reset();
// Enabling the extension in incognito mode, should cause requests from
@@ -254,11 +244,11 @@ TEST_P(RulesetManagerTest, IncognitoRequests) {
browser_context()));
EXPECT_EQ(
Action(ActionType::BLOCK),
- manager->EvaluateRequest(request_info, true /*is_incognito_context*/));
+ manager()->EvaluateRequest(request_info, true /*is_incognito_context*/));
request_info.dnr_action.reset();
EXPECT_EQ(
Action(ActionType::BLOCK),
- manager->EvaluateRequest(request_info, false /*is_incognito_context*/));
+ manager()->EvaluateRequest(request_info, false /*is_incognito_context*/));
request_info.dnr_action.reset();
}
@@ -266,9 +256,6 @@ TEST_P(RulesetManagerTest, IncognitoRequests) {
// Extensions.DeclarativeNetRequest.EvaluateRequestTime.AllExtensions2
// is only emitted when there are active rulesets.
TEST_P(RulesetManagerTest, TotalEvaluationTimeHistogram) {
- RulesetManager* manager = info_map()->GetRulesetManager();
- ASSERT_TRUE(manager);
-
WebRequestInfo example_com_request(
GetRequestParamsForURL("http://example.com"));
WebRequestInfo google_com_request(
@@ -280,10 +267,10 @@ TEST_P(RulesetManagerTest, TotalEvaluationTimeHistogram) {
base::HistogramTester tester;
EXPECT_EQ(
Action(ActionType::NONE),
- manager->EvaluateRequest(example_com_request, is_incognito_context));
+ manager()->EvaluateRequest(example_com_request, is_incognito_context));
EXPECT_EQ(
Action(ActionType::NONE),
- manager->EvaluateRequest(google_com_request, is_incognito_context));
+ manager()->EvaluateRequest(google_com_request, is_incognito_context));
tester.ExpectTotalCount(kHistogramName, 0);
example_com_request.dnr_action.reset();
google_com_request.dnr_action.reset();
@@ -295,18 +282,18 @@ TEST_P(RulesetManagerTest, TotalEvaluationTimeHistogram) {
std::unique_ptr<CompositeMatcher> matcher;
ASSERT_NO_FATAL_FAILURE(
CreateMatcherForRules({rule}, "test_extension", &matcher));
- manager->AddRuleset(last_loaded_extension()->id(), std::move(matcher),
- URLPatternSet());
+ manager()->AddRuleset(last_loaded_extension()->id(), std::move(matcher),
+ URLPatternSet());
{
base::HistogramTester tester;
EXPECT_EQ(
Action(ActionType::BLOCK),
- manager->EvaluateRequest(example_com_request, is_incognito_context));
+ manager()->EvaluateRequest(example_com_request, is_incognito_context));
tester.ExpectTotalCount(kHistogramName, 1);
EXPECT_EQ(
Action(ActionType::NONE),
- manager->EvaluateRequest(google_com_request, is_incognito_context));
+ manager()->EvaluateRequest(google_com_request, is_incognito_context));
tester.ExpectTotalCount(kHistogramName, 2);
example_com_request.dnr_action.reset();
google_com_request.dnr_action.reset();
@@ -315,9 +302,6 @@ TEST_P(RulesetManagerTest, TotalEvaluationTimeHistogram) {
// Test redirect rules.
TEST_P(RulesetManagerTest, Redirect) {
- RulesetManager* manager = info_map()->GetRulesetManager();
- ASSERT_TRUE(manager);
-
// Add an extension ruleset which redirects "example.com" to "google.com".
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("example.com");
@@ -328,8 +312,8 @@ TEST_P(RulesetManagerTest, Redirect) {
ASSERT_NO_FATAL_FAILURE(
CreateMatcherForRules({rule}, "test_extension", &matcher,
{"*://example.com/*", "*://abc.com/*"}));
- manager->AddRuleset(last_loaded_extension()->id(), std::move(matcher),
- URLPatternSet());
+ manager()->AddRuleset(last_loaded_extension()->id(), std::move(matcher),
+ URLPatternSet());
// Create a request to "example.com" with an empty initiator. It should be
// redirected to "google.com".
@@ -339,35 +323,32 @@ TEST_P(RulesetManagerTest, Redirect) {
expected_redirect_action.redirect_url = GURL("http://google.com");
WebRequestInfo request_1(GetRequestParamsForURL(kExampleURL, base::nullopt));
EXPECT_EQ(expected_redirect_action,
- manager->EvaluateRequest(request_1, is_incognito_context));
+ manager()->EvaluateRequest(request_1, is_incognito_context));
// Change the initiator to "xyz.com". It should not be redirected since we
// don't have host permissions to the request initiator.
WebRequestInfo request_2(GetRequestParamsForURL(
kExampleURL, url::Origin::Create(GURL("http://xyz.com"))));
EXPECT_EQ(Action(ActionType::NONE),
- manager->EvaluateRequest(request_2, is_incognito_context));
+ manager()->EvaluateRequest(request_2, is_incognito_context));
// Change the initiator to "abc.com". It should be redirected since we have
// the required host permissions.
WebRequestInfo request_3(GetRequestParamsForURL(
kExampleURL, url::Origin::Create(GURL("http://abc.com"))));
EXPECT_EQ(expected_redirect_action,
- manager->EvaluateRequest(request_3, is_incognito_context));
+ manager()->EvaluateRequest(request_3, is_incognito_context));
// Ensure web-socket requests are not redirected.
WebRequestInfo request_4(
GetRequestParamsForURL("ws://example.com", base::nullopt));
EXPECT_EQ(Action(ActionType::NONE),
- manager->EvaluateRequest(request_4, is_incognito_context));
+ manager()->EvaluateRequest(request_4, is_incognito_context));
}
// Tests that an extension can't block or redirect resources on the chrome-
// extension scheme.
TEST_P(RulesetManagerTest, ExtensionScheme) {
- RulesetManager* manager = info_map()->GetRulesetManager();
- ASSERT_TRUE(manager);
-
const Extension* extension_1 = nullptr;
const Extension* extension_2 = nullptr;
// Add an extension with a background page which blocks all requests.
@@ -380,7 +361,8 @@ TEST_P(RulesetManagerTest, ExtensionScheme) {
std::vector<std::string>({URLPattern::kAllUrlsPattern}),
true /* has_background_script*/));
extension_1 = last_loaded_extension();
- manager->AddRuleset(extension_1->id(), std::move(matcher), URLPatternSet());
+ manager()->AddRuleset(extension_1->id(), std::move(matcher),
+ URLPatternSet());
}
// Add another extension with a background page which redirects all requests
@@ -397,17 +379,18 @@ TEST_P(RulesetManagerTest, ExtensionScheme) {
std::vector<std::string>({URLPattern::kAllUrlsPattern}),
true /* has_background_script*/));
extension_2 = last_loaded_extension();
- manager->AddRuleset(extension_2->id(), std::move(matcher), URLPatternSet());
+ manager()->AddRuleset(extension_2->id(), std::move(matcher),
+ URLPatternSet());
}
- EXPECT_EQ(2u, manager->GetMatcherCountForTest());
+ EXPECT_EQ(2u, manager()->GetMatcherCountForTest());
// Ensure that "http://example.com" will be blocked (with blocking taking
// priority over redirection).
WebRequestInfo request_1(GetRequestParamsForURL("http://example.com"));
EXPECT_EQ(
Action(ActionType::BLOCK),
- manager->EvaluateRequest(request_1, false /*is_incognito_context*/));
+ manager()->EvaluateRequest(request_1, false /*is_incognito_context*/));
// Ensure that the background page for |extension_1| won't be blocked or
// redirected.
@@ -417,7 +400,7 @@ TEST_P(RulesetManagerTest, ExtensionScheme) {
GetRequestParamsForURL(background_page_url_1.spec()));
EXPECT_EQ(
Action(ActionType::NONE),
- manager->EvaluateRequest(request_2, false /*is_incognito_context*/));
+ manager()->EvaluateRequest(request_2, false /*is_incognito_context*/));
// Ensure that the background page for |extension_2| won't be blocked or
// redirected.
@@ -427,7 +410,7 @@ TEST_P(RulesetManagerTest, ExtensionScheme) {
GetRequestParamsForURL(background_page_url_2.spec()));
EXPECT_EQ(
Action(ActionType::NONE),
- manager->EvaluateRequest(request_3, false /*is_incognito_context*/));
+ manager()->EvaluateRequest(request_3, false /*is_incognito_context*/));
// Also ensure that an arbitrary url on the chrome extension scheme is also
// not blocked or redirected.
@@ -435,13 +418,10 @@ TEST_P(RulesetManagerTest, ExtensionScheme) {
"%s://%s/%s", kExtensionScheme, "extension_id", "path")));
EXPECT_EQ(
Action(ActionType::NONE),
- manager->EvaluateRequest(request_4, false /*is_incognito_context*/));
+ manager()->EvaluateRequest(request_4, false /*is_incognito_context*/));
}
TEST_P(RulesetManagerTest, PageAllowingAPI) {
- RulesetManager* manager = info_map()->GetRulesetManager();
- ASSERT_TRUE(manager);
-
// Add an extension which blocks all requests except for requests from
// http://google.com/allow* which are allowed.
{
@@ -465,8 +445,8 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) {
URLPatternSet pattern_set(
{URLPattern(URLPattern::SCHEME_ALL, "http://google.com/allow*")});
- manager->AddRuleset(last_loaded_extension()->id(), std::move(matcher),
- std::move(pattern_set));
+ manager()->AddRuleset(last_loaded_extension()->id(), std::move(matcher),
+ std::move(pattern_set));
}
constexpr int kDummyFrameRoutingId = 2;
@@ -594,15 +574,12 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) {
? Action(ActionType::BLOCK)
: Action(ActionType::NONE);
EXPECT_EQ(expected_action,
- manager->EvaluateRequest(WebRequestInfo(std::move(params)),
- false /*is_incognito_context*/));
+ manager()->EvaluateRequest(WebRequestInfo(std::move(params)),
+ false /*is_incognito_context*/));
}
}
TEST_P(RulesetManagerTest, HostPermissionForInitiator) {
- RulesetManager* manager = info_map()->GetRulesetManager();
- ASSERT_TRUE(manager);
-
// Add an extension which redirects all sub-resource and sub-frame requests
// made to example.com, to foo.com. By default, the "main_frame" type is
// excluded if no "resource_types" are specified.
@@ -660,10 +637,9 @@ TEST_P(RulesetManagerTest, HostPermissionForInitiator) {
ActionType::NONE, ActionType::BLOCK},
};
- auto verify_test_case = [this, manager](
- const std::string& url,
- const base::Optional<url::Origin>& initiator,
- const Action& expected_action) {
+ auto verify_test_case = [this](const std::string& url,
+ const base::Optional<url::Origin>& initiator,
+ const Action& expected_action) {
SCOPED_TRACE(base::StringPrintf(
"Url-%s initiator-%s", url.c_str(),
initiator ? initiator->Serialize().c_str() : "empty"));
@@ -672,14 +648,14 @@ TEST_P(RulesetManagerTest, HostPermissionForInitiator) {
bool is_incognito_context = false;
EXPECT_EQ(expected_action,
- manager->EvaluateRequest(request, is_incognito_context));
+ manager()->EvaluateRequest(request, is_incognito_context));
};
// Test redirect extension.
{
SCOPED_TRACE("Testing redirect extension");
- manager->AddRuleset(redirect_extension_id, std::move(redirect_matcher),
- URLPatternSet());
+ manager()->AddRuleset(redirect_extension_id, std::move(redirect_matcher),
+ URLPatternSet());
for (const auto& test : cases) {
Action expected_action(test.expected_action_redirect_extension);
if (test.expected_action_redirect_extension == ActionType::REDIRECT)
@@ -687,19 +663,19 @@ TEST_P(RulesetManagerTest, HostPermissionForInitiator) {
verify_test_case(test.url, test.initiator, expected_action);
}
- manager->RemoveRuleset(redirect_extension_id);
+ manager()->RemoveRuleset(redirect_extension_id);
}
// Test blocking extension.
{
SCOPED_TRACE("Testing blocking extension");
- manager->AddRuleset(blocking_extension_id, std::move(blocking_matcher),
- URLPatternSet());
+ manager()->AddRuleset(blocking_extension_id, std::move(blocking_matcher),
+ URLPatternSet());
for (const auto& test : cases) {
verify_test_case(test.url, test.initiator,
Action(test.expected_action_blocking_extension));
}
- manager->RemoveRuleset(blocking_extension_id);
+ manager()->RemoveRuleset(blocking_extension_id);
}
}
diff --git a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc
index fcfdf5db350..fe07b62a6cf 100644
--- a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc
@@ -15,6 +15,7 @@
#include "base/test/values_test_util.h"
#include "base/time/time.h"
#include "base/values.h"
+#include "chrome/browser/extensions/extension_service_test_base.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/extension_test_util.h"
@@ -22,16 +23,13 @@
#include "extensions/browser/api/declarative_webrequest/request_stage.h"
#include "extensions/browser/api/declarative_webrequest/webrequest_condition.h"
#include "extensions/browser/api/declarative_webrequest/webrequest_constants.h"
+#include "extensions/browser/api/web_request/permission_helper.h"
#include "extensions/browser/api/web_request/web_request_api_helpers.h"
#include "extensions/browser/api/web_request/web_request_info.h"
-#include "extensions/browser/info_map.h"
+#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "extensions/common/extensions_client.h"
-#include "net/base/request_priority.h"
#include "net/http/http_response_headers.h"
-#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
-#include "net/url_request/url_request.h"
-#include "net/url_request/url_request_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -76,11 +74,7 @@ std::unique_ptr<WebRequestActionSet> CreateSetOfActions(const char* json) {
} // namespace
-class WebRequestActionWithThreadsTest : public testing::Test {
- public:
- WebRequestActionWithThreadsTest()
- : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {}
-
+class WebRequestActionWithThreadsTest : public ExtensionServiceTestBase {
protected:
void SetUp() override;
@@ -98,21 +92,15 @@ class WebRequestActionWithThreadsTest : public testing::Test {
// executable for http://clients1.google.com.
void CheckActionNeedsAllUrls(const char* action, RequestStage stage);
- private:
- content::TestBrowserThreadBundle thread_bundle_;
-
- protected:
- net::TestURLRequestContext context_;
-
// An extension with *.com host permissions and the DWR permission.
scoped_refptr<Extension> extension_;
// An extension with host permissions for all URLs and the DWR permission.
scoped_refptr<Extension> extension_all_urls_;
- scoped_refptr<InfoMap> extension_info_map_;
};
void WebRequestActionWithThreadsTest::SetUp() {
- testing::Test::SetUp();
+ ExtensionServiceTestBase::SetUp();
+ InitializeEmptyExtensionService();
std::string error;
extension_ = LoadManifestUnchecked("permissions",
@@ -130,17 +118,8 @@ void WebRequestActionWithThreadsTest::SetUp() {
"ext_id_2",
&error);
ASSERT_TRUE(extension_all_urls_.get()) << error;
- extension_info_map_ = new InfoMap;
- ASSERT_TRUE(extension_info_map_.get());
- extension_info_map_->AddExtension(
- extension_.get(),
- base::Time::Now(),
- false /*incognito_enabled*/,
- false /*notifications_disabled*/);
- extension_info_map_->AddExtension(extension_all_urls_.get(),
- base::Time::Now(),
- false /*incognito_enabled*/,
- false /*notifications_disabled*/);
+ ExtensionRegistry::Get(browser_context())->AddEnabled(extension_);
+ ExtensionRegistry::Get(browser_context())->AddEnabled(extension_all_urls_);
}
bool WebRequestActionWithThreadsTest::ActionWorksOnRequest(
@@ -149,21 +128,19 @@ bool WebRequestActionWithThreadsTest::ActionWorksOnRequest(
const WebRequestActionSet* action_set,
RequestStage stage) {
const int kRendererId = 2;
- std::unique_ptr<net::URLRequest> regular_request(
- context_.CreateRequest(GURL(url_string), net::DEFAULT_PRIORITY, NULL,
- TRAFFIC_ANNOTATION_FOR_TESTS));
EventResponseDeltas deltas;
scoped_refptr<net::HttpResponseHeaders> headers(
new net::HttpResponseHeaders(""));
- WebRequestInfoInitParams request_params(regular_request.get());
+ WebRequestInfoInitParams params;
+ params.url = GURL(url_string);
+ WebRequestInfoInitParams request_params(std::move(params));
request_params.render_process_id = kRendererId;
WebRequestInfo request_info(std::move(request_params));
WebRequestData request_data(&request_info, stage, headers.get());
std::set<std::string> ignored_tags;
- WebRequestAction::ApplyInfo apply_info = { extension_info_map_.get(),
- request_data,
- false /*crosses_incognito*/,
- &deltas, &ignored_tags };
+ WebRequestAction::ApplyInfo apply_info = {
+ PermissionHelper::Get(browser_context()), request_data,
+ false /*crosses_incognito*/, &deltas, &ignored_tags};
action_set->Apply(extension_id, base::Time(), &apply_info);
return (1u == deltas.size() || !ignored_tags.empty());
}
diff --git a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc
index 51d86cb4112..5ac5e3a80c3 100644
--- a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc
@@ -17,12 +17,16 @@
#include "base/test/values_test_util.h"
#include "base/values.h"
#include "chrome/common/extensions/extension_test_util.h"
+#include "chrome/test/base/testing_profile.h"
#include "components/url_matcher/url_matcher_constants.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "extensions/browser/api/declarative/rules_registry_service.h"
#include "extensions/browser/api/declarative_webrequest/webrequest_constants.h"
+#include "extensions/browser/api/web_request/permission_helper.h"
#include "extensions/browser/api/web_request/web_request_api_helpers.h"
#include "extensions/browser/api/web_request/web_request_info.h"
+#include "extensions/browser/extension_prefs.h"
+#include "extensions/browser/extension_registry.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest-message.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -42,8 +46,8 @@ using url_matcher::URLMatcher;
namespace extensions {
namespace {
-const char kExtensionId[] = "ext1";
-const char kExtensionId2[] = "ext2";
+const char kExtensionId[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+const char kExtensionId2[] = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
const char kRuleId1[] = "rule1";
const char kRuleId2[] = "rule2";
const char kRuleId3[] = "rule3";
@@ -53,7 +57,7 @@ const char kRuleId4[] = "rule4";
WebRequestInfoInitParams CreateRequestParams(const GURL& url) {
WebRequestInfoInitParams info;
info.url = url;
- info.is_browser_side_navigation = true;
+ info.is_navigation_request = true;
info.type = content::ResourceType::kMainFrame;
info.web_request_type = WebRequestResourceType::MAIN_FRAME;
return info;
@@ -63,14 +67,11 @@ WebRequestInfoInitParams CreateRequestParams(const GURL& url) {
class TestWebRequestRulesRegistry : public WebRequestRulesRegistry {
public:
- explicit TestWebRequestRulesRegistry(
- scoped_refptr<InfoMap> extension_info_map)
- : WebRequestRulesRegistry(NULL /*profile*/,
- NULL /* cache_delegate */,
+ explicit TestWebRequestRulesRegistry(content::BrowserContext* context)
+ : WebRequestRulesRegistry(context,
+ nullptr /* cache_delegate */,
RulesRegistryService::kDefaultRulesRegistryID),
- num_clear_cache_calls_(0) {
- SetExtensionInfoMapForTesting(extension_info_map);
- }
+ num_clear_cache_calls_(0) {}
// Returns how often the in-memory caches of the renderers were instructed
// to be cleared.
@@ -93,12 +94,6 @@ class TestWebRequestRulesRegistry : public WebRequestRulesRegistry {
class WebRequestRulesRegistryTest : public testing::Test {
public:
- WebRequestRulesRegistryTest()
- : test_browser_thread_bundle_(
- content::TestBrowserThreadBundle::IO_MAINLOOP) {}
-
- ~WebRequestRulesRegistryTest() override {}
-
void SetUp() override;
void TearDown() override {
@@ -229,12 +224,12 @@ class WebRequestRulesRegistryTest : public testing::Test {
protected:
content::TestBrowserThreadBundle test_browser_thread_bundle_;
+ TestingProfile profile_;
// Two extensions with host permissions for all URLs and the DWR permission.
// Installation times will be so that |extension_| is older than
// |extension2_|.
scoped_refptr<Extension> extension_;
scoped_refptr<Extension> extension2_;
- scoped_refptr<InfoMap> extension_info_map_;
};
void WebRequestRulesRegistryTest::SetUp() {
@@ -255,22 +250,20 @@ void WebRequestRulesRegistryTest::SetUp() {
kExtensionId2,
&error);
ASSERT_TRUE(extension2_.get()) << error;
- extension_info_map_ = new InfoMap;
- ASSERT_TRUE(extension_info_map_.get());
- extension_info_map_->AddExtension(extension_.get(),
- base::Time() + base::TimeDelta::FromDays(1),
- false /*incognito_enabled*/,
- false /*notifications_disabled*/);
- extension_info_map_->AddExtension(extension2_.get(),
- base::Time() + base::TimeDelta::FromDays(2),
- false /*incognito_enabled*/,
- false /*notifications_disabled*/);
+ CHECK(ExtensionRegistry::Get(&profile_));
+ ExtensionRegistry::Get(&profile_)->AddEnabled(extension_);
+ ExtensionPrefs::Get(&profile_)->OnExtensionInstalled(
+ extension_.get(), Extension::State::ENABLED, syncer::StringOrdinal(), "");
+ ExtensionRegistry::Get(&profile_)->AddEnabled(extension2_);
+ ExtensionPrefs::Get(&profile_)->OnExtensionInstalled(
+ extension2_.get(), Extension::State::ENABLED, syncer::StringOrdinal(),
+ "");
}
TEST_F(WebRequestRulesRegistryTest, AddRulesImpl) {
scoped_refptr<TestWebRequestRulesRegistry> registry(
- new TestWebRequestRulesRegistry(extension_info_map_));
+ new TestWebRequestRulesRegistry(&profile_));
std::string error;
{
@@ -295,9 +288,9 @@ TEST_F(WebRequestRulesRegistryTest, AddRulesImpl) {
for (auto it = matches.cbegin(); it != matches.cend(); ++it)
matches_ids.insert((*it)->id());
EXPECT_TRUE(
- base::ContainsKey(matches_ids, std::make_pair(kExtensionId, kRuleId1)));
+ base::Contains(matches_ids, std::make_pair(kExtensionId, kRuleId1)));
EXPECT_TRUE(
- base::ContainsKey(matches_ids, std::make_pair(kExtensionId, kRuleId2)));
+ base::Contains(matches_ids, std::make_pair(kExtensionId, kRuleId2)));
GURL foobar_url("http://www.foobar.com");
WebRequestInfo foobar_request_info(CreateRequestParams(foobar_url));
@@ -311,7 +304,7 @@ TEST_F(WebRequestRulesRegistryTest, AddRulesImpl) {
TEST_F(WebRequestRulesRegistryTest, RemoveRulesImpl) {
scoped_refptr<TestWebRequestRulesRegistry> registry(
- new TestWebRequestRulesRegistry(extension_info_map_));
+ new TestWebRequestRulesRegistry(&profile_));
std::string error;
// Setup RulesRegistry to contain two rules.
@@ -361,7 +354,7 @@ TEST_F(WebRequestRulesRegistryTest, RemoveRulesImpl) {
TEST_F(WebRequestRulesRegistryTest, RemoveAllRulesImpl) {
scoped_refptr<TestWebRequestRulesRegistry> registry(
- new TestWebRequestRulesRegistry(extension_info_map_));
+ new TestWebRequestRulesRegistry(&profile_));
std::string error;
{
@@ -418,7 +411,7 @@ TEST_F(WebRequestRulesRegistryTest, RemoveAllRulesImpl) {
// Test precedences between extensions.
TEST_F(WebRequestRulesRegistryTest, Precedences) {
scoped_refptr<WebRequestRulesRegistry> registry(
- new TestWebRequestRulesRegistry(extension_info_map_));
+ new TestWebRequestRulesRegistry(&profile_));
std::string error;
{
@@ -438,8 +431,8 @@ TEST_F(WebRequestRulesRegistryTest, Precedences) {
GURL url("http://www.google.com");
WebRequestInfo request_info(CreateRequestParams(url));
WebRequestData request_data(&request_info, ON_BEFORE_REQUEST);
- EventResponseDeltas deltas =
- registry->CreateDeltas(NULL, request_data, false);
+ EventResponseDeltas deltas = registry->CreateDeltas(
+ PermissionHelper::Get(&profile_), request_data, false);
// The second extension is installed later and will win for this reason
// in conflict resolution.
@@ -450,20 +443,17 @@ TEST_F(WebRequestRulesRegistryTest, Precedences) {
const EventResponseDelta& loser = deltas.back();
EXPECT_EQ(kExtensionId2, winner.extension_id);
- EXPECT_EQ(base::Time() + base::TimeDelta::FromDays(2),
- winner.extension_install_time);
EXPECT_EQ(GURL("http://www.bar.com"), winner.new_url);
+ EXPECT_GT(winner.extension_install_time, loser.extension_install_time);
EXPECT_EQ(kExtensionId, loser.extension_id);
- EXPECT_EQ(base::Time() + base::TimeDelta::FromDays(1),
- loser.extension_install_time);
EXPECT_EQ(GURL("http://www.foo.com"), loser.new_url);
}
// Test priorities of rules within one extension.
TEST_F(WebRequestRulesRegistryTest, Priorities) {
scoped_refptr<WebRequestRulesRegistry> registry(
- new TestWebRequestRulesRegistry(extension_info_map_));
+ new TestWebRequestRulesRegistry(&profile_));
std::string error;
{
@@ -490,16 +480,14 @@ TEST_F(WebRequestRulesRegistryTest, Priorities) {
GURL url("http://www.google.com/index.html");
WebRequestInfo request_info(CreateRequestParams(url));
WebRequestData request_data(&request_info, ON_BEFORE_REQUEST);
- EventResponseDeltas deltas =
- registry->CreateDeltas(nullptr, request_data, false);
+ EventResponseDeltas deltas = registry->CreateDeltas(
+ PermissionHelper::Get(&profile_), request_data, false);
// The redirect by the first extension is ignored due to the ignore rule.
ASSERT_EQ(1u, deltas.size());
const EventResponseDelta& effective_rule = *deltas.begin();
EXPECT_EQ(kExtensionId2, effective_rule.extension_id);
- EXPECT_EQ(base::Time() + base::TimeDelta::FromDays(2),
- effective_rule.extension_install_time);
EXPECT_EQ(GURL("http://www.bar.com"), effective_rule.new_url);
}
@@ -558,7 +546,7 @@ TEST_F(WebRequestRulesRegistryTest, IgnoreRulesByTag) {
ASSERT_TRUE(api::events::Rule::Populate(*value2, &rule2));
scoped_refptr<WebRequestRulesRegistry> registry(
- new TestWebRequestRulesRegistry(extension_info_map_));
+ new TestWebRequestRulesRegistry(&profile_));
std::string error = registry->AddRulesImpl(kExtensionId, rules);
EXPECT_EQ("", error);
EXPECT_FALSE(registry->IsEmpty());
@@ -566,8 +554,8 @@ TEST_F(WebRequestRulesRegistryTest, IgnoreRulesByTag) {
GURL url("http://www.foo.com/test");
WebRequestInfo request_info(CreateRequestParams(url));
WebRequestData request_data(&request_info, ON_BEFORE_REQUEST);
- EventResponseDeltas deltas =
- registry->CreateDeltas(NULL, request_data, false);
+ EventResponseDeltas deltas = registry->CreateDeltas(
+ PermissionHelper::Get(&profile_), request_data, false);
// The redirect by the redirect rule is ignored due to the ignore rule.
std::set<const WebRequestRule*> matches = registry->GetMatches(request_data);
@@ -579,7 +567,7 @@ TEST_F(WebRequestRulesRegistryTest, IgnoreRulesByTag) {
// GetMatches.
TEST_F(WebRequestRulesRegistryTest, GetMatchesCheckFulfilled) {
scoped_refptr<TestWebRequestRulesRegistry> registry(
- new TestWebRequestRulesRegistry(extension_info_map_));
+ new TestWebRequestRulesRegistry(&profile_));
const std::string kMatchingUrlAttribute(
"\"url\": { \"pathContains\": \"\" }, \n");
const std::string kNonMatchingNonUrlAttribute(
@@ -628,7 +616,7 @@ TEST_F(WebRequestRulesRegistryTest, GetMatchesCheckFulfilled) {
// differ.
TEST_F(WebRequestRulesRegistryTest, GetMatchesDifferentUrls) {
scoped_refptr<TestWebRequestRulesRegistry> registry(
- new TestWebRequestRulesRegistry(extension_info_map_));
+ new TestWebRequestRulesRegistry(&profile_));
const std::string kUrlAttribute(
"\"url\": { \"hostContains\": \"url\" }, \n");
const std::string kFirstPartyUrlAttribute(
@@ -814,7 +802,7 @@ TEST_F(WebRequestRulesRegistryTest, CheckOriginAndPathRegEx) {
ASSERT_TRUE(api::events::Rule::Populate(*value, &rule));
scoped_refptr<WebRequestRulesRegistry> registry(
- new TestWebRequestRulesRegistry(extension_info_map_));
+ new TestWebRequestRulesRegistry(&profile_));
URLMatcher matcher;
std::string error = registry->AddRulesImpl(kExtensionId, rules);
@@ -826,14 +814,16 @@ TEST_F(WebRequestRulesRegistryTest, CheckOriginAndPathRegEx) {
GURL url1("http://bar.com/index.html?foo.com");
WebRequestInfo request1_info(CreateRequestParams(url1));
WebRequestData request_data1(&request1_info, ON_BEFORE_REQUEST);
- deltas = registry->CreateDeltas(NULL, request_data1, false);
+ deltas = registry->CreateDeltas(PermissionHelper::Get(&profile_),
+ request_data1, false);
EXPECT_EQ(0u, deltas.size());
// This is a correct match.
GURL url2("http://foo.com/index.html");
WebRequestInfo request2_info(CreateRequestParams(url2));
WebRequestData request_data2(&request2_info, ON_BEFORE_REQUEST);
- deltas = registry->CreateDeltas(NULL, request_data2, false);
+ deltas = registry->CreateDeltas(PermissionHelper::Get(&profile_),
+ request_data2, false);
EXPECT_EQ(1u, deltas.size());
}
diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc
index 99e44945f48..a923c4d2d71 100644
--- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc
@@ -61,13 +61,12 @@
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
+#include "content/public/browser/system_connector.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/drop_data.h"
-#include "content/public/common/service_manager_connection.h"
#include "extensions/browser/api/file_handlers/app_file_handler_util.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/browser/app_window/app_window_registry.h"
-#include "extensions/browser/content_verifier.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/error_map.h"
#include "extensions/browser/event_router_factory.h"
@@ -352,7 +351,7 @@ DeveloperPrivateAPI* DeveloperPrivateAPI::Get(
}
DeveloperPrivateAPI::DeveloperPrivateAPI(content::BrowserContext* context)
- : profile_(Profile::FromBrowserContext(context)), weak_factory_(this) {
+ : profile_(Profile::FromBrowserContext(context)) {
RegisterNotifications();
}
@@ -366,8 +365,7 @@ DeveloperPrivateEventRouter::DeveloperPrivateEventRouter(Profile* profile)
extension_management_observer_(this),
command_service_observer_(this),
profile_(profile),
- event_router_(EventRouter::Get(profile_)),
- weak_factory_(this) {
+ event_router_(EventRouter::Get(profile_)) {
extension_registry_observer_.Add(ExtensionRegistry::Get(profile_));
error_console_observer_.Add(ErrorConsole::Get(profile));
process_manager_observer_.Add(ProcessManager::Get(profile));
@@ -1220,9 +1218,8 @@ DeveloperPrivateInstallDroppedFileFunction::Run() {
ExtensionService* service = GetExtensionService(browser_context());
if (path.MatchesExtension(FILE_PATH_LITERAL(".zip"))) {
- ZipFileInstaller::Create(
- content::ServiceManagerConnection::GetForProcess()->GetConnector(),
- MakeRegisterInExtensionServiceCallback(service))
+ ZipFileInstaller::Create(content::GetSystemConnector(),
+ MakeRegisterInExtensionServiceCallback(service))
->LoadFromZipFile(path);
} else {
auto prompt = std::make_unique<ExtensionInstallPrompt>(web_contents);
@@ -1882,7 +1879,7 @@ DeveloperPrivateRepairExtensionFunction::Run() {
// Also note that if we let |reinstaller| continue with the repair, this would
// have uninstalled the extension but then we would have failed to reinstall
// it for policy check (see PolicyCheck::Start()).
- if (ContentVerifier::ShouldRepairIfCorrupted(management_policy, extension))
+ if (management_policy->ShouldRepairIfCorrupted(extension))
return RespondNow(Error(kCannotRepairPolicyExtension));
content::WebContents* web_contents = GetSenderWebContents();
diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h
index 9785abc3336..4113d204780 100644
--- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h
+++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h
@@ -175,7 +175,7 @@ class DeveloperPrivateEventRouter : public ExtensionRegistryObserver,
content::NotificationRegistrar notification_registrar_;
- base::WeakPtrFactory<DeveloperPrivateEventRouter> weak_factory_;
+ base::WeakPtrFactory<DeveloperPrivateEventRouter> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateEventRouter);
};
@@ -283,7 +283,7 @@ class DeveloperPrivateAPI : public BrowserContextKeyedAPI,
// Created lazily upon OnListenerAdded.
std::unique_ptr<DeveloperPrivateEventRouter> developer_private_event_router_;
- base::WeakPtrFactory<DeveloperPrivateAPI> weak_factory_;
+ base::WeakPtrFactory<DeveloperPrivateAPI> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateAPI);
};
diff --git a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc
index c885dc1aa37..e083fc2499d 100644
--- a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc
+++ b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc
@@ -398,9 +398,7 @@ ExtensionInfoGenerator::ExtensionInfoGenerator(
warning_service_(WarningService::Get(browser_context)),
error_console_(ErrorConsole::Get(browser_context)),
image_loader_(ImageLoader::Get(browser_context)),
- pending_image_loads_(0u),
- weak_factory_(this) {
-}
+ pending_image_loads_(0u) {}
ExtensionInfoGenerator::~ExtensionInfoGenerator() {
}
diff --git a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.h b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.h
index 84628f86bd8..43f14e8a704 100644
--- a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.h
+++ b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.h
@@ -97,7 +97,7 @@ class ExtensionInfoGenerator {
// The callback to run once all infos have been created.
ExtensionInfosCallback callback_;
- base::WeakPtrFactory<ExtensionInfoGenerator> weak_factory_;
+ base::WeakPtrFactory<ExtensionInfoGenerator> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ExtensionInfoGenerator);
};
diff --git a/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc b/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc
index e025c5a9ee7..d51463b16ef 100644
--- a/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc
@@ -74,13 +74,13 @@ class DevicePermissionsManagerTest : public testing::Test {
->SetFakeHidManagerForTesting(std::move(hid_manager_ptr));
base::RunLoop().RunUntilIdle();
- device4_ = fake_hid_manager_.CreateAndAddDevice("Test HID Device", "abcde",
+ device4_ = fake_hid_manager_.CreateAndAddDevice(
+ 0, 0, "Test HID Device", "abcde", HidBusType::kHIDBusTypeUSB);
+ device5_ = fake_hid_manager_.CreateAndAddDevice(0, 0, "Test HID Device", "",
HidBusType::kHIDBusTypeUSB);
- device5_ = fake_hid_manager_.CreateAndAddDevice("Test HID Device", "",
- HidBusType::kHIDBusTypeUSB);
- device6_ = fake_hid_manager_.CreateAndAddDevice("Test HID Device", "67890",
- HidBusType::kHIDBusTypeUSB);
- device7_ = fake_hid_manager_.CreateAndAddDevice("Test HID Device", "",
+ device6_ = fake_hid_manager_.CreateAndAddDevice(
+ 0, 0, "Test HID Device", "67890", HidBusType::kHIDBusTypeUSB);
+ device7_ = fake_hid_manager_.CreateAndAddDevice(0, 0, "Test HID Device", "",
HidBusType::kHIDBusTypeUSB);
}
diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc
index e9237e6585a..689928221a8 100644
--- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc
+++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc
@@ -45,7 +45,6 @@
#include "chrome/browser/download/download_query.h"
#include "chrome/browser/download/download_shelf.h"
#include "chrome/browser/download/download_stats.h"
-#include "chrome/browser/download/drag_download_item.h"
#include "chrome/browser/extensions/chrome_extension_function_details.h"
#include "chrome/browser/icon_loader.h"
#include "chrome/browser/icon_manager.h"
@@ -148,6 +147,8 @@ const char kDangerSafe[] = "safe";
const char kDangerUncommon[] = "uncommon";
const char kDangerUnwanted[] = "unwanted";
const char kDangerWhitelistedByPolicy[] = "whitelistedByPolicy";
+const char kDangerAsyncScanning[] = "asyncScanning";
+const char kDangerPasswordProtected[] = "passwordProtected";
const char kDangerUrl[] = "url";
const char kEndTimeKey[] = "endTime";
const char kEndedAfterKey[] = "endedAfter";
@@ -182,11 +183,12 @@ const char kFinalUrlRegexKey[] = "finalUrlRegex";
// Note: Any change to the danger type strings, should be accompanied by a
// corresponding change to downloads.json.
const char* const kDangerStrings[] = {
- kDangerSafe, kDangerFile,
- kDangerUrl, kDangerContent,
- kDangerSafe, kDangerUncommon,
- kDangerAccepted, kDangerHost,
- kDangerUnwanted, kDangerWhitelistedByPolicy};
+ kDangerSafe, kDangerFile,
+ kDangerUrl, kDangerContent,
+ kDangerSafe, kDangerUncommon,
+ kDangerAccepted, kDangerHost,
+ kDangerUnwanted, kDangerWhitelistedByPolicy,
+ kDangerAsyncScanning, kDangerPasswordProtected};
static_assert(base::size(kDangerStrings) == download::DOWNLOAD_DANGER_TYPE_MAX,
"kDangerStrings should have DOWNLOAD_DANGER_TYPE_MAX elements");
@@ -1492,36 +1494,6 @@ void DownloadsOpenFunction::OpenPromptDone(int download_id, bool accept) {
Respond(NoArguments());
}
-DownloadsDragFunction::DownloadsDragFunction() {}
-
-DownloadsDragFunction::~DownloadsDragFunction() {}
-
-ExtensionFunction::ResponseAction DownloadsDragFunction::Run() {
- std::unique_ptr<downloads::Drag::Params> params(
- downloads::Drag::Params::Create(*args_));
- EXTENSION_FUNCTION_VALIDATE(params.get());
- DownloadItem* download_item = GetDownload(
- browser_context(), include_incognito_information(), params->download_id);
- content::WebContents* web_contents =
- dispatcher()->GetVisibleWebContents();
- std::string error;
- if (InvalidId(download_item, &error) ||
- Fault(!web_contents, download_extension_errors::kInvisibleContext,
- &error)) {
- return RespondNow(Error(error));
- }
- RecordApiFunctions(DOWNLOADS_FUNCTION_DRAG);
- gfx::Image* icon = g_browser_process->icon_manager()->LookupIconFromFilepath(
- download_item->GetTargetFilePath(), IconLoader::NORMAL);
- gfx::NativeView view = web_contents->GetNativeView();
- {
- // Enable nested tasks during DnD, while |DragDownload()| blocks.
- base::MessageLoopCurrent::ScopedNestableTaskAllower allow;
- DragDownloadItem(download_item, icon, view);
- }
- return RespondNow(NoArguments());
-}
-
DownloadsSetShelfEnabledFunction::DownloadsSetShelfEnabledFunction() {}
DownloadsSetShelfEnabledFunction::~DownloadsSetShelfEnabledFunction() {}
diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h
index 7a44733c8c3..105cbe800e6 100644
--- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h
+++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h
@@ -275,19 +275,6 @@ class DownloadsSetShelfEnabledFunction : public UIThreadExtensionFunction {
DISALLOW_COPY_AND_ASSIGN(DownloadsSetShelfEnabledFunction);
};
-class DownloadsDragFunction : public UIThreadExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("downloads.drag", DOWNLOADS_DRAG)
- DownloadsDragFunction();
- ResponseAction Run() override;
-
- protected:
- ~DownloadsDragFunction() override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(DownloadsDragFunction);
-};
-
class DownloadsGetFileIconFunction : public ChromeAsyncExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("downloads.getFileIcon", DOWNLOADS_GETFILEICON)
diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc
index 734a2c28b0c..039b3d9d3d8 100644
--- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc
@@ -32,7 +32,6 @@
#include "chrome/browser/extensions/api/downloads_internal/downloads_internal_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
-#include "chrome/browser/net/url_request_mock_util.h"
#include "chrome/browser/platform_util_internal.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
@@ -54,6 +53,7 @@
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
+#include "content/public/test/browser_test_utils.h"
#include "content/public/test/download_test_observer.h"
#include "content/public/test/test_download_http_response.h"
#include "content/public/test/test_navigation_observer.h"
@@ -349,6 +349,7 @@ class DownloadExtensionTest : public ExtensionApiTest {
current_browser(),
extension_->GetResourceURL("empty.html"),
ui::PAGE_TRANSITION_LINK);
+ EXPECT_TRUE(content::WaitForLoadStop(tab));
EventRouter::Get(current_browser()->profile())
->AddEventListener(downloads::OnCreated::kEventName,
tab->GetMainFrame()->GetProcess(), GetExtensionId());
@@ -383,9 +384,6 @@ class DownloadExtensionTest : public ExtensionApiTest {
// InProcessBrowserTest
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&chrome_browser_net::SetUrlRequestMocksEnabled, true));
GoOnTheRecord();
current_browser()->profile()->GetPrefs()->SetBoolean(
prefs::kPromptForDownload, false);
@@ -1237,14 +1235,6 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
RunFunction(new DownloadsShowDefaultFolderFunction(),
DownloadItemIdAsArgList(item.get()));
}
-
-IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
- DownloadsDragFunction) {
- ScopedCancellingItem item(CreateFirstSlowTestDownload());
- ASSERT_TRUE(item.get());
-
- RunFunction(new DownloadsDragFunction(), DownloadItemIdAsArgList(item.get()));
-}
#endif
diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc
index bc7a300145b..eff7bf7ddfb 100644
--- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc
@@ -100,7 +100,7 @@ class DownloadsApiUnitTest : public ExtensionApiUnittest {
private:
void QueryDownloads(
- const HistoryService::DownloadQueryCallback& callback) override {}
+ HistoryService::DownloadQueryCallback callback) override {}
};
// Constructs and returns a TestDownloadCoreService.
diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc
index 8e7a0466dff..5fa0fffc205 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc
@@ -33,9 +33,9 @@
#include "components/account_id/account_id.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/prefs/pref_service.h"
+#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/user_manager/scoped_user_manager.h"
#include "extensions/common/extension_builder.h"
-#include "services/identity/public/cpp/identity_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
@@ -172,9 +172,9 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest {
}
// Derived classes can override this method to set the required authenticated
- // user in the SigninManager class.
+ // user in the IdentityManager class.
virtual void SetAuthenticatedUser() {
- identity::MakePrimaryAccountAvailable(
+ signin::MakePrimaryAccountAvailable(
IdentityManagerFactory::GetForProfile(browser()->profile()),
kUserEmail);
}
@@ -588,7 +588,7 @@ class EPKChallengeMachineKeyUnmanagedUserTest
: public EPKChallengeMachineKeyTest {
protected:
void SetAuthenticatedUser() override {
- identity::MakePrimaryAccountAvailable(
+ signin::MakePrimaryAccountAvailable(
IdentityManagerFactory::GetForProfile(browser()->profile()),
account_id_.GetUserEmail());
}
@@ -601,7 +601,7 @@ class EPKChallengeMachineKeyUnmanagedUserTest
const std::string email = "test@chromium.com";
const AccountId account_id_ =
AccountId::FromUserEmailGaiaId(email,
- identity::GetTestGaiaIdForEmail(email));
+ signin::GetTestGaiaIdForEmail(email));
};
TEST_F(EPKChallengeMachineKeyUnmanagedUserTest, UserNotManaged) {
@@ -612,7 +612,7 @@ TEST_F(EPKChallengeMachineKeyUnmanagedUserTest, UserNotManaged) {
class EPKChallengeUserKeyUnmanagedUserTest : public EPKChallengeUserKeyTest {
protected:
void SetAuthenticatedUser() override {
- identity::MakePrimaryAccountAvailable(
+ signin::MakePrimaryAccountAvailable(
IdentityManagerFactory::GetForProfile(browser()->profile()),
account_id_.GetUserEmail());
}
@@ -625,7 +625,7 @@ class EPKChallengeUserKeyUnmanagedUserTest : public EPKChallengeUserKeyTest {
const std::string email = "test@chromium.com";
const AccountId account_id_ =
AccountId::FromUserEmailGaiaId(email,
- identity::GetTestGaiaIdForEmail(email));
+ signin::GetTestGaiaIdForEmail(email));
};
TEST_F(EPKChallengeUserKeyUnmanagedUserTest, UserNotManaged) {
diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc
index 08affbf89ef..92e1bc05574 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc
@@ -219,7 +219,9 @@ void EPKPChallengeKeyBase::IsAttestationPreparedCallback(
return;
}
if (!result.value()) {
- context.callback.Run(PREPARE_KEY_RESET_REQUIRED);
+ cryptohome_client_->TpmIsEnabled(
+ base::BindOnce(&EPKPChallengeKeyBase::PrepareKeyErrorHandlerCallback,
+ base::Unretained(this), context));
return;
}
// Attestation is available, see if the key we need already exists.
@@ -231,6 +233,21 @@ void EPKPChallengeKeyBase::IsAttestationPreparedCallback(
base::Unretained(this), context));
}
+void EPKPChallengeKeyBase::PrepareKeyErrorHandlerCallback(
+ const PrepareKeyContext& context,
+ base::Optional<bool> is_tpm_enabled) {
+ if (!is_tpm_enabled.has_value()) {
+ context.callback.Run(PREPARE_KEY_DBUS_ERROR);
+ return;
+ }
+
+ if (is_tpm_enabled.value()) {
+ context.callback.Run(PREPARE_KEY_RESET_REQUIRED);
+ } else {
+ context.callback.Run(PREPARE_KEY_ATTESTATION_UNSUPPORTED);
+ }
+}
+
void EPKPChallengeKeyBase::DoesKeyExistCallback(
const PrepareKeyContext& context,
base::Optional<bool> result) {
@@ -303,8 +320,6 @@ const char EPKPChallengeMachineKey::kKeyRegistrationFailedError[] =
const char EPKPChallengeMachineKey::kNonEnterpriseDeviceError[] =
"The device is not enterprise enrolled.";
-const char EPKPChallengeMachineKey::kKeyName[] = "attest-ent-machine";
-
EPKPChallengeMachineKey::EPKPChallengeMachineKey() : EPKPChallengeKeyBase() {
}
@@ -380,7 +395,7 @@ void EPKPChallengeMachineKey::GetDeviceAttestationEnabledCallback(
PrepareKey(chromeos::attestation::KEY_DEVICE,
EmptyAccountId(), // Not used.
- kKeyName,
+ chromeos::attestation::kEnterpriseMachineKey,
chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE,
false, // user consent is not required.
base::Bind(&EPKPChallengeMachineKey::PrepareKeyCallback,
@@ -400,7 +415,8 @@ void EPKPChallengeMachineKey::PrepareKeyCallback(const std::string& challenge,
async_caller_->TpmAttestationSignEnterpriseChallenge(
chromeos::attestation::KEY_DEVICE,
cryptohome::Identification(), // Not used.
- kKeyName, GetEnterpriseDomain(), GetDeviceId(),
+ chromeos::attestation::kEnterpriseMachineKey, GetEnterpriseDomain(),
+ GetDeviceId(),
register_key ? chromeos::attestation::CHALLENGE_INCLUDE_SIGNED_PUBLIC_KEY
: chromeos::attestation::CHALLENGE_OPTION_NONE,
challenge,
@@ -420,7 +436,7 @@ void EPKPChallengeMachineKey::SignChallengeCallback(
async_caller_->TpmAttestationRegisterKey(
chromeos::attestation::KEY_DEVICE,
cryptohome::Identification(), // Not used.
- kKeyName,
+ chromeos::attestation::kEnterpriseMachineKey,
base::Bind(&EPKPChallengeMachineKey::RegisterKeyCallback,
base::Unretained(this), response));
} else {
@@ -450,8 +466,6 @@ const char EPKPChallengeUserKey::kUserPolicyDisabledError[] =
const char EPKPChallengeUserKey::kUserKeyNotAvailable[] =
"User keys cannot be challenged in this profile.";
-const char EPKPChallengeUserKey::kKeyName[] = "attest-ent-user";
-
EPKPChallengeUserKey::EPKPChallengeUserKey() : EPKPChallengeKeyBase() {
}
@@ -544,7 +558,8 @@ void EPKPChallengeUserKey::GetDeviceAttestationEnabledCallback(
return;
}
- PrepareKey(chromeos::attestation::KEY_USER, GetAccountId(), kKeyName,
+ PrepareKey(chromeos::attestation::KEY_USER, GetAccountId(),
+ chromeos::attestation::kEnterpriseUserKey,
chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE,
require_user_consent,
base::Bind(&EPKPChallengeUserKey::PrepareKeyCallback,
@@ -563,12 +578,13 @@ void EPKPChallengeUserKey::PrepareKeyCallback(const std::string& challenge,
// Everything is checked. Sign the challenge.
async_caller_->TpmAttestationSignEnterpriseChallenge(
chromeos::attestation::KEY_USER,
- cryptohome::Identification(GetAccountId()), kKeyName, GetUserEmail(),
- GetDeviceId(),
+ cryptohome::Identification(GetAccountId()),
+ chromeos::attestation::kEnterpriseUserKey, GetUserEmail(), GetDeviceId(),
register_key ? chromeos::attestation::CHALLENGE_INCLUDE_SIGNED_PUBLIC_KEY
: chromeos::attestation::CHALLENGE_OPTION_NONE,
- challenge, base::Bind(&EPKPChallengeUserKey::SignChallengeCallback,
- base::Unretained(this), register_key));
+ challenge,
+ base::Bind(&EPKPChallengeUserKey::SignChallengeCallback,
+ base::Unretained(this), register_key));
}
void EPKPChallengeUserKey::SignChallengeCallback(bool register_key,
@@ -582,7 +598,8 @@ void EPKPChallengeUserKey::SignChallengeCallback(bool register_key,
if (register_key) {
async_caller_->TpmAttestationRegisterKey(
chromeos::attestation::KEY_USER,
- cryptohome::Identification(GetAccountId()), kKeyName,
+ cryptohome::Identification(GetAccountId()),
+ chromeos::attestation::kEnterpriseUserKey,
base::Bind(&EPKPChallengeUserKey::RegisterKeyCallback,
base::Unretained(this), response));
} else {
diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h
index 821da1af97d..66cb475b59f 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h
+++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h
@@ -61,7 +61,8 @@ class EPKPChallengeKeyBase {
PREPARE_KEY_DBUS_ERROR,
PREPARE_KEY_USER_REJECTED,
PREPARE_KEY_GET_CERTIFICATE_FAILED,
- PREPARE_KEY_RESET_REQUIRED
+ PREPARE_KEY_RESET_REQUIRED,
+ PREPARE_KEY_ATTESTATION_UNSUPPORTED
};
EPKPChallengeKeyBase();
@@ -143,6 +144,8 @@ class EPKPChallengeKeyBase {
void IsAttestationPreparedCallback(const PrepareKeyContext& context,
base::Optional<bool> result);
+ void PrepareKeyErrorHandlerCallback(const PrepareKeyContext& context,
+ base::Optional<bool> is_tpm_enabled);
void DoesKeyExistCallback(const PrepareKeyContext& context,
base::Optional<bool> result);
void AskForUserConsent(const base::Callback<void(bool)>& callback) const;
diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc
index 599b76fb7e4..3dc0c29bc66 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc
@@ -34,10 +34,10 @@
#include "components/account_id/account_id.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/prefs/pref_service.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/user_manager/scoped_user_manager.h"
#include "extensions/common/extension_builder.h"
-#include "services/identity/public/cpp/identity_manager.h"
-#include "services/identity/public/cpp/identity_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
@@ -58,6 +58,7 @@ const int kDBusError = 1;
const int kUserRejected = 2;
const int kGetCertificateFailed = 3;
const int kResetRequired = 4;
+const int kPrepareKeyAttestationUnsupported = 5;
const char kUserEmail[] = "test@google.com";
@@ -201,11 +202,11 @@ class EPKPChallengeKeyTestBase : public BrowserWithTestWindowTest {
}
// Derived classes can override this method to set the required authenticated
- // user in the SigninManager class.
+ // user in the IdentityManager class.
virtual void SetAuthenticatedUser() {
auto* identity_manager =
IdentityManagerFactory::GetForProfile(browser()->profile());
- identity::MakePrimaryAccountAvailable(identity_manager, kUserEmail);
+ signin::MakePrimaryAccountAvailable(identity_manager, kUserEmail);
}
chromeos::FakeCryptohomeClient cryptohome_client_;
@@ -334,6 +335,15 @@ TEST_F(EPKPChallengeMachineKeyTest, AttestationNotPrepared) {
utils::RunFunctionAndReturnError(func_.get(), kArgs, browser()));
}
+// Test that we get proper error message in case we don't have TPM.
+TEST_F(EPKPChallengeMachineKeyTest, AttestationUnsupported) {
+ cryptohome_client_.set_tpm_attestation_is_prepared(false);
+ cryptohome_client_.set_tpm_is_enabled(false);
+
+ EXPECT_EQ(GetCertificateError(kPrepareKeyAttestationUnsupported),
+ utils::RunFunctionAndReturnError(func_.get(), kArgs, browser()));
+}
+
TEST_F(EPKPChallengeMachineKeyTest, AttestationPreparedDbusFailed) {
cryptohome_client_.SetServiceIsAvailable(false);
@@ -579,8 +589,8 @@ class EPKPChallengeMachineKeyUnmanagedUserTest
void SetAuthenticatedUser() override {
auto* identity_manager =
IdentityManagerFactory::GetForProfile(browser()->profile());
- identity::MakePrimaryAccountAvailable(identity_manager,
- account_id_.GetUserEmail());
+ signin::MakePrimaryAccountAvailable(identity_manager,
+ account_id_.GetUserEmail());
}
TestingProfile* CreateProfile() override {
@@ -592,7 +602,7 @@ class EPKPChallengeMachineKeyUnmanagedUserTest
const std::string kOtherEmail = "test@chromium.com";
const AccountId account_id_ = AccountId::FromUserEmailGaiaId(
kOtherEmail,
- identity::GetTestGaiaIdForEmail(kOtherEmail));
+ signin::GetTestGaiaIdForEmail(kOtherEmail));
};
TEST_F(EPKPChallengeMachineKeyUnmanagedUserTest, UserNotManaged) {
@@ -605,8 +615,8 @@ class EPKPChallengeUserKeyUnmanagedUserTest : public EPKPChallengeUserKeyTest {
void SetAuthenticatedUser() override {
auto* identity_manager =
IdentityManagerFactory::GetForProfile(browser()->profile());
- identity::MakePrimaryAccountAvailable(identity_manager,
- account_id_.GetUserEmail());
+ signin::MakePrimaryAccountAvailable(identity_manager,
+ account_id_.GetUserEmail());
}
TestingProfile* CreateProfile() override {
@@ -618,7 +628,7 @@ class EPKPChallengeUserKeyUnmanagedUserTest : public EPKPChallengeUserKeyTest {
const std::string kOtherEmail = "test@chromium.com";
const AccountId account_id_ = AccountId::FromUserEmailGaiaId(
kOtherEmail,
- identity::GetTestGaiaIdForEmail(kOtherEmail));
+ signin::GetTestGaiaIdForEmail(kOtherEmail));
};
TEST_F(EPKPChallengeUserKeyUnmanagedUserTest, UserNotManaged) {
diff --git a/chromium/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc b/chromium/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc
index c9aa19e8eba..5af703b6ed9 100644
--- a/chromium/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc
@@ -81,7 +81,7 @@ void ExecuteExtensionAction(Browser* browser, const Extension* extension) {
class BlankImageSource : public gfx::CanvasImageSource {
public:
explicit BlankImageSource(const gfx::Size& size)
- : gfx::CanvasImageSource(size, false) {}
+ : gfx::CanvasImageSource(size) {}
~BlankImageSource() override {}
void Draw(gfx::Canvas* canvas) override {}
@@ -159,6 +159,38 @@ class BrowserActionApiTest : public ExtensionApiTest {
DISALLOW_COPY_AND_ASSIGN(BrowserActionApiTest);
};
+// Canvas tests rely on the harness producing pixel output in order to read back
+// pixels from a canvas element. So we have to override the setup function.
+class BrowserActionApiCanvasTest : public BrowserActionApiTest {
+ public:
+ void SetUp() override {
+ EnablePixelOutput();
+ ExtensionApiTest::SetUp();
+ }
+};
+
+// Watches a frame is swapped with a new frame by e.g., navigation.
+class RenderFrameChangedWatcher : public content::WebContentsObserver {
+ public:
+ explicit RenderFrameChangedWatcher(WebContents* web_contents)
+ : WebContentsObserver(web_contents) {}
+
+ void RenderFrameHostChanged(content::RenderFrameHost* old_host,
+ content::RenderFrameHost* new_host) override {
+ created_frame_ = new_host;
+ run_loop_.Quit();
+ }
+
+ content::RenderFrameHost* WaitAndReturnNewFrame() {
+ run_loop_.Run();
+ return created_frame_;
+ }
+
+ private:
+ base::RunLoop run_loop_;
+ content::RenderFrameHost* created_frame_;
+};
+
IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, Basic) {
ASSERT_TRUE(embedded_test_server()->Start());
ASSERT_TRUE(RunExtensionTest("browser_action/basics")) << message_;
@@ -190,7 +222,7 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, Basic) {
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
-IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, DynamicBrowserAction) {
+IN_PROC_BROWSER_TEST_F(BrowserActionApiCanvasTest, DynamicBrowserAction) {
ASSERT_TRUE(RunExtensionTest("browser_action/no_icon")) << message_;
const Extension* extension = GetSingleLoadedExtension();
ASSERT_TRUE(extension) << message_;
@@ -375,7 +407,7 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, DynamicBrowserAction) {
EXPECT_EQ(kEmptyPathError, catcher.message());
}
-IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, InvisibleIconBrowserAction) {
+IN_PROC_BROWSER_TEST_F(BrowserActionApiCanvasTest, InvisibleIconBrowserAction) {
// Turn this on so errors are reported.
ExtensionActionSetIconFunction::SetReportErrorForInvisibleIconForTesting(
true);
@@ -827,12 +859,19 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, BrowserActionPopupWithIframe) {
// Navigate the popup's iframe to a (cross-site) web page, and wait for that
// page to send a message, which will ensure that the page has loaded.
+ RenderFrameChangedWatcher watcher(
+ WebContents::FromRenderFrameHost(frame_host));
GURL foo_url(embedded_test_server()->GetURL("foo.com", "/popup_iframe.html"));
std::string script = "location.href = '" + foo_url.spec() + "'";
- std::string result;
- EXPECT_TRUE(
- content::ExecuteScriptAndExtractString(frame_host, script, &result));
- EXPECT_EQ("DONE", result);
+ EXPECT_TRUE(ExecuteScript(frame_host, script));
+
+ frame_host = watcher.WaitAndReturnNewFrame();
+
+ // Confirm that the new page (popup_iframe.html) is actually loaded.
+ content::DOMMessageQueue dom_message_queue(frame_host);
+ std::string json;
+ EXPECT_TRUE(dom_message_queue.WaitForMessage(&json));
+ EXPECT_EQ("\"DONE\"", json);
EXPECT_TRUE(actions_bar->HidePopup());
}
diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc
index 1f2c8aa8225..ef0c3b6b928 100644
--- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc
+++ b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc
@@ -32,7 +32,6 @@
#include "chrome/common/extensions/api/extension_action/action_info.h"
#include "content/public/browser/notification_service.h"
#include "extensions/browser/event_router.h"
-#include "extensions/browser/extension_function_registry.h"
#include "extensions/browser/extension_host.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_util.h"
@@ -90,34 +89,7 @@ static base::LazyInstance<BrowserContextKeyedAPIFactory<ExtensionActionAPI>>::
DestructorAtExit g_extension_action_api_factory = LAZY_INSTANCE_INITIALIZER;
ExtensionActionAPI::ExtensionActionAPI(content::BrowserContext* context)
- : browser_context_(context),
- extension_prefs_(nullptr) {
- ExtensionFunctionRegistry& registry =
- ExtensionFunctionRegistry::GetInstance();
-
- // Browser Actions
- registry.RegisterFunction<BrowserActionSetIconFunction>();
- registry.RegisterFunction<BrowserActionSetTitleFunction>();
- registry.RegisterFunction<BrowserActionSetBadgeTextFunction>();
- registry.RegisterFunction<BrowserActionSetBadgeBackgroundColorFunction>();
- registry.RegisterFunction<BrowserActionSetPopupFunction>();
- registry.RegisterFunction<BrowserActionGetTitleFunction>();
- registry.RegisterFunction<BrowserActionGetBadgeTextFunction>();
- registry.RegisterFunction<BrowserActionGetBadgeBackgroundColorFunction>();
- registry.RegisterFunction<BrowserActionGetPopupFunction>();
- registry.RegisterFunction<BrowserActionEnableFunction>();
- registry.RegisterFunction<BrowserActionDisableFunction>();
- registry.RegisterFunction<BrowserActionOpenPopupFunction>();
-
- // Page Actions
- registry.RegisterFunction<PageActionShowFunction>();
- registry.RegisterFunction<PageActionHideFunction>();
- registry.RegisterFunction<PageActionSetIconFunction>();
- registry.RegisterFunction<PageActionSetTitleFunction>();
- registry.RegisterFunction<PageActionSetPopupFunction>();
- registry.RegisterFunction<PageActionGetTitleFunction>();
- registry.RegisterFunction<PageActionGetPopupFunction>();
-}
+ : browser_context_(context), extension_prefs_(nullptr) {}
ExtensionActionAPI::~ExtensionActionAPI() {
}
@@ -316,9 +288,9 @@ ExtensionFunction::ResponseAction ExtensionActionFunction::Run() {
if (!contents_)
return RespondNow(Error(kNoTabError, base::NumberToString(tab_id_)));
} else {
- // Only browser actions have a default tabId.
- EXTENSION_FUNCTION_VALIDATE(extension_action_->action_type() ==
- ActionInfo::TYPE_BROWSER);
+ // Page actions do not have a default tabId.
+ EXTENSION_FUNCTION_VALIDATE(extension_action_->action_type() !=
+ ActionInfo::TYPE_PAGE);
}
return RunExtensionAction();
}
diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h
index d75a9023c05..f4d9ea2b9dd 100644
--- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h
+++ b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h
@@ -251,6 +251,102 @@ class ExtensionActionGetBadgeBackgroundColorFunction
};
//
+// action.* aliases for supported action APIs.
+//
+
+class ActionSetIconFunction : public ExtensionActionSetIconFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("action.setIcon", ACTION_SETICON)
+
+ protected:
+ ~ActionSetIconFunction() override {}
+};
+
+class ActionGetPopupFunction : public ExtensionActionGetPopupFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("action.getPopup", ACTION_GETPOPUP)
+
+ protected:
+ ~ActionGetPopupFunction() override {}
+};
+
+class ActionSetPopupFunction : public ExtensionActionSetPopupFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("action.setPopup", ACTION_SETPOPUP)
+
+ protected:
+ ~ActionSetPopupFunction() override {}
+};
+
+class ActionGetTitleFunction : public ExtensionActionGetTitleFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("action.getTitle", ACTION_GETTITLE)
+
+ protected:
+ ~ActionGetTitleFunction() override {}
+};
+
+class ActionSetTitleFunction : public ExtensionActionSetTitleFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("action.setTitle", ACTION_SETTITLE)
+
+ protected:
+ ~ActionSetTitleFunction() override {}
+};
+
+class ActionGetBadgeTextFunction : public ExtensionActionGetBadgeTextFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("action.getBadgeText", ACTION_GETBADGETEXT)
+
+ protected:
+ ~ActionGetBadgeTextFunction() override {}
+};
+
+class ActionSetBadgeTextFunction : public ExtensionActionSetBadgeTextFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("action.setBadgeText", ACTION_SETBADGETEXT)
+
+ protected:
+ ~ActionSetBadgeTextFunction() override {}
+};
+
+class ActionGetBadgeBackgroundColorFunction
+ : public ExtensionActionGetBadgeBackgroundColorFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("action.getBadgeBackgroundColor",
+ ACTION_GETBADGEBACKGROUNDCOLOR)
+
+ protected:
+ ~ActionGetBadgeBackgroundColorFunction() override {}
+};
+
+class ActionSetBadgeBackgroundColorFunction
+ : public ExtensionActionSetBadgeBackgroundColorFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("action.setBadgeBackgroundColor",
+ ACTION_SETBADGEBACKGROUNDCOLOR)
+
+ protected:
+ ~ActionSetBadgeBackgroundColorFunction() override {}
+};
+
+class ActionEnableFunction : public ExtensionActionShowFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("action.enable", ACTION_ENABLE)
+
+ protected:
+ ~ActionEnableFunction() override {}
+};
+
+class ActionDisableFunction : public ExtensionActionHideFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("action.disable", ACTION_DISABLE)
+
+ protected:
+ ~ActionDisableFunction() override {}
+};
+
+//
// browserAction.* aliases for supported browserAction APIs.
//
diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc b/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc
index 93b5c147acc..c90241d63ad 100644
--- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc
@@ -7,7 +7,9 @@
#include <string>
#include "base/macros.h"
+#include "base/run_loop.h"
#include "base/scoped_observer.h"
+#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h"
@@ -16,23 +18,44 @@
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/sessions/session_tab_helper.h"
#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/extensions/browser_action_test_util.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/extensions/extension_test_util.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/version_info/channel.h"
+#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
+#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/browsertest_util.h"
+#include "extensions/browser/extension_icon_image.h"
+#include "extensions/browser/process_manager.h"
#include "extensions/browser/state_store.h"
+#include "extensions/common/extension.h"
#include "extensions/common/features/feature_channel.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/test/extension_test_message_listener.h"
+#include "extensions/test/result_catcher.h"
#include "extensions/test/test_extension_dir.h"
#include "ui/base/window_open_disposition.h"
+#include "ui/gfx/color_utils.h"
namespace extensions {
namespace {
+// Runs |script| in the background page of the extension with the given
+// |extension_id|, and waits for it to send a test-passed result. This will
+// fail if the test in |script| fails.
+void RunTestAndWaitForSuccess(Profile* profile,
+ const ExtensionId& extension_id,
+ const std::string& script) {
+ SCOPED_TRACE(script);
+ ResultCatcher result_catcher;
+ browsertest_util::ExecuteScriptInBackgroundPageNoWait(profile, extension_id,
+ script);
+ EXPECT_TRUE(result_catcher.GetNextResult()) << result_catcher.message();
+}
+
// A helper class to track StateStore changes.
class TestStateStoreObserver : public StateStore::TestObserver {
public:
@@ -63,6 +86,94 @@ class TestStateStoreObserver : public StateStore::TestObserver {
DISALLOW_COPY_AND_ASSIGN(TestStateStoreObserver);
};
+// A helper class to handle setting or getting the values for an action from JS.
+class ActionTestHelper {
+ public:
+ ActionTestHelper(const char* api_name,
+ const char* set_method_name,
+ const char* get_method_name,
+ const char* js_property_key,
+ Profile* profile,
+ const ExtensionId& extension_id)
+ : api_name_(api_name),
+ set_method_name_(set_method_name),
+ get_method_name_(get_method_name),
+ js_property_key_(js_property_key),
+ profile_(profile),
+ extension_id_(extension_id) {}
+ ~ActionTestHelper() = default;
+
+ // Checks the value for the given |tab_id|.
+ void CheckValueForTab(const char* expected_js_value, int tab_id) const {
+ constexpr char kScriptTemplate[] =
+ R"(chrome.%s.%s({tabId: %d}, (res) => {
+ chrome.test.assertNoLastError();
+ chrome.test.assertEq(%s, res);
+ chrome.test.notifyPass();
+ });)";
+ RunTestAndWaitForSuccess(
+ profile_, extension_id_,
+ base::StringPrintf(kScriptTemplate, api_name_, get_method_name_, tab_id,
+ expected_js_value));
+ }
+
+ // Checks the default value.
+ void CheckDefaultValue(const char* expected_js_value) const {
+ constexpr char kScriptTemplate[] =
+ R"(chrome.%s.%s({}, (res) => {
+ chrome.test.assertNoLastError();
+ chrome.test.assertEq(%s, res);
+ chrome.test.notifyPass();
+ });)";
+ RunTestAndWaitForSuccess(
+ profile_, extension_id_,
+ base::StringPrintf(kScriptTemplate, api_name_, get_method_name_,
+ expected_js_value));
+ }
+
+ // Sets the value for a given |tab_id|.
+ void SetValueForTab(const char* new_js_value, int tab_id) const {
+ constexpr char kScriptTemplate[] =
+ R"(chrome.%s.%s({tabId: %d, %s: %s}, () => {
+ chrome.test.assertNoLastError();
+ chrome.test.notifyPass();
+ });)";
+ RunTestAndWaitForSuccess(
+ profile_, extension_id_,
+ base::StringPrintf(kScriptTemplate, api_name_, set_method_name_, tab_id,
+ js_property_key_, new_js_value));
+ }
+
+ // Sets the default value.
+ void SetDefaultValue(const char* new_js_value) const {
+ constexpr char kScriptTemplate[] =
+ R"(chrome.%s.%s({%s: %s}, () => {
+ chrome.test.assertNoLastError();
+ chrome.test.notifyPass();
+ });)";
+ RunTestAndWaitForSuccess(
+ profile_, extension_id_,
+ base::StringPrintf(kScriptTemplate, api_name_, set_method_name_,
+ js_property_key_, new_js_value));
+ }
+
+ private:
+ // The name of the api (e.g., "action").
+ const char* const api_name_;
+ // The name of the method to call to set the value (e.g., "setPopup").
+ const char* const set_method_name_;
+ // The name of the method to call to get the value (e.g., "getPopup").
+ const char* const get_method_name_;
+ // The name of the property in the set method details (e.g., "popup").
+ const char* const js_property_key_;
+ // The associated profile.
+ Profile* const profile_;
+ // The id of the extension.
+ const ExtensionId extension_id_;
+
+ DISALLOW_COPY_AND_ASSIGN(ActionTestHelper);
+};
+
} // namespace
class ExtensionActionAPITest : public ExtensionApiTest {
@@ -83,6 +194,19 @@ class ExtensionActionAPITest : public ExtensionApiTest {
return nullptr;
}
+ const char* GetAPIName(ActionInfo::Type action_type) {
+ switch (action_type) {
+ case ActionInfo::TYPE_ACTION:
+ return "action";
+ case ActionInfo::TYPE_BROWSER:
+ return "browserAction";
+ case ActionInfo::TYPE_PAGE:
+ return "pageAction";
+ }
+ NOTREACHED();
+ return nullptr;
+ }
+
private:
DISALLOW_COPY_AND_ASSIGN(ExtensionActionAPITest);
};
@@ -100,12 +224,97 @@ class MultiActionAPITest
: current_channel_(
extension_test_util::GetOverrideChannelForActionType(GetParam())) {}
+ // Returns true if the |action| has whatever state its default is on the
+ // tab with the given |tab_id|.
+ bool ActionHasDefaultState(const ExtensionAction& action, int tab_id) const {
+ bool is_visible = action.GetIsVisible(tab_id);
+ bool default_is_visible =
+ action.default_state() == ActionInfo::STATE_ENABLED;
+ return is_visible == default_is_visible;
+ }
+
+ // Ensures the |action| is enabled on the tab with the given |tab_id|.
+ void EnsureActionIsEnabledOnTab(ExtensionAction* action, int tab_id) {
+ if (action->GetIsVisible(tab_id))
+ return;
+ action->SetIsVisible(tab_id, true);
+ // Just setting the state on the action doesn't update the UI. Ensure
+ // observers are notified.
+ extensions::ExtensionActionAPI* extension_action_api =
+ extensions::ExtensionActionAPI::Get(profile());
+ extension_action_api->NotifyChange(action, GetActiveTab(), profile());
+ }
+
+ // Ensures the |action| is enabled on the currently-active tab.
+ void EnsureActionIsEnabledOnActiveTab(ExtensionAction* action) {
+ EnsureActionIsEnabledOnTab(action, GetActiveTabId());
+ }
+
+ // Returns the id of the currently-active tab.
+ int GetActiveTabId() const {
+ content::WebContents* web_contents = GetActiveTab();
+ return SessionTabHelper::IdForTab(web_contents).id();
+ }
+
+ content::WebContents* GetActiveTab() const {
+ return browser()->tab_strip_model()->GetActiveWebContents();
+ }
+
+ // Returns the action associated with |extension|.
+ ExtensionAction* GetExtensionAction(const Extension& extension) {
+ auto* action_manager = ExtensionActionManager::Get(profile());
+ return action_manager->GetExtensionAction(extension);
+ }
+
+ // Waits for the given |icon| to finish it's first load.
+ // TODO(devlin): It's unfortunate we need this here. Ideally, either this
+ // would be less convoluted, or would even be taken care of by the extension
+ // loading methods.
+ void WaitForIconLoaded(IconImage* icon) {
+ class IconImageWaiter : public IconImage::Observer {
+ public:
+ IconImageWaiter() : observer_(this) {}
+ ~IconImageWaiter() override = default;
+
+ void Wait(IconImage* icon) {
+ if (!icon->did_complete_initial_load()) {
+ observer_.Add(icon);
+ run_loop_.Run();
+ }
+ }
+
+ private:
+ // IconImage::Observer:
+ void OnExtensionIconImageChanged(IconImage* icon) override {
+ DCHECK(icon->did_complete_initial_load());
+ run_loop_.Quit();
+ }
+
+ base::RunLoop run_loop_;
+ ScopedObserver<IconImage, IconImage::Observer> observer_;
+
+ DISALLOW_COPY_AND_ASSIGN(IconImageWaiter);
+ };
+
+ IconImageWaiter().Wait(icon);
+ }
+
private:
std::unique_ptr<ScopedCurrentChannel> current_channel_;
DISALLOW_COPY_AND_ASSIGN(MultiActionAPITest);
};
+// Canvas tests rely on the harness producing pixel output in order to read back
+// pixels from a canvas element. So we have to override the setup function.
+class MultiActionAPICanvasTest : public MultiActionAPITest {
+ public:
+ void SetUp() override {
+ EnablePixelOutput();
+ ExtensionActionAPITest::SetUp();
+ }
+};
+
// Check that updating the browser action badge for a specific tab id does not
// cause a disk write (since we only persist the defaults).
// Only browser actions persist settings.
@@ -269,10 +478,569 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPITest, TitleLocalization) {
action->GetTitle(ExtensionAction::kDefaultTabId));
}
+// Tests dispatching the onClicked event to listeners when the extension action
+// in the toolbar is pressed.
+IN_PROC_BROWSER_TEST_P(MultiActionAPITest, OnClickedDispatching) {
+ constexpr char kManifestTemplate[] =
+ R"({
+ "name": "Test Clicking",
+ "manifest_version": 2,
+ "version": "0.1",
+ "%s": {},
+ "background": { "scripts": ["background.js"] }
+ })";
+ constexpr char kBackgroundJsTemplate[] =
+ R"(chrome.%s.onClicked.addListener((tab) => {
+ // Check a few properties on the tabs object to make sure it's sane.
+ chrome.test.assertTrue(!!tab);
+ chrome.test.assertTrue(tab.id > 0);
+ chrome.test.assertTrue(tab.index > -1);
+ chrome.test.notifyPass();
+ });)";
+
+ TestExtensionDir test_dir;
+ test_dir.WriteManifest(
+ base::StringPrintf(kManifestTemplate, GetManifestKey(GetParam())));
+ test_dir.WriteFile(
+ FILE_PATH_LITERAL("background.js"),
+ base::StringPrintf(kBackgroundJsTemplate, GetAPIName(GetParam())));
+
+ // Though this says "BrowserActionTestUtil", it's actually used for all
+ // toolbar actions.
+ // TODO(devlin): Rename it to ToolbarActionTestUtil.
+ std::unique_ptr<BrowserActionTestUtil> toolbar_helper =
+ BrowserActionTestUtil::Create(browser());
+ EXPECT_EQ(0, toolbar_helper->NumberOfBrowserActions());
+ const Extension* extension = LoadExtension(test_dir.UnpackedPath());
+ ASSERT_TRUE(extension);
+ ASSERT_EQ(1, toolbar_helper->NumberOfBrowserActions());
+ EXPECT_EQ(extension->id(), toolbar_helper->GetExtensionId(0));
+
+ ExtensionAction* action = GetExtensionAction(*extension);
+ ASSERT_TRUE(action);
+
+ const int tab_id = GetActiveTabId();
+ EXPECT_TRUE(ActionHasDefaultState(*action, tab_id));
+ EnsureActionIsEnabledOnActiveTab(action);
+ EXPECT_FALSE(action->HasPopup(tab_id));
+
+ ResultCatcher result_catcher;
+ toolbar_helper->Press(0);
+ ASSERT_TRUE(result_catcher.GetNextResult()) << result_catcher.message();
+}
+
+// Tests the creation of a popup when one is specified in the manifest.
+IN_PROC_BROWSER_TEST_P(MultiActionAPITest, PopupCreation) {
+ constexpr char kManifestTemplate[] =
+ R"({
+ "name": "Test Clicking",
+ "manifest_version": 2,
+ "version": "0.1",
+ "%s": {
+ "default_popup": "popup.html"
+ }
+ })";
+
+ constexpr char kPopupHtml[] =
+ R"(<!doctype html>
+ <html>
+ <script src="popup.js"></script>
+ </html>)";
+ constexpr char kPopupJs[] =
+ "window.onload = function() { chrome.test.notifyPass(); };";
+
+ TestExtensionDir test_dir;
+ test_dir.WriteManifest(
+ base::StringPrintf(kManifestTemplate, GetManifestKey(GetParam())));
+ test_dir.WriteFile(FILE_PATH_LITERAL("popup.html"), kPopupHtml);
+ test_dir.WriteFile(FILE_PATH_LITERAL("popup.js"), kPopupJs);
+
+ const Extension* extension = LoadExtension(test_dir.UnpackedPath());
+ ASSERT_TRUE(extension);
+
+ std::unique_ptr<BrowserActionTestUtil> toolbar_helper =
+ BrowserActionTestUtil::Create(browser());
+
+ ExtensionAction* action = GetExtensionAction(*extension);
+ ASSERT_TRUE(action);
+
+ const int tab_id = GetActiveTabId();
+ EXPECT_TRUE(ActionHasDefaultState(*action, tab_id));
+ EnsureActionIsEnabledOnActiveTab(action);
+ EXPECT_TRUE(action->HasPopup(tab_id));
+
+ ResultCatcher result_catcher;
+ toolbar_helper->Press(0);
+ EXPECT_TRUE(result_catcher.GetNextResult()) << result_catcher.message();
+
+ ProcessManager* process_manager = ProcessManager::Get(profile());
+ ProcessManager::FrameSet frames =
+ process_manager->GetRenderFrameHostsForExtension(extension->id());
+ ASSERT_EQ(1u, frames.size());
+ content::RenderFrameHost* render_frame_host = *frames.begin();
+ EXPECT_EQ(extension->GetResourceURL("popup.html"),
+ render_frame_host->GetLastCommittedURL());
+
+ content::WebContents* popup_contents =
+ content::WebContents::FromRenderFrameHost(render_frame_host);
+ ASSERT_TRUE(popup_contents);
+
+ content::WebContentsDestroyedWatcher contents_destroyed(popup_contents);
+ EXPECT_TRUE(content::ExecuteScript(popup_contents, "window.close()"));
+ contents_destroyed.Wait();
+
+ frames = process_manager->GetRenderFrameHostsForExtension(extension->id());
+ EXPECT_EQ(0u, frames.size());
+}
+
+// Tests setting the icon dynamically from the background page.
+IN_PROC_BROWSER_TEST_P(MultiActionAPICanvasTest, DynamicSetIcon) {
+ constexpr char kManifestTemplate[] =
+ R"({
+ "name": "Test Clicking",
+ "manifest_version": 2,
+ "version": "0.1",
+ "%s": {
+ "default_icon": "red_icon.png"
+ },
+ "background": { "scripts": ["background.js"] }
+ })";
+ constexpr char kBackgroundJsTemplate[] =
+ R"(function setIcon(details) {
+ chrome.%s.setIcon(details, () => {
+ chrome.test.assertNoLastError();
+ chrome.test.notifyPass();
+ });
+ })";
+
+ std::string blue_icon;
+ std::string red_icon;
+ {
+ base::ScopedAllowBlockingForTesting allow_blocking;
+ ASSERT_TRUE(base::ReadFileToString(
+ test_data_dir_.AppendASCII("icon_rgb_0_0_255.png"), &blue_icon));
+ ASSERT_TRUE(base::ReadFileToString(
+ test_data_dir_.AppendASCII("icon_rgb_255_0_0.png"), &red_icon));
+ }
+
+ TestExtensionDir test_dir;
+ test_dir.WriteManifest(
+ base::StringPrintf(kManifestTemplate, GetManifestKey(GetParam())));
+ test_dir.WriteFile(
+ FILE_PATH_LITERAL("background.js"),
+ base::StringPrintf(kBackgroundJsTemplate, GetAPIName(GetParam())));
+ test_dir.WriteFile(FILE_PATH_LITERAL("blue_icon.png"), blue_icon);
+ test_dir.WriteFile(FILE_PATH_LITERAL("red_icon.png"), red_icon);
+
+ const Extension* extension = LoadExtension(test_dir.UnpackedPath());
+ ASSERT_TRUE(extension);
+
+ ExtensionAction* action = GetExtensionAction(*extension);
+ ASSERT_TRUE(action);
+
+ ASSERT_TRUE(action->default_icon());
+ // Wait for the default icon to finish loading; otherwise it may be empty
+ // when we check it.
+ WaitForIconLoaded(action->default_icon_image());
+
+ int tab_id = GetActiveTabId();
+ EXPECT_TRUE(ActionHasDefaultState(*action, tab_id));
+ EnsureActionIsEnabledOnActiveTab(action);
+
+ std::unique_ptr<BrowserActionTestUtil> toolbar_helper =
+ BrowserActionTestUtil::Create(browser());
+
+ ASSERT_EQ(1, toolbar_helper->NumberOfBrowserActions());
+ EXPECT_EQ(extension->id(), toolbar_helper->GetExtensionId(0));
+
+ gfx::Image default_icon = toolbar_helper->GetIcon(0);
+ EXPECT_FALSE(default_icon.IsEmpty());
+
+ // Check the midpoint. All these icons are solid, but the rendered icon
+ // includes padding.
+ const int mid_x = default_icon.Width() / 2;
+ const int mid_y = default_icon.Height() / 2;
+ // Note: We only validate the color here as a quick-and-easy way of validating
+ // the icon is what we expect. Other tests do much more rigorous testing of
+ // the icon's rendering.
+ EXPECT_EQ(SK_ColorRED, default_icon.AsBitmap().getColor(mid_x, mid_y));
+
+ // Create a new tab.
+ ui_test_utils::NavigateToURLWithDisposition(
+ browser(), GURL("chrome://newtab"),
+ WindowOpenDisposition::NEW_FOREGROUND_TAB,
+ ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
+
+ const int new_tab_id = GetActiveTabId();
+ EXPECT_NE(new_tab_id, tab_id);
+ EXPECT_TRUE(ActionHasDefaultState(*action, new_tab_id));
+ EnsureActionIsEnabledOnActiveTab(action);
+
+ // The new tab should still have the same icon (the default).
+ gfx::Image new_tab_icon = toolbar_helper->GetIcon(0);
+ EXPECT_FALSE(default_icon.IsEmpty());
+ EXPECT_EQ(SK_ColorRED, default_icon.AsBitmap().getColor(mid_x, mid_y));
+
+ // Set the icon for the new tab to a different icon in the extension package.
+ RunTestAndWaitForSuccess(
+ profile(), extension->id(),
+ base::StringPrintf("setIcon({tabId: %d, path: 'blue_icon.png'});",
+ new_tab_id));
+
+ new_tab_icon = toolbar_helper->GetIcon(0);
+ EXPECT_FALSE(new_tab_icon.IsEmpty());
+ EXPECT_EQ(SK_ColorBLUE, new_tab_icon.AsBitmap().getColor(mid_x, mid_y));
+
+ // Next, set the icon to a dynamically-generated one (from canvas image data).
+ constexpr char kSetIconFromImageData[] =
+ R"({
+ let canvas = document.createElement('canvas');
+ canvas.width = 32;
+ canvas.height = 32;
+ let context = canvas.getContext('2d');
+ context.clearRect(0, 0, 32, 32);
+ context.fillStyle = '#00FF00'; // Green
+ context.fillRect(0, 0, 32, 32);
+ let imageData = context.getImageData(0, 0, 32, 32);
+ setIcon({tabId: %d, imageData: imageData});
+ })";
+ RunTestAndWaitForSuccess(
+ profile(), extension->id(),
+ base::StringPrintf(kSetIconFromImageData, new_tab_id));
+
+ new_tab_icon = toolbar_helper->GetIcon(0);
+ EXPECT_FALSE(new_tab_icon.IsEmpty());
+ EXPECT_EQ(SK_ColorGREEN, new_tab_icon.AsBitmap().getColor(mid_x, mid_y));
+
+ // Switch back to the first tab. The icon should still be red, since the other
+ // changes were for specific tabs.
+ browser()->tab_strip_model()->ActivateTabAt(0);
+ gfx::Image first_tab_icon = toolbar_helper->GetIcon(0);
+ EXPECT_FALSE(first_tab_icon.IsEmpty());
+ EXPECT_EQ(SK_ColorRED, first_tab_icon.AsBitmap().getColor(mid_x, mid_y));
+
+ // TODO(devlin): Add tests for setting icons as a dictionary of
+ // { size -> image_data }.
+}
+
+// Tests various getter and setter methods.
+IN_PROC_BROWSER_TEST_P(MultiActionAPITest, GettersAndSetters) {
+ // Load up an extension with default values.
+ constexpr char kManifestTemplate[] =
+ R"({
+ "name": "Test Getters and Setters",
+ "manifest_version": 2,
+ "version": "0.1",
+ "%s": {
+ "default_title": "default title",
+ "default_popup": "default_popup.html"
+ },
+ "background": { "scripts": ["background.js"] }
+ })";
+ constexpr char kBackgroundJs[] = "// Intentionally blank.";
+ constexpr char kPopupHtml[] =
+ "<!doctype html><html><body>Blank</body></html>";
+
+ TestExtensionDir test_dir;
+ test_dir.WriteManifest(
+ base::StringPrintf(kManifestTemplate, GetManifestKey(GetParam())));
+ test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs);
+ test_dir.WriteFile(FILE_PATH_LITERAL("default_popup.html"), kPopupHtml);
+ test_dir.WriteFile(FILE_PATH_LITERAL("custom_popup1.html"), kPopupHtml);
+ test_dir.WriteFile(FILE_PATH_LITERAL("custom_popup2.html"), kPopupHtml);
+
+ const Extension* extension = LoadExtension(test_dir.UnpackedPath());
+ ASSERT_TRUE(extension);
+
+ ExtensionAction* action = GetExtensionAction(*extension);
+ ASSERT_TRUE(action);
+
+ int first_tab_id = GetActiveTabId();
+ ui_test_utils::NavigateToURLWithDisposition(
+ browser(), GURL("chrome://newtab"),
+ WindowOpenDisposition::NEW_FOREGROUND_TAB,
+ ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
+ int second_tab_id = GetActiveTabId();
+
+ // A simple structure to hold different representations of values (one JS,
+ // one C++).
+ struct ValuePair {
+ std::string cpp;
+ std::string js;
+
+ bool operator!=(const ValuePair& rhs) const {
+ return rhs.cpp != this->cpp || rhs.js != this->js;
+ }
+ };
+
+ // A function that returns the the C++ result for the given ExtensionAction
+ // and tab id.
+ using CPPValueGetter =
+ base::RepeatingCallback<std::string(ExtensionAction*, int)>;
+
+ auto run_test =
+ [action, first_tab_id, second_tab_id](
+ ActionTestHelper& test_helper, const ValuePair& default_value,
+ const ValuePair& custom_value1, const ValuePair& custom_value2,
+ CPPValueGetter value_getter) {
+ // Ensure all values are mutually exclusive.
+ EXPECT_NE(default_value, custom_value1);
+ EXPECT_NE(default_value, custom_value2);
+ EXPECT_NE(custom_value1, custom_value2);
+
+ SCOPED_TRACE(base::StringPrintf(
+ "default: '%s', custom1: '%s', custom2: '%s'",
+ default_value.cpp.c_str(), custom_value1.cpp.c_str(),
+ custom_value2.cpp.c_str()));
+
+ // A helper to check the value of a property of the action in both
+ // C++ (from the ExtensionAction object) and in JS (through the API
+ // method).
+ auto check_value = [action, &value_getter, &test_helper](
+ const ValuePair& expected_value, int tab_id) {
+ EXPECT_EQ(expected_value.cpp, value_getter.Run(action, tab_id));
+ if (tab_id == ExtensionAction::kDefaultTabId)
+ test_helper.CheckDefaultValue(expected_value.js.c_str());
+ else
+ test_helper.CheckValueForTab(expected_value.js.c_str(), tab_id);
+ };
+
+ // Page actions don't support setting a default value (because they are
+ // inherently tab-specific).
+ bool supports_default = GetParam() != ActionInfo::TYPE_PAGE;
+
+ // Check the initial state. These should start at the defaults.
+ if (supports_default)
+ check_value(default_value, ExtensionAction::kDefaultTabId);
+ check_value(default_value, first_tab_id);
+ check_value(default_value, second_tab_id);
+
+ // Set the value for the first tab to be the first custom value.
+ test_helper.SetValueForTab(custom_value1.js.c_str(), first_tab_id);
+
+ // The first tab should have the custom value, while the second tab
+ // (and the default tab, if supported) should still have the default
+ // value.
+ if (supports_default)
+ check_value(default_value, ExtensionAction::kDefaultTabId);
+ check_value(custom_value1, first_tab_id);
+ check_value(default_value, second_tab_id);
+
+ if (supports_default) {
+ // Change the default value to the second custom value.
+ test_helper.SetDefaultValue(custom_value2.js.c_str());
+
+ // Now, the default and second tab should each have the second custom
+ // value. Since the first tab had its own value set, it should still
+ // be set to the first custom value.
+ check_value(custom_value2, ExtensionAction::kDefaultTabId);
+ check_value(custom_value1, first_tab_id);
+ check_value(custom_value2, second_tab_id);
+ }
+ };
+
+ const char* kApiName = GetAPIName(GetParam());
+
+ {
+ // setPopup/getPopup.
+ GURL default_popup_url = extension->GetResourceURL("default_popup.html");
+ GURL custom_popup_url1 = extension->GetResourceURL("custom_popup1.html");
+ GURL custom_popup_url2 = extension->GetResourceURL("custom_popup2.html");
+ ValuePair default_popup{default_popup_url.spec(),
+ base::StrCat({"'", default_popup_url.spec(), "'"})};
+ ValuePair custom_popup1{custom_popup_url1.spec(),
+ base::StrCat({"'", custom_popup_url1.spec(), "'"})};
+ ValuePair custom_popup2{custom_popup_url2.spec(),
+ base::StrCat({"'", custom_popup_url2.spec(), "'"})};
+
+ auto get_popup = [](ExtensionAction* action, int tab_id) {
+ return action->GetPopupUrl(tab_id).spec();
+ };
+
+ ActionTestHelper popup_helper(kApiName, "setPopup", "getPopup", "popup",
+ profile(), extension->id());
+ run_test(popup_helper, default_popup, custom_popup1, custom_popup2,
+ base::BindRepeating(get_popup));
+ }
+ {
+ // setTitle/getTitle.
+ ValuePair default_title{"default title", "'default title'"};
+ ValuePair custom_title1{"custom title1", "'custom title1'"};
+ ValuePair custom_title2{"custom title2", "'custom title2'"};
+
+ auto get_title = [](ExtensionAction* action, int tab_id) {
+ return action->GetTitle(tab_id);
+ };
+
+ ActionTestHelper title_helper(kApiName, "setTitle", "getTitle", "title",
+ profile(), extension->id());
+ run_test(title_helper, default_title, custom_title1, custom_title2,
+ base::BindRepeating(get_title));
+ }
+
+ // Page actions don't have badges; for them, the test is done.
+ if (GetParam() == ActionInfo::TYPE_PAGE)
+ return;
+
+ {
+ // setBadgeText/getBadgeText.
+ ValuePair default_badge_text{"", "''"};
+ ValuePair custom_badge_text1{"custom badge1", "'custom badge1'"};
+ ValuePair custom_badge_text2{"custom badge2", "'custom badge2'"};
+
+ auto get_badge_text = [](ExtensionAction* action, int tab_id) {
+ return action->GetBadgeText(tab_id);
+ };
+
+ ActionTestHelper badge_text_helper(kApiName, "setBadgeText", "getBadgeText",
+ "text", profile(), extension->id());
+ run_test(badge_text_helper, default_badge_text, custom_badge_text1,
+ custom_badge_text2, base::BindRepeating(get_badge_text));
+ }
+ {
+ // setBadgeColor/getBadgeColor.
+ ValuePair default_badge_color{"0,0,0", "[0, 0, 0, 0]"};
+ ValuePair custom_badge_color1{"255,0,0", "[255, 0, 0, 255]"};
+ ValuePair custom_badge_color2{"0,255,0", "[0, 255, 0, 255]"};
+
+ auto get_badge_color = [](ExtensionAction* action, int tab_id) {
+ return color_utils::SkColorToRgbString(
+ action->GetBadgeBackgroundColor(tab_id));
+ };
+
+ ActionTestHelper badge_color_helper(kApiName, "setBadgeBackgroundColor",
+ "getBadgeBackgroundColor", "color",
+ profile(), extension->id());
+ run_test(badge_color_helper, default_badge_color, custom_badge_color1,
+ custom_badge_color2, base::BindRepeating(get_badge_color));
+ }
+}
+
+// Tests the functions to enable and disable extension actions.
+IN_PROC_BROWSER_TEST_P(MultiActionAPITest, EnableAndDisable) {
+ constexpr char kManifestTemplate[] =
+ R"({
+ "name": "enabled/disabled action test",
+ "version": "0.1",
+ "manifest_version": 2,
+ "%s": {},
+ "background": {"scripts": ["background.js"]}
+ })";
+
+ TestExtensionDir test_dir;
+ test_dir.WriteManifest(
+ base::StringPrintf(kManifestTemplate, GetManifestKey(GetParam())));
+ test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
+ "// This space left blank.");
+ const Extension* extension = LoadExtension(test_dir.UnpackedPath());
+ ASSERT_TRUE(extension);
+ ExtensionAction* action = GetExtensionAction(*extension);
+ ASSERT_TRUE(action);
+
+ const int tab_id1 = GetActiveTabId();
+ EnsureActionIsEnabledOnTab(action, tab_id1);
+
+ ui_test_utils::NavigateToURLWithDisposition(
+ browser(), GURL("chrome://newtab"),
+ WindowOpenDisposition::NEW_FOREGROUND_TAB,
+ ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
+
+ const int tab_id2 = GetActiveTabId();
+ EnsureActionIsEnabledOnTab(action, tab_id2);
+
+ EXPECT_NE(tab_id1, tab_id2);
+
+ const char* enable_function = nullptr;
+ const char* disable_function = nullptr;
+ switch (GetParam()) {
+ case ActionInfo::TYPE_ACTION:
+ case ActionInfo::TYPE_BROWSER:
+ enable_function = "enable";
+ disable_function = "disable";
+ break;
+ case ActionInfo::TYPE_PAGE:
+ enable_function = "show";
+ disable_function = "hide";
+ break;
+ }
+
+ // Start by toggling the extension action on the current tab.
+ {
+ constexpr char kScriptTemplate[] =
+ R"(chrome.%s.%s(%d, () => {
+ chrome.test.assertNoLastError();
+ chrome.test.notifyPass();
+ });)";
+ RunTestAndWaitForSuccess(
+ profile(), extension->id(),
+ base::StringPrintf(kScriptTemplate, GetAPIName(GetParam()),
+ disable_function, tab_id2));
+ EXPECT_FALSE(action->GetIsVisible(tab_id2));
+ EXPECT_TRUE(action->GetIsVisible(tab_id1));
+ }
+
+ {
+ constexpr char kScriptTemplate[] =
+ R"(chrome.%s.%s(%d, () => {
+ chrome.test.assertNoLastError();
+ chrome.test.notifyPass();
+ });)";
+ RunTestAndWaitForSuccess(
+ profile(), extension->id(),
+ base::StringPrintf(kScriptTemplate, GetAPIName(GetParam()),
+ enable_function, tab_id2));
+ EXPECT_TRUE(action->GetIsVisible(tab_id2));
+ EXPECT_TRUE(action->GetIsVisible(tab_id1));
+ }
+
+ // Page actions can't be enabled/disabled globally, but others can. Try
+ // toggling global state by omitting the tab id if the type isn't a page
+ // action.
+ if (GetParam() == ActionInfo::TYPE_PAGE)
+ return;
+
+ // We need to undo the explicit enable from above, since tab-specific
+ // values take precedence.
+ action->ClearAllValuesForTab(tab_id2);
+ {
+ constexpr char kScriptTemplate[] =
+ R"(chrome.%s.%s(() => {
+ chrome.test.assertNoLastError();
+ chrome.test.notifyPass();
+ });)";
+ RunTestAndWaitForSuccess(
+ profile(), extension->id(),
+ base::StringPrintf(kScriptTemplate, GetAPIName(GetParam()),
+ disable_function));
+ EXPECT_EQ(false, action->GetIsVisible(tab_id2));
+ EXPECT_EQ(false, action->GetIsVisible(tab_id1));
+ }
+
+ {
+ constexpr char kScriptTemplate[] =
+ R"(chrome.%s.%s(() => {
+ chrome.test.assertNoLastError();
+ chrome.test.notifyPass();
+ });)";
+ RunTestAndWaitForSuccess(
+ profile(), extension->id(),
+ base::StringPrintf(kScriptTemplate, GetAPIName(GetParam()),
+ enable_function));
+ EXPECT_EQ(true, action->GetIsVisible(tab_id2));
+ EXPECT_EQ(true, action->GetIsVisible(tab_id1));
+ }
+}
+
INSTANTIATE_TEST_SUITE_P(,
MultiActionAPITest,
testing::Values(ActionInfo::TYPE_ACTION,
ActionInfo::TYPE_PAGE,
ActionInfo::TYPE_BROWSER));
+INSTANTIATE_TEST_SUITE_P(,
+ MultiActionAPICanvasTest,
+ testing::Values(ActionInfo::TYPE_ACTION,
+ ActionInfo::TYPE_PAGE,
+ ActionInfo::TYPE_BROWSER));
+
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc b/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc
index 5c762878153..33f9d427be5 100644
--- a/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc
+++ b/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc
@@ -18,9 +18,9 @@
#include "chrome/browser/ui/simple_message_box.h"
#include "chrome/grit/generated_resources.h"
#include "components/feedback/system_logs/system_logs_fetcher.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/browser_context.h"
-#include "services/identity/public/cpp/identity_manager.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
@@ -33,8 +33,6 @@
#include "chrome/browser/chromeos/system_logs/single_log_file_log_source.h"
#include "chrome/browser/extensions/component_loader.h"
#include "chrome/browser/extensions/extension_service.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/ash/kiosk_next_shell_client.h"
#include "components/feedback/feedback_util.h"
#include "components/feedback/system_logs/system_logs_source.h"
#include "extensions/browser/extension_system.h"
@@ -200,8 +198,12 @@ void ChromeFeedbackPrivateDelegate::FetchExtraLogs(
constexpr bool scrub = true;
if (system_logs::ContainsIwlwifiLogs(feedback_data->sys_info())) {
+ // TODO (jkardatzke): Modify this so that we are using the same instance of
+ // the anonymizer for the rest of the logs.
+ // We can pass null for the 1st party IDs since we are just anonymizing
+ // wifi data here.
system_logs::SystemLogsFetcher* fetcher =
- new system_logs::SystemLogsFetcher(scrub);
+ new system_logs::SystemLogsFetcher(scrub, nullptr);
fetcher->AddSource(std::make_unique<system_logs::IwlwifiDumpLogSource>());
fetcher->Fetch(base::BindOnce(&OnFetchedExtraLogs, feedback_data,
std::move(callback)));
@@ -221,11 +223,6 @@ void ChromeFeedbackPrivateDelegate::UnloadFeedbackExtension(
api::feedback_private::LandingPageType
ChromeFeedbackPrivateDelegate::GetLandingPageType(
const feedback::FeedbackData& feedback_data) const {
- if (KioskNextShellClient::Get() &&
- KioskNextShellClient::Get()->has_launched()) {
- return api::feedback_private::LANDING_PAGE_TYPE_NOLANDINGPAGE;
- }
-
// Googlers using eve get a custom landing page.
if (!feedback_util::IsGoogleEmail(feedback_data.user_email()))
return api::feedback_private::LANDING_PAGE_TYPE_NORMAL;
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc b/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc
index 5e1ea66b880..d5d37cb5c27 100644
--- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc
@@ -10,6 +10,8 @@
#include "chrome/browser/extensions/component_loader.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/feedback/feedback_dialog_utils.h"
+#include "chrome/browser/feedback/feedback_uploader_chrome.h"
+#include "chrome/browser/feedback/feedback_uploader_factory_chrome.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/extensions/extension_constants.h"
@@ -94,14 +96,19 @@ class FeedbackTest : public ExtensionBrowserTest {
}
};
-// Disabled for ASan due to flakiness on Mac ASan 64 Tests (1).
-// See crbug.com/757243.
-#if defined(ADDRESS_SANITIZER)
-#define MAYBE_ShowFeedback DISABLED_ShowFeedback
-#else
-#define MAYBE_ShowFeedback ShowFeedback
-#endif
-IN_PROC_BROWSER_TEST_F(FeedbackTest, MAYBE_ShowFeedback) {
+class TestFeedbackUploaderDelegate
+ : public feedback::FeedbackUploaderChrome::Delegate {
+ public:
+ explicit TestFeedbackUploaderDelegate(base::RunLoop* quit_on_dispatch)
+ : quit_on_dispatch_(quit_on_dispatch) {}
+
+ void OnStartDispatchingReport() override { quit_on_dispatch_->Quit(); }
+
+ private:
+ base::RunLoop* quit_on_dispatch_;
+};
+
+IN_PROC_BROWSER_TEST_F(FeedbackTest, ShowFeedback) {
WaitForExtensionViewsToLoad();
ASSERT_TRUE(IsFeedbackAppAvailable());
@@ -109,14 +116,7 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, MAYBE_ShowFeedback) {
VerifyFeedbackAppLaunch();
}
-// Disabled for ASan due to flakiness on Mac ASan 64 Tests (1).
-// See crbug.com/757243.
-#if defined(ADDRESS_SANITIZER)
-#define MAYBE_ShowLoginFeedback DISABLED_ShowLoginFeedback
-#else
-#define MAYBE_ShowLoginFeedback ShowLoginFeedback
-#endif
-IN_PROC_BROWSER_TEST_F(FeedbackTest, MAYBE_ShowLoginFeedback) {
+IN_PROC_BROWSER_TEST_F(FeedbackTest, ShowLoginFeedback) {
WaitForExtensionViewsToLoad();
ASSERT_TRUE(IsFeedbackAppAvailable());
@@ -138,16 +138,9 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, MAYBE_ShowLoginFeedback) {
EXPECT_TRUE(bool_result);
}
-// Disabled for ASan due to flakiness on Mac ASan 64 Tests (1).
-// See crbug.com/757243.
-#if defined(ADDRESS_SANITIZER)
-#define MAYBE_AnonymousUser DISABLED_AnonymousUser
-#else
-#define MAYBE_AnonymousUser AnonymousUser
-#endif
// Tests that there's an option in the email drop down box with a value
// 'anonymous_user'.
-IN_PROC_BROWSER_TEST_F(FeedbackTest, MAYBE_AnonymousUser) {
+IN_PROC_BROWSER_TEST_F(FeedbackTest, AnonymousUser) {
WaitForExtensionViewsToLoad();
ASSERT_TRUE(IsFeedbackAppAvailable());
@@ -176,16 +169,9 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, MAYBE_AnonymousUser) {
EXPECT_TRUE(bool_result);
}
-// Disabled for ASan due to flakiness on Mac ASan 64 Tests (1).
-// See crbug.com/757243.
-#if defined(ADDRESS_SANITIZER)
-#define MAYBE_ExtraDiagnostics DISABLED_ExtraDiagnostics
-#else
-#define MAYBE_ExtraDiagnostics ExtraDiagnostics
-#endif
// Ensures that when extra diagnostics are provided with feedback, they are
// injected properly in the system information.
-IN_PROC_BROWSER_TEST_F(FeedbackTest, MAYBE_ExtraDiagnostics) {
+IN_PROC_BROWSER_TEST_F(FeedbackTest, ExtraDiagnostics) {
WaitForExtensionViewsToLoad();
ASSERT_TRUE(IsFeedbackAppAvailable());
@@ -216,16 +202,9 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, MAYBE_ExtraDiagnostics) {
EXPECT_TRUE(bool_result);
}
-// Disabled for ASan due to flakiness on Mac ASan 64 Tests (1).
-// See crbug.com/757243.
-#if defined(ADDRESS_SANITIZER)
-#define MAYBE_ShowFeedbackFromAssistant DISABLED_ShowFeedbackFromAssistant
-#else
-#define MAYBE_ShowFeedbackFromAssistant ShowFeedbackFromAssistant
-#endif
// Ensures that when triggered from Assistant with Google account, Assistant
// checkbox are not hidden.
-IN_PROC_BROWSER_TEST_F(FeedbackTest, MAYBE_ShowFeedbackFromAssistant) {
+IN_PROC_BROWSER_TEST_F(FeedbackTest, ShowFeedbackFromAssistant) {
WaitForExtensionViewsToLoad();
ASSERT_TRUE(IsFeedbackAppAvailable());
@@ -303,7 +282,7 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, ProvideBluetoothLogs) {
EXPECT_TRUE(bool_result);
}
#endif // if defined(CHROME_OS)
-
+
IN_PROC_BROWSER_TEST_F(FeedbackTest, GetTargetTabUrl) {
const std::pair<std::string, std::string> test_cases[] = {
{"https://www.google.com/", "https://www.google.com/"},
@@ -340,4 +319,49 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, GetTargetTabUrl) {
DevToolsWindowTesting::CloseDevToolsWindowSync(devtools_window);
}
}
+
+IN_PROC_BROWSER_TEST_F(FeedbackTest, SubmissionTest) {
+ WaitForExtensionViewsToLoad();
+
+ ASSERT_TRUE(IsFeedbackAppAvailable());
+ StartFeedbackUI(FeedbackFlow::FEEDBACK_FLOW_GOOGLEINTERNAL, std::string());
+ VerifyFeedbackAppLaunch();
+
+ AppWindow* const window =
+ PlatformAppBrowserTest::GetFirstAppWindowForBrowser(browser());
+ ASSERT_TRUE(window);
+ content::WebContents* const content = window->web_contents();
+
+ // Set a delegate for the uploader which will be invoked when the report
+ // normally would have been uploaded. We have it setup to then quit the
+ // RunLoop which will then allow us to terminate.
+ base::RunLoop run_loop;
+ TestFeedbackUploaderDelegate delegate(&run_loop);
+ feedback::FeedbackUploaderFactoryChrome::GetInstance()
+ ->GetForBrowserContext(browser()->profile())
+ ->set_feedback_uploader_delegate(&delegate);
+
+ // Click the send button.
+ bool bool_result = false;
+ ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
+ content,
+ "domAutomationController.send("
+ " ((function() {"
+ " if ($('send-report-button') != null) {"
+ " document.getElementById('send-report-button').click();"
+ " return true;"
+ " }"
+ " return false;"
+ " })()));",
+ &bool_result));
+ EXPECT_TRUE(bool_result);
+
+ // This will DCHECK if the JS private API call doesn't return a value, which
+ // is the main case we are concerned about.
+ run_loop.Run();
+ feedback::FeedbackUploaderFactoryChrome::GetInstance()
+ ->GetForBrowserContext(browser()->profile())
+ ->set_feedback_uploader_delegate(nullptr);
+}
+
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc b/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc
index 2f63eff6a5d..95152d04cec 100644
--- a/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc
+++ b/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc
@@ -15,7 +15,6 @@
#include "base/command_line.h"
#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
-#include "base/metrics/histogram_macros.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/trace_event/trace_event.h"
@@ -101,7 +100,6 @@ void MaybeUnlocalizeFontName(std::string* font_name) {
FontSettingsEventRouter::FontSettingsEventRouter(Profile* profile)
: profile_(profile) {
TRACE_EVENT0("browser,startup", "FontSettingsEventRouter::ctor")
- SCOPED_UMA_HISTOGRAM_TIMER("Extensions.FontSettingsEventRouterCtorTime");
registrar_.Init(profile_->GetPrefs());
diff --git a/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc b/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc
index 7e92c5b2fb0..3415d2fcaed 100644
--- a/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc
+++ b/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc
@@ -12,7 +12,6 @@
#include <vector>
#include "base/bind.h"
-#include "base/metrics/histogram_macros.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
@@ -142,8 +141,6 @@ GcmUnregisterFunction::GcmUnregisterFunction() {}
GcmUnregisterFunction::~GcmUnregisterFunction() {}
ExtensionFunction::ResponseAction GcmUnregisterFunction::Run() {
- UMA_HISTOGRAM_BOOLEAN("GCM.APICallUnregister", true);
-
GetGCMDriver()->Unregister(
extension()->id(),
base::Bind(&GcmUnregisterFunction::CompleteFunctionWithResult, this));
diff --git a/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc b/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc
index 1357ae0d862..58b8d24dda3 100644
--- a/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc
@@ -126,8 +126,8 @@ IN_PROC_BROWSER_TEST_F(GcmApiTest, Register) {
const std::vector<std::string>& sender_ids =
service()->last_registered_sender_ids();
- EXPECT_TRUE(base::ContainsValue(sender_ids, "Sender1"));
- EXPECT_TRUE(base::ContainsValue(sender_ids, "Sender2"));
+ EXPECT_TRUE(base::Contains(sender_ids, "Sender1"));
+ EXPECT_TRUE(base::Contains(sender_ids, "Sender2"));
}
IN_PROC_BROWSER_TEST_F(GcmApiTest, Unregister) {
diff --git a/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow.cc b/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow.cc
index 8e1bb0510da..63053cac503 100644
--- a/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow.cc
+++ b/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow.cc
@@ -14,10 +14,11 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/chrome_device_id_helper.h"
#include "chrome/browser/signin/identity_manager_factory.h"
-#include "components/signin/core/browser/ubertoken_fetcher.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "components/signin/public/identity_manager/ubertoken_fetcher.h"
+#include "google_apis/gaia/gaia_auth_fetcher.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/base/escape.h"
-#include "services/identity/public/cpp/identity_manager.h"
namespace extensions {
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_api.h b/chromium/chrome/browser/extensions/api/identity/identity_api.h
index 057a33f33c5..3ebdb2dcc38 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_api.h
+++ b/chromium/chrome/browser/extensions/api/identity/identity_api.h
@@ -29,10 +29,10 @@
#include "chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.h"
#include "chrome/browser/extensions/api/identity/web_auth_flow.h"
#include "chrome/browser/extensions/chrome_extension_function.h"
-#include "components/signin/core/browser/signin_buildflags.h"
+#include "components/signin/public/base/signin_buildflags.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "extensions/browser/browser_context_keyed_api_factory.h"
#include "extensions/browser/event_router.h"
-#include "services/identity/public/cpp/identity_manager.h"
namespace content {
class BrowserContext;
@@ -79,7 +79,7 @@ class IdentityTokenCacheValue {
};
class IdentityAPI : public BrowserContextKeyedAPI,
- public identity::IdentityManager::Observer {
+ public signin::IdentityManager::Observer {
public:
typedef std::map<ExtensionTokenKey, IdentityTokenCacheValue> CachedTokens;
@@ -128,7 +128,7 @@ class IdentityAPI : public BrowserContextKeyedAPI,
static const char* service_name() { return "IdentityAPI"; }
static const bool kServiceIsNULLWhileTesting = true;
- // identity::IdentityManager::Observer:
+ // signin::IdentityManager::Observer:
void OnRefreshTokenUpdatedForAccount(
const CoreAccountInfo& account_info) override;
// NOTE: This class must listen for this callback rather than
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc b/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc
index 06ba8e19052..a4d5166c2eb 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc
@@ -8,7 +8,7 @@
#include "build/build_config.h"
#include "chrome/browser/signin/scoped_account_consistency.h"
#include "chrome/test/base/testing_profile.h"
-#include "components/signin/core/browser/signin_buildflags.h"
+#include "components/signin/public/base/signin_buildflags.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc
index bb187fb62b2..99e6d3972a3 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc
@@ -47,17 +47,17 @@
#include "components/guest_view/browser/guest_view_base.h"
#include "components/prefs/pref_service.h"
#include "components/signin/core/browser/account_reconcilor.h"
-#include "components/signin/core/browser/list_accounts_test_utils.h"
-#include "components/signin/core/browser/signin_pref_names.h"
+#include "components/signin/public/base/list_accounts_test_utils.h"
+#include "components/signin/public/base/signin_pref_names.h"
+#include "components/signin/public/identity_manager/accounts_mutator.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/api_test_utils.h"
#include "extensions/common/extension_builder.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
-#include "services/identity/public/cpp/accounts_mutator.h"
-#include "services/identity/public/cpp/identity_manager.h"
-#include "services/identity/public/cpp/identity_test_utils.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -353,7 +353,7 @@ class FakeGetAuthTokenFunction : public IdentityGetAuthTokenFunction {
// Fix auth error on secondary account or add a new account.
void FixOrAddSecondaryAccount() {
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(GetProfile());
std::vector<CoreAccountInfo> accounts =
identity_manager->GetAccountsWithRefreshTokens();
@@ -373,7 +373,7 @@ class FakeGetAuthTokenFunction : public IdentityGetAuthTokenFunction {
}
}
if (!fixed_auth_error) {
- identity::MakeAccountAvailable(identity_manager, "secondary@example.com");
+ signin::MakeAccountAvailable(identity_manager, "secondary@example.com");
}
}
@@ -382,15 +382,15 @@ class FakeGetAuthTokenFunction : public IdentityGetAuthTokenFunction {
EXPECT_FALSE(login_ui_shown_);
login_ui_shown_ = true;
if (login_ui_result_) {
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(GetProfile());
if (IdentityAPI::GetFactoryInstance()
->Get(GetProfile())
->AreExtensionsRestrictedToPrimaryAccount()) {
// Set a primary account.
ASSERT_FALSE(identity_manager->HasPrimaryAccount());
- identity::MakeAccountAvailable(identity_manager, "primary@example.com");
- identity::SetPrimaryAccount(identity_manager, "primary@example.com");
+ signin::MakeAccountAvailable(identity_manager, "primary@example.com");
+ signin::SetPrimaryAccount(identity_manager, "primary@example.com");
} else {
FixOrAddSecondaryAccount();
}
@@ -495,7 +495,7 @@ class IdentityTestWithSignin : public AsyncExtensionBrowserTest {
return IdentityAPI::GetFactoryInstance()->Get(browser()->profile());
}
- identity::IdentityTestEnvironment* identity_test_env() {
+ signin::IdentityTestEnvironment* identity_test_env() {
return identity_test_env_profile_adaptor_->identity_test_env();
}
@@ -717,7 +717,7 @@ IN_PROC_BROWSER_TEST_F(IdentityGetProfileUserInfoFunctionTest,
class GetAuthTokenFunctionTest
: public IdentityTestWithSignin,
- public identity::IdentityManager::DiagnosticsObserver {
+ public signin::IdentityManager::DiagnosticsObserver {
public:
GetAuthTokenFunctionTest() {
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
@@ -814,8 +814,8 @@ class GetAuthTokenFunctionTest
base::OnceClosure on_access_token_requested_;
private:
- // identity::IdentityManager::DiagnosticsObserver:
- void OnAccessTokenRequested(const std::string& account_id,
+ // signin::IdentityManager::DiagnosticsObserver:
+ void OnAccessTokenRequested(const CoreAccountId& account_id,
const std::string& consumer_id,
const identity::ScopeSet& scopes) override {
if (on_access_token_requested_.is_null())
@@ -1523,7 +1523,7 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
signin::SetListAccountsResponseOneAccount(
account_info.email, account_info.gaia, &test_url_loader_factory_);
auto* identity_manager = IdentityManagerFactory::GetForProfile(profile);
- identity::SetFreshnessOfAccountsInGaiaCookie(identity_manager, false);
+ signin::SetFreshnessOfAccountsInGaiaCookie(identity_manager, false);
scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES));
scoped_refptr<FakeGetAuthTokenFunction> func(new FakeGetAuthTokenFunction());
@@ -2001,8 +2001,8 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesDefault) {
const ExtensionTokenKey* token_key = func->GetExtensionTokenKeyForTest();
EXPECT_EQ(2ul, token_key->scopes.size());
- EXPECT_TRUE(base::ContainsKey(token_key->scopes, "scope1"));
- EXPECT_TRUE(base::ContainsKey(token_key->scopes, "scope2"));
+ EXPECT_TRUE(base::Contains(token_key->scopes, "scope1"));
+ EXPECT_TRUE(base::Contains(token_key->scopes, "scope2"));
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmpty) {
@@ -2030,7 +2030,7 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmail) {
const ExtensionTokenKey* token_key = func->GetExtensionTokenKeyForTest();
EXPECT_EQ(1ul, token_key->scopes.size());
- EXPECT_TRUE(base::ContainsKey(token_key->scopes, "email"));
+ EXPECT_TRUE(base::Contains(token_key->scopes, "email"));
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmailFooBar) {
@@ -2047,9 +2047,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmailFooBar) {
const ExtensionTokenKey* token_key = func->GetExtensionTokenKeyForTest();
EXPECT_EQ(3ul, token_key->scopes.size());
- EXPECT_TRUE(base::ContainsKey(token_key->scopes, "email"));
- EXPECT_TRUE(base::ContainsKey(token_key->scopes, "foo"));
- EXPECT_TRUE(base::ContainsKey(token_key->scopes, "bar"));
+ EXPECT_TRUE(base::Contains(token_key->scopes, "email"));
+ EXPECT_TRUE(base::Contains(token_key->scopes, "foo"));
+ EXPECT_TRUE(base::Contains(token_key->scopes, "bar"));
}
#if defined(OS_CHROMEOS)
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc b/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc
index e125be0e33c..87a72fb83d1 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc
+++ b/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc
@@ -13,9 +13,9 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/common/extensions/api/identity.h"
-#include "components/signin/core/browser/account_info.h"
+#include "components/signin/public/identity_manager/account_info.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/browser_context.h"
-#include "services/identity/public/cpp/identity_manager.h"
namespace extensions {
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc
index e2a13a15a17..2efd2f74eb6 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc
+++ b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc
@@ -23,10 +23,13 @@
#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
#include "chrome/common/extensions/api/identity.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/signin_pref_names.h"
+#include "components/signin/public/base/signin_pref_names.h"
+#include "components/signin/public/identity_manager/access_token_info.h"
+#include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/common/extension_l10n_util.h"
+#include "google_apis/gaia/gaia_auth_util.h"
#include "google_apis/gaia/gaia_urls.h"
#include "services/identity/public/cpp/scope_set.h"
@@ -66,7 +69,8 @@ bool IsBrowserSigninAllowed(Profile* profile) {
IdentityGetAuthTokenFunction::IdentityGetAuthTokenFunction()
:
#if defined(OS_CHROMEOS)
- OAuth2TokenService::Consumer(kExtensionsIdentityAPIOAuthConsumerName),
+ OAuth2AccessTokenManager::Consumer(
+ kExtensionsIdentityAPIOAuthConsumerName),
#endif
interactive_(false),
should_prompt_for_scopes_(false),
@@ -74,8 +78,7 @@ IdentityGetAuthTokenFunction::IdentityGetAuthTokenFunction()
token_key_(/*extension_id=*/std::string(),
/*account_id=*/std::string(),
/*scopes=*/std::set<std::string>()),
- scoped_identity_manager_observer_(this),
- weak_ptr_factory_(this) {
+ scoped_identity_manager_observer_(this) {
}
IdentityGetAuthTokenFunction::~IdentityGetAuthTokenFunction() {
@@ -181,7 +184,7 @@ void IdentityGetAuthTokenFunction::GetAuthTokenForPrimaryAccount(
// No primary account, try the first account in cookies.
DCHECK_EQ(AccountListeningMode::kNotListening, account_listening_mode_);
account_listening_mode_ = AccountListeningMode::kListeningCookies;
- identity::AccountsInCookieJarInfo accounts_in_cookies =
+ signin::AccountsInCookieJarInfo accounts_in_cookies =
identity_manager->GetAccountsInCookieJar();
if (accounts_in_cookies.accounts_are_fresh) {
OnAccountsInCookieUpdated(accounts_in_cookies,
@@ -239,7 +242,7 @@ void IdentityGetAuthTokenFunction::OnReceivedExtensionAccountInfo(
}
void IdentityGetAuthTokenFunction::OnAccountsInCookieUpdated(
- const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
+ const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
const GoogleServiceAuthError& error) {
if (account_listening_mode_ != AccountListeningMode::kListeningCookies)
return;
@@ -512,8 +515,6 @@ void IdentityGetAuthTokenFunction::OnMintTokenFailure(
}
break;
case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS:
- case GoogleServiceAuthError::ACCOUNT_DELETED:
- case GoogleServiceAuthError::ACCOUNT_DISABLED:
// TODO(courage): flush ticket and retry once
if (ShouldStartSigninFlow()) {
StartSigninFlow();
@@ -688,7 +689,7 @@ void IdentityGetAuthTokenFunction::OnGetAccessTokenComplete(
#if defined(OS_CHROMEOS)
void IdentityGetAuthTokenFunction::OnGetTokenSuccess(
- const OAuth2TokenService::Request* request,
+ const OAuth2AccessTokenManager::Request* request,
const OAuth2AccessTokenConsumer::TokenResponse& token_response) {
device_access_token_request_.reset();
OnGetAccessTokenComplete(token_response.access_token,
@@ -697,7 +698,7 @@ void IdentityGetAuthTokenFunction::OnGetTokenSuccess(
}
void IdentityGetAuthTokenFunction::OnGetTokenFailure(
- const OAuth2TokenService::Request* request,
+ const OAuth2AccessTokenManager::Request* request,
const GoogleServiceAuthError& error) {
device_access_token_request_.reset();
OnGetAccessTokenComplete(base::nullopt, base::Time(), error);
@@ -706,7 +707,7 @@ void IdentityGetAuthTokenFunction::OnGetTokenFailure(
void IdentityGetAuthTokenFunction::OnAccessTokenFetchCompleted(
GoogleServiceAuthError error,
- identity::AccessTokenInfo access_token_info) {
+ signin::AccessTokenInfo access_token_info) {
token_key_account_access_token_fetcher_.reset();
if (error.state() == GoogleServiceAuthError::NONE) {
OnGetAccessTokenComplete(access_token_info.token,
@@ -736,10 +737,10 @@ void IdentityGetAuthTokenFunction::StartDeviceAccessTokenRequest() {
chromeos::DeviceOAuth2TokenServiceFactory::Get();
// Since robot account refresh tokens are scoped down to [any-api] only,
// request access token for [any-api] instead of login.
- OAuth2TokenService::ScopeSet scopes;
+ OAuth2AccessTokenManager::ScopeSet scopes;
scopes.insert(GaiaConstants::kAnyApiOAuth2Scope);
- device_access_token_request_ =
- service->StartRequest(service->GetRobotAccountId(), scopes, this);
+ device_access_token_request_ = service->StartAccessTokenRequest(
+ service->GetRobotAccountId(), scopes, this);
}
bool IdentityGetAuthTokenFunction::IsOriginWhitelistedInPublicSession() {
@@ -768,12 +769,11 @@ void IdentityGetAuthTokenFunction::StartTokenKeyAccountAccessTokenRequest() {
token_key_account_access_token_fetcher_ =
identity_manager->CreateAccessTokenFetcherForClient(
token_key_.account_id, app_client_id, app_client_secret,
- kExtensionsIdentityAPIOAuthConsumerName,
- OAuth2TokenService::ScopeSet(),
+ kExtensionsIdentityAPIOAuthConsumerName, ::identity::ScopeSet(),
base::BindOnce(
&IdentityGetAuthTokenFunction::OnAccessTokenFetchCompleted,
base::Unretained(this)),
- identity::AccessTokenFetcher::Mode::kImmediate);
+ signin::AccessTokenFetcher::Mode::kImmediate);
return;
}
}
@@ -786,7 +786,7 @@ void IdentityGetAuthTokenFunction::StartTokenKeyAccountAccessTokenRequest() {
base::BindOnce(
&IdentityGetAuthTokenFunction::OnAccessTokenFetchCompleted,
base::Unretained(this)),
- identity::AccessTokenFetcher::Mode::kImmediate);
+ signin::AccessTokenFetcher::Mode::kImmediate);
}
void IdentityGetAuthTokenFunction::StartGaiaRequest(
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h
index 6ff40e6af18..0eb440bebac 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h
+++ b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h
@@ -15,16 +15,16 @@
#include "chrome/browser/extensions/api/identity/gaia_web_auth_flow.h"
#include "chrome/browser/extensions/api/identity/identity_mint_queue.h"
#include "chrome/browser/extensions/chrome_extension_function.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "extensions/browser/extension_function_histogram_value.h"
#include "google_apis/gaia/google_service_auth_error.h"
+#include "google_apis/gaia/oauth2_access_token_manager.h"
#include "google_apis/gaia/oauth2_mint_token_flow.h"
-#include "google_apis/gaia/oauth2_token_service.h"
-#include "services/identity/public/cpp/identity_manager.h"
-namespace identity {
+namespace signin {
class AccessTokenFetcher;
struct AccessTokenInfo;
-} // namespace identity
+} // namespace signin
namespace extensions {
@@ -48,9 +48,9 @@ namespace extensions {
class IdentityGetAuthTokenFunction : public ChromeAsyncExtensionFunction,
public GaiaWebAuthFlow::Delegate,
public IdentityMintRequestQueue::Request,
- public identity::IdentityManager::Observer,
+ public signin::IdentityManager::Observer,
#if defined(OS_CHROMEOS)
- public OAuth2TokenService::Consumer,
+ public OAuth2AccessTokenManager::Consumer,
#endif
public OAuth2MintTokenFlow::Delegate {
public:
@@ -80,17 +80,17 @@ class IdentityGetAuthTokenFunction : public ChromeAsyncExtensionFunction,
// TODO(blundell): Investigate feasibility of moving the ChromeOS use case
// to use the Identity Service instead of being an
-// OAuth2TokenService::Consumer.
+// OAuth2AccessTokenManager::Consumer.
#if defined(OS_CHROMEOS)
void OnGetTokenSuccess(
- const OAuth2TokenService::Request* request,
+ const OAuth2AccessTokenManager::Request* request,
const OAuth2AccessTokenConsumer::TokenResponse& token_response) override;
- void OnGetTokenFailure(const OAuth2TokenService::Request* request,
+ void OnGetTokenFailure(const OAuth2AccessTokenManager::Request* request,
const GoogleServiceAuthError& error) override;
#endif
void OnAccessTokenFetchCompleted(GoogleServiceAuthError error,
- identity::AccessTokenInfo access_token_info);
+ signin::AccessTokenInfo access_token_info);
// Invoked on completion of the access token fetcher.
// Exposed for testing.
@@ -108,11 +108,12 @@ class IdentityGetAuthTokenFunction : public ChromeAsyncExtensionFunction,
// Pending request for an access token from the device account (via
// DeviceOAuth2TokenService).
- std::unique_ptr<OAuth2TokenService::Request> device_access_token_request_;
+ std::unique_ptr<OAuth2AccessTokenManager::Request>
+ device_access_token_request_;
// Pending fetcher for an access token for |token_key_.account_id| (via
// IdentityManager).
- std::unique_ptr<identity::AccessTokenFetcher>
+ std::unique_ptr<signin::AccessTokenFetcher>
token_key_account_access_token_fetcher_;
private:
@@ -135,11 +136,11 @@ class IdentityGetAuthTokenFunction : public ChromeAsyncExtensionFunction,
// Called when the AccountInfo that this instance should use is available.
void OnReceivedExtensionAccountInfo(const CoreAccountInfo* account_info);
- // identity::IdentityManager::Observer implementation:
+ // signin::IdentityManager::Observer implementation:
void OnRefreshTokenUpdatedForAccount(
const CoreAccountInfo& account_info) override;
void OnAccountsInCookieUpdated(
- const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
+ const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
const GoogleServiceAuthError& error) override;
void OnPrimaryAccountSet(
const CoreAccountInfo& primary_account_info) override;
@@ -217,7 +218,7 @@ class IdentityGetAuthTokenFunction : public ChromeAsyncExtensionFunction,
std::unique_ptr<base::CallbackList<void()>::Subscription>
identity_api_shutdown_subscription_;
- ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer>
+ ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer>
scoped_identity_manager_observer_;
// This class can be listening to account changes, but only for one type of
@@ -231,7 +232,7 @@ class IdentityGetAuthTokenFunction : public ChromeAsyncExtensionFunction,
AccountListeningMode account_listening_mode_ =
AccountListeningMode::kNotListening;
- base::WeakPtrFactory<IdentityGetAuthTokenFunction> weak_ptr_factory_;
+ base::WeakPtrFactory<IdentityGetAuthTokenFunction> weak_ptr_factory_{this};
};
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc b/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc
index f452bc2db0d..638ad8b7ef3 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc
+++ b/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc
@@ -8,11 +8,11 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/common/extensions/api/identity.h"
-#include "components/signin/core/browser/account_info.h"
+#include "components/signin/public/identity_manager/account_info.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/browser_context.h"
#include "extensions/common/extension.h"
#include "extensions/common/permissions/permissions_data.h"
-#include "services/identity/public/cpp/identity_manager.h"
namespace extensions {
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_mint_queue.cc b/chromium/chrome/browser/extensions/api/identity/identity_mint_queue.cc
index 73650b0a6f9..ea6dc52f2e7 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_mint_queue.cc
+++ b/chromium/chrome/browser/extensions/api/identity/identity_mint_queue.cc
@@ -73,7 +73,7 @@ void IdentityMintRequestQueue::RequestCancel(
bool IdentityMintRequestQueue::empty(IdentityMintRequestQueue::MintType type,
const ExtensionTokenKey& key) {
RequestQueueMap& request_queue_map = GetRequestQueueMap(type);
- return !base::ContainsKey(request_queue_map, key) ||
+ return !base::Contains(request_queue_map, key) ||
(request_queue_map.find(key))->second.empty();
}
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc
index 3dddc112fdf..7447bbcab5c 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc
@@ -19,7 +19,7 @@
#include "chrome/test/base/in_process_browser_test.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "services/service_manager/public/cpp/connector.h"
namespace extensions {
@@ -103,9 +103,7 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
private:
void SetUpOnMainThread() override {
- connector_ = content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->Clone();
+ connector_ = content::GetSystemConnector()->Clone();
}
void StartWriteTest() {
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc
index dffe7832647..3f5d95f8bc8 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc
@@ -20,7 +20,7 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/storage_partition.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_host.h"
#include "extensions/browser/extension_registry.h"
@@ -39,9 +39,7 @@ namespace image_writer {
using content::BrowserThread;
OperationManager::OperationManager(content::BrowserContext* context)
- : browser_context_(context),
- extension_registry_observer_(this),
- weak_factory_(this) {
+ : browser_context_(context), extension_registry_observer_(this) {
extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_));
Profile* profile = Profile::FromBrowserContext(browser_context_);
registrar_.Add(this,
@@ -247,9 +245,7 @@ void OperationManager::OnExtensionUnloaded(
std::unique_ptr<service_manager::Connector>
OperationManager::CreateConnector() {
- return content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->Clone();
+ return content::GetSystemConnector()->Clone();
}
void OperationManager::Observe(int type,
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h
index 48abcac2426..e9c88e3ac22 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h
@@ -122,7 +122,7 @@ class OperationManager : public BrowserContextKeyedAPI,
ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver>
extension_registry_observer_;
- base::WeakPtrFactory<OperationManager> weak_factory_;
+ base::WeakPtrFactory<OperationManager> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(OperationManager);
};
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc
index 389479b1ae2..fa04548454b 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc
@@ -8,12 +8,16 @@
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h"
#include "content/public/browser/browser_thread.h"
+
+#if defined(USE_UDEV)
#include "device/udev_linux/scoped_udev.h"
+#endif
namespace extensions {
// TODO(haven): Udev code may be duplicated in the Chrome codebase.
// https://code.google.com/p/chromium/issues/detail?id=284898
+#if defined(USE_UDEV)
// Returns the integer contained in |attr|. Returns 0 on error.
static uint64_t get_int_attr(const char* attr) {
uint64_t result = 0;
@@ -41,10 +45,12 @@ static int get_device_blk_size(const std::string& path) {
return blk_size;
}
+#endif // defined(USE_UDEV)
// static
scoped_refptr<StorageDeviceList>
RemovableStorageProvider::PopulateDeviceList() {
+#if defined(USE_UDEV)
device::ScopedUdevPtr udev(device::udev_new());
if (!udev) {
DLOG(ERROR) << "Can't create udev";
@@ -109,6 +115,9 @@ RemovableStorageProvider::PopulateDeviceList() {
}
return device_list;
+#else
+ return nullptr;
+#endif // defined(USE_UDEV)
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc
index 2310abe97c8..bcb23055c50 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc
@@ -13,7 +13,7 @@
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
-#include "net/url_request/test_url_request_interceptor.h"
+#include "content/public/test/url_loader_interceptor.h"
#include "services/service_manager/public/cpp/connector.h"
namespace extensions {
@@ -30,8 +30,6 @@ using testing::Lt;
const char kTestImageUrl[] = "http://localhost/test/image.zip";
-typedef net::LocalHostTestURLRequestInterceptor GetInterceptor;
-
} // namespace
// This class gives us a generic Operation with the ability to set or inspect
@@ -94,25 +92,28 @@ class WriteFromUrlOperationForTest : public WriteFromUrlOperation {
class ImageWriterWriteFromUrlOperationTest : public ImageWriterUnitTestBase {
protected:
- ImageWriterWriteFromUrlOperationTest() : manager_(&test_profile_) {}
-
- void SetUp() override {
- ImageWriterUnitTestBase::SetUp();
-
- // Turn on interception and set up our dummy file.
- get_interceptor_.reset(new GetInterceptor(
- base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}),
- base::CreateTaskRunnerWithTraits(
- {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
- base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})));
- get_interceptor_->SetResponse(GURL(kTestImageUrl),
- test_utils_.GetImagePath());
- }
+ ImageWriterWriteFromUrlOperationTest()
+ : url_loader_interceptor_(base::BindRepeating(
+ &ImageWriterWriteFromUrlOperationTest::HandleRequest,
+ base::Unretained(this))),
+ url_interception_count_(0),
+ manager_(&test_profile_) {}
void TearDown() override {
ImageWriterUnitTestBase::TearDown();
}
+ // Intercepts network requests.
+ bool HandleRequest(content::URLLoaderInterceptor::RequestParams* params) {
+ if (params->url_request.url == GURL(kTestImageUrl)) {
+ url_interception_count_++;
+ content::URLLoaderInterceptor::WriteResponse(test_utils_.GetImagePath(),
+ params->client.get());
+ return true;
+ }
+ return false;
+ }
+
scoped_refptr<WriteFromUrlOperationForTest> CreateOperation(
const GURL& url,
const std::string& hash) {
@@ -131,7 +132,8 @@ class ImageWriterWriteFromUrlOperationTest : public ImageWriterUnitTestBase {
}
TestingProfile test_profile_;
- std::unique_ptr<GetInterceptor> get_interceptor_;
+ content::URLLoaderInterceptor url_loader_interceptor_;
+ int url_interception_count_;
MockOperationManager manager_;
};
@@ -205,7 +207,7 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, DownloadFile) {
EXPECT_TRUE(base::ContentsEqual(test_utils_.GetImagePath(),
operation->GetImagePath()));
- EXPECT_EQ(1, get_interceptor_->GetHitCount());
+ EXPECT_EQ(1, url_interception_count_);
operation->Cancel();
}
@@ -236,11 +238,30 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, VerifyFile) {
operation->SetImagePath(test_utils_.GetImagePath());
{
base::RunLoop run_loop;
- operation->VerifyDownload(run_loop.QuitClosure());
+ // The OnProgress tasks are posted with priority USER_VISIBLE priority so
+ // post the quit closure with the same priority to ensure it doesn't run too
+ // soon.
+ operation->VerifyDownload(base::Bind(
+ [](base::OnceClosure quit_closure) {
+ base::PostTaskWithTraits(
+ FROM_HERE,
+ {content::BrowserThread::UI, base::TaskPriority::USER_VISIBLE},
+ std::move(quit_closure));
+ },
+ run_loop.QuitClosure()));
+
run_loop.Run();
}
operation->Cancel();
+
+ // The OnProgress calls we're expecting are posted to the Operation's
+ // SequencedTaskRunner. Flush it before the mock's expectations are checked.
+ {
+ base::RunLoop run_loop;
+ operation->PostTask(run_loop.QuitClosure());
+ run_loop.Run();
+ }
}
} // namespace image_writer
diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc
index d4dc455d531..b3d868bd61e 100644
--- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc
+++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc
@@ -9,7 +9,7 @@
#include <memory>
#include <utility>
-#include "ash/public/interfaces/keyboard_config.mojom.h"
+#include "ash/public/cpp/keyboard/keyboard_config.h"
#include "base/feature_list.h"
#include "base/macros.h"
#include "chrome/browser/chromeos/input_method/input_method_engine.h"
@@ -91,7 +91,7 @@ void SetMenuItemToMenu(
out->enabled = input.enabled ? *input.enabled : true;
}
-keyboard::mojom::KeyboardConfig GetKeyboardConfig() {
+keyboard::KeyboardConfig GetKeyboardConfig() {
return ChromeKeyboardControllerClient::Get()->GetKeyboardConfig();
}
diff --git a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc
index f71d6b6428d..1f6eb29db33 100644
--- a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc
+++ b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc
@@ -61,10 +61,7 @@ ExtensionFunction::ResponseAction InstanceIDApiFunction::Run() {
"chrome.instanceID not supported in incognito mode"));
}
- bool isInstanceIDEnabled = IsEnabled();
- UMA_HISTOGRAM_BOOLEAN("InstanceID.Enabled", isInstanceIDEnabled);
-
- if (!isInstanceIDEnabled) {
+ if (!IsEnabled()) {
return RespondNow(Error(
InstanceIDResultToError(instance_id::InstanceID::DISABLED)));
}
diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc
index 79319a90768..125a7777f72 100644
--- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc
@@ -167,7 +167,7 @@ std::vector<std::string> GetSortedThirdPartyIMEs(
auto it = descriptors.begin();
while (it != descriptors.end() && descriptors.size()) {
if (third_party_ime_set.count(it->id()) &&
- base::ContainsValue(it->language_codes(), language)) {
+ base::Contains(it->language_codes(), language)) {
ime_list.push_back(it->id());
// Remove the added descriptor from the candidate list.
it = descriptors.erase(it);
@@ -226,7 +226,7 @@ LanguageSettingsPrivateGetLanguageListFunction::Run() {
language.native_display_name = entry.native_display_name;
// Set optional fields only if they differ from the default.
- if (base::ContainsKey(spellcheck_language_set, entry.code)) {
+ if (base::Contains(spellcheck_language_set, entry.code)) {
language.supports_spellcheck.reset(new bool(true));
}
if (entry.supports_translate) {
@@ -286,7 +286,7 @@ LanguageSettingsPrivateEnableLanguageFunction::Run() {
std::string chrome_language = language_code;
language::ToChromeLanguageSynonym(&chrome_language);
- if (base::ContainsValue(languages, chrome_language)) {
+ if (base::Contains(languages, chrome_language)) {
LOG(ERROR) << "Language " << chrome_language << " already enabled";
return RespondNow(NoArguments());
}
@@ -319,7 +319,7 @@ LanguageSettingsPrivateDisableLanguageFunction::Run() {
std::string chrome_language = language_code;
language::ToChromeLanguageSynonym(&chrome_language);
- if (!base::ContainsValue(languages, chrome_language)) {
+ if (!base::Contains(languages, chrome_language)) {
LOG(ERROR) << "Language " << chrome_language << " not enabled";
return RespondNow(NoArguments());
}
diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_unittest.cc b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_unittest.cc
index 743b339b2bd..a35e419d0e0 100644
--- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_unittest.cc
@@ -93,7 +93,7 @@ class LanguageSettingsPrivateDelegateTest
std::unique_ptr<base::RunLoop> run_loop_;
};
-#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+#if BUILDFLAG(USE_RENDERER_SPELLCHECKER)
TEST_F(LanguageSettingsPrivateDelegateTest,
RetryDownloadHunspellDictionaryTest) {
@@ -116,6 +116,6 @@ TEST_F(LanguageSettingsPrivateDelegateTest,
EXPECT_FALSE(afterStatuses.front().download_failed);
}
-#endif // !BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+#endif // BUILDFLAG(USE_RENDERER_SPELLCHECKER)
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc
index 75d783e861b..eb9da3ee60f 100644
--- a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc
+++ b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc
@@ -39,8 +39,8 @@
#include "chrome/common/web_application_info.h"
#include "components/favicon/core/favicon_service.h"
#include "content/public/browser/browser_context.h"
+#include "content/public/browser/system_connector.h"
#include "content/public/browser/web_contents.h"
-#include "content/public/common/service_manager_connection.h"
#include "extensions/browser/api/management/management_api.h"
#include "extensions/browser/api/management/management_api_constants.h"
#include "extensions/browser/disable_reason.h"
@@ -70,8 +70,7 @@ class ManagementSetEnabledFunctionInstallPromptDelegate
const extensions::Extension* extension,
const base::Callback<void(bool)>& callback)
: install_prompt_(new ExtensionInstallPrompt(web_contents)),
- callback_(callback),
- weak_factory_(this) {
+ callback_(callback) {
ExtensionInstallPrompt::PromptType type =
ExtensionInstallPrompt::GetReEnablePromptTypeForExtension(
browser_context, extension);
@@ -97,7 +96,7 @@ class ManagementSetEnabledFunctionInstallPromptDelegate
base::Callback<void(bool)> callback_;
base::WeakPtrFactory<ManagementSetEnabledFunctionInstallPromptDelegate>
- weak_factory_;
+ weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ManagementSetEnabledFunctionInstallPromptDelegate);
};
@@ -258,10 +257,10 @@ void ChromeManagementAPIDelegate::LaunchAppFunctionDelegate(
// returned.
extensions::LaunchContainer launch_container =
GetLaunchContainer(extensions::ExtensionPrefs::Get(context), extension);
- OpenApplication(AppLaunchParams(Profile::FromBrowserContext(context),
- extension, launch_container,
- WindowOpenDisposition::NEW_FOREGROUND_TAB,
- extensions::SOURCE_MANAGEMENT_API));
+ OpenApplication(AppLaunchParams(
+ Profile::FromBrowserContext(context), extension->id(), launch_container,
+ WindowOpenDisposition::NEW_FOREGROUND_TAB,
+ extensions::AppLaunchSource::kSourceManagementApi));
#if defined(OS_CHROMEOS)
chromeos::DemoSession::RecordAppLaunchSourceIfInDemoMode(
@@ -288,8 +287,7 @@ void ChromeManagementAPIDelegate::
extensions::ManagementGetPermissionWarningsByManifestFunction* function,
const std::string& manifest_str) const {
data_decoder::SafeJsonParser::Parse(
- content::ServiceManagerConnection::GetForProcess()->GetConnector(),
- manifest_str,
+ content::GetSystemConnector(), manifest_str,
base::BindOnce(
&extensions::ManagementGetPermissionWarningsByManifestFunction::
OnParseSuccess,
diff --git a/chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc b/chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc
new file mode 100644
index 00000000000..af20dd95ad9
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc
@@ -0,0 +1,148 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/extensions/extension_action_runner.h"
+#include "chrome/browser/extensions/extension_apitest.h"
+#include "chrome/test/base/ui_test_utils.h"
+#include "extensions/browser/extension_dialog_auto_confirm.h"
+#include "extensions/browser/extension_registry.h"
+#include "extensions/browser/test_extension_registry_observer.h"
+#include "extensions/test/extension_test_message_listener.h"
+#include "extensions/test/result_catcher.h"
+#include "extensions/test/test_extension_dir.h"
+
+namespace extensions {
+
+namespace {
+enum class ContextType {
+ kEventPage,
+ kServiceWorker,
+};
+
+// Returns the newly added WebContents.
+// TODO(lazyboy): We have at least 3 versions of this AddTab within
+// //extensions, put this in a central place and use that instead.
+content::WebContents* AddTab(Browser* browser, const GURL& url) {
+ int starting_tab_count = browser->tab_strip_model()->count();
+ ui_test_utils::NavigateToURLWithDisposition(
+ browser, url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
+ ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
+ int tab_count = browser->tab_strip_model()->count();
+ EXPECT_EQ(starting_tab_count + 1, tab_count);
+ return browser->tab_strip_model()->GetActiveWebContents();
+}
+
+} // namespace
+
+// Tests management API from a non-persistent extension (event page or
+// Service Worker).
+class ManagementApiNonPersistentApiTest
+ : public ExtensionApiTest,
+ public testing::WithParamInterface<ContextType> {
+ protected:
+ const Extension* LoadNonPersistentExtension(const char* relative_path) {
+ return LoadExtensionWithFlags(test_data_dir_.AppendASCII(relative_path),
+ GetParam() == ContextType::kEventPage
+ ? kFlagNone
+ : kFlagRunAsServiceWorkerBasedExtension);
+ }
+};
+
+// Tests chrome.management.uninstallSelf API.
+IN_PROC_BROWSER_TEST_P(ManagementApiNonPersistentApiTest, UninstallSelf) {
+ constexpr char kEventPageBackgroundScript[] = R"({"scripts": ["script.js"]})";
+ constexpr char kServiceWorkerBackgroundScript[] =
+ R"({"service_worker": "script.js"})";
+
+ constexpr char kManifest[] =
+ R"({
+ "name": "Test Extension",
+ "manifest_version": 2,
+ "version": "0.1",
+ "background": %s
+ })";
+ std::string manifest =
+ base::StringPrintf(kManifest, GetParam() == ContextType::kEventPage
+ ? kEventPageBackgroundScript
+ : kServiceWorkerBackgroundScript);
+
+ // This script uninstalls itself.
+ constexpr char kScript[] =
+ "chrome.management.uninstallSelf({showConfirmDialog: false});";
+
+ TestExtensionDir test_dir;
+
+ test_dir.WriteManifest(manifest);
+ test_dir.WriteFile(FILE_PATH_LITERAL("script.js"), kScript);
+
+ // Construct this before loading the extension, since the extension will
+ // immediately uninstall itself when it loads.
+ extensions::TestExtensionRegistryObserver observer(
+ extensions::ExtensionRegistry::Get(browser()->profile()));
+
+ base::FilePath path = test_dir.Pack();
+ // NOTE: Do not use a scoped_refptr<Extension> as the |extension| might get
+ // uninstalled right away.
+ const Extension* extension = LoadExtension(path);
+
+ EXPECT_EQ(extension, observer.WaitForExtensionUninstalled());
+}
+
+// Tests chrome.management.uninstall with a real user gesture
+// (i.e. browserAction.onClicked event).
+IN_PROC_BROWSER_TEST_P(ManagementApiNonPersistentApiTest,
+ UninstallViaBrowserAction) {
+ const Extension* extension_b = LoadNonPersistentExtension(
+ "management/uninstall_via_browser_action/extension_b");
+ ASSERT_TRUE(extension_b);
+ const ExtensionId extension_b_id = extension_b->id();
+
+ ExtensionRegistry* registry = ExtensionRegistry::Get(profile());
+ // extension_b should be installed.
+ // Note: For the purpose of this test, just checking whether the extension is
+ // installed or not (ExtensionRegistry::EVERYTHING)
+ // is enough. But for clarity, we check for enabled-ness
+ // (ExtensionRegistry::ENABLED) here.
+ EXPECT_TRUE(
+ registry->GetExtensionById(extension_b_id, ExtensionRegistry::ENABLED));
+
+ // Load extension_a and wait for browserAction.onClicked listener
+ // registration.
+ ExtensionTestMessageListener listener_added("ready", false);
+ const Extension* extension_a = LoadNonPersistentExtension(
+ "management/uninstall_via_browser_action/extension_a");
+ ASSERT_TRUE(extension_a);
+ EXPECT_TRUE(listener_added.WaitUntilSatisfied());
+
+ // We need to accept uninstallation prompt since this is not a
+ // self-uninstallation.
+ ScopedTestDialogAutoConfirm auto_confirm_uninstall(
+ ScopedTestDialogAutoConfirm::ACCEPT);
+
+ ResultCatcher catcher;
+ // Click on browser action to start the test, |extension_a| will uninstall
+ // |extension_b|.
+ {
+ content::WebContents* web_contents = AddTab(browser(), GURL("about:blank"));
+ ASSERT_TRUE(web_contents);
+ ExtensionActionRunner::GetForWebContents(
+ browser()->tab_strip_model()->GetActiveWebContents())
+ ->RunAction(extension_a, true);
+ }
+ EXPECT_TRUE(catcher.GetNextResult()) << message_;
+
+ // extension_b should be gone.
+ EXPECT_FALSE(registry->GetExtensionById(extension_b_id,
+ ExtensionRegistry::EVERYTHING));
+}
+
+INSTANTIATE_TEST_SUITE_P(EventPage,
+ ManagementApiNonPersistentApiTest,
+ ::testing::Values(ContextType::kEventPage));
+
+INSTANTIATE_TEST_SUITE_P(ServiceWorker,
+ ManagementApiNonPersistentApiTest,
+ ::testing::Values(ContextType::kServiceWorker));
+
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/management/management_apitest.cc b/chromium/chrome/browser/extensions/api/management/management_apitest.cc
index 2a3b0f125f1..b9b4b8e09b0 100644
--- a/chromium/chrome/browser/extensions/api/management/management_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/management/management_apitest.cc
@@ -25,7 +25,6 @@
#include "extensions/browser/extension_system.h"
#include "extensions/browser/test_management_policy.h"
#include "extensions/common/manifest.h"
-#include "extensions/common/switches.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
#include "extensions/test/test_extension_dir.h"
@@ -68,8 +67,8 @@ class ExtensionManagementApiTest : public extensions::ExtensionApiTest {
DisableExtension(extension_ids_["disabled_app"]);
}
- // Load an app, and wait for a message from app "management/launch_on_install"
- // indicating that the new app has been launched.
+ // Load an app, and wait for a message that it has been launched. This should
+ // be sent by the launched app, to ensure the page is fully loaded.
void LoadAndWaitForLaunch(const std::string& app_path,
std::string* out_app_id) {
ExtensionTestMessageListener launched_app("launched app", false);
@@ -158,81 +157,32 @@ class InstallReplacementWebAppApiTest : public ExtensionManagementApiTest {
~InstallReplacementWebAppApiTest() override = default;
protected:
+ static const char kManifest[];
+ static const char kAppManifest[];
+
void SetUpOnMainThread() override {
ExtensionManagementApiTest::SetUpOnMainThread();
https_test_server_.ServeFilesFromDirectory(test_data_dir_);
ASSERT_TRUE(https_test_server_.Start());
}
- void SetUpCommandLine(base::CommandLine* command_line) override {
- ExtensionManagementApiTest::SetUpCommandLine(command_line);
- command_line->AppendSwitchASCII(
- extensions::switches::kWhitelistedExtensionID,
- "odfeghegfpmohakomgihhcnoboeecemb");
- }
-
- void RunTest(const char* web_app_path,
+ void RunTest(const char* manifest,
+ const char* web_app_path,
const char* background_script,
- bool from_webstore,
- bool whitelisted) {
- static constexpr char kManifest[] =
- R"({
- "name": "Management API Test",
- "version": "0.1",
- "manifest_version": 2,
- "background": { "scripts": ["background.js"] },
- "replacement_web_app": "%s"
- })";
-
- static constexpr char kPem[] =
- "-----BEGIN PRIVATE KEY-----"
- "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCs5ycnzJEUSwlN"
- "U7yAuywl8vro4dXew7Eijdd+gYwHAtaQyKxpeJHy09eusWKTfHEaOdqfqssqPMnl"
- "XqoC+Tyt/24xM6rw6uSyAV78DRSAl7AxiyemxTh5P2rzaN4ytJayLpZDzwi38zeZ"
- "QJC4TcSk04bclB2zfLFmMe8W53oxdE8vV6Xa2TPFigR6PV0FcRE40cCPHFhRTDwz"
- "C04b/qW30Ceix2AeLPT4+qsGroq5kLt7zTgvaA+QToKeZNX41snk1w2u/IhOXG+J"
- "0jyZnFU1lgnA9ScMW0laA+Ba2WXB5tLPgyRyyABRRaT5oiJCxRLQc+HFnMdUftGK"
- "D4MKnf+/AgMBAAECggEADJ+/8x7zhMjJwBSaEcgYvBiWi0RZ6i7dkwlKL5lj0Os7"
- "IU0VkYnVFiaze7TF3sDaPTD2Lmw48zeHAjE8NoVeEdIxiHQeSgLMedaxybNmyNDK"
- "c4OWfI2vxuKDe4wvlQIscowGOqM2HsAqUg0tw9chwWsUUKyb0owLI8wHieOSv2OA"
- "w8UlhflqkXLBUc4Mx3iqkIwAyrxQXT/vlA0M8/QvikK/zfeZYZ4f8tg23m3T0fV3"
- "HC4k/Q09MFyUvURVYNpbPHrL83/ZbaHBniEjy+qBX4POO4xrKhow77tr/znB8bsA"
- "T3mRwrEnYoIZmkwxlAdOMNxSYcAKZh4jPWOut0VQ0QKBgQDk341ysCaNzRq7nscR"
- "RzDtpAA+UPcS2vcssXKDRjhsTp31qsUsVsYjTX+O/sv2uyb4HikYiFZOe3iPIfOl"
- "ni7ZfhYFMMIZFjjP0cjQ7C/+ArxGb96DcTbRf7SNTDOLTtZy1jZSgIRek+2vvcr1"
- "a/xPUMCxLEZdUPu+AVhKYHKHOQKBgQDBZVr04r4s5/BygRR3NhFgquI8ffdPHZzC"
- "riEO1X/YOucTs+F+qwTvr25kRozpEjFsZJUibJTDngX9OziatAQdnjt5CtabOXd/"
- "1rSgUadWEvRrcy/aaouCE1J+1unX6Kk5RHmIsK1YP3wC6JrHmqfnEVq9kaoUubTC"
- "WHZfgjQGtwKBgF3B0nD8Bh8quVvIlGXYkwuWll7wzfYUaxMM8gsi1fRQVFcSCMm8"
- "FljZ43pRmH5PdoxH1q/tEeX+oImJ8ASVgz2ncB/aNHkQaF+B4dDsIFDfD/+Ozkls"
- "NHen5+/GGotj1WefpwsvCIqx8LmAd0cIYIihXP53U6/gf+/7Hw8A6YnJAoGAEbhs"
- "xiWEkW7LLGLBck7k9ruRsUNFht1KwNfdtZNAfJqhE8AWuFmJQUEM12lTfgOpvanV"
- "tGrIksgG+nYTsLEv81rNTkD8+wof9fnBYTM6Jvvjo3jReKzsjYWhuHeOw7bQ0quA"
- "i1LM/1oJzeZsUD/OhLClZNtU/0Mo2enrJsMyay8CgYEApCQ8BDMYewQj2MCM92Vw"
- "DWDzqQpfaGIG/eDAeEtdicbfdih3zUWfhEVOpnvf7s7nS8bMVpAo9pGW6sT/s8eX"
- "POGiP9efxb2uHsX06pkAYZm9nddIliWnm0/eDBmSSXPymAZaNYFrex4wxMII20K/"
- "ZX1nuseC+Lx0yzxa/c+iCWg="
- "-----END PRIVATE KEY-----";
-
+ bool from_webstore) {
extensions::TestExtensionDir extension_dir;
extension_dir.WriteManifest(base::StringPrintf(
- kManifest, https_test_server_.GetURL(web_app_path).spec().c_str()));
+ manifest, https_test_server_.GetURL(web_app_path).spec().c_str()));
extension_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
background_script);
-
- base::FilePath crx;
- if (whitelisted)
- crx = extension_dir.PackWithPem(kPem);
- else
- crx = extension_dir.Pack();
-
extensions::ResultCatcher catcher;
if (from_webstore) {
// |expected_change| is the expected change in the number of installed
// extensions.
- ASSERT_TRUE(InstallExtensionFromWebstore(crx, 1 /* expected_change */));
+ ASSERT_TRUE(InstallExtensionFromWebstore(extension_dir.UnpackedPath(),
+ 1 /* expected_change */));
} else {
- ASSERT_TRUE(LoadExtension(crx));
+ ASSERT_TRUE(LoadExtension(extension_dir.UnpackedPath()));
}
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
@@ -241,15 +191,25 @@ class InstallReplacementWebAppApiTest : public ExtensionManagementApiTest {
net::EmbeddedTestServer https_test_server_;
};
-IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NotWhitelisted) {
- static constexpr char kBackground[] = R"(
- chrome.test.assertEq(undefined, chrome.management.installReplacementWebApp);
- chrome.test.notifyPass();
- )";
-
- RunTest("/management/install_replacement_web_app/good_web_app/index.html",
- kBackground, true /* from_webstore */, false /* whitelisted */);
-}
+const char InstallReplacementWebAppApiTest::kManifest[] =
+ R"({
+ "name": "Management API Test",
+ "version": "0.1",
+ "manifest_version": 2,
+ "background": { "scripts": ["background.js"] },
+ "replacement_web_app": "%s"
+ })";
+
+const char InstallReplacementWebAppApiTest::kAppManifest[] =
+ R"({
+ "name": "Management API Test",
+ "version": "0.1",
+ "manifest_version": 2,
+ "app": {
+ "background": { "scripts": ["background.js"] }
+ },
+ "replacement_web_app": "%s"
+ })";
IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NotWebstore) {
static constexpr char kBackground[] = R"(
@@ -259,8 +219,9 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NotWebstore) {
chrome.test.notifyPass();
});)";
- RunTest("/management/install_replacement_web_app/good_web_app/index.html",
- kBackground, false /* from_webstore */, true /* whitelisted */);
+ RunTest(kManifest,
+ "/management/install_replacement_web_app/good_web_app/index.html",
+ kBackground, false /* from_webstore */);
}
IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NoGesture) {
@@ -271,8 +232,9 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NoGesture) {
chrome.test.notifyPass();
});)";
- RunTest("/management/install_replacement_web_app/good_web_app/index.html",
- kBackground, true /* from_webstore */, true /* whitelisted */);
+ RunTest(kManifest,
+ "/management/install_replacement_web_app/good_web_app/index.html",
+ kBackground, true /* from_webstore */);
}
IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NotInstallableWebApp) {
@@ -285,8 +247,9 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NotInstallableWebApp) {
});
});)";
- RunTest("/management/install_replacement_web_app/bad_web_app/index.html",
- kBackground, true /* from_webstore */, true /* whitelisted */);
+ RunTest(kManifest,
+ "/management/install_replacement_web_app/bad_web_app/index.html",
+ kBackground, true /* from_webstore */);
}
IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, InstallableWebApp) {
@@ -320,8 +283,44 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, InstallableWebApp) {
web_app::WebAppProviderBase::GetProviderBase(browser()->profile());
EXPECT_FALSE(provider->registrar().IsInstalled(good_web_app_url));
- RunTest(kGoodWebAppURL, kBackground, true /* from_webstore */,
- true /* whitelisted */);
+ RunTest(kManifest, kGoodWebAppURL, kBackground, true /* from_webstore */);
+ EXPECT_TRUE(provider->registrar().IsInstalled(good_web_app_url));
+ chrome::SetAutoAcceptPWAInstallConfirmationForTesting(false);
+}
+
+IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest,
+ InstallableWebAppInPlatformApp) {
+ static constexpr char kBackground[] =
+ R"(chrome.test.runTests([
+ function runInstall() {
+ chrome.test.runWithUserGesture(function() {
+ chrome.management.installReplacementWebApp(function() {
+ chrome.test.assertNoLastError();
+ chrome.test.succeed();
+ });
+ });
+ },
+ function runInstallWhenAlreadyInstalled() {
+ chrome.test.runWithUserGesture(function() {
+ chrome.management.installReplacementWebApp(function() {
+ chrome.test.assertLastError(
+ 'Web app is already installed.');
+ chrome.test.succeed();
+ });
+ });
+ }
+ ]);)";
+ static constexpr char kGoodWebAppURL[] =
+ "/management/install_replacement_web_app/good_web_app/index.html";
+
+ chrome::SetAutoAcceptPWAInstallConfirmationForTesting(true);
+ const GURL good_web_app_url = https_test_server_.GetURL(kGoodWebAppURL);
+
+ auto* provider =
+ web_app::WebAppProviderBase::GetProviderBase(browser()->profile());
+ EXPECT_FALSE(provider->registrar().IsInstalled(good_web_app_url));
+
+ RunTest(kAppManifest, kGoodWebAppURL, kBackground, true /* from_webstore */);
EXPECT_TRUE(provider->registrar().IsInstalled(good_web_app_url));
chrome::SetAutoAcceptPWAInstallConfirmationForTesting(false);
}
@@ -434,12 +433,14 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) {
ASSERT_TRUE(app_browser->is_app());
}
-// Disabled: crbug.com/230165, crbug.com/915339
-#if defined(OS_WIN) || defined(OS_MACOSX)
+// Disabled: crbug.com/230165, crbug.com/915339, crbug.com/979399
+#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \
+ defined(OS_CHROMEOS)
#define MAYBE_LaunchTabApp DISABLED_LaunchTabApp
#else
#define MAYBE_LaunchTabApp LaunchTabApp
#endif
+
IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, MAYBE_LaunchTabApp) {
extensions::ExtensionService* service =
extensions::ExtensionSystem::Get(browser()->profile())
diff --git a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc
index 7676a54d87b..b05f8f0c8cd 100644
--- a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc
@@ -403,8 +403,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) {
ASSERT_EQ("2.0", extension->VersionString());
ASSERT_TRUE(notification_listener.started());
ASSERT_TRUE(notification_listener.finished());
- ASSERT_TRUE(base::ContainsKey(notification_listener.updates(),
- "ogjcoiohnmldgjemafoockdghcjciccf"));
+ ASSERT_TRUE(base::Contains(notification_listener.updates(),
+ "ogjcoiohnmldgjemafoockdghcjciccf"));
notification_listener.Reset();
// Now try doing an update to version 3, which has been incorrectly
@@ -417,8 +417,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) {
ASSERT_TRUE(WaitForExtensionInstallError());
ASSERT_TRUE(notification_listener.started());
ASSERT_TRUE(notification_listener.finished());
- ASSERT_TRUE(base::ContainsKey(notification_listener.updates(),
- "ogjcoiohnmldgjemafoockdghcjciccf"));
+ ASSERT_TRUE(base::Contains(notification_listener.updates(),
+ "ogjcoiohnmldgjemafoockdghcjciccf"));
// Make sure the extension state is the same as before.
ASSERT_EQ(size_before + 1, registry->enabled_extensions().size());
@@ -514,8 +514,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest,
EXPECT_TRUE(listener2.WaitUntilSatisfied());
ASSERT_TRUE(notification_listener.started());
ASSERT_TRUE(notification_listener.finished());
- ASSERT_TRUE(base::ContainsKey(notification_listener.updates(),
- "ogjcoiohnmldgjemafoockdghcjciccf"));
+ ASSERT_TRUE(base::Contains(notification_listener.updates(),
+ "ogjcoiohnmldgjemafoockdghcjciccf"));
notification_listener.Reset();
}
diff --git a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc
index 9f241e74ad1..9d49d65504c 100644
--- a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc
+++ b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc
@@ -13,12 +13,9 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/chromeos/delegate_to_browser_gpu_service_accelerator_factory.h"
#include "content/public/browser/render_frame_host.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/video_capture_service.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
-#include "services/service_manager/public/cpp/connector.h"
-#include "services/video_capture/public/mojom/constants.mojom.h"
#include "services/video_capture/public/mojom/device_factory.mojom.h"
-#include "services/video_capture/public/mojom/device_factory_provider.mojom.h"
namespace extensions {
@@ -68,26 +65,18 @@ void MediaPerceptionAPIDelegateChromeOS::LoadCrOSComponent(
base::BindOnce(OnLoadComponent, std::move(load_callback)));
}
-void MediaPerceptionAPIDelegateChromeOS::
- BindDeviceFactoryProviderToVideoCaptureService(
- video_capture::mojom::DeviceFactoryProviderPtr* provider) {
+void MediaPerceptionAPIDelegateChromeOS::BindVideoSourceProvider(
+ mojo::PendingReceiver<video_capture::mojom::VideoSourceProvider> receiver) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- // In unit test environments, there may not be any connector.
- content::ServiceManagerConnection* connection =
- content::ServiceManagerConnection::GetForProcess();
- if (!connection)
- return;
- service_manager::Connector* connector = connection->GetConnector();
- if (!connector)
- return;
- connector->BindInterface(video_capture::mojom::kServiceName, provider);
-
video_capture::mojom::AcceleratorFactoryPtr accelerator_factory;
mojo::MakeStrongBinding(
std::make_unique<
content::DelegateToBrowserGpuServiceAcceleratorFactory>(),
mojo::MakeRequest(&accelerator_factory));
- (*provider)->InjectGpuDependencies(std::move(accelerator_factory));
+
+ auto& service = content::GetVideoCaptureService();
+ service.InjectGpuDependencies(std::move(accelerator_factory));
+ service.ConnectToVideoSourceProvider(std::move(receiver));
}
void MediaPerceptionAPIDelegateChromeOS::SetMediaPerceptionRequestHandler(
diff --git a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h
index 1d765110283..45abc51201e 100644
--- a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h
+++ b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h
@@ -20,8 +20,9 @@ class MediaPerceptionAPIDelegateChromeOS
void LoadCrOSComponent(
const api::media_perception_private::ComponentType& type,
LoadCrOSComponentCallback load_callback) override;
- void BindDeviceFactoryProviderToVideoCaptureService(
- video_capture::mojom::DeviceFactoryProviderPtr* provider) override;
+ void BindVideoSourceProvider(
+ mojo::PendingReceiver<video_capture::mojom::VideoSourceProvider> receiver)
+ override;
void SetMediaPerceptionRequestHandler(
MediaPerceptionRequestHandler handler) override;
void ForwardMediaPerceptionRequest(
diff --git a/chromium/chrome/browser/extensions/api/messaging/OWNERS b/chromium/chrome/browser/extensions/api/messaging/OWNERS
index e156a4cba3d..8e55ee8768b 100644
--- a/chromium/chrome/browser/extensions/api/messaging/OWNERS
+++ b/chromium/chrome/browser/extensions/api/messaging/OWNERS
@@ -1,6 +1,5 @@
# For extension/app messaging.
rdevlin.cronin@chromium.org
-asargent@chromium.org
# For native messaging.
sergeyu@chromium.org
diff --git a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc
index 37f434a3de3..b19df51e216 100644
--- a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc
@@ -127,6 +127,7 @@ std::unique_ptr<MessagePort> ChromeMessagingDelegate::CreateReceiverForTab(
std::unique_ptr<MessagePort>
ChromeMessagingDelegate::CreateReceiverForNativeApp(
+ content::BrowserContext* browser_context,
base::WeakPtr<MessagePort::ChannelDelegate> channel_delegate,
content::RenderFrameHost* source,
const std::string& extension_id,
@@ -136,8 +137,9 @@ ChromeMessagingDelegate::CreateReceiverForNativeApp(
std::string* error_out) {
DCHECK(error_out);
gfx::NativeView native_view = source ? source->GetNativeView() : nullptr;
- std::unique_ptr<NativeMessageHost> native_host = NativeMessageHost::Create(
- native_view, extension_id, native_app_name, allow_user_level, error_out);
+ std::unique_ptr<NativeMessageHost> native_host =
+ NativeMessageHost::Create(browser_context, native_view, extension_id,
+ native_app_name, allow_user_level, error_out);
if (!native_host.get())
return nullptr;
return std::make_unique<NativeMessagePort>(channel_delegate, receiver_port_id,
diff --git a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h
index 047341694d1..050786e4951 100644
--- a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h
+++ b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h
@@ -31,6 +31,7 @@ class ChromeMessagingDelegate : public MessagingDelegate {
content::WebContents* receiver_contents,
int receiver_frame_id) override;
std::unique_ptr<MessagePort> CreateReceiverForNativeApp(
+ content::BrowserContext* browser_context,
base::WeakPtr<MessagePort::ChannelDelegate> channel_delegate,
content::RenderFrameHost* source,
const std::string& extension_id,
diff --git a/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.cc b/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.cc
index 67b38a5de1a..b0058cb5ef3 100644
--- a/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.cc
@@ -47,8 +47,7 @@ int IncognitoConnectability::ScopedAlertTracker::GetAndResetAlertCount() {
}
IncognitoConnectability::IncognitoConnectability(
- content::BrowserContext* context)
- : weak_factory_(this) {
+ content::BrowserContext* context) {
CHECK(context->IsOffTheRecord());
}
@@ -150,10 +149,10 @@ void IncognitoConnectability::OnInteractiveResponse(
break;
}
- DCHECK(base::ContainsKey(pending_origins_, make_pair(extension_id, origin)));
+ DCHECK(base::Contains(pending_origins_, make_pair(extension_id, origin)));
PendingOrigin& pending_origin =
pending_origins_[make_pair(extension_id, origin)];
- DCHECK(base::ContainsKey(pending_origin, infobar_service));
+ DCHECK(base::Contains(pending_origin, infobar_service));
std::vector<base::Callback<void(bool)>> callbacks;
if (response == ScopedAlertTracker::INTERACTIVE) {
diff --git a/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.h b/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.h
index 2984f8730cc..f0fe400ca9f 100644
--- a/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.h
+++ b/chromium/chrome/browser/extensions/api/messaging/incognito_connectability.h
@@ -126,7 +126,7 @@ class IncognitoConnectability : public BrowserContextKeyedAPI {
// the query is resolved.
PendingOriginMap pending_origins_;
- base::WeakPtrFactory<IncognitoConnectability> weak_factory_;
+ base::WeakPtrFactory<IncognitoConnectability> weak_factory_{this};
};
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc
index e4116adadc8..1ba3053c6d1 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc
@@ -146,6 +146,7 @@ bool MatchesSecurityOrigin(const BuiltInHost& host,
} // namespace
std::unique_ptr<NativeMessageHost> NativeMessageHost::Create(
+ content::BrowserContext* browser_context,
gfx::NativeView native_view,
const std::string& source_extension_id,
const std::string& native_host_name,
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc
index 03089a914e9..c5efa12855f 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc
@@ -89,8 +89,7 @@ NativeMessagePort::NativeMessagePort(
std::unique_ptr<NativeMessageHost> native_message_host)
: weak_channel_delegate_(channel_delegate),
host_task_runner_(native_message_host->task_runner()),
- port_id_(port_id),
- weak_factory_(this) {
+ port_id_(port_id) {
core_.reset(new Core(std::move(native_message_host),
weak_factory_.GetWeakPtr(),
base::ThreadTaskRunnerHandle::Get()));
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_port.h b/chromium/chrome/browser/extensions/api/messaging/native_message_port.h
index 1e7684bb304..f087bd07c75 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_message_port.h
+++ b/chromium/chrome/browser/extensions/api/messaging/native_message_port.h
@@ -42,7 +42,7 @@ class NativeMessagePort : public MessagePort {
const PortId port_id_;
std::unique_ptr<Core> core_;
- base::WeakPtrFactory<NativeMessagePort> weak_factory_;
+ base::WeakPtrFactory<NativeMessagePort> weak_factory_{this};
};
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc
index 7b7133641d5..b6e5a3e5595 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc
@@ -6,6 +6,7 @@
#include <stddef.h>
#include <stdint.h>
+
#include <utility>
#include "base/bind.h"
@@ -15,7 +16,10 @@
#include "base/task/post_task.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h"
+#include "chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h"
#include "chrome/browser/extensions/api/messaging/native_process_launcher.h"
+#include "chrome/browser/profiles/profile.h"
+#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/common/constants.h"
@@ -38,6 +42,15 @@ const size_t kMessageHeaderSize = 4;
// Size of the buffer to be allocated for each read.
const size_t kReadBufferSize = 4096;
+base::FilePath GetProfilePathIfEnabled(Profile* profile,
+ const std::string& extension_id,
+ const std::string& host_id) {
+ return extensions::ExtensionSupportsConnectionFromNativeApp(
+ extension_id, host_id, profile, /* log_errors = */ false)
+ ? profile->GetPath()
+ : base::FilePath();
+}
+
} // namespace
namespace extensions {
@@ -55,8 +68,7 @@ NativeMessageProcessHost::NativeMessageProcessHost(
read_file_(-1),
#endif
read_pending_(false),
- write_pending_(false),
- weak_factory_(this) {
+ write_pending_(false) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
task_runner_ = base::CreateSingleThreadTaskRunnerWithTraits(
@@ -82,15 +94,19 @@ NativeMessageProcessHost::~NativeMessageProcessHost() {
// static
std::unique_ptr<NativeMessageHost> NativeMessageHost::Create(
+ content::BrowserContext* browser_context,
gfx::NativeView native_view,
const std::string& source_extension_id,
const std::string& native_host_name,
bool allow_user_level,
std::string* error_message) {
return NativeMessageProcessHost::CreateWithLauncher(
- source_extension_id,
- native_host_name,
- NativeProcessLauncher::CreateDefault(allow_user_level, native_view));
+ source_extension_id, native_host_name,
+ NativeProcessLauncher::CreateDefault(
+ allow_user_level, native_view,
+ GetProfilePathIfEnabled(Profile::FromBrowserContext(browser_context),
+ source_extension_id, native_host_name),
+ /* require_native_initiated_connections = */ false));
}
// static
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h
index b7355714661..1fb358fb70b 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h
+++ b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h
@@ -134,7 +134,7 @@ class NativeMessageProcessHost : public NativeMessageHost {
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
- base::WeakPtrFactory<NativeMessageProcessHost> weak_factory_;
+ base::WeakPtrFactory<NativeMessageProcessHost> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(NativeMessageProcessHost);
};
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc
index 4e27254cf0d..ddab3fb0276 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc
@@ -10,23 +10,34 @@
#include <memory>
#include <utility>
+#include "base/base_paths.h"
+#include "base/base_switches.h"
#include "base/bind.h"
+#include "base/command_line.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_reader.h"
+#include "base/path_service.h"
#include "base/process/process_metrics.h"
#include "base/rand_util.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/test/scoped_feature_list.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "build/build_config.h"
+#include "chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h"
#include "chrome/browser/extensions/api/messaging/native_messaging_test_util.h"
#include "chrome/browser/extensions/api/messaging/native_process_launcher.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/common/chrome_features.h"
+#include "chrome/common/chrome_switches.h"
+#include "chrome/test/base/testing_profile.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
@@ -167,6 +178,7 @@ class NativeMessagingTest : public ::testing::Test,
std::unique_ptr<NativeMessageHost> native_message_host_;
std::unique_ptr<base::RunLoop> run_loop_;
content::TestBrowserThreadBundle thread_bundle_;
+ TestingProfile profile_;
std::string last_message_;
std::unique_ptr<base::DictionaryValue> last_message_parsed_;
@@ -267,11 +279,8 @@ TEST_F(NativeMessagingTest, EchoConnect) {
ASSERT_NO_FATAL_FAILURE(test_host.RegisterTestHost(false));
std::string error_message;
native_message_host_ = NativeMessageProcessHost::Create(
- NULL,
- ScopedTestNativeMessagingHost::kExtensionId,
- ScopedTestNativeMessagingHost::kHostName,
- false,
- &error_message);
+ &profile_, NULL, ScopedTestNativeMessagingHost::kExtensionId,
+ ScopedTestNativeMessagingHost::kHostName, false, &error_message);
native_message_host_->Start(this);
ASSERT_TRUE(native_message_host_);
@@ -302,6 +311,120 @@ TEST_F(NativeMessagingTest, EchoConnect) {
EXPECT_EQ("bar", text);
EXPECT_TRUE(last_message_parsed_->GetString("caller_url", &url));
EXPECT_EQ(expected_url, url);
+
+ const base::Value* args = nullptr;
+ ASSERT_TRUE(last_message_parsed_->Get("args", &args));
+ EXPECT_TRUE(args->is_none());
+}
+
+// Test send message with a real client. The args passed when launching the
+// native messaging host should contain reconnect args.
+TEST_F(NativeMessagingTest, ReconnectArgs) {
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndEnableFeature(features::kOnConnectNative);
+ ScopedAllowNativeAppConnectionForTest allow_native_app_connection(true);
+ ScopedTestNativeMessagingHost test_host;
+ ASSERT_NO_FATAL_FAILURE(test_host.RegisterTestHost(false));
+ std::string error_message;
+ native_message_host_ = NativeMessageProcessHost::Create(
+ &profile_, NULL, ScopedTestNativeMessagingHost::kExtensionId,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ false, &error_message);
+ native_message_host_->Start(this);
+ ASSERT_TRUE(native_message_host_);
+
+ native_message_host_->OnMessage("{\"text\": \"Hello.\"}");
+ run_loop_.reset(new base::RunLoop());
+ run_loop_->Run();
+ ASSERT_FALSE(last_message_.empty());
+ ASSERT_TRUE(last_message_parsed_);
+
+ const base::ListValue* args_value = nullptr;
+ ASSERT_TRUE(last_message_parsed_->GetList("args", &args_value));
+ std::vector<base::CommandLine::StringType> args;
+ args.reserve(args_value->GetSize());
+ for (auto& arg : args_value->GetList()) {
+ ASSERT_TRUE(arg.is_string());
+#if defined(OS_WIN)
+ args.push_back(base::UTF8ToUTF16(arg.GetString()));
+#else
+ args.push_back(arg.GetString());
+#endif
+ }
+ base::CommandLine cmd_line(args);
+ base::FilePath exe_path;
+ ASSERT_TRUE(base::PathService::Get(base::FILE_EXE, &exe_path));
+ EXPECT_EQ(exe_path, cmd_line.GetProgram());
+ EXPECT_TRUE(cmd_line.HasSwitch(switches::kNoStartupWindow));
+ EXPECT_EQ(
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ cmd_line.GetSwitchValueASCII(switches::kNativeMessagingConnectHost));
+ EXPECT_EQ(
+ ScopedTestNativeMessagingHost::kExtensionId,
+ cmd_line.GetSwitchValueASCII(switches::kNativeMessagingConnectExtension));
+ EXPECT_EQ(features::kOnConnectNative.name,
+ cmd_line.GetSwitchValueASCII(switches::kEnableFeatures));
+ EXPECT_EQ(profile_.GetPath().BaseName(),
+ cmd_line.GetSwitchValuePath(switches::kProfileDirectory));
+ EXPECT_EQ(profile_.GetPath().DirName(),
+ cmd_line.GetSwitchValuePath(switches::kUserDataDir));
+}
+
+// Test send message with a real client. The args passed when launching the
+// native messaging host should not contain reconnect args.
+TEST_F(NativeMessagingTest, ReconnectArgs_Disabled) {
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndDisableFeature(features::kOnConnectNative);
+ ScopedTestNativeMessagingHost test_host;
+ ASSERT_NO_FATAL_FAILURE(test_host.RegisterTestHost(false));
+ std::string error_message;
+ native_message_host_ = NativeMessageProcessHost::Create(
+ &profile_, NULL, ScopedTestNativeMessagingHost::kExtensionId,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ false, &error_message);
+ native_message_host_->Start(this);
+ ASSERT_TRUE(native_message_host_);
+
+ native_message_host_->OnMessage("{\"text\": \"Hello.\"}");
+ run_loop_.reset(new base::RunLoop());
+ run_loop_->Run();
+ ASSERT_FALSE(last_message_.empty());
+ ASSERT_TRUE(last_message_parsed_);
+
+ const base::Value* args = nullptr;
+ ASSERT_TRUE(last_message_parsed_->Get("args", &args));
+ EXPECT_TRUE(args->is_none());
+}
+
+// Test that reconnect args are not sent if the extension is not permitted to
+// receive natively-established connections.
+TEST_F(NativeMessagingTest, ReconnectArgsIfNativeConnectionDisallowed) {
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndEnableFeature(features::kOnConnectNative);
+ ScopedAllowNativeAppConnectionForTest disallow_native_app_connection(false);
+ ScopedTestNativeMessagingHost test_host;
+ ASSERT_NO_FATAL_FAILURE(test_host.RegisterTestHost(false));
+ std::string error_message;
+ native_message_host_ = NativeMessageProcessHost::Create(
+ &profile_, NULL, ScopedTestNativeMessagingHost::kExtensionId,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ false, &error_message);
+ native_message_host_->Start(this);
+ ASSERT_TRUE(native_message_host_);
+
+ native_message_host_->OnMessage("{\"text\": \"Hello.\"}");
+ run_loop_.reset(new base::RunLoop());
+ run_loop_->Run();
+ ASSERT_FALSE(last_message_.empty());
+ ASSERT_TRUE(last_message_parsed_);
+
+ const base::Value* args_value = nullptr;
+ ASSERT_TRUE(last_message_parsed_->Get("args", &args_value));
+ EXPECT_TRUE(args_value->is_none());
}
TEST_F(NativeMessagingTest, UserLevel) {
@@ -310,11 +433,8 @@ TEST_F(NativeMessagingTest, UserLevel) {
std::string error_message;
native_message_host_ = NativeMessageProcessHost::Create(
- NULL,
- ScopedTestNativeMessagingHost::kExtensionId,
- ScopedTestNativeMessagingHost::kHostName,
- true,
- &error_message);
+ &profile_, NULL, ScopedTestNativeMessagingHost::kExtensionId,
+ ScopedTestNativeMessagingHost::kHostName, true, &error_message);
native_message_host_->Start(this);
ASSERT_TRUE(native_message_host_);
@@ -331,11 +451,8 @@ TEST_F(NativeMessagingTest, DisallowUserLevel) {
std::string error_message;
native_message_host_ = NativeMessageProcessHost::Create(
- NULL,
- ScopedTestNativeMessagingHost::kExtensionId,
- ScopedTestNativeMessagingHost::kHostName,
- false,
- &error_message);
+ &profile_, NULL, ScopedTestNativeMessagingHost::kExtensionId,
+ ScopedTestNativeMessagingHost::kHostName, false, &error_message);
native_message_host_->Start(this);
ASSERT_TRUE(native_message_host_);
run_loop_.reset(new base::RunLoop());
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc
index 0983cc2ca74..e8cc9ae6148 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc
@@ -2,10 +2,20 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include "base/feature_list.h"
+#include "base/test/scoped_feature_list.h"
+#include "build/build_config.h"
#include "chrome/browser/extensions/api/messaging/native_messaging_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
+#include "chrome/browser/ui/browser_list.h"
+#include "chrome/browser/ui/startup/startup_browser_creator.h"
+#include "chrome/common/chrome_features.h"
+#include "chrome/common/chrome_switches.h"
+#include "extensions/browser/process_manager.h"
+#include "extensions/test/result_catcher.h"
namespace extensions {
+namespace {
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, NativeMessagingBasic) {
extensions::ScopedTestNativeMessagingHost test_host;
@@ -19,4 +29,124 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, UserLevelNativeMessaging) {
ASSERT_TRUE(RunExtensionTest("native_messaging")) << message_;
}
+#if !defined(OS_CHROMEOS)
+
+class TestProcessManagerObserver : public ProcessManagerObserver {
+ public:
+ TestProcessManagerObserver() : observer_(this) {}
+
+ void WaitForProcessShutdown(ProcessManager* process_manager,
+ const std::string& extension_id) {
+ DCHECK(!quit_);
+ extension_id_ = extension_id;
+ base::RunLoop run_loop;
+ quit_ = run_loop.QuitClosure();
+
+ observer_.Add(process_manager);
+ run_loop.Run();
+ }
+
+ private:
+ void OnBackgroundHostClose(const std::string& extension_id) override {
+ if (extension_id != extension_id_) {
+ return;
+ }
+ observer_.RemoveAll();
+ extension_id_.clear();
+ std::move(quit_).Run();
+ }
+
+ std::string extension_id_;
+ ScopedObserver<ProcessManager, TestProcessManagerObserver> observer_;
+ base::OnceClosure quit_;
+
+ DISALLOW_COPY_AND_ASSIGN(TestProcessManagerObserver);
+};
+
+// Disabled on Windows due to timeouts; see https://crbug.com/984897.
+#if defined(OS_WIN)
+#define MAYBE_NativeMessagingLaunch DISABLED_NativeMessagingLaunch
+#else
+#define MAYBE_NativeMessagingLaunch NativeMessagingLaunch
+#endif
+IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_NativeMessagingLaunch) {
+ base::test::ScopedFeatureList features;
+ features.InitAndEnableFeature(features::kOnConnectNative);
+ ProcessManager::SetEventPageIdleTimeForTesting(1);
+ ProcessManager::SetEventPageSuspendingTimeForTesting(1);
+ extensions::ScopedTestNativeMessagingHost test_host;
+ ASSERT_NO_FATAL_FAILURE(test_host.RegisterTestHost(false));
+
+ auto* extension =
+ LoadExtension(test_data_dir_.AppendASCII("native_messaging_launch"));
+ TestProcessManagerObserver observer;
+ observer.WaitForProcessShutdown(ProcessManager::Get(profile()),
+ extension->id());
+
+ ResultCatcher catcher;
+
+ base::CommandLine command_line(*base::CommandLine::ForCurrentProcess());
+ command_line.AppendSwitchASCII(switches::kNativeMessagingConnectExtension,
+ extension->id());
+ command_line.AppendSwitchASCII(
+ switches::kNativeMessagingConnectHost,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName);
+
+ StartupBrowserCreator::ProcessCommandLineAlreadyRunning(command_line, {},
+ profile()->GetPath());
+
+ if (!catcher.GetNextResult()) {
+ FAIL() << catcher.message();
+ }
+ size_t tabs = 0;
+ for (auto* browser : *BrowserList::GetInstance()) {
+ tabs += browser->tab_strip_model()->count();
+ }
+ EXPECT_EQ(1u, tabs);
+}
+
+// Test that a natively-initiated connection from a host not supporting
+// natively-initiated connections is not allowed. The test extension expects the
+// channel to be immediately closed with an error.
+IN_PROC_BROWSER_TEST_F(
+ ExtensionApiTest,
+ NativeMessagingLaunch_LaunchFromNativeUnsupportedByNativeHost) {
+ base::test::ScopedFeatureList features;
+ features.InitAndEnableFeature(features::kOnConnectNative);
+ ProcessManager::SetEventPageIdleTimeForTesting(1);
+ ProcessManager::SetEventPageSuspendingTimeForTesting(1);
+ extensions::ScopedTestNativeMessagingHost test_host;
+ ASSERT_NO_FATAL_FAILURE(test_host.RegisterTestHost(false));
+
+ auto* extension = LoadExtension(
+ test_data_dir_.AppendASCII("native_messaging_launch_unsupported"));
+ TestProcessManagerObserver observer;
+ observer.WaitForProcessShutdown(ProcessManager::Get(profile()),
+ extension->id());
+
+ ResultCatcher catcher;
+
+ base::CommandLine command_line(*base::CommandLine::ForCurrentProcess());
+ command_line.AppendSwitchASCII(switches::kNativeMessagingConnectExtension,
+ extension->id());
+ command_line.AppendSwitchASCII(switches::kNativeMessagingConnectHost,
+ ScopedTestNativeMessagingHost::kHostName);
+
+ StartupBrowserCreator::ProcessCommandLineAlreadyRunning(command_line, {},
+ profile()->GetPath());
+
+ if (!catcher.GetNextResult()) {
+ FAIL() << catcher.message();
+ }
+ size_t tabs = 0;
+ for (auto* browser : *BrowserList::GetInstance()) {
+ tabs += browser->tab_strip_model()->count();
+ }
+ EXPECT_EQ(1u, tabs);
+}
+
+#endif // !defined(OS_CHROMEOS)
+
+} // namespace
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.cc
index 7ddb9b946e4..5750d0ff045 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.cc
@@ -10,6 +10,7 @@
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/values.h"
+#include "chrome/common/chrome_features.h"
namespace extensions {
@@ -135,6 +136,19 @@ bool NativeMessagingHostManifest::Parse(base::DictionaryValue* dictionary,
allowed_origins_.AddPattern(pattern);
}
+ if (base::FeatureList::IsEnabled(features::kOnConnectNative)) {
+ if (const base::Value* supports_native_initiated_connections =
+ dictionary->FindKey("supports_native_initiated_connections")) {
+ if (!supports_native_initiated_connections->is_bool()) {
+ *error_message =
+ "supports_native_initiated_connections must be a boolean.";
+ return false;
+ }
+ supports_native_initiated_connections_ =
+ supports_native_initiated_connections->GetBool();
+ }
+ }
+
return true;
}
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h
index 9e7f98ca88d..d31c3db1f26 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h
@@ -40,6 +40,9 @@ class NativeMessagingHostManifest {
HostInterface host_interface() const { return interface_; }
const base::FilePath& path() const { return path_; }
const URLPatternSet& allowed_origins() const { return allowed_origins_; }
+ bool supports_native_initiated_connections() const {
+ return supports_native_initiated_connections_;
+ }
private:
NativeMessagingHostManifest();
@@ -53,6 +56,7 @@ class NativeMessagingHostManifest {
HostInterface interface_;
base::FilePath path_;
URLPatternSet allowed_origins_;
+ bool supports_native_initiated_connections_ = false;
DISALLOW_COPY_AND_ASSIGN(NativeMessagingHostManifest);
};
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc
index b12e3d7be51..4f4b61bb09b 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc
@@ -8,7 +8,11 @@
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/string_escape.h"
+#include "base/strings/strcat.h"
+#include "base/strings/stringprintf.h"
+#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
+#include "chrome/common/chrome_features.h"
#include "extensions/common/url_pattern_set.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
@@ -32,18 +36,32 @@ class NativeMessagingHostManifestTest : public ::testing::Test {
}
protected:
- bool WriteManifest(const std::string& name,
- const std::string& path,
- const std::string& origin) {
- return WriteManifest("{"
- " \"name\": \"" + name + "\","
- " \"description\": \"Native Messaging Test\","
- " \"path\": " + base::GetQuotedJSONString(path) + ","
- " \"type\": \"stdio\","
- " \"allowed_origins\": ["
- " \"" + origin + "\""
- " ]"
- "}");
+ bool WriteManifest(
+ const std::string& name,
+ const std::string& path,
+ const std::string& origin,
+ base::Optional<std::string> supports_native_initiated_connections) {
+ std::string supports_native_initiated_connections_snippet;
+ if (supports_native_initiated_connections) {
+ supports_native_initiated_connections_snippet = base::StrCat({
+ R"("supports_native_initiated_connections": )",
+ *supports_native_initiated_connections,
+ ",\n",
+ });
+ }
+ return WriteManifest(base::StringPrintf(
+ R"({
+ "name": "%s",
+ "description": "Native Messaging Test",
+ "path": %s,
+ "type": "stdio",
+ %s
+ "allowed_origins": [
+ "%s"
+ ]
+ })",
+ name.c_str(), base::GetQuotedJSONString(path).c_str(),
+ supports_native_initiated_connections_snippet.c_str(), origin.c_str()));
}
bool WriteManifest(const std::string& manifest_content) {
@@ -72,7 +90,8 @@ TEST_F(NativeMessagingHostManifestTest, HostNameValidation) {
}
TEST_F(NativeMessagingHostManifestTest, LoadValid) {
- ASSERT_TRUE(WriteManifest(kTestHostName, kTestHostPath, kTestOrigin));
+ ASSERT_TRUE(
+ WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, base::nullopt));
std::string error_message;
std::unique_ptr<NativeMessagingHostManifest> manifest =
@@ -89,11 +108,83 @@ TEST_F(NativeMessagingHostManifestTest, LoadValid) {
GURL("chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/")));
EXPECT_FALSE(manifest->allowed_origins().MatchesSecurityOrigin(
GURL("chrome-extension://jnldjmfmopnpolahpmmgbagdohdnhkik/")));
+ EXPECT_FALSE(manifest->supports_native_initiated_connections());
+}
+
+TEST_F(NativeMessagingHostManifestTest,
+ LoadValid_SupportsNativeInitiatedConnections) {
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndEnableFeature(features::kOnConnectNative);
+ ASSERT_TRUE(WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, "true"));
+ std::string error_message;
+ std::unique_ptr<NativeMessagingHostManifest> manifest =
+ NativeMessagingHostManifest::Load(manifest_path_, &error_message);
+ ASSERT_TRUE(manifest) << "Failed to load manifest: " << error_message;
+ EXPECT_TRUE(error_message.empty());
+
+ EXPECT_TRUE(manifest->supports_native_initiated_connections());
+}
+
+TEST_F(NativeMessagingHostManifestTest,
+ LoadValid_SupportsNativeInitiatedConnectionsWithFeatureDisabled) {
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndDisableFeature(features::kOnConnectNative);
+ ASSERT_TRUE(WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, "true"));
+ std::string error_message;
+ std::unique_ptr<NativeMessagingHostManifest> manifest =
+ NativeMessagingHostManifest::Load(manifest_path_, &error_message);
+ ASSERT_TRUE(manifest) << "Failed to load manifest: " << error_message;
+ EXPECT_TRUE(error_message.empty());
+
+ EXPECT_FALSE(manifest->supports_native_initiated_connections());
+}
+
+TEST_F(NativeMessagingHostManifestTest,
+ LoadValid_DoesNotSupportNativeInitiatedConnections) {
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndEnableFeature(features::kOnConnectNative);
+ ASSERT_TRUE(
+ WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, "false"));
+ std::string error_message;
+ std::unique_ptr<NativeMessagingHostManifest> manifest =
+ NativeMessagingHostManifest::Load(manifest_path_, &error_message);
+ ASSERT_TRUE(manifest) << "Failed to load manifest: " << error_message;
+ EXPECT_TRUE(error_message.empty());
+
+ EXPECT_FALSE(manifest->supports_native_initiated_connections());
+}
+
+TEST_F(NativeMessagingHostManifestTest,
+ LoadValid_DoesNotSpecifySupportNativeInitiatedConnections) {
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndEnableFeature(features::kOnConnectNative);
+ ASSERT_TRUE(
+ WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, base::nullopt));
+ std::string error_message;
+ std::unique_ptr<NativeMessagingHostManifest> manifest =
+ NativeMessagingHostManifest::Load(manifest_path_, &error_message);
+ ASSERT_TRUE(manifest) << "Failed to load manifest: " << error_message;
+ EXPECT_TRUE(error_message.empty());
+
+ EXPECT_FALSE(manifest->supports_native_initiated_connections());
+}
+
+TEST_F(NativeMessagingHostManifestTest,
+ LoadInvalidSupportsNativeInitiatedConnections) {
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndEnableFeature(features::kOnConnectNative);
+ ASSERT_TRUE(
+ WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, "\"true\""));
+ std::string error_message;
+ std::unique_ptr<NativeMessagingHostManifest> manifest =
+ NativeMessagingHostManifest::Load(manifest_path_, &error_message);
+ ASSERT_FALSE(manifest);
+ EXPECT_FALSE(error_message.empty());
}
TEST_F(NativeMessagingHostManifestTest, InvalidName) {
- ASSERT_TRUE(WriteManifest(".com.chrome.test.native_host",
- kTestHostPath, kTestOrigin));
+ ASSERT_TRUE(WriteManifest(".com.chrome.test.native_host", kTestHostPath,
+ kTestOrigin, base::nullopt));
std::string error_message;
std::unique_ptr<NativeMessagingHostManifest> manifest =
@@ -105,7 +196,7 @@ TEST_F(NativeMessagingHostManifestTest, InvalidName) {
// Verify that match-all origins are rejected.
TEST_F(NativeMessagingHostManifestTest, MatchAllOrigin) {
ASSERT_TRUE(WriteManifest(kTestHostName, kTestHostPath,
- "chrome-extension://*/"));
+ "chrome-extension://*/", base::nullopt));
std::string error_message;
std::unique_ptr<NativeMessagingHostManifest> manifest =
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc
new file mode 100644
index 00000000000..eabfae9941d
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc
@@ -0,0 +1,126 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h"
+
+#include <memory>
+#include <utility>
+
+#include "chrome/browser/extensions/api/messaging/native_message_port.h"
+#include "chrome/browser/extensions/api/messaging/native_message_process_host.h"
+#include "chrome/browser/extensions/api/messaging/native_process_launcher.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/common/extensions/manifest_handlers/natively_connectable_handler.h"
+#include "extensions/browser/api/messaging/channel_endpoint.h"
+#include "extensions/browser/api/messaging/message_service.h"
+#include "extensions/browser/event_router.h"
+#include "extensions/browser/extension_registry.h"
+#include "extensions/common/api/messaging/messaging_endpoint.h"
+#include "extensions/common/permissions/permission_set.h"
+#include "extensions/common/permissions/permissions_data.h"
+
+namespace extensions {
+namespace {
+
+ScopedAllowNativeAppConnectionForTest* g_allow_native_app_connection_for_test =
+ nullptr;
+
+} // namespace
+
+bool ExtensionSupportsConnectionFromNativeApp(const std::string& extension_id,
+ const std::string& host_id,
+ Profile* profile,
+ bool log_errors) {
+ if (g_allow_native_app_connection_for_test) {
+ return g_allow_native_app_connection_for_test->allow();
+ }
+ if (profile->IsOffTheRecord()) {
+ return false;
+ }
+ auto* extension =
+ ExtensionRegistry::Get(profile)->enabled_extensions().GetByID(
+ extension_id);
+ if (!extension) {
+ LOG_IF(ERROR, log_errors)
+ << "Failed to launch native messaging connection: Unknown extension ID "
+ << extension_id;
+ return false;
+ }
+ const auto* natively_connectable_hosts =
+ NativelyConnectableHosts::GetConnectableNativeMessageHosts(*extension);
+ if (!natively_connectable_hosts ||
+ !natively_connectable_hosts->count(host_id)) {
+ LOG_IF(ERROR, log_errors)
+ << "Extension \"" << extension_id << "\" does not list \"" << host_id
+ << "\" in its natively_connectable manifest field";
+ return false;
+ }
+ if (!extension->permissions_data()->active_permissions().HasAPIPermission(
+ "nativeMessaging")) {
+ LOG_IF(ERROR, log_errors)
+ << "Extension \"" << extension_id
+ << "\" does not have the \"nativeMessaging\" permission";
+ return false;
+ }
+ if (!extension->permissions_data()->active_permissions().HasAPIPermission(
+ "transientBackground")) {
+ LOG_IF(ERROR, log_errors)
+ << "Extension \"" << extension_id
+ << "\" does not have the \"transientBackground\" permission";
+ return false;
+ }
+ if (!EventRouter::Get(profile)->ExtensionHasEventListener(
+ extension_id, "runtime.onConnectNative")) {
+ LOG_IF(ERROR, log_errors)
+ << "Failed to launch native messaging connection: Extension \""
+ << extension_id << "\" is not listening for runtime.onConnectNative";
+ return false;
+ }
+
+ return true;
+}
+
+ScopedAllowNativeAppConnectionForTest::ScopedAllowNativeAppConnectionForTest(
+ bool allow)
+ : allow_(allow) {
+ DCHECK(!g_allow_native_app_connection_for_test);
+ g_allow_native_app_connection_for_test = this;
+}
+
+ScopedAllowNativeAppConnectionForTest::
+ ~ScopedAllowNativeAppConnectionForTest() {
+ DCHECK_EQ(this, g_allow_native_app_connection_for_test);
+ g_allow_native_app_connection_for_test = nullptr;
+}
+
+void LaunchNativeMessageHostFromNativeApp(const std::string& extension_id,
+ const std::string& host_id,
+ Profile* profile) {
+ if (!ExtensionSupportsConnectionFromNativeApp(extension_id, host_id, profile,
+ /* log_errors = */ true)) {
+ // TODO(crbug.com/967262): Report errors to the native messaging host.
+ return;
+ }
+ const extensions::PortId port_id(base::UnguessableToken::Create(),
+ 1 /* port_number */, true /* is_opener */);
+ extensions::MessageService* const message_service =
+ extensions::MessageService::Get(profile);
+ // TODO(crbug.com/967262): Apply policy for allow_user_level.
+ auto native_message_host = NativeMessageProcessHost::CreateWithLauncher(
+ extension_id, host_id,
+ NativeProcessLauncher::CreateDefault(
+ /* allow_user_level = */ true, /* native_view = */ nullptr,
+ profile->GetPath(),
+ /* require_native_initiated_connections = */ true));
+ auto native_message_port = std::make_unique<extensions::NativeMessagePort>(
+ message_service->GetChannelDelegate(), port_id,
+ std::move(native_message_host));
+ message_service->OpenChannelToExtension(
+ extensions::ChannelEndpoint(profile), port_id,
+ extensions::MessagingEndpoint::ForNativeApp(host_id),
+ std::move(native_message_port), extension_id, GURL(),
+ std::string() /* channel_name */);
+}
+
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h
new file mode 100644
index 00000000000..d730422c455
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h
@@ -0,0 +1,44 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_EXTENSIONS_API_MESSAGING_NATIVE_MESSAGING_LAUNCH_FROM_NATIVE_H_
+#define CHROME_BROWSER_EXTENSIONS_API_MESSAGING_NATIVE_MESSAGING_LAUNCH_FROM_NATIVE_H_
+
+#include <string>
+#include "base/macros.h"
+
+class Profile;
+
+namespace extensions {
+
+// Returns whether |extension_id| running in |profile| is allowed to accept
+// connections from native host named |host_id|.
+bool ExtensionSupportsConnectionFromNativeApp(const std::string& extension_id,
+ const std::string& host_id,
+ Profile* profile,
+ bool log_errors);
+
+// Creates a native messaging connection between the extension with ID
+// |extension_id| with |profile| and the native messaging host with name
+// |host_id|.
+void LaunchNativeMessageHostFromNativeApp(const std::string& extension_id,
+ const std::string& host_id,
+ Profile* profile);
+
+class ScopedAllowNativeAppConnectionForTest {
+ public:
+ explicit ScopedAllowNativeAppConnectionForTest(bool allow);
+ ~ScopedAllowNativeAppConnectionForTest();
+
+ bool allow() const { return allow_; }
+
+ private:
+ const bool allow_;
+
+ DISALLOW_COPY_AND_ASSIGN(ScopedAllowNativeAppConnectionForTest);
+};
+
+} // namespace extensions
+
+#endif // CHROME_BROWSER_EXTENSIONS_API_MESSAGING_NATIVE_MESSAGING_LAUNCH_FROM_NATIVE_H_
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc
new file mode 100644
index 00000000000..48ab25ef66f
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc
@@ -0,0 +1,236 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h"
+
+#include <memory>
+#include <utility>
+
+#include "base/path_service.h"
+#include "base/test/values_test_util.h"
+#include "chrome/browser/extensions/api/messaging/native_messaging_test_util.h"
+#include "chrome/test/base/testing_profile.h"
+#include "components/version_info/version_info.h"
+#include "content/public/test/test_browser_thread_bundle.h"
+#include "extensions/browser/event_router.h"
+#include "extensions/browser/event_router_factory.h"
+#include "extensions/browser/extension_prefs.h"
+#include "extensions/browser/extension_registry.h"
+#include "extensions/common/extension_paths.h"
+#include "extensions/common/features/feature_channel.h"
+#include "extensions/common/manifest_constants.h"
+#include "extensions/common/value_builder.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace extensions {
+namespace {
+
+class MockEventRouter : public EventRouter {
+ public:
+ MockEventRouter(content::BrowserContext* browser_context,
+ ExtensionPrefs* extension_prefs,
+ const bool* has_listener_result)
+ : EventRouter(browser_context, extension_prefs),
+ has_listener_result_(has_listener_result) {
+ DCHECK(has_listener_result_);
+ }
+
+ bool ExtensionHasEventListener(const std::string& extension_id,
+ const std::string& event_name) const override {
+ return *has_listener_result_;
+ }
+
+ private:
+ const bool* has_listener_result_;
+};
+
+std::unique_ptr<KeyedService> BuildMockEventRouter(
+ const bool* has_listener_result,
+ content::BrowserContext* context) {
+ return std::make_unique<MockEventRouter>(
+ context, ExtensionPrefs::Get(context), has_listener_result);
+}
+
+class ExtensionSupportsConnectionFromNativeAppTest : public ::testing::Test {
+ public:
+ ExtensionSupportsConnectionFromNativeAppTest()
+ : channel_(version_info::Channel::DEV) {}
+
+ void SetUp() override {
+ EventRouterFactory::GetInstance()->SetTestingFactory(
+ &profile_,
+ base::BindRepeating(&BuildMockEventRouter, &has_listener_result_));
+ }
+
+ protected:
+ void RegisterExtension(bool natively_connectable,
+ bool transient_background_permission,
+ bool native_messaging_permission) {
+ DictionaryBuilder manifest_builder(
+ static_cast<base::DictionaryValue&&>(base::test::ParseJson(R"(
+ {
+ "version": "1.0.0.0",
+ "manifest_version": 2,
+ "name": "native messaging test",
+ "description": "native messaging test",
+ "background": {
+ "scripts": ["test.js"],
+ "persistent": false
+ }
+ }
+ )")));
+
+ if (natively_connectable) {
+ ListBuilder natively_connectable_hosts;
+ natively_connectable_hosts.Append(
+ ScopedTestNativeMessagingHost::kHostName);
+
+ natively_connectable_hosts.Append(
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName);
+ manifest_builder.Set(manifest_keys::kNativelyConnectable,
+ natively_connectable_hosts.Build());
+ }
+
+ ListBuilder permissions;
+ if (transient_background_permission) {
+ permissions.Append("transientBackground");
+ }
+ if (native_messaging_permission) {
+ permissions.Append("nativeMessaging");
+ }
+ manifest_builder.Set(manifest_keys::kPermissions, permissions.Build());
+
+ base::FilePath path;
+ EXPECT_TRUE(base::PathService::Get(DIR_TEST_DATA, &path));
+
+ std::string error;
+ scoped_refptr<Extension> extension(
+ Extension::Create(path, Manifest::INTERNAL, *manifest_builder.Build(),
+ Extension::NO_FLAGS, &error));
+ ASSERT_TRUE(extension.get()) << error;
+ ExtensionRegistry::Get(&profile_)->AddEnabled(extension);
+ extension_id_ = extension->id();
+ }
+
+ ScopedCurrentChannel channel_;
+ content::TestBrowserThreadBundle thread_bundle_;
+ bool has_listener_result_ = true;
+ TestingProfile profile_;
+ std::string extension_id_;
+};
+
+TEST_F(ExtensionSupportsConnectionFromNativeAppTest, Success) {
+ ASSERT_NO_FATAL_FAILURE(RegisterExtension(true, true, true));
+
+ EXPECT_TRUE(ExtensionSupportsConnectionFromNativeApp(
+ extension_id_,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ &profile_, false));
+}
+
+TEST_F(ExtensionSupportsConnectionFromNativeAppTest, NoOnConnectNative) {
+ ASSERT_NO_FATAL_FAILURE(RegisterExtension(true, true, true));
+ has_listener_result_ = false;
+
+ EXPECT_FALSE(ExtensionSupportsConnectionFromNativeApp(
+ extension_id_,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ &profile_, false));
+}
+
+TEST_F(ExtensionSupportsConnectionFromNativeAppTest, OffTheRecordProfile) {
+ auto* off_the_record_profile = profile_.GetOffTheRecordProfile();
+ ASSERT_NO_FATAL_FAILURE(RegisterExtension(true, true, true));
+
+ EXPECT_FALSE(ExtensionSupportsConnectionFromNativeApp(
+ extension_id_,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ off_the_record_profile, false));
+}
+
+TEST_F(ExtensionSupportsConnectionFromNativeAppTest, NotNativelyConnectable) {
+ ASSERT_NO_FATAL_FAILURE(RegisterExtension(false, true, true));
+
+ EXPECT_FALSE(ExtensionSupportsConnectionFromNativeApp(
+ extension_id_,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ &profile_, false));
+}
+
+TEST_F(ExtensionSupportsConnectionFromNativeAppTest, NotTransientBackground) {
+ ASSERT_NO_FATAL_FAILURE(RegisterExtension(true, false, true));
+
+ EXPECT_FALSE(ExtensionSupportsConnectionFromNativeApp(
+ extension_id_,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ &profile_, false));
+}
+
+TEST_F(ExtensionSupportsConnectionFromNativeAppTest, NotNativeMessaging) {
+ ASSERT_NO_FATAL_FAILURE(RegisterExtension(true, true, false));
+
+ EXPECT_FALSE(ExtensionSupportsConnectionFromNativeApp(
+ extension_id_,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ &profile_, false));
+}
+
+TEST_F(ExtensionSupportsConnectionFromNativeAppTest, NativeMessagingOnly) {
+ ASSERT_NO_FATAL_FAILURE(RegisterExtension(false, false, true));
+
+ EXPECT_FALSE(ExtensionSupportsConnectionFromNativeApp(
+ extension_id_,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ &profile_, false));
+}
+
+TEST_F(ExtensionSupportsConnectionFromNativeAppTest, TransientBackgroundOnly) {
+ ASSERT_NO_FATAL_FAILURE(RegisterExtension(false, true, false));
+
+ EXPECT_FALSE(ExtensionSupportsConnectionFromNativeApp(
+ extension_id_,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ &profile_, false));
+}
+
+TEST_F(ExtensionSupportsConnectionFromNativeAppTest, NativelyConnectableOnly) {
+ ASSERT_NO_FATAL_FAILURE(RegisterExtension(true, false, false));
+
+ EXPECT_FALSE(ExtensionSupportsConnectionFromNativeApp(
+ extension_id_,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ &profile_, false));
+}
+
+TEST_F(ExtensionSupportsConnectionFromNativeAppTest, NoPermissions) {
+ ASSERT_NO_FATAL_FAILURE(RegisterExtension(false, false, false));
+ has_listener_result_ = false;
+
+ EXPECT_FALSE(ExtensionSupportsConnectionFromNativeApp(
+ extension_id_,
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ &profile_, false));
+}
+
+TEST_F(ExtensionSupportsConnectionFromNativeAppTest, UnknownExtension) {
+ EXPECT_FALSE(ExtensionSupportsConnectionFromNativeApp(
+ "fake extension id",
+ ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName,
+ &profile_, false));
+}
+
+} // namespace
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.cc
index 1acf4aec153..34d944dbb63 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.cc
@@ -29,12 +29,15 @@ namespace {
void WriteTestNativeHostManifest(const base::FilePath& target_dir,
const std::string& host_name,
const base::FilePath& host_path,
- bool user_level) {
+ bool user_level,
+ bool supports_native_initiated_connections) {
std::unique_ptr<base::DictionaryValue> manifest(new base::DictionaryValue());
manifest->SetString("name", host_name);
manifest->SetString("description", "Native Messaging Echo Test");
manifest->SetString("type", "stdio");
manifest->SetString("path", host_path.AsUTF8Unsafe());
+ manifest->SetBoolean("supports_native_initiated_connections",
+ supports_native_initiated_connections);
std::unique_ptr<base::ListValue> origins(new base::ListValue());
origins->AppendString(base::StringPrintf(
@@ -63,6 +66,9 @@ const char ScopedTestNativeMessagingHost::kHostName[] =
"com.google.chrome.test.echo";
const char ScopedTestNativeMessagingHost::kBinaryMissingHostName[] =
"com.google.chrome.test.host_binary_missing";
+const char ScopedTestNativeMessagingHost::
+ kSupportsNativeInitiatedConnectionsHostName[] =
+ "com.google.chrome.test.inbound_native_echo";
const char ScopedTestNativeMessagingHost::kExtensionId[] =
"knldjmfmopnpolahpmmgbagdohdnhkik";
@@ -95,11 +101,16 @@ void ScopedTestNativeMessagingHost::RegisterTestHost(bool user_level) {
base::FilePath host_path = test_user_data_dir.AppendASCII("echo.bat");
#endif
ASSERT_NO_FATAL_FAILURE(WriteTestNativeHostManifest(
- temp_dir_.GetPath(), kHostName, host_path, user_level));
+ temp_dir_.GetPath(), kHostName, host_path, user_level, false));
ASSERT_NO_FATAL_FAILURE(WriteTestNativeHostManifest(
temp_dir_.GetPath(), kBinaryMissingHostName,
- test_user_data_dir.AppendASCII("missing_nm_binary.exe"), user_level));
+ test_user_data_dir.AppendASCII("missing_nm_binary.exe"), user_level,
+ false));
+
+ ASSERT_NO_FATAL_FAILURE(WriteTestNativeHostManifest(
+ temp_dir_.GetPath(), kSupportsNativeInitiatedConnectionsHostName,
+ host_path, user_level, true));
}
ScopedTestNativeMessagingHost::~ScopedTestNativeMessagingHost() {
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.h b/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.h
index 0757bf70294..b5ccbdc70a5 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.h
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.h
@@ -29,6 +29,8 @@ class ScopedTestNativeMessagingHost {
public:
static const char kHostName[];
static const char kBinaryMissingHostName[];
+ static const char kSupportsNativeInitiatedConnectionsHostName[];
+
static const char kExtensionId[];
ScopedTestNativeMessagingHost();
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc
index a281b8500bc..fc731d68f81 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc
@@ -5,20 +5,30 @@
#include "chrome/browser/extensions/api/messaging/native_process_launcher.h"
#include <inttypes.h>
+
#include <utility>
+#include "base/base64.h"
+#include "base/base_paths.h"
+#include "base/base_switches.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
+#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
+#include "base/path_service.h"
+#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/task/post_task.h"
+#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h"
+#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths.h"
+#include "chrome/common/chrome_switches.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "url/gurl.h"
@@ -35,7 +45,9 @@ namespace {
class NativeProcessLauncherImpl : public NativeProcessLauncher {
public:
NativeProcessLauncherImpl(bool allow_user_level_hosts,
- intptr_t native_window);
+ intptr_t native_window,
+ const base::FilePath& profile_directory,
+ bool require_native_initiated_connections);
~NativeProcessLauncherImpl() override;
void Launch(const GURL& origin,
@@ -45,7 +57,10 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher {
private:
class Core : public base::RefCountedThreadSafe<Core> {
public:
- Core(bool allow_user_level_hosts, intptr_t native_window);
+ Core(bool allow_user_level_hosts,
+ intptr_t native_window,
+ const base::FilePath& profile_directory,
+ bool require_native_initiated_connections);
void Launch(const GURL& origin,
const std::string& native_host_name,
const LaunchedCallback& callback);
@@ -71,8 +86,11 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher {
bool detached_;
- bool allow_user_level_hosts_;
+ const bool allow_user_level_hosts_;
+
+ const base::FilePath profile_directory_;
+ const bool require_native_initiated_connections_;
#if defined(OS_WIN)
// Handle of the native window corresponding to the extension.
intptr_t window_handle_;
@@ -87,11 +105,17 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher {
};
NativeProcessLauncherImpl::Core::Core(bool allow_user_level_hosts,
- intptr_t window_handle)
+ intptr_t window_handle,
+ const base::FilePath& profile_directory,
+ bool require_native_initiated_connections)
: detached_(false),
- allow_user_level_hosts_(allow_user_level_hosts)
+ allow_user_level_hosts_(allow_user_level_hosts),
+ profile_directory_(profile_directory),
+ require_native_initiated_connections_(
+ require_native_initiated_connections)
#if defined(OS_WIN)
- , window_handle_(window_handle)
+ ,
+ window_handle_(window_handle)
#endif // OS_WIN
{}
@@ -158,6 +182,12 @@ void NativeProcessLauncherImpl::Core::DoLaunchOnThreadPool(
return;
}
+ if (require_native_initiated_connections_ &&
+ !manifest->supports_native_initiated_connections()) {
+ PostErrorResult(callback, RESULT_FORBIDDEN);
+ return;
+ }
+
base::FilePath host_path = manifest->path();
if (!host_path.IsAbsolute()) {
// On Windows host path is allowed to be relative to the location of the
@@ -196,6 +226,41 @@ void NativeProcessLauncherImpl::Core::DoLaunchOnThreadPool(
base::StringPrintf("--parent-window=%" PRIdPTR, window_handle_));
#endif // !defined(OS_WIN)
+ if (manifest->supports_native_initiated_connections() &&
+ !profile_directory_.empty()) {
+ base::FilePath exe_path;
+ base::PathService::Get(base::FILE_EXE, &exe_path);
+
+ base::CommandLine reconnect_command_line(exe_path);
+ reconnect_command_line.AppendSwitch(::switches::kNoStartupWindow);
+ reconnect_command_line.AppendSwitchASCII(
+ ::switches::kNativeMessagingConnectHost, native_host_name);
+ reconnect_command_line.AppendSwitchASCII(
+ ::switches::kNativeMessagingConnectExtension, origin.host());
+ reconnect_command_line.AppendSwitchASCII(::switches::kEnableFeatures,
+ features::kOnConnectNative.name);
+ reconnect_command_line.AppendSwitchPath(::switches::kProfileDirectory,
+ profile_directory_.BaseName());
+ reconnect_command_line.AppendSwitchPath(::switches::kUserDataDir,
+ profile_directory_.DirName());
+#if defined(OS_WIN)
+ reconnect_command_line.AppendArg(
+ ::switches::kPrefetchArgumentBrowserBackground);
+#endif
+ base::Value args(base::Value::Type::LIST);
+ args.GetList().reserve(reconnect_command_line.argv().size());
+ for (const auto& arg : reconnect_command_line.argv()) {
+ args.GetList().emplace_back(arg);
+ }
+ std::string encoded_reconnect_command;
+ bool success =
+ base::JSONWriter::Write(std::move(args), &encoded_reconnect_command);
+ DCHECK(success);
+ base::Base64Encode(encoded_reconnect_command, &encoded_reconnect_command);
+ command_line.AppendArg(
+ base::StrCat({"--reconnect-command=", encoded_reconnect_command}));
+ }
+
base::Process process;
base::File read_file;
base::File write_file;
@@ -246,9 +311,13 @@ void NativeProcessLauncherImpl::Core::PostResult(
NativeProcessLauncherImpl::NativeProcessLauncherImpl(
bool allow_user_level_hosts,
- intptr_t window_handle)
- : core_(new Core(allow_user_level_hosts, window_handle)) {
-}
+ intptr_t window_handle,
+ const base::FilePath& profile_directory,
+ bool require_native_initiated_connections)
+ : core_(new Core(allow_user_level_hosts,
+ window_handle,
+ profile_directory,
+ require_native_initiated_connections)) {}
NativeProcessLauncherImpl::~NativeProcessLauncherImpl() {
core_->Detach();
@@ -265,14 +334,17 @@ void NativeProcessLauncherImpl::Launch(const GURL& origin,
// static
std::unique_ptr<NativeProcessLauncher> NativeProcessLauncher::CreateDefault(
bool allow_user_level_hosts,
- gfx::NativeView native_view) {
+ gfx::NativeView native_view,
+ const base::FilePath& profile_directory,
+ bool require_native_initiated_connections) {
intptr_t window_handle = 0;
#if defined(OS_WIN)
window_handle = reinterpret_cast<intptr_t>(
views::HWNDForNativeView(native_view));
#endif
- return std::unique_ptr<NativeProcessLauncher>(
- new NativeProcessLauncherImpl(allow_user_level_hosts, window_handle));
+ return std::make_unique<NativeProcessLauncherImpl>(
+ allow_user_level_hosts, window_handle, profile_directory,
+ require_native_initiated_connections);
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h
index 8ebf09c3bd1..51102bc3247 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h
+++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h
@@ -42,10 +42,16 @@ class NativeProcessLauncher {
// Creates default launcher for the current OS. |native_view| refers to the
// window that contains calling page. Can be nullptr, e.g. for background
- // pages.
+ // pages. If |profile_directory| is non-empty and the host supports
+ // native-initiated connections, additional reconnect args will be passed to
+ // the host. If |require_native_initiated_connections| is true, the connection
+ // will be allowed only if the native messaging host sets
+ // "supports_native_initiated_connections" to true in its manifest.
static std::unique_ptr<NativeProcessLauncher> CreateDefault(
bool allow_user_level_hosts,
- gfx::NativeView native_view);
+ gfx::NativeView native_view,
+ const base::FilePath& profile_directory,
+ bool require_native_initiated_connections);
NativeProcessLauncher() {}
virtual ~NativeProcessLauncher() {}
diff --git a/chromium/chrome/browser/extensions/api/module/OWNERS b/chromium/chrome/browser/extensions/api/module/OWNERS
deleted file mode 100644
index c35595ced3f..00000000000
--- a/chromium/chrome/browser/extensions/api/module/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-asargent@chromium.org
diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc
index 50dee6a1a61..d8121216c4c 100644
--- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc
@@ -649,7 +649,7 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, CreateNetwork) {
IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest,
CreateNetworkForPolicyControlledNetwork) {
- const std::string user_policy_blob =
+ constexpr char kUserPolicyBlob[] =
R"({
"NetworkConfigurations": [{
"GUID": "stub_wifi2",
@@ -670,7 +670,7 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest,
policy.Set(policy::key::kOpenNetworkConfiguration,
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
policy::POLICY_SOURCE_CLOUD,
- base::WrapUnique(new base::Value(user_policy_blob)), nullptr);
+ std::make_unique<base::Value>(kUserPolicyBlob), nullptr);
provider_.UpdateChromePolicy(policy);
content::RunAllPendingInMessageLoop();
@@ -684,7 +684,7 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, ForgetNetwork) {
IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest,
ForgetPolicyControlledNetwork) {
- const std::string user_policy_blob =
+ constexpr char kUserPolicyBlob[] =
R"({
"NetworkConfigurations": [{
"GUID": "stub_wifi2",
@@ -705,7 +705,7 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest,
policy.Set(policy::key::kOpenNetworkConfiguration,
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
policy::POLICY_SOURCE_CLOUD,
- base::WrapUnique(new base::Value(user_policy_blob)), nullptr);
+ std::make_unique<base::Value>(kUserPolicyBlob), nullptr);
provider_.UpdateChromePolicy(policy);
content::RunAllPendingInMessageLoop();
@@ -715,14 +715,14 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest,
// TODO(stevenjb): Find a better way to set this up on Chrome OS.
IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, GetManagedProperties) {
- const std::string uidata_blob =
- "{ \"user_settings\": {"
- " \"WiFi\": {"
- " \"Passphrase\": \"FAKE_CREDENTIAL_VPaJDV9x\" }"
- " }"
- "}";
+ constexpr char kUidataBlob[] =
+ R"({
+ "user_settings": {
+ "WiFi": {"Passphrase": "FAKE_CREDENTIAL_VPaJDV9x"}
+ }
+ })";
service_test_->SetServiceProperty(kWifi2ServicePath, shill::kUIDataProperty,
- base::Value(uidata_blob));
+ base::Value(kUidataBlob));
service_test_->SetServiceProperty(
kWifi2ServicePath, shill::kAutoConnectProperty, base::Value(false));
@@ -731,27 +731,27 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, GetManagedProperties) {
content::RunAllPendingInMessageLoop();
- const std::string user_policy_blob =
- "{ \"NetworkConfigurations\": ["
- " { \"GUID\": \"stub_wifi2\","
- " \"Type\": \"WiFi\","
- " \"Name\": \"My WiFi Network\","
- " \"WiFi\": {"
- " \"HexSSID\": \"77696669325F50534B\"," // "wifi2_PSK"
- " \"Passphrase\": \"passphrase\","
- " \"Recommended\": [ \"AutoConnect\", \"Passphrase\" ],"
- " \"Security\": \"WPA-PSK\" }"
- " }"
- " ],"
- " \"Certificates\": [],"
- " \"Type\": \"UnencryptedConfiguration\""
- "}";
+ constexpr char kUserPolicyBlob[] = R"({
+ "NetworkConfigurations": [
+ { "GUID": "stub_wifi2",
+ "Type": "WiFi",
+ "Name": "My WiFi Network",
+ "WiFi": {
+ "HexSSID": "77696669325F50534B",
+ "Passphrase": "passphrase",
+ "Recommended": [ "AutoConnect", "Passphrase" ],
+ "Security": "WPA-PSK" }
+ }
+ ],
+ "Certificates": [],
+ "Type": "UnencryptedConfiguration"
+ })";
policy::PolicyMap policy;
policy.Set(policy::key::kOpenNetworkConfiguration,
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER,
policy::POLICY_SOURCE_CLOUD,
- base::WrapUnique(new base::Value(user_policy_blob)), nullptr);
+ std::make_unique<base::Value>(kUserPolicyBlob), nullptr);
provider_.UpdateChromePolicy(policy);
content::RunAllPendingInMessageLoop();
diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc
index 45ea9511897..752316e49f8 100644
--- a/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc
+++ b/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc
@@ -603,11 +603,6 @@ bool NotificationsCreateFunction::RunNotificationsApi() {
SetResult(std::make_unique<base::Value>(notification_id));
- // TODO(crbug.com/749402): Cap the length of notification Ids to a certain
- // limit if the histogram indicates that this is safe to do.
- UMA_HISTOGRAM_COUNTS_1000("Notifications.ExtensionNotificationIdLength",
- notification_id.size());
-
// TODO(dewittj): Add more human-readable error strings if this fails.
if (!CreateNotification(notification_id, &params_->options))
return false;
diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc
index 599e8ca921d..4826ad17a57 100644
--- a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc
@@ -205,9 +205,11 @@ class NotificationsApiTest : public extensions::ExtensionApiTest {
}
void LaunchPlatformApp(const Extension* extension) {
- OpenApplication(AppLaunchParams(
- browser()->profile(), extension, extensions::LAUNCH_CONTAINER_NONE,
- WindowOpenDisposition::NEW_WINDOW, extensions::SOURCE_TEST));
+ OpenApplication(
+ AppLaunchParams(browser()->profile(), extension->id(),
+ extensions::LaunchContainer::kLaunchContainerNone,
+ WindowOpenDisposition::NEW_WINDOW,
+ extensions::AppLaunchSource::kSourceTest));
}
std::unique_ptr<NotificationDisplayServiceTester> display_service_tester_;
diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_browsertest.cc b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_browsertest.cc
deleted file mode 100644
index 81cd15237b5..00000000000
--- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_browsertest.cc
+++ /dev/null
@@ -1,261 +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 "base/strings/string16.h"
-#include "base/strings/utf_string_conversions.h"
-#include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
-#include "chrome/browser/extensions/api/omnibox/omnibox_api_testbase.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/search_engines/template_url_service_factory.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/browser/ui/location_bar/location_bar.h"
-#include "chrome/test/base/search_test_utils.h"
-#include "components/omnibox/browser/autocomplete_controller.h"
-#include "components/omnibox/browser/autocomplete_input.h"
-#include "components/omnibox/browser/autocomplete_match.h"
-#include "components/omnibox/browser/autocomplete_result.h"
-#include "components/omnibox/browser/omnibox_view.h"
-#include "extensions/test/result_catcher.h"
-#include "third_party/metrics_proto/omnibox_event.pb.h"
-#include "ui/base/window_open_disposition.h"
-
-using base::ASCIIToUTF16;
-using extensions::ResultCatcher;
-using metrics::OmniboxEventProto;
-
-// http://crbug.com/167158
-IN_PROC_BROWSER_TEST_F(OmniboxApiTest, DISABLED_Basic) {
- ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
-
- // The results depend on the TemplateURLService being loaded. Make sure it is
- // loaded so that the autocomplete results are consistent.
- Profile* profile = browser()->profile();
- search_test_utils::WaitForTemplateURLServiceToLoad(
- TemplateURLServiceFactory::GetForProfile(profile));
-
- AutocompleteController* autocomplete_controller =
- GetAutocompleteController(browser());
-
- // Test that our extension's keyword is suggested to us when we partially type
- // it.
- {
- AutocompleteInput input(ASCIIToUTF16("keywor"),
- metrics::OmniboxEventProto::NTP,
- ChromeAutocompleteSchemeClassifier(profile));
- autocomplete_controller->Start(input);
- WaitForAutocompleteDone(autocomplete_controller);
- EXPECT_TRUE(autocomplete_controller->done());
-
- // Now, peek into the controller to see if it has the results we expect.
- // First result should be to search for what was typed, second should be to
- // enter "extension keyword" mode.
- const AutocompleteResult& result = autocomplete_controller->result();
- ASSERT_EQ(2U, result.size()) << AutocompleteResultAsString(result);
- AutocompleteMatch match = result.match_at(0);
- EXPECT_EQ(AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, match.type);
- EXPECT_FALSE(match.deletable);
-
- match = result.match_at(1);
- EXPECT_EQ(ASCIIToUTF16("kw"), match.keyword);
- }
-
- // Test that our extension can send suggestions back to us.
- {
- AutocompleteInput input(ASCIIToUTF16("kw suggestio"),
- metrics::OmniboxEventProto::NTP,
- ChromeAutocompleteSchemeClassifier(profile));
- autocomplete_controller->Start(input);
- WaitForAutocompleteDone(autocomplete_controller);
- EXPECT_TRUE(autocomplete_controller->done());
-
- // Now, peek into the controller to see if it has the results we expect.
- // First result should be to invoke the keyword with what we typed, 2-4
- // should be to invoke with suggestions from the extension, and the last
- // should be to search for what we typed.
- const AutocompleteResult& result = autocomplete_controller->result();
- ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);
-
- EXPECT_EQ(ASCIIToUTF16("kw"), result.match_at(0).keyword);
- EXPECT_EQ(ASCIIToUTF16("kw suggestio"), result.match_at(0).fill_into_edit);
- EXPECT_EQ(AutocompleteMatchType::SEARCH_OTHER_ENGINE,
- result.match_at(0).type);
- EXPECT_EQ(AutocompleteProvider::TYPE_KEYWORD,
- result.match_at(0).provider->type());
- EXPECT_EQ(ASCIIToUTF16("kw"), result.match_at(1).keyword);
- EXPECT_EQ(ASCIIToUTF16("kw suggestion1"),
- result.match_at(1).fill_into_edit);
- EXPECT_EQ(AutocompleteProvider::TYPE_KEYWORD,
- result.match_at(1).provider->type());
- EXPECT_EQ(ASCIIToUTF16("kw"), result.match_at(2).keyword);
- EXPECT_EQ(ASCIIToUTF16("kw suggestion2"),
- result.match_at(2).fill_into_edit);
- EXPECT_EQ(AutocompleteProvider::TYPE_KEYWORD,
- result.match_at(2).provider->type());
- EXPECT_EQ(ASCIIToUTF16("kw"), result.match_at(3).keyword);
- EXPECT_EQ(ASCIIToUTF16("kw suggestion3"),
- result.match_at(3).fill_into_edit);
- EXPECT_EQ(AutocompleteProvider::TYPE_KEYWORD,
- result.match_at(3).provider->type());
-
- base::string16 description =
- ASCIIToUTF16("Description with style: <match>, [dim], (url till end)");
- EXPECT_EQ(description, result.match_at(1).contents);
- ASSERT_EQ(6u, result.match_at(1).contents_class.size());
-
- EXPECT_EQ(0u,
- result.match_at(1).contents_class[0].offset);
- EXPECT_EQ(ACMatchClassification::NONE,
- result.match_at(1).contents_class[0].style);
-
- EXPECT_EQ(description.find('<'),
- result.match_at(1).contents_class[1].offset);
- EXPECT_EQ(ACMatchClassification::MATCH,
- result.match_at(1).contents_class[1].style);
-
- EXPECT_EQ(description.find('>') + 1u,
- result.match_at(1).contents_class[2].offset);
- EXPECT_EQ(ACMatchClassification::NONE,
- result.match_at(1).contents_class[2].style);
-
- EXPECT_EQ(description.find('['),
- result.match_at(1).contents_class[3].offset);
- EXPECT_EQ(ACMatchClassification::DIM,
- result.match_at(1).contents_class[3].style);
-
- EXPECT_EQ(description.find(']') + 1u,
- result.match_at(1).contents_class[4].offset);
- EXPECT_EQ(ACMatchClassification::NONE,
- result.match_at(1).contents_class[4].style);
-
- EXPECT_EQ(description.find('('),
- result.match_at(1).contents_class[5].offset);
- EXPECT_EQ(ACMatchClassification::URL,
- result.match_at(1).contents_class[5].style);
-
- AutocompleteMatch match = result.match_at(4);
- EXPECT_EQ(AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, match.type);
- EXPECT_EQ(AutocompleteProvider::TYPE_SEARCH,
- result.match_at(4).provider->type());
- EXPECT_FALSE(match.deletable);
- }
-
- // Flaky, see http://crbug.com/167158
- /*
- {
- LocationBar* location_bar = GetLocationBar(browser());
- ResultCatcher catcher;
- OmniboxView* omnibox_view = location_bar->GetOmniboxView();
- omnibox_view->OnBeforePossibleChange();
- omnibox_view->SetUserText(ASCIIToUTF16("kw command"));
- omnibox_view->OnAfterPossibleChange(true);
- location_bar->AcceptInput();
- // This checks that the keyword provider (via javascript)
- // gets told to navigate to the string "command".
- EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
- }
- */
-}
-
-IN_PROC_BROWSER_TEST_F(OmniboxApiTest, OnInputEntered) {
- ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
- Profile* profile = browser()->profile();
- search_test_utils::WaitForTemplateURLServiceToLoad(
- TemplateURLServiceFactory::GetForProfile(profile));
-
- LocationBar* location_bar = GetLocationBar(browser());
- OmniboxView* omnibox_view = location_bar->GetOmniboxView();
- ResultCatcher catcher;
- AutocompleteController* autocomplete_controller =
- GetAutocompleteController(browser());
- omnibox_view->OnBeforePossibleChange();
- omnibox_view->SetUserText(ASCIIToUTF16("kw command"));
- omnibox_view->OnAfterPossibleChange(true);
-
- {
- AutocompleteInput input(ASCIIToUTF16("kw command"),
- metrics::OmniboxEventProto::NTP,
- ChromeAutocompleteSchemeClassifier(profile));
- autocomplete_controller->Start(input);
- }
- omnibox_view->model()->AcceptInput(WindowOpenDisposition::CURRENT_TAB, false);
- WaitForAutocompleteDone(autocomplete_controller);
- EXPECT_TRUE(autocomplete_controller->done());
- EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
-
- omnibox_view->OnBeforePossibleChange();
- omnibox_view->SetUserText(ASCIIToUTF16("kw newtab"));
- omnibox_view->OnAfterPossibleChange(true);
- WaitForAutocompleteDone(autocomplete_controller);
- EXPECT_TRUE(autocomplete_controller->done());
-
- {
- AutocompleteInput input(ASCIIToUTF16("kw newtab"),
- metrics::OmniboxEventProto::NTP,
- ChromeAutocompleteSchemeClassifier(profile));
- autocomplete_controller->Start(input);
- }
- omnibox_view->model()->AcceptInput(WindowOpenDisposition::NEW_FOREGROUND_TAB,
- false);
- WaitForAutocompleteDone(autocomplete_controller);
- EXPECT_TRUE(autocomplete_controller->done());
- EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
-}
-
-// Tests that we get suggestions from and send input to the incognito context
-// of an incognito split mode extension.
-// http://crbug.com/100927
-// Test is flaky: http://crbug.com/101219
-IN_PROC_BROWSER_TEST_F(OmniboxApiTest, DISABLED_IncognitoSplitMode) {
- Profile* profile = browser()->profile();
- ResultCatcher catcher_incognito;
- catcher_incognito.RestrictToBrowserContext(profile->GetOffTheRecordProfile());
-
- ASSERT_TRUE(RunExtensionTestIncognito("omnibox")) << message_;
-
- // Open an incognito window and wait for the incognito extension process to
- // respond.
- Browser* incognito_browser = CreateIncognitoBrowser();
- ASSERT_TRUE(catcher_incognito.GetNextResult()) << catcher_incognito.message();
-
- // The results depend on the TemplateURLService being loaded. Make sure it is
- // loaded so that the autocomplete results are consistent.
- search_test_utils::WaitForTemplateURLServiceToLoad(
- TemplateURLServiceFactory::GetForProfile(browser()->profile()));
-
- LocationBar* location_bar = GetLocationBar(incognito_browser);
- AutocompleteController* autocomplete_controller =
- GetAutocompleteController(incognito_browser);
-
- // Test that we get the incognito-specific suggestions.
- {
- AutocompleteInput input(ASCIIToUTF16("kw suggestio"),
- metrics::OmniboxEventProto::NTP,
- ChromeAutocompleteSchemeClassifier(profile));
- autocomplete_controller->Start(input);
- WaitForAutocompleteDone(autocomplete_controller);
- EXPECT_TRUE(autocomplete_controller->done());
-
- // First result should be to invoke the keyword with what we typed, 2-4
- // should be to invoke with suggestions from the extension, and the last
- // should be to search for what we typed.
- const AutocompleteResult& result = autocomplete_controller->result();
- ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);
- ASSERT_FALSE(result.match_at(0).keyword.empty());
- EXPECT_EQ(ASCIIToUTF16("kw suggestion3 incognito"),
- result.match_at(3).fill_into_edit);
- }
-
- // Test that our input is sent to the incognito context. The test will do a
- // text comparison and succeed only if "command incognito" is sent to the
- // incognito context.
- {
- ResultCatcher catcher;
- AutocompleteInput input(ASCIIToUTF16("kw command incognito"),
- metrics::OmniboxEventProto::NTP,
- ChromeAutocompleteSchemeClassifier(profile));
- autocomplete_controller->Start(input);
- location_bar->AcceptInput();
- EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
- }
-}
diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_interactive_test.cc b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_interactive_test.cc
index c45a45ca66e..87a86d9ce2d 100644
--- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_interactive_test.cc
+++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_interactive_test.cc
@@ -2,21 +2,44 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include "base/format_macros.h"
+#include "base/strings/string16.h"
+#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
-#include "chrome/browser/extensions/api/omnibox/omnibox_api_testbase.h"
+#include "chrome/browser/chrome_notification_types.h"
+#include "chrome/browser/extensions/extension_apitest.h"
+#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
+#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
+#include "chrome/browser/ui/browser_window.h"
+#include "chrome/browser/ui/location_bar/location_bar.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/search_test_utils.h"
+#include "chrome/test/base/ui_test_utils.h"
+#include "components/omnibox/browser/autocomplete_controller.h"
+#include "components/omnibox/browser/autocomplete_input.h"
+#include "components/omnibox/browser/autocomplete_match.h"
+#include "components/omnibox/browser/autocomplete_result.h"
+#include "components/omnibox/browser/omnibox_controller_emitter.h"
+#include "components/omnibox/browser/omnibox_popup_model.h"
+#include "components/omnibox/browser/omnibox_view.h"
+#include "content/public/test/test_utils.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
#include "third_party/metrics_proto/omnibox_event.pb.h"
+#include "ui/base/window_open_disposition.h"
namespace {
+using base::ASCIIToUTF16;
+using extensions::ResultCatcher;
+using metrics::OmniboxEventProto;
+using ui_test_utils::WaitForAutocompleteDone;
+
void InputKeys(Browser* browser, const std::vector<ui::KeyboardCode>& keys) {
for (auto key : keys) {
// Note that sending key presses can be flaky at times.
@@ -25,8 +48,267 @@ void InputKeys(Browser* browser, const std::vector<ui::KeyboardCode>& keys) {
}
}
+LocationBar* GetLocationBar(Browser* browser) {
+ return browser->window()->GetLocationBar();
+}
+
+AutocompleteController* GetAutocompleteController(Browser* browser) {
+ return GetLocationBar(browser)
+ ->GetOmniboxView()
+ ->model()
+ ->autocomplete_controller();
+}
+
+base::string16 AutocompleteResultAsString(const AutocompleteResult& result) {
+ std::string output(base::StringPrintf("{%" PRIuS "} ", result.size()));
+ for (size_t i = 0; i < result.size(); ++i) {
+ AutocompleteMatch match = result.match_at(i);
+ std::string provider_name = match.provider->GetName();
+ output.append(base::StringPrintf("[\"%s\" by \"%s\"] ",
+ base::UTF16ToUTF8(match.contents).c_str(),
+ provider_name.c_str()));
+ }
+ return base::UTF8ToUTF16(output);
+}
+
+using OmniboxApiTest = extensions::ExtensionApiTest;
+
} // namespace
+// http://crbug.com/167158
+IN_PROC_BROWSER_TEST_F(OmniboxApiTest, DISABLED_Basic) {
+ ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
+
+ // The results depend on the TemplateURLService being loaded. Make sure it is
+ // loaded so that the autocomplete results are consistent.
+ Profile* profile = browser()->profile();
+ search_test_utils::WaitForTemplateURLServiceToLoad(
+ TemplateURLServiceFactory::GetForProfile(profile));
+
+ AutocompleteController* autocomplete_controller =
+ GetAutocompleteController(browser());
+
+ // Test that our extension's keyword is suggested to us when we partially type
+ // it.
+ {
+ AutocompleteInput input(ASCIIToUTF16("keywor"),
+ metrics::OmniboxEventProto::NTP,
+ ChromeAutocompleteSchemeClassifier(profile));
+ autocomplete_controller->Start(input);
+ WaitForAutocompleteDone(browser());
+ EXPECT_TRUE(autocomplete_controller->done());
+
+ // Now, peek into the controller to see if it has the results we expect.
+ // First result should be to search for what was typed, second should be to
+ // enter "extension keyword" mode.
+ const AutocompleteResult& result = autocomplete_controller->result();
+ ASSERT_EQ(2U, result.size()) << AutocompleteResultAsString(result);
+ AutocompleteMatch match = result.match_at(0);
+ EXPECT_EQ(AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, match.type);
+ EXPECT_FALSE(match.deletable);
+
+ match = result.match_at(1);
+ EXPECT_EQ(ASCIIToUTF16("kw"), match.keyword);
+ }
+
+ // Test that our extension can send suggestions back to us.
+ {
+ AutocompleteInput input(ASCIIToUTF16("kw suggestio"),
+ metrics::OmniboxEventProto::NTP,
+ ChromeAutocompleteSchemeClassifier(profile));
+ autocomplete_controller->Start(input);
+ WaitForAutocompleteDone(browser());
+ EXPECT_TRUE(autocomplete_controller->done());
+
+ // Now, peek into the controller to see if it has the results we expect.
+ // First result should be to invoke the keyword with what we typed, 2-4
+ // should be to invoke with suggestions from the extension, and the last
+ // should be to search for what we typed.
+ const AutocompleteResult& result = autocomplete_controller->result();
+ ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);
+
+ EXPECT_EQ(ASCIIToUTF16("kw"), result.match_at(0).keyword);
+ EXPECT_EQ(ASCIIToUTF16("kw suggestio"), result.match_at(0).fill_into_edit);
+ EXPECT_EQ(AutocompleteMatchType::SEARCH_OTHER_ENGINE,
+ result.match_at(0).type);
+ EXPECT_EQ(AutocompleteProvider::TYPE_KEYWORD,
+ result.match_at(0).provider->type());
+ EXPECT_EQ(ASCIIToUTF16("kw"), result.match_at(1).keyword);
+ EXPECT_EQ(ASCIIToUTF16("kw suggestion1"),
+ result.match_at(1).fill_into_edit);
+ EXPECT_EQ(AutocompleteProvider::TYPE_KEYWORD,
+ result.match_at(1).provider->type());
+ EXPECT_EQ(ASCIIToUTF16("kw"), result.match_at(2).keyword);
+ EXPECT_EQ(ASCIIToUTF16("kw suggestion2"),
+ result.match_at(2).fill_into_edit);
+ EXPECT_EQ(AutocompleteProvider::TYPE_KEYWORD,
+ result.match_at(2).provider->type());
+ EXPECT_EQ(ASCIIToUTF16("kw"), result.match_at(3).keyword);
+ EXPECT_EQ(ASCIIToUTF16("kw suggestion3"),
+ result.match_at(3).fill_into_edit);
+ EXPECT_EQ(AutocompleteProvider::TYPE_KEYWORD,
+ result.match_at(3).provider->type());
+
+ base::string16 description =
+ ASCIIToUTF16("Description with style: <match>, [dim], (url till end)");
+ EXPECT_EQ(description, result.match_at(1).contents);
+ ASSERT_EQ(6u, result.match_at(1).contents_class.size());
+
+ EXPECT_EQ(0u, result.match_at(1).contents_class[0].offset);
+ EXPECT_EQ(ACMatchClassification::NONE,
+ result.match_at(1).contents_class[0].style);
+
+ EXPECT_EQ(description.find('<'),
+ result.match_at(1).contents_class[1].offset);
+ EXPECT_EQ(ACMatchClassification::MATCH,
+ result.match_at(1).contents_class[1].style);
+
+ EXPECT_EQ(description.find('>') + 1u,
+ result.match_at(1).contents_class[2].offset);
+ EXPECT_EQ(ACMatchClassification::NONE,
+ result.match_at(1).contents_class[2].style);
+
+ EXPECT_EQ(description.find('['),
+ result.match_at(1).contents_class[3].offset);
+ EXPECT_EQ(ACMatchClassification::DIM,
+ result.match_at(1).contents_class[3].style);
+
+ EXPECT_EQ(description.find(']') + 1u,
+ result.match_at(1).contents_class[4].offset);
+ EXPECT_EQ(ACMatchClassification::NONE,
+ result.match_at(1).contents_class[4].style);
+
+ EXPECT_EQ(description.find('('),
+ result.match_at(1).contents_class[5].offset);
+ EXPECT_EQ(ACMatchClassification::URL,
+ result.match_at(1).contents_class[5].style);
+
+ AutocompleteMatch match = result.match_at(4);
+ EXPECT_EQ(AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED, match.type);
+ EXPECT_EQ(AutocompleteProvider::TYPE_SEARCH,
+ result.match_at(4).provider->type());
+ EXPECT_FALSE(match.deletable);
+ }
+
+ // Flaky, see http://crbug.com/167158
+ /*
+ {
+ LocationBar* location_bar = GetLocationBar(browser());
+ ResultCatcher catcher;
+ OmniboxView* omnibox_view = location_bar->GetOmniboxView();
+ omnibox_view->OnBeforePossibleChange();
+ omnibox_view->SetUserText(ASCIIToUTF16("kw command"));
+ omnibox_view->OnAfterPossibleChange(true);
+ location_bar->AcceptInput();
+ // This checks that the keyword provider (via javascript)
+ // gets told to navigate to the string "command".
+ EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
+ }
+ */
+}
+
+IN_PROC_BROWSER_TEST_F(OmniboxApiTest, OnInputEntered) {
+ ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
+ Profile* profile = browser()->profile();
+ search_test_utils::WaitForTemplateURLServiceToLoad(
+ TemplateURLServiceFactory::GetForProfile(profile));
+
+ LocationBar* location_bar = GetLocationBar(browser());
+ OmniboxView* omnibox_view = location_bar->GetOmniboxView();
+ ResultCatcher catcher;
+ AutocompleteController* autocomplete_controller =
+ GetAutocompleteController(browser());
+ omnibox_view->OnBeforePossibleChange();
+ omnibox_view->SetUserText(ASCIIToUTF16("kw command"));
+ omnibox_view->OnAfterPossibleChange(true);
+
+ {
+ AutocompleteInput input(ASCIIToUTF16("kw command"),
+ metrics::OmniboxEventProto::NTP,
+ ChromeAutocompleteSchemeClassifier(profile));
+ autocomplete_controller->Start(input);
+ }
+ omnibox_view->model()->AcceptInput(WindowOpenDisposition::CURRENT_TAB);
+ WaitForAutocompleteDone(browser());
+ EXPECT_TRUE(autocomplete_controller->done());
+ EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
+
+ omnibox_view->OnBeforePossibleChange();
+ omnibox_view->SetUserText(ASCIIToUTF16("kw newtab"));
+ omnibox_view->OnAfterPossibleChange(true);
+ WaitForAutocompleteDone(browser());
+ EXPECT_TRUE(autocomplete_controller->done());
+
+ {
+ AutocompleteInput input(ASCIIToUTF16("kw newtab"),
+ metrics::OmniboxEventProto::NTP,
+ ChromeAutocompleteSchemeClassifier(profile));
+ autocomplete_controller->Start(input);
+ }
+ omnibox_view->model()->AcceptInput(WindowOpenDisposition::NEW_FOREGROUND_TAB);
+ WaitForAutocompleteDone(browser());
+ EXPECT_TRUE(autocomplete_controller->done());
+ EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
+}
+
+// Tests that we get suggestions from and send input to the incognito context
+// of an incognito split mode extension.
+// http://crbug.com/100927
+// Test is flaky: http://crbug.com/101219
+IN_PROC_BROWSER_TEST_F(OmniboxApiTest, DISABLED_IncognitoSplitMode) {
+ Profile* profile = browser()->profile();
+ ResultCatcher catcher_incognito;
+ catcher_incognito.RestrictToBrowserContext(profile->GetOffTheRecordProfile());
+
+ ASSERT_TRUE(RunExtensionTestIncognito("omnibox")) << message_;
+
+ // Open an incognito window and wait for the incognito extension process to
+ // respond.
+ Browser* incognito_browser = CreateIncognitoBrowser();
+ ASSERT_TRUE(catcher_incognito.GetNextResult()) << catcher_incognito.message();
+
+ // The results depend on the TemplateURLService being loaded. Make sure it is
+ // loaded so that the autocomplete results are consistent.
+ search_test_utils::WaitForTemplateURLServiceToLoad(
+ TemplateURLServiceFactory::GetForProfile(browser()->profile()));
+
+ LocationBar* location_bar = GetLocationBar(incognito_browser);
+ AutocompleteController* autocomplete_controller =
+ GetAutocompleteController(incognito_browser);
+
+ // Test that we get the incognito-specific suggestions.
+ {
+ AutocompleteInput input(ASCIIToUTF16("kw suggestio"),
+ metrics::OmniboxEventProto::NTP,
+ ChromeAutocompleteSchemeClassifier(profile));
+ autocomplete_controller->Start(input);
+ WaitForAutocompleteDone(browser());
+ EXPECT_TRUE(autocomplete_controller->done());
+
+ // First result should be to invoke the keyword with what we typed, 2-4
+ // should be to invoke with suggestions from the extension, and the last
+ // should be to search for what we typed.
+ const AutocompleteResult& result = autocomplete_controller->result();
+ ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);
+ ASSERT_FALSE(result.match_at(0).keyword.empty());
+ EXPECT_EQ(ASCIIToUTF16("kw suggestion3 incognito"),
+ result.match_at(3).fill_into_edit);
+ }
+
+ // Test that our input is sent to the incognito context. The test will do a
+ // text comparison and succeed only if "command incognito" is sent to the
+ // incognito context.
+ {
+ ResultCatcher catcher;
+ AutocompleteInput input(ASCIIToUTF16("kw command incognito"),
+ metrics::OmniboxEventProto::NTP,
+ ChromeAutocompleteSchemeClassifier(profile));
+ autocomplete_controller->Start(input);
+ location_bar->AcceptInput();
+ EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
+ }
+}
+
// Tests that the autocomplete popup doesn't reopen after accepting input for
// a given query.
// http://crbug.com/88552
@@ -49,7 +331,7 @@ IN_PROC_BROWSER_TEST_F(OmniboxApiTest, PopupStaysClosed) {
omnibox_view->OnBeforePossibleChange();
omnibox_view->SetUserText(base::ASCIIToUTF16("kw comman"));
omnibox_view->OnAfterPossibleChange(true);
- WaitForAutocompleteDone(autocomplete_controller);
+ WaitForAutocompleteDone(browser());
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(popup_model->IsOpen());
@@ -66,7 +348,7 @@ IN_PROC_BROWSER_TEST_F(OmniboxApiTest, PopupStaysClosed) {
ChromeAutocompleteSchemeClassifier(profile));
autocomplete_controller->Start(input);
location_bar->AcceptInput();
- WaitForAutocompleteDone(autocomplete_controller);
+ WaitForAutocompleteDone(browser());
EXPECT_TRUE(autocomplete_controller->done());
// This checks that the keyword provider (via javascript)
// gets told to navigate to the string "command".
@@ -100,7 +382,7 @@ IN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_DeleteOmniboxSuggestionResult) {
// Input a keyword query and wait for suggestions from the extension.
InputKeys(browser(), {ui::VKEY_K, ui::VKEY_W, ui::VKEY_SPACE, ui::VKEY_D});
- WaitForAutocompleteDone(autocomplete_controller);
+ WaitForAutocompleteDone(browser());
EXPECT_TRUE(autocomplete_controller->done());
// Peek into the controller to see if it has the results we expect.
@@ -172,7 +454,7 @@ IN_PROC_BROWSER_TEST_F(OmniboxApiTest, ExtensionSuggestionsOnlyInKeywordMode) {
// Input a keyword query and wait for suggestions from the extension.
InputKeys(browser(), {ui::VKEY_K, ui::VKEY_W, ui::VKEY_SPACE, ui::VKEY_D});
- WaitForAutocompleteDone(autocomplete_controller);
+ WaitForAutocompleteDone(browser());
EXPECT_TRUE(autocomplete_controller->done());
// Peek into the controller to see if it has the results we expect.
@@ -209,7 +491,7 @@ IN_PROC_BROWSER_TEST_F(OmniboxApiTest, ExtensionSuggestionsOnlyInKeywordMode) {
InputKeys(browser(), {ui::VKEY_K, ui::VKEY_W, ui::VKEY_SPACE, ui::VKEY_BACK,
ui::VKEY_D});
- WaitForAutocompleteDone(autocomplete_controller);
+ WaitForAutocompleteDone(browser());
EXPECT_TRUE(autocomplete_controller->done());
// Peek into the controller to see if it has the results we expect. Since
diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_testbase.h b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_testbase.h
deleted file mode 100644
index 8d0f6846850..00000000000
--- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_testbase.h
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright (c) 2013 The Chromium 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_EXTENSIONS_API_OMNIBOX_OMNIBOX_API_TESTBASE_H_
-#define CHROME_BROWSER_EXTENSIONS_API_OMNIBOX_OMNIBOX_API_TESTBASE_H_
-
-#include <stddef.h>
-
-#include "base/format_macros.h"
-#include "base/strings/stringprintf.h"
-#include "base/strings/utf_string_conversions.h"
-#include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/extensions/extension_apitest.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/browser/ui/browser_window.h"
-#include "chrome/browser/ui/location_bar/location_bar.h"
-#include "components/omnibox/browser/autocomplete_match.h"
-#include "components/omnibox/browser/autocomplete_result.h"
-#include "components/omnibox/browser/omnibox_popup_model.h"
-#include "components/omnibox/browser/omnibox_view.h"
-#include "content/public/test/test_utils.h"
-
-class AutocompleteController;
-
-class OmniboxApiTest : public extensions::ExtensionApiTest {
- protected:
- LocationBar* GetLocationBar(Browser* browser) const {
- return browser->window()->GetLocationBar();
- }
-
- AutocompleteController* GetAutocompleteController(Browser* browser) const {
- return GetLocationBar(browser)->GetOmniboxView()->model()->popup_model()->
- autocomplete_controller();
- }
-
- // TODO(phajdan.jr): Get rid of this wait-in-a-loop pattern.
- void WaitForAutocompleteDone(AutocompleteController* controller) {
- while (!controller->done()) {
- content::WindowedNotificationObserver ready_observer(
- chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY,
- content::Source<AutocompleteController>(controller));
- ready_observer.Wait();
- }
- }
-
- static base::string16 AutocompleteResultAsString(
- const AutocompleteResult& result) {
- std::string output(base::StringPrintf("{%" PRIuS "} ", result.size()));
- for (size_t i = 0; i < result.size(); ++i) {
- AutocompleteMatch match = result.match_at(i);
- std::string provider_name = match.provider->GetName();
- output.append(
- base::StringPrintf("[\"%s\" by \"%s\"] ",
- base::UTF16ToUTF8(match.contents).c_str(),
- provider_name.c_str()));
- }
- return base::UTF8ToUTF16(output);
- }
-};
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_OMNIBOX_OMNIBOX_API_TESTBASE_H_
diff --git a/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.cc b/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.cc
index 0d7ad81a62c..1d92faec7e4 100644
--- a/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.cc
+++ b/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.cc
@@ -26,6 +26,7 @@
#include "content/public/browser/web_contents.h"
#include "content/public/common/mhtml_generation_params.h"
#include "extensions/common/extension_messages.h"
+#include "extensions/common/permissions/permissions_data.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/extensions/public_session_permission_helper.h"
diff --git a/chromium/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc b/chromium/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc
index cba0bb4c606..4041ed42e28 100644
--- a/chromium/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/page_capture/page_capture_apitest.cc
@@ -65,7 +65,18 @@ class PageCaptureSaveAsMHTMLDelegate
base::FilePath temp_file_;
};
-IN_PROC_BROWSER_TEST_F(ExtensionPageCaptureApiTest, SaveAsMHTML) {
+// TODO(crbug.com/961017): Fix memory leaks in tests and re-enable on LSAN.
+#ifdef LEAK_SANITIZER
+#define MAYBE_SaveAsMHTML DISABLED_SaveAsMHTML
+#define MAYBE_SaveAsMHTMLWithActiveTabWithFileAccess \
+ DISABLED_SaveAsMHTMLWithActiveTabWithFileAccess
+#else
+#define MAYBE_SaveAsMHTML SaveAsMHTML
+#define MAYBE_SaveAsMHTMLWithActiveTabWithFileAccess \
+ SaveAsMHTMLWithActiveTabWithFileAccess
+#endif
+
+IN_PROC_BROWSER_TEST_F(ExtensionPageCaptureApiTest, MAYBE_SaveAsMHTML) {
ASSERT_TRUE(StartEmbeddedTestServer());
PageCaptureSaveAsMHTMLDelegate delegate;
ASSERT_TRUE(RunExtensionTestWithFlagsAndArg(
@@ -83,7 +94,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionPageCaptureApiTest, SaveAsMHTML) {
}
IN_PROC_BROWSER_TEST_F(ExtensionPageCaptureApiTest,
- SaveAsMHTMLWithActiveTabWithFileAccess) {
+ MAYBE_SaveAsMHTMLWithActiveTabWithFileAccess) {
ASSERT_TRUE(StartEmbeddedTestServer());
PageCaptureSaveAsMHTMLDelegate delegate;
ASSERT_TRUE(RunExtensionTest("page_capture")) << message_;
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc
index 524ae75a6b3..f07d7d273b8 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc
+++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc
@@ -35,6 +35,9 @@
#include "chrome/browser/chromeos/login/quick_unlock/auth_token.h"
#include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_factory.h"
#include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_storage.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#include "chromeos/login/auth/password_visibility_utils.h"
+#include "components/user_manager/user.h"
#endif
namespace {
@@ -217,6 +220,13 @@ bool PasswordsPrivateDelegateImpl::OsReauthCall(
#elif defined(OS_MACOSX)
return password_manager_util_mac::AuthenticateUser(purpose);
#elif defined(OS_CHROMEOS)
+ const bool user_cannot_manually_enter_password =
+ !chromeos::password_visibility::AccountHasUserFacingPassword(
+ chromeos::ProfileHelper::Get()
+ ->GetUserByProfile(profile_)
+ ->GetAccountId());
+ if (user_cannot_manually_enter_password)
+ return true;
chromeos::quick_unlock::QuickUnlockStorage* quick_unlock_storage =
chromeos::quick_unlock::QuickUnlockFactory::GetForProfile(profile_);
const chromeos::quick_unlock::AuthToken* auth_token =
diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc b/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc
index 4a2b0dfcc5b..e762b4a7776 100644
--- a/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc
@@ -21,6 +21,7 @@
#include "extensions/browser/test_extension_registry_observer.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/manifest_handlers/permissions_parser.h"
+#include "extensions/common/permissions/permissions_data.h"
#include "extensions/test/test_extension_dir.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc b/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc
index 09b9b975cee..d05673e9883 100644
--- a/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc
+++ b/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc
@@ -180,7 +180,7 @@ void VerifyTrustAPI::IOPart::Verify(std::unique_ptr<Params> params,
return;
}
- if (!base::ContainsKey(extension_to_verifier_, extension_id)) {
+ if (!base::Contains(extension_to_verifier_, extension_id)) {
extension_to_verifier_[extension_id] =
net::CertVerifier::CreateDefault(/*cert_net_fetcher=*/nullptr);
}
diff --git a/chromium/chrome/browser/extensions/api/preference/preference_api.cc b/chromium/chrome/browser/extensions/api/preference/preference_api.cc
index 346eeb905d5..d8d88361618 100644
--- a/chromium/chrome/browser/extensions/api/preference/preference_api.cc
+++ b/chromium/chrome/browser/extensions/api/preference/preference_api.cc
@@ -309,7 +309,7 @@ class PrefMapping {
void RegisterPrefTransformer(
const std::string& browser_pref,
std::unique_ptr<PrefTransformerInterface> transformer) {
- DCHECK(!base::ContainsKey(transformers_, browser_pref))
+ DCHECK(!base::Contains(transformers_, browser_pref))
<< "Trying to register pref transformer for " << browser_pref
<< " twice";
transformers_[browser_pref] = std::move(transformer);
diff --git a/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.cc b/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.cc
index ab229e48872..6c5eba36e8d 100644
--- a/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.cc
@@ -20,7 +20,10 @@
#if BUILDFLAG(ENABLE_PDF)
#include "pdf/pdf_features.h"
-#endif
+#if defined(OS_CHROMEOS)
+#include "chrome/browser/chromeos/login/ui/login_display_host.h"
+#endif // defined(OS_CHROMEOS)
+#endif // BUILDFLAG(ENABLE_PDF)
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
#include "chrome/common/chrome_features.h"
@@ -125,7 +128,14 @@ void AddAdditionalDataForPdf(base::DictionaryValue* dict) {
dict->SetKey("pdfAnnotationsEnabled",
base::Value(base::FeatureList::IsEnabled(
chrome_pdf::features::kPDFAnnotations)));
-#endif
+
+ bool enable_printing = true;
+#if defined(OS_CHROMEOS)
+ // For Chrome OS, enable printing only if we are not at OOBE.
+ enable_printing = !chromeos::LoginDisplayHost::default_host();
+#endif // defined(OS_CHROMEOS)
+ dict->SetKey("printingEnabled", base::Value(enable_printing));
+#endif // BUILDFLAG(ENABLE_PDF)
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
dict->SetKey("newPrintPreviewLayoutEnabled",
base::Value(base::FeatureList::IsEnabled(
diff --git a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc
index 71465157038..af092f1be71 100644
--- a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc
@@ -51,7 +51,7 @@ class TestEventRouter : public EventRouter {
bool ExtensionHasEventListener(const std::string& extension_id,
const std::string& event_name) const override {
- return base::ContainsKey(fake_registry_, Entry(extension_id, event_name));
+ return base::Contains(fake_registry_, Entry(extension_id, event_name));
}
// Pretend that |extension_id| is listening for |event_name|.
diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc
index 9cff1e3b5a2..e9e97071061 100644
--- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc
@@ -9,11 +9,13 @@
#include <utility>
#include <vector>
+#include "base/feature_list.h"
#include "base/task/post_task.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_service_test_base.h"
#include "chrome/browser/extensions/extension_tab_util.h"
+#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/safe_browsing/test_safe_browsing_service.h"
#include "chrome/browser/sessions/session_tab_helper.h"
#include "chrome/browser/ui/browser.h"
@@ -78,7 +80,6 @@ class SafeBrowsingPrivateApiUnitTest : public ExtensionServiceTestBase {
std::unique_ptr<TestBrowserWindow> browser_window_;
std::unique_ptr<Browser> browser_;
- scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_;
DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateApiUnitTest);
};
@@ -97,12 +98,6 @@ void SafeBrowsingPrivateApiUnitTest::SetUp() {
// Initialize Safe Browsing service.
safe_browsing::TestSafeBrowsingServiceFactory sb_service_factory;
auto* safe_browsing_service = sb_service_factory.CreateSafeBrowsingService();
- system_request_context_getter_ =
- base::MakeRefCounted<net::TestURLRequestContextGetter>(
- base::CreateSingleThreadTaskRunnerWithTraits(
- {content::BrowserThread::IO}));
- TestingBrowserProcess::GetGlobal()->SetSystemRequestContext(
- system_request_context_getter_.get());
TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService(
safe_browsing_service);
g_browser_process->safe_browsing_service()->Initialize();
@@ -120,6 +115,10 @@ void SafeBrowsingPrivateApiUnitTest::TearDown() {
TestingBrowserProcess::GetGlobal()->safe_browsing_service()->ShutDown();
TestingBrowserProcess::GetGlobal()->SetSafeBrowsingService(nullptr);
+ // Depends on LocalState from ChromeRenderViewHostTestHarness.
+ if (SystemNetworkContextManager::GetInstance())
+ SystemNetworkContextManager::DeleteInstance();
+
ExtensionServiceTestBase::TearDown();
}
diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc
index 6ffd453df0d..5516d33789c 100644
--- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc
+++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc
@@ -5,18 +5,57 @@
#include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h"
#include "base/strings/string_number_conversions.h"
+#include "base/strings/stringprintf.h"
+#include "base/time/time.h"
+#include "chrome/browser/browser_process.h"
+#include "chrome/browser/policy/browser_dm_token_storage.h"
+#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/common/extensions/api/safe_browsing_private.h"
+#include "components/policy/core/common/cloud/cloud_policy_client.h"
+#include "components/policy/core/common/cloud/device_management_service.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/browser_context.h"
#include "extensions/browser/event_router.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "url/gurl.h"
namespace extensions {
+const base::Feature SafeBrowsingPrivateEventRouter::kRealtimeReportingFeature{
+ "SafeBrowsingRealtimeReporting", base::FEATURE_DISABLED_BY_DEFAULT};
+
+// Key names used with when building the dictionary to pass to the real-time
+// reporting API.
+const char SafeBrowsingPrivateEventRouter::kKeyUrl[] = "url";
+const char SafeBrowsingPrivateEventRouter::kKeyUserName[] = "userName";
+const char SafeBrowsingPrivateEventRouter::kKeyIsPhishingUrl[] =
+ "isPhishingUrl";
+const char SafeBrowsingPrivateEventRouter::kKeyProfileUserName[] =
+ "profileUserName";
+const char SafeBrowsingPrivateEventRouter::kKeyFileName[] = "fileName";
+const char SafeBrowsingPrivateEventRouter::kKeyDownloadDigestSha256[] =
+ "downloadDigestSha256";
+const char SafeBrowsingPrivateEventRouter::kKeyReason[] = "reason";
+const char SafeBrowsingPrivateEventRouter::kKeyNetErrorCode[] = "netErrorCode";
+const char SafeBrowsingPrivateEventRouter::kKeyClickedThrough[] =
+ "clickedThrough";
+
+const char SafeBrowsingPrivateEventRouter::kKeyPasswordReuseEvent[] =
+ "passwordReuseEvent";
+const char SafeBrowsingPrivateEventRouter::kKeyPasswordChangedEvent[] =
+ "passwordChangedEvent";
+const char SafeBrowsingPrivateEventRouter::kKeyDangerousDownloadEvent[] =
+ "dangerousDownloadEvent";
+const char SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent[] =
+ "interstitialEvent";
+
SafeBrowsingPrivateEventRouter::SafeBrowsingPrivateEventRouter(
content::BrowserContext* context)
- : context_(context), event_router_(nullptr) {
+ : context_(context) {
event_router_ = EventRouter::Get(context_);
+ InitRealtimeReportingClient();
}
SafeBrowsingPrivateEventRouter::~SafeBrowsingPrivateEventRouter() {}
@@ -25,74 +64,96 @@ void SafeBrowsingPrivateEventRouter::OnPolicySpecifiedPasswordReuseDetected(
const GURL& url,
const std::string& user_name,
bool is_phishing_url) {
- // |event_router_| can be null in tests.
- if (!event_router_)
- return;
-
api::safe_browsing_private::PolicySpecifiedPasswordReuse params;
params.url = url.spec();
params.user_name = user_name;
params.is_phishing_url = is_phishing_url;
- auto event_value = std::make_unique<base::ListValue>();
- event_value->Append(params.ToValue());
+ // |event_router_| can be null in tests.
+ if (event_router_) {
+ auto event_value = std::make_unique<base::ListValue>();
+ event_value->Append(params.ToValue());
+
+ auto extension_event = std::make_unique<Event>(
+ events::
+ SAFE_BROWSING_PRIVATE_ON_POLICY_SPECIFIED_PASSWORD_REUSE_DETECTED,
+ api::safe_browsing_private::OnPolicySpecifiedPasswordReuseDetected::
+ kEventName,
+ std::move(event_value));
+ event_router_->BroadcastEvent(std::move(extension_event));
+ }
- auto extension_event = std::make_unique<Event>(
- events::SAFE_BROWSING_PRIVATE_ON_POLICY_SPECIFIED_PASSWORD_REUSE_DETECTED,
- api::safe_browsing_private::OnPolicySpecifiedPasswordReuseDetected::
- kEventName,
- std::move(event_value));
- event_router_->BroadcastEvent(std::move(extension_event));
+ if (client_) {
+ // Convert |params| to a real-time event dictionary and report it.
+ base::Value event(base::Value::Type::DICTIONARY);
+ event.SetStringKey(kKeyUrl, params.url);
+ event.SetStringKey(kKeyUserName, params.user_name);
+ event.SetBoolKey(kKeyIsPhishingUrl, params.is_phishing_url);
+ event.SetStringKey(kKeyProfileUserName, GetProfileUserName());
+ ReportRealtimeEvent(kKeyPasswordReuseEvent, std::move(event));
+ }
}
void SafeBrowsingPrivateEventRouter::OnPolicySpecifiedPasswordChanged(
const std::string& user_name) {
// |event_router_| can be null in tests.
- if (!event_router_)
- return;
+ if (event_router_) {
+ auto event_value = std::make_unique<base::ListValue>();
+ event_value->Append(std::make_unique<base::Value>(user_name));
+ auto extension_event = std::make_unique<Event>(
+ events::SAFE_BROWSING_PRIVATE_ON_POLICY_SPECIFIED_PASSWORD_CHANGED,
+ api::safe_browsing_private::OnPolicySpecifiedPasswordChanged::
+ kEventName,
+ std::move(event_value));
+ event_router_->BroadcastEvent(std::move(extension_event));
+ }
- auto event_value = std::make_unique<base::ListValue>();
- event_value->Append(std::make_unique<base::Value>(user_name));
- auto extension_event = std::make_unique<Event>(
- events::SAFE_BROWSING_PRIVATE_ON_POLICY_SPECIFIED_PASSWORD_CHANGED,
- api::safe_browsing_private::OnPolicySpecifiedPasswordChanged::kEventName,
- std::move(event_value));
- event_router_->BroadcastEvent(std::move(extension_event));
+ if (client_) {
+ // Convert |params| to a real-time event dictionary and report it.
+ base::Value event(base::Value::Type::DICTIONARY);
+ event.SetStringKey(kKeyUserName, user_name);
+ event.SetStringKey(kKeyProfileUserName, GetProfileUserName());
+ ReportRealtimeEvent(kKeyPasswordChangedEvent, std::move(event));
+ }
}
void SafeBrowsingPrivateEventRouter::OnDangerousDownloadOpened(
const GURL& url,
const std::string& file_name,
- const std::string& download_digest_sha256,
- const std::string& user_name) {
- // |event_router_| can be null in tests.
- if (!event_router_)
- return;
-
+ const std::string& download_digest_sha256) {
api::safe_browsing_private::DangerousDownloadInfo params;
params.url = url.spec();
params.file_name = file_name;
params.download_digest_sha256 = download_digest_sha256;
- params.user_name = user_name;
- auto event_value = std::make_unique<base::ListValue>();
- event_value->Append(params.ToValue());
-
- auto extension_event = std::make_unique<Event>(
- events::SAFE_BROWSING_PRIVATE_ON_DANGEROUS_DOWNLOAD_OPENED,
- api::safe_browsing_private::OnDangerousDownloadOpened::kEventName,
- std::move(event_value));
- event_router_->BroadcastEvent(std::move(extension_event));
+ params.user_name = GetProfileUserName();
+
+ // |event_router_| can be null in tests.
+ if (event_router_) {
+ auto event_value = std::make_unique<base::ListValue>();
+ event_value->Append(params.ToValue());
+
+ auto extension_event = std::make_unique<Event>(
+ events::SAFE_BROWSING_PRIVATE_ON_DANGEROUS_DOWNLOAD_OPENED,
+ api::safe_browsing_private::OnDangerousDownloadOpened::kEventName,
+ std::move(event_value));
+ event_router_->BroadcastEvent(std::move(extension_event));
+ }
+
+ if (client_) {
+ // Convert |params| to a real-time event dictionary and report it.
+ base::Value event(base::Value::Type::DICTIONARY);
+ event.SetStringKey(kKeyUrl, params.url);
+ event.SetStringKey(kKeyFileName, params.file_name);
+ event.SetStringKey(kKeyDownloadDigestSha256, params.download_digest_sha256);
+ event.SetStringKey(kKeyProfileUserName, params.user_name);
+ ReportRealtimeEvent(kKeyDangerousDownloadEvent, std::move(event));
+ }
}
void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialShown(
const GURL& url,
const std::string& reason,
- int net_error_code,
- const std::string& user_name) {
- // |event_router_| can be null in tests.
- if (!event_router_)
- return;
-
+ int net_error_code) {
api::safe_browsing_private::InterstitialInfo params;
params.url = url.spec();
params.reason = reason;
@@ -100,27 +161,36 @@ void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialShown(
params.net_error_code =
std::make_unique<std::string>(base::NumberToString(net_error_code));
}
- params.user_name = user_name;
+ params.user_name = GetProfileUserName();
+
+ // |event_router_| can be null in tests.
+ if (event_router_) {
+ auto event_value = std::make_unique<base::ListValue>();
+ event_value->Append(params.ToValue());
- auto event_value = std::make_unique<base::ListValue>();
- event_value->Append(params.ToValue());
+ auto extension_event = std::make_unique<Event>(
+ events::SAFE_BROWSING_PRIVATE_ON_SECURITY_INTERSTITIAL_SHOWN,
+ api::safe_browsing_private::OnSecurityInterstitialShown::kEventName,
+ std::move(event_value));
+ event_router_->BroadcastEvent(std::move(extension_event));
+ }
- auto extension_event = std::make_unique<Event>(
- events::SAFE_BROWSING_PRIVATE_ON_SECURITY_INTERSTITIAL_SHOWN,
- api::safe_browsing_private::OnSecurityInterstitialShown::kEventName,
- std::move(event_value));
- event_router_->BroadcastEvent(std::move(extension_event));
+ if (client_) {
+ // Convert |params| to a real-time event dictionary and report it.
+ base::Value event(base::Value::Type::DICTIONARY);
+ event.SetStringKey(kKeyUrl, params.url);
+ event.SetStringKey(kKeyReason, params.reason);
+ event.SetIntKey(kKeyNetErrorCode, net_error_code);
+ event.SetStringKey(kKeyProfileUserName, params.user_name);
+ event.SetBoolKey(kKeyClickedThrough, false);
+ ReportRealtimeEvent(kKeyInterstitialEvent, std::move(event));
+ }
}
void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialProceeded(
const GURL& url,
const std::string& reason,
- int net_error_code,
- const std::string& user_name) {
- // |event_router_| can be null in tests.
- if (!event_router_)
- return;
-
+ int net_error_code) {
api::safe_browsing_private::InterstitialInfo params;
params.url = url.spec();
params.reason = reason;
@@ -128,16 +198,116 @@ void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialProceeded(
params.net_error_code =
std::make_unique<std::string>(base::NumberToString(net_error_code));
}
- params.user_name = user_name;
+ params.user_name = GetProfileUserName();
+
+ // |event_router_| can be null in tests.
+ if (event_router_) {
+ auto event_value = std::make_unique<base::ListValue>();
+ event_value->Append(params.ToValue());
+
+ auto extension_event = std::make_unique<Event>(
+ events::SAFE_BROWSING_PRIVATE_ON_SECURITY_INTERSTITIAL_PROCEEDED,
+ api::safe_browsing_private::OnSecurityInterstitialProceeded::kEventName,
+ std::move(event_value));
+ event_router_->BroadcastEvent(std::move(extension_event));
+ }
+
+ if (client_) {
+ // Convert |params| to a real-time event dictionary and report it.
+ base::Value event(base::Value::Type::DICTIONARY);
+ event.SetStringKey(kKeyUrl, params.url);
+ event.SetStringKey(kKeyReason, params.reason);
+ event.SetIntKey(kKeyNetErrorCode, net_error_code);
+ event.SetStringKey(kKeyProfileUserName, params.user_name);
+ event.SetBoolKey(kKeyClickedThrough, true);
+ ReportRealtimeEvent(kKeyInterstitialEvent, std::move(event));
+ }
+}
+
+void SafeBrowsingPrivateEventRouter::SetCloudPolicyClientForTesting(
+ std::unique_ptr<policy::CloudPolicyClient> client) {
+ DCHECK_EQ(nullptr, client_.get());
+ client_ = std::move(client);
+}
+
+void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClient() {
+ if (!base::FeatureList::IsEnabled(kRealtimeReportingFeature))
+ return;
+
+ // |identity_manager_| may be null in tests. If there is no identity
+ // manager don't enable the real-time reporting API since the router won't
+ // be able to fill in all the info needed for the reports.
+ identity_manager_ = IdentityManagerFactory::GetForProfile(
+ Profile::FromBrowserContext(context_));
+ if (!identity_manager_)
+ return;
+
+ // |device_management_service| may be null in tests. If there is no device
+ // management service don't enable the real-time reporting API since the
+ // router won't be able to create the reporting server client below.
+ policy::DeviceManagementService* device_management_service =
+ g_browser_process->browser_policy_connector()
+ ->device_management_service();
+ if (!device_management_service)
+ return;
+
+ // Make sure we have a DM token to proceed. During the lifetime of a running
+ // chrome browser, this can only change from empty to non-empty. There are
+ // no cases where chrome starts with a dm token and then it goes away.
+ // When chrome starts without a dm token and determines that one is needed,
+ // browser startup is blocked until it is retrieved or an error occurs. In
+ // the latter case, chrome won't try to retrieve it again until the next
+ // restart.
+ //
+ // Therefore, it is OK to retrieve the dm token once here on initialization
+ // of the router to determine if real-time reporting can be enabled or not.
+ std::string dm_token =
+ policy::BrowserDMTokenStorage::Get()->RetrieveDMToken();
+ std::string client_id =
+ policy::BrowserDMTokenStorage::Get()->RetrieveClientId();
+
+ if (dm_token.empty())
+ return;
- auto event_value = std::make_unique<base::ListValue>();
- event_value->Append(params.ToValue());
+ // Make sure DeviceManagementService has been initialized.
+ device_management_service->ScheduleInitialization(0);
+
+ client_ = std::make_unique<policy::CloudPolicyClient>(
+ /*machine_id=*/std::string(), /*machine_model=*/std::string(),
+ /*brand_code=*/std::string(), /*ethernet_mac_address=*/std::string(),
+ /*dock_mac_address=*/std::string(), /*manufacture_date=*/std::string(),
+ device_management_service, g_browser_process->shared_url_loader_factory(),
+ nullptr, policy::CloudPolicyClient::DeviceDMTokenCallback());
+
+ if (!client_->is_registered()) {
+ client_->SetupRegistration(
+ dm_token, client_id,
+ /*user_affiliation_ids=*/std::vector<std::string>());
+ }
+}
+
+void SafeBrowsingPrivateEventRouter::ReportRealtimeEvent(const char* name,
+ base::Value event) {
+ // Format the current time (UTC) in RFC3339 format.
+ base::Time::Exploded now_exploded;
+ base::Time::Now().UTCExplode(&now_exploded);
+ std::string now_str = base::StringPrintf(
+ "%d-%02d-%02dT%02d:%02d:%02d.%03dZ", now_exploded.year,
+ now_exploded.month, now_exploded.day_of_month, now_exploded.hour,
+ now_exploded.minute, now_exploded.second, now_exploded.millisecond);
+
+ base::Value wrapper(base::Value::Type::DICTIONARY);
+ wrapper.SetStringKey("time", now_str);
+ wrapper.SetKey(name, std::move(event));
+
+ client_->UploadRealtimeReport(std::move(wrapper), base::DoNothing());
+}
- auto extension_event = std::make_unique<Event>(
- events::SAFE_BROWSING_PRIVATE_ON_SECURITY_INTERSTITIAL_PROCEEDED,
- api::safe_browsing_private::OnSecurityInterstitialProceeded::kEventName,
- std::move(event_value));
- event_router_->BroadcastEvent(std::move(extension_event));
+std::string SafeBrowsingPrivateEventRouter::GetProfileUserName() {
+ // |identity_manager_| may be null is some tests.
+ return identity_manager_ && identity_manager_->HasPrimaryAccount()
+ ? identity_manager_->GetPrimaryAccountInfo().email
+ : std::string();
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h
index e5267e9dce4..aa247397917 100644
--- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h
+++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h
@@ -5,9 +5,12 @@
#ifndef CHROME_BROWSER_EXTENSIONS_API_SAFE_BROWSING_PRIVATE_SAFE_BROWSING_PRIVATE_EVENT_ROUTER_H_
#define CHROME_BROWSER_EXTENSIONS_API_SAFE_BROWSING_PRIVATE_SAFE_BROWSING_PRIVATE_EVENT_ROUTER_H_
+#include <memory>
#include <string>
+#include "base/feature_list.h"
#include "base/macros.h"
+#include "base/values.h"
#include "components/keyed_service/core/keyed_service.h"
namespace content {
@@ -18,13 +21,43 @@ namespace extensions {
class EventRouter;
}
+namespace signin {
+class IdentityManager;
+}
+
class GURL;
+namespace policy {
+class CloudPolicyClient;
+}
+
namespace extensions {
// An event router that observes Safe Browsing events and notifies listeners.
+// The router also uploads events to the chrome reporting server side API if
+// the kRealtimeReportingFeature feature is enabled.
class SafeBrowsingPrivateEventRouter : public KeyedService {
public:
+ // Feature that controls whether real-time reports are sent.
+ static const base::Feature kRealtimeReportingFeature;
+
+ // Key names used with when building the dictionary to pass to the real-time
+ // reporting API.
+ static const char kKeyUrl[];
+ static const char kKeyUserName[];
+ static const char kKeyIsPhishingUrl[];
+ static const char kKeyProfileUserName[];
+ static const char kKeyFileName[];
+ static const char kKeyDownloadDigestSha256[];
+ static const char kKeyReason[];
+ static const char kKeyNetErrorCode[];
+ static const char kKeyClickedThrough[];
+
+ static const char kKeyPasswordReuseEvent[];
+ static const char kKeyPasswordChangedEvent[];
+ static const char kKeyDangerousDownloadEvent[];
+ static const char kKeyInterstitialEvent[];
+
explicit SafeBrowsingPrivateEventRouter(content::BrowserContext* context);
~SafeBrowsingPrivateEventRouter() override;
@@ -41,24 +74,38 @@ class SafeBrowsingPrivateEventRouter : public KeyedService {
// Notifies listeners that the user just opened a dangerous download.
void OnDangerousDownloadOpened(const GURL& url,
const std::string& file_name,
- const std::string& download_digest_sha256,
- const std::string& user_name);
+ const std::string& download_digest_sha256);
// Notifies listeners that the user saw a security interstitial.
void OnSecurityInterstitialShown(const GURL& url,
const std::string& reason,
- int net_error_code,
- const std::string& user_name);
+ int net_error_code);
// Notifies listeners that the user clicked-through a security interstitial.
void OnSecurityInterstitialProceeded(const GURL& url,
const std::string& reason,
- int net_error_code,
- const std::string& user_name);
+ int net_error_code);
+
+ void SetCloudPolicyClientForTesting(
+ std::unique_ptr<policy::CloudPolicyClient> client);
private:
+ // Initialize the real-time report client if needed. This client is used only
+ // if real-time reporting is enabled, the machine is properly reigistered
+ // with CBCM and the appropriate policies are enabled.
+ void InitRealtimeReportingClient();
+
+ // Report safe browsing event through real-time reporting channel, if enabled.
+ void ReportRealtimeEvent(const char* name, base::Value event);
+
+ // Returns the Gaia email address of the account signed in to the profile or
+ // an empty string if the profile is not signed in.
+ std::string GetProfileUserName();
+
content::BrowserContext* context_;
- EventRouter* event_router_;
+ signin::IdentityManager* identity_manager_ = nullptr;
+ EventRouter* event_router_ = nullptr;
+ std::unique_ptr<policy::CloudPolicyClient> client_;
DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateEventRouter);
};
diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.cc
index f9cc8435642..560dcbcd769 100644
--- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.cc
+++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.cc
@@ -5,6 +5,7 @@
#include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.h"
#include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h"
+#include "chrome/browser/signin/identity_manager_factory.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "content/public/browser/browser_context.h"
#include "extensions/browser/extension_system_provider.h"
@@ -31,6 +32,7 @@ SafeBrowsingPrivateEventRouterFactory::SafeBrowsingPrivateEventRouterFactory()
"SafeBrowsingPrivateEventRouter",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory());
+ DependsOn(IdentityManagerFactory::GetInstance());
}
SafeBrowsingPrivateEventRouterFactory::
diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc
index c60f6603d14..bf6702672f3 100644
--- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc
@@ -6,16 +6,31 @@
#include "base/bind.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/mock_callback.h"
+#include "base/test/scoped_feature_list.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.h"
#include "chrome/common/extensions/api/safe_browsing_private.h"
#include "chrome/test/base/testing_profile.h"
+#include "components/policy/core/common/cloud/mock_cloud_policy_client.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "extensions/browser/test_event_router.h"
+#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
+using ::testing::_;
+using ::testing::Mock;
+using ::testing::SaveArg;
+
namespace extensions {
+namespace {
+
+ACTION_P(CaptureArg, wrapper) {
+ *wrapper = arg0.Clone();
+}
+
+} // namespace
+
class SafeBrowsingEventObserver : public TestEventRouter::EventObserver {
public:
// The observer will only listen to events with the |event_name|.
@@ -71,31 +86,45 @@ class SafeBrowsingPrivateEventRouterTest : public testing::Test {
SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_)
->OnDangerousDownloadOpened(GURL("https://evil.com/malware.exe"),
"/path/to/malware.exe",
- "sha256_or_malware_exe", "user_name");
+ "sha256_or_malware_exe");
}
void TriggerOnSecurityInterstitialShownEvent() {
SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_)
->OnSecurityInterstitialShown(GURL("https://phishing.com/"), "PHISHING",
- 0, "user_name");
+ 0);
}
void TriggerOnSecurityInterstitialProceededEvent() {
SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_)
->OnSecurityInterstitialProceeded(GURL("https://phishing.com/"),
- "PHISHING", -201, "user_name");
+ "PHISHING", -201);
}
void SetUpRouters() {
event_router_ = extensions::CreateAndUseTestEventRouter(&profile_);
SafeBrowsingPrivateEventRouterFactory::GetInstance()->SetTestingFactory(
&profile_, base::BindRepeating(&BuildSafeBrowsingPrivateEventRouter));
+
+ // Make sure real-time feature is eanbled so that the tests will run.
+ scoped_feature_list_.InitAndEnableFeature(
+ SafeBrowsingPrivateEventRouter::kRealtimeReportingFeature);
+
+ // Set a mock cloud policy client in the router. The router will own the
+ // client, but a pointer to the client is maintained in the test class to
+ // manage expectations.
+ client_ = new policy::MockCloudPolicyClient();
+ std::unique_ptr<policy::CloudPolicyClient> client(client_);
+ SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_)
+ ->SetCloudPolicyClientForTesting(std::move(client));
}
protected:
content::TestBrowserThreadBundle thread_bundle_;
+ base::test::ScopedFeatureList scoped_feature_list_;
TestingProfile profile_;
extensions::TestEventRouter* event_router_ = nullptr;
+ policy::MockCloudPolicyClient* client_;
private:
DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateEventRouterTest);
@@ -108,12 +137,26 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnReuseDetected) {
kEventName);
event_router_->AddEventObserver(&event_observer);
+ base::Value wrapper;
+ EXPECT_CALL(*client_, UploadRealtimeReport(_, _))
+ .WillOnce(CaptureArg(&wrapper));
+
TriggerOnPolicySpecifiedPasswordReuseDetectedEvent();
base::RunLoop().RunUntilIdle();
auto captured_args = event_observer.PassEventArgs().GetList()[0].Clone();
EXPECT_EQ("https://phishing.com/", captured_args.FindKey("url")->GetString());
EXPECT_EQ("user_name_1", captured_args.FindKey("userName")->GetString());
+
+ Mock::VerifyAndClearExpectations(client_);
+ EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type());
+ base::Value* event =
+ wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyPasswordReuseEvent);
+ EXPECT_NE(nullptr, event);
+ EXPECT_EQ("https://phishing.com/",
+ *event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyUrl));
+ EXPECT_EQ("user_name_1", *event->FindStringKey(
+ SafeBrowsingPrivateEventRouter::kKeyUserName));
}
TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnPasswordChanged) {
@@ -122,11 +165,23 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnPasswordChanged) {
api::safe_browsing_private::OnPolicySpecifiedPasswordChanged::kEventName);
event_router_->AddEventObserver(&event_observer);
+ base::Value wrapper;
+ EXPECT_CALL(*client_, UploadRealtimeReport(_, _))
+ .WillOnce(CaptureArg(&wrapper));
+
TriggerOnPolicySpecifiedPasswordChangedEvent();
base::RunLoop().RunUntilIdle();
auto captured_args = event_observer.PassEventArgs().GetList()[0].Clone();
EXPECT_EQ("user_name_2", captured_args.GetString());
+
+ Mock::VerifyAndClearExpectations(client_);
+ EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type());
+ base::Value* event =
+ wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyPasswordChangedEvent);
+ EXPECT_NE(nullptr, event);
+ EXPECT_EQ("user_name_2", *event->FindStringKey(
+ SafeBrowsingPrivateEventRouter::kKeyUserName));
}
TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnDangerousDownloadOpened) {
@@ -135,6 +190,10 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnDangerousDownloadOpened) {
api::safe_browsing_private::OnDangerousDownloadOpened::kEventName);
event_router_->AddEventObserver(&event_observer);
+ base::Value wrapper;
+ EXPECT_CALL(*client_, UploadRealtimeReport(_, _))
+ .WillOnce(CaptureArg(&wrapper));
+
TriggerOnDangerousDownloadOpenedEvent();
base::RunLoop().RunUntilIdle();
@@ -143,9 +202,18 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnDangerousDownloadOpened) {
captured_args.FindKey("url")->GetString());
EXPECT_EQ("/path/to/malware.exe",
captured_args.FindKey("fileName")->GetString());
- EXPECT_EQ("user_name", captured_args.FindKey("userName")->GetString());
+ EXPECT_EQ("", captured_args.FindKey("userName")->GetString());
EXPECT_EQ("sha256_or_malware_exe",
captured_args.FindKey("downloadDigestSha256")->GetString());
+
+ Mock::VerifyAndClearExpectations(client_);
+ EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type());
+ base::Value* event = wrapper.FindKey(
+ SafeBrowsingPrivateEventRouter::kKeyDangerousDownloadEvent);
+ EXPECT_NE(nullptr, event);
+ EXPECT_EQ(
+ "/path/to/malware.exe",
+ *event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyFileName));
}
TEST_F(SafeBrowsingPrivateEventRouterTest,
@@ -155,6 +223,10 @@ TEST_F(SafeBrowsingPrivateEventRouterTest,
api::safe_browsing_private::OnSecurityInterstitialProceeded::kEventName);
event_router_->AddEventObserver(&event_observer);
+ base::Value wrapper;
+ EXPECT_CALL(*client_, UploadRealtimeReport(_, _))
+ .WillOnce(CaptureArg(&wrapper));
+
TriggerOnSecurityInterstitialProceededEvent();
base::RunLoop().RunUntilIdle();
@@ -162,7 +234,19 @@ TEST_F(SafeBrowsingPrivateEventRouterTest,
EXPECT_EQ("https://phishing.com/", captured_args.FindKey("url")->GetString());
EXPECT_EQ("PHISHING", captured_args.FindKey("reason")->GetString());
EXPECT_EQ("-201", captured_args.FindKey("netErrorCode")->GetString());
- EXPECT_EQ("user_name", captured_args.FindKey("userName")->GetString());
+ EXPECT_EQ("", captured_args.FindKey("userName")->GetString());
+
+ Mock::VerifyAndClearExpectations(client_);
+ EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type());
+ base::Value* event =
+ wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent);
+ EXPECT_NE(nullptr, event);
+ EXPECT_EQ("PHISHING",
+ *event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyReason));
+ EXPECT_EQ(-201, *event->FindIntKey(
+ SafeBrowsingPrivateEventRouter::kKeyNetErrorCode));
+ EXPECT_TRUE(
+ *event->FindBoolKey(SafeBrowsingPrivateEventRouter::kKeyClickedThrough));
}
TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSecurityInterstitialShown) {
@@ -171,6 +255,10 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSecurityInterstitialShown) {
api::safe_browsing_private::OnSecurityInterstitialShown::kEventName);
event_router_->AddEventObserver(&event_observer);
+ base::Value wrapper;
+ EXPECT_CALL(*client_, UploadRealtimeReport(_, _))
+ .WillOnce(CaptureArg(&wrapper));
+
TriggerOnSecurityInterstitialShownEvent();
base::RunLoop().RunUntilIdle();
@@ -178,6 +266,18 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSecurityInterstitialShown) {
EXPECT_EQ("https://phishing.com/", captured_args.FindKey("url")->GetString());
EXPECT_EQ("PHISHING", captured_args.FindKey("reason")->GetString());
EXPECT_FALSE(captured_args.FindKey("netErrorCode"));
- EXPECT_EQ("user_name", captured_args.FindKey("userName")->GetString());
+ EXPECT_EQ("", captured_args.FindKey("userName")->GetString());
+
+ Mock::VerifyAndClearExpectations(client_);
+ EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type());
+ base::Value* event =
+ wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent);
+ EXPECT_NE(nullptr, event);
+ EXPECT_EQ("PHISHING",
+ *event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyReason));
+ EXPECT_EQ(
+ 0, *event->FindIntKey(SafeBrowsingPrivateEventRouter::kKeyNetErrorCode));
+ EXPECT_FALSE(
+ *event->FindBoolKey(SafeBrowsingPrivateEventRouter::kKeyClickedThrough));
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.cc b/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.cc
index 63e56da23b9..4227609b7ab 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.cc
@@ -4,12 +4,14 @@
#include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.h"
+#include "base/feature_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/system/timezone_resolver_manager.h"
#include "chrome/browser/extensions/api/settings_private/generated_pref.h"
#include "chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
+#include "chrome/common/chrome_features.h"
#include "chrome/common/extensions/api/settings_private.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
@@ -66,12 +68,18 @@ SetPrefResult GeneratedResolveTimezoneByGeolocationOnOff::SetPref(
if (!value->is_bool())
return SetPrefResult::PREF_TYPE_MISMATCH;
- // Check if preference is policy or primary-user controlled, or if the user is
- // a child, and therefore cannot deactivate automatic timezone.
+ // Check if preference is policy or primary-user controlled, and therefore
+ // cannot deactivate automatic timezone.
if (chromeos::system::TimeZoneResolverManager::
IsTimeZoneResolutionPolicyControlled() ||
- !profile_->IsSameProfile(ProfileManager::GetPrimaryUserProfile()) ||
- profile_->IsChild()) {
+ !profile_->IsSameProfile(ProfileManager::GetPrimaryUserProfile())) {
+ return SetPrefResult::PREF_NOT_MODIFIABLE;
+ }
+
+ // If the Parent Access Code feature is not available, children must use
+ // automatic timezone.
+ if (profile_->IsChild() &&
+ !base::FeatureList::IsEnabled(features::kParentAccessCodeForTimeChange)) {
return SetPrefResult::PREF_NOT_MODIFIABLE;
}
diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.cc b/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.cc
index fa90ade78a3..24f509a9801 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.cc
@@ -31,6 +31,16 @@ GeneratedPrefsFactory::GeneratedPrefsFactory()
GeneratedPrefsFactory::~GeneratedPrefsFactory() {}
+content::BrowserContext* GeneratedPrefsFactory::GetBrowserContextToUse(
+ content::BrowserContext* context) const {
+ // Use |context| even if it is off-the-record/incognito.
+ return context;
+}
+
+bool GeneratedPrefsFactory::ServiceIsNULLWhileTesting() const {
+ return true;
+}
+
KeyedService* GeneratedPrefsFactory::BuildServiceInstanceFor(
content::BrowserContext* profile) const {
return new GeneratedPrefs(static_cast<Profile*>(profile));
diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h b/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h
index e755cf0f57b..10fc892653c 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h
+++ b/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h
@@ -29,6 +29,9 @@ class GeneratedPrefsFactory : public BrowserContextKeyedServiceFactory {
~GeneratedPrefsFactory() override;
// BrowserContextKeyedServiceFactory implementation.
+ content::BrowserContext* GetBrowserContextToUse(
+ content::BrowserContext* context) const override;
+ bool ServiceIsNULLWhileTesting() const override;
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* profile) const override;
diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc b/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc
index 133958aba26..620e7fa6e2f 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc
@@ -4,9 +4,11 @@
#include "chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.h"
+#include "base/feature_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/system/timezone_resolver_manager.h"
#include "chrome/browser/profiles/profile_manager.h"
+#include "chrome/common/chrome_features.h"
#include "chrome/common/extensions/api/settings_private.h"
#include "components/user_manager/user_manager.h"
@@ -36,13 +38,15 @@ void GeneratedTimeZonePrefBase::OnTimeZoneResolverUpdated() {
void GeneratedTimeZonePrefBase::UpdateTimeZonePrefControlledBy(
settings_api::PrefObject* out_pref) const {
- if (profile_->IsChild()) {
- out_pref->controlled_by = settings_api::ControlledBy::CONTROLLED_BY_PARENT;
- out_pref->enforcement = settings_api::ENFORCEMENT_ENFORCED;
- } else if (chromeos::system::TimeZoneResolverManager::
- IsTimeZoneResolutionPolicyControlled()) {
+ if (chromeos::system::TimeZoneResolverManager::
+ IsTimeZoneResolutionPolicyControlled()) {
out_pref->controlled_by = settings_api::CONTROLLED_BY_DEVICE_POLICY;
out_pref->enforcement = settings_api::ENFORCEMENT_ENFORCED;
+ } else if (profile_->IsChild() &&
+ !base::FeatureList::IsEnabled(
+ features::kParentAccessCodeForTimeChange)) {
+ out_pref->controlled_by = settings_api::ControlledBy::CONTROLLED_BY_PARENT;
+ out_pref->enforcement = settings_api::ENFORCEMENT_ENFORCED;
} else if (!profile_->IsSameProfile(
ProfileManager::GetPrimaryUserProfile())) {
out_pref->controlled_by = settings_api::CONTROLLED_BY_PRIMARY_USER;
diff --git a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc
index 7155c905d10..f41d39b5833 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc
@@ -44,6 +44,7 @@
#if defined(OS_CHROMEOS)
#include "ash/public/cpp/ash_pref_names.h" // nogncheck
#include "chrome/browser/chromeos/crostini/crostini_pref_names.h"
+#include "chrome/browser/chromeos/guest_os/guest_os_pref_names.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"
@@ -52,8 +53,10 @@
#include "chrome/browser/chromeos/system/timezone_util.h"
#include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.h"
#include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.h"
-#include "chrome/browser/ui/ash/assistant/assistant_pref_util.h"
+#include "chrome/browser/supervised_user/supervised_user_service.h"
+#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
#include "chromeos/constants/chromeos_features.h"
+#include "chromeos/services/assistant/public/cpp/assistant_prefs.h"
#include "chromeos/settings/cros_settings_names.h"
#include "components/arc/arc_prefs.h"
#include "ui/chromeos/events/pref_names.h"
@@ -74,6 +77,27 @@ bool IsPrivilegedCrosSetting(const std::string& pref_name) {
// controlled or owner controlled.
return true;
}
+
+bool IsRestrictedCrosSettingForChildUser(Profile* profile,
+ const std::string& pref_name) {
+ if (!profile->IsChild())
+ return false;
+
+ return SupervisedUserServiceFactory::GetForProfile(profile)
+ ->IsRestrictedCrosSettingForChildUser(pref_name);
+}
+
+const base::Value* GetRestrictedCrosSettingValueForChildUser(
+ Profile* profile,
+ const std::string& pref_name) {
+ // Make sure that profile belongs to a child and the preference is
+ // pre-set.
+ DCHECK(IsRestrictedCrosSettingForChildUser(profile, pref_name));
+
+ return SupervisedUserServiceFactory::GetForProfile(profile)
+ ->GetRestrictedCrosSettingValueForChildUser(pref_name);
+}
+
#endif
bool IsSettingReadOnly(const std::string& pref_name) {
@@ -128,6 +152,7 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[bookmarks::prefs::kShowBookmarkBar] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
+
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
(*s_whitelist)[::prefs::kUseCustomChromeFrame] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
@@ -288,6 +313,20 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
// Accessibility.
(*s_whitelist)[::prefs::kAccessibilityImageLabelsEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[::prefs::kAccessibilityCaptionsTextSize] =
+ settings_api::PrefType::PREF_TYPE_STRING;
+ (*s_whitelist)[::prefs::kAccessibilityCaptionsTextFont] =
+ settings_api::PrefType::PREF_TYPE_STRING;
+ (*s_whitelist)[::prefs::kAccessibilityCaptionsTextColor] =
+ settings_api::PrefType::PREF_TYPE_STRING;
+ (*s_whitelist)[::prefs::kAccessibilityCaptionsTextOpacity] =
+ settings_api::PrefType::PREF_TYPE_NUMBER;
+ (*s_whitelist)[::prefs::kAccessibilityCaptionsBackgroundColor] =
+ settings_api::PrefType::PREF_TYPE_STRING;
+ (*s_whitelist)[::prefs::kAccessibilityCaptionsTextShadow] =
+ settings_api::PrefType::PREF_TYPE_STRING;
+ (*s_whitelist)[::prefs::kAccessibilityCaptionsBackgroundOpacity] =
+ settings_api::PrefType::PREF_TYPE_NUMBER;
#if defined(OS_CHROMEOS)
// Accounts / Users / People.
@@ -355,6 +394,22 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessSelectKeyCodes] =
+ settings_api::PrefType::PREF_TYPE_LIST;
+ (*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessSelectSetting] =
+ settings_api::PrefType::PREF_TYPE_NUMBER;
+ (*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessNextKeyCodes] =
+ settings_api::PrefType::PREF_TYPE_LIST;
+ (*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessNextSetting] =
+ settings_api::PrefType::PREF_TYPE_NUMBER;
+ (*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessPreviousKeyCodes] =
+ settings_api::PrefType::PREF_TYPE_LIST;
+ (*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessPreviousSetting] =
+ settings_api::PrefType::PREF_TYPE_NUMBER;
+ (*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessAutoScanEnabled] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessAutoScanSpeedMs] =
+ settings_api::PrefType::PREF_TYPE_NUMBER;
(*s_whitelist)[ash::prefs::kAccessibilityVirtualKeyboardEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[ash::prefs::kAccessibilityMonoAudioEnabled] =
@@ -370,34 +425,36 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
(*s_whitelist)[::prefs::kTextToSpeechVolume] =
settings_api::PrefType::PREF_TYPE_NUMBER;
- // Crostini
+ // Guest OS
(*s_whitelist)[crostini::prefs::kCrostiniEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[crostini::prefs::kGuestOSPathsSharedToVms] =
- settings_api::PrefType::PREF_TYPE_DICTIONARY;
(*s_whitelist)[crostini::prefs::kCrostiniSharedUsbDevices] =
settings_api::PrefType::PREF_TYPE_LIST;
(*s_whitelist)[crostini::prefs::kCrostiniContainers] =
settings_api::PrefType::PREF_TYPE_LIST;
+ (*s_whitelist)[guest_os::prefs::kGuestOSPathsSharedToVms] =
+ settings_api::PrefType::PREF_TYPE_DICTIONARY;
// Android Apps.
(*s_whitelist)[arc::prefs::kArcEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
// Google Assistant.
- (*s_whitelist)[::assistant::prefs::kAssistantConsentStatus] =
+ (*s_whitelist)[chromeos::assistant::prefs::kAssistantConsentStatus] =
settings_api::PrefType::PREF_TYPE_NUMBER;
+ (*s_whitelist)[chromeos::assistant::prefs::kAssistantDisabledByPolicy] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[arc::prefs::kVoiceInteractionEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[arc::prefs::kVoiceInteractionContextEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[arc::prefs::kVoiceInteractionHotwordAlwaysOn] =
+ (*s_whitelist)[chromeos::assistant::prefs::kAssistantHotwordAlwaysOn] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[arc::prefs::kVoiceInteractionHotwordEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[arc::prefs::kVoiceInteractionNotificationEnabled] =
+ (*s_whitelist)[chromeos::assistant::prefs::kAssistantLaunchWithMicOpen] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[arc::prefs::kVoiceInteractionLaunchWithMicOpen] =
+ (*s_whitelist)[chromeos::assistant::prefs::kAssistantNotificationEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
// Misc.
@@ -413,6 +470,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[prefs::kRestoreLastLockScreenNote] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[ash::prefs::kLockScreenMediaKeysEnabled] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
// Bluetooth & Internet settings.
(*s_whitelist)[chromeos::kAllowBluetooth] =
@@ -449,8 +508,6 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
settings_api::PrefType::PREF_TYPE_NUMBER;
// Ash settings.
- (*s_whitelist)[ash::prefs::kKioskNextShellEnabled] =
- settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[ash::prefs::kEnableStylusTools] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[ash::prefs::kLaunchPaletteOnEjectEvent] =
@@ -558,6 +615,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
#if defined(GOOGLE_CHROME_BUILD)
(*s_whitelist)[::prefs::kMediaRouterEnableCloudServices] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[::prefs::kUserFeedbackAllowed] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
#endif // defined(GOOGLE_CHROME_BUILD)
// Media Remoting settings.
@@ -711,6 +770,15 @@ std::unique_ptr<settings_api::PrefObject> PrefsUtil::GetPref(
user_manager::UserManager::Get()->GetOwnerAccountId().GetUserEmail()));
return pref_object;
}
+
+ if (IsRestrictedCrosSettingForChildUser(profile_, name)) {
+ pref_object->controlled_by =
+ settings_api::ControlledBy::CONTROLLED_BY_CHILD_RESTRICTIONS;
+ pref_object->enforcement = settings_api::Enforcement::ENFORCEMENT_ENFORCED;
+ pref_object->value = std::make_unique<base::Value>(
+ GetRestrictedCrosSettingValueForChildUser(profile_, name)->Clone());
+ return pref_object;
+ }
#endif
const Extension* extension = GetExtensionControllingPref(*pref_object);
diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc
index 4898ddb897a..821ed539375 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc
@@ -17,10 +17,6 @@
#include "content/public/common/page_zoom.h"
#include "extensions/browser/extension_function_registry.h"
-namespace {
- const char kDelegateIsNull[] = "delegate is null";
-}
-
namespace extensions {
////////////////////////////////////////////////////////////////////////////////
@@ -37,8 +33,7 @@ ExtensionFunction::ResponseAction SettingsPrivateSetPrefFunction::Run() {
SettingsPrivateDelegate* delegate =
SettingsPrivateDelegateFactory::GetForBrowserContext(browser_context());
- if (delegate == nullptr)
- return RespondNow(Error(kDelegateIsNull));
+ DCHECK(delegate);
settings_private::SetPrefResult result =
delegate->SetPref(parameters->name, parameters->value.get());
@@ -71,11 +66,8 @@ SettingsPrivateGetAllPrefsFunction::~SettingsPrivateGetAllPrefsFunction() {
ExtensionFunction::ResponseAction SettingsPrivateGetAllPrefsFunction::Run() {
SettingsPrivateDelegate* delegate =
SettingsPrivateDelegateFactory::GetForBrowserContext(browser_context());
-
- if (delegate == nullptr)
- return RespondNow(Error(kDelegateIsNull));
- else
- return RespondNow(OneArgument(delegate->GetAllPrefs()));
+ DCHECK(delegate);
+ return RespondNow(OneArgument(delegate->GetAllPrefs()));
}
////////////////////////////////////////////////////////////////////////////////
@@ -92,8 +84,7 @@ ExtensionFunction::ResponseAction SettingsPrivateGetPrefFunction::Run() {
SettingsPrivateDelegate* delegate =
SettingsPrivateDelegateFactory::GetForBrowserContext(browser_context());
- if (delegate == nullptr)
- return RespondNow(Error(kDelegateIsNull));
+ DCHECK(delegate);
std::unique_ptr<base::Value> value = delegate->GetPref(parameters->name);
if (value->is_none())
@@ -114,11 +105,8 @@ ExtensionFunction::ResponseAction
SettingsPrivateGetDefaultZoomFunction::Run() {
SettingsPrivateDelegate* delegate =
SettingsPrivateDelegateFactory::GetForBrowserContext(browser_context());
-
- if (delegate == nullptr)
- return RespondNow(Error(kDelegateIsNull));
- else
- return RespondNow(OneArgument(delegate->GetDefaultZoom()));
+ DCHECK(delegate);
+ return RespondNow(OneArgument(delegate->GetDefaultZoom()));
}
////////////////////////////////////////////////////////////////////////////////
@@ -137,9 +125,7 @@ ExtensionFunction::ResponseAction
SettingsPrivateDelegate* delegate =
SettingsPrivateDelegateFactory::GetForBrowserContext(browser_context());
- if (delegate == nullptr)
- return RespondNow(Error(kDelegateIsNull));
-
+ DCHECK(delegate);
delegate->SetDefaultZoom(parameters->zoom);
return RespondNow(OneArgument(std::make_unique<base::Value>(true)));
}
diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc
new file mode 100644
index 00000000000..6b7a7b7f1c6
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc
@@ -0,0 +1,57 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/values.h"
+#include "chrome/browser/chromeos/login/mixin_based_in_process_browser_test.h"
+#include "chrome/browser/chromeos/login/test/guest_session_mixin.h"
+#include "chrome/browser/extensions/api/settings_private/prefs_util_enums.h"
+#include "chrome/browser/extensions/api/settings_private/settings_private_api.h"
+#include "chrome/browser/extensions/api/settings_private/settings_private_delegate.h"
+#include "chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.h"
+#include "chrome/browser/extensions/api/settings_private/settings_private_event_router.h"
+#include "chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/browser.h"
+#include "content/public/test/browser_test.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace extensions {
+namespace {
+
+class SettingsPrivateGuestModeTest
+ : public chromeos::MixinBasedInProcessBrowserTest {
+ protected:
+ chromeos::GuestSessionMixin guest_session_{&mixin_host_};
+};
+
+// Regression test for https://crbug.com/887383.
+IN_PROC_BROWSER_TEST_F(SettingsPrivateGuestModeTest, GuestMode) {
+ Profile* guest_profile = browser()->profile();
+ EXPECT_TRUE(guest_profile->IsOffTheRecord());
+
+ // SettingsPrivate uses the incognito profile, not the recording profile,
+ // to set preferences.
+ SettingsPrivateDelegate* delegate =
+ SettingsPrivateDelegateFactory::GetForBrowserContext(guest_profile);
+ Profile* delegate_profile = delegate->profile_for_test();
+ EXPECT_EQ(guest_profile, delegate_profile);
+ EXPECT_NE(guest_profile->GetOriginalProfile(), delegate_profile);
+
+ // SettingsPrivate observes the incognito profile, not the recording profile,
+ // for pref changes.
+ SettingsPrivateEventRouter* router =
+ SettingsPrivateEventRouterFactory::GetForProfile(guest_profile);
+ Profile* router_profile = static_cast<Profile*>(router->context_for_test());
+ EXPECT_EQ(guest_profile, router_profile);
+ EXPECT_NE(guest_profile->GetOriginalProfile(), router_profile);
+
+ // Page zoom preferences cannot be changed in guest mode and always return a
+ // default value.
+ EXPECT_EQ(settings_private::SetPrefResult::PREF_NOT_MODIFIABLE,
+ delegate->SetDefaultZoom(0.5));
+ EXPECT_EQ(delegate->GetDefaultZoom()->GetDouble(), 0.0);
+}
+
+} // namespace
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc
index adf858f84b0..9eb362464dd 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc
@@ -10,6 +10,7 @@
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/extensions/api/settings_private/prefs_util.h"
+#include "chrome/browser/extensions/api/settings_private/prefs_util_enums.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
#include "chrome/common/pref_names.h"
@@ -58,14 +59,21 @@ settings_private::SetPrefResult SettingsPrivateDelegate::SetPref(
}
std::unique_ptr<base::Value> SettingsPrivateDelegate::GetDefaultZoom() {
+ // Zoom level prefs aren't available for off-the-record profiles (like guest
+ // mode on Chrome OS). The setting isn't visible to users anyway, so return a
+ // default value.
+ if (profile_->IsOffTheRecord())
+ return std::make_unique<base::Value>(0.0);
double zoom = content::ZoomLevelToZoomFactor(
profile_->GetZoomLevelPrefs()->GetDefaultZoomLevelPref());
- std::unique_ptr<base::Value> value(new base::Value(zoom));
- return value;
+ return std::make_unique<base::Value>(zoom);
}
settings_private::SetPrefResult SettingsPrivateDelegate::SetDefaultZoom(
double zoom) {
+ // See comment in GetDefaultZoom().
+ if (profile_->IsOffTheRecord())
+ return settings_private::SetPrefResult::PREF_NOT_MODIFIABLE;
double zoom_factor = content::ZoomFactorToZoomLevel(zoom);
profile_->GetZoomLevelPrefs()->SetDefaultZoomLevelPref(zoom_factor);
return settings_private::SetPrefResult::SUCCESS;
diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.h b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.h
index e2d07ca2d67..bbe82f1ac17 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.h
+++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.h
@@ -50,6 +50,8 @@ class SettingsPrivateDelegate : public KeyedService {
// Sets the pref.
virtual settings_private::SetPrefResult SetDefaultZoom(double zoom);
+ Profile* profile_for_test() { return profile_; }
+
protected:
Profile* profile_; // weak; not owned by us
std::unique_ptr<PrefsUtil> prefs_util_;
diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.cc
index e855cac044a..fd8ed79cc27 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.cc
@@ -6,7 +6,6 @@
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/api/settings_private/settings_private_delegate.h"
-#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/extension_system_provider.h"
@@ -39,8 +38,6 @@ SettingsPrivateDelegateFactory::~SettingsPrivateDelegateFactory() {
content::BrowserContext* SettingsPrivateDelegateFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
// Use the incognito profile when in Guest mode.
- if (context->IsOffTheRecord())
- return chrome::GetBrowserContextRedirectedInIncognito(context);
return context;
}
diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.cc
index c6804a179b1..c09ec777fb2 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.cc
@@ -23,22 +23,15 @@ namespace extensions {
SettingsPrivateEventRouter::SettingsPrivateEventRouter(
content::BrowserContext* context)
- : context_(context), listening_(false), weak_ptr_factory_(this) {
- // Register with the event router so we know when renderers are listening to
- // our events. We first check and see if there *is* an event router, because
- // some unit tests try to create all context services, but don't initialize
- // the event router first.
- EventRouter* event_router = EventRouter::Get(context_);
- if (event_router) {
- event_router->RegisterObserver(
- this, api::settings_private::OnPrefsChanged::kEventName);
- StartOrStopListeningForPrefsChanges();
- }
-
+ : context_(context) {
Profile* profile = Profile::FromBrowserContext(context_);
- prefs_util_.reset(new PrefsUtil(profile));
+ prefs_util_ = std::make_unique<PrefsUtil>(profile);
user_prefs_registrar_.Init(profile->GetPrefs());
local_state_registrar_.Init(g_browser_process->local_state());
+
+ EventRouter::Get(context_)->RegisterObserver(
+ this, api::settings_private::OnPrefsChanged::kEventName);
+ StartOrStopListeningForPrefsChanges();
}
SettingsPrivateEventRouter::~SettingsPrivateEventRouter() {
@@ -51,15 +44,12 @@ void SettingsPrivateEventRouter::OnGeneratedPrefChanged(
}
void SettingsPrivateEventRouter::Shutdown() {
- // Unregister with the event router. We first check and see if there *is* an
- // event router, because some unit tests try to shutdown all context services,
- // but didn't initialize the event router first.
- EventRouter* event_router = EventRouter::Get(context_);
- if (event_router)
- event_router->UnregisterObserver(this);
+ EventRouter::Get(context_)->UnregisterObserver(this);
if (listening_) {
+#if defined(OS_CHROMEOS)
cros_settings_subscription_map_.clear();
+#endif
const PrefsUtil::TypedPrefMap& keys = prefs_util_->GetWhitelistedKeys();
settings_private::GeneratedPrefs* generated_prefs =
settings_private::GeneratedPrefsFactory::GetForBrowserContext(context_);
@@ -96,6 +86,7 @@ PrefChangeRegistrar* SettingsPrivateEventRouter::FindRegistrarForPref(
}
void SettingsPrivateEventRouter::StartOrStopListeningForPrefsChanges() {
+ DCHECK(prefs_util_);
EventRouter* event_router = EventRouter::Get(context_);
bool should_listen = event_router->HasEventListener(
api::settings_private::OnPrefsChanged::kEventName);
@@ -128,12 +119,15 @@ void SettingsPrivateEventRouter::StartOrStopListeningForPrefsChanges() {
} else if (!should_listen && listening_) {
const PrefsUtil::TypedPrefMap& keys = prefs_util_->GetWhitelistedKeys();
for (const auto& it : keys) {
- if (prefs_util_->IsCrosSetting(it.first))
+ if (prefs_util_->IsCrosSetting(it.first)) {
+#if defined(OS_CHROMEOS)
cros_settings_subscription_map_.erase(it.first);
- else if (generated_prefs && generated_prefs->HasPref(it.first))
+#endif
+ } else if (generated_prefs && generated_prefs->HasPref(it.first)) {
generated_prefs->RemoveObserver(it.first, this);
- else
+ } else {
FindRegistrarForPref(it.first)->Remove(it.first);
+ }
}
}
listening_ = should_listen;
diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h
index 4d28143ee7b..3471e7441cf 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h
+++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h
@@ -5,6 +5,7 @@
#ifndef CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_SETTINGS_PRIVATE_EVENT_ROUTER_H_
#define CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_SETTINGS_PRIVATE_EVENT_ROUTER_H_
+#include <map>
#include <memory>
#include "base/macros.h"
@@ -15,12 +16,9 @@
#include "components/prefs/pref_change_registrar.h"
#include "extensions/browser/event_router.h"
-// TODO(wychen): ChromeOS headers should only be included when building
-// ChromeOS, and the following headers should be guarded by
-// #if defined(OS_CHROMEOS). However, the types are actually
-// used, and it takes another CL to clean them up.
-// Reference: crbug.com/720159
+#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/settings/cros_settings.h"
+#endif
namespace content {
class BrowserContext;
@@ -43,6 +41,8 @@ class SettingsPrivateEventRouter
// settings_private::GeneratedPref::Observer implementation.
void OnGeneratedPrefChanged(const std::string& pref_name) override;
+ content::BrowserContext* context_for_test() { return context_; }
+
protected:
explicit SettingsPrivateEventRouter(content::BrowserContext* context);
@@ -73,17 +73,19 @@ class SettingsPrivateEventRouter
PrefChangeRegistrar* FindRegistrarForPref(const std::string& pref_name);
+#if defined(OS_CHROMEOS)
using SubscriptionMap =
std::map<std::string,
std::unique_ptr<chromeos::CrosSettings::ObserverSubscription>>;
SubscriptionMap cros_settings_subscription_map_;
+#endif
- content::BrowserContext* context_;
- bool listening_;
+ content::BrowserContext* const context_;
+ bool listening_ = false;
std::unique_ptr<PrefsUtil> prefs_util_;
- base::WeakPtrFactory<SettingsPrivateEventRouter> weak_ptr_factory_;
+ base::WeakPtrFactory<SettingsPrivateEventRouter> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SettingsPrivateEventRouter);
};
diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.cc
index 227e15d0c7a..fd9b77db655 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.cc
@@ -2,11 +2,13 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include "chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.h"
+
#include "chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.h"
#include "chrome/browser/extensions/api/settings_private/settings_private_event_router.h"
-#include "chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "content/public/browser/browser_context.h"
+#include "extensions/browser/event_router_factory.h"
#include "extensions/browser/extension_system_provider.h"
#include "extensions/browser/extensions_browser_client.h"
@@ -30,6 +32,7 @@ SettingsPrivateEventRouterFactory::SettingsPrivateEventRouterFactory()
"SettingsPrivateEventRouter",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory());
+ DependsOn(EventRouterFactory::GetInstance());
DependsOn(SettingsPrivateDelegateFactory::GetInstance());
}
@@ -44,7 +47,8 @@ KeyedService* SettingsPrivateEventRouterFactory::BuildServiceInstanceFor(
content::BrowserContext*
SettingsPrivateEventRouterFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
- return ExtensionsBrowserClient::Get()->GetOriginalContext(context);
+ // Use the incognito profile in guest mode.
+ return context;
}
bool SettingsPrivateEventRouterFactory::ServiceIsCreatedWithBrowserContext()
@@ -53,7 +57,7 @@ bool SettingsPrivateEventRouterFactory::ServiceIsCreatedWithBrowserContext()
}
bool SettingsPrivateEventRouterFactory::ServiceIsNULLWhileTesting() const {
- return false;
+ return true;
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc
index f4f9013ada4..ad64682385f 100644
--- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc
@@ -19,71 +19,22 @@
#include "chrome/browser/sync/device_info_sync_service_factory.h"
#include "components/sync_device_info/device_info.h"
#include "components/sync_device_info/device_info_sync_service.h"
-#include "components/sync_device_info/device_info_tracker.h"
+#include "components/sync_device_info/fake_device_info_tracker.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "extensions/common/extension.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using syncer::DeviceInfo;
-using syncer::DeviceInfoTracker;
+using syncer::FakeDeviceInfoTracker;
using testing::Return;
namespace extensions {
-class MockDeviceInfoTracker : public DeviceInfoTracker {
- public:
- ~MockDeviceInfoTracker() override {}
-
- bool IsSyncing() const override { return !devices_.empty(); }
-
- std::unique_ptr<DeviceInfo> GetDeviceInfo(
- const std::string& client_id) const override {
- NOTREACHED();
- return std::unique_ptr<DeviceInfo>();
- }
-
- static std::unique_ptr<DeviceInfo> CloneDeviceInfo(
- const DeviceInfo& device_info) {
- return std::make_unique<DeviceInfo>(
- device_info.guid(), device_info.client_name(),
- device_info.chrome_version(), device_info.sync_user_agent(),
- device_info.device_type(), device_info.signin_scoped_device_id(),
- device_info.last_updated_timestamp(),
- device_info.send_tab_to_self_receiving_enabled());
- }
-
- std::vector<std::unique_ptr<DeviceInfo>> GetAllDeviceInfo() const override {
- std::vector<std::unique_ptr<DeviceInfo>> list;
-
- for (const DeviceInfo* device : devices_)
- list.push_back(CloneDeviceInfo(*device));
-
- return list;
- }
-
- void AddObserver(Observer* observer) override { NOTREACHED(); }
-
- void RemoveObserver(Observer* observer) override { NOTREACHED(); }
-
- int CountActiveDevices() const override {
- NOTREACHED();
- return 0;
- }
-
- void Add(const DeviceInfo* device) { devices_.push_back(device); }
-
- void ForcePulseForTest() override { NOTREACHED(); }
-
- private:
- // DeviceInfo stored here are not owned.
- std::vector<const DeviceInfo*> devices_;
-};
-
TEST(SignedInDevicesAPITest, GetSignedInDevices) {
content::TestBrowserThreadBundle thread_bundle;
TestingProfile profile;
- MockDeviceInfoTracker device_tracker;
+ FakeDeviceInfoTracker device_tracker;
TestExtensionPrefs extension_prefs(base::ThreadTaskRunnerHandle::Get().get());
// Add a couple of devices and make sure we get back public ids for them.
@@ -140,7 +91,7 @@ class MockDeviceInfoSyncService : public syncer::DeviceInfoSyncService {
MockDeviceInfoSyncService() = default;
~MockDeviceInfoSyncService() override = default;
- MockDeviceInfoTracker* mock_tracker() { return &tracker_; }
+ FakeDeviceInfoTracker* fake_tracker() { return &tracker_; }
// DeviceInfoSyncService implementation.
syncer::LocalDeviceInfoProvider* GetLocalDeviceInfoProvider() override {
@@ -155,7 +106,7 @@ class MockDeviceInfoSyncService : public syncer::DeviceInfoSyncService {
}
private:
- MockDeviceInfoTracker tracker_;
+ FakeDeviceInfoTracker tracker_;
};
std::unique_ptr<KeyedService> CreateMockDeviceInfoSyncService(
@@ -200,10 +151,10 @@ base::DictionaryValue* GetDictionaryFromList(int index,
}
TEST_F(ExtensionSignedInDevicesTest, GetAll) {
- MockDeviceInfoTracker* device_tracker =
+ FakeDeviceInfoTracker* device_tracker =
static_cast<MockDeviceInfoSyncService*>(
DeviceInfoSyncServiceFactory::GetForProfile(profile()))
- ->mock_tracker();
+ ->fake_tracker();
DeviceInfo device_info1(base::GenerateGUID(), "abc Device", "XYZ v1",
"XYZ SyncAgent v1",
diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc
index cba75303ea2..17081c07d58 100644
--- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc
@@ -13,9 +13,9 @@
#include "chrome/test/base/testing_profile.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/testing_pref_store.h"
+#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "extensions/browser/event_router.h"
-#include "services/identity/public/cpp/identity_test_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc b/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc
index 116d11b88df..0e34dab6a97 100644
--- a/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc
@@ -511,12 +511,12 @@ class TestSocketFactory : public net::ClientSocketFactory {
success_);
}
std::unique_ptr<net::SSLClientSocket> CreateSSLClientSocket(
+ net::SSLClientContext*,
std::unique_ptr<net::StreamSocket>,
const net::HostPortPair&,
- const net::SSLConfig&,
- const net::SSLClientSocketContext&) override {
+ const net::SSLConfig&) override {
NOTIMPLEMENTED();
- return std::unique_ptr<net::SSLClientSocket>();
+ return nullptr;
}
std::unique_ptr<net::ProxyClientSocket> CreateProxyClientSocket(
std::unique_ptr<net::StreamSocket> stream_socket,
diff --git a/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc b/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc
index 417d22e213e..ef8acf121ef 100644
--- a/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc
+++ b/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc
@@ -101,7 +101,7 @@ class ManagedValueStoreCache::ExtensionTracker
ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver>
extension_registry_observer_;
policy::SchemaRegistry* schema_registry_;
- base::WeakPtrFactory<ExtensionTracker> weak_factory_;
+ base::WeakPtrFactory<ExtensionTracker> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ExtensionTracker);
};
@@ -112,8 +112,7 @@ ManagedValueStoreCache::ExtensionTracker::ExtensionTracker(
: profile_(profile),
policy_domain_(policy_domain),
extension_registry_observer_(this),
- schema_registry_(profile->GetPolicySchemaRegistryService()->registry()),
- weak_factory_(this) {
+ schema_registry_(profile->GetPolicySchemaRegistryService()->registry()) {
extension_registry_observer_.Add(ExtensionRegistry::Get(profile_));
// Load schemas when the extension system is ready. It might be ready now.
ExtensionSystem::Get(profile_)->ready().Post(
diff --git a/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc b/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc
index 52fdd9b11e4..c6b32bc49be 100644
--- a/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc
@@ -8,6 +8,7 @@
#include "base/json/json_writer.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
+#include "base/task/post_task.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/storage/settings_sync_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
@@ -31,6 +32,7 @@
#include "components/sync/model/sync_error_factory.h"
#include "components/sync/model/sync_error_factory_mock.h"
#include "components/sync/model/syncable_service.h"
+#include "extensions/browser/api/storage/backend_task_runner.h"
#include "extensions/browser/api/storage/settings_namespace.h"
#include "extensions/browser/api/storage/storage_frontend.h"
#include "extensions/browser/extension_system.h"
@@ -111,19 +113,65 @@ class ExtensionSettingsApiTest : public ExtensionApiTest {
settings_namespace, normal_action, incognito_action, NULL, true);
}
- syncer::SyncableService* GetSyncableService() {
- return settings_sync_util::GetSyncableService(browser()->profile(),
- kModelType);
+ static void InitSyncOnBackgroundSequence(
+ base::OnceCallback<base::WeakPtr<syncer::SyncableService>()>
+ syncable_service_provider,
+ syncer::SyncChangeProcessor* sync_processor) {
+ DCHECK(GetBackendTaskRunner()->RunsTasksInCurrentSequence());
+
+ base::WeakPtr<syncer::SyncableService> syncable_service =
+ std::move(syncable_service_provider).Run();
+ DCHECK(syncable_service.get());
+ EXPECT_FALSE(
+ syncable_service
+ ->MergeDataAndStartSyncing(
+ kModelType, syncer::SyncDataList(),
+ std::make_unique<syncer::SyncChangeProcessorWrapperForTest>(
+ sync_processor),
+ std::make_unique<syncer::SyncErrorFactoryMock>())
+ .error()
+ .IsSet());
}
void InitSync(syncer::SyncChangeProcessor* sync_processor) {
base::RunLoop().RunUntilIdle();
- InitSyncWithSyncableService(sync_processor, GetSyncableService());
+
+ base::RunLoop loop;
+ GetBackendTaskRunner()->PostTaskAndReply(
+ FROM_HERE,
+ base::BindOnce(&InitSyncOnBackgroundSequence,
+ settings_sync_util::GetSyncableServiceProvider(
+ profile(), kModelType),
+ sync_processor),
+ loop.QuitClosure());
+ loop.Run();
+ }
+
+ static void SendChangesOnBackgroundSequence(
+ base::OnceCallback<base::WeakPtr<syncer::SyncableService>()>
+ syncable_service_provider,
+ const syncer::SyncChangeList& change_list) {
+ DCHECK(GetBackendTaskRunner()->RunsTasksInCurrentSequence());
+
+ base::WeakPtr<syncer::SyncableService> syncable_service =
+ std::move(syncable_service_provider).Run();
+ DCHECK(syncable_service.get());
+ EXPECT_FALSE(
+ syncable_service->ProcessSyncChanges(FROM_HERE, change_list).IsSet());
}
void SendChanges(const syncer::SyncChangeList& change_list) {
base::RunLoop().RunUntilIdle();
- SendChangesToSyncableService(change_list, GetSyncableService());
+
+ base::RunLoop loop;
+ GetBackendTaskRunner()->PostTaskAndReply(
+ FROM_HERE,
+ base::BindOnce(&SendChangesOnBackgroundSequence,
+ settings_sync_util::GetSyncableServiceProvider(
+ profile(), kModelType),
+ change_list),
+ loop.QuitClosure());
+ loop.Run();
}
void SetPolicies(const base::DictionaryValue& policies) {
@@ -178,26 +226,9 @@ class ExtensionSettingsApiTest : public ExtensionApiTest {
return message_json;
}
- void InitSyncWithSyncableService(
- syncer::SyncChangeProcessor* sync_processor,
- syncer::SyncableService* settings_service) {
- EXPECT_FALSE(settings_service
- ->MergeDataAndStartSyncing(
- kModelType, syncer::SyncDataList(),
- std::unique_ptr<syncer::SyncChangeProcessor>(
- new syncer::SyncChangeProcessorWrapperForTest(
- sync_processor)),
- std::unique_ptr<syncer::SyncErrorFactory>(
- new syncer::SyncErrorFactoryMock()))
- .error()
- .IsSet());
- }
-
void SendChangesToSyncableService(
const syncer::SyncChangeList& change_list,
syncer::SyncableService* settings_service) {
- EXPECT_FALSE(
- settings_service->ProcessSyncChanges(FROM_HERE, change_list).IsSet());
}
protected:
diff --git a/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc b/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc
index 29cdc5a7efd..3d81dd4973e 100644
--- a/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc
@@ -1320,11 +1320,7 @@ TEST_F(ExtensionSettingsSyncTest,
Manifest::Type type = Manifest::TYPE_LEGACY_PACKAGED_APP;
// This value should be larger than the limit in sync_storage_backend.cc.
- std::string string_10k;
- for (size_t i = 0; i < 10000; ++i) {
- string_10k.append("a");
- }
- base::Value large_value(string_10k);
+ base::Value large_value(std::string(10000, 'a'));
PostOnBackendSequenceAndWait(FROM_HERE, [&, this]() {
GetSyncableService(model_type)
diff --git a/chromium/chrome/browser/extensions/api/storage/settings_sync_util.cc b/chromium/chrome/browser/extensions/api/storage/settings_sync_util.cc
index 04ae94c54d0..c8045c759f0 100644
--- a/chromium/chrome/browser/extensions/api/storage/settings_sync_util.cc
+++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_util.cc
@@ -119,16 +119,6 @@ syncer::SyncChange CreateDelete(
CreateData(extension_id, key, no_value, type));
}
-syncer::SyncableService* GetSyncableService(content::BrowserContext* context,
- syncer::ModelType type) {
- DCHECK(IsOnBackendSequence());
- DCHECK(type == syncer::APP_SETTINGS || type == syncer::EXTENSION_SETTINGS);
- StorageFrontend* frontend = StorageFrontend::Get(context);
- SyncValueStoreCache* sync_cache = static_cast<SyncValueStoreCache*>(
- frontend->GetValueStoreCache(settings_namespace::SYNC));
- return sync_cache->GetSyncableService(type);
-}
-
base::OnceCallback<base::WeakPtr<syncer::SyncableService>()>
GetSyncableServiceProvider(content::BrowserContext* context,
syncer::ModelType type) {
diff --git a/chromium/chrome/browser/extensions/api/storage/settings_sync_util.h b/chromium/chrome/browser/extensions/api/storage/settings_sync_util.h
index 7aaf63708a1..73d352e0e08 100644
--- a/chromium/chrome/browser/extensions/api/storage/settings_sync_util.h
+++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_util.h
@@ -55,12 +55,6 @@ syncer::SyncChange CreateDelete(
const std::string& key,
syncer::ModelType type);
-// Returns the sync service for settings. Must be called on the backend
-// sequence. |type| must be either APP_SETTINGS or EXTENSION_SETTINGS.
-// TODO(crbug.com/933874): Remove once the old sync controller is removed.
-syncer::SyncableService* GetSyncableService(content::BrowserContext* context,
- syncer::ModelType type);
-
// Returns a callback that provides a SyncableService. The function must be
// called on the UI thread and |type| must be either APP_SETTINGS or
// EXTENSION_SETTINGS. The returned callback must be called on the backend
diff --git a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc
index f23382b04c8..a764287ec52 100644
--- a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc
+++ b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc
@@ -39,7 +39,7 @@ SyncValueStoreCache::SyncValueStoreCache(
scoped_refptr<ValueStoreFactory> factory,
scoped_refptr<SettingsObserverList> observers,
const base::FilePath& profile_path)
- : initialized_(false), weak_ptr_factory_(this) {
+ : initialized_(false) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// This post is safe since the destructor can only be invoked from the
diff --git a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h
index 39c0dab7633..1e4225c0735 100644
--- a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h
+++ b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h
@@ -55,7 +55,7 @@ class SyncValueStoreCache : public ValueStoreCache {
bool initialized_;
std::unique_ptr<SyncStorageBackend> app_backend_;
std::unique_ptr<SyncStorageBackend> extension_backend_;
- base::WeakPtrFactory<SyncValueStoreCache> weak_ptr_factory_;
+ base::WeakPtrFactory<SyncValueStoreCache> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SyncValueStoreCache);
};
diff --git a/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.cc b/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.cc
index 9e81f0a33ed..3841b7adf65 100644
--- a/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.cc
@@ -10,7 +10,6 @@
#include "chrome/browser/prerender/prerender_contents.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
-#include "content/public/browser/stream_info.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/guest_view/mime_handler_view/mime_handler_stream_manager.h"
@@ -26,7 +25,6 @@ void StreamsPrivateAPI::SendExecuteMimeTypeHandlerEvent(
int frame_tree_node_id,
int render_process_id,
int render_frame_id,
- std::unique_ptr<content::StreamInfo> stream,
content::mojom::TransferrableURLLoaderPtr transferrable_loader,
const GURL& original_url) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
@@ -69,9 +67,9 @@ void StreamsPrivateAPI::SendExecuteMimeTypeHandlerEvent(
GURL handler_url(Extension::GetBaseURLFromExtensionId(extension_id).spec() +
handler->handler_url());
int tab_id = ExtensionTabUtil::GetTabId(web_contents);
- std::unique_ptr<StreamContainer> stream_container(new StreamContainer(
- std::move(stream), tab_id, embedded, handler_url, extension_id,
- std::move(transferrable_loader), original_url));
+ std::unique_ptr<StreamContainer> stream_container(
+ new StreamContainer(tab_id, embedded, handler_url, extension_id,
+ std::move(transferrable_loader), original_url));
MimeHandlerStreamManager::Get(browser_context)
->AddStream(view_id, std::move(stream_container), frame_tree_node_id,
render_process_id, render_frame_id);
diff --git a/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h b/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h
index 32908bcff27..5506ae5e985 100644
--- a/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h
+++ b/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h
@@ -11,18 +11,13 @@
#include "base/macros.h"
#include "content/public/common/transferrable_url_loader.mojom.h"
-namespace content {
-struct StreamInfo;
-}
-
namespace extensions {
// TODO(devlin): This is now only used for the MimeTypesHandler API. We should
// rename and move it to make that clear. https://crbug.com/890401.
class StreamsPrivateAPI {
public:
- // Send the onExecuteMimeTypeHandler event to |extension_id|.
- // The data for the document will be readable from |stream|. If the viewer is
+ // Send the onExecuteMimeTypeHandler event to |extension_id|. If the viewer is
// being opened in a BrowserPlugin, specify a non-empty |view_id| of the
// plugin. |embedded| should be set to whether the document is embedded
// within another document. The |frame_tree_node_id| parameter is used for
@@ -41,7 +36,6 @@ class StreamsPrivateAPI {
int frame_tree_node_id,
int render_process_id,
int render_frame_id,
- std::unique_ptr<content::StreamInfo> stream,
content::mojom::TransferrableURLLoaderPtr transferrable_loader,
const GURL& original_url);
};
diff --git a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.cc b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.cc
index ee22cb179bf..926161b9923 100644
--- a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.cc
+++ b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.cc
@@ -159,7 +159,7 @@ void SystemIndicatorManager::SetSystemIndicatorDynamicIcon(
const Extension& extension,
gfx::Image icon) {
DCHECK(thread_checker_.CalledOnValidThread());
- DCHECK(base::ContainsKey(system_indicators_, extension.id()));
+ DCHECK(base::Contains(system_indicators_, extension.id()));
auto& indicator = system_indicators_[extension.id()];
indicator.dynamic_icon = icon;
if (indicator.system_tray_indicator)
@@ -170,7 +170,7 @@ void SystemIndicatorManager::SetSystemIndicatorEnabled(
const Extension& extension,
bool is_enabled) {
DCHECK(thread_checker_.CalledOnValidThread());
- DCHECK(base::ContainsKey(system_indicators_, extension.id()));
+ DCHECK(base::Contains(system_indicators_, extension.id()));
auto& indicator = system_indicators_[extension.id()];
bool is_already_enabled = !!indicator.system_tray_indicator;
if (is_already_enabled == is_enabled)
@@ -192,7 +192,7 @@ void SystemIndicatorManager::OnExtensionLoaded(
content::BrowserContext* browser_context,
const Extension* extension) {
DCHECK(thread_checker_.CalledOnValidThread());
- DCHECK(!base::ContainsKey(system_indicators_, extension->id()));
+ DCHECK(!base::Contains(system_indicators_, extension->id()));
const ExtensionIconSet* indicator_icon =
SystemIndicatorHandler::GetSystemIndicatorIcon(*extension);
if (!indicator_icon)
diff --git a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tabs_owner.cc b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tabs_owner.cc
index 97bf387ec8d..561d3a7dbdb 100644
--- a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tabs_owner.cc
+++ b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tabs_owner.cc
@@ -15,6 +15,7 @@
#include "content/public/browser/web_contents.h"
#include "extensions/browser/extension_host.h"
#include "extensions/browser/process_manager.h"
+#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
using content::WebContents;
@@ -81,23 +82,28 @@ void OffscreenTabsOwner::RequestMediaAccessPermission(
if (tab_capture_registry &&
tab_capture_registry->VerifyRequest(
request.render_process_id, request.render_frame_id, extension_id)) {
- if (request.audio_type == blink::MEDIA_GUM_TAB_AUDIO_CAPTURE) {
+ if (request.audio_type ==
+ blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE) {
devices.push_back(blink::MediaStreamDevice(
- blink::MEDIA_GUM_TAB_AUDIO_CAPTURE, std::string(), std::string()));
+ blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE, std::string(),
+ std::string()));
}
- if (request.video_type == blink::MEDIA_GUM_TAB_VIDEO_CAPTURE) {
+ if (request.video_type ==
+ blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE) {
devices.push_back(blink::MediaStreamDevice(
- blink::MEDIA_GUM_TAB_VIDEO_CAPTURE, std::string(), std::string()));
+ blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE, std::string(),
+ std::string()));
}
}
DVLOG(2) << "Allowing " << devices.size()
<< " capture devices for OffscreenTab content.";
- std::move(callback).Run(devices,
- devices.empty() ? blink::MEDIA_DEVICE_INVALID_STATE
- : blink::MEDIA_DEVICE_OK,
- nullptr);
+ std::move(callback).Run(
+ devices,
+ devices.empty() ? blink::mojom::MediaStreamRequestResult::INVALID_STATE
+ : blink::mojom::MediaStreamRequestResult::OK,
+ nullptr);
}
void OffscreenTabsOwner::DestroyTab(OffscreenTab* tab) {
diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc
index 911f68fddde..9a140c10ead 100644
--- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc
+++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc
@@ -251,11 +251,11 @@ bool TabCaptureRegistry::VerifyRequest(
void TabCaptureRegistry::OnRequestUpdate(
int target_render_process_id,
int target_render_frame_id,
- blink::MediaStreamType stream_type,
+ blink::mojom::MediaStreamType stream_type,
const content::MediaRequestState new_state) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (stream_type != blink::MEDIA_GUM_TAB_VIDEO_CAPTURE &&
- stream_type != blink::MEDIA_GUM_TAB_AUDIO_CAPTURE) {
+ if (stream_type != blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE &&
+ stream_type != blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE) {
return;
}
diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h
index e5733c0b3c2..5f02c884095 100644
--- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h
+++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h
@@ -99,7 +99,7 @@ class TabCaptureRegistry : public BrowserContextKeyedAPI,
// MediaCaptureDevicesDispatcher::Observer implementation.
void OnRequestUpdate(int target_render_process_id,
int target_render_frame_id,
- blink::MediaStreamType stream_type,
+ blink::mojom::MediaStreamType stream_type,
const content::MediaRequestState state) override;
// Send a StatusChanged event containing the current state of |request|.
diff --git a/chromium/chrome/browser/extensions/api/tabs/app_base_window.cc b/chromium/chrome/browser/extensions/api/tabs/app_base_window.cc
index 324756e61ba..fd82bdb14ba 100644
--- a/chromium/chrome/browser/extensions/api/tabs/app_base_window.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/app_base_window.cc
@@ -105,12 +105,12 @@ void AppBaseWindow::FlashFrame(bool flash) {
GetBaseWindow()->FlashFrame(flash);
}
-bool AppBaseWindow::IsAlwaysOnTop() const {
- return GetBaseWindow()->IsAlwaysOnTop();
+ui::ZOrderLevel AppBaseWindow::GetZOrderLevel() const {
+ return GetBaseWindow()->GetZOrderLevel();
}
-void AppBaseWindow::SetAlwaysOnTop(bool always_on_top) {
- GetBaseWindow()->SetAlwaysOnTop(always_on_top);
+void AppBaseWindow::SetZOrderLevel(ui::ZOrderLevel level) {
+ GetBaseWindow()->SetZOrderLevel(level);
}
NativeAppWindow* AppBaseWindow::GetBaseWindow() const {
diff --git a/chromium/chrome/browser/extensions/api/tabs/app_base_window.h b/chromium/chrome/browser/extensions/api/tabs/app_base_window.h
index d9ccfb599bb..7e17b858a29 100644
--- a/chromium/chrome/browser/extensions/api/tabs/app_base_window.h
+++ b/chromium/chrome/browser/extensions/api/tabs/app_base_window.h
@@ -45,8 +45,8 @@ class AppBaseWindow : public ui::BaseWindow {
void Restore() override;
void SetBounds(const gfx::Rect& bounds) override;
void FlashFrame(bool flash) override;
- bool IsAlwaysOnTop() const override;
- void SetAlwaysOnTop(bool always_on_top) override;
+ ui::ZOrderLevel GetZOrderLevel() const override;
+ void SetZOrderLevel(ui::ZOrderLevel order) override;
NativeAppWindow* GetBaseWindow() const;
diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc
index bb3a4f05a79..7433a5793f0 100644
--- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc
@@ -26,7 +26,6 @@
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/api/tabs/tabs_constants.h"
#include "chrome/browser/extensions/api/tabs/tabs_util.h"
#include "chrome/browser/extensions/api/tabs/windows_util.h"
@@ -68,8 +67,6 @@
#include "components/zoom/zoom_controller.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
-#include "content/public/browser/notification_details.h"
-#include "content/public/browser/notification_source.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
@@ -222,15 +219,9 @@ void AssignOptionalValue(const std::unique_ptr<T>& source,
*destination = std::make_unique<T>(*source);
}
-void ReportRequestedWindowState(windows::WindowState state) {
- UMA_HISTOGRAM_ENUMERATION("TabsApi.RequestedWindowState", state,
- windows::WINDOW_STATE_LAST + 1);
-}
-
ui::WindowShowState ConvertToWindowShowState(windows::WindowState state) {
switch (state) {
case windows::WINDOW_STATE_NORMAL:
- case windows::WINDOW_STATE_DOCKED:
return ui::SHOW_STATE_NORMAL;
case windows::WINDOW_STATE_MINIMIZED:
return ui::SHOW_STATE_MINIMIZED;
@@ -264,7 +255,6 @@ bool IsValidStateForWindowsCreateFunction(
// If maximised/fullscreen, default focused state should be focused.
return !(create_data->focused && !*create_data->focused) && !has_bound;
case windows::WINDOW_STATE_NORMAL:
- case windows::WINDOW_STATE_DOCKED:
case windows::WINDOW_STATE_NONE:
return true;
}
@@ -525,10 +515,6 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() {
std::string extension_id;
if (create_data) {
- // Report UMA stats to decide when to remove the deprecated "docked" windows
- // state (crbug.com/703733).
- ReportRequestedWindowState(create_data->state);
-
// Figure out window type before figuring out bounds so that default
// bounds can be set according to the window type.
switch (create_data->type) {
@@ -675,10 +661,6 @@ ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() {
return RespondNow(Error(error));
}
- // Report UMA stats to decide when to remove the deprecated "docked" windows
- // state (crbug.com/703733).
- ReportRequestedWindowState(params->update_info.state);
-
// Don't allow locked fullscreen operations on a window without the proper
// permission (also don't allow any operations on a locked window if the
// extension doesn't have the permission).
@@ -1711,7 +1693,7 @@ void TabsCaptureVisibleTabFunction::OnCaptureSuccess(const SkBitmap& bitmap) {
return;
}
- Respond(OneArgument(std::make_unique<base::Value>(base64_result)));
+ Respond(OneArgument(std::make_unique<base::Value>(std::move(base64_result))));
}
void TabsCaptureVisibleTabFunction::OnCaptureFailure(CaptureResult result) {
@@ -1785,7 +1767,7 @@ ExtensionFunction::ResponseAction TabsDetectLanguageFunction::Run() {
Error(tabs_constants::kCannotDetermineLanguageOfUnloadedTab));
}
- AddRef(); // Balanced in GotLanguage().
+ AddRef(); // Balanced in RespondWithLanguage().
ChromeTranslateClient* chrome_translate_client =
ChromeTranslateClient::FromWebContents(contents);
@@ -1797,45 +1779,52 @@ ExtensionFunction::ResponseAction TabsDetectLanguageFunction::Run() {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
- &TabsDetectLanguageFunction::GotLanguage, this,
+ &TabsDetectLanguageFunction::RespondWithLanguage, this,
chrome_translate_client->GetLanguageState().original_language()));
return RespondLater();
}
- // The tab contents does not know its language yet. Let's wait until it
+
+ // The tab contents does not know its language yet. Let's wait until it
// receives it, or until the tab is closed/navigates to some other page.
- registrar_.Add(this, chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
- content::Source<WebContents>(contents));
- registrar_.Add(
- this, chrome::NOTIFICATION_TAB_CLOSING,
- content::Source<NavigationController>(&(contents->GetController())));
- registrar_.Add(
- this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
- content::Source<NavigationController>(&(contents->GetController())));
+
+ // Observe the WebContents' lifetime and navigations.
+ Observe(contents);
+ // Wait until the language is determined.
+ chrome_translate_client->translate_driver().AddObserver(this);
+ is_observing_ = true;
+
return RespondLater();
}
-void TabsDetectLanguageFunction::Observe(
- int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) {
- std::string language;
- if (type == chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED) {
- const translate::LanguageDetectionDetails* lang_det_details =
- content::Details<const translate::LanguageDetectionDetails>(details)
- .ptr();
- language = lang_det_details->adopted_language;
- }
+void TabsDetectLanguageFunction::NavigationEntryCommitted(
+ const content::LoadCommittedDetails& load_details) {
+ // Call RespondWithLanguage() with an empty string as we want to guarantee the
+ // callback is called for every API call the extension made.
+ RespondWithLanguage(std::string());
+}
- registrar_.RemoveAll();
+void TabsDetectLanguageFunction::WebContentsDestroyed() {
+ // Call RespondWithLanguage() with an empty string as we want to guarantee the
+ // callback is called for every API call the extension made.
+ RespondWithLanguage(std::string());
+}
- // Call GotLanguage in all cases as we want to guarantee the callback is
- // called for every API call the extension made.
- GotLanguage(language);
+void TabsDetectLanguageFunction::OnLanguageDetermined(
+ const translate::LanguageDetectionDetails& details) {
+ RespondWithLanguage(details.adopted_language);
}
-void TabsDetectLanguageFunction::GotLanguage(const std::string& language) {
- Respond(OneArgument(std::make_unique<base::Value>(language)));
+void TabsDetectLanguageFunction::RespondWithLanguage(
+ const std::string& language) {
+ // Stop observing.
+ if (is_observing_) {
+ ChromeTranslateClient::FromWebContents(web_contents())
+ ->translate_driver()
+ .RemoveObserver(this);
+ Observe(nullptr);
+ }
+ Respond(OneArgument(std::make_unique<base::Value>(language)));
Release(); // Balanced in Run()
}
diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h
index 2c8f067fba7..37c2da5cf71 100644
--- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h
+++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h
@@ -11,9 +11,9 @@
#include "base/compiler_specific.h"
#include "chrome/browser/extensions/chrome_extension_function_details.h"
#include "chrome/common/extensions/api/tabs.h"
+#include "components/translate/content/browser/content_translate_driver.h"
#include "components/zoom/zoom_controller.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
+#include "content/public/browser/web_contents_observer.h"
#include "extensions/browser/api/execute_code_function.h"
#include "extensions/browser/api/web_contents_capture_client.h"
#include "extensions/browser/extension_function.h"
@@ -180,17 +180,30 @@ class TabsRemoveFunction : public UIThreadExtensionFunction {
bool RemoveTab(int tab_id, std::string* error);
DECLARE_EXTENSION_FUNCTION("tabs.remove", TABS_REMOVE)
};
-class TabsDetectLanguageFunction : public UIThreadExtensionFunction,
- public content::NotificationObserver {
+class TabsDetectLanguageFunction
+ : public UIThreadExtensionFunction,
+ public content::WebContentsObserver,
+ public translate::ContentTranslateDriver::Observer {
private:
~TabsDetectLanguageFunction() override {}
ResponseAction Run() override;
- void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) override;
- void GotLanguage(const std::string& language);
- content::NotificationRegistrar registrar_;
+ // content::WebContentsObserver:
+ void NavigationEntryCommitted(
+ const content::LoadCommittedDetails& load_details) override;
+ void WebContentsDestroyed() override;
+
+ // translate::ContentTranslateDriver::Observer:
+ void OnLanguageDetermined(
+ const translate::LanguageDetectionDetails& details) override;
+
+ // Resolves the API call with the detected |language|.
+ void RespondWithLanguage(const std::string& language);
+
+ // Indicates if this instance is observing the tabs' WebContents and the
+ // ContentTranslateDriver, in which case the observers must be unregistered.
+ bool is_observing_ = false;
+
DECLARE_EXTENSION_FUNCTION("tabs.detectLanguage", TABS_DETECTLANGUAGE)
};
diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc
index 7380061d7fa..60915b4d639 100644
--- a/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc
@@ -255,11 +255,11 @@ TEST_F(TabsApiUnitTest, QueryWithHostPermission) {
int first_tab_id = -1;
ASSERT_TRUE(first_tab_info->GetInteger("id", &first_tab_id));
- EXPECT_TRUE(base::ContainsValue(expected_tabs_ids, first_tab_id));
+ EXPECT_TRUE(base::Contains(expected_tabs_ids, first_tab_id));
int third_tab_id = -1;
ASSERT_TRUE(third_tab_info->GetInteger("id", &third_tab_id));
- EXPECT_TRUE(base::ContainsValue(expected_tabs_ids, third_tab_id));
+ EXPECT_TRUE(base::Contains(expected_tabs_ids, third_tab_id));
}
while (!browser()->tab_strip_model()->empty())
browser()->tab_strip_model()->DetachWebContentsAt(0);
diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc
index 6539ae0132f..0a076f31c73 100644
--- a/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc
@@ -4,8 +4,8 @@
#include "chrome/browser/extensions/api/tabs/tabs_util.h"
+#include "ash/public/cpp/window_pin_type.h"
#include "ash/public/cpp/window_properties.h"
-#include "ash/public/interfaces/window_pin_type.mojom.h"
#include "base/metrics/histogram_macros.h"
#include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
#include "chrome/browser/chromeos/arc/arc_session_manager.h"
@@ -20,7 +20,6 @@
#include "ui/aura/window.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/clipboard_types.h"
-#include "ui/base/ui_base_features.h"
namespace extensions {
namespace tabs_util {
@@ -39,22 +38,19 @@ void SetLockedFullscreenState(Browser* browser, bool locked) {
aura::Window* window = browser->window()->GetNativeWindow();
// TRUSTED_PINNED is used here because that one locks the window fullscreen
// without allowing the user to exit (as opposed to regular PINNED).
- window->SetProperty(ash::kWindowPinTypeKey,
- locked ? ash::mojom::WindowPinType::TRUSTED_PINNED
- : ash::mojom::WindowPinType::NONE);
+ window->SetProperty(
+ ash::kWindowPinTypeKey,
+ locked ? ash::WindowPinType::kTrustedPinned : ash::WindowPinType::kNone);
// Update the set of available browser commands.
browser->command_controller()->LockedFullscreenStateChanged();
// Disallow screenshots in locked fullscreen mode.
- // TODO(isandrk, 816900): ChromeScreenshotGrabber isn't implemented in Mash
- // yet, remove this conditional when it becomes available.
- if (!features::IsMultiProcessMash())
- ChromeScreenshotGrabber::Get()->set_screenshots_allowed(!locked);
+ ChromeScreenshotGrabber::Get()->set_screenshots_allowed(!locked);
// Reset the clipboard and kill dev tools when entering or exiting locked
// fullscreen (security concerns).
- ui::Clipboard::GetForCurrentThread()->Clear(ui::CLIPBOARD_TYPE_COPY_PASTE);
+ ui::Clipboard::GetForCurrentThread()->Clear(ui::ClipboardType::kCopyPaste);
content::DevToolsAgentHost::DetachAllClients();
// Disable ARC while in the locked fullscreen mode.
diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc
index 05d0922f0db..b27e4bca86e 100644
--- a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc
@@ -16,7 +16,6 @@
#include "chrome/browser/extensions/api/tabs/windows_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_tab_util.h"
-#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/window_controller.h"
#include "chrome/browser/extensions/window_controller_list.h"
#include "chrome/browser/profiles/profile.h"
@@ -25,6 +24,7 @@
#include "content/public/browser/notification_service.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/browser/event_router.h"
+#include "extensions/browser/extension_util.h"
#include "extensions/common/constants.h"
using content::BrowserContext;
diff --git a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc
index 9f1e8e13b1f..1dc03aa89af 100644
--- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc
@@ -79,7 +79,6 @@ bool CommandSupportsArguments(const std::string& name) {
}
void NotifyProcessOutput(content::BrowserContext* browser_context,
- const std::string& extension_id,
int tab_id,
const std::string& terminal_id,
const std::string& output_type,
@@ -87,8 +86,8 @@ void NotifyProcessOutput(content::BrowserContext* browser_context,
if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&NotifyProcessOutput, browser_context, extension_id,
- tab_id, terminal_id, output_type, output));
+ base::BindOnce(&NotifyProcessOutput, browser_context, tab_id,
+ terminal_id, output_type, output));
return;
}
@@ -104,7 +103,7 @@ void NotifyProcessOutput(content::BrowserContext* browser_context,
std::unique_ptr<extensions::Event> event(new extensions::Event(
extensions::events::TERMINAL_PRIVATE_ON_PROCESS_OUTPUT,
terminal_private::OnProcessOutput::kEventName, std::move(args)));
- event_router->DispatchEventToExtension(extension_id, std::move(event));
+ event_router->BroadcastEvent(std::move(event));
}
}
@@ -177,14 +176,11 @@ TerminalPrivateOpenTerminalProcessFunction::Run() {
FROM_HERE,
base::BindOnce(
&TerminalPrivateOpenTerminalProcessFunction::OpenOnRegistryTaskRunner,
- this,
- base::Bind(&NotifyProcessOutput, browser_context(), extension_id(),
- tab_id),
+ this, base::Bind(&NotifyProcessOutput, browser_context(), tab_id),
base::Bind(
&TerminalPrivateOpenTerminalProcessFunction::RespondOnUIThread,
this),
- arguments,
- user_id_hash));
+ arguments, user_id_hash));
return RespondLater();
}
diff --git a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/OWNERS b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/OWNERS
index 9834f7a713e..94fbd75ac8d 100644
--- a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/OWNERS
+++ b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/OWNERS
@@ -1,3 +1,3 @@
-file://ash/keyboard/ui/OWNERS
+file://ash/keyboard/OWNERS
# COMPONENT: UI>Input>VirtualKeyboard
diff --git a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc
index 812e63a5eb9..7f27757fb74 100644
--- a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc
+++ b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc
@@ -9,7 +9,7 @@
#include <utility>
#include "ash/public/cpp/keyboard/keyboard_switches.h"
-#include "ash/public/interfaces/keyboard_controller_types.mojom.h"
+#include "ash/public/cpp/keyboard/keyboard_types.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/feature_list.h"
@@ -26,7 +26,7 @@
#include "chromeos/constants/chromeos_features.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "extensions/browser/event_router.h"
#include "extensions/common/api/virtual_keyboard.h"
#include "extensions/common/api/virtual_keyboard_private.h"
@@ -58,16 +58,16 @@ std::string GenerateFeatureFlag(const std::string& feature, bool enabled) {
return feature + (enabled ? "-enabled" : "-disabled");
}
-keyboard::mojom::ContainerType ConvertKeyboardModeToContainerType(int mode) {
+keyboard::ContainerType ConvertKeyboardModeToContainerType(int mode) {
switch (mode) {
case keyboard_api::KEYBOARD_MODE_FULL_WIDTH:
- return keyboard::mojom::ContainerType::kFullWidth;
+ return keyboard::ContainerType::kFullWidth;
case keyboard_api::KEYBOARD_MODE_FLOATING:
- return keyboard::mojom::ContainerType::kFloating;
+ return keyboard::ContainerType::kFloating;
}
NOTREACHED();
- return keyboard::mojom::ContainerType::kFullWidth;
+ return keyboard::ContainerType::kFullWidth;
}
// Returns the ui::TextInputClient of the active InputMethod or nullptr.
@@ -152,7 +152,7 @@ std::string GetKeyboardLayout() {
// TODO(bshe): layout string is currently hard coded. We should use more
// standard keyboard layouts.
return ChromeKeyboardControllerClient::Get()->IsEnableFlagSet(
- keyboard::mojom::KeyboardEnableFlag::kAccessibilityEnabled)
+ keyboard::KeyboardEnableFlag::kAccessibilityEnabled)
? "system-qwerty"
: "qwerty";
}
@@ -172,11 +172,10 @@ ChromeVirtualKeyboardDelegate::~ChromeVirtualKeyboardDelegate() {}
void ChromeVirtualKeyboardDelegate::GetKeyboardConfig(
OnKeyboardSettingsCallback on_settings_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- if (!audio_system_)
- audio_system_ = audio::CreateAudioSystem(
- content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->Clone());
+ if (!audio_system_) {
+ audio_system_ =
+ audio::CreateAudioSystem(content::GetSystemConnector()->Clone());
+ }
audio_system_->HasInputDevices(
base::BindOnce(&ChromeVirtualKeyboardDelegate::OnHasInputDevices,
weak_this_, std::move(on_settings_callback)));
@@ -196,7 +195,7 @@ bool ChromeVirtualKeyboardDelegate::HideKeyboard() {
// Pass HIDE_REASON_MANUAL since calls to HideKeyboard as part of this API
// would be user generated.
- keyboard_client->HideKeyboard(ash::mojom::HideReason::kUser);
+ keyboard_client->HideKeyboard(ash::HideReason::kUser);
return true;
}
@@ -254,7 +253,7 @@ bool ChromeVirtualKeyboardDelegate::ShowLanguageSettings() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
auto* keyboard_client = ChromeKeyboardControllerClient::Get();
if (keyboard_client->is_keyboard_enabled())
- keyboard_client->HideKeyboard(ash::mojom::HideReason::kUser);
+ keyboard_client->HideKeyboard(ash::HideReason::kUser);
base::RecordAction(base::UserMetricsAction("OpenLanguageOptionsDialog"));
chrome::ShowSettingsSubPageForProfile(ProfileManager::GetActiveUserProfile(),
@@ -310,7 +309,7 @@ bool ChromeVirtualKeyboardDelegate::SetDraggableArea(
}
bool ChromeVirtualKeyboardDelegate::SetRequestedKeyboardState(int state_enum) {
- using keyboard::mojom::KeyboardEnableFlag;
+ using keyboard::KeyboardEnableFlag;
auto* client = ChromeKeyboardControllerClient::Get();
keyboard_api::KeyboardState state =
static_cast<keyboard_api::KeyboardState>(state_enum);
@@ -348,10 +347,9 @@ void ChromeVirtualKeyboardDelegate::OnHasInputDevices(
// TODO(bshe): Consolidate a11y, hotrod and normal mode into a mode enum. See
// crbug.com/529474.
- results->SetBoolean(
- "a11ymode",
- keyboard_client->IsEnableFlagSet(
- keyboard::mojom::KeyboardEnableFlag::kAccessibilityEnabled));
+ results->SetBoolean("a11ymode",
+ keyboard_client->IsEnableFlagSet(
+ keyboard::KeyboardEnableFlag::kAccessibilityEnabled));
results->SetBoolean("hotrodmode", g_hotrod_keyboard_enabled);
std::unique_ptr<base::ListValue> features(new base::ListValue());
@@ -365,7 +363,7 @@ void ChromeVirtualKeyboardDelegate::OnHasInputDevices(
features->AppendString(GenerateFeatureFlag("virtualkeyboardmdui", true));
features->AppendString(GenerateFeatureFlag("imeservice", true));
- keyboard::mojom::KeyboardConfig config = keyboard_client->GetKeyboardConfig();
+ keyboard::KeyboardConfig config = keyboard_client->GetKeyboardConfig();
// TODO(oka): Change this to use config.voice_input.
features->AppendString(GenerateFeatureFlag(
"voiceinput", has_audio_input_devices && config.voice_input));
@@ -412,9 +410,9 @@ ChromeVirtualKeyboardDelegate::RestrictFeatures(
const api::virtual_keyboard::FeatureRestrictions& restrictions =
params.restrictions;
api::virtual_keyboard::FeatureRestrictions update;
- keyboard::mojom::KeyboardConfig current_config =
+ keyboard::KeyboardConfig current_config =
ChromeKeyboardControllerClient::Get()->GetKeyboardConfig();
- keyboard::mojom::KeyboardConfig config(current_config);
+ keyboard::KeyboardConfig config(current_config);
if (restrictions.spell_check_enabled &&
config.spell_check != *restrictions.spell_check_enabled) {
update.spell_check_enabled =
@@ -446,7 +444,7 @@ ChromeVirtualKeyboardDelegate::RestrictFeatures(
config.handwriting = *restrictions.handwriting_enabled;
}
- if (!config.Equals(current_config)) {
+ if (config != current_config) {
ChromeKeyboardControllerClient::Get()->SetKeyboardConfig(config);
// This reloads virtual keyboard even if it exists. This ensures virtual
// keyboard gets the correct state through
diff --git a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc
index 372a0127428..117d716bb22 100644
--- a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc
+++ b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc
@@ -49,10 +49,8 @@ bool FrameNavigationState::IsValidUrl(const GURL& url) {
return true;
}
// Allow about:blank and about:srcdoc.
- if (url.spec() == url::kAboutBlankURL ||
- url.spec() == content::kAboutSrcDocURL) {
+ if (url.IsAboutBlank() || url.IsAboutSrcdoc())
return true;
- }
return allow_extension_scheme_ && url.scheme() == kExtensionScheme;
}
diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc
index 14e565b45b5..b06f9750014 100644
--- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc
@@ -19,7 +19,6 @@
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_browser_main.h"
-#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/download/download_browsertest.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/extensions/api/web_navigation/web_navigation_api.h"
@@ -43,6 +42,7 @@
#include "content/public/common/url_constants.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/download_test_observer.h"
+#include "content/public/test/no_renderer_crashes_assertion.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/extension_system.h"
#include "extensions/common/switches.h"
@@ -66,39 +66,36 @@ namespace {
// |script| in the last committed RVH and resumes the load when a URL ending in
// |until_url_suffix| commits. This class expects |script| to trigger the load
// of an URL ending in |until_url_suffix|.
-class DelayLoadStartAndExecuteJavascript
- : public content::NotificationObserver,
- public content::WebContentsObserver {
+class DelayLoadStartAndExecuteJavascript : public TabStripModelObserver,
+ public content::WebContentsObserver {
public:
- DelayLoadStartAndExecuteJavascript(
- const GURL& delay_url,
- const std::string& script,
- const std::string& until_url_suffix)
+ DelayLoadStartAndExecuteJavascript(Browser* browser,
+ const GURL& delay_url,
+ const std::string& script,
+ const std::string& until_url_suffix)
: content::WebContentsObserver(),
delay_url_(delay_url),
until_url_suffix_(until_url_suffix),
- script_(script),
- has_user_gesture_(false),
- script_was_executed_(false),
- rfh_(nullptr) {
- registrar_.Add(this,
- chrome::NOTIFICATION_TAB_ADDED,
- content::NotificationService::AllSources());
+ script_(script) {
+ tab_strip_observer_.Add(browser->tab_strip_model());
}
+
~DelayLoadStartAndExecuteJavascript() override {}
- void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) override {
- if (type != chrome::NOTIFICATION_TAB_ADDED) {
- NOTREACHED();
+ // TabStripModelObserver:
+ void OnTabStripModelChanged(
+ TabStripModel* tab_strip_model,
+ const TabStripModelChange& change,
+ const TabStripSelectionChange& selection) override {
+ if (change.type() != TabStripModelChange::kInserted)
return;
- }
+
content::WebContentsObserver::Observe(
- content::Details<content::WebContents>(details).ptr());
- registrar_.RemoveAll();
+ change.GetInsert()->contents[0].contents);
+ tab_strip_observer_.RemoveAll();
}
+ // WebContentsObserver:
void DidStartNavigation(
content::NavigationHandle* navigation_handle) override {
if (navigation_handle->GetURL() != delay_url_ || !rfh_)
@@ -127,7 +124,7 @@ class DelayLoadStartAndExecuteJavascript
if (script_was_executed_ &&
base::EndsWith(navigation_handle->GetURL().spec(), until_url_suffix_,
base::CompareCase::SENSITIVE)) {
- content::WebContentsObserver::Observe(NULL);
+ content::WebContentsObserver::Observe(nullptr);
if (throttle_)
throttle_->Unblock();
}
@@ -167,16 +164,16 @@ class DelayLoadStartAndExecuteJavascript
bool throttled_ = false;
};
- content::NotificationRegistrar registrar_;
-
base::WeakPtr<WillStartRequestObserverThrottle> throttle_;
+ ScopedObserver<TabStripModel, TabStripModelObserver> tab_strip_observer_{
+ this};
GURL delay_url_;
std::string until_url_suffix_;
std::string script_;
- bool has_user_gesture_;
- bool script_was_executed_;
- content::RenderFrameHost* rfh_;
+ bool has_user_gesture_ = false;
+ bool script_was_executed_ = false;
+ content::RenderFrameHost* rfh_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(DelayLoadStartAndExecuteJavascript);
};
@@ -498,13 +495,11 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcess) {
// See crossProcess/d.html.
DelayLoadStartAndExecuteJavascript call_script(
- embedded_test_server()->GetURL("/test1"),
- "navigate2()",
+ browser(), embedded_test_server()->GetURL("/test1"), "navigate2()",
"empty.html");
DelayLoadStartAndExecuteJavascript call_script_user_gesture(
- embedded_test_server()->GetURL("/test2"),
- "navigate2()",
+ browser(), embedded_test_server()->GetURL("/test2"), "navigate2()",
"empty.html");
call_script_user_gesture.set_has_user_gesture(true);
@@ -517,14 +512,12 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, DISABLED_CrossProcessFragment) {
// See crossProcessFragment/f.html.
DelayLoadStartAndExecuteJavascript call_script3(
- embedded_test_server()->GetURL("/test3"),
- "updateFragment()",
+ browser(), embedded_test_server()->GetURL("/test3"), "updateFragment()",
base::StringPrintf("f.html?%u#foo", embedded_test_server()->port()));
// See crossProcessFragment/g.html.
DelayLoadStartAndExecuteJavascript call_script4(
- embedded_test_server()->GetURL("/test4"),
- "updateFragment()",
+ browser(), embedded_test_server()->GetURL("/test4"), "updateFragment()",
base::StringPrintf("g.html?%u#foo", embedded_test_server()->port()));
ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcessFragment"))
@@ -536,20 +529,17 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcessHistory) {
// See crossProcessHistory/e.html.
DelayLoadStartAndExecuteJavascript call_script2(
- embedded_test_server()->GetURL("/test2"),
- "updateHistory()",
+ browser(), embedded_test_server()->GetURL("/test2"), "updateHistory()",
"empty.html");
// See crossProcessHistory/h.html.
DelayLoadStartAndExecuteJavascript call_script5(
- embedded_test_server()->GetURL("/test5"),
- "updateHistory()",
+ browser(), embedded_test_server()->GetURL("/test5"), "updateHistory()",
"empty.html");
// See crossProcessHistory/i.html.
DelayLoadStartAndExecuteJavascript call_script6(
- embedded_test_server()->GetURL("/test6"),
- "updateHistory()",
+ browser(), embedded_test_server()->GetURL("/test6"), "updateHistory()",
"empty.html");
ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcessHistory"))
@@ -569,8 +559,15 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, PendingDeletion) {
}
// TODO(jam): http://crbug.com/350550
-#if !(defined(OS_CHROMEOS) && defined(ADDRESS_SANITIZER))
-IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, Crash) {
+// TODO(crbug/974787): Flaky on Win7 debug builds.
+#if (defined(OS_CHROMEOS) && defined(ADDRESS_SANITIZER)) || \
+ (defined(OS_WIN) && !(defined(NDEBUG)))
+#define MAYBE_Crash DISABLED_Crash
+#else
+#define MAYBE_Crash Crash
+#endif
+IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, MAYBE_Crash) {
+ content::ScopedAllowRendererCrashes scoped_allow_renderer_crashes;
ASSERT_TRUE(StartEmbeddedTestServer());
// Wait for the extension to set itself up and return control to us.
@@ -598,6 +595,4 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, Crash) {
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
-#endif
-
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc
index 40ee4b1fb7a..e0dbdfd790e 100644
--- a/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc
@@ -31,13 +31,10 @@
#include "base/values.h"
#include "chrome/browser/content_settings/cookie_settings_factory.h"
#include "chrome/browser/extensions/event_router_forwarder.h"
-#include "chrome/browser/net/chrome_extensions_network_delegate.h"
-#include "chrome/browser/net/chrome_network_delegate.h"
#include "chrome/browser/renderer_host/chrome_navigation_ui_data.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
-#include "components/about_handler/about_protocol_handler.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/prefs/pref_member.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
@@ -53,17 +50,7 @@
#include "extensions/common/extension_messages.h"
#include "extensions/common/features/feature.h"
#include "google_apis/gaia/gaia_urls.h"
-#include "net/base/auth.h"
-#include "net/base/elements_upload_data_stream.h"
-#include "net/base/request_priority.h"
-#include "net/base/upload_bytes_element_reader.h"
-#include "net/base/upload_file_element_reader.h"
-#include "net/dns/mock_host_resolver.h"
-#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
-#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
-#include "net/url_request/url_request_job_factory_impl.h"
-#include "net/url_request/url_request_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest-message.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -108,21 +95,6 @@ namespace {
constexpr const char kExampleUrl[] = "http://example.com";
-static void EventHandledOnIOThread(
- void* profile,
- int worker_thread_id,
- int64_t service_worker_version_id,
- const std::string& extension_id,
- const std::string& event_name,
- const std::string& sub_event_name,
- uint64_t request_id,
- ExtensionWebRequestEventRouter::EventResponse* response) {
- ExtensionWebRequestEventRouter::GetInstance()->OnEventHandled(
- profile, extension_id, event_name, sub_event_name, request_id,
- 0 /* render_process_id */, 0 /* web_view_instance_id */, worker_thread_id,
- service_worker_version_id, response);
-}
-
// Returns whether |warnings| contains an extension for |extension_id|.
bool HasIgnoredAction(const helpers::IgnoredActions& ignored_actions,
const std::string& extension_id,
@@ -136,54 +108,6 @@ bool HasIgnoredAction(const helpers::IgnoredActions& ignored_actions,
return false;
}
-// Parses the JSON data attached to the |message| and tries to return it.
-// |param| must outlive |out|.
-void GetPartOfMessageArguments(IPC::Message* message,
- const base::DictionaryValue** out,
- ExtensionMsg_DispatchEvent::Param* param) {
- ASSERT_EQ(static_cast<uint32_t>(ExtensionMsg_DispatchEvent::ID),
- message->type());
- ASSERT_TRUE(ExtensionMsg_DispatchEvent::Read(message, param));
- const base::ListValue& list = std::get<1>(*param);
- ASSERT_EQ(1u, list.GetSize());
- ASSERT_TRUE(list.GetDictionary(0, out));
-}
-
-base::Value FormBinaryValue(base::StringPiece str) {
- base::Value list(base::Value::Type::LIST);
- list.GetList().emplace_back(base::Value(
- base::Value::BlobStorage(str.data(), str.data() + str.size())));
- return list;
-}
-
-base::Value FormStringValue(base::StringPiece str) {
- base::Value list(base::Value::Type::LIST);
- list.GetList().emplace_back(base::Value(str));
- return list;
-}
-
-// Returns a main-frame request to |url|.
-std::unique_ptr<net::URLRequest> CreateRequestHelper(
- const GURL& url,
- net::TestURLRequestContext* context,
- net::TestDelegate* delegate) {
- CHECK(context);
- CHECK(delegate);
-
- std::unique_ptr<net::URLRequest> request = context->CreateRequest(
- url, net::DEFAULT_PRIORITY, delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
- content::ResourceRequestInfo::AllocateForTesting(
- request.get(), content::ResourceType::kMainFrame, /*context*/ nullptr,
- -1 /* render_process_id */, -1 /* render_view_id */,
- -1 /* render_frame_id */, true /* is_main_frame */,
- content::ResourceInterceptPolicy::kAllowNone, false /* is_async */,
- content::PREVIEWS_OFF,
- ChromeNavigationUIData::CreateForMainFrameNavigation(
- nullptr /* web_contents */, WindowOpenDisposition::CURRENT_TAB,
- 0 /* data_reduction_proxy_page_id */));
- return request;
-}
-
} // namespace
// A mock event router that responds to events with a pre-arranged queue of
@@ -227,354 +151,22 @@ class TestIPCSender : public IPC::Sender {
SentMessages sent_messages_;
};
-class TestLogger : public WebRequestInfoLogger {
- public:
- TestLogger() = default;
- ~TestLogger() override = default;
-
- size_t log_size() const { return events_.size(); }
- void clear() { events_.clear(); }
-
- // WebRequestInfo::Logger:
- void LogEvent(net::NetLogEventType event_type,
- const std::string& extension_id) override {
- events_.push_back({event_type, extension_id});
- }
- void LogBlockedBy(const std::string& blocker_info) override {}
- void LogUnblocked() override {}
-
- private:
- using Event = std::pair<net::NetLogEventType, std::string>;
- std::vector<Event> events_;
-
- DISALLOW_COPY_AND_ASSIGN(TestLogger);
-};
-
class ExtensionWebRequestTest : public testing::Test {
public:
ExtensionWebRequestTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
- profile_manager_(TestingBrowserProcess::GetGlobal()),
- event_router_(new EventRouterForwarder) {}
+ profile_manager_(TestingBrowserProcess::GetGlobal()) {}
protected:
void SetUp() override {
ASSERT_TRUE(profile_manager_.SetUp());
- network_delegate_.reset(new ChromeNetworkDelegate(event_router_.get()));
- network_delegate_->set_profile(&profile_);
- network_delegate_->set_cookie_settings(
- CookieSettingsFactory::GetForProfile(&profile_).get());
- context_.reset(new net::TestURLRequestContext(true));
- context_->set_network_delegate(network_delegate_.get());
- context_->Init();
- }
-
- // Fires a URLRequest with the specified |method|, |content_type| and three
- // elements of upload data: bytes_1, a dummy empty file, bytes_2.
- void FireURLRequestWithData(const std::string& method,
- const char* content_type,
- const std::vector<char>& bytes_1,
- const std::vector<char>& bytes_2);
-
- // Returns a main-frame request to |url|.
- std::unique_ptr<net::URLRequest> CreateRequest(const GURL& url) {
- return CreateRequestHelper(url, context_.get(), &delegate_);
}
content::TestBrowserThreadBundle thread_bundle_;
TestingProfile profile_;
TestingProfileManager profile_manager_;
- net::TestDelegate delegate_;
- TestIPCSender ipc_sender_;
- scoped_refptr<EventRouterForwarder> event_router_;
- std::unique_ptr<ChromeNetworkDelegate> network_delegate_;
- std::unique_ptr<net::TestURLRequestContext> context_;
};
-// Tests that we handle disagreements among extensions about responses to
-// blocking events (redirection) by choosing the response from the
-// most-recently-installed extension.
-TEST_F(ExtensionWebRequestTest, BlockingEventPrecedenceRedirect) {
- std::string extension1_id("1");
- std::string extension2_id("2");
- ExtensionWebRequestEventRouter::RequestFilter filter;
- const std::string kEventName(web_request::OnBeforeRequest::kEventName);
- base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_);
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension1_id, extension1_id, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, ExtraInfoSpec::BLOCKING, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension2_id, extension2_id, events::FOR_TEST, kEventName,
- kEventName + "/2", filter, ExtraInfoSpec::BLOCKING, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- net::URLRequestJobFactoryImpl job_factory;
- job_factory.SetProtocolHandler(
- url::kAboutScheme,
- base::WrapUnique(new about_handler::AboutProtocolHandler()));
- context_->set_job_factory(&job_factory);
-
- GURL redirect_url("about:redirected");
- GURL not_chosen_redirect_url("about:not_chosen");
-
- std::unique_ptr<net::URLRequest> request = CreateRequest(GURL("about:blank"));
- {
- // onBeforeRequest will be dispatched twice initially. The second response -
- // the redirect - should win, since it has a later |install_time|. The
- // redirect will dispatch another pair of onBeforeRequest. There, the first
- // response should win (later |install_time|).
- ExtensionWebRequestEventRouter::EventResponse* response = NULL;
-
- // Extension1 response. Arrives first, but ignored due to install_time.
- response = new ExtensionWebRequestEventRouter::EventResponse(
- extension1_id, base::Time::FromDoubleT(1));
- response->new_url = not_chosen_redirect_url;
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, extension1_id, kEventName,
- kEventName + "/1", request->identifier(), response));
-
- // Extension2 response. Arrives second, and chosen because of install_time.
- response = new ExtensionWebRequestEventRouter::EventResponse(
- extension2_id, base::Time::FromDoubleT(2));
- response->new_url = redirect_url;
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, extension2_id, kEventName,
- kEventName + "/2", request->identifier(), response));
-
- // Extension2 response to the redirected URL. Arrives first, and chosen.
- response = new ExtensionWebRequestEventRouter::EventResponse(
- extension2_id, base::Time::FromDoubleT(2));
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, extension2_id, kEventName,
- kEventName + "/2", request->identifier(), response));
-
- // Extension1 response to the redirected URL. Arrives second, and ignored.
- response = new ExtensionWebRequestEventRouter::EventResponse(
- extension1_id, base::Time::FromDoubleT(1));
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, extension1_id, kEventName,
- kEventName + "/1", request->identifier(), response));
-
- request->Start();
- base::RunLoop().Run();
-
- EXPECT_TRUE(!request->is_pending());
- EXPECT_EQ(net::OK, delegate_.request_status());
- EXPECT_EQ(redirect_url, request->url());
- EXPECT_EQ(2U, request->url_chain().size());
- EXPECT_EQ(0U, ipc_sender_.GetNumTasks());
- }
-
- // Now test the same thing but the extensions answer in reverse order.
- std::unique_ptr<net::URLRequest> request2 =
- CreateRequest(GURL("about:blank"));
- {
- ExtensionWebRequestEventRouter::EventResponse* response = NULL;
-
- // Extension2 response. Arrives first, and chosen because of install_time.
- response = new ExtensionWebRequestEventRouter::EventResponse(
- extension2_id, base::Time::FromDoubleT(2));
- response->new_url = redirect_url;
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, extension2_id, kEventName,
- kEventName + "/2", request2->identifier(), response));
-
- // Extension1 response. Arrives second, but ignored due to install_time.
- response = new ExtensionWebRequestEventRouter::EventResponse(
- extension1_id, base::Time::FromDoubleT(1));
- response->new_url = not_chosen_redirect_url;
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, extension1_id, kEventName,
- kEventName + "/1", request2->identifier(), response));
-
- // Extension2 response to the redirected URL. Arrives first, and chosen.
- response = new ExtensionWebRequestEventRouter::EventResponse(
- extension2_id, base::Time::FromDoubleT(2));
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, extension2_id, kEventName,
- kEventName + "/2", request2->identifier(), response));
-
- // Extension1 response to the redirected URL. Arrives second, and ignored.
- response = new ExtensionWebRequestEventRouter::EventResponse(
- extension1_id, base::Time::FromDoubleT(1));
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, extension1_id, kEventName,
- kEventName + "/1", request2->identifier(), response));
-
- request2->Start();
- base::RunLoop().Run();
-
- EXPECT_TRUE(!request2->is_pending());
- EXPECT_EQ(net::OK, delegate_.request_status());
- EXPECT_EQ(redirect_url, request2->url());
- EXPECT_EQ(2U, request2->url_chain().size());
- EXPECT_EQ(0U, ipc_sender_.GetNumTasks());
- }
-
- ExtensionWebRequestEventRouter::EventListener::ID id1(
- &profile_, extension1_id, kEventName + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::EventListener::ID id2(
- &profile_, extension2_id, kEventName + "/2", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
- false);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id2,
- false);
-}
-
-// Test that a request is canceled if this is requested by any extension
-// regardless whether it is the extension with the highest precedence.
-TEST_F(ExtensionWebRequestTest, BlockingEventPrecedenceCancel) {
- std::string extension1_id("1");
- std::string extension2_id("2");
- ExtensionWebRequestEventRouter::RequestFilter filter;
- const std::string kEventName(web_request::OnBeforeRequest::kEventName);
- base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_);
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension1_id, extension1_id, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, ExtraInfoSpec::BLOCKING, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension2_id, extension2_id, events::FOR_TEST, kEventName,
- kEventName + "/2", filter, ExtraInfoSpec::BLOCKING, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- GURL request_url("about:blank");
- std::unique_ptr<net::URLRequest> request = CreateRequest(request_url);
-
- // onBeforeRequest will be dispatched twice. The second response -
- // the redirect - would win, since it has a later |install_time|, but
- // the first response takes precedence because cancel >> redirect.
- GURL redirect_url("about:redirected");
- ExtensionWebRequestEventRouter::EventResponse* response = NULL;
-
- // Extension1 response. Arrives first, would be ignored in principle due to
- // install_time but "cancel" always wins.
- response = new ExtensionWebRequestEventRouter::EventResponse(
- extension1_id, base::Time::FromDoubleT(1));
- response->cancel = true;
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, extension1_id, kEventName,
- kEventName + "/1", request->identifier(), response));
-
- // Extension2 response. Arrives second, but has higher precedence
- // due to its later install_time.
- response = new ExtensionWebRequestEventRouter::EventResponse(
- extension2_id, base::Time::FromDoubleT(2));
- response->new_url = redirect_url;
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, extension2_id, kEventName,
- kEventName + "/2", request->identifier(), response));
-
- request->Start();
-
- base::RunLoop().Run();
-
- EXPECT_TRUE(!request->is_pending());
- EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, delegate_.request_status());
- EXPECT_EQ(request_url, request->url());
- EXPECT_EQ(1U, request->url_chain().size());
- EXPECT_EQ(0U, ipc_sender_.GetNumTasks());
-
- ExtensionWebRequestEventRouter::EventListener::ID id1(
- &profile_, extension1_id, kEventName + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::EventListener::ID id2(
- &profile_, extension2_id, kEventName + "/2", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
- false);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id2,
- false);
-}
-
-TEST_F(ExtensionWebRequestTest, SimulateChancelWhileBlocked) {
- // We subscribe to OnBeforeRequest and OnErrorOccurred.
- // While the OnBeforeRequest handler is blocked, we cancel the request.
- // We verify that the response of the blocked OnBeforeRequest handler
- // is ignored.
-
- std::string extension_id("1");
- ExtensionWebRequestEventRouter::RequestFilter filter;
-
- // Subscribe to OnBeforeRequest and OnErrorOccurred.
- const std::string kEventName(web_request::OnBeforeRequest::kEventName);
- const std::string kEventName2(web_request::OnErrorOccurred::kEventName);
- base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_);
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id, extension_id, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, ExtraInfoSpec::BLOCKING, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id, extension_id, events::FOR_TEST, kEventName2,
- kEventName2 + "/1", filter, 0, 0, 0, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- GURL request_url("about:blank");
- std::unique_ptr<net::URLRequest> request = CreateRequest(request_url);
-
- ExtensionWebRequestEventRouter::EventResponse* response = NULL;
-
- // Extension response for the OnBeforeRequest handler. This should not be
- // processed because request is canceled before the handler responds.
- response = new ExtensionWebRequestEventRouter::EventResponse(
- extension_id, base::Time::FromDoubleT(1));
- GURL redirect_url("about:redirected");
- response->new_url = redirect_url;
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, extension_id, kEventName,
- kEventName + "/1", request->identifier(), response));
-
- base::RunLoop run_loop;
-
- // Extension response for OnErrorOccurred: Terminate the message loop.
- ipc_sender_.PushTask(base::BindRepeating(
- base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask),
- base::ThreadTaskRunnerHandle::Get(), FROM_HERE,
- run_loop.QuitWhenIdleClosure()));
-
- request->Start();
- // request->Start() will have submitted OnBeforeRequest by the time we cancel.
- int net_error = request->Cancel();
- run_loop.Run();
-
- EXPECT_EQ(net::ERR_ABORTED, net_error);
- EXPECT_TRUE(!request->is_pending());
- EXPECT_EQ(request_url, request->url());
- EXPECT_EQ(1U, request->url_chain().size());
- EXPECT_EQ(0U, ipc_sender_.GetNumTasks());
-
- ExtensionWebRequestEventRouter::EventListener::ID id1(
- &profile_, extension_id, kEventName + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::EventListener::ID id2(
- &profile_, extension_id, kEventName2 + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
- false);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id2,
- false);
-}
-
namespace {
// Create the numerical representation of |values|, strings passed as
@@ -591,447 +183,6 @@ bool GenerateInfoSpec(const std::string& values, int* result) {
} // namespace
-void ExtensionWebRequestTest::FireURLRequestWithData(
- const std::string& method,
- const char* content_type,
- const std::vector<char>& bytes_1,
- const std::vector<char>& bytes_2) {
- // The request URL can be arbitrary but must have an HTTP or HTTPS scheme.
- GURL request_url("http://www.example.com");
- std::unique_ptr<net::URLRequest> request = CreateRequest(request_url);
- request->set_method(method);
- if (content_type != NULL) {
- request->SetExtraRequestHeaderByName(net::HttpRequestHeaders::kContentType,
- content_type,
- true /* overwrite */);
- }
- std::vector<std::unique_ptr<net::UploadElementReader>> element_readers;
- element_readers.push_back(std::make_unique<net::UploadBytesElementReader>(
- &(bytes_1[0]), bytes_1.size()));
- element_readers.push_back(std::make_unique<net::UploadFileElementReader>(
- base::ThreadTaskRunnerHandle::Get().get(), base::FilePath(), 0, 0,
- base::Time()));
- element_readers.push_back(std::make_unique<net::UploadBytesElementReader>(
- &(bytes_2[0]), bytes_2.size()));
- request->set_upload(std::make_unique<net::ElementsUploadDataStream>(
- std::move(element_readers), 0));
- ipc_sender_.PushTask(base::DoNothing());
- request->Start();
-}
-
-TEST_F(ExtensionWebRequestTest, AccessRequestBodyData) {
- // We verify that URLRequest body is accessible to OnBeforeRequest listeners.
- // These testing steps are repeated twice in a row:
- // 1. Register an extension requesting "requestBody" in ExtraInfoSpec and
- // file a POST URLRequest with a multipart-encoded form. See it getting
- // parsed.
- // 2. Do the same, but without requesting "requestBody". Nothing should be
- // parsed.
- // 3. With "requestBody", fire a POST URLRequest which is not a parseable
- // HTML form. Raw data should be returned.
- // 4. Do the same, but with a PUT method. Result should be the same.
- const std::string kMethodPost("POST");
- const std::string kMethodPut("PUT");
-
- // Input.
- const char kPlainBlock1[] = "abcd\n";
- const size_t kPlainBlock1Length = sizeof(kPlainBlock1) - 1;
- std::vector<char> plain_1(kPlainBlock1, kPlainBlock1 + kPlainBlock1Length);
- const char kPlainBlock2[] = "1234\n";
- const size_t kPlainBlock2Length = sizeof(kPlainBlock2) - 1;
- std::vector<char> plain_2(kPlainBlock2, kPlainBlock2 + kPlainBlock2Length);
-#define kBoundary "THIS_IS_A_BOUNDARY"
- const char kFormBlock1[] =
- "--" kBoundary
- "\r\n"
- "Content-Disposition: form-data; name=\"A\"\r\n"
- "\r\n"
- "test text\r\n"
- "--" kBoundary
- "\r\n"
- "Content-Disposition: form-data; name=\"B\"; filename=\"\"\r\n"
- "Content-Type: application/octet-stream\r\n"
- "\r\n"
- "--" kBoundary
- "\r\n"
- "Content-Disposition: form-data; name=\"B_content\"\r\n"
- "Content-Type: application/octet-stream\r\n"
- "\r\n"
- "\uffff\uffff\uffff\uffff\r\n"
- "--" kBoundary "\r\n";
- std::vector<char> form_1(kFormBlock1, kFormBlock1 + sizeof(kFormBlock1) - 1);
- const char kFormBlock2[] =
- "Content-Disposition: form-data; name=\"C\"\r\n"
- "\r\n"
- "test password\r\n"
- "--" kBoundary "--";
- std::vector<char> form_2(kFormBlock2, kFormBlock2 + sizeof(kFormBlock2) - 1);
-
- // Expected output.
- // Paths to look for in returned dictionaries.
- const std::string kBodyPath(keys::kRequestBodyKey);
- const std::string kFormDataPath(
- kBodyPath + "." + keys::kRequestBodyFormDataKey);
- const std::string kRawPath(kBodyPath + "." + keys::kRequestBodyRawKey);
- const std::string kErrorPath(kBodyPath + "." + keys::kRequestBodyErrorKey);
- const std::string* const kPath[] = {
- &kFormDataPath,
- &kBodyPath,
- &kRawPath,
- &kRawPath
- };
- // Contents of formData.
- struct KeyValuePairs {
- const char* key;
- base::Value value;
- };
- KeyValuePairs kFormDataPairs[] = {
- {"A", FormStringValue("test text")},
- {"B", FormStringValue("")},
- {"B_content", FormBinaryValue("\uffff\uffff\uffff\uffff")},
- {"C", FormStringValue("test password")}};
- std::unique_ptr<base::Value> form_data =
- std::make_unique<base::Value>(base::Value::Type::DICTIONARY);
- for (auto& pair : kFormDataPairs) {
- form_data->SetKey(pair.key, std::move(pair.value));
- }
-
- ASSERT_TRUE(form_data.get() != NULL);
- ASSERT_TRUE(form_data->type() == base::Value::Type::DICTIONARY);
- // Contents of raw.
- base::ListValue raw;
- extensions::subtle::AppendKeyValuePair(
- keys::kRequestBodyRawBytesKey,
- Value::CreateWithCopiedBuffer(kPlainBlock1, kPlainBlock1Length), &raw);
- extensions::subtle::AppendKeyValuePair(
- keys::kRequestBodyRawFileKey,
- std::make_unique<base::Value>(std::string()), &raw);
- extensions::subtle::AppendKeyValuePair(
- keys::kRequestBodyRawBytesKey,
- Value::CreateWithCopiedBuffer(kPlainBlock2, kPlainBlock2Length), &raw);
- // Summary.
- const base::Value* const kExpected[] = {
- form_data.get(),
- NULL,
- &raw,
- &raw,
- };
- static_assert(base::size(kPath) == base::size(kExpected),
- "kPath and kExpected arrays should have the same number "
- "of elements");
- // Header.
- const char kMultipart[] = "multipart/form-data; boundary=" kBoundary;
-#undef kBoundary
-
- // Set up a dummy extension name.
- const std::string kEventName(web_request::OnBeforeRequest::kEventName);
- ExtensionWebRequestEventRouter::RequestFilter filter;
- std::string extension_id("1");
- const std::string string_spec_post("blocking,requestBody");
- const std::string string_spec_no_post("blocking");
- int extra_info_spec_empty = 0;
- int extra_info_spec_body = 0;
- base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_);
-
- // Part 1.
- // Subscribe to OnBeforeRequest with requestBody requirement.
- ASSERT_TRUE(GenerateInfoSpec(string_spec_post, &extra_info_spec_body));
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id, extension_id, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, extra_info_spec_body, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- FireURLRequestWithData(kMethodPost, kMultipart, form_1, form_2);
-
- // We inspect the result in the message list of |ipc_sender_| later.
- base::RunLoop().RunUntilIdle();
-
- ExtensionWebRequestEventRouter::EventListener::ID id1(
- &profile_, extension_id, kEventName + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
- false);
-
- // Part 2.
- // Now subscribe to OnBeforeRequest *without* the requestBody requirement.
- ASSERT_TRUE(
- GenerateInfoSpec(string_spec_no_post, &extra_info_spec_empty));
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id, extension_id, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, extra_info_spec_empty, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- FireURLRequestWithData(kMethodPost, kMultipart, form_1, form_2);
-
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
- false);
-
- // Subscribe to OnBeforeRequest with requestBody requirement.
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id, extension_id, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, extra_info_spec_body, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- // Part 3.
- // Now send a POST request with body which is not parseable as a form.
- FireURLRequestWithData(kMethodPost, NULL /*no header*/, plain_1, plain_2);
-
- // Part 4.
- // Now send a PUT request with the same body as above.
- FireURLRequestWithData(kMethodPut, NULL /*no header*/, plain_1, plain_2);
-
- base::RunLoop().RunUntilIdle();
-
- // Clean-up.
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
- false);
-
- IPC::Message* message = NULL;
- auto i = ipc_sender_.sent_begin();
- for (size_t test = 0; test < base::size(kExpected); ++test) {
- SCOPED_TRACE(testing::Message("iteration number ") << test);
- EXPECT_NE(i, ipc_sender_.sent_end());
- message = (i++)->get();
- const base::DictionaryValue* details = nullptr;
- ExtensionMsg_DispatchEvent::Param param;
- GetPartOfMessageArguments(message, &details, &param);
- ASSERT_TRUE(details != NULL);
- const base::Value* result = NULL;
- if (kExpected[test]) {
- EXPECT_TRUE(details->Get(*(kPath[test]), &result));
- EXPECT_TRUE(kExpected[test]->Equals(result));
- } else {
- EXPECT_FALSE(details->Get(*(kPath[test]), &result));
- }
- }
-
- EXPECT_EQ(i, ipc_sender_.sent_end());
-}
-
-// Tests whether requestBody is only present on the events that requested it.
-TEST_F(ExtensionWebRequestTest, MinimalAccessRequestBodyData) {
- const std::string kEventName(web_request::OnBeforeRequest::kEventName);
- ExtensionWebRequestEventRouter::RequestFilter filter;
- const std::string extension_id1("1");
- const std::string extension_id2("2");
- int extra_info_spec_body = 0;
- int extra_info_spec_empty = 0;
- ASSERT_TRUE(GenerateInfoSpec("requestBody", &extra_info_spec_body));
- base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_);
-
- bool kExpected[] = {
- true,
- false,
- false,
- true,
- };
-
- // Extension 1 with requestBody spec.
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id1, extension_id1, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, extra_info_spec_body, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- // Extension 1 without requestBody spec.
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id1, extension_id1, events::FOR_TEST, kEventName,
- kEventName + "/2", filter, extra_info_spec_empty, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- // Extension 2, without requestBody spec.
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id2, extension_id2, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, extra_info_spec_empty, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- // Extension 2, with requestBody spec.
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id2, extension_id2, events::FOR_TEST, kEventName,
- kEventName + "/2", filter, extra_info_spec_body, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- // Only one request is sent, but more than one event will be triggered.
- for (size_t i = 1; i < base::size(kExpected); ++i)
- ipc_sender_.PushTask(base::DoNothing());
-
- const std::vector<char> part_of_body(1);
- FireURLRequestWithData("POST", nullptr, part_of_body, part_of_body);
-
- base::RunLoop().RunUntilIdle();
-
- // Clean-up
- ExtensionWebRequestEventRouter::EventListener::ID id1(
- &profile_, extension_id1, kEventName + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::EventListener::ID id2(
- &profile_, extension_id1, kEventName + "/2", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::EventListener::ID id3(
- &profile_, extension_id2, kEventName + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::EventListener::ID id4(
- &profile_, extension_id2, kEventName + "/2", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
- false);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id2,
- false);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id3,
- false);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id4,
- false);
-
- auto i = ipc_sender_.sent_begin();
-
- for (size_t test = 0; test < base::size(kExpected); ++test, ++i) {
- SCOPED_TRACE(testing::Message("iteration number ") << test);
- EXPECT_NE(i, ipc_sender_.sent_end());
- IPC::Message* message = i->get();
- const base::DictionaryValue* details = nullptr;
- ExtensionMsg_DispatchEvent::Param param;
- GetPartOfMessageArguments(message, &details, &param);
- ASSERT_TRUE(details != nullptr);
- EXPECT_EQ(kExpected[test], details->HasKey(keys::kRequestBodyKey));
- }
-
- EXPECT_EQ(i, ipc_sender_.sent_end());
-}
-
-#if defined(OS_CHROMEOS)
-// Tests that proper filtering is applied in public session (non-whitelisted
-// extension gets some things filtered out, while there's no filtering applied
-// for a whitelisted extension).
-TEST_F(ExtensionWebRequestTest, ProperFilteringInPublicSession) {
- chromeos::ScopedTestPublicSessionLoginState state;
- const std::string kEventName(web_request::OnBeforeRequest::kEventName);
- ExtensionWebRequestEventRouter::RequestFilter filter;
- // Whitelisted extension (User Agent Switcher).
- const std::string extension_id1("djflhoibgkdhkhhcedjiklpkjnoahfmg");
- const std::string extension_id2 =
- crx_file::id_util::GenerateId("nonwhitelisted");
- int extra_info_spec_body = 0;
- ASSERT_TRUE(GenerateInfoSpec("requestBody", &extra_info_spec_body));
- base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_);
-
- bool kExpected[] = {
- true,
- false,
- };
-
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id1, extension_id1, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, extra_info_spec_body, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id2, extension_id2, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, extra_info_spec_body, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- // Only one request is sent, but more than one event will be triggered.
- for (size_t i = 1; i < base::size(kExpected); ++i)
- ipc_sender_.PushTask(base::DoNothing());
-
- const std::vector<char> part_of_body(1);
- FireURLRequestWithData("POST", nullptr, part_of_body, part_of_body);
-
- base::RunLoop().RunUntilIdle();
-
- // Clean-up
- ExtensionWebRequestEventRouter::EventListener::ID id1(
- &profile_, extension_id1, kEventName + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::EventListener::ID id2(
- &profile_, extension_id2, kEventName + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
- false);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id2,
- false);
-
- TestIPCSender::SentMessages::const_iterator i = ipc_sender_.sent_begin();
-
- for (size_t test = 0; test < base::size(kExpected); ++test, ++i) {
- SCOPED_TRACE(testing::Message("iteration number ") << test);
- EXPECT_NE(i, ipc_sender_.sent_end());
- IPC::Message* message = i->get();
- const base::DictionaryValue* details = nullptr;
- ExtensionMsg_DispatchEvent::Param param;
- GetPartOfMessageArguments(message, &details, &param);
- ASSERT_TRUE(details != nullptr);
- EXPECT_EQ(kExpected[test], details->HasKey(keys::kRequestBodyKey));
- }
-
- EXPECT_EQ(i, ipc_sender_.sent_end());
-}
-#endif
-
-TEST_F(ExtensionWebRequestTest, NoAccessRequestBodyData) {
- // We verify that URLRequest body is NOT accessible to OnBeforeRequest
- // listeners when the type of the request is different from POST or PUT, or
- // when the request body is empty. 3 requests are fired, without upload data,
- // a POST, PUT and GET request. For none of them the "requestBody" object
- // property should be present in the details passed to the onBeforeRequest
- // event listener.
- const char* const kMethods[] = { "POST", "PUT", "GET" };
-
- // Set up a dummy extension name.
- const std::string kEventName(web_request::OnBeforeRequest::kEventName);
- ExtensionWebRequestEventRouter::RequestFilter filter;
- const std::string extension_id("1");
- int extra_info_spec = 0;
- ASSERT_TRUE(GenerateInfoSpec("blocking,requestBody", &extra_info_spec));
- base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_);
-
- // Subscribe to OnBeforeRequest with requestBody requirement.
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id, extension_id, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, extra_info_spec, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- // The request URL can be arbitrary but must have an HTTP or HTTPS scheme.
- const GURL request_url("http://www.example.com");
-
- for (size_t i = 0; i < base::size(kMethods); ++i) {
- std::unique_ptr<net::URLRequest> request = CreateRequest(request_url);
- request->set_method(kMethods[i]);
- ipc_sender_.PushTask(base::DoNothing());
- request->Start();
- }
-
- // We inspect the result in the message list of |ipc_sender_| later.
- base::RunLoop().RunUntilIdle();
-
- ExtensionWebRequestEventRouter::EventListener::ID id1(
- &profile_, extension_id, kEventName + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
- false);
-
- auto i = ipc_sender_.sent_begin();
- for (size_t test = 0; test < base::size(kMethods); ++test, ++i) {
- SCOPED_TRACE(testing::Message("iteration number ") << test);
- EXPECT_NE(i, ipc_sender_.sent_end());
- IPC::Message* message = i->get();
- const base::DictionaryValue* details = nullptr;
- ExtensionMsg_DispatchEvent::Param param;
- GetPartOfMessageArguments(message, &details, &param);
- ASSERT_TRUE(details != NULL);
- EXPECT_FALSE(details->HasKey(keys::kRequestBodyKey));
- }
-
- EXPECT_EQ(i, ipc_sender_.sent_end());
-}
-
// Tests that |render_process_id| is not relevant for adding and removing
// listeners with |web_view_instance_id| = 0.
TEST_F(ExtensionWebRequestTest, AddAndRemoveListeners) {
@@ -1039,7 +190,6 @@ TEST_F(ExtensionWebRequestTest, AddAndRemoveListeners) {
ExtensionWebRequestEventRouter::RequestFilter filter;
const std::string kEventName(web_request::OnBeforeRequest::kEventName);
const std::string kSubEventName = kEventName + "/1";
- base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_);
EXPECT_EQ(
0u,
ExtensionWebRequestEventRouter::GetInstance()->GetListenerCountForTesting(
@@ -1049,13 +199,11 @@ TEST_F(ExtensionWebRequestTest, AddAndRemoveListeners) {
ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
&profile_, ext_id, ext_id, events::FOR_TEST, kEventName, kSubEventName,
filter, 0, 1 /* render_process_id */, 0, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
+ blink::mojom::kInvalidServiceWorkerVersionId);
ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
&profile_, ext_id, ext_id, events::FOR_TEST, kEventName, kSubEventName,
filter, 0, 2 /* render_process_id */, 0, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
+ blink::mojom::kInvalidServiceWorkerVersionId);
EXPECT_EQ(
2u,
ExtensionWebRequestEventRouter::GetInstance()->GetListenerCountForTesting(
@@ -1080,297 +228,6 @@ TEST_F(ExtensionWebRequestTest, AddAndRemoveListeners) {
&profile_, kEventName));
}
-// The set of blocked requests should not grow unbounded.
-TEST_F(ExtensionWebRequestTest, BlockedRequestsAreRemoved) {
- std::string extension_id("1");
- ExtensionWebRequestEventRouter::RequestFilter filter;
-
- // Subscribe to OnBeforeRequest.
- const std::string kEventName(web_request::OnBeforeRequest::kEventName);
- base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_);
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension_id, extension_id, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, ExtraInfoSpec::BLOCKING, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
- ExtensionWebRequestEventRouter::EventListener::ID id(
- &profile_, extension_id, kEventName + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::EventListener* listener =
- ExtensionWebRequestEventRouter::GetInstance()->FindEventListener(id);
- ASSERT_NE(nullptr, listener);
- EXPECT_EQ(0u, listener->blocked_requests.size());
-
- // Send a request. It should block. Wait for the run loop to become idle.
- GURL request_url("about:blank");
- std::unique_ptr<net::URLRequest> request = CreateRequest(request_url);
- // Extension response for OnErrorOccurred: Terminate the message loop.
- {
- base::RunLoop run_loop;
- ipc_sender_.PushTask(base::BindRepeating(
- base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask),
- base::ThreadTaskRunnerHandle::Get(), FROM_HERE,
- run_loop.QuitWhenIdleClosure()));
- request->Start();
- run_loop.Run();
- }
-
- // Confirm that there is a blocked request.
- EXPECT_EQ(1u, listener->blocked_requests.size());
-
- // Send a response through.
- ExtensionWebRequestEventRouter::EventResponse* response =
- new ExtensionWebRequestEventRouter::EventResponse(
- extension_id, base::Time::FromDoubleT(1));
- response->cancel = true;
- ExtensionWebRequestEventRouter::GetInstance()->OnEventHandled(
- &profile_, extension_id, kEventName, kEventName + "/1",
- request->identifier(), 0 /* render_process_id */,
- 0 /* web_view_instance_id */, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId, response);
- {
- base::RunLoop run_loop;
- run_loop.RunUntilIdle();
- }
-
- // Now there should be no blocked requests.
- EXPECT_EQ(0u, listener->blocked_requests.size());
-
- EXPECT_TRUE(!request->is_pending());
- EXPECT_EQ(net::URLRequestStatus::FAILED, request->status().status());
- EXPECT_EQ(net::ERR_BLOCKED_BY_CLIENT, request->status().error());
- EXPECT_EQ(0U, ipc_sender_.GetNumTasks());
-
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id, false);
-}
-
-struct HeaderModificationTest_Header {
- const char* name;
- const char* value;
-};
-
-struct HeaderModificationTest_Modification {
- enum Type {
- SET,
- REMOVE
- };
-
- int extension_id;
- Type type;
- const char* key;
- const char* value;
-};
-
-struct HeaderModificationTest {
- int before_size;
- HeaderModificationTest_Header before[10];
- int modification_size;
- HeaderModificationTest_Modification modification[10];
- int after_size;
- HeaderModificationTest_Header after[10];
-};
-
-class ExtensionWebRequestHeaderModificationTest
- : public testing::TestWithParam<HeaderModificationTest> {
- public:
- ExtensionWebRequestHeaderModificationTest()
- : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
- profile_manager_(TestingBrowserProcess::GetGlobal()),
- event_router_(new EventRouterForwarder) {}
-
- protected:
- void SetUp() override {
- ASSERT_TRUE(profile_manager_.SetUp());
- network_delegate_.reset(new ChromeNetworkDelegate(event_router_.get()));
- network_delegate_->set_profile(&profile_);
- network_delegate_->set_cookie_settings(
- CookieSettingsFactory::GetForProfile(&profile_).get());
- context_.reset(new net::TestURLRequestContext(true));
- host_resolver_.reset(new net::MockHostResolver());
- host_resolver_->rules()->AddSimulatedFailure("doesnotexist");
- context_->set_host_resolver(host_resolver_.get());
- context_->set_network_delegate(network_delegate_.get());
- context_->Init();
- }
-
- // Returns a main-frame request to |url|.
- std::unique_ptr<net::URLRequest> CreateRequest(const GURL& url) {
- return CreateRequestHelper(url, context_.get(), &delegate_);
- }
-
- content::TestBrowserThreadBundle thread_bundle_;
- TestingProfile profile_;
- TestingProfileManager profile_manager_;
- net::TestDelegate delegate_;
- TestIPCSender ipc_sender_;
- scoped_refptr<EventRouterForwarder> event_router_;
- std::unique_ptr<ChromeNetworkDelegate> network_delegate_;
- std::unique_ptr<net::MockHostResolver> host_resolver_;
- std::unique_ptr<net::TestURLRequestContext> context_;
-};
-
-TEST_P(ExtensionWebRequestHeaderModificationTest, TestModifications) {
- std::string extension1_id("1");
- std::string extension2_id("2");
- std::string extension3_id("3");
- ExtensionWebRequestEventRouter::RequestFilter filter;
- const std::string kEventName(keys::kOnBeforeSendHeadersEvent);
- base::WeakPtrFactory<TestIPCSender> ipc_sender_factory(&ipc_sender_);
-
- // Install two extensions that can modify headers. Extension 2 has
- // higher precedence than extension 1.
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension1_id, extension1_id, events::FOR_TEST, kEventName,
- kEventName + "/1", filter, ExtraInfoSpec::BLOCKING, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension2_id, extension2_id, events::FOR_TEST, kEventName,
- kEventName + "/2", filter, ExtraInfoSpec::BLOCKING, 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- // Install one extension that observes the final headers.
- ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
- &profile_, extension3_id, extension3_id, events::FOR_TEST,
- keys::kOnSendHeadersEvent, std::string(keys::kOnSendHeadersEvent) + "/3",
- filter, ExtraInfoSpec::REQUEST_HEADERS, 0, 0, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId,
- ipc_sender_factory.GetWeakPtr());
-
- GURL request_url("http://doesnotexist/does_not_exist.html");
- std::unique_ptr<net::URLRequest> request = CreateRequest(request_url);
-
- // Initialize headers available before extensions are notified of the
- // onBeforeSendHeaders event.
- HeaderModificationTest test = GetParam();
- net::HttpRequestHeaders before_headers;
- for (int i = 0; i < test.before_size; ++i)
- before_headers.SetHeader(test.before[i].name, test.before[i].value);
- request->SetExtraRequestHeaders(before_headers);
-
- // Gather the modifications to the headers for the respective extensions.
- // We assume here that all modifications of one extension are listed
- // in a continuous block of |test.modifications_|.
- ExtensionWebRequestEventRouter::EventResponse* response = NULL;
- for (int i = 0; i < test.modification_size; ++i) {
- const HeaderModificationTest_Modification& mod = test.modification[i];
- if (response == NULL) {
- response = new ExtensionWebRequestEventRouter::EventResponse(
- mod.extension_id == 1 ? extension1_id : extension2_id,
- base::Time::FromDoubleT(mod.extension_id));
- response->request_headers.reset(new net::HttpRequestHeaders());
- response->request_headers->MergeFrom(request->extra_request_headers());
- }
-
- switch (mod.type) {
- case HeaderModificationTest_Modification::SET:
- response->request_headers->SetHeader(mod.key, mod.value);
- break;
- case HeaderModificationTest_Modification::REMOVE:
- response->request_headers->RemoveHeader(mod.key);
- break;
- }
-
- // Trigger the result when this is the last modification statement or
- // the block of modifications for the next extension starts.
- if (i+1 == test.modification_size ||
- mod.extension_id != test.modification[i+1].extension_id) {
- ipc_sender_.PushTask(base::BindRepeating(
- &EventHandledOnIOThread, &profile_, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId,
- mod.extension_id == 1 ? extension1_id : extension2_id, kEventName,
- kEventName + (mod.extension_id == 1 ? "/1" : "/2"),
- request->identifier(), response));
- response = NULL;
- }
- }
-
- // Don't do anything for the onSendHeaders message.
- ipc_sender_.PushTask(base::DoNothing());
-
- // Note that we mess up the headers slightly:
- // request->Start() will first add additional headers (e.g. the User-Agent)
- // and then send an event to the extension. When we have prepared our
- // answers to the onBeforeSendHeaders events above, these headers did not
- // exists and are therefore not listed in the responses. This makes
- // them seem deleted.
- request->Start();
- base::RunLoop().Run();
-
- EXPECT_TRUE(!request->is_pending());
- // This cannot succeed as we send the request to a server that does not exist.
- EXPECT_EQ(net::ERR_NAME_NOT_RESOLVED, delegate_.request_status());
- EXPECT_EQ(request_url, request->url());
- EXPECT_EQ(1U, request->url_chain().size());
- EXPECT_EQ(0U, ipc_sender_.GetNumTasks());
-
- // Calculate the expected headers.
- net::HttpRequestHeaders expected_headers;
- for (int i = 0; i < test.after_size; ++i) {
- expected_headers.SetHeader(test.after[i].name,
- test.after[i].value);
- }
-
- // Counter for the number of observed onSendHeaders events.
- int num_headers_observed = 0;
-
- // Search the onSendHeaders signal in the IPC messages and check that
- // it contained the correct headers.
- TestIPCSender::SentMessages::const_iterator i;
- for (i = ipc_sender_.sent_begin(); i != ipc_sender_.sent_end(); ++i) {
- IPC::Message* message = i->get();
- if (ExtensionMsg_DispatchEvent::ID != message->type())
- continue;
- ExtensionMsg_DispatchEvent::Param message_tuple;
- ExtensionMsg_DispatchEvent::Read(message, &message_tuple);
- const ExtensionMsg_DispatchEvent_Params& params =
- std::get<0>(message_tuple);
-
- if (params.event_name != std::string(keys::kOnSendHeadersEvent) + "/3")
- continue;
-
- const base::ListValue& event_args = std::get<1>(message_tuple);
- const base::DictionaryValue* event_arg_dict = nullptr;
- ASSERT_TRUE(event_args.GetDictionary(0, &event_arg_dict));
-
- const base::ListValue* request_headers = nullptr;
- ASSERT_TRUE(event_arg_dict->GetList(keys::kRequestHeadersKey,
- &request_headers));
-
- net::HttpRequestHeaders observed_headers;
- for (size_t j = 0; j < request_headers->GetSize(); ++j) {
- const base::DictionaryValue* header = nullptr;
- ASSERT_TRUE(request_headers->GetDictionary(j, &header));
- std::string key;
- std::string value;
- ASSERT_TRUE(header->GetString(keys::kHeaderNameKey, &key));
- ASSERT_TRUE(header->GetString(keys::kHeaderValueKey, &value));
- observed_headers.SetHeader(key, value);
- }
-
- EXPECT_EQ(expected_headers.ToString(), observed_headers.ToString());
- ++num_headers_observed;
- }
- EXPECT_EQ(1, num_headers_observed);
- ExtensionWebRequestEventRouter::EventListener::ID id1(
- &profile_, extension1_id, kEventName + "/1", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::EventListener::ID id2(
- &profile_, extension2_id, kEventName + "/2", 0, 0,
- extensions::kMainThreadId, blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::EventListener::ID id3(
- &profile_, extension3_id, std::string(keys::kOnSendHeadersEvent) + "/3",
- 0, 0, extensions::kMainThreadId,
- blink::mojom::kInvalidServiceWorkerVersionId);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
- false);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id2,
- false);
- ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id3,
- false);
-}
-
namespace {
void TestInitFromValue(const std::string& values, bool expected_return_code,
@@ -1424,147 +281,6 @@ TEST_F(ExtensionWebRequestTest, InitFromValue) {
TestInitFromValue("blocking,asyncBlocking", false, 0);
}
-namespace {
-
-const HeaderModificationTest_Modification::Type SET =
- HeaderModificationTest_Modification::SET;
-const HeaderModificationTest_Modification::Type REMOVE =
- HeaderModificationTest_Modification::REMOVE;
-
-HeaderModificationTest kTests[] = {
- // Check that extension 2 always wins when settings the same header.
- {
- // Headers before test.
- 2, { {"header1", "value1"},
- {"header2", "value2"} },
- // Modifications in test.
- 2, { {1, SET, "header1", "foo"},
- {2, SET, "header1", "bar"} },
- // Headers after test.
- 2, { {"header1", "bar"},
- {"header2", "value2"} }
- },
- // Same as before in reverse execution order.
- {
- // Headers before test.
- 2, { {"header1", "value1"},
- {"header2", "value2"} },
- // Modifications in test.
- 2, { {2, SET, "header1", "bar"},
- {1, SET, "header1", "foo"} },
- // Headers after test.
- 2, { {"header1", "bar"},
- {"header2", "value2"} }
- },
- // Check that two extensions can modify different headers that do not
- // conflict.
- {
- // Headers before test.
- 2, { {"header1", "value1"},
- {"header2", "value2"} },
- // Modifications in test.
- 2, { {1, SET, "header1", "foo"},
- {2, SET, "header2", "bar"} },
- // Headers after test.
- 2, { {"header1", "foo"},
- {"header2", "bar"} }
- },
- // Check insert/delete conflict.
- {
- // Headers before test.
- 1, { {"header1", "value1"} },
- // Modifications in test.
- 2, { {1, SET, "header1", "foo"},
- {2, REMOVE, "header1", NULL} },
- // Headers after test.
- 0, { }
- },
- {
- // Headers before test.
- 1, { {"header1", "value1"} },
- // Modifications in test.
- 2, { {2, REMOVE, "header1", NULL},
- {1, SET, "header1", "foo"} },
- // Headers after test.
- 0, {}
- },
- {
- // Headers before test.
- 1, { {"header1", "value1"} },
- // Modifications in test.
- 2, { {1, REMOVE, "header1", NULL},
- {2, SET, "header1", "foo"} },
- // Headers after test.
- 1, { {"header1", "foo"} }
- },
- {
- // Headers before test.
- 1, { {"header1", "value1"} },
- // Modifications in test.
- 2, { {2, SET, "header1", "foo"},
- {1, REMOVE, "header1", NULL} },
- // Headers after test.
- 1, { {"header1", "foo"} }
- },
- // Check that edits are atomic (i.e. either all edit requests of an
- // extension are executed or none).
- {
- // Headers before test.
- 0, { },
- // Modifications in test.
- 3, { {1, SET, "header1", "value1"},
- {1, SET, "header2", "value2"},
- {2, SET, "header1", "foo"} },
- // Headers after test.
- 1, { {"header1", "foo"} } // set(header2) is ignored
- },
- // Check that identical edits do not conflict (set(header2) would be ignored
- // if set(header1) were considered a conflict).
- {
- // Headers before test.
- 0, { },
- // Modifications in test.
- 3, { {1, SET, "header1", "value2"},
- {1, SET, "header2", "foo"},
- {2, SET, "header1", "value2"} },
- // Headers after test.
- 2, { {"header1", "value2"},
- {"header2", "foo"} }
- },
- // Check that identical deletes do not conflict (set(header2) would be ignored
- // if delete(header1) were considered a conflict).
- {
- // Headers before test.
- 1, { {"header1", "value1"} },
- // Modifications in test.
- 3, { {1, REMOVE, "header1", NULL},
- {1, SET, "header2", "foo"},
- {2, REMOVE, "header1", NULL} },
- // Headers after test.
- 1, { {"header2", "foo"} }
- },
- // Check that setting a value to an identical value is not considered an
- // edit operation that can conflict.
- {
- // Headers before test.
- 1, { {"header1", "value1"} },
- // Modifications in test.
- 3, { {1, SET, "header1", "foo"},
- {1, SET, "header2", "bar"},
- {2, SET, "header1", "value1"} },
- // Headers after test.
- 2, { {"header1", "foo"},
- {"header2", "bar"} }
- },
-};
-
-INSTANTIATE_TEST_SUITE_P(ExtensionWebRequest,
- ExtensionWebRequestHeaderModificationTest,
- ::testing::ValuesIn(kTests));
-
-} // namespace
-
-
TEST(ExtensionWebRequestHelpersTest,
TestInDecreasingExtensionInstallationTimeOrder) {
EventResponseDelta a("ext_1", base::Time::FromInternalValue(0));
@@ -1817,7 +533,6 @@ TEST(ExtensionWebRequestHelpersTest, TestCalculateOnAuthRequiredDelta) {
TEST(ExtensionWebRequestHelpersTest, TestMergeCancelOfResponses) {
EventResponseDeltas deltas;
- TestLogger logger;
bool canceled = false;
// Single event that does not cancel.
@@ -1826,9 +541,8 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeCancelOfResponses) {
d1.cancel = false;
deltas.push_back(std::move(d1));
}
- MergeCancelOfResponses(deltas, &canceled, &logger);
+ MergeCancelOfResponses(deltas, &canceled);
EXPECT_FALSE(canceled);
- EXPECT_EQ(0u, logger.log_size());
// Second event that cancels the request
{
@@ -1837,14 +551,12 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeCancelOfResponses) {
deltas.push_back(std::move(d2));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
- MergeCancelOfResponses(deltas, &canceled, &logger);
+ MergeCancelOfResponses(deltas, &canceled);
EXPECT_TRUE(canceled);
- EXPECT_EQ(1u, logger.log_size());
}
TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses) {
EventResponseDeltas deltas;
- TestLogger logger;
helpers::IgnoredActions ignored_actions;
GURL effective_new_url;
@@ -1854,7 +566,7 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses) {
deltas.push_back(std::move(d0));
}
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
- &ignored_actions, &logger);
+ &ignored_actions);
EXPECT_TRUE(effective_new_url.is_empty());
// Single redirect.
@@ -1865,12 +577,10 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses) {
deltas.push_back(std::move(d1));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
- logger.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
- &ignored_actions, &logger);
+ &ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_TRUE(ignored_actions.empty());
- EXPECT_EQ(1u, logger.log_size());
// Ignored redirect (due to precedence).
GURL new_url_2("http://bar.com");
@@ -1881,14 +591,12 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
- &ignored_actions, &logger);
+ &ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_EQ(1u, ignored_actions.size());
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
- EXPECT_EQ(2u, logger.log_size());
// Overriding redirect.
GURL new_url_3("http://baz.com");
@@ -1899,16 +607,14 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
- &ignored_actions, &logger);
+ &ignored_actions);
EXPECT_EQ(new_url_3, effective_new_url);
EXPECT_EQ(2u, ignored_actions.size());
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid1",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
- EXPECT_EQ(3u, logger.log_size());
// Check that identical redirects don't cause a conflict.
{
@@ -1918,23 +624,20 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
- &ignored_actions, &logger);
+ &ignored_actions);
EXPECT_EQ(new_url_3, effective_new_url);
EXPECT_EQ(2u, ignored_actions.size());
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid1",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
- EXPECT_EQ(4u, logger.log_size());
}
// This tests that we can redirect to data:// urls, which is considered
// a kind of cancelling requests.
TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses2) {
EventResponseDeltas deltas;
- TestLogger logger;
helpers::IgnoredActions ignored_actions;
GURL effective_new_url;
@@ -1946,7 +649,7 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses2) {
deltas.push_back(std::move(d0));
}
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
- &ignored_actions, &logger);
+ &ignored_actions);
EXPECT_EQ(new_url_0, effective_new_url);
// Cancel request by redirecting to a data:// URL. This shall override
@@ -1959,12 +662,10 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses2) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
- &ignored_actions, &logger);
+ &ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_TRUE(ignored_actions.empty());
- EXPECT_EQ(1u, logger.log_size());
// Cancel request by redirecting to the same data:// URL. This shall
// not create any conflicts as it is in line with d1.
@@ -1976,13 +677,11 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses2) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
- &ignored_actions, &logger);
+ &ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_TRUE(ignored_actions.empty());
- EXPECT_EQ(2u, logger.log_size());
// Cancel redirect by redirecting to a different data:// URL. This needs
// to create a conflict.
@@ -1994,21 +693,18 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses2) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
- &ignored_actions, &logger);
+ &ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_EQ(1u, ignored_actions.size());
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid3",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
- EXPECT_EQ(3u, logger.log_size());
}
// This tests that we can redirect to about:blank, which is considered
// a kind of cancelling requests.
TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses3) {
EventResponseDeltas deltas;
- TestLogger logger;
helpers::IgnoredActions ignored_actions;
GURL effective_new_url;
@@ -2020,7 +716,7 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses3) {
deltas.push_back(std::move(d0));
}
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
- &ignored_actions, &logger);
+ &ignored_actions);
EXPECT_EQ(new_url_0, effective_new_url);
// Cancel request by redirecting to about:blank. This shall override
@@ -2033,18 +729,15 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses3) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
- &ignored_actions, &logger);
+ &ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_TRUE(ignored_actions.empty());
- EXPECT_EQ(1u, logger.log_size());
}
// This tests that WebSocket requests can not be redirected.
TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses4) {
EventResponseDeltas deltas;
- TestLogger logger;
helpers::IgnoredActions ignored_actions;
GURL effective_new_url;
@@ -2055,7 +748,7 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses4) {
deltas.push_back(std::move(delta));
}
MergeOnBeforeRequestResponses(GURL("ws://example.com"), deltas,
- &effective_new_url, &ignored_actions, &logger);
+ &effective_new_url, &ignored_actions);
EXPECT_EQ(GURL(), effective_new_url);
}
@@ -2077,11 +770,8 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
net::HttpRequestHeaders headers0;
headers0.MergeFrom(base_headers);
WebRequestInfoInitParams info_params;
- info_params.logger = std::make_unique<TestLogger>();
WebRequestInfo info(std::move(info_params));
info.dnr_action.emplace(Action::Type::NONE);
- // Take a reference to TestLogger to simplify accessing TestLogger methods.
- TestLogger& logger = static_cast<TestLogger&>(*info.logger);
MergeOnBeforeSendHeadersResponses(info, deltas, &headers0, &ignored_actions,
&ignore1, &ignore2,
&request_headers_modified0);
@@ -2090,7 +780,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
ASSERT_TRUE(headers0.GetHeader("key2", &header_value));
EXPECT_EQ("value 2", header_value);
EXPECT_EQ(0u, ignored_actions.size());
- EXPECT_EQ(0u, logger.log_size());
EXPECT_FALSE(request_headers_modified0);
// Delete, modify and add a header.
@@ -2103,7 +792,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
ignore1.clear();
ignore2.clear();
bool request_headers_modified1;
@@ -2118,7 +806,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
ASSERT_TRUE(headers1.GetHeader("key3", &header_value));
EXPECT_EQ("value 3", header_value);
EXPECT_EQ(0u, ignored_actions.size());
- EXPECT_EQ(1u, logger.log_size());
EXPECT_TRUE(request_headers_modified1);
// Check that conflicts are atomic, i.e. if one header modification
@@ -2132,7 +819,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
ignore1.clear();
ignore2.clear();
bool request_headers_modified2;
@@ -2151,7 +837,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
- EXPECT_EQ(2u, logger.log_size());
EXPECT_TRUE(request_headers_modified2);
// Check that identical modifications don't conflict and operations
@@ -2165,7 +850,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
ignore1.clear();
ignore2.clear();
bool request_headers_modified3;
@@ -2185,13 +869,11 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
- EXPECT_EQ(3u, logger.log_size());
EXPECT_TRUE(request_headers_modified3);
// Check that headers removed by Declarative Net Request API can't be modified
// and result in a conflict.
ignored_actions.clear();
- logger.clear();
ignore1.clear();
ignore2.clear();
bool request_headers_modified4 = false;
@@ -2219,7 +901,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid3",
web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
- EXPECT_EQ(3u, logger.log_size());
EXPECT_TRUE(request_headers_modified4);
}
@@ -2245,7 +926,6 @@ TEST(ExtensionWebRequestHelpersTest,
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
WebRequestInfoInitParams info_params;
- info_params.logger = std::make_unique<TestLogger>();
WebRequestInfo info(std::move(info_params));
info.dnr_action.emplace(Action::Type::NONE);
helpers::IgnoredActions ignored_actions;
@@ -2255,9 +935,6 @@ TEST(ExtensionWebRequestHelpersTest,
net::HttpRequestHeaders headers;
headers.SetHeader("key1", "value 1");
- // Take a reference to TestLogger to simplify accessing TestLogger methods.
- TestLogger& logger = static_cast<TestLogger&>(*info.logger);
-
MergeOnBeforeSendHeadersResponses(info, deltas, &headers, &ignored_actions,
&removed_headers, &set_headers,
&request_headers_modified);
@@ -2266,7 +943,6 @@ TEST(ExtensionWebRequestHelpersTest,
ASSERT_TRUE(headers.GetHeader("key1", &header_value));
EXPECT_EQ("ext1", header_value);
EXPECT_EQ(1u, ignored_actions.size());
- EXPECT_EQ(2u, logger.log_size());
EXPECT_TRUE(request_headers_modified);
EXPECT_THAT(removed_headers, ::testing::IsEmpty());
EXPECT_THAT(set_headers, ElementsAre("key1"));
@@ -2323,10 +999,7 @@ TEST(ExtensionWebRequestHelpersTest,
ignored_actions.clear();
WebRequestInfoInitParams info_params;
- info_params.logger = std::make_unique<TestLogger>();
WebRequestInfo info(std::move(info_params));
- // Take a reference to TestLogger to simplify accessing TestLogger methods.
- TestLogger& logger = static_cast<TestLogger&>(*info.logger);
MergeOnBeforeSendHeadersResponses(info, deltas, &headers1, &ignored_actions,
&ignore1, &ignore2,
&request_headers_modified1);
@@ -2334,7 +1007,6 @@ TEST(ExtensionWebRequestHelpersTest,
ASSERT_TRUE(headers1.GetHeader("Cookie", &header_value));
EXPECT_EQ("name=new value; name2=new value; name4=\"value 4\"", header_value);
EXPECT_EQ(0u, ignored_actions.size());
- EXPECT_EQ(0u, logger.log_size());
EXPECT_FALSE(request_headers_modified1);
}
@@ -2366,7 +1038,6 @@ std::string GetCookieExpirationDate(int delta_secs) {
TEST(ExtensionWebRequestHelpersTest,
TestMergeCookiesInOnHeadersReceivedResponses) {
- TestLogger logger;
std::string header_value;
EventResponseDeltas deltas;
@@ -2400,9 +1071,8 @@ TEST(ExtensionWebRequestHelpersTest,
}
scoped_refptr<net::HttpResponseHeaders> new_headers0;
MergeCookiesInOnHeadersReceivedResponses(GURL(), deltas, base_headers.get(),
- &new_headers0, &logger);
+ &new_headers0);
EXPECT_FALSE(new_headers0.get());
- EXPECT_EQ(0u, logger.log_size());
ResponseCookieModification add_cookie;
add_cookie.type = helpers::ADD;
@@ -2550,7 +1220,7 @@ TEST(ExtensionWebRequestHelpersTest,
net::HttpUtil::AssembleRawHeaders(base_headers_string));
scoped_refptr<net::HttpResponseHeaders> new_headers1;
MergeCookiesInOnHeadersReceivedResponses(GURL(), deltas, headers1.get(),
- &new_headers1, &logger);
+ &new_headers1);
EXPECT_TRUE(new_headers1->HasHeader("Foo"));
size_t iter = 0;
@@ -2574,7 +1244,6 @@ TEST(ExtensionWebRequestHelpersTest,
while (new_headers1->EnumerateHeader(&iter, "Set-Cookie", &cookie_string))
actual_cookies.insert(cookie_string);
EXPECT_EQ(expected_cookies, actual_cookies);
- EXPECT_EQ(0u, logger.log_size());
}
TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
@@ -2600,11 +1269,8 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
GURL allowed_unsafe_redirect_url0;
WebRequestInfoInitParams info_params;
info_params.url = GURL(kExampleUrl);
- info_params.logger = std::make_unique<TestLogger>();
WebRequestInfo info(std::move(info_params));
info.dnr_action.emplace(Action::Type::NONE);
- // Take a reference to TestLogger to simplify accessing TestLogger methods.
- TestLogger& logger = static_cast<TestLogger&>(*info.logger);
MergeOnHeadersReceivedResponses(info, deltas, base_headers.get(),
&new_headers0, &allowed_unsafe_redirect_url0,
@@ -2613,7 +1279,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
EXPECT_FALSE(new_headers0.get());
EXPECT_TRUE(allowed_unsafe_redirect_url0.is_empty());
EXPECT_EQ(0u, ignored_actions.size());
- EXPECT_EQ(0u, logger.log_size());
EXPECT_FALSE(response_headers_modified0);
{
@@ -2627,7 +1292,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
bool response_headers_modified1;
scoped_refptr<net::HttpResponseHeaders> new_headers1;
GURL allowed_unsafe_redirect_url1;
@@ -2649,7 +1313,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
}
EXPECT_EQ(expected1, actual1);
EXPECT_EQ(0u, ignored_actions.size());
- EXPECT_EQ(1u, logger.log_size());
EXPECT_TRUE(response_headers_modified1);
// Check that we replace response headers only once.
@@ -2664,7 +1327,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
bool response_headers_modified2;
scoped_refptr<net::HttpResponseHeaders> new_headers2;
GURL allowed_unsafe_redirect_url2;
@@ -2684,7 +1346,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_RESPONSE_HEADERS));
- EXPECT_EQ(2u, logger.log_size());
EXPECT_TRUE(response_headers_modified2);
// Ensure headers removed by Declarative Net Request API can't be added by web
@@ -2692,7 +1353,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
info.dnr_action.emplace(Action::Type::REMOVE_HEADERS);
info.dnr_action->response_headers_to_remove = {"key3"};
ignored_actions.clear();
- logger.clear();
bool response_headers_modified3 = false;
scoped_refptr<net::HttpResponseHeaders> new_headers3;
GURL allowed_unsafe_redirect_url3;
@@ -2714,7 +1374,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid1",
web_request::IGNORED_ACTION_TYPE_RESPONSE_HEADERS));
- EXPECT_EQ(2u, logger.log_size());
EXPECT_TRUE(response_headers_modified3);
}
@@ -2746,11 +1405,8 @@ TEST(ExtensionWebRequestHelpersTest,
WebRequestInfoInitParams info_params;
info_params.url = GURL(kExampleUrl);
- info_params.logger = std::make_unique<TestLogger>();
WebRequestInfo info(std::move(info_params));
info.dnr_action.emplace(Action::Type::NONE);
- // Take a reference to TestLogger to simplify accessing TestLogger methods.
- TestLogger& logger = static_cast<TestLogger&>(*info.logger);
MergeOnHeadersReceivedResponses(info, deltas, base_headers.get(),
&new_headers1, &allowed_unsafe_redirect_url1,
@@ -2771,7 +1427,6 @@ TEST(ExtensionWebRequestHelpersTest,
}
EXPECT_EQ(expected1, actual1);
EXPECT_EQ(0u, ignored_actions.size());
- EXPECT_EQ(1u, logger.log_size());
EXPECT_TRUE(response_headers_modified1);
}
@@ -2800,10 +1455,7 @@ TEST(ExtensionWebRequestHelpersTest,
WebRequestInfoInitParams info_params;
info_params.url = GURL(kExampleUrl);
- info_params.logger = std::make_unique<TestLogger>();
WebRequestInfo info(std::move(info_params));
- // Take a reference to TestLogger to simplify accessing TestLogger methods.
- TestLogger& logger = static_cast<TestLogger&>(*info.logger);
MergeOnHeadersReceivedResponses(info, deltas, base_headers.get(),
&new_headers0, &allowed_unsafe_redirect_url0,
@@ -2812,7 +1464,6 @@ TEST(ExtensionWebRequestHelpersTest,
EXPECT_FALSE(new_headers0.get());
EXPECT_TRUE(allowed_unsafe_redirect_url0.is_empty());
EXPECT_EQ(0u, ignored_actions.size());
- EXPECT_EQ(0u, logger.log_size());
EXPECT_FALSE(response_headers_modified0);
// Single redirect.
@@ -2823,7 +1474,6 @@ TEST(ExtensionWebRequestHelpersTest,
deltas.push_back(std::move(d1));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
- logger.clear();
bool response_headers_modified1;
scoped_refptr<net::HttpResponseHeaders> new_headers1;
@@ -2837,12 +1487,10 @@ TEST(ExtensionWebRequestHelpersTest,
EXPECT_TRUE(new_headers1->HasHeaderValue("Location", new_url_1.spec()));
EXPECT_EQ(new_url_1, allowed_unsafe_redirect_url1);
EXPECT_TRUE(ignored_actions.empty());
- EXPECT_EQ(1u, logger.log_size());
EXPECT_FALSE(response_headers_modified1);
}
TEST(ExtensionWebRequestHelpersTest, TestMergeOnAuthRequiredResponses) {
- TestLogger logger;
helpers::IgnoredActions ignored_actions;
EventResponseDeltas deltas;
base::string16 username = base::ASCIIToUTF16("foo");
@@ -2856,11 +1504,10 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnAuthRequiredResponses) {
}
net::AuthCredentials auth0;
bool credentials_set =
- MergeOnAuthRequiredResponses(deltas, &auth0, &ignored_actions, &logger);
+ MergeOnAuthRequiredResponses(deltas, &auth0, &ignored_actions);
EXPECT_FALSE(credentials_set);
EXPECT_TRUE(auth0.Empty());
EXPECT_EQ(0u, ignored_actions.size());
- EXPECT_EQ(0u, logger.log_size());
// Check that we can set AuthCredentials.
{
@@ -2870,16 +1517,14 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnAuthRequiredResponses) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
net::AuthCredentials auth1;
credentials_set =
- MergeOnAuthRequiredResponses(deltas, &auth1, &ignored_actions, &logger);
+ MergeOnAuthRequiredResponses(deltas, &auth1, &ignored_actions);
EXPECT_TRUE(credentials_set);
EXPECT_FALSE(auth1.Empty());
EXPECT_EQ(username, auth1.username());
EXPECT_EQ(password, auth1.password());
EXPECT_EQ(0u, ignored_actions.size());
- EXPECT_EQ(1u, logger.log_size());
// Check that we set AuthCredentials only once.
{
@@ -2889,10 +1534,9 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnAuthRequiredResponses) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
net::AuthCredentials auth2;
credentials_set =
- MergeOnAuthRequiredResponses(deltas, &auth2, &ignored_actions, &logger);
+ MergeOnAuthRequiredResponses(deltas, &auth2, &ignored_actions);
EXPECT_TRUE(credentials_set);
EXPECT_FALSE(auth2.Empty());
EXPECT_EQ(username, auth1.username());
@@ -2901,7 +1545,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnAuthRequiredResponses) {
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_AUTH_CREDENTIALS));
- EXPECT_EQ(2u, logger.log_size());
// Check that we can set identical AuthCredentials twice without causing
// a conflict.
@@ -2912,10 +1555,9 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnAuthRequiredResponses) {
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
- logger.clear();
net::AuthCredentials auth3;
credentials_set =
- MergeOnAuthRequiredResponses(deltas, &auth3, &ignored_actions, &logger);
+ MergeOnAuthRequiredResponses(deltas, &auth3, &ignored_actions);
EXPECT_TRUE(credentials_set);
EXPECT_FALSE(auth3.Empty());
EXPECT_EQ(username, auth1.username());
@@ -2924,7 +1566,6 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnAuthRequiredResponses) {
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_AUTH_CREDENTIALS));
- EXPECT_EQ(3u, logger.log_size());
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc
index 4f7e40c972a..1398d76db6b 100644
--- a/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc
@@ -86,6 +86,7 @@
#include "extensions/test/result_catcher.h"
#include "extensions/test/test_extension_dir.h"
#include "google_apis/gaia/gaia_switches.h"
+#include "mojo/public/cpp/bindings/remote.h"
#include "net/dns/mock_host_resolver.h"
#include "net/http/http_util.h"
#include "net/test/embedded_test_server/default_handlers.h"
@@ -97,7 +98,6 @@
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request_filter.h"
#include "net/url_request/url_request_interceptor.h"
-#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/test/test_url_loader_client.h"
@@ -221,46 +221,6 @@ bool HasSeenWebRequestInBackgroundPage(const Extension* extension,
return seen;
}
-// The DevTool's remote front-end is hardcoded to a URL with a fixed port.
-// Redirect all responses to a URL with port.
-class DevToolsFrontendInterceptor : public net::URLRequestInterceptor {
- public:
- DevToolsFrontendInterceptor(int port, const base::FilePath& root_dir)
- : port_(port), test_root_dir_(root_dir) {}
-
- net::URLRequestJob* MaybeInterceptRequest(
- net::URLRequest* request,
- net::NetworkDelegate* network_delegate) const override {
- // The DevTools front-end has a hard-coded scheme (and implicit port 443).
- // We simulate a response for it.
- // net::URLRequestRedirectJob cannot be used because DevToolsUIBindings
- // rejects URLs whose base URL is not the hard-coded URL.
- if (request->url().EffectiveIntPort() != port_) {
- return new net::URLRequestMockHTTPJob(
- request, network_delegate,
- test_root_dir_.AppendASCII(request->url().path().substr(1)));
- }
- return nullptr;
- }
-
- private:
- int port_;
- base::FilePath test_root_dir_;
-};
-
-void SetUpDevToolsFrontendInterceptorOnIO(int port,
- const base::FilePath& root_dir) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- net::URLRequestFilter::GetInstance()->AddHostnameInterceptor(
- "https", kRemoteFrontendDomain,
- std::make_unique<DevToolsFrontendInterceptor>(port, root_dir));
-}
-
-void TearDownDevToolsFrontendInterceptorOnIO() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- net::URLRequestFilter::GetInstance()->ClearHandlers();
-}
-
} // namespace
class ExtensionWebRequestApiTest : public ExtensionApiTest {
@@ -294,6 +254,14 @@ class ExtensionWebRequestApiTest : public ExtensionApiTest {
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"(
chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
details.requestHeaders.push({name: 'foo', value: 'bar'});
+ details.requestHeaders.push({
+ name: 'frameId',
+ value: details.frameId.toString()
+ });
+ details.requestHeaders.push({
+ name: 'resourceType',
+ value: details.type
+ });
return {requestHeaders: details.requestHeaders};
}, {urls: ['*://*/echoheader*']}, ['blocking', 'requestHeaders']);
@@ -361,32 +329,13 @@ class DevToolsFrontendInWebRequestApiTest : public ExtensionApiTest {
int port = embedded_test_server()->port();
- if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
- url_loader_interceptor_ = std::make_unique<content::URLLoaderInterceptor>(
- base::BindRepeating(&DevToolsFrontendInWebRequestApiTest::OnIntercept,
- base::Unretained(this), port));
- } else {
- base::RunLoop run_loop;
- base::PostTaskWithTraitsAndReply(
- FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&SetUpDevToolsFrontendInterceptorOnIO, port,
- test_root_dir_),
- run_loop.QuitClosure());
- run_loop.Run();
- }
+ url_loader_interceptor_ = std::make_unique<content::URLLoaderInterceptor>(
+ base::BindRepeating(&DevToolsFrontendInWebRequestApiTest::OnIntercept,
+ base::Unretained(this), port));
}
void TearDownOnMainThread() override {
- if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
- url_loader_interceptor_.reset();
- } else {
- base::RunLoop run_loop;
- base::PostTaskWithTraitsAndReply(
- FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&TearDownDevToolsFrontendInterceptorOnIO),
- run_loop.QuitClosure());
- run_loop.Run();
- }
+ url_loader_interceptor_.reset();
ExtensionApiTest::TearDownOnMainThread();
}
@@ -407,9 +356,9 @@ class DevToolsFrontendInWebRequestApiTest : public ExtensionApiTest {
private:
bool OnIntercept(int test_server_port,
content::URLLoaderInterceptor::RequestParams* params) {
- // See comments in DevToolsFrontendInterceptor above. The devtools remote
- // frontend URLs are hardcoded into Chrome and are requested by some of the
- // tests here to exercise their behavior with respect to WebRequest.
+ // The devtools remote frontend URLs are hardcoded into Chrome and are
+ // requested by some of the tests here to exercise their behavior with
+ // respect to WebRequest.
//
// We treat any URL request not targeting the test server as targeting the
// remote frontend, and we intercept them to fulfill from test data rather
@@ -473,8 +422,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestComplex) {
message_;
}
-// This test times out regularly on MSAN trybots. See https://crbug.com/733395.
-#if defined(MEMORY_SANITIZER)
+// This test times out regularly on ASAN/MSAN trybots. See
+// https://crbug.com/733395.
+#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER)
#define MAYBE_WebRequestTypes DISABLED_WebRequestTypes
#else
#define MAYBE_WebRequestTypes WebRequestTypes
@@ -743,12 +693,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
MAYBE_WebRequestDeclarative2) {
ASSERT_TRUE(StartEmbeddedTestServer());
- const char* network_service_arg =
- base::FeatureList::IsEnabled(network::features::kNetworkService)
- ? "NetworkServiceEnabled"
- : "NetworkServiceDisabled";
- ASSERT_TRUE(RunExtensionSubtestWithArg("webrequest", "test_declarative2.html",
- network_service_arg))
+ ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_declarative2.html"))
<< message_;
}
@@ -1532,34 +1477,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebSocketRequestOnWorker) {
<< message_;
}
-// Tests the WebRequestProxyingWebSocket does not crash when there is a
-// connection error before AddChannelRequest is called. Regression test for
-// http://crbug.com/878574.
-IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
- WebSocketConnectionErrorBeforeChannelRequest) {
- if (!base::FeatureList::IsEnabled(network::features::kNetworkService))
- return;
-
- InstallWebRequestExtension("extension");
-
- network::mojom::WebSocketPtr web_socket;
- network::mojom::WebSocketRequest request = mojo::MakeRequest(&web_socket);
- network::mojom::AuthenticationHandlerPtr auth_handler;
- content::RenderFrameHost* host =
- browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame();
- extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get(
- profile())
- ->MaybeProxyWebSocket(host, &request, &auth_handler, nullptr);
- content::BrowserContext::GetDefaultStoragePartition(profile())
- ->GetNetworkContext()
- ->CreateWebSocket(std::move(request), network::mojom::kBrowserProcessId,
- host->GetProcess()->GetID(),
- url::Origin::Create(GURL("http://example.com")),
- network::mojom::kWebSocketOptionNone,
- std::move(auth_handler), nullptr);
- web_socket.reset();
-}
-
// Tests that a clean close from the server is not reported as an error when
// there is a race between OnDropChannel and SendFrame.
// Regression test for https://crbug.com/937790.
@@ -1803,11 +1720,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, InitiatorAccessRequired) {
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
WebRequestApiClearsBindingOnFirstListener) {
- // Skip if network service is disabled since the proxy is not used. Also skip
- // if the proxy is forced since the bindings will never be cleared in that
- // case.
- if (!base::FeatureList::IsEnabled(network::features::kNetworkService) ||
- base::FeatureList::IsEnabled(
+ // Skip if the proxy is forced since the bindings will never be cleared in
+ // that case.
+ if (base::FeatureList::IsEnabled(
extensions_features::kForceWebRequestProxyForTest)) {
return;
}
@@ -1836,9 +1751,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
// Regression test for http://crbug.com/878366.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
WebRequestApiDoesNotCrashOnErrorAfterProfileDestroyed) {
- if (!base::FeatureList::IsEnabled(network::features::kNetworkService))
- return;
-
ASSERT_TRUE(StartEmbeddedTestServer());
// Create a profile that will be destroyed later.
@@ -1859,20 +1771,20 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
content::BrowserContext::GetDefaultStoragePartition(temp_profile)
->FlushNetworkInterfaceForTesting();
- network::mojom::URLLoaderFactoryPtr factory;
- auto request = mojo::MakeRequest(&factory);
+ mojo::Remote<network::mojom::URLLoaderFactory> factory;
+ auto pending_receiver = factory.BindNewPipeAndPassReceiver();
auto temp_web_contents =
WebContents::Create(WebContents::CreateParams(temp_profile));
content::RenderFrameHost* frame = temp_web_contents->GetMainFrame();
EXPECT_TRUE(api->MaybeProxyURLLoaderFactory(
frame->GetProcess()->GetBrowserContext(), frame,
- frame->GetProcess()->GetID(), false, false, &request, nullptr));
+ frame->GetProcess()->GetID(), false, false, &pending_receiver, nullptr));
temp_web_contents.reset();
auto params = network::mojom::URLLoaderFactoryParams::New();
params->process_id = 0;
content::BrowserContext::GetDefaultStoragePartition(temp_profile)
->GetNetworkContext()
- ->CreateURLLoaderFactory(std::move(request), std::move(params));
+ ->CreateURLLoaderFactory(std::move(pending_receiver), std::move(params));
network::TestURLLoaderClient client;
network::mojom::URLLoaderPtr loader;
@@ -2109,21 +2021,7 @@ IN_PROC_BROWSER_TEST_F(LocalNTPInterceptionWebRequestAPITest,
// Ensure that devtools frontend requests are hidden from the webRequest API.
IN_PROC_BROWSER_TEST_F(DevToolsFrontendInWebRequestApiTest, HiddenRequests) {
- // Test expectations differ with the Network Service because of the way
- // request interception is done for the test. In the legacy networking path a
- // URLRequestMockHTTPJob is used, which does not generate
- // |onBeforeHeadersSent| events. With the Network Service enabled, requests
- // issued to HTTP URLs by these tests look like real HTTP requests and
- // therefore do generate |onBeforeHeadersSent| events.
- //
- // These tests adjust their expectations accordingly based on whether or not
- // the Network Service is enabled.
- const char* network_service_arg =
- base::FeatureList::IsEnabled(network::features::kNetworkService)
- ? "NetworkServiceEnabled"
- : "NetworkServiceDisabled";
- ASSERT_TRUE(RunExtensionSubtestWithArg("webrequest", "test_devtools.html",
- network_service_arg))
+ ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_devtools.html"))
<< message_;
}
@@ -2633,21 +2531,51 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
// response for the navigation preload request, and respond with it to create
// the page.
GURL url = embedded_test_server()->GetURL(
- "/echoheader?foo&service-worker-navigation-preload");
+ "/echoheader?frameId&resourceType&service-worker-navigation-preload");
ui_test_utils::NavigateToURL(browser(), url);
+ content::WebContents* web_contents =
+ browser()->tab_strip_model()->GetActiveWebContents();
+
// Since the request was to "/echoheader", the response describes the request
// headers.
//
- // The extension is expected to add a "foo: bar" header to the request
- // before it goes to network. Verify that it did.
+ // The expectation is "0\nmain_frame\ntrue" because...
//
- // The browser adds a "service-worker-navigation-preload: true" header for
- // navigation preload requests, so also sanity check that header to prove
- // that this test is really testing the navigation preload request.
- EXPECT_EQ("bar\ntrue",
- EvalJs(browser()->tab_strip_model()->GetActiveWebContents(),
- "document.body.textContent;"));
+ // 1) The extension is expected to add a "frameId: {id}" header, where {id} is
+ // details.frameId. This id is 0 for the main frame.
+ // 2) The extension is similarly expected to add a "resourceType: {type}"
+ // header, where {type} is details.type.
+ // 3) The browser adds a "service-worker-navigation-preload: true" header for
+ // navigation preload requests, so also sanity check that header to prove
+ // that this test is really testing the navigation preload request.
+ EXPECT_EQ("0\nmain_frame\ntrue",
+ EvalJs(web_contents, "document.body.textContent;"));
+
+ // Repeat the test from an iframe, to test that details.frameId and resource
+ // type is populated correctly.
+ const char kAddIframe[] = R"(
+ (async () => {
+ const iframe = document.createElement('iframe');
+ await new Promise(resolve => {
+ iframe.src = $1;
+ iframe.onload = resolve;
+ document.body.appendChild(iframe);
+ });
+ const result = iframe.contentWindow.document.body.textContent;
+
+ // Expect "{frameId}\nsub_frame\ntrue" where {frameId} is a positive
+ // integer.
+ const split = result.split('\n');
+ if (parseInt(split[0]) > 0 && split[1] == 'sub_frame' &&
+ split[2] == 'true') {
+ return 'ok';
+ }
+ return 'bad result: ' + result;
+ })();
+ )";
+
+ EXPECT_EQ("ok", EvalJs(web_contents, content::JsReplace(kAddIframe, url)));
}
// Ensure we don't strip off initiator incorrectly in web request events when
diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc
index 74cdf220816..3739ff2aa03 100644
--- a/chromium/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/web_request/web_request_event_details_unittest.cc
@@ -5,7 +5,6 @@
#include "extensions/browser/api/web_request/web_request_event_details.h"
#include "base/stl_util.h"
-#include "base/test/scoped_task_environment.h"
#include "base/values.h"
#include "extensions/browser/api/web_request/web_request_api_constants.h"
#include "extensions/browser/api/web_request/web_request_api_helpers.h"
@@ -13,8 +12,6 @@
#include "google_apis/gaia/gaia_urls.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
-#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
-#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
@@ -77,8 +74,6 @@ TEST(WebRequestEventDetailsTest, WhitelistedCopyForPublicSession) {
TEST(WebRequestEventDetailsTest, SetResponseHeaders) {
const int kFilter =
extension_web_request_api_helpers::ExtraInfoSpec::RESPONSE_HEADERS;
- base::test::ScopedTaskEnvironment scoped_task_environment;
- net::TestURLRequestContext context;
char headers_string[] =
"HTTP/1.0 200 OK\r\n"
@@ -90,10 +85,9 @@ TEST(WebRequestEventDetailsTest, SetResponseHeaders) {
{
// Non-Gaia URL.
- std::unique_ptr<net::URLRequest> request = context.CreateRequest(
- GURL("http://www.example.com"), net::DEFAULT_PRIORITY, nullptr,
- TRAFFIC_ANNOTATION_FOR_TESTS);
- WebRequestInfo request_info(request.get());
+ WebRequestInfoInitParams params;
+ params.url = GURL("http://www.example.com");
+ WebRequestInfo request_info(std::move(params));
WebRequestEventDetails details(request_info, kFilter);
details.SetResponseHeaders(request_info, headers.get());
std::unique_ptr<base::DictionaryValue> dict =
@@ -113,10 +107,9 @@ TEST(WebRequestEventDetailsTest, SetResponseHeaders) {
{
// Gaia URL.
- std::unique_ptr<net::URLRequest> gaia_request = context.CreateRequest(
- GaiaUrls::GetInstance()->gaia_url(), net::DEFAULT_PRIORITY, nullptr,
- TRAFFIC_ANNOTATION_FOR_TESTS);
- WebRequestInfo gaia_request_info(gaia_request.get());
+ WebRequestInfoInitParams params;
+ params.url = GaiaUrls::GetInstance()->gaia_url();
+ WebRequestInfo gaia_request_info(std::move(params));
WebRequestEventDetails gaia_details(gaia_request_info, kFilter);
gaia_details.SetResponseHeaders(gaia_request_info, headers.get());
std::unique_ptr<base::DictionaryValue> dict =
diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc
index d9e2bea4e94..c73e3247c93 100644
--- a/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc
@@ -7,20 +7,18 @@
#include <memory>
#include "base/macros.h"
+#include "chrome/browser/extensions/extension_service_test_base.h"
#include "chrome/common/extensions/extension_test_util.h"
#include "chrome/common/url_constants.h"
#include "chromeos/login/login_state/scoped_test_public_session_login_state.h"
#include "content/public/test/test_browser_thread_bundle.h"
+#include "extensions/browser/api/web_request/permission_helper.h"
#include "extensions/browser/api/web_request/web_request_info.h"
#include "extensions/browser/api/web_request/web_request_permissions.h"
-#include "extensions/browser/info_map.h"
+#include "extensions/browser/extension_registry.h"
#include "extensions/common/constants.h"
#include "extensions/common/permissions/permissions_data.h"
#include "ipc/ipc_message.h"
-#include "net/base/request_priority.h"
-#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
-#include "net/url_request/url_request.h"
-#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_CHROMEOS)
@@ -29,25 +27,18 @@
using extension_test_util::LoadManifestUnchecked;
using extensions::Extension;
+using extensions::ExtensionRegistry;
using extensions::Manifest;
using extensions::PermissionsData;
using extensions::WebRequestInfo;
using extensions::WebRequestInfoInitParams;
-class ExtensionWebRequestHelpersTestWithThreadsTest : public testing::Test {
- public:
- ExtensionWebRequestHelpersTestWithThreadsTest()
- : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {}
-
+class ExtensionWebRequestHelpersTestWithThreadsTest
+ : public extensions::ExtensionServiceTestBase {
protected:
void SetUp() override;
- private:
- content::TestBrowserThreadBundle thread_bundle_;
-
- protected:
- net::TestURLRequestContext context;
-
+ extensions::PermissionHelper* permission_helper_ = nullptr;
// This extension has Web Request permissions, but no host permission.
scoped_refptr<Extension> permissionless_extension_;
// This extension has Web Request permissions, and *.com a host permission.
@@ -55,11 +46,12 @@ class ExtensionWebRequestHelpersTestWithThreadsTest : public testing::Test {
// This extension is the same as com_extension, except it's installed from
// Manifest::EXTERNAL_POLICY_DOWNLOAD.
scoped_refptr<Extension> com_policy_extension_;
- scoped_refptr<extensions::InfoMap> extension_info_map_;
};
void ExtensionWebRequestHelpersTestWithThreadsTest::SetUp() {
- testing::Test::SetUp();
+ ExtensionServiceTestBase::SetUp();
+ InitializeEmptyExtensionService();
+ permission_helper_ = extensions::PermissionHelper::Get(browser_context());
std::string error;
permissionless_extension_ = LoadManifestUnchecked("permissions",
@@ -85,21 +77,10 @@ void ExtensionWebRequestHelpersTestWithThreadsTest::SetUp() {
"ext_id_3",
&error);
ASSERT_TRUE(com_policy_extension_.get()) << error;
- extension_info_map_ = new extensions::InfoMap;
- extension_info_map_->AddExtension(permissionless_extension_.get(),
- base::Time::Now(),
- false, // incognito_enabled
- false); // notifications_disabled
- extension_info_map_->AddExtension(
- com_extension_.get(),
- base::Time::Now(),
- false, // incognito_enabled
- false); // notifications_disabled
- extension_info_map_->AddExtension(
- com_policy_extension_.get(),
- base::Time::Now(),
- false, // incognito_enabled
- false); // notifications_disabled
+ ExtensionRegistry::Get(browser_context())
+ ->AddEnabled(permissionless_extension_);
+ ExtensionRegistry::Get(browser_context())->AddEnabled(com_extension_);
+ ExtensionRegistry::Get(browser_context())->AddEnabled(com_policy_extension_);
}
// Ensures that requests to extension blacklist urls can't be intercepted by
@@ -117,12 +98,12 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest,
WebRequestInfo request_1(create_request_params(
"http://www.gstatic.com/chrome/extensions/blacklist"));
EXPECT_TRUE(
- WebRequestPermissions::HideRequest(extension_info_map_.get(), request_1));
+ WebRequestPermissions::HideRequest(permission_helper_, request_1));
WebRequestInfo request_2(create_request_params(
"https://www.gstatic.com/chrome/extensions/blacklist"));
EXPECT_TRUE(
- WebRequestPermissions::HideRequest(extension_info_map_.get(), request_2));
+ WebRequestPermissions::HideRequest(permission_helper_, request_2));
}
// Ensure requests made by the local NTP are hidden from extensions. Regression
@@ -133,14 +114,14 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, LocalNTPRequests) {
auto create_request_params =
[&example_com](const url::Origin& initiator, content::ResourceType type,
extensions::WebRequestResourceType web_request_type,
- bool is_browser_side_navigation) {
+ bool is_navigation_request) {
WebRequestInfoInitParams info_params;
info_params.url = example_com;
info_params.initiator = initiator;
info_params.render_process_id = -1;
info_params.type = type;
info_params.web_request_type = web_request_type;
- info_params.is_browser_side_navigation = is_browser_side_navigation;
+ info_params.is_navigation_request = is_navigation_request;
return info_params;
};
@@ -152,14 +133,14 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, LocalNTPRequests) {
create_request_params(ntp_origin, content::ResourceType::kSubResource,
extensions::WebRequestResourceType::OTHER, false);
EXPECT_TRUE(WebRequestPermissions::HideRequest(
- extension_info_map_.get(), WebRequestInfo(std::move(info_params_1))));
+ permission_helper_, WebRequestInfo(std::move(info_params_1))));
// Sub-frame navigations initiated from the local ntp should be hidden.
WebRequestInfoInitParams info_params_2 = create_request_params(
ntp_origin, content::ResourceType::kSubFrame,
extensions::WebRequestResourceType::SUB_FRAME, true);
EXPECT_TRUE(WebRequestPermissions::HideRequest(
- extension_info_map_.get(), WebRequestInfo(std::move(info_params_2))));
+ permission_helper_, WebRequestInfo(std::move(info_params_2))));
// Sub-frame navigations initiated from a non-sensitive domain should not be
// hidden.
@@ -167,133 +148,115 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, LocalNTPRequests) {
url::Origin::Create(example_com), content::ResourceType::kSubFrame,
extensions::WebRequestResourceType::SUB_FRAME, true);
EXPECT_FALSE(WebRequestPermissions::HideRequest(
- extension_info_map_.get(), WebRequestInfo(std::move(info_params_3))));
+ permission_helper_, WebRequestInfo(std::move(info_params_3))));
}
TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest,
TestCanExtensionAccessURL_HostPermissions) {
- // Request with empty initiator.
- std::unique_ptr<net::URLRequest> request(
- context.CreateRequest(GURL("http://example.com"), net::DEFAULT_PRIORITY,
- NULL, TRAFFIC_ANNOTATION_FOR_TESTS));
-
+ const GURL url("http://example.com");
const content::ResourceType kResourceType =
content::ResourceType::kSubResource;
EXPECT_EQ(PermissionsData::PageAccess::kAllowed,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), permissionless_extension_->id(),
- request->url(),
+ permission_helper_, permissionless_extension_->id(), url,
-1, // No tab id.
false, // crosses_incognito
- WebRequestPermissions::DO_NOT_CHECK_HOST, request->initiator(),
+ WebRequestPermissions::DO_NOT_CHECK_HOST, base::nullopt,
kResourceType));
EXPECT_EQ(PermissionsData::PageAccess::kDenied,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), permissionless_extension_->id(),
- request->url(),
+ permission_helper_, permissionless_extension_->id(), url,
-1, // No tab id.
false, // crosses_incognito
WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL,
- request->initiator(), kResourceType));
+ base::nullopt, kResourceType));
EXPECT_EQ(PermissionsData::PageAccess::kAllowed,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), com_extension_->id(), request->url(),
+ permission_helper_, com_extension_->id(), url,
-1, // No tab id.
false, // crosses_incognito
WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL,
- request->initiator(), kResourceType));
+ base::nullopt, kResourceType));
EXPECT_EQ(
PermissionsData::PageAccess::kAllowed,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), com_extension_->id(), request->url(),
+ permission_helper_, com_extension_->id(), url,
-1, // No tab id.
false, // crosses_incognito
WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL_AND_INITIATOR,
- request->initiator(), kResourceType));
+ base::nullopt, kResourceType));
EXPECT_EQ(PermissionsData::PageAccess::kDenied,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), com_extension_->id(), request->url(),
+ permission_helper_, com_extension_->id(), url,
-1, // No tab id.
false, // crosses_incognito
- WebRequestPermissions::REQUIRE_ALL_URLS, request->initiator(),
+ WebRequestPermissions::REQUIRE_ALL_URLS, base::nullopt,
kResourceType));
- std::unique_ptr<net::URLRequest> request_with_initiator(
- context.CreateRequest(GURL("http://example.com"), net::DEFAULT_PRIORITY,
- nullptr, TRAFFIC_ANNOTATION_FOR_TESTS));
- request_with_initiator->set_initiator(
+ base::Optional<url::Origin> initiator(
url::Origin::Create(GURL("http://www.example.org")));
- EXPECT_EQ(PermissionsData::PageAccess::kAllowed,
- WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), permissionless_extension_->id(),
- request_with_initiator->url(),
- -1, // No tab id.
- false, // crosses_incognito
- WebRequestPermissions::DO_NOT_CHECK_HOST,
- request_with_initiator->initiator(), kResourceType));
+ EXPECT_EQ(
+ PermissionsData::PageAccess::kAllowed,
+ WebRequestPermissions::CanExtensionAccessURL(
+ permission_helper_, permissionless_extension_->id(), url,
+ -1, // No tab id.
+ false, // crosses_incognito
+ WebRequestPermissions::DO_NOT_CHECK_HOST, initiator, kResourceType));
EXPECT_EQ(PermissionsData::PageAccess::kDenied,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), permissionless_extension_->id(),
- request_with_initiator->url(),
+ permission_helper_, permissionless_extension_->id(), url,
-1, // No tab id.
false, // crosses_incognito
WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL,
- request_with_initiator->initiator(), kResourceType));
+ initiator, kResourceType));
EXPECT_EQ(PermissionsData::PageAccess::kAllowed,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), com_extension_->id(),
- request_with_initiator->url(),
+ permission_helper_, com_extension_->id(), url,
-1, // No tab id.
false, // crosses_incognito
WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL,
- request_with_initiator->initiator(), kResourceType));
+ initiator, kResourceType));
// Doesn't have access to the initiator.
EXPECT_EQ(
PermissionsData::PageAccess::kDenied,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), com_extension_->id(),
- request_with_initiator->url(),
+ permission_helper_, com_extension_->id(), url,
-1, // No tab id.
false, // crosses_incognito
WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL_AND_INITIATOR,
- request_with_initiator->initiator(), kResourceType));
+ initiator, kResourceType));
// Navigation requests don't need access to the initiator.
EXPECT_EQ(
PermissionsData::PageAccess::kAllowed,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), com_extension_->id(),
- request_with_initiator->url(),
+ permission_helper_, com_extension_->id(), url,
-1, // No tab id.
false, // crosses_incognito
WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL_AND_INITIATOR,
- request_with_initiator->initiator(),
- content::ResourceType::kSubFrame));
+ initiator, content::ResourceType::kSubFrame));
- EXPECT_EQ(PermissionsData::PageAccess::kDenied,
- WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), com_extension_->id(),
- request_with_initiator->url(),
- -1, // No tab id.
- false, // crosses_incognito
- WebRequestPermissions::REQUIRE_ALL_URLS,
- request_with_initiator->initiator(), kResourceType));
+ EXPECT_EQ(
+ PermissionsData::PageAccess::kDenied,
+ WebRequestPermissions::CanExtensionAccessURL(
+ permission_helper_, com_extension_->id(), url,
+ -1, // No tab id.
+ false, // crosses_incognito
+ WebRequestPermissions::REQUIRE_ALL_URLS, initiator, kResourceType));
// Public Sessions tests.
#if defined(OS_CHROMEOS)
- std::unique_ptr<net::URLRequest> org_request(context.CreateRequest(
- GURL("http://example.org"), net::DEFAULT_PRIORITY, nullptr));
+ const GURL org_url("http://example.org");
// com_extension_ doesn't have host permission for .org URLs.
EXPECT_EQ(PermissionsData::PageAccess::kDenied,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), com_policy_extension_->id(),
- org_request->url(),
+ permission_helper_, com_policy_extension_->id(), org_url,
-1, // No tab id.
false, // crosses_incognito
WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL,
- org_request->initiator(), kResourceType));
+ base::nullopt, kResourceType));
chromeos::ScopedTestPublicSessionLoginState login_state;
@@ -301,34 +264,29 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest,
// are whitelisted.
EXPECT_EQ(PermissionsData::PageAccess::kAllowed,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), com_policy_extension_->id(),
- org_request->url(),
+ permission_helper_, com_policy_extension_->id(), org_url,
-1, // No tab id.
false, // crosses_incognito
WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL,
- org_request->initiator(), kResourceType));
+ base::nullopt, kResourceType));
EXPECT_EQ(PermissionsData::PageAccess::kAllowed,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), com_policy_extension_->id(),
- org_request->url(),
+ permission_helper_, com_policy_extension_->id(), org_url,
-1, // No tab id.
false, // crosses_incognito
- WebRequestPermissions::REQUIRE_ALL_URLS,
- org_request->initiator(), kResourceType));
+ WebRequestPermissions::REQUIRE_ALL_URLS, base::nullopt,
+ kResourceType));
// Make sure that chrome:// URLs cannot be accessed.
- std::unique_ptr<net::URLRequest> chrome_request(
- context.CreateRequest(GURL("chrome://version/"), net::DEFAULT_PRIORITY,
- nullptr, TRAFFIC_ANNOTATION_FOR_TESTS));
+ const GURL chrome_url("chrome://version/");
EXPECT_EQ(PermissionsData::PageAccess::kDenied,
WebRequestPermissions::CanExtensionAccessURL(
- extension_info_map_.get(), com_policy_extension_->id(),
- chrome_request->url(),
+ permission_helper_, com_policy_extension_->id(), chrome_url,
-1, // No tab id.
false, // crosses_incognito
WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL,
- chrome_request->initiator(), kResourceType));
+ base::nullopt, kResourceType));
#endif
}
diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc
index 0799d4a36b2..9d920b10a5c 100644
--- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc
@@ -19,8 +19,8 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/media_device_id.h"
#include "content/public/browser/render_frame_host.h"
+#include "content/public/browser/system_connector.h"
#include "content/public/browser/web_contents.h"
-#include "content/public/common/service_manager_connection.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/error_utils.h"
@@ -135,10 +135,8 @@ std::string WebrtcAudioPrivateFunction::device_id_salt() const {
media::AudioSystem* WebrtcAudioPrivateFunction::GetAudioSystem() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!audio_system_) {
- audio_system_ = audio::CreateAudioSystem(
- content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->Clone());
+ audio_system_ =
+ audio::CreateAudioSystem(content::GetSystemConnector()->Clone());
}
return audio_system_.get();
}
diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc
index 37f2157e186..50073312642 100644
--- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc
@@ -33,8 +33,8 @@
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/media_device_id.h"
+#include "content/public/browser/system_connector.h"
#include "content/public/browser/web_contents.h"
-#include "content/public/common/service_manager_connection.h"
#include "content/public/test/browser_test_utils.h"
#include "extensions/common/permissions/permission_set.h"
#include "extensions/common/permissions/permissions_data.h"
@@ -71,10 +71,8 @@ namespace {
void GetAudioDeviceDescriptions(bool for_input,
AudioDeviceDescriptions* device_descriptions) {
base::RunLoop run_loop;
- std::unique_ptr<media::AudioSystem> audio_system = audio::CreateAudioSystem(
- content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->Clone());
+ std::unique_ptr<media::AudioSystem> audio_system =
+ audio::CreateAudioSystem(content::GetSystemConnector()->Clone());
audio_system->GetDeviceDescriptions(
for_input,
base::BindOnce(
diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc
index 8efee8786a5..3896f0b9e8f 100644
--- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc
@@ -176,7 +176,7 @@ content::RenderProcessHost* WebrtcLoggingPrivateFunction::RphFromRequest(
return rph;
}
-scoped_refptr<WebRtcLoggingHandlerHost>
+WebRtcLoggingHandlerHost*
WebrtcLoggingPrivateFunction::LoggingHandlerFromRequest(
const api::webrtc_logging_private::RequestInfo& request,
const std::string& security_origin) {
@@ -185,12 +185,10 @@ WebrtcLoggingPrivateFunction::LoggingHandlerFromRequest(
// SetError() will have been called by RphFromRequest().
return nullptr;
}
-
- return base::UserDataAdapter<WebRtcLoggingHandlerHost>::Get(
- host, WebRtcLoggingHandlerHost::kWebRtcLoggingHandlerHostKey);
+ return WebRtcLoggingHandlerHost::FromRenderProcessHost(host);
}
-scoped_refptr<WebRtcLoggingHandlerHost>
+WebRtcLoggingHandlerHost*
WebrtcLoggingPrivateFunctionWithGenericCallback::PrepareTask(
const api::webrtc_logging_private::RequestInfo& request,
const std::string& security_origin,
@@ -248,21 +246,16 @@ bool WebrtcLoggingPrivateSetMetaDataFunction::RunAsync() {
EXTENSION_FUNCTION_VALIDATE(params.get());
WebRtcLoggingHandlerHost::GenericDoneCallback callback;
- scoped_refptr<WebRtcLoggingHandlerHost> webrtc_logging_handler_host =
+ WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
PrepareTask(params->request, params->security_origin, &callback);
- if (!webrtc_logging_handler_host.get())
+ if (!webrtc_logging_handler_host)
return false;
std::unique_ptr<MetaDataMap> meta_data(new MetaDataMap());
for (const MetaDataEntry& entry : params->meta_data)
(*meta_data)[entry.key] = entry.value;
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&WebRtcLoggingHandlerHost::SetMetaData,
- webrtc_logging_handler_host, std::move(meta_data),
- callback));
-
+ webrtc_logging_handler_host->SetMetaData(std::move(meta_data), callback);
return true;
}
@@ -271,16 +264,12 @@ bool WebrtcLoggingPrivateStartFunction::RunAsync() {
EXTENSION_FUNCTION_VALIDATE(params.get());
WebRtcLoggingHandlerHost::GenericDoneCallback callback;
- scoped_refptr<WebRtcLoggingHandlerHost> webrtc_logging_handler_host =
+ WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
PrepareTask(params->request, params->security_origin, &callback);
- if (!webrtc_logging_handler_host.get())
+ if (!webrtc_logging_handler_host)
return false;
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&WebRtcLoggingHandlerHost::StartLogging,
- webrtc_logging_handler_host, callback));
-
+ webrtc_logging_handler_host->StartLogging(callback);
return true;
}
@@ -289,9 +278,9 @@ bool WebrtcLoggingPrivateSetUploadOnRenderCloseFunction::RunAsync() {
SetUploadOnRenderClose::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
- scoped_refptr<WebRtcLoggingHandlerHost> webrtc_logging_handler_host(
+ WebRtcLoggingHandlerHost* webrtc_logging_handler_host(
LoggingHandlerFromRequest(params->request, params->security_origin));
- if (!webrtc_logging_handler_host.get())
+ if (!webrtc_logging_handler_host)
return false;
webrtc_logging_handler_host->set_upload_log_on_render_close(
@@ -313,16 +302,12 @@ bool WebrtcLoggingPrivateStopFunction::RunAsync() {
EXTENSION_FUNCTION_VALIDATE(params.get());
WebRtcLoggingHandlerHost::GenericDoneCallback callback;
- scoped_refptr<WebRtcLoggingHandlerHost> webrtc_logging_handler_host =
+ WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
PrepareTask(params->request, params->security_origin, &callback);
- if (!webrtc_logging_handler_host.get())
+ if (!webrtc_logging_handler_host)
return false;
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&WebRtcLoggingHandlerHost::StopLogging,
- webrtc_logging_handler_host, callback));
-
+ webrtc_logging_handler_host->StopLogging(callback);
return true;
}
@@ -331,19 +316,15 @@ bool WebrtcLoggingPrivateStoreFunction::RunAsync() {
EXTENSION_FUNCTION_VALIDATE(params.get());
WebRtcLoggingHandlerHost::GenericDoneCallback callback;
- scoped_refptr<WebRtcLoggingHandlerHost> webrtc_logging_handler_host =
+ WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
PrepareTask(params->request, params->security_origin, &callback);
- if (!webrtc_logging_handler_host.get())
+ if (!webrtc_logging_handler_host)
return false;
const std::string local_log_id(HashIdWithOrigin(params->security_origin,
params->log_id));
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&WebRtcLoggingHandlerHost::StoreLog,
- webrtc_logging_handler_host, local_log_id, callback));
-
+ webrtc_logging_handler_host->StoreLog(local_log_id, callback);
return true;
}
@@ -352,9 +333,9 @@ bool WebrtcLoggingPrivateUploadStoredFunction::RunAsync() {
UploadStored::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
- scoped_refptr<WebRtcLoggingHandlerHost> logging_handler(
- LoggingHandlerFromRequest(params->request, params->security_origin));
- if (!logging_handler.get())
+ WebRtcLoggingHandlerHost* logging_handler =
+ LoggingHandlerFromRequest(params->request, params->security_origin);
+ if (!logging_handler)
return false;
WebRtcLoggingHandlerHost::UploadDoneCallback callback = base::Bind(
@@ -363,11 +344,7 @@ bool WebrtcLoggingPrivateUploadStoredFunction::RunAsync() {
const std::string local_log_id(HashIdWithOrigin(params->security_origin,
params->log_id));
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&WebRtcLoggingHandlerHost::UploadStoredLog,
- logging_handler, local_log_id, callback));
-
+ logging_handler->UploadStoredLog(local_log_id, callback);
return true;
}
@@ -375,18 +352,15 @@ bool WebrtcLoggingPrivateUploadFunction::RunAsync() {
std::unique_ptr<Upload::Params> params(Upload::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
- scoped_refptr<WebRtcLoggingHandlerHost> logging_handler(
- LoggingHandlerFromRequest(params->request, params->security_origin));
- if (!logging_handler.get())
+ WebRtcLoggingHandlerHost* logging_handler =
+ LoggingHandlerFromRequest(params->request, params->security_origin);
+ if (!logging_handler)
return false;
WebRtcLoggingHandlerHost::UploadDoneCallback callback = base::Bind(
&WebrtcLoggingPrivateUploadFunction::FireCallback, this);
- base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&WebRtcLoggingHandlerHost::UploadLog,
- logging_handler, callback));
-
+ logging_handler->UploadLog(callback);
return true;
}
@@ -395,16 +369,12 @@ bool WebrtcLoggingPrivateDiscardFunction::RunAsync() {
EXTENSION_FUNCTION_VALIDATE(params.get());
WebRtcLoggingHandlerHost::GenericDoneCallback callback;
- scoped_refptr<WebRtcLoggingHandlerHost> webrtc_logging_handler_host =
+ WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
PrepareTask(params->request, params->security_origin, &callback);
- if (!webrtc_logging_handler_host.get())
+ if (!webrtc_logging_handler_host)
return false;
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&WebRtcLoggingHandlerHost::DiscardLog,
- webrtc_logging_handler_host, callback));
-
+ webrtc_logging_handler_host->DiscardLog(callback);
return true;
}
@@ -430,25 +400,19 @@ bool WebrtcLoggingPrivateStartRtpDumpFunction::RunAsync() {
return false;
}
- scoped_refptr<WebRtcLoggingHandlerHost> webrtc_logging_handler_host(
- base::UserDataAdapter<WebRtcLoggingHandlerHost>::Get(
- host, WebRtcLoggingHandlerHost::kWebRtcLoggingHandlerHostKey));
+ WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
+ WebRtcLoggingHandlerHost::FromRenderProcessHost(host);
WebRtcLoggingHandlerHost::GenericDoneCallback callback = base::Bind(
&WebrtcLoggingPrivateStartRtpDumpFunction::FireCallback, this);
// This call cannot fail.
content::RenderProcessHost::WebRtcStopRtpDumpCallback stop_callback =
- host->StartRtpDump(params->incoming,
- params->outgoing,
+ host->StartRtpDump(params->incoming, params->outgoing,
base::Bind(&WebRtcLoggingHandlerHost::OnRtpPacket,
- webrtc_logging_handler_host));
+ webrtc_logging_handler_host->GetWeakPtr()));
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&WebRtcLoggingHandlerHost::StartRtpDump,
- webrtc_logging_handler_host, type, callback,
- stop_callback));
+ webrtc_logging_handler_host->StartRtpDump(type, callback, stop_callback);
return true;
}
@@ -474,17 +438,13 @@ bool WebrtcLoggingPrivateStopRtpDumpFunction::RunAsync() {
return false;
}
- scoped_refptr<WebRtcLoggingHandlerHost> webrtc_logging_handler_host(
- base::UserDataAdapter<WebRtcLoggingHandlerHost>::Get(
- host, WebRtcLoggingHandlerHost::kWebRtcLoggingHandlerHostKey));
+ WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
+ WebRtcLoggingHandlerHost::FromRenderProcessHost(host);
WebRtcLoggingHandlerHost::GenericDoneCallback callback = base::Bind(
&WebrtcLoggingPrivateStopRtpDumpFunction::FireCallback, this);
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&WebRtcLoggingHandlerHost::StopRtpDump,
- webrtc_logging_handler_host, type, callback));
+ webrtc_logging_handler_host->StopRtpDump(type, callback);
return true;
}
@@ -567,10 +527,9 @@ bool WebrtcLoggingPrivateStartEventLoggingFunction::RunAsync() {
return false;
}
- scoped_refptr<WebRtcLoggingHandlerHost> webrtc_logging_handler_host(
- base::UserDataAdapter<WebRtcLoggingHandlerHost>::Get(
- host, WebRtcLoggingHandlerHost::kWebRtcLoggingHandlerHostKey));
- if (!webrtc_logging_handler_host.get()) {
+ WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
+ WebRtcLoggingHandlerHost::FromRenderProcessHost(host);
+ if (!webrtc_logging_handler_host) {
SetError("WebRTC logging handler not found.");
return false;
}
@@ -579,13 +538,9 @@ bool WebrtcLoggingPrivateStartEventLoggingFunction::RunAsync() {
base::BindRepeating(
&WebrtcLoggingPrivateStartEventLoggingFunction::FireCallback, this);
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&WebRtcLoggingHandlerHost::StartEventLogging,
- webrtc_logging_handler_host, params->session_id,
- params->max_log_size_bytes, params->output_period_ms,
- params->web_app_id, callback));
-
+ webrtc_logging_handler_host->StartEventLogging(
+ params->session_id, params->max_log_size_bytes, params->output_period_ms,
+ params->web_app_id, callback);
return true;
}
@@ -618,10 +573,9 @@ bool WebrtcLoggingPrivateGetLogsDirectoryFunction::RunAsync() {
// that should be granted access to the logs directory.
content::RenderProcessHost* host = render_frame_host()->GetProcess();
- scoped_refptr<WebRtcLoggingHandlerHost> webrtc_logging_handler_host(
- base::UserDataAdapter<WebRtcLoggingHandlerHost>::Get(
- host, WebRtcLoggingHandlerHost::kWebRtcLoggingHandlerHostKey));
- if (!webrtc_logging_handler_host.get()) {
+ WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
+ WebRtcLoggingHandlerHost::FromRenderProcessHost(host);
+ if (!webrtc_logging_handler_host) {
FireErrorCallback("WebRTC logging handler not found.");
return true;
}
diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h
index cd28a5372ad..34b1124f71e 100644
--- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h
+++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h
@@ -32,7 +32,7 @@ class WebrtcLoggingPrivateFunction : public ChromeAsyncExtensionFunction {
const api::webrtc_logging_private::RequestInfo& request,
const std::string& security_origin);
- scoped_refptr<WebRtcLoggingHandlerHost> LoggingHandlerFromRequest(
+ WebRtcLoggingHandlerHost* LoggingHandlerFromRequest(
const api::webrtc_logging_private::RequestInfo& request,
const std::string& security_origin);
};
@@ -46,10 +46,10 @@ class WebrtcLoggingPrivateFunctionWithGenericCallback
// a generic callback object for when the task is completed.
// If the logging handler can't be found for the given request+origin, the
// returned ptr will be null.
- scoped_refptr<WebRtcLoggingHandlerHost> PrepareTask(
- const api::webrtc_logging_private::RequestInfo& request,
- const std::string& security_origin,
- WebRtcLoggingHandlerHost::GenericDoneCallback* callback);
+ WebRtcLoggingHandlerHost* PrepareTask(
+ const api::webrtc_logging_private::RequestInfo& request,
+ const std::string& security_origin,
+ WebRtcLoggingHandlerHost::GenericDoneCallback* callback);
// Must be called on UI thread.
void FireCallback(bool success, const std::string& error_message);
diff --git a/chromium/chrome/browser/extensions/api/webstore_private/OWNERS b/chromium/chrome/browser/extensions/api/webstore_private/OWNERS
deleted file mode 100644
index 980a7a2a651..00000000000
--- a/chromium/chrome/browser/extensions/api/webstore_private/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-# Anyone in the parent directories can review changes to this directory,
-# but the following people are the most knowledgable:
-asargent@chromium.org
diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc
index fa23cd274f8..ce5a5c00e6e 100644
--- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc
@@ -32,6 +32,7 @@
#include "chrome/common/pref_names.h"
#include "components/crx_file/id_util.h"
#include "components/prefs/pref_service.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/gpu_feature_checker.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
@@ -41,7 +42,6 @@
#include "extensions/common/extension.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"
-#include "services/identity/public/cpp/identity_manager.h"
#include "url/gurl.h"
#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
diff --git a/chromium/chrome/browser/flag-metadata.json b/chromium/chrome/browser/flag-metadata.json
index ea9536adbad..3c264eb1246 100644
--- a/chromium/chrome/browser/flag-metadata.json
+++ b/chromium/chrome/browser/flag-metadata.json
@@ -49,6 +49,11 @@
"expiry_milestone": 80
},
{
+ "name": "show-sync-paused-reason-cookies-cleared-on-exit",
+ "owners": [ "msalama" ],
+ "expiry_milestone": 85
+ },
+ {
"name": "allow-insecure-localhost",
"owners": [ "security-dev" ],
"expiry_milestone": 76
@@ -88,11 +93,21 @@
"expiry_milestone": 76
},
{
+ "name": "android-picture-in-picture-api",
+ "owners": [ "beccahughes", "jazzhsu" ],
+ "expiry_milestone": 78
+ },
+ {
"name": "android-site-settings-ui-refresh",
"owners": [ "hkamila" ],
"expiry_milestone": 76
},
{
+ "name": "animated-avatar-button",
+ "owners": ["jkrcal"],
+ "expiry_milestone": 78
+ },
+ {
"name": "app-management",
"owners": [ "//chrome/browser/resources/app_management/OWNERS" ],
"expiry_milestone": 76
@@ -217,6 +232,11 @@
"expiry_milestone": 79
},
{
+ "name": "autofill-assistant-direct-actions",
+ "owners": [ "//components/autofill_assistant/OWNERS" ],
+ "expiry_milestone": 81
+ },
+ {
"name": "autofill-cache-query-responses",
"owners": [ "rogerm" ],
"expiry_milestone": 72
@@ -326,6 +346,21 @@
"expiry_milestone": 79
},
{
+ "name": "enable-ambient-authentication-in-incognito",
+ "owners": ["rhalavati", "chrome-privacy-core@google.com"],
+ "expiry_milestone": 87
+ },
+ {
+ "name": "enable-ambient-authentication-in-guest-session",
+ "owners": ["rhalavati", "chrome-privacy-core@google.com"],
+ "expiry_milestone": 87
+ },
+ {
+ "name": "enable-autofill-save-card-show-no-thanks",
+ "owners": ["siashah", "jsaul@google.com"],
+ "expiry_milestone": 82
+ },
+ {
"name": "automatic-password-generation",
"owners": [ "ioanap", "fhorschig" ],
"expiry_milestone": 76
@@ -336,6 +371,11 @@
"expiry_milestone": 76
},
{
+ "name": "bluetooth-aggressive-appearance-filter",
+ "owners": [ "hansberry" ],
+ "expiry_milestone": 80
+ },
+ {
"name": "bypass-app-banner-engagement-checks",
"owners": [ "dominickn" ],
"expiry_milestone": 78
@@ -346,6 +386,16 @@
"expiry_milestone": 76
},
{
+ "name": "camera-system-web-app",
+ "owners": [ "calamity", "ortuno" ],
+ "expiry_milestone": 82
+ },
+ {
+ "name": "cast-media-route-provider",
+ "owners": [ "mfoltz", "takumif" ],
+ "expiry_milestone": 83
+ },
+ {
"name": "cct-module",
"owners": [ "mvanouwerkerk", "//chrome/android/java/src/org/chromium/chrome/browser/customtabs/OWNERS" ],
"expiry_milestone": 76
@@ -391,10 +441,25 @@
"expiry_milestone": 78
},
{
+ "name": "chrome-colors-custom-color-picker",
+ "owners": ["gayane"],
+ "expiry_milestone": 79
+ },
+ {
"name": "clear-old-browsing-data",
"owners": [ "dullweber" ],
"expiry_milestone": 78
},
+ {
+ "name": "click-to-call-receiver",
+ "owners": [ "//chrome/browser/sharing/OWNERS" ],
+ "expiry_milestone": 79
+ },
+ {
+ "name": "click-to-call-ui",
+ "owners": [ "//chrome/browser/sharing/OWNERS" ],
+ "expiry_milestone": 79
+ },
{
"name": "click-to-open-pdf",
"owners": [ "tommycli" ],
@@ -458,12 +523,12 @@
{
"name": "cookie-deprecation-messages",
"owners": [ "chlily", "aarontag" ],
- "expiry_milestone": 82
+ "expiry_milestone": 85
},
{
"name": "cookies-without-same-site-must-be-secure",
"owners": [ "chlily", "morlovich" ],
- "expiry_milestone": 80
+ "expiry_milestone": 83
},
{
"name": "cros-regions-mode",
@@ -471,9 +536,9 @@
"expiry_milestone": 80
},
{
- "name": "crostini-app-search",
- "owners": [ "crostini-ui" ],
- "expiry_milestone": 76
+ "name": "cross-origin-embedder-policy",
+ "owners": [ "yhirano" ],
+ "expiry_milestone": 83
},
{
"name": "crostini-backup",
@@ -481,6 +546,11 @@
"expiry_milestone": 77
},
{
+ "name": "crostini-webui-installer",
+ "owners": [ "lxj", "timloh", "benwells" ],
+ "expiry_milestone": 82
+ },
+ {
"name": "crostini-gpu-support",
"owners": [ "nverne", "benwells" ],
"expiry_milestone": 78
@@ -534,6 +604,16 @@
"expiry_milestone": 78
},
{
+ "name": "dial-media-route-provider",
+ "owners": [ "mfoltz", "takumif" ],
+ "expiry_milestone": 83
+ },
+ {
+ "name": "direct-actions",
+ "owners": [ "szermatt", "tedchoc", "twellington" ],
+ "expiry_milestone": 81
+ },
+ {
"name": "direct-manipulation-stylus",
"owners": [ "lanwei", "input-dev" ],
"expiry_milestone": 76
@@ -558,6 +638,13 @@
"expiry_milestone": -1
},
{
+ "name": "disable-accelerated-video-encode",
+ "owners": [ "chromeos-video-eng@google.com" ],
+ // This flag does not expire because it allows users to disable HW video
+ // encoding for debugging purpose and temporary workaround for some issues.
+ "expiry_milestone": -1
+ },
+ {
"name": "disable-best-effort-tasks",
"owners": [ "catan-team@chromium.org" ],
"expiry_milestone": 75
@@ -719,11 +806,6 @@
"expiry_milestone": 76
},
{
- "name": "enable-app-banners",
- "owners": [ "desktop-pwas-team@google.com" ],
- "expiry_milestone": 76
- },
- {
"name": "enable-app-data-search",
"owners": [ "jennyz", "kaznacheev" ],
"expiry_milestone": 78
@@ -734,6 +816,11 @@
"expiry_milestone": 78
},
{
+ "name": "enable-search-box-selection",
+ "owners": [ "ginko", "newcomer" ],
+ "expiry_milestone": 78
+ },
+ {
"name": "enable-app-list-search-autocomplete",
"owners": [ "newcomer" ],
"expiry_milestone": 75
@@ -764,9 +851,14 @@
"expiry_milestone": 78
},
{
+ "name": "enable-assistant-media-session-integration",
+ "owners": [ "croissant-eng" ],
+ "expiry_milestone": 78
+ },
+ {
"name": "enable-assistant-app-support",
"owners": [ "croissant-eng" ],
- "expiry_milestone": 76
+ "expiry_milestone": 78
},
{
"name": "enable-assistant-dsp",
@@ -784,9 +876,9 @@
"expiry_milestone": 76
},
{
- "name": "enable-assistant-voice-match",
+ "name": "enable-assistant-routines",
"owners": [ "croissant-eng" ],
- "expiry_milestone": 76
+ "expiry_milestone": 82
},
{
"name": "enable-async-dns",
@@ -799,6 +891,11 @@
"expiry_milestone": 76
},
{
+ "name": "enable-aura-tooltips-on-windows",
+ "owners": [ "cliffsmo" ],
+ "expiry_milestone": 78
+ },
+ {
"name": "enable-autofill-account-wallet-storage",
"owners": [ "feuunk", "butter-team@google.com" ],
"expiry_milestone": 76
@@ -832,6 +929,11 @@
"expiry_milestone": 76
},
{
+ "name": "enable-autofill-credit-card-upload-feedback",
+ "owners": [ "siyua@chromium.org, payments-autofill-team@google.com" ],
+ "expiry_milestone": 79
+ },
+ {
"name": "enable-autofill-do-not-migrate-unsupported-local-cards",
"owners": [ "sujiezhu@google.com", "jsaul@google.com" ],
"expiry_milestone": 80
@@ -867,26 +969,11 @@
"expiry_milestone": 78
},
{
- "name": "enable-autofill-save-card-improved-user-consent",
- "owners": [ "chrome-autofill@google.com" ],
- "expiry_milestone": 73
- },
- {
"name": "enable-autofill-save-credit-card-uses-improved-messaging",
"owners": [ "siyua@chromium.org", "payments-autofill-team@google.com" ],
"expiry_milestone": 78
},
{
- "name": "enable-autofill-save-credit-card-uses-strike-system",
- "owners": [ "annelim@google.com", "jsaul@google.com" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-autofill-save-credit-card-uses-strike-system-v2",
- "owners": [ "annelim@google.com", "jsaul@google.com" ],
- "expiry_milestone": 76
- },
- {
"name": "enable-autofill-send-experiment-ids-in-payments-rpcs",
"owners": [ "dlkumar@google.com" ],
"expiry_milestone": 76
@@ -917,19 +1004,24 @@
"expiry_milestone": 76
},
{
+ "name": "enable-caption-settings",
+ "owners": [ "evliu" ],
+ "expiry_milestone": 80
+ },
+ {
"name": "enable-chrome-duet",
"owners": [ "mdjones" ],
"expiry_milestone": 79
},
{
"name": "enable-chrome-duet-labels",
- "owners": [ "amaralp" ],
+ "owners": [ "mdjones" ],
"expiry_milestone": 79
},
{
"name": "enable-chromeos-account-manager",
"owners": [ "sinhak@chromium.org" ],
- "expiry_milestone": 76
+ "expiry_milestone": 79
},
{
"name": "enable-cloud-print-xps",
@@ -964,11 +1056,6 @@
"expiry_milestone": 77
},
{
- "name": "enable-cros-ime-service",
- "owners": [ "essential-inputs-team@google.com" ],
- "expiry_milestone": 76
- },
- {
"name": "enable-cros-vm-cups-proxy",
"owners": [ "//chrome/services/cups_proxy/OWNERS" ],
"expiry_milestone": 78
@@ -979,11 +1066,6 @@
"expiry_milestone": 79
},
{
- "name": "enable-custom-context-menu",
- "owners": [ "chrome-android-app" ],
- "expiry_milestone": 77
- },
- {
"name": "enable-custom-mac-paper-sizes",
"owners": [ "//printing/OWNERS" ],
"expiry_milestone": 76
@@ -1000,19 +1082,19 @@
"expiry_milestone": 79
},
{
- "name": "enable-desktop-pwas-link-capturing",
+ "name": "enable-desktop-pwas-local-updating",
"owners": [ "desktop-pwas-team@google.com" ],
- "expiry_milestone": 76
+ "expiry_milestone": 80
},
{
- "name": "enable-desktop-pwas-stay-in-window",
+ "name": "enable-desktop-pwas-omnibox-install",
"owners": [ "desktop-pwas-team@google.com" ],
- "expiry_milestone": 76
+ "expiry_milestone": 79
},
{
- "name": "enable-desktop-pwas-omnibox-install",
+ "name": "enable-desktop-pwas-unified-install",
"owners": [ "desktop-pwas-team@google.com" ],
- "expiry_milestone": 79
+ "expiry_milestone": 78
},
{
"name": "enable-devtools-experiments",
@@ -1026,11 +1108,6 @@
"expiry_milestone": 80
},
{
- "name": "enable-drive-fs",
- "owners": [ "sammc", "dats" ],
- "expiry_milestone": 76
- },
- {
"name": "enable-encryption-migration",
"owners": [ "fukino" ],
"expiry_milestone": 76
@@ -1048,12 +1125,17 @@
{
"name": "enable-experimental-accessibility-language-detection",
"owners": [ "chrishall", "//ui/accessibility/OWNERS" ],
- "expiry_milestone": 76
+ "expiry_milestone": 80
},
{
"name": "enable-experimental-accessibility-switch-access",
- "owners": [ "anastasi@google.com", "dmazzoni", "dtseng" ],
- "expiry_milestone": 76
+ "owners": [ "anastasi@google.com", "//ui/accessibility/OWNERS" ],
+ "expiry_milestone": 78
+ },
+ {
+ "name": "enable-experimental-accessibility-switch-access-text",
+ "owners": [ "anastasi@google.com", "//ui/accessibility/OWNERS" ],
+ "expiry_milestone": 80
},
{
"name": "enable-experimental-accessibility-autoclick",
@@ -1071,6 +1153,11 @@
"expiry_milestone": 78
},
{
+ "name": "enable-experimental-kernel-vm-support",
+ "owners": [ "jflat", "zwisler" ],
+ "expiry_milestone": 78
+ },
+ {
"name": "enable-experimental-productivity-features",
"owners": [ "feature-control@chromium.org" ],
"expiry_milestone": 76
@@ -1105,6 +1192,11 @@
"expiry_milestone": -1
},
{
+ "name": "enable-winrt-sensor-implementation",
+ "owners": [ "wensh@microsoft.com" ],
+ "expiry_milestone": 80
+ },
+ {
"name": "enable-generic-sensor",
"owners": [ "reillyg@chromium.org", "raphael.kubo.da.costa@intel.com" ],
"expiry_milestone": 72
@@ -1174,6 +1266,11 @@
"expiry_milestone": 78
},
{
+ "name": "enable-dbus-and-x11-status-icons",
+ "owners": [ "thestig", "thomasanderson" ],
+ "expiry_milestone": 80
+ },
+ {
"name": "enable-implicit-root-scroller",
"owners": [ "bokan", "input-dev" ],
"expiry_milestone": 75
@@ -1230,6 +1327,16 @@
"expiry_milestone": 78
},
{
+ "name": "enable-defer-all-script",
+ "owners": [ "//components/data_reduction_proxy/OWNERS" ],
+ "expiry_milestone": 82
+ },
+ {
+ "name": "enable-defer-all-script-without-optimization-hints",
+ "owners": [ "//components/data_reduction_proxy/OWNERS" ],
+ "expiry_milestone": 82
+ },
+ {
"name": "enable-layout-ng",
"owners": [ "layout-dev@chromium.org" ],
"expiry_milestone": 80
@@ -1294,11 +1401,6 @@
"expiry_milestone": 76
},
{
- "name": "enable-message-center-new-style-notification",
- "owners": [ "knollr", "peter" ],
- "expiry_milestone": 76
- },
- {
"name": "enable-myfiles-volume",
"owners": [ "lucmult", "noel" ],
"expiry_milestone": 76
@@ -1398,6 +1500,13 @@
"expiry_milestone": 76
},
{
+ "name" : "enable-parental-controls-settings",
+ "owners" : [ "danan", "michaelpg" ],
+ // This flag is used to enable parental controls options in ChromeOS
+ // settings.
+ "expiry_milestone" : 79
+ },
+ {
"name": "enable-parallel-downloading",
"owners": [ "qinmin", "xingliu", "dtrainor" ],
// This flag is used by dev teams on Android to disable this feature, since
@@ -1420,6 +1529,11 @@
"expiry_milestone": 80
},
{
+ "name": "enable-process-sharing-with-default-site-instances",
+ "owners": [ "acolwell" ],
+ "expiry_milestone": 81
+ },
+ {
"name": "enable-process-sharing-with-strict-site-instances",
"owners": [ "japhet" ],
"expiry_milestone": 80
@@ -1465,6 +1579,11 @@
"expiry_milestone": 80
},
{
+ "name": "enable-filtering-scroll-events",
+ "owners": [ "axantoine", "eirage", "nzolghadr", "input-dev" ],
+ "expiry_milestone": 80
+ },
+ {
"name": "enable-resource-load-scheduler",
"owners": [ "toyoshim" ],
"expiry_milestone": 78
@@ -1512,11 +1631,6 @@
"expiry_milestone": 76
},
{
- "name": "enable-send-tab-to-self-history",
- "owners": [ "//components/send_tab_to_self/OWNERS" ],
- "expiry_milestone": 78
- },
- {
"name": "enable-send-tab-to-self-show-sending-ui",
"owners": [ "//components/send_tab_to_self/OWNERS" ],
"expiry_milestone": 77
@@ -1548,6 +1662,11 @@
"expiry_milestone": 77
},
{
+ "name": "enable-sharing-device-registration",
+ "owners": [ "//chrome/browser/sharing/OWNERS" ],
+ "expiry_milestone": 79
+ },
+ {
"name": "enable-show-autofill-signatures",
"owners": [ "kolos" ],
// Used for debugging and QA by the autofill team for the indefinite future.
@@ -1597,64 +1716,9 @@
"expiry_milestone": 80
},
{
- "name": "enable-sync-pseudo-uss-app-list",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-sync-pseudo-uss-apps",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-sync-pseudo-uss-dictionary",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-sync-pseudo-uss-extension-settings",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-sync-pseudo-uss-extensions",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-sync-pseudo-uss-favicons",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-sync-pseudo-uss-history-delete-directives",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-sync-pseudo-uss-preferences",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-sync-pseudo-uss-priority-preferences",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-sync-pseudo-uss-search-engines",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-sync-pseudo-uss-supervised-users",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "enable-sync-pseudo-uss-themes",
- "owners": [ "mastiz", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
+ "name": "enable-sxg-prefetch-cache-for-navigations",
+ "owners": [ "horo", "//content/browser/web_package/OWNERS" ],
+ "expiry_milestone": 80
},
{
"name": "enable-sync-uss-bookmarks",
@@ -1662,6 +1726,11 @@
"expiry_milestone": 76
},
{
+ "name": "enable-sync-uss-nigori",
+ "owners": [ "mmoskvitin@google.com", "//components/sync/OWNERS" ],
+ "expiry_milestone": 78
+ },
+ {
"name": "enable-sync-uss-passwords",
"owners": [ "mamir", "//components/sync/OWNERS" ],
"expiry_milestone": 77
@@ -1724,6 +1793,11 @@
"expiry_milestone": -1
},
{
+ "name": "enable-two-panes-start-surface",
+ "owners": [ "gogerald"],
+ "expiry_milestone": 83
+ },
+ {
"name": "enable-unsafe-webgpu",
"owners": [ "//third_party/blink/renderer/modules/webgpu/OWNERS" ],
"expiry_milestone": 82
@@ -1752,7 +1826,7 @@
},
{
"name": "enable-virtual-keyboard",
- "owners": [ "//ash/keyboard/ui/OWNERS" ],
+ "owners": [ "//ash/keyboard/OWNERS" ],
// Useful for debugging the virtual keyboard on non-tablet devices.
"expiry_milestone": -1
},
@@ -1762,9 +1836,9 @@
"expiry_milestone": 76
},
{
- "name": "enable-viz-hit-test",
- "owners": [ "riajiang", "sunxd", "rjkroege" ],
- "expiry_milestone": 76
+ "name": "enable-viz-hit-test-surface-layer",
+ "owners": [ "yigu", "rjkroege", "kylechar" ],
+ "expiry_milestone": 78
},
{
"name": "enable-web-authentication-ble-support",
@@ -1943,6 +2017,11 @@
"expiry_milestone": 79
},
{
+ "name": "ev-details-in-page-info",
+ "owners": [ "cthomp" ],
+ "expiry_milestone": 83
+ },
+ {
"name": "expensive-background-timer-throttling",
"owners": [ "altimin" ],
"expiry_milestone": 76
@@ -1975,6 +2054,11 @@
"expiry_milestone": -1
},
{
+ "name": "font-src-local-matching",
+ "owners": [ "drott", "layout-dev" ],
+ "expiry_milestone": 82
+ },
+ {
"name": "force-use-chrome-camera",
"owners": [ "shenghao", "chromeos-camera-app-eng@google.com" ],
"expiry_milestone": 76
@@ -1992,7 +2076,12 @@
{
"name": "file-manager-feedback-panel",
"owners": [ "adanilo" ],
- "expiry_milestone": 77
+ "expiry_milestone": 78
+ },
+ {
+ "name": "file-manager-format-dialog",
+ "owners": [ "austinct" ],
+ "expiry_milestone": 78
},
{
// See https://crbug.com/904630, offical builds only.
@@ -2077,11 +2166,27 @@
"expiry_milestone": 78
},
{
+ "name": "gaia-action-buttons",
+ "owners": [ "jeroendh", "rsorokin" ],
+ "expiry_milestone": 79
+ },
+ {
"name": "gdi-text-printing",
"owners": [ "//printing/OWNERS" ],
"expiry_milestone": 76
},
{
+ "name": "gesture-properties-dbus-service",
+ "owners": [ "hcutts", "chromeos-tango@google.com" ],
+ // Used by developers for debugging and input device tuning.
+ "expiry_milestone": -1
+ },
+ {
+ "name": "global-media-controls",
+ "owners": [ "steimel", "media-dev" ],
+ "expiry_milestone": 84
+ },
+ {
"name": "google-password-manager",
"owners": [ "ioanap", "jdoerrie" ],
"expiry_milestone": 76
@@ -2089,7 +2194,7 @@
{
"name": "grid-layout-for-ntp-shortcuts",
"owners": [ "kristipark", "ramyan" ],
- "expiry_milestone": 77
+ "expiry_milestone": 78
},
{
"name": "handwriting-gesture",
@@ -2107,6 +2212,11 @@
"expiry_milestone": 77
},
{
+ "name": "harfbuzz-pdf-subsetter",
+ "owners": ["dhoss", "thestig"],
+ "expiry_milestone": 80
+ },
+ {
"name": "http-auth-committed-interstitials",
"owners": [ "jdeblasio", "estark" ],
"expiry_milestone": 77
@@ -2150,7 +2260,12 @@
{
"name": "interest-feed-content-suggestions",
"owners": [ "//chrome/android/feed/OWNERS" ],
- "expiry_milestone": 76
+ "expiry_milestone": 78
+ },
+ {
+ "name": "interest-feed-notifications",
+ "owners": [ "iwells", "//chrome/android/feed/OWNERS" ],
+ "expiry_milestone": 78
},
{
"name": "isolate-origins",
@@ -2200,8 +2315,12 @@
},
{
"name": "media-router-cast-allow-all-ips",
- // "owners": [ "your-team" ],
- "expiry_milestone": 76
+ "owners": [ "mfoltz" ],
+ // This flag is used by users with unusual network configurations to allow
+ // cast to work, but enabling this behavior has security implications that
+ // aren't easily understood. It is primarily used by support to help
+ // individual users get cast working.
+ "expiry_milestone": -1
},
{
"name": "memlog",
@@ -2236,11 +2355,21 @@
"expiry_milestone": 80
},
{
+ "name": "mirroring-service",
+ "owners": [ "mfoltz", "takumif" ],
+ "expiry_milestone": 83
+ },
+ {
"name": "mobile-identity-consistency",
"owners": [ "bsazonov", "droger", "msarda" ],
"expiry_milestone": 80
},
{
+ "name": "mouse-subframe-no-implicit-capture",
+ "owners": [ "eirage", "input-dev" ],
+ "expiry_milestone": 78
+ },
+ {
"name": "native-file-system-api",
"owners": [ "mek", "pwnall" ],
"expiry_milestone": 80
@@ -2291,6 +2420,11 @@
"expiry_milestone": 79
},
{
+ "name": "notification-scheduler-debug-options",
+ "owners": [ "//chrome/browser/notifications/scheduler/OWNERS" ],
+ "expiry_milestone": 81
+ },
+ {
"name": "ntp-customization-menu-v2",
"owners": ["kmilka", "ramyan"],
"expiry_milestone": 77
@@ -2386,19 +2520,19 @@
"expiry_milestone": 80
},
{
+ "name": "omnibox-disable-instant-extended-limit",
+ "owners": [ "pnoland", "chrome-omnibox-team@google.com" ],
+ "expiry_milestone": 80
+ },
+ {
"name": "omnibox-display-title-for-current-url",
"owners": [ "chrome-omnibox-team@google.com" ],
"expiry_milestone": 76
},
{
"name": "omnibox-drive-suggestions",
- "owners": [ "skare", "chrome-omnibox-team@google.com" ],
- "expiry_milestone": 76
- },
- {
- "name": "omnibox-deduplicate-drive-urls",
- "owners": [ "skare", "chrome-omnibox-team@google.com" ],
- "expiry_milestone": 76
+ "owners": [ "manukh", "chrome-omnibox-team@google.com" ],
+ "expiry_milestone": 80
},
{
"name": "omnibox-experimental-keyword-mode",
@@ -2421,9 +2555,9 @@
"expiry_milestone": 80
},
{
- "name": "omnibox-new-answer-layout",
- "owners": [ "chrome-omnibox-team@google.com" ],
- "expiry_milestone": 76
+ "name": "omnibox-on-device-head-suggestions",
+ "owners": [ "cechen", "suggest-2g@google.com" ],
+ "expiry_milestone": 80
},
{
"name": "omnibox-pedal-suggestions",
@@ -2446,6 +2580,11 @@
"expiry_milestone": 76
},
{
+ "name": "omnibox-search-engine-logo",
+ "owners": [ "wylieb", "chrome-omnibox-team@google.com" ],
+ "expiry_milestone": 80
+ },
+ {
"name": "omnibox-short-bookmark-suggestions",
"owners": [ "krb", "chrome-omnibox-team@google.com" ],
"expiry_milestone": 78
@@ -2521,6 +2660,11 @@
"expiry_milestone": 80
},
{
+ "name": "omnibox-wrap-popup-position",
+ "owners": [ "krb", "chrome-omnibox-team@google.com" ],
+ "expiry_milestone": 81
+ },
+ {
"name": "omnibox-zero-suggestions-on-ntp",
"owners": [ "chrome-android-omnibox-team@google.com" ],
"expiry_milestone": 81
@@ -2541,6 +2685,11 @@
"expiry_milestone": 79
},
{
+ "name": "openxr",
+ "owners": [ "//device/vr/OWNERS", "xr-dev@chromium.org" ],
+ "expiry_milestone": 79
+ },
+ {
"name": "out-of-blink-cors",
"owners": [ "toyoshim" ],
"expiry_milestone": 76
@@ -2588,6 +2737,16 @@
"expiry_milestone": 78
},
{
+ "name": "password-editing-android",
+ "owners": [ "izuzic", "fhorschig" ],
+ "expiry_milestone": 80
+ },
+ {
+ "name": "password-manager-onboarding-android",
+ "owners": ["achulkov", "ioanap"],
+ "expiry_milestone": 80
+ },
+ {
"name": "passwords-keyboard-accessory",
"owners": [ "fhorschig" ],
"expiry_milestone": 76
@@ -2618,6 +2777,16 @@
"expiry_milestone": 78
},
{
+ "name": "periodic-background-sync",
+ "owners": [ "nator" ],
+ "expiry_milestone": 80
+ },
+ {
+ "name": "policy-atomic-group-enabled",
+ "owners": [ "ydago" ],
+ "expiry_milestone": 80
+ },
+ {
"name": "postscript-printing",
"owners": [ "//printing/OWNERS" ],
"expiry_milestone": 76
@@ -2638,16 +2807,6 @@
"expiry_milestone": 83
},
{
- "name": "pwa-improved-splash-screen",
- "owners": [ "desktop-pwas-team@google.com" ],
- "expiry_milestone": 76
- },
- {
- "name": "pwa-persistent-notification",
- "owners": [ "desktop-pwas-team@google.com" ],
- "expiry_milestone": 76
- },
- {
"name": "reader-mode-heuristics",
"owners": [ "mdjones" ],
"expiry_milestone": 78
@@ -2668,19 +2827,19 @@
"expiry_milestone": 75
},
{
- "name": "safe-browsing-telemetry-for-apk-downloads",
+ "name": "safe-browsing-use-local-blacklists-v2",
"owners": [ "vakh" ],
"expiry_milestone": 76
},
{
- "name": "safe-browsing-use-local-blacklists-v2",
- "owners": [ "vakh" ],
- "expiry_milestone": 76
+ "name": "safety-tips",
+ "owners": [ "jdeblasio", "estark", "meacer" ],
+ "expiry_milestone": 82
},
{
"name": "same-site-by-default-cookies",
"owners": [ "chlily", "morlovich" ],
- "expiry_milestone": 80
+ "expiry_milestone": 83
},
{
"name": "scheduler-configuration",
@@ -2688,6 +2847,11 @@
"expiry_milestone": 77
},
{
+ "name": "security-interstitials-dark-mode",
+ "owners": ["estark"],
+ "expiry_milestone": 79
+ },
+ {
"name": "session-restore-prioritizes-background-use-cases",
"owners": [ "chrisha" ],
"expiry_milestone": 76
@@ -2705,11 +2869,26 @@
"expiry_milestone": 78
},
{
+ "name": "shelf-dense-clamshell",
+ "owners": [ "manucornet", "mmourgos" ],
+ "expiry_milestone": 82
+ },
+ {
+ "name": "shelf-hotseat",
+ "owners": [ "manucornet", "newcomer" ],
+ "expiry_milestone": 82
+ },
+ {
"name": "shelf-hover-previews",
"owners": [ "manucornet" ],
"expiry_milestone": 77
},
{
+ "name": "shelf-scrollable",
+ "owners": [ "andrewxu", "manucornet" ],
+ "expiry_milestone": 82
+ },
+ {
"name": "shopping-assist",
"owners": [ "yusufo", "donnd" ],
// This is a shopping assistance experiment for Android.
@@ -2722,9 +2901,9 @@
"expiry_milestone": -1
},
{
- "name": "show-managed-ui",
- // "owners": [ "your-team" ],
- "expiry_milestone": 76
+ "name": "show-bluetooth-device-battery",
+ "owners": [ "hansberry" ],
+ "expiry_milestone": 80
},
{
"name": "show-taps",
@@ -2741,6 +2920,11 @@
"expiry_milestone": -1
},
{
+ "name": "enable-bookmark-reorder",
+ "owners": ["jhimawan@google.com", "twellington" ],
+ "expiry_milestone": 80
+ },
+ {
"name": "enable-virtual-desks",
"owners": [ "afakhry" ],
// This is a flag to enable or disable the Virtual Desks feature.
@@ -2769,6 +2953,11 @@
"expiry_milestone": 78
},
{
+ "name": "release-notes",
+ "owners": [ "yulunwu" ],
+ "expiry_milestone": 79
+ },
+ {
"name": "smart-dim-model-v3",
"owners": [ "amoylan", "jiameng" ],
"expiry_milestone": 80
@@ -2804,21 +2993,6 @@
"expiry_milestone": 80
},
{
- "name": "sync-USS-autofill-profile",
- "owners": [ "jkrcal", "treib", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "sync-USS-autofill-wallet-data",
- "owners": [ "jkrcal", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
- "name": "sync-USS-autofill-wallet-metadata",
- "owners": [ "jkrcal", "//components/sync/OWNERS" ],
- "expiry_milestone": 76
- },
- {
"name": "sync-support-secondary-account",
"owners": [ "treib", "//components/sync/OWNERS" ],
"expiry_milestone": 76
@@ -2849,6 +3023,11 @@
"expiry_milestone": 82
},
{
+ "name": "terminal-system-app",
+ "owners": [ "joelhockey", "benwells", "//chrome/browser/chromeos/guest_os/OWNERS" ],
+ "expiry_milestone": 82
+ },
+ {
"name": "treat-unsafe-downloads-as-active-content",
"owners": [ "jdeblasio", "cthomp" ],
"expiry_milestone": 79
@@ -2877,8 +3056,13 @@
},
{
"name": "touch-selection-strategy",
- // "owners": [ "your-team" ],
- "expiry_milestone": 76
+ "owners": [ "omrilio" ],
+ "expiry_milestone": 80
+ },
+ {
+ "name": "touch-to-fill",
+ "owners": [ "jdoerrie" ],
+ "expiry_milestone": 80
},
{
"name": "touchpad-overscroll-history-navigation",
@@ -2954,6 +3138,11 @@
"expiry_milestone": -1
},
{
+ "name": "usage-stats",
+ "owners": [ "pnoland", "chromeshine@google.com" ],
+ "expiry_milestone": 80
+ },
+ {
"name": "use-angle",
"owners": [ "angle-team@google.com" ],
// This flag is used by certain customers to set ANGLE to use its OpenGL
@@ -3000,9 +3189,9 @@
"expiry_milestone": 76
},
{
- "name": "user-activity-prediction-ml-service",
- "owners": [ "amoylan", "pmalani", "jiameng" ],
- "expiry_milestone": 76
+ "name": "username-first-flow",
+ "owners": [ "dvadym" ],
+ "expiry_milestone": 80
},
{
"name": "views-cast-dialog",
@@ -3047,6 +3236,11 @@
"expiry_milestone": 79
},
{
+ "name": "win-use-native-spellchecker",
+ "owners": [ "gujen@google.com", "yyushkina@google.com" ],
+ "expiry_milestone": 81
+ },
+ {
"name": "windows-mixed-reality",
"owners": [ "//device/vr/OWNERS", "xr-dev@chromium.org" ],
"expiry_milestone": 79
@@ -3060,6 +3254,11 @@
"name": "enable-streamlined-usb-printer-setup",
"owners": [ "baileyberro" ],
"expiry_milestone": 77
+ },
+ {
+ "name": "update-hover-at-begin-frame",
+ "owners": [ "lanwei", "input-dev" ],
+ "expiry_milestone": 81
}
// This is an alphabetized list; please do your part to keep it organized by
diff --git a/chromium/chrome/browser/flag-never-expire-list.json b/chromium/chrome/browser/flag-never-expire-list.json
index df1a9e701bf..0abc52c88cd 100644
--- a/chromium/chrome/browser/flag-never-expire-list.json
+++ b/chromium/chrome/browser/flag-never-expire-list.json
@@ -21,6 +21,7 @@
"disable-accelerated-2d-canvas",
"disable-accelerated-mjpeg-decode",
"disable-accelerated-video-decode",
+ "disable-accelerated-video-encode",
"disable-explicit-dma-fences",
"disable-javascript-harmony-shipping",
"disable-threaded-scrolling",
@@ -59,11 +60,13 @@
"force-text-direction",
"force-ui-direction",
"force-update-menu-type",
+ "gesture-properties-dbus-service",
"ignore-gpu-blacklist",
"ignore-previews-blocklist",
"in-product-help-demo-mode-choice",
"list-all-display-modes",
"load-media-router-component-extension",
+ "media-router-cast-allow-all-ips",
"memlog",
"memlog-sampling-rate",
"memlog-stack-mode",
diff --git a/chromium/chrome/browser/chromeos/supervision/mojom/BUILD.gn b/chromium/chrome/browser/lookalikes/safety_tips/BUILD.gn
index 0603a847482..bbcd9b1bf1d 100644
--- a/chromium/chrome/browser/chromeos/supervision/mojom/BUILD.gn
+++ b/chromium/chrome/browser/lookalikes/safety_tips/BUILD.gn
@@ -2,14 +2,10 @@
# 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")
+import("//third_party/protobuf/proto_library.gni")
-mojom("mojom") {
+proto_library("proto") {
sources = [
- "onboarding_controller.mojom",
- ]
-
- public_deps = [
- "//url/mojom:url_mojom_gurl",
+ "safety_tips.proto",
]
}
diff --git a/chromium/chrome/browser/media/BUILD.gn b/chromium/chrome/browser/media/BUILD.gn
index 4ffc0e9a556..c6768520d73 100644
--- a/chromium/chrome/browser/media/BUILD.gn
+++ b/chromium/chrome/browser/media/BUILD.gn
@@ -13,6 +13,9 @@ mojom("mojo_bindings") {
public_deps = [
"//url/mojom:url_mojom_origin",
]
+
+ # TODO(https://crbug.com/968369): Change to use new names.
+ use_old_js_lite_bindings_names = true
}
proto_library("media_engagement_preload_proto") {
diff --git a/chromium/chrome/browser/media/router/BUILD.gn b/chromium/chrome/browser/media/router/BUILD.gn
index ed765cc2222..29707ed15c0 100644
--- a/chromium/chrome/browser/media/router/BUILD.gn
+++ b/chromium/chrome/browser/media/router/BUILD.gn
@@ -68,6 +68,9 @@ static_library("router") {
if (enable_extensions) {
deps += [
"discovery",
+ "//components/mirroring/mojom:host",
+ "//components/mirroring/mojom:service",
+ "//components/translate/content/common",
"//mojo/public/cpp/bindings",
"//ui/base:buildflags",
]
@@ -142,17 +145,27 @@ static_library("router") {
if (enable_openscreen) {
sources += [
+ "providers/openscreen/discovery/open_screen_listener.cc",
+ "providers/openscreen/discovery/open_screen_listener.h",
"providers/openscreen/network_service_async_packet_sender.cc",
"providers/openscreen/network_service_async_packet_sender.h",
"providers/openscreen/network_service_quic_packet_writer.cc",
"providers/openscreen/network_service_quic_packet_writer.h",
"providers/openscreen/platform/logging.cc",
+ "providers/openscreen/platform/task_runner.cc",
+ "providers/openscreen/platform/task_runner.h",
+ "providers/openscreen/platform/time.cc",
+ "providers/openscreen/platform/trace_logging_platform.cc",
]
configs +=
[ "//third_party/openscreen/src/build:allow_build_from_embedder" ]
- deps += [ "//third_party/openscreen/src/platform" ]
+ deps += [
+ "//third_party/openscreen/src/osp/public",
+ "//third_party/openscreen/src/platform",
+ "//third_party/openscreen/src/util",
+ ]
}
}
}
diff --git a/chromium/chrome/browser/media/router/discovery/BUILD.gn b/chromium/chrome/browser/media/router/discovery/BUILD.gn
index ef7a335a6d3..2e3ece36bfe 100644
--- a/chromium/chrome/browser/media/router/discovery/BUILD.gn
+++ b/chromium/chrome/browser/media/router/discovery/BUILD.gn
@@ -1,7 +1,8 @@
# 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.
-#
+
+assert(!is_android)
static_library("discovery") {
inputs = [
@@ -46,6 +47,16 @@ static_library("discovery") {
"dial/safe_dial_app_info_parser.h",
"dial/safe_dial_device_description_parser.cc",
"dial/safe_dial_device_description_parser.h",
+ "discovery_network_info.cc",
+ "discovery_network_info.h",
+ "discovery_network_list.h",
+ "discovery_network_list_wifi.h",
+ "discovery_network_monitor.cc",
+ "discovery_network_monitor.h",
+ "discovery_network_monitor_metric_observer.cc",
+ "discovery_network_monitor_metric_observer.h",
+ "discovery_network_monitor_metrics.cc",
+ "discovery_network_monitor_metrics.h",
"mdns/cast_media_sink_service.cc",
"mdns/cast_media_sink_service.h",
"mdns/cast_media_sink_service_impl.cc",
@@ -62,28 +73,20 @@ static_library("discovery") {
"media_sink_discovery_metrics.h",
]
- if (!is_android) {
- sources += [
- "discovery_network_info.cc",
- "discovery_network_info.h",
- "discovery_network_list.h",
- "discovery_network_list_wifi.h",
- "discovery_network_list_wifi_linux.cc",
- "discovery_network_list_wifi_mac.mm",
- "discovery_network_list_win.cc",
- "discovery_network_monitor.cc",
- "discovery_network_monitor.h",
- "discovery_network_monitor_metric_observer.cc",
- "discovery_network_monitor_metric_observer.h",
- "discovery_network_monitor_metrics.cc",
- "discovery_network_monitor_metrics.h",
- ]
- if (is_posix) {
- sources += [ "discovery_network_list_posix.cc" ]
- }
+ if (is_linux) {
+ sources += [ "discovery_network_list_wifi_linux.cc" ]
+ }
+
+ if (is_posix) {
+ sources += [ "discovery_network_list_posix.cc" ]
}
if (is_mac) {
+ sources += [ "discovery_network_list_wifi_mac.mm" ]
libs = [ "CoreWLAN.framework" ]
}
+
+ if (is_win) {
+ sources += [ "discovery_network_list_win.cc" ]
+ }
}
diff --git a/chromium/chrome/browser/media_router_resources.grdp b/chromium/chrome/browser/media_router_resources.grdp
deleted file mode 100644
index df55acce9e5..00000000000
--- a/chromium/chrome/browser/media_router_resources.grdp
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<grit-part>
- <!-- General -->
- <include name="IDR_MEDIA_ROUTER_COMMON_CSS" file="resources\media_router\media_router_common.css" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_CSS" file="resources\media_router\media_router.css" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_DATA_JS" file="resources\media_router\media_router_data.js" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_JS" file="resources\media_router\media_router.js" flattenhtml="true" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_HTML" file="resources\media_router\media_router.html" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_INTERNALS_HTML" file="resources\media_router\media_router_internals.html" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_INTERNALS_CSS" file="resources\media_router\media_router_internals.css" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_INTERNALS_JS" file="resources\media_router\media_router_internals.js" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_UI_INTERFACE_JS" file="resources\media_router\media_router_ui_interface.js" type="BINDATA" />
-
- <!-- Polymer -->
- <if expr="_google_chrome">
- <include name="IDR_MEDIA_ROUTER_ICONS_HTML" file="resources\media_router_internal\icons\media_router_icons.html" type="BINDATA" />
- </if>
- <if expr="not _google_chrome">
- <include name="IDR_MEDIA_ROUTER_ICONS_HTML" file="resources\media_router\icons\media_router_icons.html" type="BINDATA" />
- </if>
- <include name="IDR_ISSUE_BANNER_HTML" file="resources\media_router\elements\issue_banner\issue_banner.html" type="BINDATA" />
- <include name="IDR_ISSUE_BANNER_JS" file="resources\media_router\elements\issue_banner\issue_banner.js" type="BINDATA" />
- <include name="IDR_ISSUE_BANNER_CSS" file="resources\media_router\elements\issue_banner\issue_banner.css" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_CONTAINER_HTML" file="resources\media_router\elements\media_router_container\media_router_container.html" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_CONTAINER_CSS" file="resources\media_router\elements\media_router_container\media_router_container.css" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_CONTAINER_JS" file="resources\media_router\elements\media_router_container\media_router_container.js" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_HEADER_HTML" file="resources\media_router\elements\media_router_header\media_router_header.html" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_HEADER_CSS" file="resources\media_router\elements\media_router_header\media_router_header.css" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_HEADER_JS" file="resources\media_router\elements\media_router_header\media_router_header.js" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_SEARCH_HIGHLIGHTER_CSS" file="resources\media_router\elements\media_router_search_highlighter\media_router_search_highlighter.css" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_SEARCH_HIGHLIGHTER_HTML" file="resources\media_router\elements\media_router_search_highlighter\media_router_search_highlighter.html" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_SEARCH_HIGHLIGHTER_JS" file="resources\media_router\elements\media_router_search_highlighter\media_router_search_highlighter.js" type="BINDATA" />
- <include name="IDR_ROUTE_CONTROLS_HTML" file="resources\media_router\elements\route_controls\route_controls.html" type="BINDATA" />
- <include name="IDR_ROUTE_CONTROLS_CSS" file="resources\media_router\elements\route_controls\route_controls.css" type="BINDATA" />
- <include name="IDR_ROUTE_CONTROLS_JS" file="resources\media_router\elements\route_controls\route_controls.js" type="BINDATA" />
- <include name="IDR_ROUTE_DETAILS_HTML" file="resources\media_router\elements\route_details\route_details.html" type="BINDATA" />
- <include name="IDR_ROUTE_DETAILS_CSS" file="resources\media_router\elements\route_details\route_details.css" type="BINDATA" />
- <include name="IDR_ROUTE_DETAILS_JS" file="resources\media_router\elements\route_details\route_details.js" type="BINDATA" />
- <include name="IDR_PSEUDO_SINK_SEARCH_STATE_JS" file="resources\media_router\elements\media_router_container\pseudo_sink_search_state.js" type="BINDATA" />
-</grit-part>
diff --git a/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc b/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc
index 1600849a012..140e2f492b6 100644
--- a/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc
+++ b/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc
@@ -8,10 +8,65 @@
#include "base/bind.h"
#include "base/logging.h"
+#include "base/no_destructor.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
-#include "content/public/common/service_manager_connection.h"
-#include "mojo/public/cpp/bindings/strong_binding.h"
+#include "build/build_config.h"
+#include "content/public/common/child_process_host.h"
+#include "mojo/public/cpp/bindings/remote.h"
+#include "mojo/public/cpp/bindings/self_owned_receiver.h"
+#include "services/proxy_resolver/public/mojom/proxy_resolver.mojom.h"
+
+#if defined(OS_ANDROID)
+#include "services/proxy_resolver/proxy_resolver_factory_impl.h"
+#else
+#include "content/public/browser/service_process_host.h"
+#include "services/strings/grit/services_strings.h"
+#endif
+
+namespace {
+
+proxy_resolver::mojom::ProxyResolverFactory* GetProxyResolverFactory() {
+ static base::NoDestructor<
+ mojo::Remote<proxy_resolver::mojom::ProxyResolverFactory>>
+ remote;
+ if (!remote->is_bound()) {
+#if defined(OS_ANDROID)
+ // For Android we just lazily initialize a single factory instance and keep
+ // it around forever.
+ static base::NoDestructor<proxy_resolver::ProxyResolverFactoryImpl> factory(
+ remote->BindNewPipeAndPassReceiver());
+#else
+ // For other platforms we launch the resolver in its own sandboxed service
+ // process.
+ content::ServiceProcessHost::Launch(
+ remote->BindNewPipeAndPassReceiver(),
+ content::ServiceProcessHost::Options()
+#if defined(OS_MACOSX)
+ // The proxy_resolver service runs V8, so it needs to run in the
+ // helper application that has the com.apple.security.cs.allow-jit
+ // code signing entitlement, which is CHILD_RENDERER. The service
+ // still runs under the utility process sandbox.
+ .WithChildFlags(content::ChildProcessHost::CHILD_RENDERER)
+#endif
+ .WithDisplayName(IDS_PROXY_RESOLVER_DISPLAY_NAME)
+ .Pass());
+
+ // The service will report itself idle once there are no more bound
+ // ProxyResolver instances. We drop the Remote at that point to initiate
+ // service process termination. Any subsequent call to
+ // |GetProxyResolverFactory()| will launch a new process.
+ remote->reset_on_idle_timeout(base::TimeDelta());
+
+ // Also reset on disconnection in case, e.g., the service crashes.
+ remote->reset_on_disconnect();
+#endif
+ }
+
+ return remote->get();
+}
+
+} // namespace
ChromeMojoProxyResolverFactory::ChromeMojoProxyResolverFactory() = default;
@@ -19,28 +74,21 @@ ChromeMojoProxyResolverFactory::~ChromeMojoProxyResolverFactory() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
-proxy_resolver::mojom::ProxyResolverFactoryPtr
-ChromeMojoProxyResolverFactory::CreateWithStrongBinding() {
- proxy_resolver::mojom::ProxyResolverFactoryPtr proxy_resolver_factory;
- mojo::MakeStrongBinding(std::make_unique<ChromeMojoProxyResolverFactory>(),
- mojo::MakeRequest(&proxy_resolver_factory));
- return proxy_resolver_factory;
+mojo::PendingRemote<proxy_resolver::mojom::ProxyResolverFactory>
+ChromeMojoProxyResolverFactory::CreateWithSelfOwnedReceiver() {
+ mojo::PendingRemote<proxy_resolver::mojom::ProxyResolverFactory> remote;
+ mojo::MakeSelfOwnedReceiver(
+ std::make_unique<ChromeMojoProxyResolverFactory>(),
+ remote.InitWithNewPipeAndPassReceiver());
+ return remote;
}
void ChromeMojoProxyResolverFactory::CreateResolver(
const std::string& pac_script,
- proxy_resolver::mojom::ProxyResolverRequest req,
- proxy_resolver::mojom::ProxyResolverFactoryRequestClientPtr client) {
+ mojo::PendingReceiver<proxy_resolver::mojom::ProxyResolver> receiver,
+ mojo::PendingRemote<
+ proxy_resolver::mojom::ProxyResolverFactoryRequestClient> client) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
- // Bind a ProxyResolverFactory backed by the proxy resolver service, have it
- // create a ProxyResolverFactory and then destroy the factory, to avoid
- // keeping the service alive after all resolvers have been destroyed.
- proxy_resolver::mojom::ProxyResolverFactoryPtr resolver_factory;
- content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->BindInterface(proxy_resolver::mojom::kProxyResolverServiceName,
- mojo::MakeRequest(&resolver_factory));
- resolver_factory->CreateResolver(pac_script, std::move(req),
- std::move(client));
+ GetProxyResolverFactory()->CreateResolver(pac_script, std::move(receiver),
+ std::move(client));
}
diff --git a/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.h b/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.h
index b04111b3517..0717bca4c15 100644
--- a/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.h
+++ b/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.h
@@ -10,6 +10,7 @@
#include "base/macros.h"
#include "base/sequence_checker.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
#include "services/proxy_resolver/public/mojom/proxy_resolver.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/mojom/connector.mojom.h"
@@ -26,16 +27,17 @@ class ChromeMojoProxyResolverFactory
ChromeMojoProxyResolverFactory();
~ChromeMojoProxyResolverFactory() override;
- // Convenience method that creates a ProxyResolverFactory, and Mojo strong
- // binding wrapping it.
- static proxy_resolver::mojom::ProxyResolverFactoryPtr
- CreateWithStrongBinding();
+ // Convenience method that creates a self-owned ProxyResolverFactory and
+ // returns a remote endpoint to control it.
+ static mojo::PendingRemote<proxy_resolver::mojom::ProxyResolverFactory>
+ CreateWithSelfOwnedReceiver();
// proxy_resolver::mojom::ProxyResolverFactory implementation:
void CreateResolver(
const std::string& pac_script,
- proxy_resolver::mojom::ProxyResolverRequest req,
- proxy_resolver::mojom::ProxyResolverFactoryRequestClientPtr client)
+ mojo::PendingReceiver<proxy_resolver::mojom::ProxyResolver> receiver,
+ mojo::PendingRemote<
+ proxy_resolver::mojom::ProxyResolverFactoryRequestClient> client)
override;
private:
diff --git a/chromium/chrome/browser/notifications/scheduler/BUILD.gn b/chromium/chrome/browser/notifications/scheduler/BUILD.gn
index e749e311d3b..1927f8f6c0f 100644
--- a/chromium/chrome/browser/notifications/scheduler/BUILD.gn
+++ b/chromium/chrome/browser/notifications/scheduler/BUILD.gn
@@ -2,43 +2,13 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-import("//build/buildflag_header.gni")
-
-if (is_android) {
- import("//build/config/android/rules.gni")
-}
-
group("scheduler") {
deps = [
":factory",
]
public_deps = [
- ":public",
- ]
-}
-
-source_set("public") {
- sources = [
- "notification_background_task_scheduler.h",
- "notification_data.cc",
- "notification_data.h",
- "notification_params.cc",
- "notification_params.h",
- "notification_schedule_service.h",
- "notification_scheduler_client.h",
- "notification_scheduler_client_registrar.cc",
- "notification_scheduler_client_registrar.h",
- "notification_scheduler_types.h",
- "schedule_params.cc",
- "schedule_params.h",
- "user_action_handler.h",
- ]
-
- deps = [
- "//base",
- "//components/keyed_service/core",
- "//skia",
+ "//chrome/browser/notifications/scheduler/public",
]
}
@@ -51,106 +21,19 @@ source_set("factory") {
# This target should not depend on anything in //chrome/* except the proto library.
deps = [
- ":lib",
- ":public",
- "//base",
- "//chrome/browser/notifications/proto",
- "//components/keyed_service/core",
- "//components/leveldb_proto",
- ]
-}
-
-# Internal library that embedders should not directly depend on.
-source_set("lib") {
- visibility = [
- ":factory",
- ":scheduler",
- ":unit_tests",
- "//chrome/browser/notifications/scheduler/test:test_lib",
- ]
-
- sources = [
- "background_task_coordinator.cc",
- "background_task_coordinator.h",
- "collection_store.h",
- "display_decider.cc",
- "display_decider.h",
- "distribution_policy.cc",
- "distribution_policy.h",
- "icon_entry.cc",
- "icon_entry.h",
- "icon_store.cc",
- "icon_store.h",
- "impression_history_tracker.cc",
- "impression_history_tracker.h",
- "impression_store.cc",
- "impression_store.h",
- "impression_types.cc",
- "impression_types.h",
- "init_aware_scheduler.cc",
- "init_aware_scheduler.h",
- "notification_entry.cc",
- "notification_entry.h",
- "notification_schedule_service_impl.cc",
- "notification_schedule_service_impl.h",
- "notification_scheduler.cc",
- "notification_scheduler.h",
- "notification_scheduler_context.cc",
- "notification_scheduler_context.h",
- "notification_store.cc",
- "notification_store.h",
- "proto_conversion.cc",
- "proto_conversion.h",
- "scheduled_notification_manager.cc",
- "scheduled_notification_manager.h",
- "scheduler_config.cc",
- "scheduler_config.h",
- "scheduler_utils.cc",
- "scheduler_utils.h",
- ]
-
- # This target should not depend on anything in //chrome/* except the proto library.
- deps = [
- ":public",
"//base",
"//chrome/browser/notifications/proto",
+ "//chrome/browser/notifications/scheduler/internal:lib",
+ "//chrome/browser/notifications/scheduler/public",
"//components/keyed_service/core",
"//components/leveldb_proto",
"//skia",
]
}
-source_set("unit_tests") {
+group("unit_tests") {
testonly = true
- sources = [
- "background_task_coordinator_unittest.cc",
- "display_decider_unittest.cc",
- "distribution_policy_unittest.cc",
- "icon_store_unittest.cc",
- "impression_history_tracker_unittest.cc",
- "impression_store_unittest.cc",
- "init_aware_scheduler_unittest.cc",
- "notification_store_unittests.cc",
- "proto_conversion_unittest.cc",
- "scheduled_notification_manager_unittest.cc",
- "scheduler_utils_unittest.cc",
- ]
-
deps = [
- ":lib",
- ":public",
- "//chrome/browser/notifications/proto",
- "//chrome/browser/notifications/scheduler/test:test_lib",
- "//components/leveldb_proto:test_support",
- "//testing/gmock",
- "//testing/gtest",
+ "//chrome/browser/notifications/scheduler/internal:unit_tests",
]
}
-
-if (is_android) {
- java_cpp_enum("jni_enums") {
- sources = [
- "notification_scheduler_types.h",
- ]
- }
-}
diff --git a/chromium/chrome/browser/notifications/scheduler/internal/BUILD.gn b/chromium/chrome/browser/notifications/scheduler/internal/BUILD.gn
new file mode 100644
index 00000000000..8b0d12c2d4d
--- /dev/null
+++ b/chromium/chrome/browser/notifications/scheduler/internal/BUILD.gn
@@ -0,0 +1,96 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+# Internal library that embedders should not directly depend on.
+source_set("lib") {
+ visibility = [
+ ":unit_tests",
+ "//chrome/browser/notifications/scheduler",
+ "//chrome/browser/notifications/scheduler:factory",
+ "//chrome/browser/notifications/scheduler/test:test_lib",
+ ]
+
+ sources = [
+ "background_task_coordinator.cc",
+ "background_task_coordinator.h",
+ "collection_store.h",
+ "display_decider.cc",
+ "display_decider.h",
+ "distribution_policy.cc",
+ "distribution_policy.h",
+ "icon_entry.cc",
+ "icon_entry.h",
+ "icon_store.cc",
+ "icon_store.h",
+ "impression_history_tracker.cc",
+ "impression_history_tracker.h",
+ "impression_store.cc",
+ "impression_store.h",
+ "impression_types.cc",
+ "impression_types.h",
+ "init_aware_scheduler.cc",
+ "init_aware_scheduler.h",
+ "noop_notification_schedule_service.cc",
+ "noop_notification_schedule_service.h",
+ "notification_entry.cc",
+ "notification_entry.h",
+ "notification_schedule_service_impl.cc",
+ "notification_schedule_service_impl.h",
+ "notification_scheduler.cc",
+ "notification_scheduler.h",
+ "notification_scheduler_context.cc",
+ "notification_scheduler_context.h",
+ "notification_store.cc",
+ "notification_store.h",
+ "proto_conversion.cc",
+ "proto_conversion.h",
+ "scheduled_notification_manager.cc",
+ "scheduled_notification_manager.h",
+ "scheduler_config.cc",
+ "scheduler_config.h",
+ "scheduler_utils.cc",
+ "scheduler_utils.h",
+ "webui_client.cc",
+ "webui_client.h",
+ ]
+
+ # This target should not depend on anything in //chrome/* except the proto library.
+ deps = [
+ "//base",
+ "//chrome/browser/notifications/proto",
+ "//chrome/browser/notifications/scheduler/public",
+ "//components/keyed_service/core",
+ "//components/leveldb_proto",
+ "//skia",
+ "//ui/gfx/codec",
+ ]
+}
+
+source_set("unit_tests") {
+ testonly = true
+ sources = [
+ "background_task_coordinator_unittest.cc",
+ "display_decider_unittest.cc",
+ "distribution_policy_unittest.cc",
+ "icon_store_unittest.cc",
+ "impression_history_tracker_unittest.cc",
+ "impression_store_unittest.cc",
+ "init_aware_scheduler_unittest.cc",
+ "notification_store_unittest.cc",
+ "proto_conversion_unittest.cc",
+ "scheduled_notification_manager_unittest.cc",
+ "scheduler_utils_unittest.cc",
+ ]
+
+ deps = [
+ "//chrome/browser/notifications/proto",
+ "//chrome/browser/notifications/scheduler/internal:lib",
+ "//chrome/browser/notifications/scheduler/public",
+ "//chrome/browser/notifications/scheduler/test:test_lib",
+ "//components/leveldb_proto:test_support",
+ "//skia",
+ "//testing/gmock",
+ "//testing/gtest",
+ ]
+}
diff --git a/chromium/chrome/browser/notifications/scheduler/public/BUILD.gn b/chromium/chrome/browser/notifications/scheduler/public/BUILD.gn
new file mode 100644
index 00000000000..23e87ae65e5
--- /dev/null
+++ b/chromium/chrome/browser/notifications/scheduler/public/BUILD.gn
@@ -0,0 +1,45 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+if (is_android) {
+ import("//build/config/android/rules.gni")
+}
+
+source_set("public") {
+ sources = [
+ "display_agent.cc",
+ "display_agent.h",
+ "features.cc",
+ "features.h",
+ "impression_detail.cc",
+ "impression_detail.h",
+ "notification_background_task_scheduler.h",
+ "notification_data.cc",
+ "notification_data.h",
+ "notification_params.cc",
+ "notification_params.h",
+ "notification_schedule_service.h",
+ "notification_scheduler_client.h",
+ "notification_scheduler_client_registrar.cc",
+ "notification_scheduler_client_registrar.h",
+ "notification_scheduler_types.h",
+ "schedule_params.cc",
+ "schedule_params.h",
+ "user_action_handler.h",
+ ]
+
+ deps = [
+ "//base",
+ "//components/keyed_service/core",
+ "//skia",
+ ]
+}
+
+if (is_android) {
+ java_cpp_enum("jni_enums") {
+ sources = [
+ "notification_scheduler_types.h",
+ ]
+ }
+}
diff --git a/chromium/chrome/browser/notifications/scheduler/test/BUILD.gn b/chromium/chrome/browser/notifications/scheduler/test/BUILD.gn
index ac37ed52dc0..ec4d2213eb5 100644
--- a/chromium/chrome/browser/notifications/scheduler/test/BUILD.gn
+++ b/chromium/chrome/browser/notifications/scheduler/test/BUILD.gn
@@ -2,23 +2,34 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-import("//build/buildflag_header.gni")
-
-if (is_android) {
- import("//build/config/android/rules.gni")
-}
-
source_set("test_lib") {
- visibility = [ "//chrome/browser/notifications/scheduler:unit_tests" ]
+ testonly = true
+ visibility =
+ [ "//chrome/browser/notifications/scheduler/internal:unit_tests" ]
sources = [
+ "fake_clock.cc",
+ "fake_clock.h",
+ "mock_display_agent.cc",
+ "mock_display_agent.h",
+ "mock_display_decider.cc",
+ "mock_display_decider.h",
+ "mock_impression_history_tracker.cc",
+ "mock_impression_history_tracker.h",
+ "mock_notification_background_task_scheduler.cc",
+ "mock_notification_background_task_scheduler.h",
+ "mock_scheduled_notification_manager.cc",
+ "mock_scheduled_notification_manager.h",
"test_utils.cc",
"test_utils.h",
]
deps = [
"//base",
- "//chrome/browser/notifications/scheduler:lib",
- "//chrome/browser/notifications/scheduler:public",
+ "//chrome/browser/notifications/scheduler/internal:lib",
+ "//chrome/browser/notifications/scheduler/public",
+ "//skia",
+ "//testing/gmock",
+ "//testing/gtest",
]
}
diff --git a/chromium/chrome/browser/printing/background_printing_manager.cc b/chromium/chrome/browser/printing/background_printing_manager.cc
index 14fb359b034..e2594ef515d 100644
--- a/chromium/chrome/browser/printing/background_printing_manager.cc
+++ b/chromium/chrome/browser/printing/background_printing_manager.cc
@@ -152,7 +152,7 @@ std::set<content::WebContents*> BackgroundPrintingManager::CurrentContentSet() {
bool BackgroundPrintingManager::HasPrintPreviewDialog(
WebContents* preview_dialog) {
- return base::ContainsKey(printing_contents_map_, preview_dialog);
+ return base::Contains(printing_contents_map_, preview_dialog);
}
BackgroundPrintingManager::PrintingContents::PrintingContents() = default;
diff --git a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.cc b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.cc
index 5cbacd469f5..36a6b566782 100644
--- a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.cc
+++ b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.cc
@@ -52,9 +52,7 @@ std::string ReadCloudPrintSetupProxyList(const base::FilePath& path) {
} // namespace
CloudPrintProxyService::CloudPrintProxyService(Profile* profile)
- : profile_(profile),
- weak_factory_(this) {
-}
+ : profile_(profile) {}
CloudPrintProxyService::~CloudPrintProxyService() {
}
@@ -81,7 +79,7 @@ void CloudPrintProxyService::Initialize() {
pref_change_registrar_.Init(profile_->GetPrefs());
pref_change_registrar_.Add(
prefs::kCloudPrintProxyEnabled,
- base::Bind(
+ base::BindRepeating(
base::IgnoreResult(
&CloudPrintProxyService::ApplyCloudPrintConnectorPolicy),
base::Unretained(this)));
@@ -90,8 +88,8 @@ void CloudPrintProxyService::Initialize() {
void CloudPrintProxyService::RefreshStatusFromService() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
InvokeServiceTask(
- base::Bind(&CloudPrintProxyService::RefreshCloudPrintProxyStatus,
- weak_factory_.GetWeakPtr()));
+ base::BindOnce(&CloudPrintProxyService::RefreshCloudPrintProxyStatus,
+ weak_factory_.GetWeakPtr()));
}
void CloudPrintProxyService::EnableForUserWithRobot(
@@ -117,8 +115,8 @@ void CloudPrintProxyService::DisableForUser() {
ServiceProcessControl::SERVICE_EVENT_DISABLE,
ServiceProcessControl::SERVICE_EVENT_MAX);
InvokeServiceTask(
- base::Bind(&CloudPrintProxyService::DisableCloudPrintProxy,
- weak_factory_.GetWeakPtr()));
+ base::BindOnce(&CloudPrintProxyService::DisableCloudPrintProxy,
+ weak_factory_.GetWeakPtr()));
}
bool CloudPrintProxyService::ApplyCloudPrintConnectorPolicy() {
diff --git a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.h b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.h
index 6a31220cd34..32cf5b39a99 100644
--- a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.h
+++ b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service.h
@@ -100,7 +100,7 @@ class CloudPrintProxyService : public KeyedService {
cloud_print::mojom::CloudPrintPtr cloud_print_proxy_;
- base::WeakPtrFactory<CloudPrintProxyService> weak_factory_;
+ base::WeakPtrFactory<CloudPrintProxyService> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(CloudPrintProxyService);
};
diff --git a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service_unittest.cc b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service_unittest.cc
index c0377cc3e11..9c689685bca 100644
--- a/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service_unittest.cc
+++ b/chromium/chrome/browser/printing/cloud_print/cloud_print_proxy_service_unittest.cc
@@ -151,8 +151,9 @@ class TestCloudPrintProxyService : public CloudPrintProxyService {
&process_control_.remote_interfaces());
test_api.SetBinderForName(
"cloud_print.mojom.CloudPrint",
- base::Bind(&TestCloudPrintProxyService::HandleCloudPrintProxyRequest,
- base::Unretained(this)));
+ base::BindRepeating(
+ &TestCloudPrintProxyService::HandleCloudPrintProxyRequest,
+ base::Unretained(this)));
service_manager::mojom::InterfaceProviderPtr handle;
mojo::MakeRequest(&handle);
process_control_.SetMojoHandle(std::move(handle));
diff --git a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow.cc b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow.cc
index fbc83d00a1d..376a654a8a1 100644
--- a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow.cc
+++ b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow.cc
@@ -19,7 +19,7 @@ GCDApiFlow::Request::~Request() {
std::unique_ptr<GCDApiFlow> GCDApiFlow::Create(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
- identity::IdentityManager* identity_manager) {
+ signin::IdentityManager* identity_manager) {
return std::make_unique<GCDApiFlowImpl>(url_loader_factory, identity_manager);
}
diff --git a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow.h b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow.h
index 189e7ef6f56..e8b6948eda3 100644
--- a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow.h
+++ b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow.h
@@ -20,7 +20,7 @@ namespace base {
class DictionaryValue;
}
-namespace identity {
+namespace signin {
class IdentityManager;
}
@@ -78,7 +78,7 @@ class GCDApiFlow {
static std::unique_ptr<GCDApiFlow> Create(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
- identity::IdentityManager* identity_manager);
+ signin::IdentityManager* identity_manager);
virtual void Start(std::unique_ptr<Request> request) = 0;
diff --git a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc
index 3a53cb39cc5..4d0de850450 100644
--- a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc
+++ b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.cc
@@ -18,13 +18,13 @@
#include "chrome/browser/printing/cloud_print/gcd_constants.h"
#include "chrome/common/cloud_print/cloud_print_constants.h"
#include "components/cloud_devices/common/cloud_devices_urls.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "net/base/load_flags.h"
#include "net/base/url_util.h"
#include "net/http/http_status_code.h"
#include "net/url_request/url_request_status.h"
-#include "services/identity/public/cpp/identity_manager.h"
-#include "services/identity/public/cpp/primary_account_access_token_fetcher.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
@@ -91,10 +91,9 @@ net::NetworkTrafficAnnotationTag GetNetworkTrafficAnnotation(
GCDApiFlowImpl::GCDApiFlowImpl(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
- identity::IdentityManager* identity_manager)
+ signin::IdentityManager* identity_manager)
: url_loader_factory_(url_loader_factory),
- identity_manager_(identity_manager),
- weak_factory_(this) {}
+ identity_manager_(identity_manager) {}
GCDApiFlowImpl::~GCDApiFlowImpl() {}
@@ -103,16 +102,16 @@ void GCDApiFlowImpl::Start(std::unique_ptr<Request> request) {
identity::ScopeSet oauth_scopes;
oauth_scopes.insert(request_->GetOAuthScope());
DCHECK(identity_manager_);
- token_fetcher_ = std::make_unique<identity::PrimaryAccountAccessTokenFetcher>(
+ token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>(
"cloud_print", identity_manager_, oauth_scopes,
base::BindOnce(&GCDApiFlowImpl::OnAccessTokenFetchComplete,
base::Unretained(this)),
- identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate);
+ signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate);
}
void GCDApiFlowImpl::OnAccessTokenFetchComplete(
GoogleServiceAuthError error,
- identity::AccessTokenInfo access_token_info) {
+ signin::AccessTokenInfo access_token_info) {
token_fetcher_.reset();
if (error.state() != GoogleServiceAuthError::NONE) {
diff --git a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.h b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.h
index 34bddebae51..29a97fd7b29 100644
--- a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.h
+++ b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_impl.h
@@ -11,9 +11,9 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/printing/cloud_print/gcd_api_flow.h"
-#include "services/identity/public/cpp/access_token_info.h"
+#include "components/signin/public/identity_manager/access_token_info.h"
-namespace identity {
+namespace signin {
class PrimaryAccountAccessTokenFetcher;
}
namespace network {
@@ -29,23 +29,24 @@ class GCDApiFlowImpl : public GCDApiFlow {
// Create an OAuth2-based confirmation.
GCDApiFlowImpl(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
- identity::IdentityManager* identity_manager);
+ signin::IdentityManager* identity_manager);
~GCDApiFlowImpl() override;
// GCDApiFlow implementation:
void Start(std::unique_ptr<Request> request) override;
void OnAccessTokenFetchComplete(GoogleServiceAuthError error,
- identity::AccessTokenInfo access_token_info);
+ signin::AccessTokenInfo access_token_info);
+
private:
void OnDownloadedToString(std::unique_ptr<std::string> response_body);
std::unique_ptr<network::SimpleURLLoader> url_loader_;
- std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_;
+ std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_;
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
- identity::IdentityManager* identity_manager_;
+ signin::IdentityManager* identity_manager_;
std::unique_ptr<Request> request_;
- base::WeakPtrFactory<GCDApiFlowImpl> weak_factory_;
+ base::WeakPtrFactory<GCDApiFlowImpl> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(GCDApiFlowImpl);
};
diff --git a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc
index 10fce0fc9a3..f312905ad0a 100644
--- a/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc
+++ b/chromium/chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc
@@ -15,12 +15,12 @@
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "chrome/browser/printing/cloud_print/gcd_api_flow_impl.h"
+#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_errors.h"
#include "net/http/http_request_headers.h"
-#include "services/identity/public/cpp/identity_test_environment.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -83,7 +83,7 @@ class GCDApiFlowTest : public testing::Test {
private:
content::TestBrowserThreadBundle test_browser_thread_bundle_;
- identity::IdentityTestEnvironment identity_test_environment_;
+ signin::IdentityTestEnvironment identity_test_environment_;
scoped_refptr<network::WeakWrapperSharedURLLoaderFactory>
test_shared_url_loader_factory_;
};
@@ -104,11 +104,11 @@ TEST_F(GCDApiFlowTest, SuccessOAuth2) {
gcd_flow_->OnAccessTokenFetchComplete(
GoogleServiceAuthError::AuthErrorNone(),
- identity::AccessTokenInfo(
+ signin::AccessTokenInfo(
"SomeToken", base::Time::Now() + base::TimeDelta::FromHours(1),
std::string() /* No extra information needed for this test */));
- EXPECT_TRUE(base::ContainsKey(requested_urls, GURL(kConfirmRequest)));
+ EXPECT_TRUE(base::Contains(requested_urls, GURL(kConfirmRequest)));
test_url_loader_factory_.AddResponse(kConfirmRequest, kSampleConfirmResponse);
@@ -122,7 +122,7 @@ TEST_F(GCDApiFlowTest, BadToken) {
EXPECT_CALL(*mock_delegate_, OnGCDApiFlowError(GCDApiFlow::ERROR_TOKEN));
gcd_flow_->OnAccessTokenFetchComplete(
GoogleServiceAuthError(GoogleServiceAuthError::USER_NOT_SIGNED_UP),
- identity::AccessTokenInfo());
+ signin::AccessTokenInfo());
}
TEST_F(GCDApiFlowTest, BadJson) {
@@ -134,11 +134,11 @@ TEST_F(GCDApiFlowTest, BadJson) {
gcd_flow_->OnAccessTokenFetchComplete(
GoogleServiceAuthError::AuthErrorNone(),
- identity::AccessTokenInfo(
+ signin::AccessTokenInfo(
"SomeToken", base::Time::Now() + base::TimeDelta::FromHours(1),
std::string() /* No extra information needed for this test */));
- EXPECT_TRUE(base::ContainsKey(requested_urls, GURL(kConfirmRequest)));
+ EXPECT_TRUE(base::Contains(requested_urls, GURL(kConfirmRequest)));
test_url_loader_factory_.AddResponse(kConfirmRequest,
kFailedConfirmResponseBadJson);
base::RunLoop run_loop;
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow.cc b/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow.cc
index b877102258f..8485c06fe6a 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow.cc
@@ -14,28 +14,31 @@
namespace cloud_print {
-PrivetConfirmApiCallFlow::PrivetConfirmApiCallFlow(
- const std::string& token,
- const ResponseCallback& callback)
- : callback_(callback), token_(token) {
-}
+PrivetConfirmApiCallFlow::PrivetConfirmApiCallFlow(const std::string& token,
+ ResponseCallback callback)
+ : callback_(std::move(callback)), token_(token) {}
PrivetConfirmApiCallFlow::~PrivetConfirmApiCallFlow() {
}
void PrivetConfirmApiCallFlow::OnGCDApiFlowError(GCDApiFlow::Status status) {
- callback_.Run(status);
+ if (callback_)
+ std::move(callback_).Run(status);
}
void PrivetConfirmApiCallFlow::OnGCDApiFlowComplete(
const base::DictionaryValue& value) {
+ if (!callback_)
+ return;
+
bool success = false;
if (!value.GetBoolean(cloud_print::kSuccessValue, &success)) {
- callback_.Run(GCDApiFlow::ERROR_MALFORMED_RESPONSE);
+ std::move(callback_).Run(GCDApiFlow::ERROR_MALFORMED_RESPONSE);
return;
}
- callback_.Run(success ? GCDApiFlow::SUCCESS : GCDApiFlow::ERROR_FROM_SERVER);
+ std::move(callback_).Run(success ? GCDApiFlow::SUCCESS
+ : GCDApiFlow::ERROR_FROM_SERVER);
}
GURL PrivetConfirmApiCallFlow::GetURL() {
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow.h b/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow.h
index 97a1e0a43ab..5594ddb8075 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow.h
+++ b/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow.h
@@ -14,11 +14,10 @@ namespace cloud_print {
// API call flow for server-side communication with CloudPrint for registration.
class PrivetConfirmApiCallFlow : public CloudPrintApiFlowRequest {
public:
- using ResponseCallback = base::Callback<void(GCDApiFlow::Status)>;
+ using ResponseCallback = base::OnceCallback<void(GCDApiFlow::Status)>;
// Create an OAuth2-based confirmation
- PrivetConfirmApiCallFlow(const std::string& token,
- const ResponseCallback& callback);
+ PrivetConfirmApiCallFlow(const std::string& token, ResponseCallback callback);
~PrivetConfirmApiCallFlow() override;
// CloudPrintApiFlowRequest implementation:
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow_unittest.cc b/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow_unittest.cc
index 19cd9dc7423..7480357c4f5 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow_unittest.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_confirm_api_flow_unittest.cc
@@ -46,7 +46,8 @@ class MockDelegate {
TEST(PrivetConfirmApiFlowTest, Parsing) {
StrictMock<MockDelegate> delegate;
PrivetConfirmApiCallFlow confirmation(
- "123", base::Bind(&MockDelegate::Callback, base::Unretained(&delegate)));
+ "123",
+ base::BindOnce(&MockDelegate::Callback, base::Unretained(&delegate)));
EXPECT_CALL(delegate, Callback(GCDApiFlow::SUCCESS)).Times(1);
base::Optional<base::Value> value =
@@ -56,12 +57,15 @@ TEST(PrivetConfirmApiFlowTest, Parsing) {
ASSERT_TRUE(value->GetAsDictionary(&dictionary));
confirmation.OnGCDApiFlowComplete(*dictionary);
+ PrivetConfirmApiCallFlow confirmation2(
+ "123",
+ base::BindOnce(&MockDelegate::Callback, base::Unretained(&delegate)));
EXPECT_CALL(delegate, Callback(GCDApiFlow::ERROR_FROM_SERVER)).Times(1);
value = base::JSONReader::Read(kFailedConfirmResponse);
ASSERT_TRUE(value);
ASSERT_TRUE(value->GetAsDictionary(&dictionary));
- confirmation.OnGCDApiFlowComplete(*dictionary);
+ confirmation2.OnGCDApiFlowComplete(*dictionary);
}
} // namespace
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_device_lister_unittest.cc b/chromium/chrome/browser/printing/cloud_print/privet_device_lister_unittest.cc
index c71bf33a0b0..45f9a7614b4 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_device_lister_unittest.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_device_lister_unittest.cc
@@ -35,11 +35,12 @@ class ServiceDiscoveryMockDelegate {
class MockServiceWatcher : public ServiceWatcher {
public:
MockServiceWatcher(const std::string& service_type,
- const ServiceWatcher::UpdatedCallback& callback,
+ ServiceWatcher::UpdatedCallback callback,
ServiceDiscoveryMockDelegate* mock_delegate)
- : started_(false), service_type_(service_type), callback_(callback),
- mock_delegate_(mock_delegate) {
- }
+ : started_(false),
+ service_type_(service_type),
+ callback_(std::move(callback)),
+ mock_delegate_(mock_delegate) {}
~MockServiceWatcher() override {}
@@ -116,9 +117,9 @@ class MockServiceDiscoveryClient : public ServiceDiscoveryClient {
// on service type |service_type|.
std::unique_ptr<ServiceWatcher> CreateServiceWatcher(
const std::string& service_type,
- const ServiceWatcher::UpdatedCallback& callback) override {
- return std::make_unique<MockServiceWatcher>(service_type, callback,
- mock_delegate_);
+ ServiceWatcher::UpdatedCallback callback) override {
+ return std::make_unique<MockServiceWatcher>(
+ service_type, std::move(callback), mock_delegate_);
}
// Create a service resolver object for getting detailed service information
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_http.h b/chromium/chrome/browser/printing/cloud_print/privet_http.h
index 75bb2bde161..230e7ef39ac 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_http.h
+++ b/chromium/chrome/browser/printing/cloud_print/privet_http.h
@@ -32,8 +32,8 @@ class PrivetHTTPClient;
class PrivetJSONOperation {
public:
// If value is null, the operation failed.
- typedef base::RepeatingCallback<void(const base::DictionaryValue* /*value*/)>
- ResultCallback;
+ using ResultCallback =
+ base::OnceCallback<void(const base::DictionaryValue* /*value*/)>;
virtual ~PrivetJSONOperation() {}
@@ -52,7 +52,7 @@ class PrivetHTTPClient {
// Creates operation to query basic information about local device.
virtual std::unique_ptr<PrivetJSONOperation> CreateInfoOperation(
- const PrivetJSONOperation::ResultCallback& callback) = 0;
+ PrivetJSONOperation::ResultCallback callback) = 0;
// Creates a URL loader for PrivetV1.
virtual std::unique_ptr<PrivetURLLoader> CreateURLLoader(
@@ -64,31 +64,6 @@ class PrivetHTTPClient {
PrivetURLLoader::TokenCallback token_callback) = 0;
};
-class PrivetDataReadOperation {
- public:
- enum ResponseType {
- RESPONSE_TYPE_ERROR,
- RESPONSE_TYPE_STRING,
- RESPONSE_TYPE_FILE
- };
-
- // If value is null, the operation failed.
- typedef base::Callback<void(
- ResponseType /*response_type*/,
- const std::string& /*response_str*/,
- const base::FilePath& /*response_file_path*/)> ResultCallback;
-
- virtual ~PrivetDataReadOperation() {}
-
- virtual void Start() = 0;
-
- virtual void SetDataRange(int range_start, int range_end) = 0;
-
- virtual void SaveDataToFile() = 0;
-
- virtual PrivetHTTPClient* GetHTTPClient() = 0;
-};
-
// Represents a full registration flow (/privet/register), normally consisting
// of calling the start action, the getClaimToken action, and calling the
// complete action. Some intervention from the caller is required to display the
@@ -193,7 +168,7 @@ class PrivetV1HTTPClient {
// Creates operation to query basic information about local device.
virtual std::unique_ptr<PrivetJSONOperation> CreateInfoOperation(
- const PrivetJSONOperation::ResultCallback& callback) = 0;
+ PrivetJSONOperation::ResultCallback callback) = 0;
// Creates operation to register local device using Privet v1 protocol.
virtual std::unique_ptr<PrivetRegisterOperation> CreateRegisterOperation(
@@ -202,7 +177,7 @@ class PrivetV1HTTPClient {
// Creates operation to query capabilities of local printer.
virtual std::unique_ptr<PrivetJSONOperation> CreateCapabilitiesOperation(
- const PrivetJSONOperation::ResultCallback& callback) = 0;
+ PrivetJSONOperation::ResultCallback callback) = 0;
// Creates operation to submit print job to local printer.
virtual std::unique_ptr<PrivetLocalPrintOperation> CreateLocalPrintOperation(
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_http_impl.cc b/chromium/chrome/browser/printing/cloud_print/privet_http_impl.cc
index fd8214736ac..9f9f45f696c 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_http_impl.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_http_impl.cc
@@ -94,8 +94,8 @@ GURL CreatePrivetParamURL(const std::string& path,
PrivetInfoOperationImpl::PrivetInfoOperationImpl(
PrivetHTTPClient* privet_client,
- const PrivetJSONOperation::ResultCallback& callback)
- : privet_client_(privet_client), callback_(callback) {}
+ PrivetJSONOperation::ResultCallback callback)
+ : privet_client_(privet_client), callback_(std::move(callback)) {}
PrivetInfoOperationImpl::~PrivetInfoOperationImpl() {
}
@@ -116,13 +116,15 @@ PrivetHTTPClient* PrivetInfoOperationImpl::GetHTTPClient() {
void PrivetInfoOperationImpl::OnError(int response_code,
PrivetURLLoader::ErrorType error) {
- callback_.Run(nullptr);
+ if (callback_)
+ std::move(callback_).Run(nullptr);
}
void PrivetInfoOperationImpl::OnParsedJson(int response_code,
const base::DictionaryValue& value,
bool has_error) {
- callback_.Run(&value);
+ if (callback_)
+ std::move(callback_).Run(&value);
}
// static
@@ -303,7 +305,7 @@ void PrivetRegisterOperationImpl::OnPrivetInfoDone(
}
void PrivetRegisterOperationImpl::StartInfoOperation() {
- info_operation_ = privet_client_->CreateInfoOperation(base::BindRepeating(
+ info_operation_ = privet_client_->CreateInfoOperation(base::BindOnce(
&PrivetRegisterOperationImpl::OnPrivetInfoDone, base::Unretained(this)));
info_operation_->Start();
}
@@ -339,11 +341,11 @@ PrivetJSONOperationImpl::PrivetJSONOperationImpl(
PrivetHTTPClient* privet_client,
const std::string& path,
const std::string& query_params,
- const PrivetJSONOperation::ResultCallback& callback)
+ PrivetJSONOperation::ResultCallback callback)
: privet_client_(privet_client),
path_(path),
query_params_(query_params),
- callback_(callback) {}
+ callback_(std::move(callback)) {}
PrivetJSONOperationImpl::~PrivetJSONOperationImpl() {
}
@@ -361,13 +363,15 @@ PrivetHTTPClient* PrivetJSONOperationImpl::GetHTTPClient() {
void PrivetJSONOperationImpl::OnError(int response_code,
PrivetURLLoader::ErrorType error) {
- callback_.Run(nullptr);
+ if (callback_)
+ std::move(callback_).Run(nullptr);
}
void PrivetJSONOperationImpl::OnParsedJson(int response_code,
const base::DictionaryValue& value,
bool has_error) {
- callback_.Run(&value);
+ if (callback_)
+ std::move(callback_).Run(&value);
}
void PrivetJSONOperationImpl::OnNeedPrivetToken(
@@ -394,10 +398,7 @@ PrivetLocalPrintOperationImpl::RunTasksImmediatelyForTesting::
PrivetLocalPrintOperationImpl::PrivetLocalPrintOperationImpl(
PrivetHTTPClient* privet_client,
PrivetLocalPrintOperation::Delegate* delegate)
- : privet_client_(privet_client),
- delegate_(delegate),
- weak_factory_(this) {
-}
+ : privet_client_(privet_client), delegate_(delegate) {}
PrivetLocalPrintOperationImpl::~PrivetLocalPrintOperationImpl() {
}
@@ -408,8 +409,8 @@ void PrivetLocalPrintOperationImpl::Start() {
// We need to get the /info response so we can know which APIs are available.
// TODO(noamsml): Use cached info when available.
info_operation_ = privet_client_->CreateInfoOperation(
- base::BindRepeating(&PrivetLocalPrintOperationImpl::OnPrivetInfoDone,
- weak_factory_.GetWeakPtr()));
+ base::BindOnce(&PrivetLocalPrintOperationImpl::OnPrivetInfoDone,
+ weak_factory_.GetWeakPtr()));
info_operation_->Start();
started_ = true;
}
@@ -692,8 +693,8 @@ const std::string& PrivetHTTPClientImpl::GetName() {
}
std::unique_ptr<PrivetJSONOperation> PrivetHTTPClientImpl::CreateInfoOperation(
- const PrivetJSONOperation::ResultCallback& callback) {
- return std::make_unique<PrivetInfoOperationImpl>(this, callback);
+ PrivetJSONOperation::ResultCallback callback) {
+ return std::make_unique<PrivetInfoOperationImpl>(this, std::move(callback));
}
std::unique_ptr<PrivetURLLoader> PrivetHTTPClientImpl::CreateURLLoader(
@@ -743,7 +744,7 @@ void PrivetHTTPClientImpl::RefreshPrivetToken(
if (info_operation_)
return;
- info_operation_ = CreateInfoOperation(base::BindRepeating(
+ info_operation_ = CreateInfoOperation(base::BindOnce(
&PrivetHTTPClientImpl::OnPrivetInfoDone, base::Unretained(this)));
info_operation_->Start();
}
@@ -778,8 +779,8 @@ const std::string& PrivetV1HTTPClientImpl::GetName() {
std::unique_ptr<PrivetJSONOperation>
PrivetV1HTTPClientImpl::CreateInfoOperation(
- const PrivetJSONOperation::ResultCallback& callback) {
- return info_client_->CreateInfoOperation(callback);
+ PrivetJSONOperation::ResultCallback callback) {
+ return info_client_->CreateInfoOperation(std::move(callback));
}
std::unique_ptr<PrivetRegisterOperation>
@@ -792,9 +793,9 @@ PrivetV1HTTPClientImpl::CreateRegisterOperation(
std::unique_ptr<PrivetJSONOperation>
PrivetV1HTTPClientImpl::CreateCapabilitiesOperation(
- const PrivetJSONOperation::ResultCallback& callback) {
+ PrivetJSONOperation::ResultCallback callback) {
return std::make_unique<PrivetJSONOperationImpl>(
- info_client_.get(), kPrivetCapabilitiesPath, "", callback);
+ info_client_.get(), kPrivetCapabilitiesPath, "", std::move(callback));
}
std::unique_ptr<PrivetLocalPrintOperation>
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_http_impl.h b/chromium/chrome/browser/printing/cloud_print/privet_http_impl.h
index 7c70752acb6..f828c5aa980 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_http_impl.h
+++ b/chromium/chrome/browser/printing/cloud_print/privet_http_impl.h
@@ -36,7 +36,7 @@ class PrivetInfoOperationImpl : public PrivetJSONOperation,
public PrivetURLLoader::Delegate {
public:
PrivetInfoOperationImpl(PrivetHTTPClient* privet_client,
- const PrivetJSONOperation::ResultCallback& callback);
+ PrivetJSONOperation::ResultCallback callback);
~PrivetInfoOperationImpl() override;
// PrivetJSONOperation:
@@ -138,7 +138,7 @@ class PrivetJSONOperationImpl : public PrivetJSONOperation,
PrivetJSONOperationImpl(PrivetHTTPClient* privet_client,
const std::string& path,
const std::string& query_params,
- const PrivetJSONOperation::ResultCallback& callback);
+ PrivetJSONOperation::ResultCallback callback);
~PrivetJSONOperationImpl() override;
// PrivetJSONOperation:
@@ -241,7 +241,7 @@ class PrivetLocalPrintOperationImpl : public PrivetLocalPrintOperation,
std::unique_ptr<PrivetJSONOperation> info_operation_;
std::unique_ptr<printing::PwgRasterConverter> pwg_raster_converter_;
- base::WeakPtrFactory<PrivetLocalPrintOperationImpl> weak_factory_;
+ base::WeakPtrFactory<PrivetLocalPrintOperationImpl> weak_factory_{this};
static bool run_tasks_immediately_for_testing_;
};
@@ -258,7 +258,7 @@ class PrivetHTTPClientImpl : public PrivetHTTPClient {
// PrivetHTTPClient:
const std::string& GetName() override;
std::unique_ptr<PrivetJSONOperation> CreateInfoOperation(
- const PrivetJSONOperation::ResultCallback& callback) override;
+ PrivetJSONOperation::ResultCallback callback) override;
std::unique_ptr<PrivetURLLoader> CreateURLLoader(
const GURL& url,
const std::string& request_type,
@@ -290,12 +290,12 @@ class PrivetV1HTTPClientImpl : public PrivetV1HTTPClient {
// PrivetV1HTTPClient:
const std::string& GetName() override;
std::unique_ptr<PrivetJSONOperation> CreateInfoOperation(
- const PrivetJSONOperation::ResultCallback& callback) override;
+ PrivetJSONOperation::ResultCallback callback) override;
std::unique_ptr<PrivetRegisterOperation> CreateRegisterOperation(
const std::string& user,
PrivetRegisterOperation::Delegate* delegate) override;
std::unique_ptr<PrivetJSONOperation> CreateCapabilitiesOperation(
- const PrivetJSONOperation::ResultCallback& callback) override;
+ PrivetJSONOperation::ResultCallback callback) override;
std::unique_ptr<PrivetLocalPrintOperation> CreateLocalPrintOperation(
PrivetLocalPrintOperation::Delegate* delegate) override;
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc b/chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc
index a41e05d48d2..2d64da95326 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_http_unittest.cc
@@ -373,8 +373,8 @@ class MockJSONCallback{
const base::DictionaryValue* value() { return value_.get(); }
PrivetJSONOperation::ResultCallback callback() {
- return base::Bind(&MockJSONCallback::OnPrivetJSONDone,
- base::Unretained(this));
+ return base::BindOnce(&MockJSONCallback::OnPrivetJSONDone,
+ base::Unretained(this));
}
protected:
std::unique_ptr<base::DictionaryValue> value_;
@@ -1008,7 +1008,6 @@ class PrivetHttpWithServerTest : public ::testing::Test {
std::unique_ptr<EmbeddedTestServer> server_;
std::unique_ptr<PrivetHTTPClientImpl> client_;
scoped_refptr<network::TestSharedURLLoaderFactory> shared_url_loader_factory_;
- base::Closure quit_;
};
class MockPrivetURLLoaderDelegate : public PrivetURLLoader::Delegate {
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_local_printer_lister.cc b/chromium/chrome/browser/printing/cloud_print/privet_local_printer_lister.cc
index 61323d48288..fa0812a257a 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_local_printer_lister.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_local_printer_lister.cc
@@ -72,8 +72,8 @@ void PrivetLocalPrinterLister::DeviceChanged(
device_contexts_[name] = std::move(context);
context_ptr->privet_resolution->Start(
description.address,
- base::Bind(&PrivetLocalPrinterLister::OnPrivetResolved,
- base::Unretained(this), name));
+ base::BindOnce(&PrivetLocalPrinterLister::OnPrivetResolved,
+ base::Unretained(this), name));
}
void PrivetLocalPrinterLister::DeviceCacheFlushed() {
@@ -92,7 +92,7 @@ void PrivetLocalPrinterLister::OnPrivetResolved(
auto it = device_contexts_.find(http_client->GetName());
DCHECK(it != device_contexts_.end());
- it->second->info_operation = http_client->CreateInfoOperation(base::Bind(
+ it->second->info_operation = http_client->CreateInfoOperation(base::BindOnce(
&PrivetLocalPrinterLister::OnPrivetInfoDone, base::Unretained(this),
it->second.get(), http_client->GetName()));
it->second->privet_client = std::move(http_client);
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_notifications.cc b/chromium/chrome/browser/printing/cloud_print/privet_notifications.cc
index 8087b4f7ee5..92f43abc1f0 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_notifications.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_notifications.cc
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/command_line.h"
#include "base/location.h"
-#include "base/metrics/histogram_macros.h"
#include "base/rand_util.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
@@ -34,12 +33,12 @@
#include "chrome/grit/generated_resources.h"
#include "chrome/grit/theme_resources.h"
#include "components/prefs/pref_service.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "net/net_buildflags.h"
-#include "services/identity/public/cpp/identity_manager.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/page_transition_types.h"
#include "ui/base/resource/resource_bundle.h"
@@ -60,23 +59,6 @@ const char kPrivetNotificationID[] = "privet_notification";
const char kPrivetNotificationOriginUrl[] = "chrome://devices";
const int kStartDelaySeconds = 5;
-enum PrivetNotificationsEvent {
- PRIVET_SERVICE_STARTED,
- PRIVET_LISTER_STARTED,
- PRIVET_DEVICE_CHANGED,
- PRIVET_INFO_DONE,
- PRIVET_NOTIFICATION_SHOWN,
- PRIVET_NOTIFICATION_CANCELED,
- PRIVET_NOTIFICATION_CLICKED,
- PRIVET_DISABLE_NOTIFICATIONS_CLICKED,
- PRIVET_EVENT_MAX,
-};
-
-void ReportPrivetUmaEvent(PrivetNotificationsEvent privet_event) {
- UMA_HISTOGRAM_ENUMERATION("LocalDiscovery.PrivetNotificationsEvent",
- privet_event, PRIVET_EVENT_MAX);
-}
-
} // namespace
PrivetNotificationsListener::PrivetNotificationsListener(
@@ -92,7 +74,6 @@ PrivetNotificationsListener::~PrivetNotificationsListener() {
void PrivetNotificationsListener::DeviceChanged(
const std::string& name,
const DeviceDescription& description) {
- ReportPrivetUmaEvent(PRIVET_DEVICE_CHANGED);
auto it = devices_seen_.find(name);
if (it != devices_seen_.end()) {
if (!description.id.empty() && // Device is registered
@@ -116,8 +97,8 @@ void PrivetNotificationsListener::DeviceChanged(
privet_http_factory_->CreatePrivetHTTP(name);
device_context->privet_http_resolution->Start(
description.address,
- base::Bind(&PrivetNotificationsListener::CreateInfoOperation,
- base::Unretained(this)));
+ base::BindOnce(&PrivetNotificationsListener::CreateInfoOperation,
+ base::Unretained(this)));
}
void PrivetNotificationsListener::CreateInfoOperation(
@@ -134,9 +115,8 @@ void PrivetNotificationsListener::CreateInfoOperation(
DeviceContext* device = it->second.get();
device->privet_http.swap(http_client);
device->info_operation = device->privet_http->CreateInfoOperation(
- base::Bind(&PrivetNotificationsListener::OnPrivetInfoDone,
- base::Unretained(this),
- device));
+ base::BindOnce(&PrivetNotificationsListener::OnPrivetInfoDone,
+ base::Unretained(this), device));
device->info_operation->Start();
}
@@ -245,8 +225,8 @@ void PrivetNotificationService::PrivetNotify(int devices_active,
NotificationDisplayService::GetForProfile(
Profile::FromBrowserContext(profile_))
- ->GetDisplayed(base::Bind(&PrivetNotificationService::AddNotification,
- AsWeakPtr(), devices_active, added));
+ ->GetDisplayed(base::BindOnce(&PrivetNotificationService::AddNotification,
+ AsWeakPtr(), devices_active, added));
}
void PrivetNotificationService::AddNotification(
@@ -257,7 +237,7 @@ void PrivetNotificationService::AddNotification(
// If the UI is already open or a device was removed, we'll update the
// existing notification but not add a new one.
const bool notification_exists =
- base::ContainsKey(displayed_notifications, kPrivetNotificationID);
+ base::Contains(displayed_notifications, kPrivetNotificationID);
const bool add_new_notification =
device_added &&
!local_discovery::LocalDiscoveryUIHandler::GetHasVisible();
@@ -290,9 +270,6 @@ void PrivetNotificationService::AddNotification(
kPrivetNotificationID),
rich_notification_data, CreateNotificationDelegate(profile));
- if (add_new_notification)
- ReportPrivetUmaEvent(PRIVET_NOTIFICATION_SHOWN);
-
NotificationDisplayService::GetForProfile(
Profile::FromBrowserContext(profile_))
->Display(NotificationHandler::Type::TRANSIENT, notification,
@@ -300,26 +277,26 @@ void PrivetNotificationService::AddNotification(
}
void PrivetNotificationService::PrivetRemoveNotification() {
- ReportPrivetUmaEvent(PRIVET_NOTIFICATION_CANCELED);
NotificationDisplayService::GetForProfile(
Profile::FromBrowserContext(profile_))
->Close(NotificationHandler::Type::TRANSIENT, kPrivetNotificationID);
}
void PrivetNotificationService::Start() {
-#if defined(CHROMEOS)
+#if defined(OS_CHROMEOS)
auto* identity_manager = IdentityManagerFactory::GetForProfileIfExists(
Profile::FromBrowserContext(profile_));
if (!identity_manager || !identity_manager->HasPrimaryAccount())
return;
-#endif
+#endif // defined(OS_CHROMEOS)
enable_privet_notification_member_.Init(
prefs::kLocalDiscoveryNotificationsEnabled,
Profile::FromBrowserContext(profile_)->GetPrefs(),
- base::Bind(&PrivetNotificationService::OnNotificationsEnabledChanged,
- base::Unretained(this)));
+ base::BindRepeating(
+ &PrivetNotificationService::OnNotificationsEnabledChanged,
+ base::Unretained(this)));
OnNotificationsEnabledChanged();
}
@@ -330,7 +307,6 @@ void PrivetNotificationService::OnNotificationsEnabledChanged() {
if (IsForced()) {
StartLister();
} else if (*enable_privet_notification_member_) {
- ReportPrivetUmaEvent(PRIVET_SERVICE_STARTED);
traffic_detector_ = std::make_unique<PrivetTrafficDetector>(
profile_, base::BindRepeating(&PrivetNotificationService::StartLister,
AsWeakPtr()));
@@ -351,7 +327,6 @@ void PrivetNotificationService::OnNotificationsEnabledChanged() {
}
void PrivetNotificationService::StartLister() {
- ReportPrivetUmaEvent(PRIVET_LISTER_STARTED);
service_discovery_client_ =
local_discovery::ServiceDiscoverySharedClient::GetInstance();
device_lister_.reset(
@@ -386,11 +361,9 @@ void PrivetNotificationDelegate::Click(
return;
if (*button_index == 0) {
- ReportPrivetUmaEvent(PRIVET_NOTIFICATION_CLICKED);
OpenTab(GURL(kPrivetNotificationOriginUrl));
} else {
DCHECK_EQ(1, *button_index);
- ReportPrivetUmaEvent(PRIVET_DISABLE_NOTIFICATIONS_CLICKED);
DisableNotifications();
}
CloseNotification();
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc b/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc
index 481743a2b5a..60ae78cb53f 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/bind.h"
-#include "base/metrics/histogram_macros.h"
#include "base/stl_util.h"
#include "base/sys_byteorder.h"
#include "base/task/post_task.h"
@@ -80,7 +79,7 @@ namespace cloud_print {
PrivetTrafficDetector::PrivetTrafficDetector(
content::BrowserContext* profile,
- const base::RepeatingClosure& on_traffic_detected)
+ base::RepeatingClosure on_traffic_detected)
: helper_(new Helper(profile, on_traffic_detected)) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::GetNetworkConnectionTracker()->AddNetworkConnectionObserver(this);
@@ -108,12 +107,11 @@ void PrivetTrafficDetector::OnConnectionChanged(
PrivetTrafficDetector::Helper::Helper(
content::BrowserContext* profile,
- const base::RepeatingClosure& on_traffic_detected)
+ base::RepeatingClosure on_traffic_detected)
: profile_(profile),
on_traffic_detected_(on_traffic_detected),
restart_attempts_(kMaxRestartAttempts),
- receiver_binding_(this),
- weak_ptr_factory_(this) {
+ receiver_binding_(this) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}
@@ -151,11 +149,6 @@ void PrivetTrafficDetector::Helper::Restart(
void PrivetTrafficDetector::Helper::Bind() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- if (!start_time_.is_null()) {
- base::TimeDelta time_delta = base::Time::Now() - start_time_;
- UMA_HISTOGRAM_LONG_TIMES("LocalDiscovery.DetectorRestartTime", time_delta);
- }
- start_time_ = base::Time::Now();
network::mojom::UDPSocketReceiverPtr receiver_ptr;
network::mojom::UDPSocketReceiverRequest receiver_request =
@@ -265,8 +258,6 @@ void PrivetTrafficDetector::Helper::OnReceived(
ResetConnection();
base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI},
on_traffic_detected_);
- base::TimeDelta time_delta = base::Time::Now() - start_time_;
- UMA_HISTOGRAM_LONG_TIMES("LocalDiscovery.DetectorTriggerTime", time_delta);
} else {
socket_->ReceiveMoreWithBufferSize(1, net::dns_protocol::kMaxMulticastSize);
}
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.h b/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.h
index 86df41d3af5..f34c0e65518 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.h
+++ b/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.h
@@ -34,7 +34,7 @@ class PrivetTrafficDetector
public:
// Called on the UI thread.
PrivetTrafficDetector(content::BrowserContext* profile,
- const base::RepeatingClosure& on_traffic_detected);
+ base::RepeatingClosure on_traffic_detected);
~PrivetTrafficDetector() override;
// network::NetworkConnectionTracker::NetworkConnectionObserver:
@@ -46,7 +46,7 @@ class PrivetTrafficDetector
class Helper : public network::mojom::UDPSocketReceiver {
public:
Helper(content::BrowserContext* profile,
- const base::RepeatingClosure& on_traffic_detected);
+ base::RepeatingClosure on_traffic_detected);
~Helper() override;
// network::mojom::UDPSocketReceiver:
@@ -79,14 +79,13 @@ class PrivetTrafficDetector
// Only accessed on the IO thread.
net::NetworkInterfaceList networks_;
net::IPEndPoint recv_addr_;
- base::Time start_time_;
network::mojom::UDPSocketPtr socket_;
// Implementation of socket receiver callback.
// Initialized on the UI thread, but only accessed on the IO thread.
mojo::Binding<network::mojom::UDPSocketReceiver> receiver_binding_;
- base::WeakPtrFactory<Helper> weak_ptr_factory_;
+ base::WeakPtrFactory<Helper> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(Helper);
};
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc b/chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc
index e033ccbce9b..dc6c66fd913 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc
@@ -87,8 +87,7 @@ PrivetURLLoader::PrivetURLLoader(
url_loader_factory_(url_loader_factory),
traffic_annotation_(traffic_annotation),
delegate_(delegate),
- max_retries_(kPrivetMaxRetries),
- weak_factory_(this) {}
+ max_retries_(kPrivetMaxRetries) {}
PrivetURLLoader::~PrivetURLLoader() {}
diff --git a/chromium/chrome/browser/printing/cloud_print/privet_url_loader.h b/chromium/chrome/browser/printing/cloud_print/privet_url_loader.h
index 2a9f643ec4e..537cd503da8 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_url_loader.h
+++ b/chromium/chrome/browser/printing/cloud_print/privet_url_loader.h
@@ -141,7 +141,7 @@ class PrivetURLLoader {
std::string upload_content_type_;
std::unique_ptr<network::SimpleURLLoader> url_loader_;
- base::WeakPtrFactory<PrivetURLLoader> weak_factory_;
+ base::WeakPtrFactory<PrivetURLLoader> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(PrivetURLLoader);
};
diff --git a/chromium/chrome/browser/printing/pdf_nup_converter_client.cc b/chromium/chrome/browser/printing/pdf_nup_converter_client.cc
index 60cbd7c1c48..7f1bc0b0310 100644
--- a/chromium/chrome/browser/printing/pdf_nup_converter_client.cc
+++ b/chromium/chrome/browser/printing/pdf_nup_converter_client.cc
@@ -9,7 +9,7 @@
#include "base/bind.h"
#include "chrome/services/printing/public/mojom/constants.mojom.h"
#include "chrome/services/printing/public/mojom/pdf_nup_converter.mojom.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "services/service_manager/public/cpp/connector.h"
namespace printing {
@@ -77,13 +77,8 @@ void PdfNupConverterClient::RemovePdfNupConverterRequest(int cookie) {
mojom::PdfNupConverterPtr
PdfNupConverterClient::CreatePdfNupConverterRequest() {
- if (!connector_) {
- service_manager::mojom::ConnectorRequest connector_request;
- connector_ = service_manager::Connector::Create(&connector_request);
- content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->BindConnectorRequest(std::move(connector_request));
- }
+ if (!connector_)
+ connector_ = content::GetSystemConnector()->Clone();
mojom::PdfNupConverterPtr pdf_nup_converter;
connector_->BindInterface(printing::mojom::kChromePrintingServiceName,
&pdf_nup_converter);
diff --git a/chromium/chrome/browser/printing/pdf_to_emf_converter.cc b/chromium/chrome/browser/printing/pdf_to_emf_converter.cc
index 90f43cf394c..a6f2dcbb563 100644
--- a/chromium/chrome/browser/printing/pdf_to_emf_converter.cc
+++ b/chromium/chrome/browser/printing/pdf_to_emf_converter.cc
@@ -28,7 +28,7 @@
#include "chrome/services/printing/public/mojom/pdf_to_emf_converter.mojom.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "printing/emf_win.h"
#include "printing/pdf_render_settings.h"
@@ -146,7 +146,7 @@ class PdfConverterImpl : public PdfConverter {
int page_number() const { return page_number_; }
- const PdfConverter::GetPageCallback& callback() const { return callback_; }
+ PdfConverter::GetPageCallback callback() const { return callback_; }
private:
int page_number_;
@@ -159,7 +159,7 @@ class PdfConverterImpl : public PdfConverter {
void Initialize(scoped_refptr<base::RefCountedMemory> data);
void GetPage(int page_number,
- const PdfConverter::GetPageCallback& get_page_callback) override;
+ PdfConverter::GetPageCallback get_page_callback) override;
void Stop();
@@ -272,10 +272,9 @@ void PdfConverterImpl::Initialize(scoped_refptr<base::RefCountedMemory> data) {
memcpy(memory.mapping.memory(), data->front(), data->size());
- content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->BindInterface(printing::mojom::kChromePrintingServiceName,
- &pdf_to_emf_converter_factory_);
+ content::GetSystemConnector()->BindInterface(
+ printing::mojom::kChromePrintingServiceName,
+ &pdf_to_emf_converter_factory_);
pdf_to_emf_converter_factory_.set_connection_error_handler(base::BindOnce(
&PdfConverterImpl::OnFailed, weak_ptr_factory_.GetWeakPtr(),
std::string("Connection to PdfToEmfConverterFactory error.")));
@@ -306,7 +305,7 @@ void PdfConverterImpl::OnPageCount(mojom::PdfToEmfConverterPtr converter,
void PdfConverterImpl::GetPage(
int page_number,
- const PdfConverter::GetPageCallback& get_page_callback) {
+ PdfConverter::GetPageCallback get_page_callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(pdf_to_emf_converter_.is_bound());
diff --git a/chromium/chrome/browser/printing/pdf_to_emf_converter.h b/chromium/chrome/browser/printing/pdf_to_emf_converter.h
index 08089827447..f1d6791aeca 100644
--- a/chromium/chrome/browser/printing/pdf_to_emf_converter.h
+++ b/chromium/chrome/browser/printing/pdf_to_emf_converter.h
@@ -35,8 +35,7 @@ class PdfConverter {
// PDF provided in Start() call.
// Calls |get_page_callback| after conversion. |emf| of callback in not NULL
// if conversion succeeded.
- virtual void GetPage(int page_number,
- const GetPageCallback& get_page_callback) = 0;
+ virtual void GetPage(int page_number, GetPageCallback get_page_callback) = 0;
};
// Object used by tests to exercise the temporary file creation failure code
diff --git a/chromium/chrome/browser/printing/pdf_to_emf_converter_browsertest.cc b/chromium/chrome/browser/printing/pdf_to_emf_converter_browsertest.cc
index b038a8c7628..0794ce53f65 100644
--- a/chromium/chrome/browser/printing/pdf_to_emf_converter_browsertest.cc
+++ b/chromium/chrome/browser/printing/pdf_to_emf_converter_browsertest.cc
@@ -30,14 +30,14 @@ constexpr gfx::Size k200DpiSize = gfx::Size(200, 200);
constexpr size_t kHeaderSize = sizeof(ENHMETAHEADER);
-void StartCallbackImpl(base::Closure quit_closure,
+void StartCallbackImpl(base::OnceClosure quit_closure,
int* page_count_out,
int page_count_in) {
*page_count_out = page_count_in;
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
-void GetPageCallbackImpl(base::Closure quit_closure,
+void GetPageCallbackImpl(base::OnceClosure quit_closure,
int* page_number_out,
std::unique_ptr<MetafilePlayer>* file_out,
int page_number_in,
@@ -45,7 +45,7 @@ void GetPageCallbackImpl(base::Closure quit_closure,
std::unique_ptr<MetafilePlayer> file_in) {
*page_number_out = page_number_in;
*file_out = std::move(file_in);
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
// |page_number| is 0-based. Returned result has 1-based page number.
@@ -231,7 +231,7 @@ IN_PROC_BROWSER_TEST_F(PdfToEmfConverterBrowserTest, FailureNoTempFile) {
int page_count = -1;
std::unique_ptr<PdfConverter> pdf_converter = PdfConverter::StartPdfConverter(
base::MakeRefCounted<base::RefCountedStaticMemory>(), PdfRenderSettings(),
- base::Bind(&StartCallbackImpl, run_loop.QuitClosure(), &page_count));
+ base::BindOnce(&StartCallbackImpl, run_loop.QuitClosure(), &page_count));
run_loop.Run();
EXPECT_EQ(0, page_count);
}
@@ -244,7 +244,7 @@ IN_PROC_BROWSER_TEST_F(PdfToEmfConverterBrowserTest, FailureBadPdf) {
int page_count = -1;
std::unique_ptr<PdfConverter> pdf_converter = PdfConverter::StartPdfConverter(
bad_pdf_data, PdfRenderSettings(),
- base::Bind(&StartCallbackImpl, run_loop.QuitClosure(), &page_count));
+ base::BindOnce(&StartCallbackImpl, run_loop.QuitClosure(), &page_count));
run_loop.Run();
EXPECT_EQ(0, page_count);
}
diff --git a/chromium/chrome/browser/printing/print_browsertest.cc b/chromium/chrome/browser/printing/print_browsertest.cc
index 5d17cdb351c..e2a8b92c752 100644
--- a/chromium/chrome/browser/printing/print_browsertest.cc
+++ b/chromium/chrome/browser/printing/print_browsertest.cc
@@ -33,6 +33,7 @@
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test_utils.h"
+#include "content/public/test/no_renderer_crashes_assertion.h"
#include "extensions/common/extension.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
@@ -111,7 +112,7 @@ class NupPrintingTestDelegate : public PrintingMessageFilter::TestDelegate {
class TestPrintFrameContentMsgFilter : public content::BrowserMessageFilter {
public:
TestPrintFrameContentMsgFilter(int document_cookie,
- const base::RepeatingClosure& msg_callback)
+ base::RepeatingClosure msg_callback)
: content::BrowserMessageFilter(PrintMsgStart),
document_cookie_(document_cookie),
task_runner_(base::SequencedTaskRunnerHandle::Get()),
@@ -523,6 +524,7 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessPrintBrowserTest,
auto filter =
base::MakeRefCounted<KillPrintFrameContentMsgFilter>(subframe_rph);
+ content::ScopedAllowRendererCrashes allow_renderer_crashes(subframe_rph);
subframe_rph->AddFilter(filter.get());
PrintAndWaitUntilPreviewIsReady(/*print_only_selection=*/false);
diff --git a/chromium/chrome/browser/printing/print_dialog_cloud.cc b/chromium/chrome/browser/printing/print_dialog_cloud.cc
index e22449566b5..363c7915aac 100644
--- a/chromium/chrome/browser/printing/print_dialog_cloud.cc
+++ b/chromium/chrome/browser/printing/print_dialog_cloud.cc
@@ -14,9 +14,8 @@
#include "chrome/browser/ui/browser_window.h"
#include "components/cloud_devices/common/cloud_devices_urls.h"
#include "components/google/core/common/google_util.h"
-#include "components/signin/core/browser/account_consistency_method.h"
#include "components/signin/core/browser/signin_header_helper.h"
-#include "components/signin/core/browser/signin_metrics.h"
+#include "components/signin/public/base/signin_metrics.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
@@ -29,9 +28,7 @@ namespace {
class SignInObserver : public content::WebContentsObserver {
public:
SignInObserver(content::WebContents* web_contents, base::OnceClosure callback)
- : WebContentsObserver(web_contents),
- callback_(std::move(callback)),
- weak_ptr_factory_(this) {}
+ : WebContentsObserver(web_contents), callback_(std::move(callback)) {}
private:
// Overridden from content::WebContentsObserver:
@@ -58,7 +55,7 @@ class SignInObserver : public content::WebContentsObserver {
}
base::OnceClosure callback_;
- base::WeakPtrFactory<SignInObserver> weak_ptr_factory_;
+ base::WeakPtrFactory<SignInObserver> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SignInObserver);
};
diff --git a/chromium/chrome/browser/printing/print_dialog_cloud_win.cc b/chromium/chrome/browser/printing/print_dialog_cloud_win.cc
index 66eeefda1f9..0880b837865 100644
--- a/chromium/chrome/browser/printing/print_dialog_cloud_win.cc
+++ b/chromium/chrome/browser/printing/print_dialog_cloud_win.cc
@@ -132,9 +132,9 @@ void CreatePrintDialogForFile(content::BrowserContext* browser_context,
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
- base::Bind(&ReadFile, path_to_file),
- base::Bind(&CreatePrintDialog, browser_context, print_job_title,
- print_ticket, file_type));
+ base::BindOnce(&ReadFile, path_to_file),
+ base::BindOnce(&CreatePrintDialog, browser_context, print_job_title,
+ print_ticket, file_type));
}
} // namespace
diff --git a/chromium/chrome/browser/printing/print_job.cc b/chromium/chrome/browser/printing/print_job.cc
index 61163cb9fa5..b039a047907 100644
--- a/chromium/chrome/browser/printing/print_job.cc
+++ b/chromium/chrome/browser/printing/print_job.cc
@@ -16,6 +16,7 @@
#include "build/build_config.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/printing/print_job_worker.h"
+#include "chrome/browser/printing/printer_query.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
@@ -50,7 +51,7 @@ PrintJob::~PrintJob() {
DCHECK(!worker_ || !worker_->IsRunning());
}
-void PrintJob::Initialize(PrinterQuery* query,
+void PrintJob::Initialize(std::unique_ptr<PrinterQuery> query,
const base::string16& name,
int page_count) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
@@ -60,15 +61,15 @@ void PrintJob::Initialize(PrinterQuery* query,
DCHECK(!document_);
worker_ = query->DetachWorker();
worker_->SetPrintJob(this);
- settings_ = query->settings();
+ const PrintSettings& settings = query->settings();
auto new_doc =
- base::MakeRefCounted<PrintedDocument>(settings_, name, query->cookie());
+ base::MakeRefCounted<PrintedDocument>(settings, name, query->cookie());
new_doc->set_page_count(page_count);
UpdatePrintedDocument(new_doc);
#if defined(OS_WIN)
- pdf_page_mapping_ = PageRange::GetPages(settings_.ranges());
+ pdf_page_mapping_ = PageRange::GetPages(settings.ranges());
if (pdf_page_mapping_.empty()) {
for (int i = 0; i < page_count; i++)
pdf_page_mapping_.push_back(i);
@@ -103,13 +104,14 @@ void PrintJob::StartConversionToNativeFormat(
if (PrintedDocument::HasDebugDumpPath())
document()->DebugDumpData(print_data.get(), FILE_PATH_LITERAL(".pdf"));
- if (settings_.printer_is_textonly()) {
+ const PrintSettings& settings = document()->settings();
+ if (settings.printer_is_textonly()) {
StartPdfToTextConversion(print_data, page_size);
- } else if ((settings_.printer_is_ps2() || settings_.printer_is_ps3()) &&
+ } else if ((settings.printer_is_ps2() || settings.printer_is_ps3()) &&
!base::FeatureList::IsEnabled(
features::kDisablePostScriptPrinting)) {
StartPdfToPostScriptConversion(print_data, content_area, physical_offsets,
- settings_.printer_is_ps2());
+ settings.printer_is_ps2());
} else {
StartPdfToEmfConversion(print_data, page_size, content_area);
}
@@ -233,6 +235,10 @@ PrintedDocument* PrintJob::document() const {
return document_.get();
}
+const PrintSettings& PrintJob::settings() const {
+ return document()->settings();
+}
+
#if defined(OS_WIN)
class PrintJob::PdfConversionState {
public:
@@ -250,7 +256,7 @@ class PrintJob::PdfConversionState {
std::move(start_callback));
}
- void GetMorePages(const PdfConverter::GetPageCallback& get_page_callback) {
+ void GetMorePages(PdfConverter::GetPageCallback get_page_callback) {
const int kMaxNumberOfTempFilesPerDocument = 3;
while (pages_in_progress_ < kMaxNumberOfTempFilesPerDocument &&
current_page_ < page_count_) {
@@ -259,7 +265,7 @@ class PrintJob::PdfConversionState {
}
}
- void OnPageProcessed(const PdfConverter::GetPageCallback& get_page_callback) {
+ void OnPageProcessed(PdfConverter::GetPageCallback get_page_callback) {
--pages_in_progress_;
GetMorePages(get_page_callback);
// Release converter if we don't need this any more.
@@ -294,12 +300,13 @@ void PrintJob::StartPdfToEmfConversion(
// Update : The missing letters seem to have been caused by the same
// problem as https://crbug.com/659604 which was resolved. GDI printing
// seems to work with the fix for this bug applied.
+ const PrintSettings& settings = document()->settings();
bool print_text_with_gdi =
- settings_.print_text_with_gdi() && !settings_.printer_is_xps() &&
+ settings.print_text_with_gdi() && !settings.printer_is_xps() &&
base::FeatureList::IsEnabled(features::kGdiTextPrinting);
PdfRenderSettings render_settings(
- content_area, gfx::Point(0, 0), settings_.dpi_size(),
- /*autorotate=*/true, settings_.color() == COLOR,
+ content_area, gfx::Point(0, 0), settings.dpi_size(),
+ /*autorotate=*/true, settings.color() == COLOR,
print_text_with_gdi ? PdfRenderSettings::Mode::GDI_TEXT
: PdfRenderSettings::Mode::NORMAL);
pdf_conversion_state_->Start(
@@ -346,7 +353,7 @@ void PrintJob::OnPdfPageConverted(int page_number,
}
pdf_conversion_state_->GetMorePages(
- base::Bind(&PrintJob::OnPdfPageConverted, this));
+ base::BindRepeating(&PrintJob::OnPdfPageConverted, this));
}
void PrintJob::StartPdfToTextConversion(
@@ -357,8 +364,9 @@ void PrintJob::StartPdfToTextConversion(
pdf_conversion_state_ =
std::make_unique<PdfConversionState>(gfx::Size(), gfx::Rect());
gfx::Rect page_area = gfx::Rect(0, 0, page_size.width(), page_size.height());
+ const PrintSettings& settings = document()->settings();
PdfRenderSettings render_settings(
- page_area, gfx::Point(0, 0), settings_.dpi_size(),
+ page_area, gfx::Point(0, 0), settings.dpi_size(),
/*autorotate=*/true,
/*use_color=*/true, PdfRenderSettings::Mode::TEXTONLY);
pdf_conversion_state_->Start(
@@ -375,9 +383,10 @@ void PrintJob::StartPdfToPostScriptConversion(
DCHECK(!pdf_conversion_state_);
pdf_conversion_state_ = std::make_unique<PdfConversionState>(
gfx::Size(), gfx::Rect());
+ const PrintSettings& settings = document()->settings();
PdfRenderSettings render_settings(
- content_area, physical_offsets, settings_.dpi_size(),
- /*autorotate=*/true, settings_.color() == COLOR,
+ content_area, physical_offsets, settings.dpi_size(),
+ /*autorotate=*/true, settings.color() == COLOR,
ps_level2 ? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2
: PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3);
pdf_conversion_state_->Start(
@@ -424,7 +433,6 @@ void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) {
switch (event_details.type()) {
case JobEventDetails::FAILED: {
- settings_.Clear();
// No need to cancel since the worker already canceled itself.
Stop();
break;
@@ -451,7 +459,7 @@ void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) {
case JobEventDetails::PAGE_DONE:
if (pdf_conversion_state_) {
pdf_conversion_state_->OnPageProcessed(
- base::Bind(&PrintJob::OnPdfPageConverted, this));
+ base::BindRepeating(&PrintJob::OnPdfPageConverted, this));
}
break;
#endif // defined(OS_WIN)
@@ -532,10 +540,6 @@ bool PrintJob::PostTask(const base::Location& from_here,
void PrintJob::HoldUntilStopIsCalled() {
}
-void PrintJob::set_settings(const PrintSettings& settings) {
- settings_ = settings;
-}
-
void PrintJob::set_job_pending(bool pending) {
is_job_pending_ = pending;
}
diff --git a/chromium/chrome/browser/printing/print_job.h b/chromium/chrome/browser/printing/print_job.h
index 6c0e5f5897f..b50220ddb73 100644
--- a/chromium/chrome/browser/printing/print_job.h
+++ b/chromium/chrome/browser/printing/print_job.h
@@ -51,7 +51,7 @@ class PrintJob : public base::RefCountedThreadSafe<PrintJob>,
// Grabs the ownership of the PrintJobWorker from a PrinterQuery along with
// the print settings. Sets the expected page count of the print job based on
// the settings.
- virtual void Initialize(PrinterQuery* query,
+ virtual void Initialize(std::unique_ptr<PrinterQuery> query,
const base::string16& name,
int page_count);
@@ -103,6 +103,9 @@ class PrintJob : public base::RefCountedThreadSafe<PrintJob>,
// Access the current printed document. Warning: may be NULL.
PrintedDocument* document() const;
+ // Access stored settings.
+ const PrintSettings& settings() const;
+
// Posts the given task to be run.
bool PostTask(const base::Location& from_here, base::OnceClosure task);
@@ -114,7 +117,6 @@ class PrintJob : public base::RefCountedThreadSafe<PrintJob>,
// The functions below are used for tests only.
void set_job_pending(bool pending);
- void set_settings(const PrintSettings& settings);
// Updates |document_| to a new instance. Protected so that tests can access
// it.
@@ -178,9 +180,6 @@ class PrintJob : public base::RefCountedThreadSafe<PrintJob>,
// worker thread per print job.
std::unique_ptr<PrintJobWorker> worker_;
- // Cache of the print context settings for access in the UI thread.
- PrintSettings settings_;
-
// The printed document.
scoped_refptr<PrintedDocument> document_;
diff --git a/chromium/chrome/browser/printing/print_job_manager.cc b/chromium/chrome/browser/printing/print_job_manager.cc
index e687fee15f8..b4225e70c5d 100644
--- a/chromium/chrome/browser/printing/print_job_manager.cc
+++ b/chromium/chrome/browser/printing/print_job_manager.cc
@@ -23,22 +23,22 @@ PrintQueriesQueue::~PrintQueriesQueue() {
queued_queries_.clear();
}
-void PrintQueriesQueue::QueuePrinterQuery(PrinterQuery* query) {
+void PrintQueriesQueue::QueuePrinterQuery(std::unique_ptr<PrinterQuery> query) {
base::AutoLock lock(lock_);
DCHECK(query);
- queued_queries_.push_back(base::WrapRefCounted(query));
DCHECK(query->is_valid());
+ queued_queries_.push_back(std::move(query));
}
-scoped_refptr<PrinterQuery> PrintQueriesQueue::PopPrinterQuery(
+std::unique_ptr<PrinterQuery> PrintQueriesQueue::PopPrinterQuery(
int document_cookie) {
base::AutoLock lock(lock_);
for (auto it = queued_queries_.begin(); it != queued_queries_.end(); ++it) {
- scoped_refptr<PrinterQuery>& query = *it;
- if (query->cookie() != document_cookie || query->is_callback_pending())
+ std::unique_ptr<PrinterQuery>& query = *it;
+ if (query->cookie() != document_cookie)
continue;
- scoped_refptr<PrinterQuery> current_query = query;
+ std::unique_ptr<PrinterQuery> current_query = std::move(query);
queued_queries_.erase(it);
DCHECK(current_query->is_valid());
return current_query;
@@ -46,10 +46,10 @@ scoped_refptr<PrinterQuery> PrintQueriesQueue::PopPrinterQuery(
return nullptr;
}
-scoped_refptr<PrinterQuery> PrintQueriesQueue::CreatePrinterQuery(
+std::unique_ptr<PrinterQuery> PrintQueriesQueue::CreatePrinterQuery(
int render_process_id,
int render_frame_id) {
- return base::MakeRefCounted<PrinterQuery>(render_process_id, render_frame_id);
+ return std::make_unique<PrinterQuery>(render_process_id, render_frame_id);
}
void PrintQueriesQueue::Shutdown() {
@@ -62,8 +62,8 @@ void PrintQueriesQueue::Shutdown() {
// corresponding PrintJob, so any pending preview requests are not covered
// by PrintJobManager::StopJobs and should be stopped explicitly.
for (auto& query : queries_to_stop) {
- query->PostTask(FROM_HERE,
- base::BindOnce(&PrinterQuery::StopWorker, query));
+ query->PostTask(
+ FROM_HERE, base::BindOnce(&PrinterQuery::StopWorker, std::move(query)));
}
}
diff --git a/chromium/chrome/browser/printing/print_job_manager.h b/chromium/chrome/browser/printing/print_job_manager.h
index 285accbb8d0..e66e7f1ae21 100644
--- a/chromium/chrome/browser/printing/print_job_manager.h
+++ b/chromium/chrome/browser/printing/print_job_manager.h
@@ -29,15 +29,16 @@ class PrintQueriesQueue : public base::RefCountedThreadSafe<PrintQueriesQueue> {
// Queues a semi-initialized worker thread. Can be called from any thread.
// Current use case is queuing from the I/O thread.
// TODO(maruel): Have them vanish after a timeout (~5 minutes?)
- void QueuePrinterQuery(PrinterQuery* query);
+ void QueuePrinterQuery(std::unique_ptr<PrinterQuery> query);
// Pops a queued PrinterQuery object that was previously queued or creates
// a new one. Can be called from any thread.
- scoped_refptr<PrinterQuery> PopPrinterQuery(int document_cookie);
+ std::unique_ptr<PrinterQuery> PopPrinterQuery(int document_cookie);
// Creates new query. Virtual so that tests can override it.
- virtual scoped_refptr<PrinterQuery> CreatePrinterQuery(int render_process_id,
- int render_frame_id);
+ virtual std::unique_ptr<PrinterQuery> CreatePrinterQuery(
+ int render_process_id,
+ int render_frame_id);
void Shutdown();
@@ -47,7 +48,7 @@ class PrintQueriesQueue : public base::RefCountedThreadSafe<PrintQueriesQueue> {
private:
friend class base::RefCountedThreadSafe<PrintQueriesQueue>;
- using PrinterQueries = std::vector<scoped_refptr<PrinterQuery>>;
+ using PrinterQueries = std::vector<std::unique_ptr<PrinterQuery>>;
// Used to serialize access to |queued_queries_|.
base::Lock lock_;
diff --git a/chromium/chrome/browser/printing/print_job_unittest.cc b/chromium/chrome/browser/printing/print_job_unittest.cc
index 2192bf755d6..bd50607d5e0 100644
--- a/chromium/chrome/browser/printing/print_job_unittest.cc
+++ b/chromium/chrome/browser/printing/print_job_unittest.cc
@@ -26,10 +26,9 @@ namespace {
class TestPrintJobWorker : public PrintJobWorker {
public:
- explicit TestPrintJobWorker(PrinterQuery* query)
+ TestPrintJobWorker()
: PrintJobWorker(content::ChildProcessHost::kInvalidUniqueID,
- content::ChildProcessHost::kInvalidUniqueID,
- query) {}
+ content::ChildProcessHost::kInvalidUniqueID) {}
friend class TestQuery;
};
@@ -39,11 +38,14 @@ class TestQuery : public PrinterQuery {
: PrinterQuery(content::ChildProcessHost::kInvalidUniqueID,
content::ChildProcessHost::kInvalidUniqueID) {}
- void GetSettingsDone(const PrintSettings& new_settings,
+ void GetSettingsDone(base::OnceClosure callback,
+ const PrintSettings& new_settings,
PrintingContext::Result result) override {
FAIL();
}
+ ~TestQuery() override {}
+
std::unique_ptr<PrintJobWorker> DetachWorker() override {
{
// Do an actual detach to keep the parent class happy.
@@ -52,7 +54,7 @@ class TestQuery : public PrinterQuery {
// We're screwing up here since we're calling worker from the main thread.
// That's fine for testing. It is actually simulating PrinterQuery behavior.
- auto worker = std::make_unique<TestPrintJobWorker>(this);
+ auto worker = std::make_unique<TestPrintJobWorker>();
EXPECT_TRUE(worker->Start());
worker->printing_context()->UseDefaultSettings();
settings_ = worker->printing_context()->settings();
@@ -63,8 +65,6 @@ class TestQuery : public PrinterQuery {
const PrintSettings& settings() const override { return settings_; }
private:
- ~TestQuery() override {}
-
PrintSettings settings_;
DISALLOW_COPY_AND_ASSIGN(TestQuery);
@@ -102,8 +102,7 @@ TEST(PrintJobTest, SimplePrint) {
content::NotificationService::AllSources());
volatile bool check = false;
scoped_refptr<PrintJob> job(new TestPrintJob(&check));
- scoped_refptr<TestQuery> query = base::MakeRefCounted<TestQuery>();
- job->Initialize(query.get(), base::string16(), 1);
+ job->Initialize(std::make_unique<TestQuery>(), base::string16(), 1);
job->Stop();
while (job->document()) {
base::RunLoop().RunUntilIdle();
diff --git a/chromium/chrome/browser/printing/print_job_worker.cc b/chromium/chrome/browser/printing/print_job_worker.cc
index 691c476708b..63f432b5837 100644
--- a/chromium/chrome/browser/printing/print_job_worker.cc
+++ b/chromium/chrome/browser/printing/print_job_worker.cc
@@ -105,20 +105,6 @@ void NotificationCallback(PrintJob* print_job,
content::Details<JobEventDetails>(details.get()));
}
-// Helper function to ensure |query| is valid until at least |callback| returns.
-void WorkerHoldRefCallback(scoped_refptr<PrinterQuery> query,
- base::OnceClosure callback) {
- std::move(callback).Run();
-}
-
-void PostOnQueryThread(scoped_refptr<PrinterQuery> query,
- PrintingContext::PrintSettingsCallback callback,
- PrintingContext::Result result) {
- query->PostTask(FROM_HERE,
- base::BindOnce(&WorkerHoldRefCallback, query,
- base::BindOnce(std::move(callback), result)));
-}
-
#if defined(OS_WIN)
void PageNotificationCallback(PrintJob* print_job,
JobEventDetails::Type detail_type,
@@ -136,17 +122,13 @@ void PageNotificationCallback(PrintJob* print_job,
} // namespace
-PrintJobWorker::PrintJobWorker(int render_process_id,
- int render_frame_id,
- PrinterQuery* query)
+PrintJobWorker::PrintJobWorker(int render_process_id, int render_frame_id)
: printing_context_delegate_(
std::make_unique<PrintingContextDelegate>(render_process_id,
render_frame_id)),
printing_context_(
PrintingContext::Create(printing_context_delegate_.get())),
- query_(query),
- thread_("Printing_Worker"),
- weak_factory_(this) {
+ thread_("Printing_Worker") {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
}
@@ -154,12 +136,10 @@ PrintJobWorker::~PrintJobWorker() {
// The object is normally deleted by PrintJob in the UI thread, but when the
// user cancels printing or in the case of print preview, the worker is
// destroyed with the PrinterQuery, which is on the I/O thread.
- if (query_) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- DCHECK(!print_job_);
- } else {
+ if (print_job_) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- DCHECK(print_job_);
+ } else {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
}
Stop();
}
@@ -167,9 +147,6 @@ PrintJobWorker::~PrintJobWorker() {
void PrintJobWorker::SetPrintJob(PrintJob* print_job) {
DCHECK_EQ(page_number_, PageNumber::npos());
print_job_ = print_job;
-
- // Release the Printer Query reference. It is no longer needed.
- query_ = nullptr;
}
void PrintJobWorker::GetSettings(bool ask_user_for_settings,
@@ -177,19 +154,11 @@ void PrintJobWorker::GetSettings(bool ask_user_for_settings,
bool has_selection,
MarginType margin_type,
bool is_scripted,
- bool is_modifiable) {
+ bool is_modifiable,
+ SettingsCallback callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
DCHECK_EQ(page_number_, PageNumber::npos());
- // This function is only called by the PrinterQuery.
- DCHECK(query_);
-
- // Recursive task processing is needed for the dialog in case it needs to be
- // destroyed by a task.
- // TODO(thestig): This code is wrong. SetNestableTasksAllowed(true) is needed
- // on the thread where the PrintDlgEx is called, and definitely both calls
- // should happen on the same thread. See http://crbug.com/73466
- // MessageLoopCurrent::Get()->SetNestableTasksAllowed(true);
printing_context_->set_margin_type(margin_type);
printing_context_->set_is_modifiable(is_modifiable);
@@ -198,85 +167,70 @@ void PrintJobWorker::GetSettings(bool ask_user_for_settings,
if (ask_user_for_settings) {
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
- base::BindOnce(
- &WorkerHoldRefCallback, base::WrapRefCounted(query_),
- base::BindOnce(&PrintJobWorker::GetSettingsWithUI,
- base::Unretained(this), document_page_count,
- has_selection, is_scripted)));
+ base::BindOnce(&PrintJobWorker::GetSettingsWithUI,
+ base::Unretained(this), document_page_count,
+ has_selection, is_scripted, std::move(callback)));
} else {
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&WorkerHoldRefCallback, base::WrapRefCounted(query_),
- base::BindOnce(&PrintJobWorker::UseDefaultSettings,
- base::Unretained(this))));
+ base::BindOnce(&PrintJobWorker::UseDefaultSettings,
+ base::Unretained(this), std::move(callback)));
}
}
-void PrintJobWorker::SetSettings(base::Value new_settings) {
+void PrintJobWorker::SetSettings(base::Value new_settings,
+ SettingsCallback callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
- DCHECK(query_);
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
- base::BindOnce(
- &WorkerHoldRefCallback, base::WrapRefCounted(query_),
- base::BindOnce(&PrintJobWorker::UpdatePrintSettings,
- base::Unretained(this), std::move(new_settings))));
+ base::BindOnce(&PrintJobWorker::UpdatePrintSettings,
+ base::Unretained(this), std::move(new_settings),
+ std::move(callback)));
}
#if defined(OS_CHROMEOS)
void PrintJobWorker::SetSettingsFromPOD(
- std::unique_ptr<printing::PrintSettings> new_settings) {
+ std::unique_ptr<printing::PrintSettings> new_settings,
+ SettingsCallback callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
- DCHECK(query_);
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
- base::BindOnce(
- &WorkerHoldRefCallback, base::WrapRefCounted(query_),
- base::BindOnce(&PrintJobWorker::UpdatePrintSettingsFromPOD,
- base::Unretained(this), std::move(new_settings))));
+ base::BindOnce(&PrintJobWorker::UpdatePrintSettingsFromPOD,
+ base::Unretained(this), std::move(new_settings),
+ std::move(callback)));
}
#endif
-void PrintJobWorker::UpdatePrintSettings(base::Value new_settings) {
+void PrintJobWorker::UpdatePrintSettings(base::Value new_settings,
+ SettingsCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
PrintingContext::Result result =
printing_context_->UpdatePrintSettings(std::move(new_settings));
- GetSettingsDone(result);
+ GetSettingsDone(std::move(callback), result);
}
#if defined(OS_CHROMEOS)
void PrintJobWorker::UpdatePrintSettingsFromPOD(
- std::unique_ptr<printing::PrintSettings> new_settings) {
+ std::unique_ptr<printing::PrintSettings> new_settings,
+ SettingsCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
PrintingContext::Result result =
printing_context_->UpdatePrintSettingsFromPOD(std::move(new_settings));
- GetSettingsDone(result);
+ GetSettingsDone(std::move(callback), result);
}
#endif
-void PrintJobWorker::GetSettingsDone(PrintingContext::Result result) {
- // Most PrintingContext functions may start a message loop and process
- // message recursively, so disable recursive task processing.
- // TODO(thestig): See above comment. SetNestableTasksAllowed(false) needs to
- // be called on the same thread as the previous call. See
- // http://crbug.com/73466
- // MessageLoopCurrent::Get()->SetNestableTasksAllowed(false);
-
- // We can't use OnFailure() here since query_ does not support notifications.
-
- DCHECK(query_);
- query_->PostTask(FROM_HERE,
- base::BindOnce(&PrinterQuery::GetSettingsDone,
- base::WrapRefCounted(query_),
- printing_context_->settings(), result));
+void PrintJobWorker::GetSettingsDone(SettingsCallback callback,
+ PrintingContext::Result result) {
+ std::move(callback).Run(printing_context_->settings(), result);
}
-void PrintJobWorker::GetSettingsWithUI(
- int document_page_count,
- bool has_selection,
- bool is_scripted) {
+void PrintJobWorker::GetSettingsWithUI(int document_page_count,
+ bool has_selection,
+ bool is_scripted,
+ SettingsCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
PrintingContextDelegate* printing_context_delegate =
@@ -307,17 +261,15 @@ void PrintJobWorker::GetSettingsWithUI(
if (web_contents && web_contents->IsFullscreenForCurrentTab())
web_contents->ExitFullscreen(true);
- // weak_factory_ creates pointers valid only on query_ thread.
printing_context_->AskUserForSettings(
document_page_count, has_selection, is_scripted,
- base::BindOnce(&PostOnQueryThread, base::WrapRefCounted(query_),
- base::BindOnce(&PrintJobWorker::GetSettingsDone,
- weak_factory_.GetWeakPtr())));
+ base::BindOnce(&PrintJobWorker::GetSettingsDone,
+ weak_factory_.GetWeakPtr(), std::move(callback)));
}
-void PrintJobWorker::UseDefaultSettings() {
+void PrintJobWorker::UseDefaultSettings(SettingsCallback callback) {
PrintingContext::Result result = printing_context_->UseDefaultSettings();
- GetSettingsDone(result);
+ GetSettingsDone(std::move(callback), result);
}
void PrintJobWorker::StartPrinting(PrintedDocument* new_document) {
diff --git a/chromium/chrome/browser/printing/print_job_worker.h b/chromium/chrome/browser/printing/print_job_worker.h
index 95341c40110..d5711196e32 100644
--- a/chromium/chrome/browser/printing/print_job_worker.h
+++ b/chromium/chrome/browser/printing/print_job_worker.h
@@ -13,7 +13,6 @@
#include "base/threading/thread.h"
#include "base/values.h"
#include "build/build_config.h"
-#include "chrome/browser/printing/printer_query.h"
#include "content/public/browser/browser_thread.h"
#include "printing/page_number.h"
#include "printing/print_job_constants.h"
@@ -24,7 +23,6 @@ namespace printing {
class PrintJob;
class PrintedDocument;
class PrintedPage;
-class PrinterQuery;
// Worker thread code. It manages the PrintingContext, which can be blocking
// and/or run a message loop. This is the object that generates most
@@ -33,9 +31,10 @@ class PrinterQuery;
// PrintJob always outlives its worker instance.
class PrintJobWorker {
public:
- PrintJobWorker(int render_process_id,
- int render_frame_id,
- PrinterQuery* query);
+ using SettingsCallback =
+ base::OnceCallback<void(const PrintSettings&, PrintingContext::Result)>;
+
+ PrintJobWorker(int render_process_id, int render_frame_id);
virtual ~PrintJobWorker();
void SetPrintJob(PrintJob* print_job);
@@ -51,15 +50,16 @@ class PrintJobWorker {
bool has_selection,
MarginType margin_type,
bool is_scripted,
- bool is_modifiable);
+ bool is_modifiable,
+ SettingsCallback callback);
// Set the new print settings from a dictionary value.
- void SetSettings(base::Value new_settings);
+ void SetSettings(base::Value new_settings, SettingsCallback callback);
#if defined(OS_CHROMEOS)
// Set the new print settings from a POD type.
- void SetSettingsFromPOD(
- std::unique_ptr<printing::PrintSettings> new_settings);
+ void SetSettingsFromPOD(std::unique_ptr<printing::PrintSettings> new_settings,
+ SettingsCallback callback);
#endif
/* The following functions may only be called after calling SetPrintJob(). */
@@ -130,27 +130,29 @@ class PrintJobWorker {
// Asks the user for print settings. Must be called on the UI thread.
// Required on Mac and Linux. Windows can display UI from non-main threads,
// but sticks with this for consistency.
- void GetSettingsWithUI(
- int document_page_count,
- bool has_selection,
- bool is_scripted);
+ void GetSettingsWithUI(int document_page_count,
+ bool has_selection,
+ bool is_scripted,
+ SettingsCallback callback);
// Called on the UI thread to update the print settings.
- void UpdatePrintSettings(base::Value new_settings);
+ void UpdatePrintSettings(base::Value new_settings, SettingsCallback callback);
#if defined(OS_CHROMEOS)
// Called on the UI thread to update the print settings.
void UpdatePrintSettingsFromPOD(
- std::unique_ptr<printing::PrintSettings> new_settings);
+ std::unique_ptr<printing::PrintSettings> new_settings,
+ SettingsCallback callback);
#endif
- // Reports settings back to |query_|.
- void GetSettingsDone(PrintingContext::Result result);
+ // Reports settings back to |callback|.
+ void GetSettingsDone(SettingsCallback callback,
+ PrintingContext::Result result);
// Use the default settings. When using GTK+ or Mac, this can still end up
// displaying a dialog. So this needs to happen from the UI thread on these
// systems.
- void UseDefaultSettings();
+ void UseDefaultSettings(SettingsCallback callback);
// Printing context delegate.
const std::unique_ptr<PrintingContext::Delegate> printing_context_delegate_;
@@ -161,10 +163,6 @@ class PrintJobWorker {
// The printed document. Only has read-only access.
scoped_refptr<PrintedDocument> document_;
- // The printer query that owns this worker thread at creation. It will own
- // the object until DetachWorker() is called.
- PrinterQuery* query_ = nullptr;
-
// The print job owning this worker thread. It is guaranteed to outlive this
// object and should be set with SetPrintJob().
PrintJob* print_job_ = nullptr;
@@ -179,7 +177,7 @@ class PrintJobWorker {
scoped_refptr<base::SequencedTaskRunner> task_runner_;
// Used to generate a WeakPtr for callbacks.
- base::WeakPtrFactory<PrintJobWorker> weak_factory_;
+ base::WeakPtrFactory<PrintJobWorker> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(PrintJobWorker);
};
diff --git a/chromium/chrome/browser/printing/print_preview_data_service.cc b/chromium/chrome/browser/printing/print_preview_data_service.cc
index e932c1b7813..7f5525a59ad 100644
--- a/chromium/chrome/browser/printing/print_preview_data_service.cc
+++ b/chromium/chrome/browser/printing/print_preview_data_service.cc
@@ -117,7 +117,7 @@ void PrintPreviewDataService::SetDataEntry(
int32_t preview_ui_id,
int index,
scoped_refptr<base::RefCountedMemory> data_bytes) {
- if (!base::ContainsKey(data_store_map_, preview_ui_id))
+ if (!base::Contains(data_store_map_, preview_ui_id))
data_store_map_[preview_ui_id] = std::make_unique<PrintPreviewDataStore>();
data_store_map_[preview_ui_id]->SetPreviewDataForIndex(index,
std::move(data_bytes));
diff --git a/chromium/chrome/browser/printing/print_preview_dialog_controller.cc b/chromium/chrome/browser/printing/print_preview_dialog_controller.cc
index c26ddaa9aa1..d2a3be7590a 100644
--- a/chromium/chrome/browser/printing/print_preview_dialog_controller.cc
+++ b/chromium/chrome/browser/printing/print_preview_dialog_controller.cc
@@ -7,7 +7,6 @@
#include <stddef.h>
#include <algorithm>
-#include <memory>
#include <string>
#include <vector>
@@ -17,7 +16,6 @@
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
#include "chrome/browser/printing/print_view_manager.h"
#include "chrome/browser/task_manager/web_contents_tags.h"
@@ -37,8 +35,6 @@
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
-#include "content/public/browser/notification_details.h"
-#include "content/public/browser/notification_source.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
@@ -187,6 +183,53 @@ bool PrintPreviewDialogDelegate::ShouldShowDialogTitle() const {
} // namespace
+// PrintPreviewDialogController::WebContentsObserver ---------------------------
+
+class PrintPreviewDialogController::WebContentsObserver
+ : public content::WebContentsObserver {
+ public:
+ WebContentsObserver(PrintPreviewDialogController* controller,
+ content::WebContents* web_contents);
+ ~WebContentsObserver() override;
+
+ // content::WebContentsObserver:
+ void RenderProcessGone(base::TerminationStatus status) override;
+ void NavigationEntryCommitted(
+ const content::LoadCommittedDetails& load_details) override;
+ void WebContentsDestroyed() override;
+
+ private:
+ PrintPreviewDialogController* const controller_;
+
+ DISALLOW_COPY_AND_ASSIGN(WebContentsObserver);
+};
+
+PrintPreviewDialogController::WebContentsObserver::WebContentsObserver(
+ PrintPreviewDialogController* controller,
+ content::WebContents* web_contents)
+ : content::WebContentsObserver(web_contents), controller_(controller) {}
+
+PrintPreviewDialogController::WebContentsObserver::~WebContentsObserver() =
+ default;
+
+void PrintPreviewDialogController::WebContentsObserver::RenderProcessGone(
+ base::TerminationStatus status) {
+ controller_->OnRendererProcessClosed(
+ web_contents()->GetMainFrame()->GetProcess());
+}
+
+void PrintPreviewDialogController::WebContentsObserver::
+ NavigationEntryCommitted(
+ const content::LoadCommittedDetails& load_details) {
+ controller_->OnNavEntryCommitted(web_contents(), load_details);
+}
+
+void PrintPreviewDialogController::WebContentsObserver::WebContentsDestroyed() {
+ controller_->OnWebContentsDestroyed(web_contents());
+}
+
+// PrintPreviewDialogController ------------------------------------------------
+
PrintPreviewDialogController::PrintPreviewDialogController() = default;
// static
@@ -256,27 +299,8 @@ WebContents* PrintPreviewDialogController::GetInitiator(
return (it != preview_dialog_map_.end()) ? it->second : nullptr;
}
-void PrintPreviewDialogController::Observe(
- int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) {
- if (type == content::NOTIFICATION_RENDERER_PROCESS_CLOSED) {
- OnRendererProcessClosed(
- content::Source<content::RenderProcessHost>(source).ptr());
- } else if (type == content::NOTIFICATION_WEB_CONTENTS_DESTROYED) {
- OnWebContentsDestroyed(content::Source<WebContents>(source).ptr());
- } else {
- DCHECK_EQ(content::NOTIFICATION_NAV_ENTRY_COMMITTED, type);
- WebContents* contents =
- content::Source<NavigationController>(source)->GetWebContents();
- OnNavEntryCommitted(
- contents,
- content::Details<content::LoadCommittedDetails>(details).ptr());
- }
-}
-
void PrintPreviewDialogController::ForEachPreviewDialog(
- base::Callback<void(content::WebContents*)> callback) {
+ base::RepeatingCallback<void(content::WebContents*)> callback) {
for (const auto& it : preview_dialog_map_)
callback.Run(it.first);
}
@@ -293,7 +317,7 @@ void PrintPreviewDialogController::EraseInitiatorInfo(
if (it == preview_dialog_map_.end())
return;
- RemoveObservers(it->second);
+ RemoveObserver(it->second);
preview_dialog_map_[preview_dialog] = nullptr;
}
@@ -341,7 +365,7 @@ void PrintPreviewDialogController::OnWebContentsDestroyed(
void PrintPreviewDialogController::OnNavEntryCommitted(
WebContents* contents,
- const content::LoadCommittedDetails* details) {
+ const content::LoadCommittedDetails& details) {
WebContents* preview_dialog = GetPrintPreviewForContents(contents);
if (!preview_dialog) {
NOTREACHED();
@@ -356,19 +380,17 @@ void PrintPreviewDialogController::OnNavEntryCommitted(
void PrintPreviewDialogController::OnInitiatorNavigated(
WebContents* initiator,
- const content::LoadCommittedDetails* details) {
- if (details) {
- if (details->type == content::NAVIGATION_TYPE_EXISTING_PAGE) {
- static const ui::PageTransition kTransitions[] = {
- ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED |
- ui::PAGE_TRANSITION_FROM_ADDRESS_BAR),
- ui::PAGE_TRANSITION_LINK,
- };
- ui::PageTransition type = details->entry->GetTransitionType();
- for (ui::PageTransition transition : kTransitions) {
- if (ui::PageTransitionTypeIncludingQualifiersIs(type, transition))
- return;
- }
+ const content::LoadCommittedDetails& details) {
+ if (details.type == content::NAVIGATION_TYPE_EXISTING_PAGE) {
+ static const ui::PageTransition kTransitions[] = {
+ ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED |
+ ui::PAGE_TRANSITION_FROM_ADDRESS_BAR),
+ ui::PAGE_TRANSITION_LINK,
+ };
+ ui::PageTransition type = details.entry->GetTransitionType();
+ for (ui::PageTransition transition : kTransitions) {
+ if (ui::PageTransitionTypeIncludingQualifiersIs(type, transition))
+ return;
}
}
@@ -377,26 +399,24 @@ void PrintPreviewDialogController::OnInitiatorNavigated(
void PrintPreviewDialogController::OnPreviewDialogNavigated(
WebContents* preview_dialog,
- const content::LoadCommittedDetails* details) {
- if (details) {
- ui::PageTransition type = details->entry->GetTransitionType();
-
- // New |preview_dialog| is created. Don't update/erase map entry.
- if (waiting_for_new_preview_page_ &&
- ui::PageTransitionCoreTypeIs(type, ui::PAGE_TRANSITION_AUTO_TOPLEVEL) &&
- details->type == content::NAVIGATION_TYPE_NEW_PAGE) {
- waiting_for_new_preview_page_ = false;
- SaveInitiatorTitle(preview_dialog);
- return;
- }
+ const content::LoadCommittedDetails& details) {
+ ui::PageTransition type = details.entry->GetTransitionType();
+
+ // New |preview_dialog| is created. Don't update/erase map entry.
+ if (waiting_for_new_preview_page_ &&
+ ui::PageTransitionCoreTypeIs(type, ui::PAGE_TRANSITION_AUTO_TOPLEVEL) &&
+ details.type == content::NAVIGATION_TYPE_NEW_PAGE) {
+ waiting_for_new_preview_page_ = false;
+ SaveInitiatorTitle(preview_dialog);
+ return;
+ }
- // Cloud print sign-in causes a reload.
- if (!waiting_for_new_preview_page_ &&
- ui::PageTransitionCoreTypeIs(type, ui::PAGE_TRANSITION_RELOAD) &&
- details->type == content::NAVIGATION_TYPE_EXISTING_PAGE &&
- IsPrintPreviewURL(details->previous_url)) {
- return;
- }
+ // Cloud print sign-in causes a reload.
+ if (!waiting_for_new_preview_page_ &&
+ ui::PageTransitionCoreTypeIs(type, ui::PAGE_TRANSITION_RELOAD) &&
+ details.type == content::NAVIGATION_TYPE_EXISTING_PAGE &&
+ IsPrintPreviewURL(details.previous_url)) {
+ return;
}
NOTREACHED();
@@ -430,8 +450,8 @@ WebContents* PrintPreviewDialogController::CreatePrintPreviewDialog(
// Make the print preview WebContents show up in the task manager.
task_manager::WebContentsTags::CreateForPrintingContents(preview_dialog);
- AddObservers(initiator);
- AddObservers(preview_dialog);
+ AddObserver(initiator);
+ AddObserver(preview_dialog);
return preview_dialog;
}
@@ -450,55 +470,16 @@ void PrintPreviewDialogController::SaveInitiatorTitle(
PrintViewManager::FromWebContents(initiator)->RenderSourceName());
}
-void PrintPreviewDialogController::AddObservers(WebContents* contents) {
- registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
- content::Source<WebContents>(contents));
- registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
- content::Source<NavigationController>(&contents->GetController()));
-
- // Multiple sites may share the same RenderProcessHost, so check if this
- // notification has already been added.
- content::Source<content::RenderProcessHost> rph_source(
- contents->GetMainFrame()->GetProcess());
- if (!registrar_.IsRegistered(this,
- content::NOTIFICATION_RENDERER_PROCESS_CLOSED, rph_source)) {
- // Not registered for this host yet, so add the notification and add the
- // host to the count map with a count of 1.
- registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
- rph_source);
- host_contents_count_map_[contents->GetMainFrame()->GetProcess()] = 1;
- } else {
- // This host's notification is already registered. Increment its count in
- // the map so that the notification will not be removed from the registry
- // until all web contents that use it are destroyed.
- ++host_contents_count_map_[contents->GetMainFrame()->GetProcess()];
- }
+void PrintPreviewDialogController::AddObserver(WebContents* contents) {
+ auto emplace_result = web_contents_observers_.emplace(
+ std::piecewise_construct, std::forward_as_tuple(contents),
+ std::forward_as_tuple(
+ std::make_unique<WebContentsObserver>(this, contents)));
+ DCHECK(emplace_result.second);
}
-void PrintPreviewDialogController::RemoveObservers(WebContents* contents) {
- registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
- content::Source<WebContents>(contents));
- registrar_.Remove(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
- content::Source<NavigationController>(&contents->GetController()));
-
- // Multiple sites may share the same RenderProcessHost, so check if this
- // notification has already been added.
- content::Source<content::RenderProcessHost> rph_source(
- contents->GetMainFrame()->GetProcess());
- if (registrar_.IsRegistered(this,
- content::NOTIFICATION_RENDERER_PROCESS_CLOSED, rph_source)) {
- if (host_contents_count_map_[contents->GetMainFrame()->GetProcess()] == 1) {
- // This is the last contents that has this render process host, so we can
- // remove the notification.
- registrar_.Remove(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
- rph_source);
- host_contents_count_map_.erase(contents->GetMainFrame()->GetProcess());
- } else {
- // Other initializers and/or dialogs are still connected to the host, so
- // we can't remove the notification. Decrement the count in the map.
- --host_contents_count_map_[contents->GetMainFrame()->GetProcess()];
- }
- }
+void PrintPreviewDialogController::RemoveObserver(WebContents* contents) {
+ web_contents_observers_.erase(contents);
}
void PrintPreviewDialogController::RemoveInitiator(
@@ -509,7 +490,7 @@ void PrintPreviewDialogController::RemoveInitiator(
// and reaches RemovePreviewDialog(), it does not attempt to also remove the
// initiator's observers.
preview_dialog_map_[preview_dialog] = nullptr;
- RemoveObservers(initiator);
+ RemoveObserver(initiator);
PrintViewManager::FromWebContents(initiator)->PrintPreviewDone();
@@ -524,12 +505,12 @@ void PrintPreviewDialogController::RemovePreviewDialog(
// Remove the initiator's observers before erasing the mapping.
WebContents* initiator = GetInitiator(preview_dialog);
if (initiator) {
- RemoveObservers(initiator);
+ RemoveObserver(initiator);
PrintViewManager::FromWebContents(initiator)->PrintPreviewDone();
}
preview_dialog_map_.erase(preview_dialog);
- RemoveObservers(preview_dialog);
+ RemoveObserver(preview_dialog);
}
} // namespace printing
diff --git a/chromium/chrome/browser/printing/print_preview_dialog_controller.h b/chromium/chrome/browser/printing/print_preview_dialog_controller.h
index fefafc8709b..351c0dfba2b 100644
--- a/chromium/chrome/browser/printing/print_preview_dialog_controller.h
+++ b/chromium/chrome/browser/printing/print_preview_dialog_controller.h
@@ -6,13 +6,12 @@
#define CHROME_BROWSER_PRINTING_PRINT_PREVIEW_DIALOG_CONTROLLER_H_
#include <map>
+#include <memory>
#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "components/sessions/core/session_id.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
class GURL;
@@ -31,9 +30,10 @@ namespace printing {
// track of the 1:1 relationship between initiator tabs and print preview
// dialogs.
class PrintPreviewDialogController
- : public base::RefCounted<PrintPreviewDialogController>,
- public content::NotificationObserver {
+ : public base::RefCounted<PrintPreviewDialogController> {
public:
+ class WebContentsObserver;
+
PrintPreviewDialogController();
static PrintPreviewDialogController* GetInstance();
@@ -62,12 +62,7 @@ class PrintPreviewDialogController
// Run |callback| on the dialog of each active print preview operation.
void ForEachPreviewDialog(
- base::Callback<void(content::WebContents*)> callback);
-
- // content::NotificationObserver implementation.
- void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) override;
+ base::RepeatingCallback<void(content::WebContents*)> callback);
// Erase the initiator info associated with |preview_dialog|.
void EraseInitiatorInfo(content::WebContents* preview_dialog);
@@ -85,26 +80,26 @@ class PrintPreviewDialogController
using PrintPreviewDialogMap =
std::map<content::WebContents*, content::WebContents*>;
- ~PrintPreviewDialogController() override;
+ ~PrintPreviewDialogController();
- // Handler for the RENDERER_PROCESS_CLOSED notification. This is observed when
- // the initiator renderer crashed.
+ // Handles the closing of the RenderProcessHost. This is observed when the
+ // initiator renderer crashes.
void OnRendererProcessClosed(content::RenderProcessHost* rph);
- // Handler for the WEB_CONTENTS_DESTROYED notification. This is observed when
- // either WebContents is closed.
+ // Handles the destruction of |contents|. This is observed when either
+ // the initiator or preview WebContents is closed.
void OnWebContentsDestroyed(content::WebContents* contents);
- // Handler for the NAV_ENTRY_COMMITTED notification. This is observed when the
- // renderer is navigated to a different page.
+ // Handles the commit of a navigation entry for |contents|. This is observed
+ // when the renderer for either WebContents is navigated to a different page.
void OnNavEntryCommitted(content::WebContents* contents,
- const content::LoadCommittedDetails* details);
+ const content::LoadCommittedDetails& details);
// Helpers for OnNavEntryCommitted().
void OnInitiatorNavigated(content::WebContents* initiator,
- const content::LoadCommittedDetails* details);
+ const content::LoadCommittedDetails& details);
void OnPreviewDialogNavigated(content::WebContents* preview_dialog,
- const content::LoadCommittedDetails* details);
+ const content::LoadCommittedDetails& details);
// Creates a new print preview dialog.
content::WebContents* CreatePrintPreviewDialog(
@@ -114,9 +109,9 @@ class PrintPreviewDialogController
// |preview_dialog| in |preview_dialog|'s PrintPreviewUI.
void SaveInitiatorTitle(content::WebContents* preview_dialog);
- // Adds/Removes observers for notifications from |contents|.
- void AddObservers(content::WebContents* contents);
- void RemoveObservers(content::WebContents* contents);
+ // Adds/Removes the WebContentsObserver for |contents|.
+ void AddObserver(content::WebContents* contents);
+ void RemoveObserver(content::WebContents* contents);
// Removes WebContents when they close/crash/navigate.
void RemoveInitiator(content::WebContents* initiator);
@@ -125,9 +120,6 @@ class PrintPreviewDialogController
// Mapping between print preview dialog and the corresponding initiator.
PrintPreviewDialogMap preview_dialog_map_;
- // A registrar for listening to notifications.
- content::NotificationRegistrar registrar_;
-
// True if the controller is waiting for a new preview dialog via
// content::NAVIGATION_TYPE_NEW_PAGE.
bool waiting_for_new_preview_page_ = false;
@@ -136,11 +128,8 @@ class PrintPreviewDialogController
// print preview dialog.
bool is_creating_print_preview_dialog_ = false;
- // How many web contents (dialogs and initiators) are watching a given render
- // process host. Used to determine when a render process host's
- // NOTIFICATION_RENDERER_PROCESS_CLOSED notification should be removed from
- // the registrar.
- std::map<content::RenderProcessHost*, int> host_contents_count_map_;
+ std::map<content::WebContents*, std::unique_ptr<WebContentsObserver>>
+ web_contents_observers_;
DISALLOW_COPY_AND_ASSIGN(PrintPreviewDialogController);
};
diff --git a/chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc b/chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc
index 98fb0002f4a..77354643bdf 100644
--- a/chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc
+++ b/chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc
@@ -53,8 +53,8 @@ class RequestPrintPreviewObserver : public WebContentsObserver {
: WebContentsObserver(dialog) {}
~RequestPrintPreviewObserver() override = default;
- void set_quit_closure(const base::Closure& quit_closure) {
- quit_closure_ = quit_closure;
+ void set_quit_closure(base::OnceClosure quit_closure) {
+ quit_closure_ = std::move(quit_closure);
}
private:
@@ -71,10 +71,11 @@ class RequestPrintPreviewObserver : public WebContentsObserver {
void OnRequestPrintPreview(
const PrintHostMsg_RequestPrintPreview_Params& /* params */) {
- base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, quit_closure_);
+ base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
+ std::move(quit_closure_));
}
- base::Closure quit_closure_;
+ base::OnceClosure quit_closure_;
DISALLOW_COPY_AND_ASSIGN(RequestPrintPreviewObserver);
};
@@ -120,9 +121,9 @@ class PrintPreviewDialogDestroyedObserver : public WebContentsObserver {
};
void PluginsLoadedCallback(
- const base::Closure& quit_closure,
+ base::OnceClosure quit_closure,
const std::vector<content::WebPluginInfo>& /* info */) {
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
bool GetPdfPluginInfo(content::WebPluginInfo* info) {
@@ -292,7 +293,7 @@ IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest,
{
base::RunLoop run_loop;
content::PluginService::GetInstance()->GetPlugins(
- base::Bind(&PluginsLoadedCallback, run_loop.QuitClosure()));
+ base::BindOnce(&PluginsLoadedCallback, run_loop.QuitClosure()));
run_loop.Run();
}
// Get the PDF plugin info.
diff --git a/chromium/chrome/browser/printing/print_preview_message_handler.cc b/chromium/chrome/browser/printing/print_preview_message_handler.cc
index cbede811f0b..5fd2ea6af9f 100644
--- a/chromium/chrome/browser/printing/print_preview_message_handler.cc
+++ b/chromium/chrome/browser/printing/print_preview_message_handler.cc
@@ -48,12 +48,12 @@ void StopWorker(int document_cookie) {
return;
scoped_refptr<PrintQueriesQueue> queue =
g_browser_process->print_job_manager()->queue();
- scoped_refptr<PrinterQuery> printer_query =
+ std::unique_ptr<PrinterQuery> printer_query =
queue->PopPrinterQuery(document_cookie);
if (printer_query) {
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&PrinterQuery::StopWorker, printer_query));
+ base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query)));
}
}
@@ -69,7 +69,7 @@ bool IsValidPageNumber(int page_number, int page_count) {
PrintPreviewMessageHandler::PrintPreviewMessageHandler(
WebContents* web_contents)
- : content::WebContentsObserver(web_contents), weak_ptr_factory_(this) {
+ : content::WebContentsObserver(web_contents) {
DCHECK(web_contents);
}
@@ -315,7 +315,7 @@ void PrintPreviewMessageHandler::OnCompositePdfPageDone(
mojom::PdfCompositor::Status status,
base::ReadOnlySharedMemoryRegion region) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (status != mojom::PdfCompositor::Status::SUCCESS) {
+ if (status != mojom::PdfCompositor::Status::kSuccess) {
DLOG(ERROR) << "Compositing pdf failed with error " << status;
return;
}
@@ -386,7 +386,7 @@ void PrintPreviewMessageHandler::OnCompositePdfDocumentDone(
mojom::PdfCompositor::Status status,
base::ReadOnlySharedMemoryRegion region) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (status != mojom::PdfCompositor::Status::SUCCESS) {
+ if (status != mojom::PdfCompositor::Status::kSuccess) {
DLOG(ERROR) << "Compositing pdf failed with error " << status;
return;
}
diff --git a/chromium/chrome/browser/printing/print_preview_message_handler.h b/chromium/chrome/browser/printing/print_preview_message_handler.h
index 8b57c48caf3..557e7b52632 100644
--- a/chromium/chrome/browser/printing/print_preview_message_handler.h
+++ b/chromium/chrome/browser/printing/print_preview_message_handler.h
@@ -9,7 +9,7 @@
#include "base/memory/read_only_shared_memory_region.h"
#include "base/memory/weak_ptr.h"
#include "chrome/services/printing/public/mojom/pdf_nup_converter.mojom.h"
-#include "components/services/pdf_compositor/public/interfaces/pdf_compositor.mojom.h"
+#include "components/services/pdf_compositor/public/mojom/pdf_compositor.mojom.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
@@ -121,7 +121,7 @@ class PrintPreviewMessageHandler
mojom::PdfNupConverter::Status status,
base::ReadOnlySharedMemoryRegion region);
- base::WeakPtrFactory<PrintPreviewMessageHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<PrintPreviewMessageHandler> weak_ptr_factory_{this};
WEB_CONTENTS_USER_DATA_KEY_DECL();
diff --git a/chromium/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc b/chromium/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc
index d328244da2f..bb799adf071 100644
--- a/chromium/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc
+++ b/chromium/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc
@@ -130,13 +130,14 @@ class PrintPreviewObserver : public WebContentsObserver {
~PrintPreviewObserver() override {}
// Sets closure for the observer so that it can end the loop.
- void set_quit_closure(const base::Closure &closure) {
- quit_closure_ = closure;
+ void set_quit_closure(base::OnceClosure closure) {
+ quit_closure_ = std::move(closure);
}
// Actually stops the message loop so that the test can proceed.
void EndLoop() {
- base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, quit_closure_);
+ base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
+ std::move(quit_closure_));
}
bool OnMessageReceived(const IPC::Message& message) override {
@@ -199,9 +200,8 @@ class PrintPreviewObserver : public WebContentsObserver {
} else if (state_ == kWaitingForFinalMessage) {
// Called by |GetUI()->handler_|, it is a callback function that call
// |EndLoop| when an attempt to save the PDF has been made.
- base::Closure end_loop_closure =
- base::Bind(&PrintPreviewObserver::EndLoop, base::Unretained(this));
- GetUI()->SetPdfSavedClosureForTesting(end_loop_closure);
+ GetUI()->SetPdfSavedClosureForTesting(base::BindOnce(
+ &PrintPreviewObserver::EndLoop, base::Unretained(this)));
ASSERT_FALSE(pdf_file_save_path_.empty());
GetUI()->SetSelectedFileForTesting(pdf_file_save_path_);
return;
@@ -290,7 +290,7 @@ class PrintPreviewObserver : public WebContentsObserver {
}
Browser* browser_;
- base::Closure quit_closure_;
+ base::OnceClosure quit_closure_;
std::unique_ptr<PrintPreviewSettings> settings_;
// State of the observer. The state indicates what message to send
diff --git a/chromium/chrome/browser/printing/print_view_manager.cc b/chromium/chrome/browser/printing/print_view_manager.cc
index 8cdc79408bf..c3a8b8056b3 100644
--- a/chromium/chrome/browser/printing/print_view_manager.cc
+++ b/chromium/chrome/browser/printing/print_view_manager.cc
@@ -33,8 +33,8 @@ namespace {
// Keeps track of pending scripted print preview closures.
// No locking, only access on the UI thread.
-base::LazyInstance<std::map<content::RenderProcessHost*, base::Closure>>::Leaky
- g_scripted_print_preview_closure_map = LAZY_INSTANCE_INITIALIZER;
+base::LazyInstance<std::map<content::RenderProcessHost*, base::OnceClosure>>::
+ Leaky g_scripted_print_preview_closure_map = LAZY_INSTANCE_INITIALIZER;
void EnableInternalPDFPluginForContents(int render_process_id,
int render_frame_id) {
@@ -170,7 +170,7 @@ void PrintViewManager::PrintPreviewDone() {
auto& map = g_scripted_print_preview_closure_map.Get();
auto it = map.find(scripted_print_preview_rph_);
CHECK(it != map.end());
- it->second.Run();
+ std::move(it->second).Run();
map.erase(it);
// PrintPreviewAlmostDone() usually already calls this. Calling it again
@@ -213,7 +213,7 @@ void PrintViewManager::OnSetupScriptedPrintPreview(
auto& map = g_scripted_print_preview_closure_map.Get();
content::RenderProcessHost* rph = rfh->GetProcess();
- if (base::ContainsKey(map, rph)) {
+ if (base::Contains(map, rph)) {
// Renderer already handling window.print(). Abort this attempt to prevent
// the renderer from having multiple nested loops. If multiple nested loops
// existed, then they have to exit in the right order and that is messy.
@@ -238,8 +238,8 @@ void PrintViewManager::OnSetupScriptedPrintPreview(
DCHECK(!print_preview_rfh_);
print_preview_rfh_ = rfh;
print_preview_state_ = SCRIPTED_PREVIEW;
- map[rph] = base::Bind(&PrintViewManager::OnScriptedPrintPreviewReply,
- base::Unretained(this), reply_msg);
+ map[rph] = base::BindOnce(&PrintViewManager::OnScriptedPrintPreviewReply,
+ base::Unretained(this), reply_msg);
scripted_print_preview_rph_ = rph;
DCHECK(!scripted_print_preview_rph_set_blocked_);
if (!scripted_print_preview_rph_->IsBlocked()) {
diff --git a/chromium/chrome/browser/printing/print_view_manager_base.cc b/chromium/chrome/browser/printing/print_view_manager_base.cc
index 309477ec68e..c4e0992f626 100644
--- a/chromium/chrome/browser/printing/print_view_manager_base.cc
+++ b/chromium/chrome/browser/printing/print_view_manager_base.cc
@@ -61,7 +61,7 @@ namespace printing {
namespace {
using PrintSettingsCallback =
- base::OnceCallback<void(scoped_refptr<PrinterQuery>)>;
+ base::OnceCallback<void(std::unique_ptr<PrinterQuery>)>;
void ShowWarningMessageBox(const base::string16& message) {
// Runs always on the UI thread.
@@ -76,11 +76,12 @@ void ShowWarningMessageBox(const base::string16& message) {
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
void OnPrintSettingsDoneWrapper(PrintSettingsCallback settings_callback,
- scoped_refptr<PrinterQuery> query) {
+ std::unique_ptr<PrinterQuery> query) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(std::move(settings_callback), query));
+ base::PostTaskWithTraits(
+ FROM_HERE, {content::BrowserThread::UI},
+ base::BindOnce(std::move(settings_callback), std::move(query)));
}
void CreateQueryWithSettings(base::Value job_settings,
@@ -92,11 +93,12 @@ void CreateQueryWithSettings(base::Value job_settings,
PrintSettingsCallback callback_wrapper =
base::BindOnce(OnPrintSettingsDoneWrapper, std::move(callback));
- scoped_refptr<printing::PrinterQuery> printer_query =
+ std::unique_ptr<printing::PrinterQuery> printer_query =
queue->CreatePrinterQuery(render_process_id, render_frame_id);
- printer_query->SetSettings(
+ auto* printer_query_ptr = printer_query.get();
+ printer_query_ptr->SetSettings(
std::move(job_settings),
- base::BindOnce(std::move(callback_wrapper), printer_query));
+ base::BindOnce(std::move(callback_wrapper), std::move(printer_query)));
}
#endif // BUILDFLAG(ENABLE_PRINT_PREVIEW)
@@ -106,15 +108,14 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents)
: PrintManager(web_contents),
printing_rfh_(nullptr),
printing_succeeded_(false),
- queue_(g_browser_process->print_job_manager()->queue()),
- weak_ptr_factory_(this) {
+ queue_(g_browser_process->print_job_manager()->queue()) {
DCHECK(queue_);
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
printing_enabled_.Init(
prefs::kPrintingEnabled, profile->GetPrefs(),
- base::Bind(&PrintViewManagerBase::UpdatePrintingEnabled,
- weak_ptr_factory_.GetWeakPtr()));
+ base::BindRepeating(&PrintViewManagerBase::UpdatePrintingEnabled,
+ weak_ptr_factory_.GetWeakPtr()));
}
PrintViewManagerBase::~PrintViewManagerBase() {
@@ -174,14 +175,14 @@ void PrintViewManagerBase::OnPrintSettingsDone(
scoped_refptr<base::RefCountedMemory> print_data,
int page_count,
PrinterHandler::PrintCallback callback,
- scoped_refptr<printing::PrinterQuery> printer_query) {
+ std::unique_ptr<printing::PrinterQuery> printer_query) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(printer_query);
// Check if the job was cancelled. This should only happen on Windows when
// the system dialog is cancelled.
if (printer_query->last_status() == PrintingContext::CANCEL) {
- queue_->QueuePrinterQuery(printer_query.get());
+ queue_->QueuePrinterQuery(std::move(printer_query));
#if defined(OS_WIN)
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::UI},
@@ -195,31 +196,32 @@ void PrintViewManagerBase::OnPrintSettingsDone(
if (!printer_query->cookie() || !printer_query->settings().dpi()) {
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&PrinterQuery::StopWorker, printer_query));
+ base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query)));
std::move(callback).Run(base::Value("Update settings failed"));
return;
}
// Post task so that the query has time to reset the callback before calling
// OnDidGetPrintedPagesCount().
- queue_->QueuePrinterQuery(printer_query.get());
+ int cookie = printer_query->cookie();
+ queue_->QueuePrinterQuery(std::move(printer_query));
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(&PrintViewManagerBase::StartLocalPrintJob,
weak_ptr_factory_.GetWeakPtr(), print_data, page_count,
- printer_query, std::move(callback)));
+ cookie, std::move(callback)));
}
void PrintViewManagerBase::StartLocalPrintJob(
scoped_refptr<base::RefCountedMemory> print_data,
int page_count,
- scoped_refptr<printing::PrinterQuery> printer_query,
+ int cookie,
PrinterHandler::PrintCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- OnDidGetPrintedPagesCount(printer_query->cookie(), page_count);
+ OnDidGetPrintedPagesCount(cookie, page_count);
- if (!PrintJobHasDocument(printer_query->cookie())) {
+ if (!PrintJobHasDocument(cookie)) {
std::move(callback).Run(base::Value("Failed to print"));
return;
}
@@ -228,7 +230,7 @@ void PrintViewManagerBase::StartLocalPrintJob(
print_job_->ResetPageMapping();
#endif
- const printing::PrintSettings& settings = printer_query->settings();
+ const printing::PrintSettings& settings = print_job_->settings();
gfx::Size page_size = settings.page_setup_device_units().physical_size();
gfx::Rect content_area =
gfx::Rect(0, 0, page_size.width(), page_size.height());
@@ -282,7 +284,7 @@ void PrintViewManagerBase::OnComposePdfDone(
mojom::PdfCompositor::Status status,
base::ReadOnlySharedMemoryRegion region) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- if (status != mojom::PdfCompositor::Status::SUCCESS) {
+ if (status != mojom::PdfCompositor::Status::kSuccess) {
DLOG(ERROR) << "Compositing pdf failed with error " << status;
return;
}
@@ -527,7 +529,8 @@ void PrintViewManagerBase::ShouldQuitFromInnerMessageLoop() {
}
}
-bool PrintViewManagerBase::CreateNewPrintJob(PrinterQuery* query) {
+bool PrintViewManagerBase::CreateNewPrintJob(
+ std::unique_ptr<PrinterQuery> query) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(!quit_inner_loop_);
DCHECK(query);
@@ -543,7 +546,7 @@ bool PrintViewManagerBase::CreateNewPrintJob(PrinterQuery* query) {
DCHECK(!print_job_);
print_job_ = base::MakeRefCounted<PrintJob>();
- print_job_->Initialize(query, RenderSourceName(), number_pages_);
+ print_job_->Initialize(std::move(query), RenderSourceName(), number_pages_);
registrar_.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT,
content::Source<PrintJob>(print_job_.get()));
printing_succeeded_ = false;
@@ -624,17 +627,13 @@ bool PrintViewManagerBase::RunInnerMessageLoop() {
static constexpr base::TimeDelta kPrinterSettingsTimeout =
base::TimeDelta::FromSeconds(60);
base::OneShotTimer quit_timer;
- base::RunLoop run_loop;
+ base::RunLoop run_loop{base::RunLoop::Type::kNestableTasksAllowed};
quit_timer.Start(FROM_HERE, kPrinterSettingsTimeout,
run_loop.QuitWhenIdleClosure());
quit_inner_loop_ = run_loop.QuitClosure();
- // Need to enable recursive task.
- {
- base::MessageLoopCurrent::ScopedNestableTaskAllower allow;
- run_loop.Run();
- }
+ run_loop.Run();
// If the inner-loop quit closure is still set then we timed out.
bool success = !quit_inner_loop_;
@@ -655,13 +654,13 @@ bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) {
// The job was initiated by a script. Time to get the corresponding worker
// thread.
- scoped_refptr<PrinterQuery> queued_query = queue_->PopPrinterQuery(cookie);
+ std::unique_ptr<PrinterQuery> queued_query = queue_->PopPrinterQuery(cookie);
if (!queued_query) {
NOTREACHED();
return false;
}
- if (!CreateNewPrintJob(queued_query.get())) {
+ if (!CreateNewPrintJob(std::move(queued_query))) {
// Don't kill anything.
return false;
}
@@ -698,13 +697,12 @@ void PrintViewManagerBase::ReleasePrinterQuery() {
if (!print_job_manager)
return;
- scoped_refptr<PrinterQuery> printer_query;
- printer_query = queue_->PopPrinterQuery(cookie);
+ std::unique_ptr<PrinterQuery> printer_query = queue_->PopPrinterQuery(cookie);
if (!printer_query)
return;
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&PrinterQuery::StopWorker, printer_query));
+ base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query)));
}
void PrintViewManagerBase::SendPrintingEnabled(bool enabled,
diff --git a/chromium/chrome/browser/printing/print_view_manager_base.h b/chromium/chrome/browser/printing/print_view_manager_base.h
index cf074791d0e..925736d379c 100644
--- a/chromium/chrome/browser/printing/print_view_manager_base.h
+++ b/chromium/chrome/browser/printing/print_view_manager_base.h
@@ -17,7 +17,7 @@
#include "chrome/browser/ui/webui/print_preview/printer_handler.h"
#include "components/prefs/pref_member.h"
#include "components/printing/browser/print_manager.h"
-#include "components/services/pdf_compositor/public/interfaces/pdf_compositor.mojom.h"
+#include "components/services/pdf_compositor/public/mojom/pdf_compositor.mojom.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "printing/buildflags/buildflags.h"
@@ -90,7 +90,7 @@ class PrintViewManagerBase : public content::NotificationObserver,
// currently a print job, safely disconnect from it. Returns false if it is
// impossible to safely disconnect from the current print job or it is
// impossible to create a new print job.
- virtual bool CreateNewPrintJob(PrinterQuery* query);
+ virtual bool CreateNewPrintJob(std::unique_ptr<PrinterQuery> query);
// Manages the low-level talk to the printer.
scoped_refptr<PrintJob> print_job_;
@@ -126,11 +126,11 @@ class PrintViewManagerBase : public content::NotificationObserver,
void OnPrintSettingsDone(scoped_refptr<base::RefCountedMemory> print_data,
int page_count,
PrinterHandler::PrintCallback callback,
- scoped_refptr<PrinterQuery> printer_query);
+ std::unique_ptr<PrinterQuery> printer_query);
void StartLocalPrintJob(scoped_refptr<base::RefCountedMemory> print_data,
int page_count,
- scoped_refptr<PrinterQuery> printer_query,
+ int cookie,
PrinterHandler::PrintCallback callback);
#endif // BUILDFLAG(ENABLE_PRINT_PREVIEW)
@@ -208,7 +208,7 @@ class PrintViewManagerBase : public content::NotificationObserver,
scoped_refptr<PrintQueriesQueue> queue_;
- base::WeakPtrFactory<PrintViewManagerBase> weak_ptr_factory_;
+ base::WeakPtrFactory<PrintViewManagerBase> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(PrintViewManagerBase);
};
diff --git a/chromium/chrome/browser/printing/print_view_manager_unittest.cc b/chromium/chrome/browser/printing/print_view_manager_unittest.cc
index 79fd9335595..89e5c28f2c8 100644
--- a/chromium/chrome/browser/printing/print_view_manager_unittest.cc
+++ b/chromium/chrome/browser/printing/print_view_manager_unittest.cc
@@ -74,9 +74,9 @@ class TestPrintViewManager : public PrintViewManagerBase {
protected:
// Override to create a TestPrintJob instead of a real one.
- bool CreateNewPrintJob(PrinterQuery* query) override {
+ bool CreateNewPrintJob(std::unique_ptr<PrinterQuery> query) override {
print_job_ = base::MakeRefCounted<TestPrintJob>();
- print_job_->Initialize(query, RenderSourceName(), number_pages_);
+ print_job_->Initialize(std::move(query), RenderSourceName(), number_pages_);
return true;
}
diff --git a/chromium/chrome/browser/printing/printer_manager_dialog.h b/chromium/chrome/browser/printing/printer_manager_dialog.h
index 6779a764664..a8df6f3ea11 100644
--- a/chromium/chrome/browser/printing/printer_manager_dialog.h
+++ b/chromium/chrome/browser/printing/printer_manager_dialog.h
@@ -12,6 +12,8 @@
#error "Printing must be enabled"
#endif
+class Profile;
+
namespace printing {
// An abstraction of a printer manager dialog. This is used for the printing
@@ -20,7 +22,7 @@ namespace printing {
class PrinterManagerDialog {
public:
// Displays the native printer manager dialog.
- static void ShowPrinterManagerDialog();
+ static void ShowPrinterManagerDialog(Profile* profile);
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(PrinterManagerDialog);
diff --git a/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc b/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc
index 0289ce155bb..672a6c5cc4f 100644
--- a/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc
+++ b/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc
@@ -87,7 +87,7 @@ void DetectAndOpenPrinterConfigDialog() {
namespace printing {
-void PrinterManagerDialog::ShowPrinterManagerDialog() {
+void PrinterManagerDialog::ShowPrinterManagerDialog(Profile* profile) {
base::PostTaskWithTraits(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
base::BindOnce(&DetectAndOpenPrinterConfigDialog));
diff --git a/chromium/chrome/browser/printing/printer_manager_dialog_mac.mm b/chromium/chrome/browser/printing/printer_manager_dialog_mac.mm
index 44bfc690f2b..6c58eff1a39 100644
--- a/chromium/chrome/browser/printing/printer_manager_dialog_mac.mm
+++ b/chromium/chrome/browser/printing/printer_manager_dialog_mac.mm
@@ -11,7 +11,7 @@ namespace printing {
static NSString* kPrintAndFaxPrefPane =
@"/System/Library/PreferencePanes/PrintAndFax.prefPane";
-void PrinterManagerDialog::ShowPrinterManagerDialog() {
+void PrinterManagerDialog::ShowPrinterManagerDialog(Profile* profile) {
[[NSWorkspace sharedWorkspace] openFile:kPrintAndFaxPrefPane];
}
diff --git a/chromium/chrome/browser/printing/printer_manager_dialog_win.cc b/chromium/chrome/browser/printing/printer_manager_dialog_win.cc
index 9ea0e8126f3..3bb3253522e 100644
--- a/chromium/chrome/browser/printing/printer_manager_dialog_win.cc
+++ b/chromium/chrome/browser/printing/printer_manager_dialog_win.cc
@@ -12,6 +12,9 @@
#include "base/path_service.h"
#include "base/task/post_task.h"
#include "base/threading/thread.h"
+#include "base/win/windows_version.h"
+#include "chrome/browser/platform_util.h"
+#include "url/gurl.h"
namespace {
@@ -32,10 +35,14 @@ void OpenPrintersDialogCallback() {
namespace printing {
-void PrinterManagerDialog::ShowPrinterManagerDialog() {
- base::PostTaskWithTraits(
- FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
- base::BindOnce(OpenPrintersDialogCallback));
+void PrinterManagerDialog::ShowPrinterManagerDialog(Profile* profile) {
+ if (base::win::GetVersion() >= base::win::Version::WIN10_RS1) {
+ platform_util::OpenExternal(profile, GURL("ms-settings:printers"));
+ } else {
+ base::PostTaskWithTraits(
+ FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
+ base::BindOnce(OpenPrintersDialogCallback));
+ }
}
} // namespace printing
diff --git a/chromium/chrome/browser/printing/printer_query.cc b/chromium/chrome/browser/printing/printer_query.cc
index 2abaa6e3168..6bd6dd72b58 100644
--- a/chromium/chrome/browser/printing/printer_query.cc
+++ b/chromium/chrome/browser/printing/printer_query.cc
@@ -23,24 +23,21 @@
namespace printing {
PrinterQuery::PrinterQuery(int render_process_id, int render_frame_id)
- : base::RefCountedDeleteOnSequence<PrinterQuery>(
- base::ThreadTaskRunnerHandle::Get()),
- cookie_(PrintSettings::NewCookie()),
+ : cookie_(PrintSettings::NewCookie()),
worker_(std::make_unique<PrintJobWorker>(render_process_id,
- render_frame_id,
- this)) {
+ render_frame_id)) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
}
PrinterQuery::~PrinterQuery() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
// The job should be finished (or at least canceled) when it is destroyed.
DCHECK(!is_print_dialog_box_shown_);
// If this fires, it is that this pending printer context has leaked.
DCHECK(!worker_);
}
-void PrinterQuery::GetSettingsDone(const PrintSettings& new_settings,
+void PrinterQuery::GetSettingsDone(base::OnceClosure callback,
+ const PrintSettings& new_settings,
PrintingContext::Result result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
is_print_dialog_box_shown_ = false;
@@ -53,15 +50,21 @@ void PrinterQuery::GetSettingsDone(const PrintSettings& new_settings,
cookie_ = 0;
}
- if (callback_) {
- // This may cause reentrancy like to call StopWorker().
- std::move(callback_).Run();
- }
+ std::move(callback).Run();
+}
+
+void PrinterQuery::PostSettingsDoneToIO(base::OnceClosure callback,
+ const PrintSettings& new_settings,
+ PrintingContext::Result result) {
+ // |this| is owned by |callback|, so |base::Unretained()| is safe.
+ base::PostTaskWithTraits(
+ FROM_HERE, {content::BrowserThread::IO},
+ base::BindOnce(&PrinterQuery::GetSettingsDone, base::Unretained(this),
+ std::move(callback), new_settings, result));
}
std::unique_ptr<PrintJobWorker> PrinterQuery::DetachWorker() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- DCHECK(!callback_);
DCHECK(worker_);
return std::move(worker_);
@@ -75,10 +78,6 @@ int PrinterQuery::cookie() const {
return cookie_;
}
-void PrinterQuery::set_callback(base::OnceClosure callback) {
- callback_ = std::move(callback);
-}
-
void PrinterQuery::GetSettings(GetSettingsAskParam ask_user_for_settings,
int expected_page_count,
bool has_selection,
@@ -89,27 +88,35 @@ void PrinterQuery::GetSettings(GetSettingsAskParam ask_user_for_settings,
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!is_print_dialog_box_shown_ || !is_scripted);
- StartWorker(std::move(callback));
+ StartWorker();
// Real work is done in PrintJobWorker::GetSettings().
is_print_dialog_box_shown_ =
ask_user_for_settings == GetSettingsAskParam::ASK_USER;
+ // |this| is owned by |callback|, so |base::Unretained()| is safe.
worker_->PostTask(
FROM_HERE,
- base::BindOnce(&PrintJobWorker::GetSettings,
- base::Unretained(worker_.get()),
- is_print_dialog_box_shown_, expected_page_count,
- has_selection, margin_type, is_scripted, is_modifiable));
+ base::BindOnce(
+ &PrintJobWorker::GetSettings, base::Unretained(worker_.get()),
+ is_print_dialog_box_shown_, expected_page_count, has_selection,
+ margin_type, is_scripted, is_modifiable,
+ base::BindOnce(&PrinterQuery::PostSettingsDoneToIO,
+ base::Unretained(this), std::move(callback))));
}
void PrinterQuery::SetSettings(base::Value new_settings,
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- StartWorker(std::move(callback));
- worker_->PostTask(FROM_HERE, base::BindOnce(&PrintJobWorker::SetSettings,
- base::Unretained(worker_.get()),
- std::move(new_settings)));
+ StartWorker();
+ // |this| is owned by |callback|, so |base::Unretained()| is safe.
+ worker_->PostTask(
+ FROM_HERE,
+ base::BindOnce(
+ &PrintJobWorker::SetSettings, base::Unretained(worker_.get()),
+ std::move(new_settings),
+ base::BindOnce(&PrinterQuery::PostSettingsDoneToIO,
+ base::Unretained(this), std::move(callback))));
}
#if defined(OS_CHROMEOS)
@@ -118,24 +125,25 @@ void PrinterQuery::SetSettingsFromPOD(
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- StartWorker(std::move(callback));
+ StartWorker();
+ // |this| is owned by |callback|, so |base::Unretained()| is safe.
worker_->PostTask(
FROM_HERE,
- base::BindOnce(&PrintJobWorker::SetSettingsFromPOD,
- base::Unretained(worker_.get()), std::move(new_settings)));
+ base::BindOnce(
+ &PrintJobWorker::SetSettingsFromPOD, base::Unretained(worker_.get()),
+ std::move(new_settings),
+ base::BindOnce(&PrinterQuery::PostSettingsDoneToIO,
+ base::Unretained(this), std::move(callback))));
}
#endif
-void PrinterQuery::StartWorker(base::OnceClosure callback) {
+void PrinterQuery::StartWorker() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- DCHECK(!callback_);
DCHECK(worker_);
// Lazily create the worker thread. There is one worker thread per print job.
if (!worker_->IsRunning())
worker_->Start();
-
- callback_ = std::move(callback);
}
void PrinterQuery::StopWorker() {
@@ -157,10 +165,6 @@ bool PrinterQuery::PostTask(const base::Location& from_here,
std::move(task));
}
-bool PrinterQuery::is_callback_pending() const {
- return !callback_.is_null();
-}
-
bool PrinterQuery::is_valid() const {
return !!worker_;
}
diff --git a/chromium/chrome/browser/printing/printer_query.h b/chromium/chrome/browser/printing/printer_query.h
index b6d8e2220d0..03047d9a425 100644
--- a/chromium/chrome/browser/printing/printer_query.h
+++ b/chromium/chrome/browser/printing/printer_query.h
@@ -9,7 +9,6 @@
#include "base/callback.h"
#include "base/macros.h"
-#include "base/memory/ref_counted_delete_on_sequence.h"
#include "base/values.h"
#include "printing/print_job_constants.h"
#include "printing/print_settings.h"
@@ -24,7 +23,7 @@ namespace printing {
class PrintJobWorker;
// Query the printer for settings.
-class PrinterQuery : public base::RefCountedDeleteOnSequence<PrinterQuery> {
+class PrinterQuery {
public:
// GetSettings() UI parameter.
enum class GetSettingsAskParam {
@@ -34,10 +33,7 @@ class PrinterQuery : public base::RefCountedDeleteOnSequence<PrinterQuery> {
// Can only be called on the IO thread.
PrinterQuery(int render_process_id, int render_frame_id);
-
- // Virtual so that tests can override.
- virtual void GetSettingsDone(const PrintSettings& new_settings,
- PrintingContext::Result result);
+ virtual ~PrinterQuery();
// Detach the PrintJobWorker associated to this object. Virtual so that tests
// can override.
@@ -52,6 +48,7 @@ class PrinterQuery : public base::RefCountedDeleteOnSequence<PrinterQuery> {
// times to reinitialize the settings. |web_contents_observer| can be queried
// to find the owner of the print setting dialog box. It is unused when
// |ask_for_user_settings| is DEFAULTS.
+ // Caller has to ensure that |this| is alive until |callback| is run.
void GetSettings(GetSettingsAskParam ask_user_for_settings,
int expected_page_count,
bool has_selection,
@@ -61,11 +58,13 @@ class PrinterQuery : public base::RefCountedDeleteOnSequence<PrinterQuery> {
base::OnceClosure callback);
// Updates the current settings with |new_settings| dictionary values.
+ // Caller has to ensure that |this| is alive until |callback| is run.
virtual void SetSettings(base::Value new_settings,
base::OnceClosure callback);
#if defined(OS_CHROMEOS)
// Updates the current settings with |new_settings|.
+ // Caller has to ensure that |this| is alive until |callback| is run.
void SetSettingsFromPOD(std::unique_ptr<PrintSettings> new_settings,
base::OnceClosure callback);
#endif
@@ -73,9 +72,6 @@ class PrinterQuery : public base::RefCountedDeleteOnSequence<PrinterQuery> {
// Stops the worker thread since the client is done with this object.
virtual void StopWorker();
- // Returns true if a GetSettings() call is pending completion.
- bool is_callback_pending() const;
-
int cookie() const;
PrintingContext::Result last_status() const { return last_status_; }
@@ -86,18 +82,18 @@ class PrinterQuery : public base::RefCountedDeleteOnSequence<PrinterQuery> {
bool PostTask(const base::Location& from_here, base::OnceClosure task);
protected:
- // RefCountedDeleteOnSequence class.
- friend class base::RefCountedDeleteOnSequence<PrinterQuery>;
- friend class base::DeleteHelper<PrinterQuery>;
-
- virtual ~PrinterQuery();
+ // Virtual so that tests can override.
+ virtual void GetSettingsDone(base::OnceClosure callback,
+ const PrintSettings& new_settings,
+ PrintingContext::Result result);
- // For unit tests to manually set the print callback.
- void set_callback(base::OnceClosure callback);
+ void PostSettingsDoneToIO(base::OnceClosure callback,
+ const PrintSettings& new_settings,
+ PrintingContext::Result result);
private:
// Lazy create the worker thread. There is one worker thread per print job.
- void StartWorker(base::OnceClosure callback);
+ void StartWorker();
// Cache of the print context settings for access in the UI thread.
PrintSettings settings_;
@@ -111,9 +107,6 @@ class PrinterQuery : public base::RefCountedDeleteOnSequence<PrinterQuery> {
// Results from the last GetSettingsDone() callback.
PrintingContext::Result last_status_ = PrintingContext::FAILED;
- // Callback waiting to be run.
- base::OnceClosure callback_;
-
// All the UI is done in a worker thread because many Win32 print functions
// are blocking and enters a message loop without your consent. There is one
// worker thread per print job.
diff --git a/chromium/chrome/browser/printing/printing_message_filter.cc b/chromium/chrome/browser/printing/printing_message_filter.cc
index 1f79e7b127f..706617b7924 100644
--- a/chromium/chrome/browser/printing/printing_message_filter.cc
+++ b/chromium/chrome/browser/printing/printing_message_filter.cc
@@ -101,7 +101,7 @@ PrintingMessageFilter::PrintingMessageFilter(int render_process_id,
->Subscribe(base::Bind(&PrintingMessageFilter::ShutdownOnUIThread,
base::Unretained(this)));
is_printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs());
- is_printing_enabled_.MoveToThread(
+ is_printing_enabled_.MoveToSequence(
base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}));
}
@@ -137,33 +137,32 @@ bool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message) {
void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- scoped_refptr<PrinterQuery> printer_query;
if (!is_printing_enabled_.GetValue()) {
// Reply with NULL query.
- OnGetDefaultPrintSettingsReply(printer_query, reply_msg);
+ OnGetDefaultPrintSettingsReply(nullptr, reply_msg);
return;
}
- printer_query = queue_->PopPrinterQuery(0);
- if (!printer_query.get()) {
+ std::unique_ptr<PrinterQuery> printer_query = queue_->PopPrinterQuery(0);
+ if (!printer_query) {
printer_query =
queue_->CreatePrinterQuery(render_process_id_, reply_msg->routing_id());
}
// Loads default settings. This is asynchronous, only the IPC message sender
// will hang until the settings are retrieved.
- printer_query->GetSettings(
+ auto* printer_query_ptr = printer_query.get();
+ printer_query_ptr->GetSettings(
PrinterQuery::GetSettingsAskParam::DEFAULTS, 0, false, DEFAULT_MARGINS,
false, false,
- base::Bind(&PrintingMessageFilter::OnGetDefaultPrintSettingsReply, this,
- printer_query, reply_msg));
+ base::BindOnce(&PrintingMessageFilter::OnGetDefaultPrintSettingsReply,
+ this, std::move(printer_query), reply_msg));
}
void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
- scoped_refptr<PrinterQuery> printer_query,
+ std::unique_ptr<PrinterQuery> printer_query,
IPC::Message* reply_msg) {
PrintMsg_Print_Params params;
- if (!printer_query.get() ||
- printer_query->last_status() != PrintingContext::OK) {
+ if (!printer_query || printer_query->last_status() != PrintingContext::OK) {
params.Reset();
} else {
RenderParamsFromPrintSettings(printer_query->settings(), &params);
@@ -172,10 +171,10 @@ void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
PrintHostMsg_GetDefaultPrintSettings::WriteReplyParams(reply_msg, params);
Send(reply_msg);
// If printing was enabled.
- if (printer_query.get()) {
+ if (printer_query) {
// If user hasn't cancelled.
if (printer_query->cookie() && printer_query->settings().dpi()) {
- queue_->QueuePrinterQuery(printer_query.get());
+ queue_->QueuePrinterQuery(std::move(printer_query));
} else {
printer_query->StopWorker();
}
@@ -189,22 +188,23 @@ void PrintingMessageFilter::OnScriptedPrint(
ModuleDatabase::GetInstance()->DisableThirdPartyBlocking();
#endif
- scoped_refptr<PrinterQuery> printer_query =
+ std::unique_ptr<PrinterQuery> printer_query =
queue_->PopPrinterQuery(params.cookie);
- if (!printer_query.get()) {
+ if (!printer_query) {
printer_query =
queue_->CreatePrinterQuery(render_process_id_, reply_msg->routing_id());
}
- printer_query->GetSettings(
+ auto* printer_query_ptr = printer_query.get();
+ printer_query_ptr->GetSettings(
PrinterQuery::GetSettingsAskParam::ASK_USER, params.expected_pages_count,
params.has_selection, params.margin_type, params.is_scripted,
params.is_modifiable,
- base::Bind(&PrintingMessageFilter::OnScriptedPrintReply, this,
- printer_query, reply_msg));
+ base::BindOnce(&PrintingMessageFilter::OnScriptedPrintReply, this,
+ std::move(printer_query), reply_msg));
}
void PrintingMessageFilter::OnScriptedPrintReply(
- scoped_refptr<PrinterQuery> printer_query,
+ std::unique_ptr<PrinterQuery> printer_query,
IPC::Message* reply_msg) {
PrintMsg_PrintPages_Params params;
if (printer_query->last_status() != PrintingContext::OK ||
@@ -218,7 +218,7 @@ void PrintingMessageFilter::OnScriptedPrintReply(
PrintHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params);
Send(reply_msg);
if (!params.params.dpi.IsEmpty() && params.params.document_cookie) {
- queue_->QueuePrinterQuery(printer_query.get());
+ queue_->QueuePrinterQuery(std::move(printer_query));
} else {
printer_query->StopWorker();
}
@@ -227,21 +227,22 @@ void PrintingMessageFilter::OnScriptedPrintReply(
void PrintingMessageFilter::OnUpdatePrintSettings(int document_cookie,
base::Value job_settings,
IPC::Message* reply_msg) {
- scoped_refptr<PrinterQuery> printer_query;
if (!is_printing_enabled_.GetValue()) {
// Reply with NULL query.
- OnUpdatePrintSettingsReply(printer_query, reply_msg);
+ OnUpdatePrintSettingsReply(nullptr, reply_msg);
return;
}
- printer_query = queue_->PopPrinterQuery(document_cookie);
- if (!printer_query.get()) {
+ std::unique_ptr<PrinterQuery> printer_query =
+ queue_->PopPrinterQuery(document_cookie);
+ if (!printer_query) {
printer_query = queue_->CreatePrinterQuery(
content::ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE);
}
- printer_query->SetSettings(
+ auto* printer_query_ptr = printer_query.get();
+ printer_query_ptr->SetSettings(
std::move(job_settings),
- base::Bind(&PrintingMessageFilter::OnUpdatePrintSettingsReply, this,
- printer_query, reply_msg));
+ base::BindOnce(&PrintingMessageFilter::OnUpdatePrintSettingsReply, this,
+ std::move(printer_query), reply_msg));
}
#if defined(OS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
@@ -253,18 +254,17 @@ void PrintingMessageFilter::NotifySystemDialogCancelled(int routing_id) {
#endif
void PrintingMessageFilter::OnUpdatePrintSettingsReply(
- scoped_refptr<PrinterQuery> printer_query,
+ std::unique_ptr<PrinterQuery> printer_query,
IPC::Message* reply_msg) {
PrintMsg_PrintPages_Params params;
- if (!printer_query.get() ||
- printer_query->last_status() != PrintingContext::OK) {
+ if (!printer_query || printer_query->last_status() != PrintingContext::OK) {
params.Reset();
} else {
RenderParamsFromPrintSettings(printer_query->settings(), &params.params);
params.params.document_cookie = printer_query->cookie();
params.pages = PageRange::GetPages(printer_query->settings().ranges());
}
- bool canceled = printer_query.get() &&
+ bool canceled = printer_query &&
(printer_query->last_status() == PrintingContext::CANCEL);
#if defined(OS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
if (canceled) {
@@ -283,9 +283,9 @@ void PrintingMessageFilter::OnUpdatePrintSettingsReply(
canceled);
Send(reply_msg);
// If user hasn't cancelled.
- if (printer_query.get()) {
+ if (printer_query) {
if (printer_query->cookie() && printer_query->settings().dpi()) {
- queue_->QueuePrinterQuery(printer_query.get());
+ queue_->QueuePrinterQuery(std::move(printer_query));
} else {
printer_query->StopWorker();
}
diff --git a/chromium/chrome/browser/printing/printing_message_filter.h b/chromium/chrome/browser/printing/printing_message_filter.h
index 04b76398ebe..9fbea6d0a2d 100644
--- a/chromium/chrome/browser/printing/printing_message_filter.h
+++ b/chromium/chrome/browser/printing/printing_message_filter.h
@@ -61,15 +61,16 @@ class PrintingMessageFilter : public content::BrowserMessageFilter {
// Get the default print setting.
void OnGetDefaultPrintSettings(IPC::Message* reply_msg);
- void OnGetDefaultPrintSettingsReply(scoped_refptr<PrinterQuery> printer_query,
- IPC::Message* reply_msg);
+ void OnGetDefaultPrintSettingsReply(
+ std::unique_ptr<PrinterQuery> printer_query,
+ IPC::Message* reply_msg);
// The renderer host have to show to the user the print dialog and returns
// the selected print settings. The task is handled by the print worker
// thread and the UI thread. The reply occurs on the IO thread.
void OnScriptedPrint(const PrintHostMsg_ScriptedPrint_Params& params,
IPC::Message* reply_msg);
- void OnScriptedPrintReply(scoped_refptr<PrinterQuery> printer_query,
+ void OnScriptedPrintReply(std::unique_ptr<PrinterQuery> printer_query,
IPC::Message* reply_msg);
// Modify the current print settings based on |job_settings|. The task is
@@ -78,7 +79,7 @@ class PrintingMessageFilter : public content::BrowserMessageFilter {
void OnUpdatePrintSettings(int document_cookie,
base::Value job_settings,
IPC::Message* reply_msg);
- void OnUpdatePrintSettingsReply(scoped_refptr<PrinterQuery> printer_query,
+ void OnUpdatePrintSettingsReply(std::unique_ptr<PrinterQuery> printer_query,
IPC::Message* reply_msg);
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
diff --git a/chromium/chrome/browser/printing/pwg_raster_converter.cc b/chromium/chrome/browser/printing/pwg_raster_converter.cc
index c140bf4ed22..5a505349612 100644
--- a/chromium/chrome/browser/printing/pwg_raster_converter.cc
+++ b/chromium/chrome/browser/printing/pwg_raster_converter.cc
@@ -20,7 +20,7 @@
#include "components/cloud_devices/common/printer_description.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "printing/pdf_render_settings.h"
#include "printing/pwg_raster_settings.h"
@@ -80,10 +80,9 @@ void PwgRasterConverterHelper::Convert(
callback_ = std::move(callback);
- content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->BindInterface(printing::mojom::kChromePrintingServiceName,
- &pdf_to_pwg_raster_converter_ptr_);
+ content::GetSystemConnector()->BindInterface(
+ printing::mojom::kChromePrintingServiceName,
+ &pdf_to_pwg_raster_converter_ptr_);
pdf_to_pwg_raster_converter_ptr_.set_connection_error_handler(
base::BindOnce(&PwgRasterConverterHelper::RunCallback, this,
@@ -101,7 +100,7 @@ void PwgRasterConverterHelper::Convert(
memcpy(memory.mapping.memory(), data->front(), data->size());
pdf_to_pwg_raster_converter_ptr_->Convert(
std::move(memory.region), settings_, bitmap_settings_,
- base::Bind(&PwgRasterConverterHelper::RunCallback, this));
+ base::BindOnce(&PwgRasterConverterHelper::RunCallback, this));
}
void PwgRasterConverterHelper::RunCallback(
@@ -280,7 +279,7 @@ PwgRasterSettings PwgRasterConverter::GetBitmapSettings(
const auto& types = raster_capability.value().document_types_supported;
result.use_color =
use_color ||
- !base::ContainsValue(
+ !base::Contains(
types, cloud_devices::printer::PwgDocumentTypeSupported::SGRAY_8);
return result;
diff --git a/chromium/chrome/browser/printing/pwg_raster_converter_browsertest.cc b/chromium/chrome/browser/printing/pwg_raster_converter_browsertest.cc
index b2e3f2bf203..3f20e6a8ff9 100644
--- a/chromium/chrome/browser/printing/pwg_raster_converter_browsertest.cc
+++ b/chromium/chrome/browser/printing/pwg_raster_converter_browsertest.cc
@@ -40,11 +40,11 @@ constexpr char kPdfToPwgRasterLongEdgeTestFile[] =
void ResultCallbackImpl(bool* called,
base::ReadOnlySharedMemoryRegion* pwg_region_out,
- base::Closure quit_closure,
+ base::OnceClosure quit_closure,
base::ReadOnlySharedMemoryRegion pwg_region_in) {
*called = true;
*pwg_region_out = std::move(pwg_region_in);
- quit_closure.Run();
+ std::move(quit_closure).Run();
}
void GetPdfData(const char* file_name,
diff --git a/chromium/chrome/browser/printing/test_print_job.cc b/chromium/chrome/browser/printing/test_print_job.cc
index af1941ddcb0..29bd1a4aa2f 100644
--- a/chromium/chrome/browser/printing/test_print_job.cc
+++ b/chromium/chrome/browser/printing/test_print_job.cc
@@ -16,15 +16,13 @@
namespace printing {
-void TestPrintJob::Initialize(PrinterQuery* query,
+void TestPrintJob::Initialize(std::unique_ptr<PrinterQuery> query,
const base::string16& name,
int page_count) {
// Since we do not actually print in these tests, just let this get destroyed
// when this function exits.
std::unique_ptr<PrintJobWorker> worker = query->DetachWorker();
- set_settings(query->settings());
-
scoped_refptr<PrintedDocument> new_doc =
base::MakeRefCounted<PrintedDocument>(query->settings(), name,
query->cookie());
diff --git a/chromium/chrome/browser/printing/test_print_job.h b/chromium/chrome/browser/printing/test_print_job.h
index d854317c21b..47de14274f7 100644
--- a/chromium/chrome/browser/printing/test_print_job.h
+++ b/chromium/chrome/browser/printing/test_print_job.h
@@ -37,7 +37,7 @@ class TestPrintJob : public PrintJob {
const content::NotificationDetails& details) override {}
// All remaining functions are PrintJob implementation.
- void Initialize(PrinterQuery* query,
+ void Initialize(std::unique_ptr<PrinterQuery> query,
const base::string16& name,
int page_count) override;
diff --git a/chromium/chrome/browser/printing/test_printer_query.cc b/chromium/chrome/browser/printing/test_printer_query.cc
index 6d26be12038..8049255aa3f 100644
--- a/chromium/chrome/browser/printing/test_printer_query.cc
+++ b/chromium/chrome/browser/printing/test_printer_query.cc
@@ -17,12 +17,11 @@
namespace printing {
-scoped_refptr<PrinterQuery> TestPrintQueriesQueue::CreatePrinterQuery(
+std::unique_ptr<PrinterQuery> TestPrintQueriesQueue::CreatePrinterQuery(
int render_process_id,
int render_frame_id) {
- scoped_refptr<TestPrinterQuery> test_query =
- base::MakeRefCounted<TestPrinterQuery>(render_process_id,
- render_frame_id);
+ auto test_query =
+ std::make_unique<TestPrinterQuery>(render_process_id, render_frame_id);
#if defined(OS_WIN)
test_query->SetPrinterType(printer_type_);
#endif
@@ -53,7 +52,6 @@ void TestPrinterQuery::SetSettings(base::Value new_settings,
#if defined(OS_WIN)
DCHECK(printer_type_);
#endif
- set_callback(std::move(callback));
PrintSettings settings;
PrintingContext::Result result =
PrintSettingsFromJobSettings(new_settings, &settings)
@@ -74,7 +72,7 @@ void TestPrinterQuery::SetSettings(base::Value new_settings,
settings.set_printer_type(*printer_type_);
#endif
- GetSettingsDone(settings, result);
+ GetSettingsDone(std::move(callback), settings, result);
}
#if defined(OS_WIN)
diff --git a/chromium/chrome/browser/printing/test_printer_query.h b/chromium/chrome/browser/printing/test_printer_query.h
index 9bc62d1b489..c1569c1a567 100644
--- a/chromium/chrome/browser/printing/test_printer_query.h
+++ b/chromium/chrome/browser/printing/test_printer_query.h
@@ -23,8 +23,9 @@ class TestPrintQueriesQueue : public PrintQueriesQueue {
// Creates a TestPrinterQuery. Sets up the printer query with the printer
// settings indicated by |printable_offset_x_|, |printable_offset_y_|, and
// |printer_type_|.
- scoped_refptr<PrinterQuery> CreatePrinterQuery(int render_process_id,
- int render_frame_id) override;
+ std::unique_ptr<PrinterQuery> CreatePrinterQuery(
+ int render_process_id,
+ int render_frame_id) override;
// Sets the printer's printable area offsets to |offset_x| and |offset_y|,
// which should be in pixels. Used to fill in printer settings that would
@@ -53,6 +54,7 @@ class TestPrinterQuery : public PrinterQuery {
public:
// Can only be called on the IO thread, since this inherits from PrinterQuery.
TestPrinterQuery(int render_process_id, int render_frame_id);
+ ~TestPrinterQuery() override;
// Updates the current settings with |new_settings| dictionary values. Also
// fills in the settings with values from |offsets_| and |printer_type_| that
@@ -73,8 +75,6 @@ class TestPrinterQuery : public PrinterQuery {
void StopWorker() override;
private:
- ~TestPrinterQuery() override;
-
base::Optional<gfx::Point> offsets_;
#if defined(OS_WIN)
base::Optional<PrintSettings::PrinterType> printer_type_;
diff --git a/chromium/chrome/browser/profiling_host/BUILD.gn b/chromium/chrome/browser/profiling_host/BUILD.gn
index 5c73c19a024..9fd1b0b4680 100644
--- a/chromium/chrome/browser/profiling_host/BUILD.gn
+++ b/chromium/chrome/browser/profiling_host/BUILD.gn
@@ -19,7 +19,6 @@ static_library("profiling_host") {
"//chrome/common:non_code_constants",
"//components/heap_profiling",
"//components/services/heap_profiling/public/cpp",
- "//components/signin/core/browser",
"//content/public/browser",
"//content/public/common",
]
diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc
index 9d249be9345..9d28e920676 100644
--- a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc
+++ b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc
@@ -16,7 +16,7 @@
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "ipc/ipc_message_macros.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "ppapi/c/pp_errors.h"
@@ -39,7 +39,6 @@
using content::BrowserPpapiHost;
using content::BrowserThread;
using content::RenderProcessHost;
-using content::ServiceManagerConnection;
namespace {
@@ -60,11 +59,9 @@ scoped_refptr<content_settings::CookieSettings> GetCookieSettings(
void PepperBindConnectorRequest(
service_manager::mojom::ConnectorRequest connector_request) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- DCHECK(ServiceManagerConnection::GetForProcess());
-
- ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->BindConnectorRequest(std::move(connector_request));
+ DCHECK(content::GetSystemConnector());
+ content::GetSystemConnector()->BindConnectorRequest(
+ std::move(connector_request));
}
} // namespace
@@ -74,9 +71,10 @@ PepperFlashBrowserHost::PepperFlashBrowserHost(BrowserPpapiHost* host,
PP_Resource resource)
: ResourceHost(host->GetPpapiHost(), instance, resource),
host_(host),
- delay_timer_(FROM_HERE, base::TimeDelta::FromSeconds(45), this,
- &PepperFlashBrowserHost::OnDelayTimerFired),
- weak_factory_(this) {
+ delay_timer_(FROM_HERE,
+ base::TimeDelta::FromSeconds(45),
+ this,
+ &PepperFlashBrowserHost::OnDelayTimerFired) {
int unused;
host->GetRenderFrameIDsForInstance(instance, &render_process_id_, &unused);
}
@@ -184,9 +182,8 @@ device::mojom::WakeLock* PepperFlashBrowserHost::GetWakeLock() {
device::mojom::WakeLockRequest request = mojo::MakeRequest(&wake_lock_);
- // Service manager connection might be not initialized in some testing
- // contexts.
- if (!ServiceManagerConnection::GetForProcess())
+ // The system Connector might be not initialized in some testing environments.
+ if (!content::GetSystemConnector())
return wake_lock_.get();
service_manager::mojom::ConnectorRequest connector_request;
diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h
index 154120ce515..f2f40b636a4 100644
--- a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h
+++ b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h
@@ -67,7 +67,7 @@ class PepperFlashBrowserHost : public ppapi::host::ResourceHost {
// For fetching the Flash LSO settings.
scoped_refptr<content_settings::CookieSettings> cookie_settings_;
- base::WeakPtrFactory<PepperFlashBrowserHost> weak_factory_;
+ base::WeakPtrFactory<PepperFlashBrowserHost> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(PepperFlashBrowserHost);
};
diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc
index 585784be33f..da447131553 100644
--- a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc
+++ b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc
@@ -32,12 +32,12 @@ const size_t kMaxClipboardWriteSize = 1000000;
ui::ClipboardType ConvertClipboardType(uint32_t type) {
switch (type) {
case PP_FLASH_CLIPBOARD_TYPE_STANDARD:
- return ui::CLIPBOARD_TYPE_COPY_PASTE;
+ return ui::ClipboardType::kCopyPaste;
case PP_FLASH_CLIPBOARD_TYPE_SELECTION:
- return ui::CLIPBOARD_TYPE_SELECTION;
+ return ui::ClipboardType::kSelection;
}
NOTREACHED();
- return ui::CLIPBOARD_TYPE_COPY_PASTE;
+ return ui::ClipboardType::kCopyPaste;
}
// Functions to pack/unpack custom data from a pickle. See the header file for
diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc
index b007195efb9..0a727e8c438 100644
--- a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc
+++ b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc
@@ -115,8 +115,7 @@ class MonitorFinder : public base::RefCountedThreadSafe<MonitorFinder> {
PepperFlashDRMHost::PepperFlashDRMHost(BrowserPpapiHost* host,
PP_Instance instance,
PP_Resource resource)
- : ppapi::host::ResourceHost(host->GetPpapiHost(), instance, resource),
- weak_factory_(this) {
+ : ppapi::host::ResourceHost(host->GetPpapiHost(), instance, resource) {
// Grant permissions to read the flash voucher file.
int render_process_id;
int render_frame_id;
diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.h b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.h
index aa4433cccff..b9d2ce7f7f6 100644
--- a/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.h
+++ b/chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.h
@@ -52,7 +52,7 @@ class PepperFlashDRMHost : public ppapi::host::ResourceHost {
scoped_refptr<DeviceIDFetcher> fetcher_;
scoped_refptr<MonitorFinder> monitor_finder_;
- base::WeakPtrFactory<PepperFlashDRMHost> weak_factory_;
+ base::WeakPtrFactory<PepperFlashDRMHost> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(PepperFlashDRMHost);
};
diff --git a/chromium/chrome/browser/resources/BUILD.gn b/chromium/chrome/browser/resources/BUILD.gn
index 9b4adc929b1..5f26c76da3c 100644
--- a/chromium/chrome/browser/resources/BUILD.gn
+++ b/chromium/chrome/browser/resources/BUILD.gn
@@ -5,16 +5,13 @@
import("//chrome/common/features.gni")
import("//tools/grit/grit_rule.gni")
-if (is_chromeos) {
- import("//chrome/browser/chromeos/kiosk_next_home/kiosk_next.gni")
-}
-
assert(!is_ios, "Chromium/iOS shouldn't use anything in //chrome")
if (closure_compile) {
group("closure_compile") {
deps = [
"engagement:closure_compile",
+ "interventions_internals:closure_compile",
]
if (is_linux || is_win || is_mac) {
deps += [
@@ -26,17 +23,15 @@ if (closure_compile) {
"local_ntp:closure_compile",
"local_state:closure_compile",
"management:closure_compile",
- "media_router:closure_compile",
"ntp4:closure_compile",
"omnibox:closure_compile",
"pdf:closure_compile",
"print_preview:closure_compile",
"quota_internals:closure_compile",
"settings:closure_compile",
- "signin/dice_sync_confirmation:closure_compile",
+ "signin/sync_confirmation:closure_compile",
"user_manager:closure_compile",
- "welcome/dice_welcome:closure_compile",
- "welcome/onboarding_welcome:closure_compile",
+ "welcome:closure_compile",
]
}
if (is_chromeos) {
@@ -111,24 +106,6 @@ if (!is_android) {
defines += [ "enable_hangout_services_extension" ]
}
- if (is_chromeos) {
- if (enable_kiosk_next) {
- defines += [ "_kiosk_next" ]
- }
-
- # The .grd contains references to generated files.
- source_is_generated = true
-
- deps = [
- "//chrome/browser/resources/chromeos/kiosk_next_home:mojom_bin",
- ]
-
- grit_flags = [
- "-E",
- "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
- ]
- }
-
outputs = [
"grit/component_extension_resources.h",
"grit/component_extension_resources_map.cc",
@@ -239,25 +216,11 @@ if (is_chromeos) {
]
output_dir = "$root_gen_dir/chrome"
}
-
- if (enable_kiosk_next && is_chrome_branded) {
- grit("kiosk_next_internal_resources") {
- source = "kiosk_next_internal_resources.grd"
- defines = chrome_grit_defines
- outputs = [
- "grit/kiosk_next_internal_resources.h",
- "grit/kiosk_next_internal_resources_map.cc",
- "grit/kiosk_next_internal_resources_map.h",
- "kiosk_next_internal_resources.pak",
- ]
- output_dir = "$root_gen_dir/chrome"
- }
- }
}
if (!is_android && !is_chromeos) {
grit("onboarding_welcome_resources") {
- source = "welcome/onboarding_welcome/onboarding_welcome_resources.grd"
+ source = "welcome/onboarding_welcome_resources.grd"
defines = chrome_grit_defines
outputs = [
diff --git a/chromium/chrome/browser/resources/about_nacl/about_nacl.html b/chromium/chrome/browser/resources/about_nacl/about_nacl.html
index a67298c446d..c8045497cae 100644
--- a/chromium/chrome/browser/resources/about_nacl/about_nacl.html
+++ b/chromium/chrome/browser/resources/about_nacl/about_nacl.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}">
+<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
diff --git a/chromium/chrome/browser/resources/app_management/BUILD.gn b/chromium/chrome/browser/resources/app_management/BUILD.gn
index ec6235547ff..d52e422fd0e 100644
--- a/chromium/chrome/browser/resources/app_management/BUILD.gn
+++ b/chromium/chrome/browser/resources/app_management/BUILD.gn
@@ -25,12 +25,14 @@ if (!is_android) {
":permission_item",
":permission_toggle",
":permission_view_header",
+ ":pin_to_shelf_item",
":pwa_permission_view",
":reducers",
":router",
":search_view",
":store",
":store_client",
+ ":toggle_row",
":types",
":util",
]
@@ -88,6 +90,7 @@ if (!is_android) {
":metadata_view",
":permission_item",
":permission_view_header",
+ ":pin_to_shelf_item",
":store_client",
]
}
@@ -105,6 +108,7 @@ if (!is_android) {
":fake_page_handler",
":metadata_view",
":permission_view_header",
+ ":pin_to_shelf_item",
":store_client",
]
}
@@ -186,6 +190,14 @@ if (!is_android) {
]
}
+ js_library("pin_to_shelf_item") {
+ deps = [
+ ":browser_proxy",
+ ":toggle_row",
+ ":types",
+ ]
+ }
+
js_library("pwa_permission_view") {
deps = [
":constants",
@@ -193,6 +205,7 @@ if (!is_android) {
":metadata_view",
":permission_item",
":permission_view_header",
+ ":pin_to_shelf_item",
":store_client",
]
}
@@ -240,6 +253,12 @@ if (!is_android) {
]
}
+ js_library("toggle_row") {
+ deps = [
+ ":types",
+ ]
+ }
+
js_library("types") {
deps = [
"//chrome/browser/ui/webui/app_management:mojo_bindings_js_library_for_compile",
diff --git a/chromium/chrome/browser/resources/app_management/actions.js b/chromium/chrome/browser/resources/app_management/actions.js
index b4a69cdb31f..24cdddee569 100644
--- a/chromium/chrome/browser/resources/app_management/actions.js
+++ b/chromium/chrome/browser/resources/app_management/actions.js
@@ -76,6 +76,17 @@ cr.define('app_management.actions', function() {
};
}
+ /**
+ * @param {boolean} isSupported
+ * @return {!cr.ui.Action}
+ */
+ function updateArcSupported(isSupported) {
+ return {
+ name: 'update-arc-supported',
+ value: isSupported,
+ };
+ }
+
return {
addApp: addApp,
@@ -84,5 +95,6 @@ cr.define('app_management.actions', function() {
changePage: changePage,
clearSearch: clearSearch,
setSearchTerm: setSearchTerm,
+ updateArcSupported: updateArcSupported,
};
});
diff --git a/chromium/chrome/browser/resources/app_management/api_listener.js b/chromium/chrome/browser/resources/app_management/api_listener.js
index 608caa14e6c..617e94b83c6 100644
--- a/chromium/chrome/browser/resources/app_management/api_listener.js
+++ b/chromium/chrome/browser/resources/app_management/api_listener.js
@@ -18,6 +18,7 @@ cr.define('app_management.apiListener', function() {
callbackRouter.onAppAdded.addListener(onAppAdded);
callbackRouter.onAppChanged.addListener(onAppChanged);
callbackRouter.onAppRemoved.addListener(onAppRemoved);
+ callbackRouter.onArcSupportChanged.addListener(onArcSupportChanged);
initialized = true;
}
@@ -50,6 +51,13 @@ cr.define('app_management.apiListener', function() {
dispatch(app_management.actions.removeApp(appId));
}
+ /**
+ * @param {boolean} isSupported
+ */
+ function onArcSupportChanged(isSupported) {
+ dispatch(app_management.actions.updateArcSupported(isSupported));
+ }
+
init();
return {};
diff --git a/chromium/chrome/browser/resources/app_management/arc_permission_view.html b/chromium/chrome/browser/resources/app_management/arc_permission_view.html
index 75cc93b0b95..1ffb3a6b0cb 100644
--- a/chromium/chrome/browser/resources/app_management/arc_permission_view.html
+++ b/chromium/chrome/browser/resources/app_management/arc_permission_view.html
@@ -1,59 +1,82 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="browser_proxy.html">
+<link rel="import" href="icons.html">
<link rel="import" href="metadata_view.html">
<link rel="import" href="permission_item.html">
<link rel="import" href="permission_view_header.html">
<link rel="import" href="shared_style.html">
<link rel="import" href="store_client.html">
+<link rel="import" href="pin_to_shelf_item.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<dom-module id="app-management-arc-permission-view">
<template>
- <style include="app-management-shared-css paper-button-style">
+ <style include="app-management-shared-css">
</style>
<app-management-permission-view-header>
</app-management-permission-view-header>
<div class="permission-list card-container">
+ <app-management-pin-to-shelf-item
+ id="pin-to-shelf-setting"
+ class="permission-card-row separated-row header-text"
+ app_="[[app_]]">
+ </app-management-pin-to-shelf-item>
<app-management-permission-item id="notifications-card"
class="permission-card-row separated-row header-text"
- permission-label="$i18n{notifications}" permission-type="NOTIFICATIONS">
+ permission-label="$i18n{notifications}" permission-type="NOTIFICATIONS"
+ hidden$="[[!isArcSupported_]]">
</app-management-permission-item>
- <div id="permissions-card" class="permission-card-row">
+ <div id="permissions-card"
+ class="permission-card-row"
+ hidden$="[[!isArcSupported_]]">
<div class="subpermission-list">
<div id="subpermission-expand-row"
- class="subpermission-row separated-row">
+ class="subpermission-row separated-row"
+ hidden$="[[!isArcSupported_]]">
<div class="header-text">$i18n{permissions}</div>
</div>
<app-management-permission-item class="subpermission-row"
- icon="cr:location-on" permission-label="$i18n{location}"
+ icon="cr:location-on"
+ permission-label="$i18n{location}"
permission-type="LOCATION">
</app-management-permission-item>
<app-management-permission-item class="subpermission-row"
- icon="cr:videocam" permission-label="$i18n{camera}"
+ icon="cr:videocam"
+ permission-label="$i18n{camera}"
permission-type="CAMERA">
</app-management-permission-item>
<app-management-permission-item class="subpermission-row"
- icon="cr:mic" permission-label="$i18n{microphone}"
+ icon="cr:mic"
+ permission-label="$i18n{microphone}"
permission-type="MICROPHONE">
</app-management-permission-item>
- <div class="subpermission-row separated-row"
- on-click="onClickNativeSettingsButton_">
- <div class="header-text">$i18n{morePermissions}</div>
- <div class="permission-row-controls">
- <cr-icon-button class="native-settings-icon icon-external" noink>
- </cr-icon-button>
- </div>
- </div>
+ <app-management-permission-item class="subpermission-row"
+ icon="app-management:contacts"
+ permission-label="$i18n{contacts}"
+ permission-type="CONTACTS">
+ </app-management-permission-item>
+ <app-management-permission-item class="subpermission-row"
+ icon="app-management:storage"
+ permission-label="$i18n{storage}"
+ permission-type="STORAGE">
+ </app-management-permission-item>
+ </div>
+ </div>
+ <div id="more-settings"
+ class="permission-card-row separated-row header-text clickable"
+ on-click="onClickNativeSettingsButton_">
+ <div class="header-text">$i18n{moreSettings}</div>
+ <div class="permission-row-controls">
+ <cr-icon-button class="native-settings-icon icon-external"
+ tabindex="0">
+ </cr-icon-button>
</div>
</div>
</div>
- <app-management-metadata-view></app-management-metadata-view>
</template>
<script src="arc_permission_view.js"></script>
</dom-module>
diff --git a/chromium/chrome/browser/resources/app_management/arc_permission_view.js b/chromium/chrome/browser/resources/app_management/arc_permission_view.js
index b361425183c..0242a758b5c 100644
--- a/chromium/chrome/browser/resources/app_management/arc_permission_view.js
+++ b/chromium/chrome/browser/resources/app_management/arc_permission_view.js
@@ -21,10 +21,18 @@ Polymer({
type: Boolean,
value: false,
},
+
+ /**
+ * @private {boolean}
+ */
+ isArcSupported_: {
+ type: Boolean,
+ }
},
attached: function() {
this.watch('app_', state => app_management.util.getSelectedApp(state));
+ this.watch('isArcSupported_', state => state.arcSupported);
this.updateFromStore();
this.listExpanded_ = false;
diff --git a/chromium/chrome/browser/resources/app_management/browser_proxy.js b/chromium/chrome/browser/resources/app_management/browser_proxy.js
index 84c80edace5..f824557fc9c 100644
--- a/chromium/chrome/browser/resources/app_management/browser_proxy.js
+++ b/chromium/chrome/browser/resources/app_management/browser_proxy.js
@@ -8,15 +8,39 @@ cr.define('app_management', function() {
/** @type {appManagement.mojom.PageCallbackRouter} */
this.callbackRouter = new appManagement.mojom.PageCallbackRouter();
- /** @type {appManagement.mojom.PageHandlerInterface} */
+ /** @type {appManagement.mojom.PageHandlerRemote} */
this.handler = null;
const urlParams = new URLSearchParams(window.location.search);
+ const arcSupported = urlParams.get('arcSupported');
const useFake = urlParams.get('fakeBackend');
if (useFake) {
- this.handler = new app_management.FakePageHandler(
- this.callbackRouter.createProxy());
+ if (arcSupported) {
+ loadTimeData.overrideValues({
+ 'isSupportedArcVersion': arcSupported.toLowerCase() === 'true',
+ });
+ } else {
+ loadTimeData.overrideValues({
+ 'isSupportedArcVersion': true,
+ });
+ }
+
+ this.fakeHandler = new app_management.FakePageHandler(
+ this.callbackRouter.$.bindNewPipeAndPassRemote());
+ this.handler = this.fakeHandler.getRemote();
+
+ const permissionOptions = {};
+ permissionOptions[PwaPermissionType.CONTENT_SETTINGS_TYPE_GEOLOCATION] =
+ {
+ permissionValue: TriState.kAllow,
+ isManaged: true,
+ };
+ permissionOptions[PwaPermissionType
+ .CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA] = {
+ permissionValue: TriState.kBlock,
+ isManaged: true
+ };
const /** @type {!Array<App>}*/ appList = [
app_management.FakePageHandler.createApp(
@@ -48,6 +72,8 @@ cr.define('app_management', function() {
{
title: 'Chrome App',
type: AppType.kExtension,
+ description:
+ 'A Chrome App installed from the Chrome Web Store.',
},
),
app_management.FakePageHandler.createApp(
@@ -62,26 +88,33 @@ cr.define('app_management', function() {
{
title: 'Chrome App, OEM installed',
type: AppType.kExtension,
+ description: 'A Chrome App installed by an OEM.',
installSource: InstallSource.kOem,
},
),
app_management.FakePageHandler.createApp(
'aapocclcgogkmnckokdopfmhonfmgok',
{
- title: 'Web App, policy installed',
+ title: 'Web App, policy applied',
type: AppType.kWeb,
- installSource: InstallSource.kPolicy,
+ isPinned: apps.mojom.OptionalBool.kTrue,
+ isPolicyPinned: apps.mojom.OptionalBool.kTrue,
+ installSource: apps.mojom.InstallSource.kPolicy,
+ permissions:
+ app_management.FakePageHandler.createWebPermissions(
+ permissionOptions),
},
),
];
- this.handler.setApps(appList);
+ this.fakeHandler.setApps(appList);
} else {
- this.handler = new appManagement.mojom.PageHandlerProxy();
- const factory = appManagement.mojom.PageHandlerFactory.getProxy();
+ this.handler = new appManagement.mojom.PageHandlerRemote();
+ const factory = appManagement.mojom.PageHandlerFactory.getRemote();
factory.createPageHandler(
- this.callbackRouter.createProxy(), this.handler.$.createRequest());
+ this.callbackRouter.$.bindNewPipeAndPassRemote(),
+ this.handler.$.bindNewPipeAndPassReceiver());
}
}
}
diff --git a/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.html b/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.html
index 53ae27cd2d5..64b890ff985 100644
--- a/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.html
+++ b/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.html
@@ -3,13 +3,12 @@
<link rel="import" href="shared_style.html">
<link rel="import" href="store_client.html">
<link rel="import" href="util.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="pin_to_shelf_item.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<dom-module id="app-management-chrome-app-permission-view">
<template>
- <style include="app-management-shared-css paper-button-style">
+ <style include="app-management-shared-css">
ul {
list-style: disc inside;
margin: 0;
@@ -24,6 +23,11 @@
#no-permissions {
padding-inline-start: 24px;
}
+
+ #pin-to-shelf-setting {
+ border-top: var(--card-separator);
+ }
+
</style>
<app-management-permission-view-header>
</app-management-permission-view-header>
@@ -31,30 +35,37 @@
<div id="app-description" class="permission-card-row secondary-text">
[[app_.description]]
</div>
- <div id="permissions-card" class="permission-card-row">
- <div class="subpermission-list">
- <div class="subpermission-row separated-row">
- <div class="header-text">$i18n{thisAppCan}</div>
- </div>
- <template is="dom-if" if="[[!hasPermissions_(messages_)]]">
- <div id="no-permissions">
- $i18n{appNoPermission}
+ <div class="permission-list">
+ <app-management-pin-to-shelf-item
+ id="pin-to-shelf-setting"
+ class="permission-card-row separated-row header-text"
+ app_="[[app_]]">
+ </app-management-pin-to-shelf-item>
+
+ <div id="permissions-card" class="permission-card-row">
+ <div class="subpermission-list">
+ <div class="subpermission-row separated-row">
+ <div class="header-text">$i18n{thisAppCan}</div>
</div>
- </template>
- <ul>
- <template is="dom-repeat"
- items="[[getPermissionMessages_(messages_)]]" as="message">
- <li>[[message]]</li>
- <ul>
- <template is="dom-repeat"
- items="[[getPermissionSubmessagesByMessage_(index, messages_)]]"
- as="submessage">
- <li>[[submessage]]</li>
- </template>
- </ul>
+ <template is="dom-if" if="[[!hasPermissions_(messages_)]]">
+ <div id="no-permissions">
+ $i18n{appNoPermission}
+ </div>
</template>
- </ul>
- <!-- TODO(crbug.com/906508): For apps which are hosted apps but not
+ <ul>
+ <template is="dom-repeat"
+ items="[[getPermissionMessages_(messages_)]]" as="message">
+ <li>[[message]]</li>
+ <ul>
+ <template is="dom-repeat"
+ items="[[getPermissionSubmessagesByMessage_(index, messages_)]]"
+ as="submessage">
+ <li>[[submessage]]</li>
+ </template>
+ </ul>
+ </template>
+ </ul>
+ <!-- TODO(crbug.com/906508): For apps which are hosted apps but not
bookmark apps, this button will actually open the site settings page
corresponding to the app, since hosted apps are not listed in
chrome://extensions.
@@ -64,16 +75,18 @@
app. -->
<!-- TODO:(crbug.com/958269) Change behaviour of "more settings"
based on the app. -->
- <div id="more-settings" class="subpermission-row separated-row"
- on-click="onClickExtensionsSettingsButton_">
- <div class="header-text">More settings</div>
- <cr-icon-button class="native-settings-icon icon-external" noink>
+ <div id="more-settings"
+ class="subpermission-row separated-row clickable"
+ on-click="onClickExtensionsSettingsButton_"
+ hidden$="[[app_.hideMoreSettings]]">
+ <div class="header-text">$i18n{moreSettings}</div>
+ <cr-icon-button class="native-settings-icon icon-external"
+ tabindex="0">
</cr-icon-button>
</div>
</div>
</div>
</div>
- <app-management-metadata-view></app-management-metadata-view>
</template>
<script src="chrome_app_permission_view.js"></script>
</dom-module>
diff --git a/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.js b/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.js
index 594ba00e5f6..f697f55754e 100644
--- a/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.js
+++ b/chromium/chrome/browser/resources/app_management/chrome_app_permission_view.js
@@ -75,5 +75,5 @@ Polymer({
*/
hasPermissions_: function(messages) {
return messages.length > 0;
- }
+ },
});
diff --git a/chromium/chrome/browser/resources/app_management/expandable_app_list.html b/chromium/chrome/browser/resources/app_management/expandable_app_list.html
index 6fe1a7965fd..88558d0c8d1 100644
--- a/chromium/chrome/browser/resources/app_management/expandable_app_list.html
+++ b/chromium/chrome/browser/resources/app_management/expandable_app_list.html
@@ -7,10 +7,11 @@
<link rel="import" href="permission_toggle.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<dom-module id="app-management-expandable-app-list">
<template>
- <style include="app-management-shared-css">
+ <style include="app-management-shared-css cr-shared-style">
#app-list-header {
align-items: center;
display: flex;
@@ -18,14 +19,9 @@
}
#app-list-title {
- font-size: var(--cr-title-text_-_font-size);
margin-inline-start: 12px;
}
- #back-button {
- margin-inline-start: 0;
- }
-
#collapse {
display: block;
min-height: var(--collapsed-height);
@@ -34,10 +30,9 @@
</style>
<div class="card-container">
<div id="app-list-header">
- <cr-icon-button class="icon-arrow-back" id="back-button"
- on-click="onClickBack_" aria-label="$i18n{back}">
- </cr-icon-button>
- <div id="app-list-title" class="header-text">[[listTitle]]</div>
+ <div id="app-list-title" class="cr-title-text header-text">
+ [[listTitle]]
+ </div>
</div>
<iron-collapse id="collapse">
<slot></slot>
diff --git a/chromium/chrome/browser/resources/app_management/expandable_app_list.js b/chromium/chrome/browser/resources/app_management/expandable_app_list.js
index 62bb0ccd98e..c7a6f4b93ac 100644
--- a/chromium/chrome/browser/resources/app_management/expandable_app_list.js
+++ b/chromium/chrome/browser/resources/app_management/expandable_app_list.js
@@ -133,11 +133,4 @@ Polymer({
loadTimeData.getString('lessApps') :
loadTimeData.getStringF('moreApps', numApps - this.collapsedSize);
},
-
- onClickBack_: function() {
- this.dispatchEvent(new CustomEvent('click-back-button', {
- bubbles: true,
- composed: true,
- }));
- }
});
diff --git a/chromium/chrome/browser/resources/app_management/fake_page_handler.js b/chromium/chrome/browser/resources/app_management/fake_page_handler.js
index 9a06d5f36bf..6c8b2492ded 100644
--- a/chromium/chrome/browser/resources/app_management/fake_page_handler.js
+++ b/chromium/chrome/browser/resources/app_management/fake_page_handler.js
@@ -8,9 +8,10 @@ cr.define('app_management', function() {
*/
class FakePageHandler {
/**
+ * @param {Object=} options
* @return {!Object<number, Permission>}
*/
- static createWebPermissions() {
+ static createWebPermissions(options) {
const permissionIds = [
PwaPermissionType.CONTENT_SETTINGS_TYPE_GEOLOCATION,
PwaPermissionType.CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
@@ -21,8 +22,17 @@ cr.define('app_management', function() {
const permissions = {};
for (const permissionId of permissionIds) {
+ let permissionValue = TriState.kAllow;
+ let isManaged = false;
+
+ if (options && options[permissionId]) {
+ const opts = options[permissionId];
+ permissionValue = opts.permissionValue || permissionValue;
+ isManaged = opts.isManaged || isManaged;
+ }
permissions[permissionId] = app_management.util.createPermission(
- permissionId, PermissionValueType.kTriState, TriState.kAllow);
+ permissionId, PermissionValueType.kTriState, permissionValue,
+ isManaged);
}
return permissions;
@@ -38,13 +48,16 @@ cr.define('app_management', function() {
ArcPermissionType.LOCATION,
ArcPermissionType.MICROPHONE,
ArcPermissionType.NOTIFICATIONS,
+ ArcPermissionType.CONTACTS,
+ ArcPermissionType.STORAGE,
];
const permissions = {};
for (const permissionId of permissionIds) {
permissions[permissionId] = app_management.util.createPermission(
- permissionId, PermissionValueType.kBool, Bool.kTrue);
+ permissionId, PermissionValueType.kBool, Bool.kTrue,
+ false /*is_managed*/);
}
return permissions;
@@ -79,8 +92,11 @@ cr.define('app_management', function() {
version: '5.1',
size: '9.0MB',
isPinned: apps.mojom.OptionalBool.kFalse,
+ isPolicyPinned: apps.mojom.OptionalBool.kFalse,
installSource: apps.mojom.InstallSource.kUser,
permissions: {},
+ hideMoreSettings: false,
+ hidePinToShelf: false,
};
if (optConfig) {
@@ -96,25 +112,31 @@ cr.define('app_management', function() {
}
/**
- * @param {appManagement.mojom.PageProxy} page
+ * @param {appManagement.mojom.PageRemote} page
*/
constructor(page) {
- /** @type {appManagement.mojom.PageProxy} */
+ this.receiver_ = new appManagement.mojom.PageHandlerReceiver(this);
+ /** @type {appManagement.mojom.PageRemote} */
this.page = page;
/** @type {!Array<App>} */
this.apps_ = [];
- this.$ = {
- flushForTesting: async () => {
- await this.page.$.flushForTesting();
- }
- };
-
/** @type {number} */
this.guid = 0;
}
+ /**
+ * @returns {!appManagement.mojom.PageHandlerRemote}
+ */
+ getRemote() {
+ return this.receiver_.$.bindNewPipeAndPassRemote();
+ }
+
+ async flushPipesForTesting() {
+ await this.page.$.flushForTesting();
+ }
+
async getApps() {
return {apps: this.apps_};
}
@@ -184,7 +206,7 @@ cr.define('app_management', function() {
optId = optId || String(this.guid++);
const app = FakePageHandler.createApp(optId, optConfig);
this.page.onAppAdded(app);
- await this.$.flushForTesting();
+ await this.flushPipesForTesting();
return app;
}
@@ -197,7 +219,7 @@ cr.define('app_management', function() {
*/
async changeApp(id, changes) {
this.page.onAppChanged(FakePageHandler.createApp(id, changes));
- await this.$.flushForTesting();
+ await this.flushPipesForTesting();
}
}
diff --git a/chromium/chrome/browser/resources/app_management/icons.html b/chromium/chrome/browser/resources/app_management/icons.html
new file mode 100644
index 00000000000..ccb16326e6b
--- /dev/null
+++ b/chromium/chrome/browser/resources/app_management/icons.html
@@ -0,0 +1,17 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/iron-iconset-svg/iron-iconset-svg.html">
+
+<iron-iconset-svg name="app-management" size="24">
+ <svg>
+ <!--
+ These icons are copied from material.io and kept in sorted order.
+ See http://goo.gl/Y1OdAq for instructions on adding additional icons.
+ -->
+ <defs>
+ <!-- From https://material.io/tools/icons/?icon=account_box&style=baseline -->
+ <g id="contacts"><path d="M19 3H5c-1.11 0-2 .89-2 2v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V5a2 2 0 0 0-2-2zm-7 3c1.65 0 3 1.35 3 3 0 1.66-1.35 3-3 3s-3-1.34-3-3c0-1.65 1.35-3 3-3zm6 12H6v-1c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1z"></path><path fill="none" d="M0 0h24v24H0z"></path></g>
+ <!-- From https://material.io/tools/icons/?icon=storage&style=baseline -->
+ <g id="storage"><path d="M2 20h20v-4H2v4zm2-3h2v2H4v-2zM2 4v4h20V4H2zm4 3H4V5h2v2zm-4 7h20v-4H2v4zm2-3h2v2H4v-2z"></path></g>
+ </defs>
+ </svg>
+</iron-iconset-svg>
diff --git a/chromium/chrome/browser/resources/app_management/main_view.js b/chromium/chrome/browser/resources/app_management/main_view.js
index 49b1fc7e249..de2073cb289 100644
--- a/chromium/chrome/browser/resources/app_management/main_view.js
+++ b/chromium/chrome/browser/resources/app_management/main_view.js
@@ -37,10 +37,6 @@ Polymer({
},
},
- listeners: {
- 'click-back-button': 'onClickBackButton',
- },
-
attached: function() {
this.watch('apps_', state => state.apps);
this.watch('notificationAppIds_', state => state.notifications.allowedIds);
@@ -59,11 +55,6 @@ Polymer({
},
/** @private */
- onClickBackButton: function() {
- window.location.href = `chrome://settings`;
- },
-
- /** @private */
onClickNotificationSublabel_: function() {
this.dispatch(app_management.actions.changePage(PageType.NOTIFICATIONS));
},
diff --git a/chromium/chrome/browser/resources/app_management/metadata_view.html b/chromium/chrome/browser/resources/app_management/metadata_view.html
index aad0dd4f41e..43948aeb5f3 100644
--- a/chromium/chrome/browser/resources/app_management/metadata_view.html
+++ b/chromium/chrome/browser/resources/app_management/metadata_view.html
@@ -15,6 +15,7 @@
}
#shelf-switch {
+ align-items: center;
display: flex;
justify-content: space-between;
}
@@ -36,13 +37,27 @@
display: flex;
justify-content: space-around;
}
+
+ #policy-indicator {
+ fill: var(--google-grey-refresh-700);
+ margin-inline-end: 12px;
+ }
</style>
<template is="dom-if" if="[[pinToShelfToggleVisible_(app_)]]">
<div id="shelf-switch-row">
<span id="shelf-switch" class="header-text">
+ <template is="dom-if" if="[[isPolicyPinned_(app_)]]">
+ <iron-icon id="policy-indicator" icon="cr:domain" tabindex="0"
+ aria-describedby="tooltip">
+ </iron-icon>
+ <paper-tooltip id="tooltip" for="policy-indicator"
+ position="top" fit-to-visible-bounds>
+ $i18n{pinControlledByPolicy}
+ </paper-tooltip>
+ </template>
$i18n{pinToShelf}
<cr-toggle id="pin-to-shelf-toggle" checked="[[isPinned_(app_)]]"
- on-change="togglePinned_">
+ on-change="togglePinned_" disabled$="[[isPolicyPinned_(app_)]]">
</cr-toggle>
</span>
</div>
@@ -51,7 +66,6 @@
<div id="metadata-overview" class="secondary-text">
<span>[[versionString_(app_)]]</span>
<span>[[sizeString_(app_)]]</span>
- <!--TODO(ceciliani): Placeholder for legal declaration-->
</div>
</template>
<script src="metadata_view.js"></script>
diff --git a/chromium/chrome/browser/resources/app_management/metadata_view.js b/chromium/chrome/browser/resources/app_management/metadata_view.js
index 8e460439d6d..d063cdc2196 100644
--- a/chromium/chrome/browser/resources/app_management/metadata_view.js
+++ b/chromium/chrome/browser/resources/app_management/metadata_view.js
@@ -41,6 +41,10 @@ Polymer({
return app.isPinned === OptionalBool.kTrue;
},
+ isPolicyPinned_: function(app) {
+ return app.isPolicyPinned === OptionalBool.kTrue;
+ },
+
/** @private */
togglePinned_: function() {
let newPinnedValue;
diff --git a/chromium/chrome/browser/resources/app_management/notifications_view.html b/chromium/chrome/browser/resources/app_management/notifications_view.html
index 20b54a336b2..c66bcb2ce6c 100644
--- a/chromium/chrome/browser/resources/app_management/notifications_view.html
+++ b/chromium/chrome/browser/resources/app_management/notifications_view.html
@@ -20,7 +20,8 @@
align-items: center;
display: flex;
margin: 24px auto;
- width: var(--card-width)
+ max-width: var(--card-max-width);
+ min-width: var(--card-min-width);
}
#notification-title {
diff --git a/chromium/chrome/browser/resources/app_management/permission_item.js b/chromium/chrome/browser/resources/app_management/permission_item.js
index 20592d65ef8..cf610ef9bcb 100644
--- a/chromium/chrome/browser/resources/app_management/permission_item.js
+++ b/chromium/chrome/browser/resources/app_management/permission_item.js
@@ -71,13 +71,14 @@ Polymer({
},
/**
+ * @param {MouseEvent} e
* @private
*/
onClick_: function(e) {
e.preventDefault();
- const toggle = /** @type {AppManagementPermissionToggleElement} */
- assert(this.$$('#permission-toggle'));
+ const toggle = /** @type {AppManagementPermissionToggleElement} */ (
+ assert(this.$$('#permission-toggle')));
toggle.togglePermission_();
},
});
diff --git a/chromium/chrome/browser/resources/app_management/permission_toggle.html b/chromium/chrome/browser/resources/app_management/permission_toggle.html
index c7a30177af9..7086ec640ad 100644
--- a/chromium/chrome/browser/resources/app_management/permission_toggle.html
+++ b/chromium/chrome/browser/resources/app_management/permission_toggle.html
@@ -1,11 +1,36 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/policy/cr_tooltip_icon.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
+<!-- TODO(jshikaram): use toggle-row here. -->
+
<dom-module id="app-management-permission-toggle">
<template>
+ <style>
+ :host {
+ align-items: center;
+ display: flex;
+ }
+
+ #policy-indicator {
+ fill: var(--google-grey-refresh-700);
+ padding-inline-end: 12px;
+ }
+ </style>
+ <template is="dom-if"
+ if="[[isPermissionManaged_(app, permissionType)]]">
+ <iron-icon id="policy-indicator" icon="cr:domain" tabindex="0"
+ aria-describedby="tooltip">
+ </iron-icon>
+ <paper-tooltip id="tooltip" for="policy-indicator"
+ position="top" fit-to-visible-bounds>
+ $i18n{controlledByPolicy}
+ </paper-tooltip>
+ </template>
<cr-toggle checked="[[getPermissionValueBool_(app, permissionType)]]"
- on-change="togglePermission_">
+ on-change="togglePermission_"
+ disabled$="[[isPermissionManaged_(app, permissionType)]]">
</cr-toggle>
</template>
<script src="permission_toggle.js"></script>
diff --git a/chromium/chrome/browser/resources/app_management/permission_toggle.js b/chromium/chrome/browser/resources/app_management/permission_toggle.js
index a8908cb2bbb..7856395ea6f 100644
--- a/chromium/chrome/browser/resources/app_management/permission_toggle.js
+++ b/chromium/chrome/browser/resources/app_management/permission_toggle.js
@@ -34,6 +34,22 @@ Polymer({
return app_management.util.getPermissionValueBool(app, permissionType);
},
+ /**
+ * @param {App} app
+ * @param {string} permissionType
+ * @return {boolean}
+ */
+ isPermissionManaged_: function(app, permissionType) {
+ if (app === undefined || permissionType === undefined) {
+ return false;
+ }
+
+ assert(app);
+
+ const permission = app_management.util.getPermission(app, permissionType);
+ assert(permission);
+ return permission.isManaged;
+ },
togglePermission_: function() {
assert(this.app);
@@ -67,8 +83,10 @@ Polymer({
*/
getNewPermissionBoolean_: function(app, permissionType) {
let newPermissionValue;
+ const currentPermission =
+ app_management.util.getPermission(app, permissionType);
- switch (app_management.util.getPermission(app, permissionType).value) {
+ switch (currentPermission.value) {
case Bool.kFalse:
newPermissionValue = Bool.kTrue;
break;
@@ -82,7 +100,8 @@ Polymer({
assert(newPermissionValue !== undefined);
return app_management.util.createPermission(
app_management.util.permissionTypeHandle(app, permissionType),
- PermissionValueType.kBool, newPermissionValue);
+ PermissionValueType.kBool, newPermissionValue,
+ currentPermission.isManaged);
},
/**
@@ -93,8 +112,10 @@ Polymer({
*/
getNewPermissionTriState_: function(app, permissionType) {
let newPermissionValue;
+ const currentPermission =
+ app_management.util.getPermission(app, permissionType);
- switch (app_management.util.getPermission(app, permissionType).value) {
+ switch (currentPermission.value) {
case TriState.kBlock:
newPermissionValue = TriState.kAllow;
break;
@@ -115,6 +136,7 @@ Polymer({
assert(newPermissionValue !== undefined);
return app_management.util.createPermission(
app_management.util.permissionTypeHandle(app, permissionType),
- PermissionValueType.kTriState, newPermissionValue);
+ PermissionValueType.kTriState, newPermissionValue,
+ currentPermission.isManaged);
},
});
diff --git a/chromium/chrome/browser/resources/app_management/permission_view_header.html b/chromium/chrome/browser/resources/app_management/permission_view_header.html
index f2e1358ae14..d0c6f0c9e55 100644
--- a/chromium/chrome/browser/resources/app_management/permission_view_header.html
+++ b/chromium/chrome/browser/resources/app_management/permission_view_header.html
@@ -1,19 +1,19 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="shared_style.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<dom-module id="app-management-permission-view-header">
<template>
- <style include="app-management-shared-css paper-button-style">
+ <style include="app-management-shared-css">
:host {
align-items: center;
display: flex;
margin: 24px auto;
- width: var(--card-width);
+ max-width: var(--card-max-width);
+ min-width: var(--card-min-width);
}
#permission-view-header-icon {
@@ -39,8 +39,8 @@
}
#policy-indicator {
- fill: var(--google-grey-refresh-500);
- padding-inline-end: 10px;
+ fill: var(--google-grey-refresh-700);
+ margin-inline-end: 12px;
}
</style>
<cr-icon-button class="icon-arrow-back" id="backButton"
@@ -52,10 +52,10 @@
<template is="dom-if" if="[[isPolicyApp_(app_)]]">
<iron-icon id="policy-indicator" icon="cr:domain"></iron-icon>
</template>
- <paper-button id="uninstall-button" on-click="onClickUninstallButton_"
- disabled$="[[getUninstallButtonDisableState_(app_)]]">
+ <cr-button id="uninstall-button" on-click="onClickUninstallButton_"
+ disabled$="[[getUninstallButtonDisableState_(app_)]]">
$i18n{uninstall}
- </paper-button>
+ </cr-button>
</div>
</template>
<script src="permission_view_header.js"></script>
diff --git a/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.html b/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.html
new file mode 100644
index 00000000000..fe4821f2988
--- /dev/null
+++ b/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.html
@@ -0,0 +1,19 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="toggle_row.html">
+
+<dom-module id="app-management-pin-to-shelf-item">
+ <template>
+ <style>
+ :host(:not([disabled])) {
+ cursor: pointer;
+ }
+ </style>
+ <app-management-toggle-row
+ label_="$i18n{pinToShelf}"
+ managed_$="[[isManaged_(app_)]]"
+ policy-label_="$i18n{pinControlledByPolicy}"
+ value_$="[[getValue_(app_)]]">
+ </app-management-toggle-row>
+ </template>
+ <script src="pin_to_shelf_item.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.js b/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.js
new file mode 100644
index 00000000000..ee5d2ac0df4
--- /dev/null
+++ b/chromium/chrome/browser/resources/app_management/pin_to_shelf_item.js
@@ -0,0 +1,95 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+Polymer({
+ is: 'app-management-pin-to-shelf-item',
+
+ properties: {
+ /**
+ * @type {App}
+ * @private
+ */
+ app_: Object,
+
+ /**
+ * @type {boolean}
+ * @private
+ */
+ hidden: {
+ type: Boolean,
+ computed: 'isAvailable_(app_)',
+ reflectToAttribute: true,
+ },
+
+ /**
+ * @type {boolean}
+ * @private
+ */
+ disabled: {
+ type: Boolean,
+ computed: 'isManaged_(app_)',
+ reflectToAttribute: true,
+ },
+ },
+
+ ready: function() {
+ // capture the onClick event before it reaches the toggle.
+ this.addEventListener('click', this.onClick_, true);
+ },
+
+ /**
+ * @param {App} app
+ * @returns {boolean} true if the app is pinned
+ * @private
+ */
+ getValue_: function(app) {
+ if (app === undefined) {
+ return false;
+ }
+ assert(app);
+ return app.isPinned === OptionalBool.kTrue;
+ },
+
+ /**
+ * @param {App} app
+ * @returns {boolean} true if pinning is available.
+ */
+ isAvailable_: function(app) {
+ if (app === undefined) {
+ return false;
+ }
+ assert(app);
+ return app.hidePinToShelf;
+ },
+
+ /**
+ * @param {App} app
+ * @returns {boolean} true if the pinning is managed by policy.
+ * @private
+ */
+ isManaged_: function(app) {
+ if (app === undefined) {
+ return false;
+ }
+ assert(app);
+ return app.isPolicyPinned === OptionalBool.kTrue;
+ },
+
+ /**
+ * @param {Event} event
+ * @private
+ */
+ onClick_: function(event) {
+ event.stopPropagation();
+
+ // Disabled
+ if (this.isManaged_(this.app_)) {
+ return;
+ }
+
+ app_management.BrowserProxy.getInstance().handler.setPinned(
+ this.app_.id,
+ assert(app_management.util.toggleOptionalBool(this.app_.isPinned)),
+ );
+ },
+});
diff --git a/chromium/chrome/browser/resources/app_management/pwa_permission_view.html b/chromium/chrome/browser/resources/app_management/pwa_permission_view.html
index 68286f74c26..17952e85e3f 100644
--- a/chromium/chrome/browser/resources/app_management/pwa_permission_view.html
+++ b/chromium/chrome/browser/resources/app_management/pwa_permission_view.html
@@ -6,20 +6,24 @@
<link rel="import" href="permission_view_header.html">
<link rel="import" href="shared_style.html">
<link rel="import" href="store_client.html">
+<link rel="import" href="pin_to_shelf_item.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<dom-module id="app-management-pwa-permission-view">
<template>
- <style include="app-management-shared-css paper-button-style">
+ <style include="app-management-shared-css">
</style>
<app-management-permission-view-header>
</app-management-permission-view-header>
<div class="permission-list card-container">
+ <app-management-pin-to-shelf-item
+ id="pin-to-shelf-setting"
+ class="permission-card-row separated-row header-text"
+ app_="[[app_]]">
+ </app-management-pin-to-shelf-item>
<app-management-permission-item id="notifications-card"
class="permission-card-row separated-row header-text"
permission-label="$i18n{notifications}"
@@ -44,18 +48,18 @@
permission-label="$i18n{microphone}"
permission-type="CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC">
</app-management-permission-item>
- <div class="subpermission-row separated-row"
+ <div class="subpermission-row separated-row clickable"
on-click="onClickSiteSettingsButton_">
- <div class="header-text">$i18n{morePermissions}</div>
+ <div class="header-text">$i18n{moreSettings}</div>
<div class="permission-row-controls">
- <cr-icon-button class="native-settings-icon icon-external" noink>
+ <cr-icon-button class="native-settings-icon icon-external"
+ tabindex="0">
</cr-icon-button>
</div>
</div>
</div>
</div>
</div>
- <app-management-metadata-view></app-management-metadata-view>
</template>
<script src="pwa_permission_view.js"></script>
</dom-module>
diff --git a/chromium/chrome/browser/resources/app_management/reducers.js b/chromium/chrome/browser/resources/app_management/reducers.js
index de6c552c626..3b9de9038d9 100644
--- a/chromium/chrome/browser/resources/app_management/reducers.js
+++ b/chromium/chrome/browser/resources/app_management/reducers.js
@@ -268,6 +268,22 @@ cr.define('app_management', function() {
}
};
+ const ArcSupported = {};
+
+ /**
+ * @param {boolean} arcSupported
+ * @param {Object} action
+ * @return {boolean}
+ */
+ ArcSupported.updateArcSupported = function(arcSupported, action) {
+ switch (action.name) {
+ case 'update-arc-supported':
+ return action.value;
+ default:
+ return arcSupported;
+ }
+ };
+
/**
* Root reducer for the App Management page. This is called by the store in
* response to an action, and the return value is used to update the UI.
@@ -280,6 +296,7 @@ cr.define('app_management', function() {
apps: AppState.updateApps(state.apps, action),
currentPage: CurrentPageState.updateCurrentPage(
state.apps, state.currentPage, action),
+ arcSupported: ArcSupported.updateArcSupported(state.arcSupported, action),
search: SearchState.updateSearch(state.apps, state.search, action),
notifications:
NotificationsState.updateNotifications(state.notifications, action),
@@ -290,6 +307,7 @@ cr.define('app_management', function() {
reduceAction: reduceAction,
AppState: AppState,
CurrentPageState: CurrentPageState,
+ ArcSupported: ArcSupported,
NotificationsState: NotificationsState,
SearchState: SearchState,
};
diff --git a/chromium/chrome/browser/resources/app_management/shared_style.html b/chromium/chrome/browser/resources/app_management/shared_style.html
index 9cb1aaae255..57215df600e 100644
--- a/chromium/chrome/browser/resources/app_management/shared_style.html
+++ b/chromium/chrome/browser/resources/app_management/shared_style.html
@@ -13,8 +13,8 @@
display: flex;
flex-direction: column;
margin: 24px auto;
- max-width: var(--card-width);
- min-width: 550px;
+ max-width: var(--card-max-width);
+ min-width: var(--card-min-width);
}
.separated-row {
@@ -23,12 +23,20 @@
justify-content: space-between;
}
+ .card-row {
+ border-top: var(--card-separator);
+ padding: 0 24px;
+ }
+
.permission-card-row {
border-top: var(--card-separator);
- cursor: pointer;
padding: 0 24px;
}
+ .clickable {
+ cursor: pointer;
+ }
+
.permission-card-row:first-child {
border-style: none;
}
@@ -52,18 +60,6 @@
flex: 0 0 var(--permission-list-item-height);
}
- .extra-permission-header-button {
- margin-inline-end: 16px;
- }
-
- .native-settings-button {
- --paper-button-ink-color: none;
- --hover-bg-color: var(--google-grey-refresh-100);
- border: none;
- display: flex;
- font-size: 12px;
- }
-
.native-settings-icon {
display: flex;
margin-inline-start: 0;
@@ -91,6 +87,11 @@
width: 36px;
}
+ .horizontal-align {
+ align-items: center;
+ display: flex;
+ }
+
.expander-list-row {
align-items: center;
border-top: var(--card-separator);
diff --git a/chromium/chrome/browser/resources/app_management/shared_vars.html b/chromium/chrome/browser/resources/app_management/shared_vars.html
index 0c46e3a7299..d42cace22d1 100644
--- a/chromium/chrome/browser/resources/app_management/shared_vars.html
+++ b/chromium/chrome/browser/resources/app_management/shared_vars.html
@@ -8,8 +8,9 @@
html {
--app-management-font-size: 13px;
--app-management-line-height: 1.54; /* 20px */
+ --card-max-width: 676px;
+ --card-min-width: 550px;
--card-separator: 1px solid rgba(0, 0, 0, 0.12);
- --card-width: 676px;
--control-separator-color: rgb(218, 220, 224);
--expanded-permission-row-height: 48px;
--header-font-weight: 500;
@@ -18,6 +19,7 @@
--permission-icon-padding: 12px;
--permission-list-item-height: 64px;
--primary-text-color: rgba(0, 0, 0, 0.87);
+ --row-item-icon-padding: 12px;
--secondary-font-weight: 400;
--secondary-text-color: rgba(0, 0, 0, 0.54);
}
diff --git a/chromium/chrome/browser/resources/app_management/toggle_row.html b/chromium/chrome/browser/resources/app_management/toggle_row.html
new file mode 100644
index 00000000000..8e2ccf129b8
--- /dev/null
+++ b/chromium/chrome/browser/resources/app_management/toggle_row.html
@@ -0,0 +1,55 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="browser_proxy.html">
+<link rel="import" href="shared_style.html">
+<link rel="import" href="store_client.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
+
+<dom-module id="app-management-toggle-row">
+ <template>
+ <style include="app-management-shared-css">
+ :host {
+ align-items: center;
+ display: flex;
+ flex: 1;
+ justify-content: space-between;
+ }
+
+ #icon {
+ padding-inline-end: var(--row-item-icon-padding);
+ }
+
+ #policy-indicator {
+ fill: var(--google-grey-refresh-700);
+ padding-inline-end: 12px;
+ }
+ </style>
+
+ <div id="left-content" class="horizontal-align">
+ <template is="dom-if" if="[[icon_]]">
+ <iron-icon id="icon" icon="[[icon_]]"></iron-icon>
+ </template>
+ <div id="label">[[label_]]</div>
+ </div>
+ <div id="right-content" class="horizontal-align">
+ <iron-icon id="policy-indicator"
+ icon="cr:domain"
+ tabindex="0"
+ aria-describedby="tooltip"
+ hidden$="[[!managed_]]">
+ </iron-icon>
+ <paper-tooltip id="tooltip"
+ for="policy-indicator"
+ position="top"
+ fit-to-visible-bounds>
+ [[policyLabel_]]
+ </paper-tooltip>
+ <cr-toggle id="toggle"
+ checked="[[value_]]"
+ disabled$="[[managed_]]">
+ </cr-toggle>
+ </div>
+ </template>
+ <script src="toggle_row.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/app_management/toggle_row.js b/chromium/chrome/browser/resources/app_management/toggle_row.js
new file mode 100644
index 00000000000..16aff0bb109
--- /dev/null
+++ b/chromium/chrome/browser/resources/app_management/toggle_row.js
@@ -0,0 +1,34 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+Polymer({
+ is: 'app-management-toggle-row',
+
+ properties: {
+ /**
+ * @type {string}
+ * @private
+ */
+ icon_: String,
+ /**
+ * @type {string}
+ * @private
+ */
+ label_: String,
+ /**
+ * @type {boolean}
+ * @private
+ */
+ managed_: {type: Boolean, value: false, reflectToAttribute: true},
+ /**
+ * @type {string}
+ * @private
+ */
+ policyLabel_: String,
+ /**
+ * @type {boolean}
+ * @private
+ */
+ value_: {type: Boolean, value: false, reflectToAttribute: true},
+ },
+});
diff --git a/chromium/chrome/browser/resources/app_management/types.js b/chromium/chrome/browser/resources/app_management/types.js
index 882b47cb58c..725836f9596 100644
--- a/chromium/chrome/browser/resources/app_management/types.js
+++ b/chromium/chrome/browser/resources/app_management/types.js
@@ -55,6 +55,7 @@ let NotificationsState;
* @typedef {{
* apps: !AppMap,
* currentPage: !Page,
+ * arcSupported: boolean,
* search: !SearchState,
* notifications: !NotificationsState,
* }}
diff --git a/chromium/chrome/browser/resources/app_management/util.js b/chromium/chrome/browser/resources/app_management/util.js
index 5330b4de071..1e94d7cce9a 100644
--- a/chromium/chrome/browser/resources/app_management/util.js
+++ b/chromium/chrome/browser/resources/app_management/util.js
@@ -17,6 +17,7 @@ cr.define('app_management.util', function() {
pageType: PageType.MAIN,
selectedAppId: null,
},
+ arcSupported: false,
search: {
term: null,
results: null,
@@ -35,6 +36,10 @@ cr.define('app_management.util', function() {
function createInitialState(apps) {
const initialState = createEmptyState();
+ initialState.arcSupported =
+ loadTimeData.valueExists('isSupportedArcVersion') &&
+ loadTimeData.getBoolean('isSupportedArcVersion');
+
for (const app of apps) {
initialState.apps[app.id] = app;
@@ -58,13 +63,15 @@ cr.define('app_management.util', function() {
* @param {number} permissionId
* @param {!PermissionValueType} valueType
* @param {number} value
+ * @param {boolean} isManaged
* @return {!Permission}
*/
- function createPermission(permissionId, valueType, value) {
+ function createPermission(permissionId, valueType, value, isManaged) {
return {
- permissionId: permissionId,
- valueType: valueType,
- value: value,
+ permissionId,
+ valueType,
+ value,
+ isManaged,
};
}
@@ -218,6 +225,23 @@ cr.define('app_management.util', function() {
return a.localeCompare(b);
}
+ /**
+ * Toggles an OptionalBool
+ *
+ * @param {OptionalBool} bool
+ * @return {OptionalBool}
+ */
+ function toggleOptionalBool(bool) {
+ switch (bool) {
+ case OptionalBool.kFalse:
+ return OptionalBool.kTrue;
+ case OptionalBool.kTrue:
+ return OptionalBool.kFalse;
+ default:
+ assertNotReached();
+ }
+ }
+
return {
addIfNeeded: addIfNeeded,
alphabeticalSort: alphabeticalSort,
@@ -232,5 +256,6 @@ cr.define('app_management.util', function() {
notificationsPermissionType: notificationsPermissionType,
permissionTypeHandle: permissionTypeHandle,
removeIfNeeded: removeIfNeeded,
+ toggleOptionalBool: toggleOptionalBool,
};
});
diff --git a/chromium/chrome/browser/resources/bluetooth_internals/adapter_broker.js b/chromium/chrome/browser/resources/bluetooth_internals/adapter_broker.js
index 0167d09cae7..918c700cce3 100644
--- a/chromium/chrome/browser/resources/bluetooth_internals/adapter_broker.js
+++ b/chromium/chrome/browser/resources/bluetooth_internals/adapter_broker.js
@@ -40,7 +40,7 @@ cr.define('adapter_broker', function() {
super();
this.adapterClient_ = new bluetooth.mojom.AdapterClient(this);
this.adapter_ = adapter;
- this.adapter_.setClient(this.adapterClient_.createProxy());
+ this.adapter_.setClient(this.adapterClient_.$.createProxy());
}
presentChanged(present) {
diff --git a/chromium/chrome/browser/resources/bookmarks/BUILD.gn b/chromium/chrome/browser/resources/bookmarks/BUILD.gn
index 84672acdb88..3fc62cd2aa8 100644
--- a/chromium/chrome/browser/resources/bookmarks/BUILD.gn
+++ b/chromium/chrome/browser/resources/bookmarks/BUILD.gn
@@ -155,6 +155,7 @@ js_library("item") {
":command_manager",
":store_client",
"//ui/webui/resources/js:icon",
+ "//ui/webui/resources/js/cr/ui:focus_without_ink",
]
externs_list = [ "$externs_path/chrome_extensions.js" ]
}
diff --git a/chromium/chrome/browser/resources/bookmarks/app.html b/chromium/chrome/browser/resources/bookmarks/app.html
index 59e496ae37a..80d1ab2229a 100644
--- a/chromium/chrome/browser/resources/bookmarks/app.html
+++ b/chromium/chrome/browser/resources/bookmarks/app.html
@@ -55,9 +55,11 @@
transition: opacity 100ms ease-out;
}
- :host-context([dark]) #splitter:hover,
- :host-context([dark]) #splitter.splitter-active {
- border-inline-start-color: var(--cr-separator-color);
+ @media (prefers-color-scheme: dark) {
+ #splitter:hover,
+ #splitter.splitter-active {
+ border-inline-start-color: var(--cr-separator-color);
+ }
}
#sidebar {
diff --git a/chromium/chrome/browser/resources/bookmarks/bookmarks.html b/chromium/chrome/browser/resources/bookmarks/bookmarks.html
index b91e6202e69..077405e88cd 100644
--- a/chromium/chrome/browser/resources/bookmarks/bookmarks.html
+++ b/chromium/chrome/browser/resources/bookmarks/bookmarks.html
@@ -1,6 +1,5 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading"
- $i18n{dark}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading">
<head>
<meta charset="utf8">
<title>$i18n{title}</title>
@@ -34,6 +33,5 @@
<link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
<link rel="import" href="app.html">
- <link rel="import" href="chrome://resources/html/dark_mode.html">
</body>
</html>
diff --git a/chromium/chrome/browser/resources/bookmarks/command_manager.html b/chromium/chrome/browser/resources/bookmarks/command_manager.html
index bdbefe95833..a2e14d04d4e 100644
--- a/chromium/chrome/browser/resources/bookmarks/command_manager.html
+++ b/chromium/chrome/browser/resources/bookmarks/command_manager.html
@@ -1,8 +1,8 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr/ui/command.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-a11y-keys-behavior/iron-a11y-keys-behavior.html">
@@ -14,7 +14,7 @@
<dom-module id="bookmarks-command-manager">
<template>
- <style include="shared-style paper-button-style">
+ <style include="shared-style">
.label {
flex: 1;
}
@@ -63,12 +63,12 @@
<div slot="title">$i18n{openDialogTitle}</div>
<div slot="body"></div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onOpenCancelTap_">
+ <cr-button class="cancel-button" on-click="onOpenCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onOpenConfirmTap_">
+ </cr-button>
+ <cr-button class="action-button" on-click="onOpenConfirmTap_">
$i18n{openDialogConfirm}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/bookmarks/dnd_manager.js b/chromium/chrome/browser/resources/bookmarks/dnd_manager.js
index 0c9bf741330..c5e68703f2a 100644
--- a/chromium/chrome/browser/resources/bookmarks/dnd_manager.js
+++ b/chromium/chrome/browser/resources/bookmarks/dnd_manager.js
@@ -330,6 +330,9 @@ cr.define('bookmarks', function() {
* @private {!Object}
*/
this.timerProxy_ = window;
+
+ /** @private {boolean} */
+ this.lastPointerWasTouch_ = false;
}
init() {
@@ -344,7 +347,8 @@ cr.define('bookmarks', function() {
'dragleave': this.onDragLeave_.bind(this),
'drop': this.onDrop_.bind(this),
'dragend': this.clearDragData_.bind(this),
- // TODO(calamity): Add touch support.
+ 'mousedown': this.onMouseDown_.bind(this),
+ 'touchstart': this.onTouchStart_.bind(this),
};
for (const event in this.documentListeners_) {
document.addEventListener(event, this.documentListeners_[event]);
@@ -388,13 +392,14 @@ cr.define('bookmarks', function() {
let draggedNodes = [];
if (isBookmarkItem(dragElement)) {
- const displayingItems =
- assert(state.nodes[state.selectedFolder].children);
-
+ const displayingItems = assert(bookmarks.util.getDisplayedList(state));
+ // TODO(crbug.com/980427): Make this search more time efficient to avoid
+ // delay on large amount of bookmark dragging.
for (const itemId of displayingItems) {
for (const element of dragData.elements) {
if (element.id == itemId) {
draggedNodes.push(element.id);
+ break;
}
}
}
@@ -407,9 +412,9 @@ cr.define('bookmarks', function() {
const dragNodeIndex = draggedNodes.indexOf(dragElement.itemId);
assert(dragNodeIndex != -1);
- // TODO(calamity): account for touch.
chrome.bookmarkManagerPrivate.startDrag(
- draggedNodes, dragNodeIndex, false);
+ draggedNodes, dragNodeIndex, this.lastPointerWasTouch_, e.clientX,
+ e.clientY);
}
/** @private */
@@ -496,6 +501,16 @@ cr.define('bookmarks', function() {
this.dropIndicator_.update(this.dropDestination_);
}
+ /** @private */
+ onMouseDown_() {
+ this.lastPointerWasTouch_ = false;
+ }
+
+ /** @private */
+ onTouchStart_() {
+ this.lastPointerWasTouch_ = true;
+ }
+
/**
* @private
* @param {DragData} dragData
diff --git a/chromium/chrome/browser/resources/bookmarks/edit_dialog.html b/chromium/chrome/browser/resources/bookmarks/edit_dialog.html
index 8bf091cb067..057e0b127e9 100644
--- a/chromium/chrome/browser/resources/bookmarks/edit_dialog.html
+++ b/chromium/chrome/browser/resources/bookmarks/edit_dialog.html
@@ -1,17 +1,16 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/assert.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="dialog_focus_manager.html">
<link rel="import" href="strings.html">
<dom-module id="bookmarks-edit-dialog">
<template>
- <style include="cr-shared-style paper-button-style">
+ <style include="cr-shared-style">
</style>
<cr-dialog id="dialog">
<div slot="title">
@@ -27,13 +26,13 @@
</cr-input>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelButtonTap_">
+ <cr-button class="cancel-button" on-click="onCancelButtonTap_">
$i18n{cancel}
- </paper-button>
- <paper-button id="saveButton" class="action-button"
+ </cr-button>
+ <cr-button id="saveButton" class="action-button"
on-click="onSaveButtonTap_">
$i18n{saveEdit}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/bookmarks/folder_node.html b/chromium/chrome/browser/resources/bookmarks/folder_node.html
index c8ddfd3f963..bfb8b4da408 100644
--- a/chromium/chrome/browser/resources/bookmarks/folder_node.html
+++ b/chromium/chrome/browser/resources/bookmarks/folder_node.html
@@ -57,10 +57,12 @@
color: var(--interactive-color);
}
- :host-context([dark]) .drag-on .menu-label,
- :host-context([dark]) .drag-on .folder-icon,
- :host-context([dark]) .drag-on #arrow {
- color: var(--google-grey-refresh-700);
+ @media (prefers-color-scheme: dark) {
+ .drag-on .menu-label,
+ .drag-on .folder-icon,
+ .drag-on #arrow {
+ color: var(--google-grey-refresh-700);
+ }
}
:host-context([dir='rtl']) #arrow:not([is-open]) {
diff --git a/chromium/chrome/browser/resources/bookmarks/images/folder.svg b/chromium/chrome/browser/resources/bookmarks/images/folder.svg
deleted file mode 100644
index d3a9e54f3e4..00000000000
--- a/chromium/chrome/browser/resources/bookmarks/images/folder.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="#757575"><path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/bookmarks/item.html b/chromium/chrome/browser/resources/bookmarks/item.html
index ec8610f1da7..c4fc5e0d617 100644
--- a/chromium/chrome/browser/resources/bookmarks/item.html
+++ b/chromium/chrome/browser/resources/bookmarks/item.html
@@ -3,6 +3,7 @@
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
+<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/html/icon.html">
<link rel="import" href="actions.html">
<link rel="import" href="shared_style.html">
@@ -28,9 +29,11 @@
background-color: var(--highlight-color);
}
- :host-context([dark]):host([is-selected-item_]),
- :host-context([dark]):host([is-selected-item_]) .folder-icon {
- color: var(--google-grey-refresh-700);
+ @media (prefers-color-scheme: dark) {
+ :host([is-selected-item_]),
+ :host([is-selected-item_]) .folder-icon {
+ color: var(--google-grey-refresh-700);
+ }
}
#website-title {
@@ -44,8 +47,10 @@
flex: 0 auto;
}
- :host-context([dark]):host([is-selected-item_]) #website-title {
- color: var(--google-grey-900);
+ @media (prefers-color-scheme: dark) {
+ :host([is-selected-item_]) #website-title {
+ color: var(--google-grey-900);
+ }
}
#website-url {
@@ -57,8 +62,10 @@
min-width: 100px;
}
- :host-context([dark]) #website-url {
- color: var(--google-grey-800);
+ @media (prefers-color-scheme: dark) {
+ #website-url {
+ color: var(--google-grey-800);
+ }
}
:host([is-selected-item_]) #website-url {
@@ -73,8 +80,10 @@
margin-inline-end: 12px;
}
- :host-context([dark]):host([is-selected-item_]) cr-icon-button {
- --cr-icon-button-color: var(--google-grey-700);
+ @media (prefers-color-scheme: dark) {
+ :host([is-selected-item_]) cr-icon-button {
+ --cr-icon-button-color: var(--google-grey-700);
+ }
}
:host(:focus) {
diff --git a/chromium/chrome/browser/resources/bookmarks/item.js b/chromium/chrome/browser/resources/bookmarks/item.js
index 82dd723fa33..f013a78094c 100644
--- a/chromium/chrome/browser/resources/bookmarks/item.js
+++ b/chromium/chrome/browser/resources/bookmarks/item.js
@@ -37,6 +37,9 @@ Polymer({
/** @private */
isFolder_: Boolean,
+
+ /** @private */
+ lastTouchPoints_: Number,
},
hostAttributes: {
@@ -55,6 +58,7 @@ Polymer({
'auxclick': 'onMiddleClick_',
'mousedown': 'cancelMiddleMouseBehavior_',
'mouseup': 'cancelMiddleMouseBehavior_',
+ 'touchstart': 'onTouchStart_',
},
/** @override */
@@ -66,6 +70,10 @@ Polymer({
this.updateFromStore();
},
+ focusMenuButton: function() {
+ cr.ui.focusWithoutInk(this.$.menuButton);
+ },
+
/** @return {BookmarksItemElement} */
getDropTarget: function() {
return this;
@@ -78,6 +86,14 @@ Polymer({
onContextMenu_: function(e) {
e.preventDefault();
e.stopPropagation();
+
+ // Prevent context menu from appearing after a drag, but allow opening the
+ // context menu through 2 taps
+ if (e.sourceCapabilities && e.sourceCapabilities.firesTouchEvents &&
+ this.lastTouchPoints_ !== 2) {
+ return;
+ }
+
this.focus();
if (!this.isSelectedItem_) {
this.selectThisItem_();
@@ -206,6 +222,14 @@ Polymer({
},
/**
+ * @param {TouchEvent} e
+ * @private
+ */
+ onTouchStart_: function(e) {
+ this.lastTouchPoints_ = e.touches.length;
+ },
+
+ /**
* Prevent default middle-mouse behavior. On Windows, this prevents autoscroll
* (during mousedown), and on Linux this prevents paste (during mouseup).
* @param {MouseEvent} e
@@ -223,7 +247,8 @@ Polymer({
*/
updateFavicon_: function(url) {
this.$.icon.className = url ? 'website-icon' : 'folder-icon';
- this.$.icon.style.backgroundImage = url ? cr.icon.getFavicon(url) : null;
+ this.$.icon.style.backgroundImage =
+ url ? cr.icon.getFavicon(url, false) : null;
},
/** @private */
diff --git a/chromium/chrome/browser/resources/bookmarks/list.js b/chromium/chrome/browser/resources/bookmarks/list.js
index 7934c960b32..3ff90db0c59 100644
--- a/chromium/chrome/browser/resources/bookmarks/list.js
+++ b/chromium/chrome/browser/resources/bookmarks/list.js
@@ -101,10 +101,12 @@ Polymer({
*/
onDisplayedIdsChanged_: async function(newValue, oldValue) {
const updatedList = newValue.map(id => ({id: id}));
+ let skipFocus = false;
let selectIndex = -1;
if (this.matches(':focus-within')) {
if (this.selectedItems_.size > 0) {
const selectedId = Array.from(this.selectedItems_)[0];
+ skipFocus = newValue.some(id => id == selectedId);
selectIndex = this.displayedList_.findIndex(({id}) => selectedId == id);
}
if (selectIndex == -1 && updatedList.length > 0) {
@@ -121,9 +123,14 @@ Polymer({
'getPluralString', 'listChanged', this.displayedList_.length);
this.fire('iron-announce', {text: label});
- if (selectIndex > -1) {
+ if (!skipFocus && selectIndex > -1) {
setTimeout(() => {
this.$.list.focusItem(selectIndex);
+ // Focus menu button so 'Undo' is only one tab stop away on delete.
+ const item = getDeepActiveElement();
+ if (item) {
+ item.focusMenuButton();
+ }
});
}
},
diff --git a/chromium/chrome/browser/resources/bookmarks/shared_style.html b/chromium/chrome/browser/resources/bookmarks/shared_style.html
index 918778c4169..22bfc62568e 100644
--- a/chromium/chrome/browser/resources/bookmarks/shared_style.html
+++ b/chromium/chrome/browser/resources/bookmarks/shared_style.html
@@ -12,8 +12,10 @@
margin: 8px 0;
}
- :host-context([dark]) hr {
- background: var(--cr-separator-color);
+ @media (prefers-color-scheme: dark) {
+ hr {
+ background: var(--cr-separator-color);
+ }
}
.drag-above::before,
@@ -53,17 +55,25 @@
}
.folder-icon {
- -webkit-mask-image: url(images/folder.svg);
- -webkit-mask-size: contain;
- background-color: currentcolor;
- color: var(--folder-icon-color);
- height: 20px;
- min-width: 20px;
- width: 20px;
+ content: url(chrome://theme/IDR_FOLDER_CLOSED);
}
+<if expr="is_macosx or is_ios">
+ @media (prefers-color-scheme: dark) {
+ .folder-icon {
+ content: url(chrome://theme/IDR_FOLDER_CLOSED_WHITE);
+ }
+ }
+</if>
+
+<if expr="not is_macosx and not is_ios">
.folder-icon[open] {
- -webkit-mask-image: url(images/folder_open.svg);
+ content: url(chrome://theme/IDR_FOLDER_OPEN);
+ }
+</if>
+
+ :host-context([dir=rtl]) .folder-icon {
+ transform: scaleX(-1);
}
.website-icon {
diff --git a/chromium/chrome/browser/resources/bookmarks/shared_vars.html b/chromium/chrome/browser/resources/bookmarks/shared_vars.html
index 4bf654aa9cf..b8d1fb34587 100644
--- a/chromium/chrome/browser/resources/bookmarks/shared_vars.html
+++ b/chromium/chrome/browser/resources/bookmarks/shared_vars.html
@@ -18,11 +18,13 @@
--splitter-width: 15px;
}
- html[dark] {
- --folder-icon-color: var(--google-grey-refresh-500);
- --folder-inactive-color: var(--google-grey-refresh-500);
- --highlight-color: var(--google-blue-refresh-300);
- --interactive-color: var(--google-blue-refresh-300);
+ @media (prefers-color-scheme: dark) {
+ html {
+ --folder-icon-color: var(--google-grey-refresh-500);
+ --folder-inactive-color: var(--google-grey-refresh-500);
+ --highlight-color: var(--google-blue-refresh-300);
+ --interactive-color: var(--google-blue-refresh-300);
+ }
}
</style>
</custom-style>
diff --git a/chromium/chrome/browser/resources/bookmarks/toolbar.html b/chromium/chrome/browser/resources/bookmarks/toolbar.html
index 989db07d3c1..d008a5ae9a7 100644
--- a/chromium/chrome/browser/resources/bookmarks/toolbar.html
+++ b/chromium/chrome/browser/resources/bookmarks/toolbar.html
@@ -25,8 +25,10 @@
margin: 4px;
}
- :host-context(html:not([dark])) cr-icon-button {
- --cr-icon-button-color: currentColor;
+ @media (prefers-color-scheme: light) {
+ cr-icon-button {
+ --cr-icon-button-color: currentColor;
+ }
}
:host(:not([narrow_])) cr-toolbar-selection-overlay {
diff --git a/chromium/chrome/browser/resources/browser_switch/browser_switch.html b/chromium/chrome/browser/resources/browser_switch/browser_switch.html
index 9b61a63d299..968ae80f108 100644
--- a/chromium/chrome/browser/resources/browser_switch/browser_switch.html
+++ b/chromium/chrome/browser/resources/browser_switch/browser_switch.html
@@ -1,5 +1,5 @@
<!DOCTYPE html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
<meta charset="utf-8">
<title>$i18n{title}</title>
diff --git a/chromium/chrome/browser/resources/browser_switch/internals/browser_switch_internals.html b/chromium/chrome/browser/resources/browser_switch/internals/browser_switch_internals.html
index e512b0ef8bc..05f5edf80ad 100644
--- a/chromium/chrome/browser/resources/browser_switch/internals/browser_switch_internals.html
+++ b/chromium/chrome/browser/resources/browser_switch/internals/browser_switch_internals.html
@@ -40,16 +40,16 @@
#url-checker-input {
width: 400px;
}
+
+ #xml-not-fetched-yet,
+ #xml-last-fetch {
+ display: none;
+ }
</style>
</head>
<body>
<h1>Legacy Browser Support Internals</h1>
- <p>
- If an XML sitelist is configured, wait 1 minute after browser
- startup for it to download, and then refresh this page.
- </p>
-
<!-- TODO(crbug/959379): Hide all this and show a message if
BrowserSwitcherEnabled is false. -->
@@ -73,6 +73,30 @@
<h2>Greylist</h2>
<table id="greylist"></table>
+ <h2>XML sitelists</h2>
+
+ <table id="xml-sitelists"></table>
+
+ <div id="xml-description-wrapper">
+ <p id="xml-not-fetched-yet">
+ XML sitelists have not been fetched yet.
+ </p>
+
+ <p id="xml-last-fetch">
+ XML sitelists were last downloaded at
+ <span id="last-fetch-placeholder"></span>.
+ </p>
+
+ <p id="xml-next-fetch">
+ Next download is at
+ <span id="next-fetch-placeholder"></span>.
+ </p>
+
+ <p>
+ <button id="refresh-xml-button">Download now</button>
+ </p>
+ </div>
+
<template id="header-row-template">
<tr>
<th>Rule</th>
@@ -91,6 +115,20 @@
</tr>
</template>
+ <template id="xml-header-row-template">
+ <tr>
+ <th>Source policy</th>
+ <th>URL</th>
+ </tr>
+ </template>
+
+ <template id="xml-row-template">
+ <tr>
+ <td></td>
+ <td></td>
+ </tr>
+ </template>
+
<script src="/internals/browser_switch_internals.js"></script>
</body>
</html>
diff --git a/chromium/chrome/browser/resources/browser_switch/internals/browser_switch_internals.js b/chromium/chrome/browser/resources/browser_switch/internals/browser_switch_internals.js
index 9e093cf759b..2b57bf2a681 100644
--- a/chromium/chrome/browser/resources/browser_switch/internals/browser_switch_internals.js
+++ b/chromium/chrome/browser/resources/browser_switch/internals/browser_switch_internals.js
@@ -22,12 +22,45 @@ let RuleSet;
let RuleSetList;
/**
+ * Returned by getRulesetSources().
+ * @typedef {{
+ * browser_switcher: Object<string, string>!,
+ * }}
+ */
+let RulesetSources;
+
+/**
+ * Returned by getTimestamps().
+ * @typedef {{
+ * last_fetch: number,
+ * next_fetch: number,
+ * }}
+ */
+let TimestampPair;
+
+/**
+ * Converts 'this_word' to 'ThisWord'
+ * @param {string} symbol
+ * @return {string}
+ */
+function snakeCaseToUpperCamelCase(symbol) {
+ if (!symbol) {
+ return symbol;
+ }
+ return symbol.replace(/(?:^|_)([a-z])/g, (_, letter) => {
+ return letter.toUpperCase();
+ });
+}
+
+/**
* Clears the table, and inserts a header row.
* @param {HTMLTableElement} table
+ * @param {HTMLTemplateElement} headerTemplate
+ * Template to use to re-create the header row.
*/
-function clearTable(table) {
+function clearTable(table, headerTemplate) {
table.innerHTML = '';
- const headerRow = document.importNode($('header-row-template').content, true);
+ const headerRow = document.importNode(headerTemplate.content, true);
table.appendChild(headerRow);
}
@@ -67,8 +100,10 @@ function createRowForRule(rule, rulesetName) {
* @param {RuleSetList} rulesets
*/
function updateTables(rulesets) {
- clearTable(/** @type {HTMLTableElement} */ ($('sitelist')));
- clearTable(/** @type {HTMLTableElement} */ ($('greylist')));
+ const headerTemplate =
+ /** @type {HTMLTemplateElement} */ ($('header-row-template'));
+ clearTable(/** @type {HTMLTableElement} */ ($('sitelist')), headerTemplate);
+ clearTable(/** @type {HTMLTableElement} */ ($('greylist')), headerTemplate);
for (const [rulesetName, ruleset] of Object.entries(rulesets)) {
for (const [listName, rules] of Object.entries(ruleset)) {
@@ -80,8 +115,6 @@ function updateTables(rulesets) {
}
}
-cr.sendWithPromise('getAllRulesets').then(updateTables);
-
function checkUrl() {
const url = $('url-checker-input').value;
if (!url) {
@@ -101,4 +134,91 @@ function checkUrl() {
}
$('url-checker-input').addEventListener('input', checkUrl);
-checkUrl();
+
+/**
+ * Formats |date| as "HH:MM:SS".
+ * @param {Date} date
+ * @return {string}
+ */
+function formatTime(date) {
+ const hh = date.getHours().toString().padStart(2, '0');
+ const mm = date.getMinutes().toString().padStart(2, '0');
+ const ss = date.getSeconds().toString().padStart(2, '0');
+ return `${hh}:${mm}:${ss}`;
+}
+
+/**
+ * Update the paragraphs under the "XML sitelists" section.
+ * @param {TimestampPair?} timestamps
+ */
+function updateTimestamps(timestamps) {
+ if (!timestamps) {
+ return;
+ }
+
+ const lastFetch = new Date(timestamps.last_fetch);
+ const nextFetch = new Date(timestamps.next_fetch);
+
+ if (lastFetch.valueOf() == 0) {
+ // Not fetched yet.
+ $('xml-not-fetched-yet').style.display = 'block';
+ $('xml-last-fetch').style.display = 'none';
+ } else {
+ // Already fetched.
+ $('xml-not-fetched-yet').style.display = 'none';
+ $('xml-last-fetch').style.display = 'block';
+ }
+
+ $('xml-next-fetch').style.display = nextFetch.valueOf() ? 'block' : 'none';
+
+ $('last-fetch-placeholder').innerText = formatTime(lastFetch);
+ $('next-fetch-placeholder').innerText = formatTime(nextFetch);
+}
+
+/**
+ * Update the table under the "XML sitelists" section.
+ * @param {RulesetSources} sources
+ */
+function updateXmlTable({browser_switcher: sources}) {
+ const headerTemplate =
+ /** @type {HTMLTemplateElement} */ ($('xml-header-row-template'));
+ clearTable(
+ /** @type {HTMLTableElement} */ ($('xml-sitelists')), headerTemplate);
+
+ for (const [prefName, url] of Object.entries(sources)) {
+ // Hacky: guess the policy name from the pref name by converting 'foo_bar'
+ // to 'BrowserSwitcherFooBar'. This relies on prefs having the same name as
+ // the associated policy.
+ const policyName = 'BrowserSwitcher' + snakeCaseToUpperCamelCase(prefName);
+ const row = document.importNode($('xml-row-template').content, true);
+ const cells = row.querySelectorAll('td');
+ cells[0].innerText = policyName;
+ cells[1].innerText = url || '(not configured)';
+ cells[1].className = 'url';
+ $('xml-sitelists').appendChild(row);
+ }
+
+ // Hide/show the description paragraphs depending on whether any XML sitelist
+ // is configured.
+ const enabled = Object.values(sources).some(x => !!x);
+ $('xml-description-wrapper').style.display = enabled ? 'block' : 'none';
+}
+
+/**
+ * Called by C++ when we need to update everything on the page.
+ */
+function updateEverything() {
+ cr.sendWithPromise('getAllRulesets').then(updateTables);
+ cr.sendWithPromise('getTimestamps').then(updateTimestamps);
+ cr.sendWithPromise('getRulesetSources').then(updateXmlTable);
+ checkUrl();
+}
+
+// TODO(crbug/959379): Keep the page up-to-date at all times: updateEverything()
+// when LBS prefs are updated, and after sitelists get refreshed.
+
+updateEverything();
+
+$('refresh-xml-button').addEventListener('click', () => {
+ chrome.send('refreshXml');
+});
diff --git a/chromium/chrome/browser/resources/certificate_viewer.css b/chromium/chrome/browser/resources/certificate_viewer.css
index 84bd0412aa1..e55b30d9aec 100644
--- a/chromium/chrome/browser/resources/certificate_viewer.css
+++ b/chromium/chrome/browser/resources/certificate_viewer.css
@@ -56,7 +56,7 @@ h3 {
#usages,
.groups > div > div {
- color: #787878;
+ color: #616161;
line-height: 18px;
padding-inline-start: 20px;
}
diff --git a/chromium/chrome/browser/resources/certificate_viewer.html b/chromium/chrome/browser/resources/certificate_viewer.html
index 6631bceb925..efbb1fc5ba4 100644
--- a/chromium/chrome/browser/resources/certificate_viewer.html
+++ b/chromium/chrome/browser/resources/certificate_viewer.html
@@ -1,4 +1,4 @@
-<!doctype html>
+<!doctype html>
<html dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
<meta charset="utf-8">
@@ -19,21 +19,25 @@
</head>
<body>
<tabbox id="tabbox">
- <tabs id="tabs" class="new-style-tabs">
- <tab>$i18n{general}</tab>
- <tab>$i18n{details}</tab>
+ <tabs id="tabs" class="new-style-tabs" role="tablist">
+ <tab id="general-tab" role="tab" aria-controls="general" tabindex="0">
+ $i18n{general}
+ </tab>
+ <tab id="details-tab" role="tab" aria-controls="details">
+ $i18n{details}
+ </tab>
</tabs>
<tabpanels id="tabpanels" class="new-style-tabs">
<!-- General -->
- <tabpanel id="general">
+ <tabpanel id="general" aria-labelledby="general-tab">
<!-- Usages -->
- <h3 id="usages-title">$i18n{usages}</h3>
+ <h3 id="usages-title" role="group">$i18n{usages}</h3>
<div id="usages"></div>
<div class="groups">
<!-- Issued to -->
<div>
- <h3>$i18n{issuedTo}</h3>
+ <h3 role="group">$i18n{issuedTo}</h3>
</div>
<div>
<div class="attribute">$i18n{cn}</div>
@@ -50,7 +54,7 @@
<!-- Issued by -->
<div>
- <h3>$i18n{issuedBy}</h3>
+ <h3 role="group">$i18n{issuedBy}</h3>
</div>
<div>
<div class="attribute">$i18n{cn}</div>
@@ -67,7 +71,7 @@
<!-- Validity -->
<div>
- <h3>$i18n{validity}</h3>
+ <h3 role="group">$i18n{validity}</h3>
</div>
<div>
<div class="attribute">$i18n{issuedOn}</div>
@@ -80,7 +84,7 @@
<!-- Fingerprints -->
<div>
- <h3>$i18n{fingerprints}</h3>
+ <h3 role="group">$i18n{fingerprints}</h3>
</div>
<div>
<div class="attribute">$i18n{sha256}</div>
@@ -94,20 +98,26 @@
</tabpanel>
<!-- Details -->
- <tabpanel>
+ <tabpanel id="details" aria-labelledby="details-tab">
<div id="hierarchy-section" class="vertical-box">
- <h3>$i18n{hierarchy}</h3>
+ <h3 id="hierarchy-label" role="group">$i18n{hierarchy}</h3>
<tree id="hierarchy" class="section-contents"
- icon-visibility='hidden'></tree>
+ aria-labelledby="hierarchy-label"
+ icon-visibility='hidden'></tree>
</div>
<div id="cert-fields-section" class="vertical-box">
- <h3>$i18n{certFields}</h3>
+ <h3 id="cert-fields-label" role="group">$i18n{certFields}</h3>
<tree id="cert-fields" class="section-contents"
- icon-visibility='hidden'></tree>
+ aria-labelledby="cert-fields-label"
+ icon-visibility='hidden'></tree>
</div>
<div id="cert-field-value-section" class="vertical-box">
- <h3>$i18n{certFieldVal}</h3>
- <div id="cert-field-value" class="section-contents"></div>
+ <h3 id="cert-field-value-label" role="group">
+ $i18n{certFieldVal}
+ </h3>
+ <div id="cert-field-value" class="section-contents" tabindex="0"
+ aria-live="polite" aria-atomic="true" aria-readonly="true"
+ aria-labelledby="cert-field-value-label" role="textbox"></div>
<div>
<button id="export">$i18n{export}</button>
</div>
diff --git a/chromium/chrome/browser/resources/chromeos/BUILD.gn b/chromium/chrome/browser/resources/chromeos/BUILD.gn
index 060fd4ba604..72b6c86c832 100644
--- a/chromium/chrome/browser/resources/chromeos/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/BUILD.gn
@@ -34,16 +34,40 @@ grit("multidevice_setup_resources") {
output_dir = "$root_gen_dir/chrome"
}
+grit("camera_resources") {
+ source = "camera/camera_resources.grd"
+
+ defines = chrome_grit_defines
+ outputs = [
+ "grit/camera_resources.h",
+ "grit/camera_resources_map.cc",
+ "grit/camera_resources_map.h",
+ "camera_resources.pak",
+ ]
+ output_dir = "$root_gen_dir/chrome"
+
+ deps = [
+ "//media/capture/video/chromeos/mojo:cros_camera_js",
+ ]
+
+ # The .grd contains references to generated files.
+ source_is_generated = true
+
+ grit_flags = [
+ "-E",
+ "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
+ ]
+}
+
group("closure_compile") {
deps = [
"add_supervision:closure_compile",
"bluetooth_pairing_dialog:closure_compile",
"braille_ime:closure_compile",
+ "camera/src/js:closure_compile",
"internet_config_dialog:closure_compile",
"internet_detail_dialog:closure_compile",
- "kiosk_next_home:closure_compile",
"login:closure_compile",
- "login:closure_compile_supervision",
"machine_learning:closure_compile",
"multidevice_setup:closure_compile",
"network_ui:closure_compile",
diff --git a/chromium/chrome/browser/resources/chromeos/autoclick/BUILD.gn b/chromium/chrome/browser/resources/chromeos/autoclick/BUILD.gn
new file mode 100644
index 00000000000..d837a9ac993
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/autoclick/BUILD.gn
@@ -0,0 +1,137 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//build/config/features.gni")
+import("//chrome/browser/resources/chromeos/chromevox/run_jsbundler.gni")
+import("//chrome/test/base/js2gtest.gni")
+import("//testing/test.gni")
+import("//third_party/closure_compiler/compile_js.gni")
+
+assert(is_chromeos)
+
+autoclick_dir = "$root_out_dir/resources/chromeos/autoclick"
+
+group("build") {
+ deps = [
+ ":autoclick_copied_files",
+ ":autoclick_guest_manifest",
+ ":autoclick_manifest",
+ ]
+}
+
+# Instead of setting up copy targets, use a script to copy all files.
+run_jsbundler("autoclick_copied_files") {
+ mode = "copy"
+ dest_dir = autoclick_dir
+ sources = [
+ "autoclick.js",
+ ]
+ rewrite_rules = [
+ rebase_path(".", root_build_dir) + ":",
+ rebase_path(closure_library_dir, root_build_dir) + ":closure",
+ ]
+}
+
+# TODO(crbug/978200): refactor this into another file like generate_manifest.gni
+# to share with other extensions.
+template("manifest") {
+ version_file = "//chrome/VERSION"
+ version_script = "//build/util/version.py"
+ template_file = "manifest.json.jinja2"
+ output_file = invoker.output_file
+ key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC6SX/t6kDEi9UiG4fULwjbEW1uJmQoiJPtxvSZ/SDH14OjSzmfP6xfE97Hus3EY8uSIMxTHkGaZliGbFbIQXQn6/XwBpQRu2gPlrfz7TWR1Hw6SboBBMOpltM9A2nx+d3jLtz+YtKNYVcHyNil9hXfFeyFe6g5kLHapKb1UO0jo3q3kovo1a1z7ujzGwogfLmb58w1hkdFBnnqumRlT55dKLN8AQ6cSdB1sjDVoMgPYeWgkzXr9cR3A8UVJookSO0sDAmD+W8BtBijapt3UVkHiIL1NTPuXvGGUHL7TPFo5WcBXFMkTz74gJqqFdO5hQ2YWXAaCxQJwgJrQPrvPMSJAgMBAAECggEADDhEDww9wWbWzUz3BQEs2In1HrOgAFStN3zEkNFc9B78AJsvpXWczgPUqk9jrg1JzkUeghlK/mDWT8MNkkdQ4kmFMYCM9/jOI6+kU3js+arxlzU84VI5r4c4RhlSOtBEMOHjF0DORP3sopMXOxPAbYjXog3xhA0szYXdedwcIik7Xu3lt1Hl5FfVZbvVLdf4vw0jTfHcp8SmHy/BDVnSCrhC3pnPGi6o+lUaSK0ca3uvcJDZGLXJ/6LyFb6uLlS2XUoBMYsombioRKrerJJSOmMTLHvfu1cM6+iQ+J0wdBnJQpgmDoSVGjnksPU2SMpWgG2OzwuZYIUGI745s19wLQKBgQDvdHsMZ4ttBr9bjydzeZVATWTICHZgXdAYgfgrbGwppYDUjfKoAuJ6bHTvff4nj8aZrY+Y1SwuvqxgHHfiggUgqg+JyeaAdQG+CLdfl1M8An+6H0x/hx0nk0oOJQhu0y1R/SbtnDJ6JASszg/VrTwHIYbzUl6xKHbZ6X41apyLYwKBgQDHKJOeZdxuYj7AsAqFGreuPoAEh0S+2VHHi4rjNz5dC1z7o/8siixfkHg7ONM2hqCKo55XYj4UWtprEFZJ9ohbizHELNzpnTxjdS0cG/VfItml6CDJaUtrkShIx17yGjNi0u/7ywHQ3slJsUXu7CbEcESwEzdoSrsC048dyxBSIwKBgF0141wtxklXcg/LBtldf6q7NbrkCGh0vDd+CEOm/eesRBz5cHbUQKLVKyO60L9HqVBTDm24tW0wzdrP2h7y69oOOOQzEqX4Zgg6Tl9IgZ7/fgbOfjG6P7ATFqWw5rp1O9QJjii6P6/p62P1Bpbvy0kfVO/MpY2iqbkjufxDFtLvAoGBAMC5p4CVGedH82oL8WI1JKLdoIzBSelV7CmqA9E1WIg5wtVRMlIrtB0WdQL6ToppZVpEU6pES8bu1Ibe3GHezL2pyZMJxw3bNuEYN3sIIz7ZPr2qEHBYEMAbTFyBcoPejvOHJO0I2s0BitBhWEeJB0r5Sb8KGYg3KRnnGIvAQh75AoGBANEC/k1umGrnMO3rwHJF7R+aTHzeMnO6oi11pmSnT7eJcF+oi7OwHS3ickU6sGrIb5QmnwCY9ES1qY6mP7N++KQGsdQM2l13MpCn8cBZgrfpQg2slP1dz8LCDW/PB+6MF7qwEHN2afVA2muQaez+q0eXZjMXmGJ3VZIXz/cxBLD6"
+ action(target_name) {
+ script = "//chrome/browser/resources/chromeos/chromevox/tools/generate_manifest.py"
+ inputs = [
+ version_file,
+ version_script,
+ ]
+ sources = [
+ template_file,
+ ]
+ outputs = [
+ output_file,
+ ]
+ args = [
+ "--key=$key",
+ "--version_file=" + rebase_path(version_file, root_build_dir),
+ "--output_manifest=" + rebase_path(output_file, root_build_dir),
+ ]
+ if (defined(invoker.is_guest_manifest) && invoker.is_guest_manifest) {
+ args += [ "--is_guest_manifest=1" ]
+ }
+ args += rebase_path(sources, root_build_dir)
+ }
+}
+
+manifest("autoclick_manifest") {
+ output_file = "$autoclick_dir/manifest.json"
+}
+
+manifest("autoclick_guest_manifest") {
+ output_file = "$autoclick_dir/manifest_guest.json"
+ is_guest_manifest = true
+}
+
+source_set("browser_tests") {
+ testonly = true
+ assert(enable_extensions)
+
+ deps = [
+ ":autoclick_extjs_tests",
+ ]
+
+ data = [
+ "$root_out_dir/chrome_100_percent.pak",
+ "$root_out_dir/chrome_200_percent.pak",
+ "$root_out_dir/locales/en-US.pak",
+ "$root_out_dir/resources.pak",
+ "$root_out_dir/resources/chromeos/autoclick/",
+ "$root_out_dir/test_data/chrome/browser/resources/chromeos/autoclick/",
+
+ # The test uses data from the original location, not the copied one.
+ "//chrome/browser/resources/chromeos/chromevox/",
+ "//chrome/browser/resources/chromeos/autoclick/",
+ "//chrome/test/data/webui/test_api.js",
+ "//chrome/third_party/mock4js/",
+ "//third_party/accessibility-audit/axs_testing.js",
+ "//third_party/chaijs/chai.js",
+ "//ui/webui/resources/js/cr.js",
+ ]
+}
+
+js2gtest("autoclick_extjs_tests") {
+ test_type = "extension"
+ sources = [
+ "autoclick_test.extjs",
+ ]
+ gen_include_files = [
+ "../chromevox/testing/callback_helper.js",
+ "mock_accessibility_private.js",
+ ]
+
+ # The test base classes generate C++ code with these deps.
+ deps = [
+ "//ash",
+ "//ash/keyboard/ui",
+ "//base",
+ "//chrome/browser/chromeos",
+ "//chrome/common",
+ ]
+ defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ]
+}
+
+js_type_check("closure_compile") {
+ deps = [
+ ":autoclick",
+ ]
+}
+
+js_library("autoclick") {
+ deps = []
+ externs_list = [
+ "$externs_path/accessibility_private.js",
+ "$externs_path/automation.js",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/BUILD.gn
index 09e7daa66d6..813d058f946 100644
--- a/chromium/chrome/browser/resources/chromeos/camera/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/camera/BUILD.gn
@@ -4,6 +4,12 @@
chrome_camera_app_dir = "$root_out_dir/resources/chromeos/camera"
+group("closure_compile") {
+ deps = [
+ "src/js:closure_compile",
+ ]
+}
+
group("chrome_camera_app") {
# According to crbug.com/855747, we should list all the files we want to copy
# rather than list only the folders to avoid potential building issue and ease
@@ -17,6 +23,8 @@ group("chrome_camera_app") {
":chrome_camera_app_css",
":chrome_camera_app_images",
":chrome_camera_app_js",
+ ":chrome_camera_app_js_browser_proxy",
+ ":chrome_camera_app_js_device",
":chrome_camera_app_js_models",
":chrome_camera_app_js_mojo",
":chrome_camera_app_js_views",
@@ -55,6 +63,8 @@ copy("chrome_camera_app_images") {
"src/images/browser_button_print.svg",
"src/images/camera_app_icons_128.png",
"src/images/camera_app_icons_48.png",
+ "src/images/camera_button_fps_30.svg",
+ "src/images/camera_button_fps_60.svg",
"src/images/camera_button_grid_off.svg",
"src/images/camera_button_grid_on.svg",
"src/images/camera_button_mic_off.svg",
@@ -121,6 +131,28 @@ copy("chrome_camera_app_js") {
]
}
+copy("chrome_camera_app_js_browser_proxy") {
+ sources = [
+ "src/js/browser_proxy/browser_proxy.js",
+ ]
+
+ outputs = [
+ "$chrome_camera_app_dir/js/browser_proxy/{{source_file_part}}",
+ ]
+}
+
+copy("chrome_camera_app_js_device") {
+ sources = [
+ "src/js/device/camera3_device_info.js",
+ "src/js/device/constraints_preferrer.js",
+ "src/js/device/device_info_updater.js",
+ ]
+
+ outputs = [
+ "$chrome_camera_app_dir/js/device/{{source_file_part}}",
+ ]
+}
+
copy("chrome_camera_app_js_models") {
sources = [
"src/js/models/filenamer.js",
@@ -166,7 +198,6 @@ copy("chrome_camera_app_js_views_camera") {
"src/js/views/camera/options.js",
"src/js/views/camera/preview.js",
"src/js/views/camera/recordtime.js",
- "src/js/views/camera/resolution_preference.js",
"src/js/views/camera/timertick.js",
]
diff --git a/chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd b/chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd
new file mode 100644
index 00000000000..0f24c24ff64
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd
@@ -0,0 +1,125 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<grit latest_public_release="0" current_release="1" output_all_resource_defines="false">
+ <outputs>
+ <output filename="grit/camera_resources.h" type="rc_header">
+ <emit emit_type='prepend'></emit>
+ </output>
+ <output filename="grit/camera_resources_map.cc"
+ type="resource_file_map_source" />
+ <output filename="grit/camera_resources_map.h"
+ type="resource_map_header" />
+ <output filename="camera_resources.pak" type="data_package" />
+ </outputs>
+ <release seq="1">
+ <structures>
+ <structure name="IDR_CAMERA_BACKGROUND_JS" file="src/js/background.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_BROWSER_JS" file="src/js/views/browser.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_BUNDLE_JS" file="src/js/google-analytics-bundle.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_CAMERA3_DEVICE_INFO_JS" file="src/js/device/camera3_device_info.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_CAMERA_JS" file="src/js/views/camera.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_CONSTRAINTS_PREFERRER_JS" file="src/js/device/constraints_preferrer.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_DEVICE_INFO_UPDATER_JS" file="src/js/device/device_info_updater.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_DIALOG_JS" file="src/js/views/dialog.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_FILENAMER_JS" file="src/js/models/filenamer.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_FILESYSTEM_JS" file="src/js/models/filesystem.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_GALLERY_BASE_JS" file="src/js/views/gallery_base.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_GALLERY_JS" file="src/js/models/gallery.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_GALLERYBUTTON_JS" file="src/js/gallerybutton.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_IMAGECAPTURE_JS" file="src/js/mojo/imagecapture.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_LAYOUT_JS" file="src/js/views/camera/layout.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_MAIN_CSS" file="src/css/main.css" type="chrome_html" />
+ <structure name="IDR_CAMERA_MAIN_HTML" file="src/views/main.html" type="chrome_html" />
+ <structure name="IDR_CAMERA_MAIN_JS" file="src/js/main.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_MANIFEST" file="manifest.json" type="chrome_html" />
+ <structure name="IDR_CAMERA_METRICS_JS" file="src/js/metrics.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_MODES_JS" file="src/js/views/camera/modes.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_NAV_JS" file="src/js/nav.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_OPTIONS_JS" file="src/js/views/camera/options.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_PREVIEW_JS" file="src/js/views/camera/preview.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_RECORDTIME_JS" file="src/js/views/camera/recordtime.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_RESOLUTION_EVENT_BROKER_JS" file="src/js/resolution_event_broker.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_SCROLLBAR_JS" file="src/js/scrollbar.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_SETTINGS_JS" file="src/js/views/settings.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_SOUND_JS" file="src/js/sound.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_STATE_JS" file="src/js/state.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_TIMERTICK_JS" file="src/js/views/camera/timertick.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_TOAST_JS" file="src/js/toast.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_TOOLTIP_JS" file="src/js/tooltip.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_UTIL_JS" file="src/js/util.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_VIEW_JS" file="src/js/views/view.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_WARNING_JS" file="src/js/views/warning.js" type="chrome_html" />
+ <structure name="IDR_CAMERA_WEBUI_BROWSER_PROXY" file="src/js/browser_proxy/webui_browser_proxy.js" type="chrome_html" />
+ </structures>
+ <includes>
+ <!-- Mojo Lite Bindings -->
+ <include name="IDR_CAMERA_IMAGE_CAPTURE_MOJOM_LITE_JS"
+ file="${root_gen_dir}/media/capture/mojom/image_capture.mojom-lite.js"
+ use_base_dir="false"
+ type="BINDATA"/>
+ <include name="IDR_CAMERA_CAMERA_COMMON_MOJOM_LITE_JS"
+ file="${root_gen_dir}/media/capture/video/chromeos/mojo/camera_common.mojom-lite.js"
+ use_base_dir="false"
+ type="BINDATA"/>
+ <include name="IDR_CAMERA_CAMERA_METADATA_MOJOM_LITE_JS"
+ file="${root_gen_dir}/media/capture/video/chromeos/mojo/camera_metadata.mojom-lite.js"
+ use_base_dir="false"
+ type="BINDATA"/>
+ <include name="IDR_CAMERA_CAMERA_METADATA_TAGS_MOJOM_LITE_JS"
+ file="${root_gen_dir}/media/capture/video/chromeos/mojo/camera_metadata_tags.mojom-lite.js"
+ use_base_dir="false"
+ type="BINDATA"/>
+ <include name="IDR_CAMERA_CROS_IMAGE_CAPTURE_MOJOM_LITE_JS"
+ file="${root_gen_dir}/media/capture/video/chromeos/mojo/cros_image_capture.mojom-lite.js"
+ use_base_dir="false"
+ type="BINDATA"/>
+
+ <include name="IDR_CAMERA_RECORD_END_OGG" file="src/sounds/record_end.ogg" type="BINDATA" />
+ <include name="IDR_CAMERA_RECORD_START_OGG" file="src/sounds/record_start.ogg" type="BINDATA" />
+ <include name="IDR_CAMERA_SHUTTER_OGG" file="src/sounds/shutter.ogg" type="BINDATA" />
+ <include name="IDR_CAMERA_TICK_OGG" file="src/sounds/tick.ogg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_MODE_SQUARE_SVG" file="src/images/camera_mode_square.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_SETTINGS_BUTTON_BACK_SVG" file="src/images/settings_button_back.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_MODE_PORTRAIT_SVG" file="src/images/camera_mode_portrait.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_TIMER_ON_3S_SVG" file="src/images/camera_button_timer_on_3s.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_SHUTTER_VIDEO_START_HOVER_SVG" file="src/images/camera_shutter_video_start_hover.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_SPINNER_SVG" file="src/images/spinner.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_INTRO_BANNER_ICON_SVG" file="src/images/camera_intro_banner_icon.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_GRID_OFF_SVG" file="src/images/camera_button_grid_off.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_MIC_ON_SVG" file="src/images/camera_button_mic_on.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_BROWSER_BUTTON_DELETE_SVG" file="src/images/browser_button_delete.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_MODE_VIDEO_SVG" file="src/images/camera_mode_video.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_STOP_SVG" file="src/images/camera_shutter_photo_stop.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_MIC_OFF_SVG" file="src/images/camera_button_mic_off.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_SHUTTER_VIDEO_STOP_HOVER_SVG" file="src/images/camera_shutter_video_stop_hover.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_SETTINGS_RESOLUTION_SVG" file="src/images/settings_resolution.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_BROWSER_BUTTON_PRINT_SVG" file="src/images/browser_button_print.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_APP_ICONS_48_PNG" file="src/images/camera_app_icons_48.png" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_TIMER_OFF_SVG" file="src/images/camera_button_timer_off.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_START_ACTIVE_SVG" file="src/images/camera_shutter_photo_start_active.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_APP_ICONS_128_PNG" file="src/images/camera_app_icons_128.png" type="BINDATA" />
+ <include name="IDR_CAMERA_SETTINGS_TIMER_DURATION_SVG" file="src/images/settings_timer_duration.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_SETTINGS_HELP_SVG" file="src/images/settings_help.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_MIRROR_ON_SVG" file="src/images/camera_button_mirror_on.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_SETTINGS_BUTTON_EXPAND_SVG" file="src/images/settings_button_expand.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_GRID_ON_SVG" file="src/images/camera_button_grid_on.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_SWITCH_DEVICE_SVG" file="src/images/camera_button_switch_device.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_STOP_HOVER_SVG" file="src/images/camera_shutter_photo_stop_hover.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_SETTINGS_GRID_TYPE_SVG" file="src/images/settings_grid_type.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_MIRROR_OFF_SVG" file="src/images/camera_button_mirror_off.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_BROWSER_BUTTON_EXPORT_SVG" file="src/images/browser_button_export.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_INTRO_BANNER_CLOSE_SVG" file="src/images/camera_intro_banner_close.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_START_SVG" file="src/images/camera_shutter_photo_start.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_BROWSER_BUTTON_BACK_SVG" file="src/images/browser_button_back.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_SHUTTER_VIDEO_STOP_SVG" file="src/images/camera_shutter_video_stop.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_SWITCH_PHOTO_SVG" file="src/images/camera_button_switch_photo.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_SETTINGS_FEEDBACK_SVG" file="src/images/settings_feedback.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_SWITCH_VIDEO_SVG" file="src/images/camera_button_switch_video.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_SHUTTER_PHOTO_START_HOVER_SVG" file="src/images/camera_shutter_photo_start_hover.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_TIMER_ON_10S_SVG" file="src/images/camera_button_timer_on_10s.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_SHUTTER_VIDEO_START_SVG" file="src/images/camera_shutter_video_start.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_MODE_PHOTO_SVG" file="src/images/camera_mode_photo.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_FOCUS_AIM_SVG" file="src/images/camera_focus_aim.svg" type="BINDATA" />
+ <include name="IDR_CAMERA_CAMERA_BUTTON_SETTINGS_SVG" file="src/images/camera_button_settings.svg" type="BINDATA" />
+ </includes>
+ </release>
+</grit>
diff --git a/chromium/chrome/browser/resources/chromeos/camera/manifest.json b/chromium/chrome/browser/resources/chromeos/camera/manifest.json
new file mode 100644
index 00000000000..894b240e3bb
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/camera/manifest.json
@@ -0,0 +1,18 @@
+{
+ "name": "Camera",
+ "display": "standalone",
+ "icons": [
+ {
+ "src": "src/images/camera_app_icons_128.png",
+ "sizes": "128x128",
+ "type": "image/png"
+ },
+ {
+ "src": "src/images/camera_app_icons_48.png",
+ "sizes": "48x48",
+ "type": "image/png"
+ }
+ ],
+ "start_url": "src/views/main.html",
+ "theme_color": "#000000"
+}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/_locales/en/messages.json b/chromium/chrome/browser/resources/chromeos/camera/src/_locales/en/messages.json
index e4bf00c50a9..5a9f048411f 100644
--- a/chromium/chrome/browser/resources/chromeos/camera/src/_locales/en/messages.json
+++ b/chromium/chrome/browser/resources/chromeos/camera/src/_locales/en/messages.json
@@ -91,6 +91,10 @@
"message": "Grid type",
"description": "Label for the button of grid-type options."
},
+ "TOGGLE_60FPS_BUTTON": {
+ "message": "60 FPS",
+ "description": "Label for the checkbox to toggle 60 FPS recording."
+ },
"TIMER_DURATION_BUTTON": {
"message": "Timer duration",
"description": "Label for the button of timer-duration options."
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/BUILD.gn
new file mode 100644
index 00000000000..7a0dd53b11e
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/camera/src/js/BUILD.gn
@@ -0,0 +1,41 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/closure_compiler/compile_js.gni")
+
+group("closure_compile") {
+ deps = [
+ ":compile_resources",
+ "browser_proxy:closure_compile",
+ "device:closure_compile",
+ "models:closure_compile",
+ "mojo:closure_compile",
+ ]
+}
+
+js_type_check("compile_resources") {
+ deps = [
+ ":resolution_event_broker",
+ ":state",
+ ":tooltip",
+ ":util",
+ ]
+}
+
+js_library("resolution_event_broker") {
+}
+
+js_library("state") {
+}
+
+js_library("tooltip") {
+}
+
+js_library("util") {
+ deps = [
+ ":tooltip",
+ "browser_proxy:browser_proxy",
+ ]
+ externs_list = [ "$externs_path/chrome_extensions.js" ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/browser_proxy/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/browser_proxy/BUILD.gn
new file mode 100644
index 00000000000..aa71df45125
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/camera/src/js/browser_proxy/BUILD.gn
@@ -0,0 +1,20 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/closure_compiler/compile_js.gni")
+
+js_type_check("closure_compile") {
+ deps = [
+ ":browser_proxy",
+ ]
+}
+
+js_library("browser_proxy") {
+ sources = [
+ "browser_proxy.js",
+ "browser_proxy_interface.js",
+ "webui_browser_proxy.js",
+ ]
+ externs_list = [ "$externs_path/chrome_extensions.js" ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/device/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/device/BUILD.gn
new file mode 100644
index 00000000000..013d454061a
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/camera/src/js/device/BUILD.gn
@@ -0,0 +1,35 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/closure_compiler/compile_js.gni")
+
+js_type_check("closure_compile") {
+ deps = [
+ ":camera3_device_info",
+ ":constraints_preferrer",
+ ":device_info_updater",
+ ]
+}
+
+js_library("camera3_device_info") {
+ deps = [
+ "../mojo:imagecapture",
+ ]
+}
+
+js_library("constraints_preferrer") {
+ deps = [
+ "..:resolution_event_broker",
+ "../browser_proxy:browser_proxy",
+ ]
+}
+
+js_library("device_info_updater") {
+ deps = [
+ "..:state",
+ "../mojo:imagecapture",
+ ":camera3_device_info",
+ ":constraints_preferrer",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn
new file mode 100644
index 00000000000..89ebf568fe6
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn
@@ -0,0 +1,28 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/closure_compiler/compile_js.gni")
+
+js_type_check("closure_compile") {
+ deps = [
+ ":filenamer",
+ ":filesystem",
+ ":gallery",
+ ]
+}
+
+js_library("filenamer") {
+}
+
+js_library("filesystem") {
+ deps = [
+ "..:util",
+ ]
+}
+
+js_library("gallery") {
+ deps = [
+ ":filesystem",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/mojo/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/mojo/BUILD.gn
new file mode 100644
index 00000000000..9d131abf33c
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/camera/src/js/mojo/BUILD.gn
@@ -0,0 +1,19 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/closure_compiler/compile_js.gni")
+
+js_type_check("closure_compile") {
+ deps = [
+ ":imagecapture",
+ ]
+}
+
+js_library("imagecapture") {
+ deps = [
+ "//media/capture/mojom:image_capture_js_library_for_compile",
+ "//media/capture/video/chromeos/mojo:cros_camera_js_library_for_compile",
+ ]
+ externs_list = [ "$externs_path/pending.js" ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd b/chromium/chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd
index 2bd7b405bee..834cc2109d1 100644
--- a/chromium/chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd
+++ b/chromium/chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd
@@ -285,6 +285,9 @@
<message desc="Label for the button of grid-type options." name="IDS_GRID_TYPE_BUTTON">
Grid type
</message>
+ <message desc="Label for the checkbox to toggle 60 FPS recording." name="IDS_TOGGLE_60FPS_BUTTON">
+ 60 FPS
+ </message>
<message desc="Label for the back button." name="IDS_BACK_BUTTON">
Go back
</message>
diff --git a/chromium/chrome/browser/resources/chromeos/chromevox/BUILD.gn b/chromium/chrome/browser/resources/chromeos/chromevox/BUILD.gn
index ccc37a1199f..32d9da3e2e8 100644
--- a/chromium/chrome/browser/resources/chromeos/chromevox/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/chromevox/BUILD.gn
@@ -341,7 +341,7 @@ run_jsbundler("chromevox_copied_files") {
]
}
-# TODO: refactor this into another file like generate_manifest.gni
+# TODO(crbug/978200): refactor this into another file like generate_manifest.gni
# to share with other extensions.
template("manifest") {
version_file = "//chrome/VERSION"
diff --git a/chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd b/chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd
index 0a00944226d..83d4ec0c1ad 100644
--- a/chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd
+++ b/chromium/chrome/browser/resources/chromeos/chromevox/strings/chromevox_strings.grd
@@ -3659,7 +3659,7 @@ If you're done with the tutorial, use ChromeVox to navigate to the Close button
Rich Text Attributes
</message>
<message desc="The text label for ChromeVox automatic rich text indication checkbox." name="IDS_CHROMEVOX_OPTIONS_RICH_TEXT_CHECKBOX_LABEL">
- Customize rich text indication
+ Announce rich text attributes
</message>
<message desc="Labels the misspell list box." name="IDS_CHROMEVOX_OPTIONS_MISSPELL_DESCRIPTION">
Indicate misspell:
@@ -3710,6 +3710,9 @@ If you're done with the tutorial, use ChromeVox to navigate to the Close button
<message desc="A string to specify time units in hours." name="IDS_CHROMEVOX_HOURS">
{COUNT, plural, =1 {hour}other {hours}}
</message>
+ <message desc="Appends language in front of content." name="IDS_CHROMEVOX_LANGUAGE_SWITCH">
+ <ph name="language">$1<ex>English</ex></ph>: <ph name="content">$2<ex>This is example content</ex></ph>
+ </message>
</messages>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/chromeos/internet_detail_dialog/BUILD.gn b/chromium/chrome/browser/resources/chromeos/internet_detail_dialog/BUILD.gn
index 5223452fb06..13434201e78 100644
--- a/chromium/chrome/browser/resources/chromeos/internet_detail_dialog/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/internet_detail_dialog/BUILD.gn
@@ -24,10 +24,12 @@ js_type_check("closure_compile") {
js_library("internet_detail_dialog") {
deps = [
+ "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior",
"//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types",
"//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior",
"//ui/webui/resources/js:assert",
"//ui/webui/resources/js:i18n_behavior",
+ "//ui/webui/resources/js/chromeos:onc_mojo",
]
externs_list = [
"$externs_path/chrome_send.js",
diff --git a/chromium/chrome/browser/resources/chromeos/kiosk_next_home/BUILD.gn b/chromium/chrome/browser/resources/chromeos/kiosk_next_home/BUILD.gn
deleted file mode 100644
index 9d5a109d980..00000000000
--- a/chromium/chrome/browser/resources/chromeos/kiosk_next_home/BUILD.gn
+++ /dev/null
@@ -1,29 +0,0 @@
-# Copyright 2019 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import("//third_party/closure_compiler/compile_js.gni")
-
-js_type_check("closure_compile") {
- deps = [
- ":kiosk_next_api",
- ]
-}
-
-js_library("kiosk_next_api") {
- sources = [
- "api.js",
- "api_impl.js",
- ]
- externs_list = [ "$externs_path/arc_apps_private.js" ]
- deps = [
- "//chrome/browser/chromeos/kiosk_next_home/mojom:mojom_js_library_for_compile",
- ]
-}
-
-js_binary("mojom_bin") {
- sources = []
- deps = [
- "//chrome/browser/chromeos/kiosk_next_home/mojom:mojom_js_library_for_compile",
- ]
-}
diff --git a/chromium/chrome/browser/resources/chromeos/kiosk_next_home/kiosk_next_resources.grdp b/chromium/chrome/browser/resources/chromeos/kiosk_next_home/kiosk_next_resources.grdp
deleted file mode 100644
index 2d95a4814a5..00000000000
--- a/chromium/chrome/browser/resources/chromeos/kiosk_next_home/kiosk_next_resources.grdp
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<grit-part>
- <if expr="_google_chrome">
- <then>
- <include name="IDR_KIOSK_NEXT_BG_JS" file="chromeos/kiosk_next_home/bg_internal.js" type="BINDATA" />
- <include name="IDR_KIOSK_NEXT_MAIN_HTML" file="chromeos/kiosk_next_home/internal/main.html" type="chrome_html" />
- </then>
- <else>
- <include name="IDR_KIOSK_NEXT_BG_JS" file="chromeos/kiosk_next_home/bg.js" type="BINDATA" />
- <include name="IDR_KIOSK_NEXT_MAIN_HTML" file="chromeos/kiosk_next_home/main.html" type="chrome_html" />
- </else>
- </if>
- <include name="IDR_KIOSK_NEXT_ICON_192" file="chromeos/kiosk_next_home/static/icon192.png" type="BINDATA" />
- <include name="IDR_KIOSK_NEXT_API_JS" file="chromeos/kiosk_next_home/api.js" type="BINDATA" />
- <include name="IDR_KIOSK_NEXT_API_IMPL_JS" file="chromeos/kiosk_next_home/api_impl.js" type="BINDATA" />
- <include name="IDR_KIOSK_NEXT_HOME_MOJOM_JS" file="${root_gen_dir}/chrome/browser/resources/chromeos/kiosk_next_home/mojom_bin.js" type="BINDATA" use_base_dir="false" />
-</grit-part>
diff --git a/chromium/chrome/browser/resources/chromeos/kiosk_next_home/manifest.json b/chromium/chrome/browser/resources/chromeos/kiosk_next_home/manifest.json
deleted file mode 100644
index f1a4295b574..00000000000
--- a/chromium/chrome/browser/resources/chromeos/kiosk_next_home/manifest.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- // chrome-extension://nbaolgedfgoedkjbfmpediclncanmpbc/
- "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq8KnOSFXgBTWY7w+jQ/T1kPD9r821cEgvPdcot2XBdA2OVF2+TJjyLmLRa/AVQzpsMrEWzPbbXSil+GFjWsiWzcohuLphMQe5pHzRVXd19ouJZNr+KL16/e74fZ77ECI9R/D0Vh6it/QICdCaLgHbjWo2AS7vhJGtp2GJcWpXG5sbG8W8BDayY5qySwAE35dFjpeeR0bDTz44+9LFE0s+sd65LDwn37nc+pJvDNNYipGP2lYC9eMk1wAydz9x3c2iYRzcGyHjbX1Z7gQvM4w8Amdjsb8f5mZeXGNKE+gvcD7kyiR7rXgK1EfaNvDCzl/uIXXPfIh5oUK9iUkdX6oNwIDAQAB",
- "name": "Kiosk Next Home",
- "version": "0.1.0",
- "manifest_version": 2,
- "description": "Kiosk Next Home",
- "display_in_launcher": false,
- "icons": {
- "192": "static/icon192.png"
- },
- "permissions": [
- "https://*.googleapis.com",
- "chrome://app-icon/",
- "mojoPrivate"
- ],
- "app": {
- "background": {
- "scripts": ["bg.js"]
- },
- "content_security_policy": "script-src 'self'; object-src 'self'; img-src 'self' data: https://lh3.googleusercontent.com chrome://app-icon"
- }
-}
diff --git a/chromium/chrome/browser/resources/chromeos/login/BUILD.gn b/chromium/chrome/browser/resources/chromeos/login/BUILD.gn
index 2a0fda62ae5..16625518952 100644
--- a/chromium/chrome/browser/resources/chromeos/login/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/login/BUILD.gn
@@ -34,7 +34,6 @@ js_type_check("closure_compile") {
":oobe_buttons",
":oobe_change_picture",
":oobe_dialog",
- ":oobe_enrollment",
":oobe_eula",
":oobe_i18n_dropdown",
":oobe_network",
@@ -53,20 +52,6 @@ js_type_check("closure_compile") {
]
}
-# We need to keep the supervision_onboarding compilation separate from the main
-# target since they depend on incompatible extern files.
-#
-# The main compilation target bundles the networking_private.js externs, it
-# gets that transitively from its :network_select_login dep.
-#
-# Supervision needs the chrome_extensions.js extern, but they end up declaring
-# the same types, so compilation fails.
-js_type_check("closure_compile_supervision") {
- deps = [
- ":supervision_onboarding",
- ]
-}
-
js2gtest("login_unitjs_tests") {
# These could be unit tests, except they need a browser context in order
# to construct a DOMParser object - so they are webui tests.
@@ -160,20 +145,6 @@ js_library("multidevice_setup_first_run") {
]
}
-js_library("supervision_onboarding") {
- deps = [
- ":login_screen_behavior",
- ":oobe_dialog_host_behavior",
- "//chrome/browser/chromeos/supervision/mojom:mojom_js_library_for_compile",
- "//ui/webui/resources/js:cr",
- ]
-
- externs_list = [
- "$externs_path/chrome_extensions.js",
- "$externs_path/webview_tag.js",
- ]
-}
-
js_library("active_directory_password_change") {
}
@@ -264,6 +235,7 @@ js_library("network_select_login") {
deps = [
"//ui/webui/resources/cr_elements/chromeos/network:cr_network_select",
"//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types",
+ "//ui/webui/resources/js/chromeos:onc_mojo",
]
}
@@ -286,12 +258,6 @@ js_library("oobe_buttons") {
js_library("oobe_dialog") {
}
-js_library("oobe_enrollment") {
- deps = [
- "//ui/webui/resources/js:i18n_behavior",
- ]
-}
-
js_library("oobe_eula") {
deps = [
":oobe_dialog_host_behavior",
diff --git a/chromium/chrome/browser/resources/chromeos/network_ui/BUILD.gn b/chromium/chrome/browser/resources/chromeos/network_ui/BUILD.gn
index 7f938a87a77..199569c5a92 100644
--- a/chromium/chrome/browser/resources/chromeos/network_ui/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/network_ui/BUILD.gn
@@ -12,10 +12,13 @@ js_type_check("closure_compile") {
js_library("network_ui") {
deps = [
+ "//chromeos/services/network_config/public/mojom:mojom_js_library_for_compile",
+ "//ui/webui/resources/cr_components/chromeos/network:mojo_interface_provider",
"//ui/webui/resources/cr_elements/chromeos/network:cr_network_icon",
"//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types",
"//ui/webui/resources/js:load_time_data",
"//ui/webui/resources/js:util",
+ "//ui/webui/resources/js/chromeos:onc_mojo",
]
externs_list = [ "$externs_path/networking_private.js" ]
}
diff --git a/chromium/chrome/browser/resources/chromeos/select_to_speak/BUILD.gn b/chromium/chrome/browser/resources/chromeos/select_to_speak/BUILD.gn
index 4c55ed58a77..e73875affca 100644
--- a/chromium/chrome/browser/resources/chromeos/select_to_speak/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/select_to_speak/BUILD.gn
@@ -58,7 +58,7 @@ run_jsbundler("select_to_speak_copied_files") {
]
}
-# TODO: refactor this into another file like generate_manifest.gni
+# TODO(crbug/978200): refactor this into another file like generate_manifest.gni
# to share with other extensions.
template("manifest") {
version_file = "//chrome/VERSION"
diff --git a/chromium/chrome/browser/resources/chromeos/switch_access/BUILD.gn b/chromium/chrome/browser/resources/chromeos/switch_access/BUILD.gn
index dd881a9af7b..33cef10b2fc 100644
--- a/chromium/chrome/browser/resources/chromeos/switch_access/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/switch_access/BUILD.gn
@@ -40,7 +40,15 @@ run_jsbundler("switch_access_copied_files") {
"icons/decrement.svg",
"icons/dictation.svg",
"icons/increment.svg",
+ "icons/jumpToBeginningOfText.svg",
+ "icons/jumpToEndOfText.svg",
"icons/keyboard.svg",
+ "icons/moveBackwardOneCharOfText.svg",
+ "icons/moveBackwardOneWordOfText.svg",
+ "icons/moveDownOneLineOfText.svg",
+ "icons/moveForwardOneCharOfText.svg",
+ "icons/moveForwardOneWordOfText.svg",
+ "icons/moveUpOneLineOfText.svg",
"icons/options.svg",
"icons/scrollDownOrForward.svg",
"icons/scrollLeft.svg",
@@ -48,6 +56,8 @@ run_jsbundler("switch_access_copied_files") {
"icons/scrollUpOrBackward.svg",
"icons/select.svg",
"icons/showContextMenu.svg",
+ "icons/textSelectionEnd.svg",
+ "icons/textSelectionStart.svg",
"key_event_handler.js",
"menu_manager.js",
"menu_panel.css",
@@ -64,6 +74,7 @@ run_jsbundler("switch_access_copied_files") {
"switch_access_constants.js",
"switch_access_predicate.js",
"text_input_manager.js",
+ "text_navigation_manager.js",
]
rewrite_rules = [
rebase_path(".", root_build_dir) + ":",
@@ -97,6 +108,7 @@ js2gtest("switch_access_extjs_tests") {
"auto_scan_manager_test.extjs",
"navigation_manager_test.extjs",
"switch_access_predicate_test.extjs",
+ "text_navigation_manager_test.extjs",
]
gen_include_files = [
"../chromevox/testing/callback_helper.js",
@@ -115,7 +127,7 @@ js2gtest("switch_access_extjs_tests") {
defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ]
}
-# TODO: refactor this into another file like generate_manifest.gni
+# TODO(crbug/978200): refactor this into another file like generate_manifest.gni
# to share with other extensions.
template("manifest") {
version_file = "//chrome/VERSION"
@@ -175,6 +187,7 @@ js_type_check("closure_compile") {
":switch_access_interface",
":switch_access_predicate",
":text_input_manager",
+ ":text_navigation_manager",
"../chromevox:constants",
"../chromevox:tree_walker",
"../select_to_speak:closure_shim",
@@ -196,6 +209,7 @@ js_library("navigation_manager") {
":switch_access_constants",
":switch_access_predicate",
":text_input_manager",
+ ":text_navigation_manager",
"../chromevox:constants",
"../chromevox:tree_walker",
]
@@ -282,6 +296,7 @@ js_library("switch_access") {
externs_list = [
"$externs_path/automation.js",
"$externs_path/chrome_extensions.js",
+ "$externs_path/command_line_private.js",
]
}
@@ -301,3 +316,10 @@ js_library("switch_access_predicate") {
js_library("text_input_manager") {
externs_list = [ "$externs_path/accessibility_private.js" ]
}
+
+js_library("text_navigation_manager") {
+ deps = [
+ ":switch_access_constants",
+ ]
+ externs_list = [ "$externs_path/accessibility_private.js" ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/switch_access/strings/switch_access_strings.grd b/chromium/chrome/browser/resources/chromeos/switch_access/strings/switch_access_strings.grd
index f80a3094f30..637e823fe73 100644
--- a/chromium/chrome/browser/resources/chromeos/switch_access/strings/switch_access_strings.grd
+++ b/chromium/chrome/browser/resources/chromeos/switch_access/strings/switch_access_strings.grd
@@ -162,8 +162,36 @@
<message desc="The Switch Access action to open the Switch Access settings page. Should be short." name="IDS_SWITCH_ACCESS_SETTINGS_ACTION">
Settings
</message>
+ <message desc="The Switch Access action for moving the text caret to the beginning of the text element." name="IDS_SWITCH_ACCESS_JUMP_TO_BEGINNING_OF_TEXT">
+ Jump to beginning
+ </message>
+ <message desc="The Switch Access action for moving the text caret to the end of the text element." name="IDS_SWITCH_ACCESS_JUMP_TO_END_OF_TEXT">
+ Jump to end
+ </message>
+ <message desc="The Switch Access action for moving the text caret backward one character." name="IDS_SWITCH_ACCESS_MOVE_BACKWARD_ONE_CHAR_OF_TEXT">
+ Move backward one char
+ </message>
+ <message desc="The Switch Access action for moving the text caret backward one word." name="IDS_SWITCH_ACCESS_MOVE_BACKWARD_ONE_WORD_OF_TEXT">
+ Move backward one word
+ </message>
+ <message desc="The Switch Access action for moving the text caret forward one character." name="IDS_SWITCH_ACCESS_MOVE_FORWARD_ONE_CHAR_OF_TEXT">
+ Move forward one char
+ </message>
+ <message desc="The Switch Access action for moving the text caret forward one word." name="IDS_SWITCH_ACCESS_MOVE_FORWARD_ONE_WORD_OF_TEXT">
+ Move forward one word
+ </message>
+ <message desc="The Switch Access action for moving the text caret down one line." name="IDS_SWITCH_ACCESS_MOVE_DOWN_ONE_LINE_OF_TEXT">
+ Move down one line
+ </message>
+ <message desc="The Switch Access action for moving the text caret up one line." name="IDS_SWITCH_ACCESS_MOVE_UP_ONE_LINE_OF_TEXT">
+ Move up one line
+ </message>
+ <message desc="The Switch Access action to set the beginning of a text selection area." name="IDS_SWITCH_ACCESS_SELECTION_START">
+ Selection start
+ </message>
+ <message desc="The Switch Access action to set the end of a text selection area." name="IDS_SWITCH_ACCESS_SELECTION_END">
+ Selection end
+ </message>
</messages>
</release>
</grit>
-
-
diff --git a/chromium/chrome/browser/resources/component_extension_resources.grd b/chromium/chrome/browser/resources/component_extension_resources.grd
index 83d54e25db7..21fb200503d 100644
--- a/chromium/chrome/browser/resources/component_extension_resources.grd
+++ b/chromium/chrome/browser/resources/component_extension_resources.grd
@@ -91,9 +91,6 @@
<include name="IDR_ARC_SUPPORT_ICON_HEADER" file="chromeos/arc_support/images/header.png" type="BINDATA" />
<include name="IDR_ARC_SUPPORT_RECOMMEND_APP_LIST_VIEW_JS" file="chromeos/arc_support/recommend_app_list_view.js" type="BINDATA" />
<include name="IDR_ARC_SUPPORT_RECOMMEND_APP_LIST_VIEW_HTML" file="chromeos/arc_support/recommend_app_list_view.html" type="chrome_html" flattenhtml="true" />
- <if expr="_kiosk_next">
- <part file="chromeos/kiosk_next_home/kiosk_next_resources.grdp" />
- </if>
</if>
<if expr="enable_plugins">
<!-- Note that resources included here also must be included in
diff --git a/chromium/chrome/browser/resources/cryptotoken/enroller.js b/chromium/chrome/browser/resources/cryptotoken/enroller.js
index 239721a3980..4fb1bef7c44 100644
--- a/chromium/chrome/browser/resources/cryptotoken/enroller.js
+++ b/chromium/chrome/browser/resources/cryptotoken/enroller.js
@@ -111,14 +111,6 @@ async function makeCertAndKey(opt_original) {
if (opt_original) {
transport = transportType(opt_original);
}
- if (transport !== null) {
- if (transport.length != 2) {
- throw Error('bad extension length');
- }
- if (transport[0] < 3) {
- throw Error('too many bits set'); // Only 5 bits are defined.
- }
- }
const keyalg = {name: 'ECDSA', namedCurve: 'P-256'};
const keypair =
diff --git a/chromium/chrome/browser/resources/default_apps/OWNERS b/chromium/chrome/browser/resources/default_apps/OWNERS
deleted file mode 100644
index c35595ced3f..00000000000
--- a/chromium/chrome/browser/resources/default_apps/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-asargent@chromium.org
diff --git a/chromium/chrome/browser/resources/device_log_ui/device_log_ui.html b/chromium/chrome/browser/resources/device_log_ui/device_log_ui.html
index 7bbd71e5a1e..d0724135998 100644
--- a/chromium/chrome/browser/resources/device_log_ui/device_log_ui.html
+++ b/chromium/chrome/browser/resources/device_log_ui/device_log_ui.html
@@ -16,6 +16,7 @@
</div>
<div id="log-checkbox-container">
<button id="log-refresh">$i18n{logRefreshText}</button>
+ <button id="log-clear">$i18n{logClearText}</button>
<label id="log-checkbox-show">$i18n{logLevelShowText}</label>
<label>
<input id="log-level-error" type="checkbox">
diff --git a/chromium/chrome/browser/resources/device_log_ui/device_log_ui.js b/chromium/chrome/browser/resources/device_log_ui/device_log_ui.js
index 24be02b292d..11103072caa 100644
--- a/chromium/chrome/browser/resources/device_log_ui/device_log_ui.js
+++ b/chromium/chrome/browser/resources/device_log_ui/device_log_ui.js
@@ -97,11 +97,14 @@ const DeviceLogUI = (function() {
* @param {Object} data A JSON structure of event log entries.
*/
const getLogCallback = function(data) {
+ const container = $('log-container');
try {
createEventLog(JSON.parse(data));
+ if (container.textContent == '') {
+ container.textContent = loadTimeData.getString('logNoEntriesText');
+ }
} catch (e) {
- const container = $('log-container');
- container.textContent = 'No log entries';
+ container.textContent = loadTimeData.getString('logNoEntriesText');
}
};
@@ -112,6 +115,11 @@ const DeviceLogUI = (function() {
chrome.send('DeviceLog.getLog');
};
+ const clearLog = function() {
+ chrome.send('DeviceLog.clearLog');
+ requestLog();
+ };
+
/**
* Sets refresh rate if the interval is found in the url.
*/
@@ -143,6 +151,7 @@ const DeviceLogUI = (function() {
$('log-timedetail').checked = false;
$('log-refresh').onclick = requestLog;
+ $('log-clear').onclick = clearLog;
checkboxes = document.querySelectorAll(
'#log-checkbox-container input[type="checkbox"]');
for (let i = 0; i < checkboxes.length; ++i) {
diff --git a/chromium/chrome/browser/resources/discards/database_tab.js b/chromium/chrome/browser/resources/discards/database_tab.js
index 34a58d7d404..1fc56fbba26 100644
--- a/chromium/chrome/browser/resources/discards/database_tab.js
+++ b/chromium/chrome/browser/resources/discards/database_tab.js
@@ -227,14 +227,14 @@ Polymer({
/** @private {!Object} */
requestedOrigins_: {},
- /** @private {?mojom.DiscardsDetailsProviderProxy} */
- uiHandler_: null,
+ /** @private {?mojom.DiscardsDetailsProviderRemote} */
+ discardsDetailsProvider_: null,
/** @override */
ready: function() {
this.setSortKey('origin');
this.requestedOrigins_ = {};
- this.uiHandler_ = discards.getOrCreateUiHandler();
+ this.discardsDetailsProvider_ = discards.getOrCreateDetailsProvider();
// Specifies the update interval of the table, in ms.
const UPDATE_INTERVAL_MS = 1000;
@@ -267,7 +267,7 @@ Polymer({
* @private
*/
updateDbRows_: function() {
- this.uiHandler_
+ this.discardsDetailsProvider_
.getSiteCharacteristicsDatabase(Object.keys(this.requestedOrigins_))
.then(response => {
// Bail if the SiteCharacteristicsDatabase is turned off.
@@ -322,13 +322,14 @@ Polymer({
* @private
*/
updateDbSizes_: function() {
- this.uiHandler_.getSiteCharacteristicsDatabaseSize().then(response => {
- // Bail if the SiteCharacteristicsDatabase is turned off.
- if (!response.dbSize) {
- return;
- }
- this.size_ = response.dbSize;
- });
+ this.discardsDetailsProvider_.getSiteCharacteristicsDatabaseSize().then(
+ response => {
+ // Bail if the SiteCharacteristicsDatabase is turned off.
+ if (!response.dbSize) {
+ return;
+ }
+ this.size_ = response.dbSize;
+ });
},
/**
diff --git a/chromium/chrome/browser/resources/discards/discards.js b/chromium/chrome/browser/resources/discards/discards.js
index f6764687c12..1e8740a01f1 100644
--- a/chromium/chrome/browser/resources/discards/discards.js
+++ b/chromium/chrome/browser/resources/discards/discards.js
@@ -6,17 +6,17 @@ cr.define('discards', function() {
'use strict';
// The following variables are initialized by 'initialize'.
- // Points to the Mojo WebUI handler.
- let uiHandler;
+ // Points to the DiscardsDetailsProviderRemote.
+ let discardsDetailsProvider;
/**
- * @return {!mojom.DiscardsDetailsProviderProxy} The UI handler.
+ * @return {!mojom.DiscardsDetailsProviderRemote} Provides discards details.
*/
- function getOrCreateUiHandler() {
- if (!uiHandler) {
- uiHandler = mojom.DiscardsDetailsProvider.getProxy();
+ function getOrCreateDetailsProvider() {
+ if (!discardsDetailsProvider) {
+ discardsDetailsProvider = mojom.DiscardsDetailsProvider.getRemote();
}
- return uiHandler;
+ return discardsDetailsProvider;
}
/**
@@ -122,7 +122,7 @@ cr.define('discards', function() {
return {
boolToString: boolToString,
durationToString: durationToString,
- getOrCreateUiHandler: getOrCreateUiHandler,
+ getOrCreateDetailsProvider: getOrCreateDetailsProvider,
maybeMakePlural: maybeMakePlural,
secondsToString: secondsToString
};
diff --git a/chromium/chrome/browser/resources/discards/discards_tab.html b/chromium/chrome/browser/resources/discards/discards_tab.html
index da52398a996..9f8b78828b3 100644
--- a/chromium/chrome/browser/resources/discards/discards_tab.html
+++ b/chromium/chrome/browser/resources/discards/discards_tab.html
@@ -9,7 +9,7 @@ general use and is not localized.
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/icon.html">
diff --git a/chromium/chrome/browser/resources/discards/discards_tab.js b/chromium/chrome/browser/resources/discards/discards_tab.js
index 24bed7a9f77..fd729e3119a 100644
--- a/chromium/chrome/browser/resources/discards/discards_tab.js
+++ b/chromium/chrome/browser/resources/discards/discards_tab.js
@@ -99,13 +99,13 @@ Polymer({
/** @private The current update timer if any. */
updateTimer_: 0,
- /** @private {(mojom.DiscardsDetailsProviderProxy|null)} */
- uiHandler_: null,
+ /** @private {(mojom.DiscardsDetailsProviderRemote|null)} */
+ discardsDetailsProvider_: null,
/** @override */
ready: function() {
this.setSortKey('utilityRank');
- this.uiHandler_ = discards.getOrCreateUiHandler();
+ this.discardsDetailsProvider_ = discards.getOrCreateDetailsProvider();
this.updateTable_();
},
@@ -198,11 +198,14 @@ Polymer({
* is only used if the state is discard related.
* @param {mojom.LifecycleUnitVisibility} visibility A visibility value.
* @param {boolean} hasFocus Whether or not the tab has input focus.
+ * @param {mojoBase.mojom.TimeDelta} stateChangeTime Delta between Unix Epoch
+ * and time at which the lifecycle state has changed.
* @return {string} A string representation of the lifecycle state, augmented
* with the discard reason if appropriate.
* @private
*/
- lifecycleStateToString_: function(state, reason, visibility, hasFocus) {
+ lifecycleStateToString_: function(
+ state, reason, visibility, hasFocus, stateChangeTime) {
const pageLifecycleStateFromVisibilityAndFocus = function() {
switch (visibility) {
case mojom.LifecycleUnitVisibility.HIDDEN:
@@ -228,7 +231,12 @@ Polymer({
return pageLifecycleStateFromVisibilityAndFocus() +
' (pending discard (' + this.discardReasonToString_(reason) + '))';
case mojom.LifecycleUnitState.DISCARDED:
- return 'discarded (' + this.discardReasonToString_(reason) + ')';
+ return 'discarded (' + this.discardReasonToString_(reason) + ')' +
+ ((reason == mojom.LifecycleUnitDiscardReason.URGENT) ? ' at ' +
+ // Must convert since Date constructor takes milliseconds.
+ (new Date(stateChangeTime.microseconds / 1000))
+ .toLocaleString() :
+ '');
case mojom.LifecycleUnitState.PENDING_UNFREEZE:
return 'frozen (pending unfreeze)';
}
@@ -240,7 +248,7 @@ Polymer({
* @private
*/
updateTableImpl_: function() {
- this.uiHandler_.getTabDiscardsInfo().then(response => {
+ this.discardsDetailsProvider_.getTabDiscardsInfo().then(response => {
this.tabInfos_ = response.infos;
});
},
@@ -287,7 +295,7 @@ Polymer({
* @private
*/
getFavIconStyle_: function(item) {
- return 'background-image:' + cr.icon.getFavicon(item.tabUrl);
+ return 'background-image:' + cr.icon.getFavicon(item.tabUrl, false);
},
/**
@@ -300,7 +308,8 @@ Polymer({
if (item.loadingState != mojom.LifecycleUnitLoadingState.UNLOADED ||
item.discardCount > 0) {
return this.lifecycleStateToString_(
- item.state, item.discardReason, item.visibility, item.hasFocus);
+ item.state, item.discardReason, item.visibility, item.hasFocus,
+ item.stateChangeTime);
} else {
return '';
}
@@ -405,7 +414,8 @@ Polymer({
*/
toggleAutoDiscardable_: function(e) {
const item = e.model.item;
- this.uiHandler_.setAutoDiscardable(item.id, !item.isAutoDiscardable)
+ this.discardsDetailsProvider_
+ .setAutoDiscardable(item.id, !item.isAutoDiscardable)
.then(this.updateTable_.bind(this));
},
@@ -415,7 +425,7 @@ Polymer({
* @private
*/
loadTab_: function(e) {
- this.uiHandler_.loadById(e.model.item.id);
+ this.discardsDetailsProvider_.loadById(e.model.item.id);
},
/**
@@ -424,7 +434,7 @@ Polymer({
* @private
*/
freezeTab_: function(e) {
- this.uiHandler_.freezeById(e.model.item.id);
+ this.discardsDetailsProvider_.freezeById(e.model.item.id);
},
/**
@@ -434,7 +444,7 @@ Polymer({
* @private
*/
discardTabImpl_: function(e, urgent) {
- this.uiHandler_.discardById(e.model.item.id, urgent)
+ this.discardsDetailsProvider_.discardById(e.model.item.id, urgent)
.then(this.updateTable_.bind(this));
},
@@ -462,7 +472,7 @@ Polymer({
* @private
*/
discardImpl_: function(urgent) {
- this.uiHandler_.discard(urgent).then(() => {
+ this.discardsDetailsProvider_.discard(urgent).then(() => {
this.updateTable_();
});
},
diff --git a/chromium/chrome/browser/resources/discards/graph_tab.js b/chromium/chrome/browser/resources/discards/graph_tab.js
index 0231a77222e..c4538c5718f 100644
--- a/chromium/chrome/browser/resources/discards/graph_tab.js
+++ b/chromium/chrome/browser/resources/discards/graph_tab.js
@@ -72,7 +72,7 @@ Polymer({
/**
* The Mojo graph data source.
*
- * @private {performanceManager.mojom.WebUIGraphDumpProxy}
+ * @private {performanceManager.mojom.WebUIGraphDumpRemote}
*/
graphDump_: null,
@@ -85,7 +85,7 @@ Polymer({
/** @override */
ready: function() {
- this.graphDump_ = performanceManager.mojom.WebUIGraphDump.getProxy();
+ this.graphDump_ = performanceManager.mojom.WebUIGraphDump.getRemote();
},
/** @override */
@@ -99,10 +99,12 @@ Polymer({
onWebViewReady_: function() {
this.changeListener_ =
new graph_tab.WebUIGraphChangeStreamImpl(this.$.webView.contentWindow);
- const client = new performanceManager.mojom
- .WebUIGraphChangeStream(this.changeListener_)
- .createProxy();
+ this.client_ = new performanceManager.mojom.WebUIGraphChangeStreamReceiver(
+ this.changeListener_);
+ // Save helper to work around closure compiler bug: https://crbug.com/969212
+ const helper = this.client_.$;
+
// Subscribe for graph updates.
- this.graphDump_.subscribeToChanges(client);
+ this.graphDump_.subscribeToChanges(helper.bindNewPipeAndPassRemote());
},
});
diff --git a/chromium/chrome/browser/resources/domain_reliability_internals/domain_reliability_internals.html b/chromium/chrome/browser/resources/domain_reliability_internals/domain_reliability_internals.html
index 7bb2a1b8e19..10203ebccca 100644
--- a/chromium/chrome/browser/resources/domain_reliability_internals/domain_reliability_internals.html
+++ b/chromium/chrome/browser/resources/domain_reliability_internals/domain_reliability_internals.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}">
+<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
diff --git a/chromium/chrome/browser/resources/downloads/browser_proxy.js b/chromium/chrome/browser/resources/downloads/browser_proxy.js
index 7dc6c8ee49d..0d5f6f5f257 100644
--- a/chromium/chrome/browser/resources/downloads/browser_proxy.js
+++ b/chromium/chrome/browser/resources/downloads/browser_proxy.js
@@ -8,12 +8,13 @@ cr.define('downloads', function() {
/** @type {downloads.mojom.PageCallbackRouter} */
this.callbackRouter = new downloads.mojom.PageCallbackRouter();
- /** @type {downloads.mojom.PageHandlerProxy} */
- this.handler = new downloads.mojom.PageHandlerProxy();
+ /** @type {downloads.mojom.PageHandlerRemote} */
+ this.handler = new downloads.mojom.PageHandlerRemote();
- const factory = downloads.mojom.PageHandlerFactory.getProxy();
+ const factory = downloads.mojom.PageHandlerFactory.getRemote();
factory.createPageHandler(
- this.callbackRouter.createProxy(), this.handler.$.createRequest());
+ this.callbackRouter.$.bindNewPipeAndPassRemote(),
+ this.handler.$.bindNewPipeAndPassReceiver());
}
}
diff --git a/chromium/chrome/browser/resources/downloads/downloads.html b/chromium/chrome/browser/resources/downloads/downloads.html
index 05a625d0f34..ad88272334d 100644
--- a/chromium/chrome/browser/resources/downloads/downloads.html
+++ b/chromium/chrome/browser/resources/downloads/downloads.html
@@ -1,6 +1,5 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading"
- $i18n{dark}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading">
<head>
<meta charset="utf-8">
<if expr="not optimize_webui">
@@ -53,6 +52,5 @@
<link rel="import" href="i18n_setup.html">
<link rel="import" href="manager.html">
<script src="downloads.js"></script>
- <link rel="import" href="chrome://resources/html/dark_mode.html">
</body>
</html>
diff --git a/chromium/chrome/browser/resources/downloads/item.html b/chromium/chrome/browser/resources/downloads/item.html
index 4534ece186a..16252c86252 100644
--- a/chromium/chrome/browser/resources/downloads/item.html
+++ b/chromium/chrome/browser/resources/downloads/item.html
@@ -5,27 +5,26 @@
<link rel="import" href="i18n_setup.html">
<link rel="import" href="icon_loader.html">
<link rel="import" href="icons.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast_manager.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_row.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_row_behavior.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-progress/paper-progress.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<dom-module id="downloads-item">
<template>
- <style include="action-link cr-hidden-style cr-icons paper-button-style">
+ <style include="action-link cr-hidden-style cr-icons">
:host {
--controlled-by-active-color: #333;
--controlled-by-active-link-color: var(--google-blue-600);
@@ -35,13 +34,15 @@
outline: none;
}
- :host-context([dark]) {
- --controlled-by-active-color: inherit;
- --controlled-by-active-link-color: var(--cr-link-color);
- --controlled-by-inactive-color: inherit;
+ @media (prefers-color-scheme: dark) {
+ :host {
+ --controlled-by-active-color: inherit;
+ --controlled-by-active-link-color: var(--cr-link-color);
+ --controlled-by-inactive-color: inherit;
+ }
}
- paper-button {
+ cr-button {
font-weight: 500;
margin: 0;
min-width: auto;
@@ -75,8 +76,10 @@
@apply --cr-card-elevation;
}
- :host-context(html:not([dark])) #content.is-active {
- background-color: var(--cr-card-background-color);
+ @media (prefers-color-scheme: light) {
+ #content.is-active {
+ background-color: var(--cr-card-background-color);
+ }
}
#content:not(.is-active) {
@@ -84,9 +87,11 @@
border: 1px var(--google-grey-300) solid;
}
- :host-context([dark]) #content:not(.is-active) {
- background: none; /* override */
- border-color: var(--google-grey-800);
+ @media (prefers-color-scheme: dark) {
+ #content:not(.is-active) {
+ background: none; /* override */
+ border-color: var(--google-grey-800);
+ }
}
#details {
@@ -101,24 +106,30 @@
padding-top: 16px;
}
- :host-context([dark]) #details {
- border-color: rgba(var(--google-grey-800-rgb), .8);
+ @media (prefers-color-scheme: dark) {
+ #details {
+ border-color: rgba(var(--google-grey-800-rgb), .8);
+ }
}
#content:not(.is-active) #details {
color: rgba(27, 27, 27, .6);
}
- :host-context([dark]) #content:not(.is-active) #details {
- color: rgba(var(--google-grey-refresh-500-rgb), .6);
+ @media (prefers-color-scheme: dark) {
+ #content:not(.is-active) #details {
+ color: rgba(var(--google-grey-refresh-500-rgb), .6);
+ }
}
#content:not(.is-active) #name {
text-decoration: line-through;
}
- :host-context([dark]) #content:not(.is-active) :-webkit-any(#name, #tag) {
- color: var(--google-grey-refresh-500);
+ @media (prefers-color-scheme: dark) {
+ #content:not(.is-active) :-webkit-any(#name, #tag) {
+ color: var(--google-grey-refresh-500);
+ }
}
.icon-wrapper {
@@ -164,9 +175,11 @@
color: var(--google-yellow-500);
}
- :host-context([dark]) #file-icon-wrapper iron-icon[icon='cr:warning'],
- :host-context([dark]) .dangerous #description {
- color: var(--google-red-refresh-300);
+ @media (prefers-color-scheme: dark) {
+ #file-icon-wrapper iron-icon[icon='cr:warning'],
+ .dangerous #description {
+ color: var(--google-red-refresh-300);
+ }
}
#name,
@@ -181,9 +194,10 @@
word-break: break-all;
}
- :host-context(html:not([dark])) .is-active
- :-webkit-any(#name, #file-link, #show) {
- color: var(--google-blue-600);
+ @media (prefers-color-scheme: light) {
+ .is-active :-webkit-any(#name, #file-link, #show) {
+ color: var(--google-blue-600);
+ }
}
#name {
@@ -215,8 +229,10 @@
margin-top: 16px;
}
- :host-context(html:not([dark])) .is-active #description {
- color: #616161;
+ @media (prefers-color-scheme: light) {
+ .is-active #description {
+ color: #616161;
+ }
}
#progress {
@@ -226,9 +242,11 @@
width: auto;
}
- :host-context([dark]) #progress {
- --paper-progress-active-color: var(--google-blue-refresh-300);
- --paper-progress-container-color: var(--google-grey-800);
+ @media (prefers-color-scheme: dark) {
+ #progress {
+ --paper-progress-active-color: var(--google-blue-refresh-300);
+ --paper-progress-container-color: var(--google-grey-800);
+ }
}
#show {
@@ -326,22 +344,22 @@
hidden="[[!completelyOnDisk_]]" focus-row-control
focus-type="show">$i18n{controlShowInFolder}</a>
<template is="dom-if" if="[[data.retry]]">
- <paper-button class="action-button" on-click="onRetryTap_"
+ <cr-button class="action-button" on-click="onRetryTap_"
focus-row-control focus-type="retry">
$i18n{controlRetry}
- </paper-button>
+ </cr-button>
</template>
<template is="dom-if" if="[[pauseOrResumeText_]]">
- <paper-button on-click="onPauseOrResumeTap_" id="pauseOrResume"
+ <cr-button on-click="onPauseOrResumeTap_" id="pauseOrResume"
focus-row-control focus-type="pauseOrResume">
[[pauseOrResumeText_]]
- </paper-button>
+ </cr-button>
</template>
<template is="dom-if" if="[[showCancel_]]">
- <paper-button on-click="onCancelTap_" focus-row-control
+ <cr-button on-click="onCancelTap_" focus-row-control
focus-type="cancel">
$i18n{controlCancel}
- </paper-button>
+ </cr-button>
</template>
<span id="controlled-by"><!-- Text populated dynamically. --></span>
</div>
@@ -350,22 +368,22 @@
<div id="dangerous" class="controls">
<!-- Dangerous file types (e.g. .exe, .jar). -->
<template is="dom-if" if="[[!isMalware_]]">
- <paper-button on-click="onDiscardDangerousTap_"
+ <cr-button on-click="onDiscardDangerousTap_"
class="action-button" focus-row-control
- focus-type="discard">$i18n{dangerDiscard}</paper-button>
- <paper-button on-click="onSaveDangerousTap_" focus-row-control
+ focus-type="discard">$i18n{dangerDiscard}</cr-button>
+ <cr-button on-click="onSaveDangerousTap_" focus-row-control
focus-type="save">
- $i18n{dangerSave}</paper-button>
+ $i18n{dangerSave}</cr-button>
</template>
<!-- Things that safe browsing has determined to be dangerous. -->
<template is="dom-if" if="[[isMalware_]]">
- <paper-button on-click="onDiscardDangerousTap_"
+ <cr-button on-click="onDiscardDangerousTap_"
class="action-button" focus-row-control focus-type="discard">
- $i18n{controlRemoveFromList}</paper-button>
- <paper-button on-click="onSaveDangerousTap_" focus-row-control
+ $i18n{controlRemoveFromList}</cr-button>
+ <cr-button on-click="onSaveDangerousTap_" focus-row-control
focus-type="save">
- $i18n{dangerRestore}</paper-button>
+ $i18n{dangerRestore}</cr-button>
</template>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/downloads/manager.html b/chromium/chrome/browser/resources/downloads/manager.html
index 015710be621..3415eceeeb5 100644
--- a/chromium/chrome/browser/resources/downloads/manager.html
+++ b/chromium/chrome/browser/resources/downloads/manager.html
@@ -7,8 +7,10 @@
<link rel="import" href="search_service.html">
<link rel="import" href="toolbar.html">
<link rel="import" href="chrome://resources/cr_components/managed_footnote/managed_footnote.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_page_host_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast_manager.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/cr/ui.html">
@@ -20,7 +22,7 @@
<dom-module id="downloads-manager">
<template>
- <style include="cr-hidden-style">
+ <style include="cr-page-host-style cr-shared-style cr-hidden-style">
:host {
display: flex;
flex: 1 0;
@@ -28,22 +30,18 @@
height: 100%;
overflow: hidden;
z-index: 0;
-
- @apply --cr-page-host;
}
- :host-context([dark]) {
- color: var(--cr-secondary-text-color);
+ @media (prefers-color-scheme: dark) {
+ :host {
+ color: var(--cr-secondary-text-color);
+ }
}
#toolbar {
z-index: 1;
}
- #drop-shadow {
- @apply --cr-container-shadow;
- }
-
:host([has-shadow_]) #drop-shadow {
opacity: var(--cr-container-shadow-max-opacity);
}
@@ -81,8 +79,10 @@
min-height: min-content;
}
- :host-context([dark]) #no-downloads {
- color: var(--cr-secondary-text-color);
+ @media (prefers-color-scheme: dark) {
+ #no-downloads {
+ color: var(--cr-secondary-text-color);
+ }
}
#no-downloads .illustration {
@@ -121,7 +121,7 @@
<downloads-toolbar id="toolbar" spinner-active="{{spinnerActive_}}"
role="none" on-search-changed="onSearchChanged_">
</downloads-toolbar>
- <div id="drop-shadow"></div>
+ <div id="drop-shadow" class="cr-container-shadow"></div>
<div id="mainContainer" on-scroll="onScroll_">
<managed-footnote hidden="[[inSearchMode_]]"></managed-footnote>
<iron-list id="downloadsList" items="[[items_]]"
diff --git a/chromium/chrome/browser/resources/downloads/manager.js b/chromium/chrome/browser/resources/downloads/manager.js
index f96ceede7df..f29e152fd0a 100644
--- a/chromium/chrome/browser/resources/downloads/manager.js
+++ b/chromium/chrome/browser/resources/downloads/manager.js
@@ -207,6 +207,8 @@ cr.define('downloads', function() {
*/
onCommand_: function(e) {
if (e.command.id == 'clear-all-command') {
+ cr.toastManager.getInstance().show(
+ loadTimeData.getString('toastClearedAll'), true);
this.mojoHandler_.clearAll();
} else if (e.command.id == 'undo-command') {
cr.toastManager.getInstance().hide();
diff --git a/chromium/chrome/browser/resources/downloads/toolbar.html b/chromium/chrome/browser/resources/downloads/toolbar.html
index f90470d34a8..77edf5f2c1f 100644
--- a/chromium/chrome/browser/resources/downloads/toolbar.html
+++ b/chromium/chrome/browser/resources/downloads/toolbar.html
@@ -32,8 +32,10 @@
margin: 4px;
}
- :host-context(html:not([dark])) cr-icon-button {
- --cr-icon-button-color: currentColor;
+ @media (prefers-color-scheme: light) {
+ cr-icon-button {
+ --cr-icon-button-color: currentColor;
+ }
}
</style>
<cr-toolbar id="toolbar" page-name="$i18n{title}"
diff --git a/chromium/chrome/browser/resources/engagement/site_engagement.js b/chromium/chrome/browser/resources/engagement/site_engagement.js
index f8f082492cc..39454c3d578 100644
--- a/chromium/chrome/browser/resources/engagement/site_engagement.js
+++ b/chromium/chrome/browser/resources/engagement/site_engagement.js
@@ -11,8 +11,8 @@ let whenPageIsPopulatedForTest;
/** @type {function()} */
let disableAutoupdateForTests;
-/** @type {mojom.SiteEngagementDetailsProviderProxy} */
-let uiHandler;
+/** @type {mojom.SiteEngagementDetailsProviderRemote} */
+let engagementDetailsProvider;
(function() {
let resolvePageIsPopulated = null;
@@ -25,7 +25,7 @@ whenPageIsPopulatedForTest = function() {
};
function initialize() {
- uiHandler = mojom.SiteEngagementDetailsProvider.getProxy();
+ engagementDetailsProvider = mojom.SiteEngagementDetailsProvider.getRemote();
/** @type {?HTMLElement} */
const engagementTableBody = $('engagement-table-body');
@@ -132,7 +132,8 @@ function initialize() {
*/
function handleBaseScoreChange(origin, e) {
const baseScoreInput = e.target;
- uiHandler.setSiteEngagementBaseScoreForUrl(origin, baseScoreInput.value);
+ engagementDetailsProvider.setSiteEngagementBaseScoreForUrl(
+ origin, baseScoreInput.value);
baseScoreInput.barCellRef.style.width = (baseScoreInput.value * 4) + 'px';
baseScoreInput.blur();
enableAutoupdate();
@@ -207,13 +208,11 @@ function initialize() {
/**
* Retrieve site engagement info and render the engagement table.
*/
- function updateEngagementTable() {
+ async function updateEngagementTable() {
// Populate engagement table.
- uiHandler.getSiteEngagementDetails().then((response) => {
- info = response.info;
- renderTable();
- resolvePageIsPopulated();
- });
+ ({info} = await engagementDetailsProvider.getSiteEngagementDetails());
+ renderTable();
+ resolvePageIsPopulated();
}
updateEngagementTable();
diff --git a/chromium/chrome/browser/resources/eoc_internals/BUILD.gn b/chromium/chrome/browser/resources/eoc_internals/BUILD.gn
deleted file mode 100644
index cbef167ce06..00000000000
--- a/chromium/chrome/browser/resources/eoc_internals/BUILD.gn
+++ /dev/null
@@ -1,18 +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("//third_party/closure_compiler/compile_js.gni")
-
-js_type_check("closure_compile") {
- deps = [
- ":eoc_internals",
- ]
-}
-
-js_library("eoc_internals") {
- deps = [
- "//chrome/browser/ui/webui/eoc_internals:mojo_bindings_js_library_for_compile",
- "//ui/webui/resources/js:util",
- ]
-}
diff --git a/chromium/chrome/browser/resources/eoc_internals/eoc_internals.html b/chromium/chrome/browser/resources/eoc_internals/eoc_internals.html
deleted file mode 100644
index 66eb4d65153..00000000000
--- a/chromium/chrome/browser/resources/eoc_internals/eoc_internals.html
+++ /dev/null
@@ -1,138 +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.
--->
-
-<!doctype html>
-<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>EOC Internals</title>
- <link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
- <link rel="stylesheet" href="eoc_internals.css">
-
- <script src="chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js"></script>
- <script src="chrome://resources/js/util.js"></script>
- <script src="eoc_internals.mojom-lite.js"></script>
-
- <script src="eoc_internals.js"></script>
-</head>
-
-<body>
- <div id="properties">
- <h3>Properties</h3>
- <div>
- <table class="details">
- <tr>
- <td>Fetch endpoint url</td>
- <td id="fetch-endpoint-url"></td>
- </tr>
- <tr>
- <td>Time to Trigger</td>
- <td id="time-to-trigger"></td>
- </tr>
- <tr>
- <td>Chrome flags setup correctly</td>
- <td id="chrome-flags-setup"></td>
- </tr>
- </table>
- </div>
- </div>
-
- <div id="metrics">
- <h3>Metrics</h3>
- <button id="clear-metrics">Clear metrics</button>
- <div id="metric-events">
- <!-- Templates populate here. -->
- </div>
- <template id="metric-event-template"> <!-- Use to populate metric events -->
- <div id="metric-event">
- <h4 id="url"></h4>
- <table class="details">
- <tr>
- <td>Was sheet peeked</td>
- <td id="sheet-peeked"></td>
- </tr>
- <tr>
- <td>Was button shown</td>
- <td id="button-shown"></td>
- </tr>
- <tr>
- <td>Was sheet opened</td>
- <td id="sheet-opened"></td>
- </tr>
- <tr>
- <td>Was sheet closed</td>
- <td id="sheet-closed"></td>
- </tr>
- <tr>
- <td>Any suggestion taken</td>
- <td id="any-suggestion-taken"></td>
- </tr>
- <tr>
- <td>Any suggestion downloaded</td>
- <td id="any-suggestion-downloaded"></td>
- </tr>
- </table>
- </div>
- </template>
- </div>
-
- <div>
- <h3>Cached Suggestion Results</h3>
- <button id="clear-suggestion-results">Clear suggestions</button>
- <div id="suggestion-results">
- <!-- Suggestion results go here. -->
- </div>
- <!-- Populate these to $("cached-suggestions") -->
- <template id="suggestion-template">
- <div> <!-- Holder element used for parent queries. -->
- <div id="suggestion-title"></div>
- <table id="suggestion-details" class="details" hidden>
- <tr>
- <td>Url</td>
- <td id="suggestion-url"></td>
- </tr>
- <tr>
- <td>Snippet</td>
- <td id="suggestion-snippet"></td>
- </tr>
- <tr>
- <td>Publisher name</td>
- <td id="suggestions-publisher-name"></td>
- </tr>
- </table>
- </div>
- </template>
-
- <template id="suggestion-result-template">
- <div id="suggestion-result">
- <h4 id="suggestion-result-url"></h4>
- <table class="details">
- <tr>
- <td>Peek confidence</td>
- <td id="peek-confidence"></td>
- </tr>
- <tr>
- <td>Page scroll percentage</td>
- <td id="peek-page-scroll-percentage"></td>
- </tr>
- <tr>
- <td>Minimum seconds on page</td>
- <td id="peek-min-seconds-on-page"></td>
- </tr>
- <tr>
- <td>Maximum number of peeks</td>
- <td id="peek-max-peeks"></td>
- </tr>
- </table>
- <h4>Suggestions</h4>
- <div id="cached-suggestions">
- </div>
- </div>
- </template>
- </div>
-</body>
-</html>
diff --git a/chromium/chrome/browser/resources/eoc_internals/eoc_internals.js b/chromium/chrome/browser/resources/eoc_internals/eoc_internals.js
deleted file mode 100644
index 4f36dfec9f2..00000000000
--- a/chromium/chrome/browser/resources/eoc_internals/eoc_internals.js
+++ /dev/null
@@ -1,155 +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.
-
-'use strict';
-
-/**
- * Reference to the backend.
- * @type {eocInternals.mojom.PageHandlerProxy}
- */
-let pageHandler = null;
-
-(function() {
-/* Utility functions */
-
-/**
- * Clears children of the given domId.
- * @param {string} domId Id of the DOM element to be cleared.
- */
-function clearChildrenForId(domId) {
- const parent = $(domId);
- while (parent.firstChild) {
- parent.removeChild(parent.firstChild);
- }
-}
-
-/* Backend wrapper functions */
-
-// Get the general properties.
-function updatePageWithProperties() {
- pageHandler.getProperties().then(response => {
- Object.keys(response.properties).forEach(function(field) {
- $(field).textContent = response.properties[field];
- });
- });
-}
-
-// Get the cache of metric events, and add them to the page.
-function updatePageWithCachedMetricEvents() {
- pageHandler.getCachedMetricEvents().then(response => {
- const metricContainerId = 'metric-events';
- clearChildrenForId(metricContainerId);
- addCachedMetricEventsToPage(response.metrics);
- });
-}
-
-// Add the metric events to the page.
-function addCachedMetricEventsToPage(metrics) {
- const metricEventTemplate = document.querySelector('#metric-event-template');
- metrics.forEach(metricEvent => {
- const metricEventClone = metricEventTemplate.content.cloneNode(true);
- metricEventClone.querySelector('#url').textContent = metricEvent.url;
- metricEventClone.querySelector('#sheet-peeked').textContent =
- metricEvent.sheetPeeked;
- metricEventClone.querySelector('#button-shown').textContent =
- metricEvent.buttonShown;
- metricEventClone.querySelector('#sheet-opened').textContent =
- metricEvent.sheetOpened;
- metricEventClone.querySelector('#sheet-closed').textContent =
- metricEvent.sheetClosed;
- metricEventClone.querySelector('#any-suggestion-taken').textContent =
- metricEvent.anySuggestionTaken;
- metricEventClone.querySelector('#any-suggestion-downloaded').textContent =
- metricEvent.anySuggestionDownloaded;
-
- $('metric-events').appendChild(metricEventClone);
- });
-}
-
-// Get the cached suggestion results, and add them to the page.
-function updatePageWithCachedSuggestionResults() {
- pageHandler.getCachedSuggestionResults().then(response => {
- const suggestionContainerId = 'suggestion-results';
- clearChildrenForId(suggestionContainerId);
- addCachedSuggestionResultsToPage(response.results);
- });
-}
-
-// Add the results to the page.
-function addCachedSuggestionResultsToPage(results) {
- const suggestionResultTemplate =
- document.querySelector('#suggestion-result-template');
- results.forEach(result => {
- const resultClone = suggestionResultTemplate.content.cloneNode(true);
- resultClone.querySelector('#suggestion-result-url').textContent =
- result.url;
- resultClone.querySelector('#peek-confidence').textContent =
- result.peekConditions.confidence.toFixed(2);
- resultClone.querySelector('#peek-page-scroll-percentage').textContent =
- result.peekConditions.pageScrollPercentage.toFixed(2);
- resultClone.querySelector('#peek-min-seconds-on-page').textContent =
- result.peekConditions.minimumSecondsOnPage.toFixed(2);
- resultClone.querySelector('#peek-max-peeks').textContent =
- result.peekConditions.maximumNumberOfPeeks;
-
- const suggestionTemplate = document.querySelector('#suggestion-template');
- result.suggestions.forEach(suggestion => {
- const suggestionClone = suggestionTemplate.content.cloneNode(true);
- suggestionClone.querySelector('#suggestion-title').textContent =
- suggestion.title;
- suggestionClone.querySelector('#suggestion-url').textContent =
- suggestion.url;
- suggestionClone.querySelector('#suggestion-title').textContent =
- suggestion.title + ' >>';
- suggestionClone.querySelector('#suggestion-title').onclick = function(
- event) {
- const suggestion = event.currentTarget.parentElement.querySelector(
- '#suggestion-details');
- suggestion.hidden = !suggestion.hidden;
- };
- suggestionClone.querySelector('#suggestions-publisher-name').textContent =
- suggestion.publisherName;
- suggestionClone.querySelector('#suggestion-snippet').textContent =
- suggestion.snippet;
- suggestionClone.querySelector('#suggestion-url').textContent =
- suggestion.url;
-
- resultClone.querySelector('#cached-suggestions')
- .appendChild(suggestionClone);
- });
-
- $('suggestion-results').appendChild(resultClone);
- });
-}
-
-// Clear the cache of metric events.
-function clearCachedMetricEvents() {
- pageHandler.clearCachedMetricEvents().then(() => {
- clearChildrenForId('metric-events');
- });
-}
-
-// Clear the cached suggestion results from the server.
-function clearCachedSuggestionResults() {
- pageHandler.clearCachedSuggestionResults().then(() => {
- clearChildrenForId('suggestion-results');
- });
-}
-
-function setupEventListeners() {
- $('clear-metrics').onclick = clearCachedMetricEvents;
- $('clear-suggestion-results').onclick = clearCachedSuggestionResults;
-}
-
-document.addEventListener('DOMContentLoaded', function() {
- // Setup backend mojo.
- pageHandler = eocInternals.mojom.PageHandler.getProxy();
-
- updatePageWithProperties();
- updatePageWithCachedMetricEvents();
- updatePageWithCachedSuggestionResults();
-
- setupEventListeners();
-});
-})();
diff --git a/chromium/chrome/browser/resources/explore_sites_internals/explore_sites_internals.js b/chromium/chrome/browser/resources/explore_sites_internals/explore_sites_internals.js
index f0e93978d57..5b9f456ae75 100644
--- a/chromium/chrome/browser/resources/explore_sites_internals/explore_sites_internals.js
+++ b/chromium/chrome/browser/resources/explore_sites_internals/explore_sites_internals.js
@@ -84,7 +84,7 @@ function forceNetworkRequest() {
document.addEventListener('DOMContentLoaded', function() {
// Setup backend mojo.
- pageHandler = exploreSitesInternals.mojom.PageHandler.getProxy();
+ pageHandler = exploreSitesInternals.mojom.PageHandler.getRemote();
updatePageWithProperties();
// Set up event listeners.
diff --git a/chromium/chrome/browser/resources/extensions/BUILD.gn b/chromium/chrome/browser/resources/extensions/BUILD.gn
index 375e5e59731..7a60d45137f 100644
--- a/chromium/chrome/browser/resources/extensions/BUILD.gn
+++ b/chromium/chrome/browser/resources/extensions/BUILD.gn
@@ -115,11 +115,11 @@ js_library("detail_view") {
js_library("drag_and_drop_handler") {
deps = [
+ ":service",
"//ui/webui/resources/js:assert",
"//ui/webui/resources/js:cr",
"//ui/webui/resources/js/cr/ui:drag_wrapper",
]
- externs_list = [ "$externs_path/developer_private.js" ]
}
js_library("drop_overlay") {
diff --git a/chromium/chrome/browser/resources/extensions/activity_log/activity_log.html b/chromium/chrome/browser/resources/extensions/activity_log/activity_log.html
index ab435e74868..6a10765807b 100644
--- a/chromium/chrome/browser/resources/extensions/activity_log/activity_log.html
+++ b/chromium/chrome/browser/resources/extensions/activity_log/activity_log.html
@@ -4,6 +4,7 @@
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/cr_tabs/cr_tabs.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
@@ -18,11 +19,7 @@
<dom-module id="extensions-activity-log">
<template>
- <style include="cr-icons shared-style">
- #activity-log-heading {
- @apply --cr-title-text;
- }
-
+ <style include="cr-icons cr-shared-style shared-style">
#clear-activities-button {
margin-inline-start: 8px;
}
@@ -75,7 +72,7 @@
'$i18nPolymer{appIcon}',
'$i18nPolymer{extensionIcon}')]]">
</template>
- <div id="activity-log-heading">
+ <div class="cr-title-text">
[[getActivityLogHeading_(extensionInfo)]]
</div>
</div>
diff --git a/chromium/chrome/browser/resources/extensions/activity_log/activity_log.js b/chromium/chrome/browser/resources/extensions/activity_log/activity_log.js
index 8f29629fe85..3f3d33e0990 100644
--- a/chromium/chrome/browser/resources/extensions/activity_log/activity_log.js
+++ b/chromium/chrome/browser/resources/extensions/activity_log/activity_log.js
@@ -147,10 +147,12 @@ cr.define('extensions', function() {
/** @private */
onCloseButtonTap_: function() {
if (this.extensionInfo.isPlaceholder) {
- extensions.navigation.navigateTo({page: Page.LIST});
+ extensions.navigation.navigateTo({page: extensions.Page.LIST});
} else {
- extensions.navigation.navigateTo(
- {page: Page.DETAILS, extensionId: this.extensionInfo.id});
+ extensions.navigation.navigateTo({
+ page: extensions.Page.DETAILS,
+ extensionId: this.extensionInfo.id
+ });
}
},
});
diff --git a/chromium/chrome/browser/resources/extensions/activity_log/activity_log_history.html b/chromium/chrome/browser/resources/extensions/activity_log/activity_log_history.html
index e7eab6e4ca3..41cb1feabd4 100644
--- a/chromium/chrome/browser/resources/extensions/activity_log/activity_log_history.html
+++ b/chromium/chrome/browser/resources/extensions/activity_log/activity_log_history.html
@@ -3,16 +3,15 @@
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/promise_resolver.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_search_field/cr_search_field.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="activity_log_history_item.html">
<link rel="import" href="../shared_style.html">
<dom-module id="activity-log-history">
<template>
- <style include="paper-button-style shared-style">
+ <style include="shared-style">
:host {
--activity-log-call-and-count-width: 514px;
--activity-type-width: 85px;
@@ -23,6 +22,7 @@
}
cr-search-field {
+ align-self: center;
margin-inline-end: auto;
}
@@ -56,10 +56,10 @@
<cr-search-field label="$i18n{activityLogSearchLabel}"
on-search-changed="onSearchChanged_">
</cr-search-field >
- <paper-button class="clear-activities-button"
+ <cr-button class="clear-activities-button"
on-click="onClearActivitiesClick_">
$i18n{clearActivities}
- </paper-button>
+ </cr-button>
<cr-icon-button id="more-actions" iron-icon="cr:more-vert"
title="$i18n{activityLogMoreActionsLabel}"
on-click="onMoreActionsClick_"></cr-icon-button>
diff --git a/chromium/chrome/browser/resources/extensions/activity_log/activity_log_history.js b/chromium/chrome/browser/resources/extensions/activity_log/activity_log_history.js
index 7ec96a7995e..fda97f585e2 100644
--- a/chromium/chrome/browser/resources/extensions/activity_log/activity_log_history.js
+++ b/chromium/chrome/browser/resources/extensions/activity_log/activity_log_history.js
@@ -2,23 +2,18 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.exportPath('extensions');
-
-/**
- * The different states the activity log page can be in. Initial state is
- * LOADING because we call the activity log API whenever a user navigates to the
- * page. LOADED is the state where the API call has returned a successful
- * result.
- * @enum {string}
- */
-const ActivityLogPageState = {
- LOADING: 'loading',
- LOADED: 'loaded'
-};
-
cr.define('extensions', function() {
'use strict';
+ /**
+ * The different states the activity log page can be in. Initial state is
+ * LOADING because we call the activity log API whenever a user navigates to
+ * the page. LOADED is the state where the API call has returned a successful
+ * result.
+ * @enum {string}
+ */
+ const ActivityLogPageState = {LOADING: 'loading', LOADED: 'loaded'};
+
/** @interface */
class ActivityLogDelegate {
/**
@@ -206,7 +201,7 @@ cr.define('extensions', function() {
value: () => [],
},
- /** @private {ActivityLogPageState} */
+ /** @private {extensions.ActivityLogPageState} */
pageState_: {
type: String,
value: ActivityLogPageState.LOADING,
@@ -414,7 +409,8 @@ cr.define('extensions', function() {
});
return {
- ActivityLogHistory: ActivityLogHistory,
ActivityLogDelegate: ActivityLogDelegate,
+ ActivityLogHistory: ActivityLogHistory,
+ ActivityLogPageState: ActivityLogPageState,
};
});
diff --git a/chromium/chrome/browser/resources/extensions/activity_log/activity_log_stream.html b/chromium/chrome/browser/resources/extensions/activity_log/activity_log_stream.html
index 4ae7a45d5e4..0d78032b425 100644
--- a/chromium/chrome/browser/resources/extensions/activity_log/activity_log_stream.html
+++ b/chromium/chrome/browser/resources/extensions/activity_log/activity_log_stream.html
@@ -1,16 +1,15 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/cr.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_search_field/cr_search_field.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
<link rel="import" href="activity_log_stream_item.html">
<link rel="import" href="../shared_style.html">
<dom-module id="activity-log-stream">
<template>
- <style include="shared-style paper-button-style">
+ <style include="shared-style">
:host {
--activity-log-call-and-time-width: 575px;
--activity-type-width: 85px;
@@ -21,6 +20,7 @@
}
cr-search-field {
+ align-self: center;
margin-inline-end: auto;
}
@@ -50,18 +50,17 @@
<cr-search-field label="$i18n{activityLogSearchLabel}"
on-search-changed="onSearchChanged_">
</cr-search-field >
- <paper-button id="toggle-stream-button" on-click="onToggleButtonClick_">
+ <cr-button id="toggle-stream-button" on-click="onToggleButtonClick_">
<span hidden$="[[isStreamOn_]]">
$i18n{startActivityStream}
</span>
<span hidden$="[[!isStreamOn_]]">
$i18n{stopActivityStream}
</span>
- </paper-button>
- <paper-button class="clear-activities-button"
- on-click="clearStream">
+ </cr-button>
+ <cr-button class="clear-activities-button" on-click="clearStream">
$i18n{clearActivities}
- </paper-button>
+ </cr-button>
</div>
<div id="empty-stream-message" class="activity-message"
hidden$="[[!isStreamEmpty_(activityStream_.length)]]">
diff --git a/chromium/chrome/browser/resources/extensions/code_section.html b/chromium/chrome/browser/resources/extensions/code_section.html
index f453c12dbf7..b4721b10309 100644
--- a/chromium/chrome/browser/resources/extensions/code_section.html
+++ b/chromium/chrome/browser/resources/extensions/code_section.html
@@ -17,10 +17,12 @@
display: block;
}
- :host-context([dark]) {
- --container-bg: rgba(0, 0, 0, .4);
- --line-bg: var(--google-grey-800);
- --main-color: var(--cr-primary-text-color);
+ @media (prefers-color-scheme: dark) {
+ :host {
+ --container-bg: rgba(0, 0, 0, .4);
+ --line-bg: var(--google-grey-800);
+ --main-color: var(--cr-primary-text-color);
+ }
}
#scroll-container {
@@ -30,8 +32,10 @@
position: relative;
}
- :host-context(html:not([dark])) #scroll-container {
- border: 1px solid var(--paper-grey-500);
+ @media (prefers-color-scheme: light) {
+ #scroll-container {
+ border: 1px solid var(--paper-grey-500);
+ }
}
#main {
@@ -49,8 +53,10 @@
text-align: end;
}
- :host-context(html:not([dark])) #line-numbers {
- border-inline-end: 1px solid var(--paper-grey-500);
+ @media (prefers-color-scheme: light) {
+ #line-numbers {
+ border-inline-end: 1px solid var(--paper-grey-500);
+ }
}
#source {
@@ -68,12 +74,14 @@
text-align: center;
}
- :host-context(html:not([dark])) #no-code {
- color: var(--paper-grey-800);
- }
+ @media (prefers-color-scheme: light) {
+ #no-code {
+ color: var(--paper-grey-800);
+ }
- :host-context(html:not([dark])) .more-code {
- color: var(--paper-grey-500);
+ .more-code {
+ color: var(--paper-grey-500);
+ }
}
#highlight-description {
@@ -81,9 +89,11 @@
overflow: hidden;
}
- :host-context([dark]) mark {
- background-color: var(--google-yellow-refresh-300);
- color: var(--google-grey-900);
+ @media (prefers-color-scheme: dark) {
+ mark {
+ background-color: var(--google-yellow-refresh-300);
+ color: var(--google-grey-900);
+ }
}
</style>
<div id="scroll-container" hidden="[[!highlighted_]]" dir="ltr">
diff --git a/chromium/chrome/browser/resources/extensions/detail_view.html b/chromium/chrome/browser/resources/extensions/detail_view.html
index b021c518c01..df4e5baf623 100644
--- a/chromium/chrome/browser/resources/extensions/detail_view.html
+++ b/chromium/chrome/browser/resources/extensions/detail_view.html
@@ -1,22 +1,21 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_container_shadow_behavior.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_tooltip_icon.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="item_behavior.html">
@@ -31,7 +30,8 @@
<dom-module id="extensions-detail-view">
<template>
- <style include="iron-flex cr-shared-style cr-icons action-link paper-button-style shared-style">
+ <style include="iron-flex cr-shared-style cr-icons action-link
+ shared-style">
:host {
--iron-icon-fill-color: var(--cr-secondary-text-color);
display: block;
@@ -55,8 +55,10 @@
color: var(--google-blue-500);
}
- :host-context([dark]) #enable-section .enabled-text {
- color: var(--google-blue-refresh-300);
+ @media (prefers-color-scheme: dark) {
+ #enable-section .enabled-text {
+ color: var(--google-blue-refresh-300);
+ }
}
#icon {
@@ -68,7 +70,6 @@
#name {
flex-grow: 1;
- @apply --cr-title-text;
}
.section {
@@ -107,13 +108,15 @@
width: auto; /* override the default button size of 24x24 */
}
- :host-context(html:not([dark])) .warning .action-button {
- background: white;
- color: var(--google-blue-500);
- }
+ @media (prefers-color-scheme: light) {
+ .warning .action-button {
+ background: white;
+ color: var(--google-blue-500);
+ }
- :host-context(html:not([dark])) #reload-button {
- color: var(--google-blue-500);
+ #reload-button {
+ color: var(--google-blue-500);
+ }
}
.warning span {
@@ -175,7 +178,7 @@
data.type,
'$i18nPolymer{appIcon}',
'$i18nPolymer{extensionIcon}')]]">
- <span id="name">[[data.name]]</span>
+ <span id="name" class="cr-title-text">[[data.name]]</span>
</div>
<div class="section continuation control-line" id="enable-section">
<span class$="[[computeEnabledStyle_(data.state)]]">
@@ -189,10 +192,10 @@
icon-aria-label="[[data.controlledInfo.type]]">
</cr-tooltip-icon>
<template is="dom-if" if="[[isTerminated_(data.state)]]">
- <paper-button id="terminated-reload-button" class="action-button"
+ <cr-button id="terminated-reload-button" class="action-button"
on-click="onReloadTap_">
$i18n{itemReload}
- </paper-button>
+ </cr-button>
</template>
<cr-toggle id="enable-toggle"
aria-label$="[[appOrExtension(
@@ -217,10 +220,10 @@
</template>
</span>
<template is="dom-if" if="[[!isTerminated_(data.state)]]">
- <paper-button id="warnings-reload-button" class="action-button"
+ <cr-button id="warnings-reload-button" class="action-button"
on-click="onReloadTap_">
$i18n{itemReload}
- </paper-button>
+ </cr-button>
</template>
</div>
<div class="section continuation warning" id="suspicious-warning"
@@ -238,10 +241,10 @@
hidden$="[[!data.disableReasons.corruptInstall]]">
<iron-icon class="warning-icon" icon="cr:warning"></iron-icon>
<span>$i18n{itemCorruptInstall}</span>
- <paper-button id="repair-button" class="action-button"
+ <cr-button id="repair-button" class="action-button"
on-click="onRepairTap_">
$i18n{itemRepair}
- </paper-button>
+ </cr-button>
</div>
<div class="section continuation warning" id="blacklisted-warning"
hidden$="[[!data.blacklistText]]">
diff --git a/chromium/chrome/browser/resources/extensions/detail_view.js b/chromium/chrome/browser/resources/extensions/detail_view.js
index 1c477906b5b..53d33c481d0 100644
--- a/chromium/chrome/browser/resources/extensions/detail_view.js
+++ b/chromium/chrome/browser/resources/extensions/detail_view.js
@@ -81,7 +81,7 @@ cr.define('extensions', function() {
/** @private */
onActivityLogTap_: function() {
extensions.navigation.navigateTo(
- {page: Page.ACTIVITY_LOG, extensionId: this.data.id});
+ {page: extensions.Page.ACTIVITY_LOG, extensionId: this.data.id});
},
/**
@@ -96,7 +96,7 @@ cr.define('extensions', function() {
/** @private */
onCloseButtonTap_: function() {
- extensions.navigation.navigateTo({page: Page.LIST});
+ extensions.navigation.navigateTo({page: extensions.Page.LIST});
},
/**
diff --git a/chromium/chrome/browser/resources/extensions/drag_and_drop_handler.html b/chromium/chrome/browser/resources/extensions/drag_and_drop_handler.html
index 2626f1e7a3f..5e959f2d095 100644
--- a/chromium/chrome/browser/resources/extensions/drag_and_drop_handler.html
+++ b/chromium/chrome/browser/resources/extensions/drag_and_drop_handler.html
@@ -1,2 +1,3 @@
<link rel="import" href="chrome://resources/html/cr.html">
+<link rel="import" href="service.html">
<script src="drag_and_drop_handler.js"></script>
diff --git a/chromium/chrome/browser/resources/extensions/drag_and_drop_handler.js b/chromium/chrome/browser/resources/extensions/drag_and_drop_handler.js
index 30bdc57f01d..15324adb0ef 100644
--- a/chromium/chrome/browser/resources/extensions/drag_and_drop_handler.js
+++ b/chromium/chrome/browser/resources/extensions/drag_and_drop_handler.js
@@ -36,7 +36,7 @@ cr.define('extensions', function() {
/** @override */
doDragEnter() {
- chrome.developerPrivate.notifyDragInstallInProgress();
+ extensions.Service.getInstance().notifyDragInstallInProgress();
this.eventTarget_.dispatchEvent(
new CustomEvent('extension-drag-started'));
}
@@ -83,7 +83,7 @@ cr.define('extensions', function() {
* @private
*/
handleFileDrop_() {
- chrome.developerPrivate.installDroppedFile();
+ extensions.Service.getInstance().installDroppedFile();
}
/**
@@ -91,15 +91,10 @@ cr.define('extensions', function() {
* @private
*/
handleDirectoryDrop_() {
- // TODO(devlin): Update this to use extensions.Service when it's not
- // shared between the MD and non-MD pages.
- chrome.developerPrivate.loadUnpacked(
- {failQuietly: true, populateError: true, useDraggedPath: true},
- (loadError) => {
- if (loadError) {
- this.eventTarget_.dispatchEvent(new CustomEvent(
- 'drag-and-drop-load-error', {detail: loadError}));
- }
+ extensions.Service.getInstance().loadUnpackedFromDrag().catch(
+ loadError => {
+ this.eventTarget_.dispatchEvent(new CustomEvent(
+ 'drag-and-drop-load-error', {detail: loadError}));
});
}
diff --git a/chromium/chrome/browser/resources/extensions/drop_overlay.html b/chromium/chrome/browser/resources/extensions/drop_overlay.html
index 985c3ca083e..b3209817520 100644
--- a/chromium/chrome/browser/resources/extensions/drop_overlay.html
+++ b/chromium/chrome/browser/resources/extensions/drop_overlay.html
@@ -23,9 +23,11 @@
z-index: 10;
}
- :host-context([dark]) {
- /* TODO(dbeam): share with cr-dialog dialog::backdrop? */
- background-color: rgba(0, 0, 0, .6);
+ @media (prefers-color-scheme: dark) {
+ :host {
+ /* TODO(dbeam): share with cr-dialog dialog::backdrop? */
+ background-color: rgba(0, 0, 0, .6);
+ }
}
#container {
diff --git a/chromium/chrome/browser/resources/extensions/error_page.html b/chromium/chrome/browser/resources/extensions/error_page.html
index d5254f4c1ee..4e0e4784985 100644
--- a/chromium/chrome/browser/resources/extensions/error_page.html
+++ b/chromium/chrome/browser/resources/extensions/error_page.html
@@ -1,10 +1,10 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_container_shadow_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
@@ -12,7 +12,6 @@
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="code_section.html">
<link rel="import" href="item_util.html">
@@ -21,7 +20,7 @@
<dom-module id="extensions-error-page">
<template>
- <style include="paper-button-style cr-icons cr-shared-style shared-style">
+ <style include="cr-icons cr-shared-style shared-style">
:host {
display: block;
height: 100%;
@@ -52,7 +51,6 @@
height: 40px;
margin-bottom: 30px;
padding: 8px 12px 0;
- @apply --cr-title-text;
}
#heading span {
@@ -96,7 +94,6 @@
}
.details-heading {
- @apply --cr-title-text;
align-items: center;
display: flex;
height: var(--cr-section-min-height);
@@ -139,14 +136,14 @@
</style>
<div class="page-container" id="container">
<div class="page-content">
- <div id="heading">
+ <div id="heading" class="cr-title-text">
<cr-icon-button class="icon-arrow-back no-overlap" id="closeButton"
aria-label="$i18n{back}" on-click="onCloseButtonTap_">
</cr-icon-button>
<span>$i18n{errorsPageHeading}</span>
- <paper-button on-click="onClearAllTap_" hidden="[[!entries_.length]]">
+ <cr-button on-click="onClearAllTap_" hidden="[[!entries_.length]]">
$i18n{clearAll}
- </paper-button>
+ </cr-button>
</div>
<div class="section">
<div id="errorsList">
@@ -177,14 +174,14 @@
<div class="devtools-controls">
<template is="dom-if"
if="[[computeIsRuntimeError_(item)]]">
- <div class="details-heading">
+ <div class="details-heading cr-title-text">
$i18n{errorContext}
</div>
<span class="context-url">
[[getContextUrl_(
item, '$i18nPolymer{errorContextUnknown}')]]
</span>
- <div class="details-heading">
+ <div class="details-heading cr-title-text">
$i18n{stackTrace}
</div>
<ul class="stack-trace-container"
diff --git a/chromium/chrome/browser/resources/extensions/error_page.js b/chromium/chrome/browser/resources/extensions/error_page.js
index fc0e44f06fe..fea88babb4a 100644
--- a/chromium/chrome/browser/resources/extensions/error_page.js
+++ b/chromium/chrome/browser/resources/extensions/error_page.js
@@ -162,7 +162,7 @@ cr.define('extensions', function() {
/** @private */
onCloseButtonTap_: function() {
- extensions.navigation.navigateTo({page: Page.LIST});
+ extensions.navigation.navigateTo({page: extensions.Page.LIST});
},
/** @private */
diff --git a/chromium/chrome/browser/resources/extensions/extensions.html b/chromium/chrome/browser/resources/extensions/extensions.html
index 51406cb7b33..83ea4fe724a 100644
--- a/chromium/chrome/browser/resources/extensions/extensions.html
+++ b/chromium/chrome/browser/resources/extensions/extensions.html
@@ -1,6 +1,6 @@
<!doctype html>
<html dir="$i18n{textdirection}" lang="$i18n{language}"
- class="loading $i18n{loadTimeClasses}" $i18n{dark}>
+ class="loading $i18n{loadTimeClasses}">
<head>
<meta charset="utf8">
<title>$i18n{title}</title>
@@ -35,13 +35,15 @@
height: 54px;
}
- html[dark].loading.in-dev-mode body::before {
- background: none;
- }
+ @media (prefers-color-scheme: dark) {
+ html.loading.in-dev-mode body::before {
+ background: none;
+ }
- html[dark].loading::before,
- html[dark].loading.in-dev-mode body::before {
- border-bottom: var(--md-toolbar-border);
+ html.loading::before,
+ html.loading.in-dev-mode body::before {
+ border-bottom: var(--md-toolbar-border);
+ }
}
html,
@@ -60,6 +62,5 @@
<extensions-manager></extensions-manager>
<link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
<link rel="import" href="chrome://extensions/manager.html">
- <link rel="import" href="chrome://resources/html/dark_mode.html">
</body>
</html>
diff --git a/chromium/chrome/browser/resources/extensions/install_warnings_dialog.html b/chromium/chrome/browser/resources/extensions/install_warnings_dialog.html
index 19b213005e6..760a8a40ae6 100644
--- a/chromium/chrome/browser/resources/extensions/install_warnings_dialog.html
+++ b/chromium/chrome/browser/resources/extensions/install_warnings_dialog.html
@@ -1,17 +1,16 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="code_section.html">
<dom-module id="extensions-install-warnings-dialog">
<template>
- <style include="cr-shared-style paper-button-style">
+ <style include="cr-shared-style">
div[slot='body'] ul {
background-color: var(--paper-red-50);
margin: 0;
@@ -20,10 +19,12 @@
padding-top: 10px;
}
- :host-context([dark]) div[slot='body'] ul {
- /* TODO(dbeam): merge with --cr-input-background-color? */
- background-color: rgba(0, 0, 0, .3);
- color: var(--error-color);
+ @media (prefers-color-scheme: dark) {
+ div[slot='body'] ul {
+ /* TODO(dbeam): merge with --cr-input-background-color? */
+ background-color: rgba(0, 0, 0, .3);
+ color: var(--error-color);
+ }
}
</style>
<cr-dialog id="dialog" close-text="$i18n{close}">
@@ -36,9 +37,9 @@
</ul>
</div>
<div slot="button-container">
- <paper-button class="action-button" on-click="onOkTap_">
+ <cr-button class="action-button" on-click="onOkTap_">
$i18n{ok}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/extensions/item.html b/chromium/chrome/browser/resources/extensions/item.html
index 5fa187adea9..4dd4b1c830c 100644
--- a/chromium/chrome/browser/resources/extensions/item.html
+++ b/chromium/chrome/browser/resources/extensions/item.html
@@ -1,14 +1,14 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
@@ -25,7 +25,8 @@
<dom-module id="extensions-item">
<template>
- <style include="iron-flex cr-hidden-style cr-icons action-link paper-button-style shared-style">
+ <style include="iron-flex cr-hidden-style cr-icons action-link
+ shared-style">
.bounded-text,
.multiline-clippable-text,
.clippable-flex-text {
@@ -90,7 +91,7 @@
}
#name-and-version {
- @apply --cr-primary-text;
+ color: var(--cr-primary-text-color);
margin-bottom: 4px;
}
@@ -145,7 +146,7 @@
padding-top: 8px;
}
- #button-strip paper-button {
+ #button-strip cr-button {
margin-inline-start: 8px;
}
@@ -304,20 +305,20 @@
</div>
<div id="button-strip" class="layout horizontal center">
<div class="layout flex horizontal center">
- <paper-button id="detailsButton" on-click="onDetailsTap_"
+ <cr-button id="detailsButton" on-click="onDetailsTap_"
aria-describedby="a11yAssociation">
$i18n{itemDetails}
- </paper-button>
- <paper-button id="remove-button" on-click="onRemoveTap_"
+ </cr-button>
+ <cr-button id="remove-button" on-click="onRemoveTap_"
aria-describedby="a11yAssociation"
hidden="[[isControlled_(data.controlledInfo)]]">
$i18n{remove}
- </paper-button>
+ </cr-button>
<template is="dom-if" if="[[shouldShowErrorsButton_(data.*)]]">
- <paper-button id="errors-button" on-click="onErrorsTap_"
+ <cr-button id="errors-button" on-click="onErrorsTap_"
aria-describedby="a11yAssociation">
$i18n{itemErrors}
- </paper-button>
+ </cr-button>
</template>
</div>
<template is="dom-if" if="[[!computeDevReloadButtonHidden_(data.*)]]">
@@ -326,16 +327,16 @@
on-click="onReloadTap_"></cr-icon-button>
</template>
<template is="dom-if" if="[[data.disableReasons.corruptInstall]]">
- <paper-button id="repair-button" class="action-button"
+ <cr-button id="repair-button" class="action-button"
aria-describedby="a11yAssociation" on-click="onRepairTap_">
$i18n{itemRepair}
- </paper-button>
+ </cr-button>
</template>
<template is="dom-if" if="[[isTerminated_(data.state)]]">
- <paper-button id="terminated-reload-button" on-click="onReloadTap_"
+ <cr-button id="terminated-reload-button" on-click="onReloadTap_"
aria-describedby="a11yAssociation" class="action-button">
$i18n{itemReload}
- </paper-button>
+ </cr-button>
</template>
<cr-toggle id="enable-toggle"
aria-label$="[[appOrExtension(
diff --git a/chromium/chrome/browser/resources/extensions/item.js b/chromium/chrome/browser/resources/extensions/item.js
index 4b1a62ff39c..008beca6c32 100644
--- a/chromium/chrome/browser/resources/extensions/item.js
+++ b/chromium/chrome/browser/resources/extensions/item.js
@@ -188,13 +188,13 @@ cr.define('extensions', function() {
}
extensions.navigation.navigateTo(
- {page: Page.ERRORS, extensionId: this.data.id});
+ {page: extensions.Page.ERRORS, extensionId: this.data.id});
},
/** @private */
onDetailsTap_: function() {
extensions.navigation.navigateTo(
- {page: Page.DETAILS, extensionId: this.data.id});
+ {page: extensions.Page.DETAILS, extensionId: this.data.id});
},
/**
@@ -208,7 +208,7 @@ cr.define('extensions', function() {
/** @private */
onExtraInspectTap_: function() {
extensions.navigation.navigateTo(
- {page: Page.DETAILS, extensionId: this.data.id});
+ {page: extensions.Page.DETAILS, extensionId: this.data.id});
},
/** @private */
diff --git a/chromium/chrome/browser/resources/extensions/item_list.html b/chromium/chrome/browser/resources/extensions/item_list.html
index 40c9027ec8e..339e774de80 100644
--- a/chromium/chrome/browser/resources/extensions/item_list.html
+++ b/chromium/chrome/browser/resources/extensions/item_list.html
@@ -35,8 +35,10 @@
text-align: center;
}
- :host-context([dark]) .empty-list-message {
- color: var(--cr-secondary-text-color);
+ @media (prefers-color-scheme: dark) {
+ .empty-list-message {
+ color: var(--cr-secondary-text-color);
+ }
}
.items-container {
diff --git a/chromium/chrome/browser/resources/extensions/keyboard_shortcuts.html b/chromium/chrome/browser/resources/extensions/keyboard_shortcuts.html
index de1fd4bc740..73968d69f68 100644
--- a/chromium/chrome/browser/resources/extensions/keyboard_shortcuts.html
+++ b/chromium/chrome/browser/resources/extensions/keyboard_shortcuts.html
@@ -4,7 +4,7 @@
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="item_behavior.html">
<link rel="import" href="shortcut_input.html">
@@ -17,10 +17,10 @@
}
.shortcut-card {
- @apply --cr-primary-text;
@apply --cr-card-elevation;
background-color: var(--cr-card-background-color);
border-radius: var(--cr-card-border-radius);
+ color: var(--cr-primary-text-color);
margin: 0 auto 16px auto;
padding-bottom: 8px;
width: var(--cr-toolbar-field-width);
@@ -64,7 +64,6 @@
display: flex;
margin-bottom: 9px;
padding: 16px var(--cr-section-padding);
- @apply --cr-title-text;
}
.icon {
@@ -83,7 +82,7 @@
<div id="container">
<template is="dom-repeat" items="[[calculateShownItems_(items.*)]]">
<div class="shortcut-card">
- <div class="card-title">
+ <div class="card-title cr-title-text">
<img class="icon" src="[[item.iconUrl]]"
alt$="[[appOrExtension(
item.type,
diff --git a/chromium/chrome/browser/resources/extensions/kiosk_dialog.html b/chromium/chrome/browser/resources/extensions/kiosk_dialog.html
index 78eb1bae22e..7210150053e 100644
--- a/chromium/chrome/browser/resources/extensions/kiosk_dialog.html
+++ b/chromium/chrome/browser/resources/extensions/kiosk_dialog.html
@@ -1,23 +1,22 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="item_behavior.html">
<link rel="import" href="kiosk_browser_proxy.html">
<dom-module id="extensions-kiosk-dialog">
<template>
- <style include="cr-shared-style paper-button-style cr-icons">
+ <style include="cr-shared-style cr-icons">
#add-kiosk-app {
margin-bottom: 10px;
margin-top: 20px;
@@ -27,7 +26,7 @@
width: 350px;
}
- #add-kiosk-app paper-button {
+ #add-kiosk-app cr-button {
margin-inline-start: 10px;
}
@@ -88,12 +87,12 @@
</span>
</div>
<div class="item-controls">
- <paper-button hidden="[[!canEditAutoLaunch_]]"
+ <cr-button hidden="[[!canEditAutoLaunch_]]"
on-click="onAutoLaunchButtonTap_">
[[getAutoLaunchButtonLabel_(item.autoLaunch,
'$i18nPolymer{kioskDisableAutoLaunch}',
'$i18nPolymer{kioskEnableAutoLaunch}')]]
- </paper-button>
+ </cr-button>
<cr-icon-button class="icon-delete-gray"
on-click="onDeleteAppTap_"></cr-icon-button>
</div>
@@ -106,10 +105,10 @@
invalid="[[errorAppId_]]" on-keydown="clearInputInvalid_"
error-message="[[getErrorMessage_(
'$i18nPolymer{kioskInvalidApp}', errorAppId_)]]">
- <paper-button id="add-button" on-click="onAddAppTap_"
+ <cr-button id="add-button" on-click="onAddAppTap_"
disabled="[[!addAppInput_]]" slot="suffix">
$i18n{add}
- </paper-button>
+ </cr-button>
</cr-input>
</div>
<cr-checkbox disabled="[[!canEditBailout_]]" id="bailout"
@@ -119,9 +118,9 @@
</cr-checkbox>
</div>
<div slot="button-container">
- <paper-button class="action-button" on-click="onDoneTap_">
+ <cr-button class="action-button" on-click="onDoneTap_">
$i18n{done}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
<cr-dialog id="confirm-dialog" close-text="$i18n{close}"
@@ -129,14 +128,12 @@
<div slot="title">$i18n{kioskDisableBailoutWarningTitle}</div>
<div slot="body">$i18n{kioskDisableBailoutWarningBody}</div>
<div slot="button-container">
- <paper-button class="cancel-button"
- on-click="onBailoutDialogCancelTap_">
+ <cr-button class="cancel-button" on-click="onBailoutDialogCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button"
- on-click="onBailoutDialogConfirmTap_">
+ </cr-button>
+ <cr-button class="action-button" on-click="onBailoutDialogConfirmTap_">
$i18n{confirm}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/extensions/load_error.html b/chromium/chrome/browser/resources/extensions/load_error.html
index 77a0f3d11bd..682b4fbcdf9 100644
--- a/chromium/chrome/browser/resources/extensions/load_error.html
+++ b/chromium/chrome/browser/resources/extensions/load_error.html
@@ -1,17 +1,16 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
<link rel="import" href="code_section.html">
<dom-module id="extensions-load-error">
<template>
- <style include="cr-shared-style paper-button-style">
+ <style include="cr-shared-style">
.description-row {
display: flex;
}
@@ -44,13 +43,13 @@
</div>
<div slot="button-container">
<paper-spinner-lite active="[[retrying_]]"></paper-spinner-lite>
- <paper-button class="cancel-button" on-click="close">
+ <cr-button class="cancel-button" on-click="close">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" disabled="[[retrying_]]"
+ </cr-button>
+ <cr-button class="action-button" disabled="[[retrying_]]"
on-click="onRetryTap_">
$i18n{loadErrorRetry}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/extensions/manager.js b/chromium/chrome/browser/resources/extensions/manager.js
index 6095756ca9e..28e8b0fdece 100644
--- a/chromium/chrome/browser/resources/extensions/manager.js
+++ b/chromium/chrome/browser/resources/extensions/manager.js
@@ -167,7 +167,7 @@ cr.define('extensions', function() {
/**
* The current page being shown. Default to null, and initPage_ will figure
* out the initial page based on url.
- * @private {?PageState}
+ * @private {?extensions.PageState}
*/
currentPage_: null,
@@ -290,8 +290,8 @@ cr.define('extensions', function() {
* @private
*/
onFilterChanged_: function(event) {
- if (this.currentPage_.page !== Page.LIST) {
- extensions.navigation.navigateTo({page: Page.LIST});
+ if (this.currentPage_.page !== extensions.Page.LIST) {
+ extensions.navigation.navigateTo({page: extensions.Page.LIST});
}
this.filter = event.detail;
},
@@ -402,15 +402,15 @@ cr.define('extensions', function() {
// that the DOM will have stale data, but there's no point in causing the
// extra work.
if (this.detailViewItem_ && this.detailViewItem_.id == item.id &&
- this.currentPage_.page == Page.DETAILS) {
+ this.currentPage_.page == extensions.Page.DETAILS) {
this.detailViewItem_ = item;
} else if (
this.errorPageItem_ && this.errorPageItem_.id == item.id &&
- this.currentPage_.page == Page.ERRORS) {
+ this.currentPage_.page == extensions.Page.ERRORS) {
this.errorPageItem_ = item;
} else if (
this.activityLogItem_ && this.activityLogItem_.id == item.id &&
- this.currentPage_.page == Page.ACTIVITY_LOG) {
+ this.currentPage_.page == extensions.Page.ACTIVITY_LOG) {
this.activityLogItem_ = item;
}
},
@@ -432,12 +432,12 @@ cr.define('extensions', function() {
// We should never try and remove a non-existent item.
assert(index >= 0);
this.splice(listId, index, 1);
- if ((this.currentPage_.page == Page.ACTIVITY_LOG ||
- this.currentPage_.page == Page.DETAILS ||
- this.currentPage_.page == Page.ERRORS) &&
+ if ((this.currentPage_.page == extensions.Page.ACTIVITY_LOG ||
+ this.currentPage_.page == extensions.Page.DETAILS ||
+ this.currentPage_.page == extensions.Page.ERRORS) &&
this.currentPage_.extensionId == itemId) {
// Leave the details page (the 'list' page is a fine choice).
- extensions.navigation.replaceWith({page: Page.LIST});
+ extensions.navigation.replaceWith({page: extensions.Page.LIST});
}
},
@@ -456,7 +456,7 @@ cr.define('extensions', function() {
/**
* Changes the active page selection.
- * @param {PageState} newPage
+ * @param {extensions.PageState} newPage
* @private
*/
changePage_: function(newPage) {
@@ -478,29 +478,31 @@ cr.define('extensions', function() {
// extension ID is not valid. This enables the use case of seeing an
// extension's install-time activities by navigating to an extension's
// activity log page, then installing the extension.
- if (this.showActivityLog && toPage == Page.ACTIVITY_LOG) {
+ if (this.showActivityLog && toPage == extensions.Page.ACTIVITY_LOG) {
activityLogPlaceholder = {
id: newPage.extensionId,
isPlaceholder: true,
};
} else {
// Attempting to view an invalid (removed?) app or extension ID.
- extensions.navigation.replaceWith({page: Page.LIST});
+ extensions.navigation.replaceWith({page: extensions.Page.LIST});
return;
}
}
}
- if (toPage == Page.DETAILS) {
+ if (toPage == extensions.Page.DETAILS) {
this.detailViewItem_ = assert(data);
- } else if (toPage == Page.ERRORS) {
+ } else if (toPage == extensions.Page.ERRORS) {
this.errorPageItem_ = assert(data);
- } else if (toPage == Page.ACTIVITY_LOG) {
+ } else if (toPage == extensions.Page.ACTIVITY_LOG) {
if (!this.showActivityLog) {
// Redirect back to the details page if we try to view the
// activity log of an extension but the flag is not set.
- extensions.navigation.replaceWith(
- {page: Page.DETAILS, extensionId: newPage.extensionId});
+ extensions.navigation.replaceWith({
+ page: extensions.Page.DETAILS,
+ extensionId: newPage.extensionId
+ });
return;
}
@@ -509,11 +511,11 @@ cr.define('extensions', function() {
if (fromPage != toPage) {
/** @type {CrViewManagerElement} */ (this.$.viewManager)
- .switchView(toPage);
+ .switchView(/** @type {string} */ (toPage));
}
if (newPage.subpage) {
- assert(newPage.subpage == Dialog.OPTIONS);
+ assert(newPage.subpage == extensions.Dialog.OPTIONS);
assert(newPage.extensionId);
this.showOptionsDialog_ = true;
this.async(() => {
@@ -521,6 +523,9 @@ cr.define('extensions', function() {
});
}
+ document.title = toPage == extensions.Page.DETAILS ?
+ `${loadTimeData.getString('title')} - ${this.detailViewItem_.name}` :
+ loadTimeData.getString('title');
this.currentPage_ = newPage;
},
diff --git a/chromium/chrome/browser/resources/extensions/navigation_helper.js b/chromium/chrome/browser/resources/extensions/navigation_helper.js
index 61915038319..75748cd70ef 100644
--- a/chromium/chrome/browser/resources/extensions/navigation_helper.js
+++ b/chromium/chrome/browser/resources/extensions/navigation_helper.js
@@ -2,39 +2,37 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.exportPath('extensions');
-
-/**
- * The different pages that can be shown at a time.
- * Note: This must remain in sync with the page ids in manager.html!
- * @enum {string}
- */
-const Page = {
- LIST: 'items-list',
- DETAILS: 'details-view',
- ACTIVITY_LOG: 'activity-log',
- SHORTCUTS: 'keyboard-shortcuts',
- ERRORS: 'error-page',
-};
-
-/** @enum {string} */
-const Dialog = {
- OPTIONS: 'options',
-};
-
-/**
- @typedef {{page: Page,
- extensionId: (string|undefined),
- subpage: (!Dialog|undefined)}}
- */
-let PageState;
-
cr.define('extensions', function() {
'use strict';
/**
- * @param {!PageState} a
- * @param {!PageState} b
+ * The different pages that can be shown at a time.
+ * Note: This must remain in sync with the page ids in manager.html!
+ * @enum {string}
+ */
+ const Page = {
+ LIST: 'items-list',
+ DETAILS: 'details-view',
+ ACTIVITY_LOG: 'activity-log',
+ SHORTCUTS: 'keyboard-shortcuts',
+ ERRORS: 'error-page',
+ };
+
+ /** @enum {string} */
+ const Dialog = {
+ OPTIONS: 'options',
+ };
+
+ /**
+ * @typedef {{page: extensions.Page,
+ * extensionId: (string|undefined),
+ * subpage: (!extensions.Dialog|undefined)}}
+ */
+ let PageState;
+
+ /**
+ * @param {!extensions.PageState} a
+ * @param {!extensions.PageState} b
* @return {boolean} Whether a and b are equal.
*/
function isPageStateEqual(a, b) {
@@ -61,10 +59,10 @@ cr.define('extensions', function() {
/** @private {number} */
this.nextListenerId_ = 1;
- /** @private {!Map<number, function(!PageState)>} */
+ /** @private {!Map<number, function(!extensions.PageState)>} */
this.listeners_ = new Map();
- /** @private {!PageState} */
+ /** @private {!extensions.PageState} */
this.previousPage_;
window.addEventListener('popstate', () => {
@@ -94,8 +92,8 @@ cr.define('extensions', function() {
}
/**
- * @return {!PageState} The page that should be displayed for the current
- * URL.
+ * @return {!extensions.PageState} The page that should be displayed for the
+ * current URL.
*/
getCurrentPage() {
const search = new URLSearchParams(location.search);
@@ -125,7 +123,7 @@ cr.define('extensions', function() {
/**
* Function to add subscribers.
- * @param {!function(!PageState)} listener
+ * @param {!function(!extensions.PageState)} listener
* @return {number} A numerical ID to be used for removing the listener.
*/
addListener(listener) {
@@ -155,7 +153,7 @@ cr.define('extensions', function() {
}
/**
- * @param {!PageState} newPage the page to navigate to.
+ * @param {!extensions.PageState} newPage the page to navigate to.
*/
navigateTo(newPage) {
const currentPage = this.getCurrentPage();
@@ -168,7 +166,8 @@ cr.define('extensions', function() {
}
/**
- * @param {!PageState} newPage the page to replace the current page with.
+ * @param {!extensions.PageState} newPage the page to replace the current
+ * page with.
*/
replaceWith(newPage) {
this.updateHistory(newPage, true /* replaceState */);
@@ -182,7 +181,7 @@ cr.define('extensions', function() {
/**
* Called when a page changes, and pushes state to history to reflect it.
- * @param {!PageState} entry
+ * @param {!extensions.PageState} entry
* @param {boolean} replaceState
*/
updateHistory(entry, replaceState) {
@@ -230,8 +229,11 @@ cr.define('extensions', function() {
const navigation = new NavigationHelper();
return {
+ Dialog: Dialog,
// Constructor exposed for testing purposes.
NavigationHelper: NavigationHelper,
navigation: navigation,
+ Page: Page,
+ PageState: PageState,
};
});
diff --git a/chromium/chrome/browser/resources/extensions/options_dialog.html b/chromium/chrome/browser/resources/extensions/options_dialog.html
index 59ced391619..77f5d941e0f 100644
--- a/chromium/chrome/browser/resources/extensions/options_dialog.html
+++ b/chromium/chrome/browser/resources/extensions/options_dialog.html
@@ -26,35 +26,39 @@
overflow: hidden;
}
+ cr-dialog::part(dialog) {
+ /* CSS variables are set by the JS. */
+ height: var(--dialog-height);
+ opacity: var(--dialog-opacity, 0);
+ /* When loading, it's possible for an size update to follow after the
+ initial size update. The debounce time on size updates is 50ms.
+ A 100ms delay for the opacity transition will allow two updates to
+ occur without showing the dialog resizing to the user. */
+ transition: opacity 100ms ease 100ms;
+ width: var(--dialog-width);
+ }
+
+ cr-dialog::part(wrapper) {
+ height: 100%;
+ max-height: initial;
+ overflow: hidden;
+ }
+
+ cr-dialog #body {
+ height: 100%;
+ padding: 0;
+ }
+
cr-dialog {
- --cr-dialog-body: {
- height: 100%;
- padding-bottom: 0;
- padding-inline-end: 0;
- padding-inline-start: 0;
- padding-top: 0;
- }
--cr-dialog-body-border-bottom: none;
--cr-dialog-body-border-top: none;
- --cr-dialog-body-container: {
- height: 100%;
- min-height: initial;
- }
- --cr-dialog-native: {
- opacity: 0;
- /* When loading, it's possible for an size update to follow after the
- initial size update. The debounce time on size updates is 50ms.
- A 100ms delay for the opacity transition will allow two updates to
- occur without showing the dialog resizing to the user. */
- transition: opacity 100ms ease 100ms;
- }
- --cr-dialog-wrapper: {
- height: 100%;
- max-height: initial;
- overflow: hidden;
- }
--scroll-border: none;
}
+
+ cr-dialog::part(body-container) {
+ height: 100%;
+ min-height: initial;
+ }
</style>
<cr-dialog id="dialog" close-text="$i18n{close}"
diff --git a/chromium/chrome/browser/resources/extensions/options_dialog.js b/chromium/chrome/browser/resources/extensions/options_dialog.js
index a3fe7176551..6e5279922d2 100644
--- a/chromium/chrome/browser/resources/extensions/options_dialog.js
+++ b/chromium/chrome/browser/resources/extensions/options_dialog.js
@@ -66,10 +66,10 @@ cr.define('extensions', function() {
Math.min(maxHeight, headerHeight + this.preferredSize_.height);
const effectiveWidth = Math.max(MIN_WIDTH, this.preferredSize_.width);
- const nativeDialog = this.$.dialog.getNative();
- nativeDialog.style.height = `${effectiveHeight}px`;
- nativeDialog.style.width = `${effectiveWidth}px`;
- nativeDialog.style.opacity = '1';
+ this.$.dialog.style.setProperty(
+ '--dialog-height', `${effectiveHeight}px`);
+ this.$.dialog.style.setProperty('--dialog-width', `${effectiveWidth}px`);
+ this.$.dialog.style.setProperty('--dialog-opacity', 1);
},
/** @param {chrome.developerPrivate.ExtensionInfo} data */
@@ -113,12 +113,14 @@ cr.define('extensions', function() {
// still on the details page. We could be on a different page if the
// user hit back while the options dialog was visible; in that case, the
// new page is already correct.
- if (currentPage && currentPage.page == Page.DETAILS) {
+ if (currentPage && currentPage.page == extensions.Page.DETAILS) {
// This will update the currentPage_ and the NavigationHelper; since
// the active page is already the details page, no main page
// transition occurs.
- extensions.navigation.navigateTo(
- {page: Page.DETAILS, extensionId: currentPage.extensionId});
+ extensions.navigation.navigateTo({
+ page: extensions.Page.DETAILS,
+ extensionId: currentPage.extensionId
+ });
}
},
});
diff --git a/chromium/chrome/browser/resources/extensions/pack_dialog.html b/chromium/chrome/browser/resources/extensions/pack_dialog.html
index 1a3c789ee58..6718e23fec0 100644
--- a/chromium/chrome/browser/resources/extensions/pack_dialog.html
+++ b/chromium/chrome/browser/resources/extensions/pack_dialog.html
@@ -1,25 +1,24 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/util.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="pack_dialog_alert.html">
<dom-module id="extensions-pack-dialog">
<template>
- <style include="cr-shared-style paper-button-style">
+ <style include="cr-shared-style">
cr-input {
margin-top: var(--cr-form-field-bottom-spacing);
--cr-input-error-display: none;
}
- paper-button[slot='suffix'] {
+ cr-button[slot='suffix'] {
margin-inline-start: 10px;
}
@@ -34,27 +33,27 @@
<div>$i18n{packDialogContent}</div>
<cr-input id="root-dir" label="$i18n{packDialogExtensionRoot}"
value="{{packDirectory_}}">
- <paper-button id="root-dir-browse" on-click="onRootBrowse_"
+ <cr-button id="root-dir-browse" on-click="onRootBrowse_"
slot="suffix">
$i18n{packDialogBrowse}
- </paper-button>
+ </cr-button>
</cr-input>
<cr-input id="key-file" label="$i18n{packDialogKeyFile}"
value="{{keyFile_}}">
- <paper-button id="key-file-browse" on-click="onKeyBrowse_"
+ <cr-button id="key-file-browse" on-click="onKeyBrowse_"
slot="suffix">
$i18n{packDialogBrowse}
- </paper-button>
+ </cr-button>
</cr-input>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelTap_">
+ <cr-button class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onConfirmTap_"
+ </cr-button>
+ <cr-button class="action-button" on-click="onConfirmTap_"
disabled="[[!packDirectory_]]">
$i18n{packDialogConfirm}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
<template is="dom-if" if="[[lastResponse_]]" restamp>
diff --git a/chromium/chrome/browser/resources/extensions/pack_dialog_alert.html b/chromium/chrome/browser/resources/extensions/pack_dialog_alert.html
index 79fa1a74167..a08e9feb5e0 100644
--- a/chromium/chrome/browser/resources/extensions/pack_dialog_alert.html
+++ b/chromium/chrome/browser/resources/extensions/pack_dialog_alert.html
@@ -1,15 +1,14 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<dom-module id="extensions-pack-dialog-alert">
<template>
- <style include="cr-shared-style paper-button-style">
+ <style include="cr-shared-style">
.body {
white-space: pre-wrap;
word-break: break-word;
@@ -21,14 +20,14 @@
<!-- No whitespace or new-lines allowed within the div.body tag. -->
<div class="body" slot="body">[[model.message]]</div>
<div class="button-container" slot="button-container">
- <paper-button class$="[[getCancelButtonClass_(confirmLabel_)]]"
+ <cr-button class$="[[getCancelButtonClass_(confirmLabel_)]]"
on-click="onCancelTap_" hidden="[[!cancelLabel_]]">
[[cancelLabel_]]
- </paper-button>
- <paper-button class="action-button" on-click="onConfirmTap_"
+ </cr-button>
+ <cr-button class="action-button" on-click="onConfirmTap_"
hidden="[[!confirmLabel_]]">
[[confirmLabel_]]
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/extensions/runtime_host_permissions.html b/chromium/chrome/browser/resources/extensions/runtime_host_permissions.html
index 3b6c39f5935..038343a0cdb 100644
--- a/chromium/chrome/browser/resources/extensions/runtime_host_permissions.html
+++ b/chromium/chrome/browser/resources/extensions/runtime_host_permissions.html
@@ -4,25 +4,22 @@
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_radio_group/cr_radio_group.html">
<link rel="import" href="chrome://resources/cr_elements/cr_radio_button/cr_radio_button.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="runtime_hosts_dialog.html">
<link rel="import" href="shared_style.html">
<link rel="import" href="strings.html">
<dom-module id="extensions-runtime-host-permissions">
<template>
- <style include="cr-shared-style action-link md-select paper-button-style
- shared-style">
+ <style include="cr-shared-style action-link md-select shared-style">
iron-icon {
--iron-icon-height: var(--cr-icon-size);
--iron-icon-width: var(--cr-icon-size);
diff --git a/chromium/chrome/browser/resources/extensions/runtime_hosts_dialog.html b/chromium/chrome/browser/resources/extensions/runtime_hosts_dialog.html
index b639ed5754b..db6b162825e 100644
--- a/chromium/chrome/browser/resources/extensions/runtime_hosts_dialog.html
+++ b/chromium/chrome/browser/resources/extensions/runtime_hosts_dialog.html
@@ -1,15 +1,14 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="strings.html">
<dom-module id="extensions-runtime-hosts-dialog">
<template>
- <style include="cr-shared-style paper-button-style"></style>
+ <style include="cr-shared-style"></style>
<cr-dialog id="dialog" close-text="$i18n{close}">
<div slot="title">[[computeDialogTitle_(currentSite)]]</div>
<div slot="body">
@@ -23,13 +22,13 @@
</cr-input>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelTap_">
+ <cr-button class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" id="submit" on-click="onSubmitTap_"
+ </cr-button>
+ <cr-button class="action-button" id="submit" on-click="onSubmitTap_"
disabled="[[computeSubmitButtonDisabled_(inputInvalid_, site_)]]">
[[computeSubmitButtonLabel_(currentSite)]]
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/extensions/service.js b/chromium/chrome/browser/resources/extensions/service.js
index b6dd8b6b99e..1acc69798be 100644
--- a/chromium/chrome/browser/resources/extensions/service.js
+++ b/chromium/chrome/browser/resources/extensions/service.js
@@ -146,18 +146,22 @@ cr.define('extensions', function() {
}
/**
- * Attempts to load an unpacked extension, optionally as another attempt at
- * a previously-specified load.
- * @param {string=} opt_retryGuid
+ * @param {chrome.developerPrivate.LoadUnpackedOptions=} opt_options
* @return {!Promise} A signal that loading finished, rejected if any error
* occurred.
* @private
*/
- loadUnpackedHelper_(opt_retryGuid) {
+ loadUnpackedHelper_(opt_options) {
return new Promise(function(resolve, reject) {
+ const options = Object.assign(
+ {
+ failQuietly: true,
+ populateError: true,
+ },
+ opt_options);
+
chrome.developerPrivate.loadUnpacked(
- {failQuietly: true, populateError: true, retryGuid: opt_retryGuid},
- (loadError) => {
+ options, (loadError) => {
if (chrome.runtime.lastError &&
chrome.runtime.lastError.message !=
'File selection was canceled.') {
@@ -270,8 +274,8 @@ cr.define('extensions', function() {
chrome.developerPrivate.showOptions(extension.id);
} else {
extensions.navigation.navigateTo({
- page: Page.DETAILS,
- subpage: Dialog.OPTIONS,
+ page: extensions.Page.DETAILS,
+ subpage: extensions.Dialog.OPTIONS,
extensionId: extension.id,
});
}
@@ -290,7 +294,9 @@ cr.define('extensions', function() {
/** @override */
retryLoadUnpacked(retryGuid) {
- return this.loadUnpackedHelper_(retryGuid);
+ // Attempt to load an unpacked extension, optionally as another attempt at
+ // a previously-specified load.
+ return this.loadUnpackedHelper_({retryGuid: retryGuid});
}
/** @override */
@@ -428,6 +434,22 @@ cr.define('extensions', function() {
a.download = fileName;
a.click();
}
+
+ /**
+ * Attempts to load an unpacked extension via a drag-n-drop gesture.
+ * @return {!Promise}
+ */
+ loadUnpackedFromDrag() {
+ return this.loadUnpackedHelper_({useDraggedPath: true});
+ }
+
+ installDroppedFile() {
+ chrome.developerPrivate.installDroppedFile();
+ }
+
+ notifyDragInstallInProgress() {
+ chrome.developerPrivate.notifyDragInstallInProgress();
+ }
}
cr.addSingletonGetter(Service);
diff --git a/chromium/chrome/browser/resources/extensions/shared_vars.html b/chromium/chrome/browser/resources/extensions/shared_vars.html
index 125f2333d0a..86b2870213f 100644
--- a/chromium/chrome/browser/resources/extensions/shared_vars.html
+++ b/chromium/chrome/browser/resources/extensions/shared_vars.html
@@ -12,8 +12,10 @@
--separator-gap: 9px;
}
- html[dark] {
- --error-color: var(--google-red-refresh-300);
+ @media (prefers-color-scheme: dark) {
+ html {
+ --error-color: var(--google-red-refresh-300);
+ }
}
</style>
</custom-style>
diff --git a/chromium/chrome/browser/resources/extensions/sidebar.html b/chromium/chrome/browser/resources/extensions/sidebar.html
index 8aaf1ef5fe8..4024fb27744 100644
--- a/chromium/chrome/browser/resources/extensions/sidebar.html
+++ b/chromium/chrome/browser/resources/extensions/sidebar.html
@@ -22,8 +22,10 @@
width: 256px;
}
- :host-context([dark]) {
- --sidebar-inactive-color: var(--cr-primary-text-color);
+ @media (prefers-color-scheme: dark) {
+ :host {
+ --sidebar-inactive-color: var(--cr-primary-text-color);
+ }
}
iron-selector .iron-selected {
diff --git a/chromium/chrome/browser/resources/extensions/sidebar.js b/chromium/chrome/browser/resources/extensions/sidebar.js
index 8f5bd9b06eb..19619f17912 100644
--- a/chromium/chrome/browser/resources/extensions/sidebar.js
+++ b/chromium/chrome/browser/resources/extensions/sidebar.js
@@ -16,8 +16,10 @@ cr.define('extensions', function() {
/** @override */
attached: function() {
this.$.sectionMenu.select(
- extensions.navigation.getCurrentPage().page == Page.SHORTCUTS ? 1 :
- 0);
+ extensions.navigation.getCurrentPage().page ==
+ extensions.Page.SHORTCUTS ?
+ 1 :
+ 0);
},
/**
diff --git a/chromium/chrome/browser/resources/extensions/toolbar.html b/chromium/chrome/browser/resources/extensions/toolbar.html
index 77ee1f84a66..7e08974284a 100644
--- a/chromium/chrome/browser/resources/extensions/toolbar.html
+++ b/chromium/chrome/browser/resources/extensions/toolbar.html
@@ -1,10 +1,10 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_tooltip_icon.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
@@ -17,7 +17,7 @@
<dom-module id="extensions-toolbar">
<template>
- <style include="cr-hidden-style paper-button-style">
+ <style include="cr-hidden-style">
:host {
--border-bottom-height: 1px;
--button-row-height: calc(2 * var(--padding-top-bottom) +
@@ -27,12 +27,14 @@
}
/* This toggle needs special styling because it's on blue background. */
- :host-context(html:not([dark])) cr-toolbar cr-toggle {
- --cr-toggle-checked-bar-color: var(--google-grey-refresh-100);
- --cr-toggle-checked-button-color: white;
- --cr-toggle-checked-ink-color: white;
- --cr-toggle-unchecked-bar-color: var(--google-grey-600);
- --cr-toggle-unchecked-ink-color: white;
+ @media (prefers-color-scheme: light) {
+ cr-toolbar cr-toggle {
+ --cr-toggle-checked-bar-color: var(--google-grey-refresh-100);
+ --cr-toggle-checked-button-color: white;
+ --cr-toggle-checked-ink-color: white;
+ --cr-toggle-unchecked-bar-color: var(--google-grey-600);
+ --cr-toggle-unchecked-ink-color: white;
+ }
}
cr-tooltip-icon {
@@ -53,9 +55,11 @@
transition: height var(--drawer-transition);
}
- :host-context([dark]) #devDrawer {
- background: none;
- border-bottom-color: var(--cr-separator-color);
+ @media (prefers-color-scheme: dark) {
+ #devDrawer {
+ background: none;
+ border-bottom-color: var(--cr-separator-color);
+ }
}
#devDrawer[expanded] {
@@ -74,7 +78,7 @@
width: 100%;
}
- #buttonStrip paper-button {
+ #buttonStrip cr-button {
margin-inline-end: 16px;
}
@@ -120,22 +124,22 @@
</template>
<div id="devDrawer" expanded$="[[expanded_]]">
<div id="buttonStrip">
- <paper-button hidden$="[[!canLoadUnpacked]]" id="loadUnpacked"
+ <cr-button hidden$="[[!canLoadUnpacked]]" id="loadUnpacked"
on-click="onLoadUnpackedTap_">
$i18n{toolbarLoadUnpacked}
- </paper-button>
- <paper-button id="packExtensions" on-click="onPackTap_">
+ </cr-button>
+ <cr-button id="packExtensions" on-click="onPackTap_">
$i18n{toolbarPack}
- </paper-button>
- <paper-button id="updateNow" on-click="onUpdateNowTap_"
+ </cr-button>
+ <cr-button id="updateNow" on-click="onUpdateNowTap_"
title="$i18n{toolbarUpdateNowTooltip}">
$i18n{toolbarUpdateNow}
- </paper-button>
+ </cr-button>
<if expr="chromeos">
- <paper-button id="kioskExtensions" on-click="onKioskTap_"
+ <cr-button id="kioskExtensions" on-click="onKioskTap_"
hidden$="[[!kioskEnabled]]">
$i18n{manageKioskApp}
- </paper-button>
+ </cr-button>
</if>
</div>
</div>
diff --git a/chromium/chrome/browser/resources/extensions/toolbar.js b/chromium/chrome/browser/resources/extensions/toolbar.js
index c231c5a95b5..7792f175221 100644
--- a/chromium/chrome/browser/resources/extensions/toolbar.js
+++ b/chromium/chrome/browser/resources/extensions/toolbar.js
@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.exportPath('extensions');
-
cr.define('extensions', function() {
/** @interface */
class ToolbarDelegate {
diff --git a/chromium/chrome/browser/resources/feed_internals/feed_internals.js b/chromium/chrome/browser/resources/feed_internals/feed_internals.js
index 02f22a26ac4..398104bc5ae 100644
--- a/chromium/chrome/browser/resources/feed_internals/feed_internals.js
+++ b/chromium/chrome/browser/resources/feed_internals/feed_internals.js
@@ -6,7 +6,7 @@
/**
* Reference to the backend.
- * @type {feedInternals.mojom.PageHandlerProxy}
+ * @type {feedInternals.mojom.PageHandlerRemote}
*/
let pageHandler = null;
@@ -153,7 +153,7 @@ function setupEventListeners() {
document.addEventListener('DOMContentLoaded', function() {
// Setup backend mojo.
- pageHandler = feedInternals.mojom.PageHandler.getProxy();
+ pageHandler = feedInternals.mojom.PageHandler.getRemote();
updatePageWithProperties();
updatePageWithUserClass();
diff --git a/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js b/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js
index 27e94de6fae..dc1a35b1729 100644
--- a/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js
+++ b/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js
@@ -111,6 +111,91 @@ cr.define('cr.login', function() {
'realm',
];
+
+ /**
+ * Handlers for the HTML5 messages received from Gaia.
+ * Each handler is a function that receives the Authenticator as 'this',
+ * and the data field of the HTML5 Payload.
+ */
+ const messageHandlers = {
+ 'attemptLogin': function(msg) {
+ this.email_ = msg.email;
+ if (this.authMode == AuthMode.DESKTOP) {
+ this.password_ = msg.password;
+ }
+ this.isSamlUserPasswordless_ = null;
+
+ this.chooseWhatToSync_ = msg.chooseWhatToSync;
+ // We need to dispatch only first event, before user enters password.
+ this.dispatchEvent(new CustomEvent('attemptLogin', {detail: msg.email}));
+ },
+ 'dialogShown': function(msg) {
+ this.dispatchEvent(new Event('dialogShown'));
+ },
+ 'dialogHidden': function(msg) {
+ this.dispatchEvent(new Event('dialogHidden'));
+ },
+ 'backButton': function(msg) {
+ this.dispatchEvent(new CustomEvent('backButton', {detail: msg.show}));
+ },
+ 'showView': function(msg) {
+ this.dispatchEvent(new Event('showView'));
+ },
+ 'menuItemClicked': function(msg) {
+ this.dispatchEvent(
+ new CustomEvent('menuItemClicked', {detail: msg.item}));
+ },
+ 'identifierEntered': function(msg) {
+ this.dispatchEvent(new CustomEvent(
+ 'identifierEntered',
+ {detail: {accountIdentifier: msg.accountIdentifier}}));
+ },
+ 'userInfo': function(msg) {
+ this.services_ = msg.services;
+ if (this.email_ && this.gaiaId_ && this.sessionIndex_) {
+ this.maybeCompleteAuth_();
+ }
+ },
+ 'showIncognito': function(msg) {
+ this.dispatchEvent(new Event('showIncognito'));
+ },
+ 'setPrimaryActionLabel': function(msg) {
+ if (!this.enableGaiaActionButtons_) {
+ return;
+ }
+ this.dispatchEvent(
+ new CustomEvent('setPrimaryActionLabel', {detail: msg.value}));
+ },
+ 'setPrimaryActionEnabled': function(msg) {
+ if (!this.enableGaiaActionButtons_) {
+ return;
+ }
+ this.dispatchEvent(
+ new CustomEvent('setPrimaryActionEnabled', {detail: msg.value}));
+ },
+ 'setSecondaryActionLabel': function(msg) {
+ if (!this.enableGaiaActionButtons_) {
+ return;
+ }
+ this.dispatchEvent(
+ new CustomEvent('setSecondaryActionLabel', {detail: msg.value}));
+ },
+ 'setSecondaryActionEnabled': function(msg) {
+ if (!this.enableGaiaActionButtons_) {
+ return;
+ }
+ this.dispatchEvent(
+ new CustomEvent('setSecondaryActionEnabled', {detail: msg.value}));
+ },
+ 'setAllActionsEnabled': function(msg) {
+ if (!this.enableGaiaActionButtons_) {
+ return;
+ }
+ this.dispatchEvent(
+ new CustomEvent('setAllActionsEnabled', {detail: msg.value}));
+ }
+ };
+
/**
* Initializes the authenticator component.
*/
@@ -143,6 +228,7 @@ cr.define('cr.login', function() {
this.readyFired_ = false;
this.webview_ = typeof webview == 'string' ? $(webview) : webview;
assert(this.webview_);
+ this.enableGaiaActionButtons_ = false;
this.webviewEventManager_ = WebviewEventManager.create();
this.clientId_ = null;
@@ -291,8 +377,9 @@ cr.define('cr.login', function() {
/**
* Re-binds to another webview.
* @param {Object} webview the new webview to be used by this Authenticator.
+ * @private
*/
- rebindWebview(webview) {
+ rebindWebview_(webview) {
if (!this.isDomLoaded_) {
// We haven't bound to the previously set webview yet, so simply update
// |webview_| to use the new element during the delayed initialization.
@@ -306,6 +393,51 @@ cr.define('cr.login', function() {
}
/**
+ * Copies attributes between nodes.
+ * @param {!Element} fromNode source to copy attributes from
+ * @param {!Element} toNode target to copy attributes to
+ * @param {!Set<string>} skipAttributes specifies attributes to be skipped
+ * @private
+ */
+ copyAttributes_(fromNode, toNode, skipAttributes) {
+ for (let i = 0; i < fromNode.attributes.length; ++i) {
+ const attribute = fromNode.attributes[i];
+ if (!skipAttributes.has(attribute.nodeName)) {
+ toNode.setAttribute(attribute.nodeName, attribute.nodeValue);
+ }
+ }
+ }
+
+ /**
+ * Changes the 'partition' attribute of |webview_|. If |webview_| has
+ * already navigated, this function re-creates it since the storage
+ * partition of an active renderer process cannot change.
+ * @param {string} newWebviewPartitionName the new partition
+ * @private
+ */
+ setWebviewPartition(newWebviewPartitionName) {
+ if (!this.webview_.src) {
+ // We have not navigated anywhere yet. Note that a webview's src
+ // attribute does not allow a change back to "".
+ this.webview_.partition = newWebviewPartitionName;
+ } else if (this.webview_.partition != newWebviewPartitionName) {
+ // The webview has already navigated. We have to re-create it.
+ const webivewParent = this.webview_.parentElement;
+
+ // Copy all attributes except for partition and src from the previous
+ // webview. Use the specified |newWebviewPartitionName|.
+ const newWebview = document.createElement('webview');
+ this.copyAttributes_(
+ this.webview_, newWebview, new Set(['src', 'partition']));
+ newWebview.partition = newWebviewPartitionName;
+
+ webivewParent.replaceChild(newWebview, this.webview_);
+
+ this.rebindWebview_(newWebview);
+ }
+ }
+
+ /**
* Loads the authenticator component with the given parameters.
* @param {AuthMode} authMode Authorization mode.
* @param {Object} data Parameters for the authorization flow.
@@ -319,6 +451,7 @@ cr.define('cr.login', function() {
this.isConstrainedWindow_ = data.constrained == '1';
this.clientId_ = data.clientId;
this.dontResizeNonEmbeddedPages = data.dontResizeNonEmbeddedPages;
+ this.enableGaiaActionButtons_ = data.enableGaiaActionButtons;
this.initialFrameUrl_ = this.constructInitialFrameUrl_(data);
this.reloadUrl_ = data.frameUrl || this.initialFrameUrl_;
@@ -605,45 +738,23 @@ cr.define('cr.login', function() {
}
const msg = e.data;
- if (msg.method == 'attemptLogin') {
- this.email_ = msg.email;
- if (this.authMode == AuthMode.DESKTOP) {
- this.password_ = msg.password;
- }
- this.isSamlUserPasswordless_ = null;
-
- this.chooseWhatToSync_ = msg.chooseWhatToSync;
- // We need to dispatch only first event, before user enters password.
- this.dispatchEvent(
- new CustomEvent('attemptLogin', {detail: msg.email}));
- } else if (msg.method == 'dialogShown') {
- this.dispatchEvent(new Event('dialogShown'));
- } else if (msg.method == 'dialogHidden') {
- this.dispatchEvent(new Event('dialogHidden'));
- } else if (msg.method == 'backButton') {
- this.dispatchEvent(new CustomEvent('backButton', {detail: msg.show}));
- } else if (msg.method == 'showView') {
- this.dispatchEvent(new Event('showView'));
- } else if (msg.method == 'menuItemClicked') {
- this.dispatchEvent(
- new CustomEvent('menuItemClicked', {detail: msg.item}));
- } else if (msg.method == 'identifierEntered') {
- this.dispatchEvent(new CustomEvent(
- 'identifierEntered',
- {detail: {accountIdentifier: msg.accountIdentifier}}));
- } else if (msg.method == 'userInfo') {
- this.services_ = msg.services;
- if (this.email_ && this.gaiaId_ && this.sessionIndex_) {
- this.maybeCompleteAuth_();
- }
- } else if (msg.method == 'showIncognito') {
- this.dispatchEvent(new Event('showIncognito'));
+ if (msg.method in messageHandlers) {
+ messageHandlers[msg.method].call(this, msg);
} else {
console.warn('Unrecognized message from GAIA: ' + msg.method);
}
}
/**
+ * Invoked to send a HTML5 message to the webview element.
+ * @param {object} e Payload of the HTML5 message.
+ */
+ sendMessageToWebview(payload) {
+ const currentUrl = this.webview_.src;
+ this.webview_.contentWindow.postMessage(payload, currentUrl);
+ }
+
+ /**
* Invoked by the hosting page to verify the Saml password.
*/
verifyConfirmedPassword(password) {
@@ -697,9 +808,9 @@ cr.define('cr.login', function() {
if (this.isSamlUserPasswordless_ === null &&
this.authFlow == AuthFlow.SAML && this.email_ && this.gaiaId_ &&
this.getIsSamlUserPasswordlessCallback) {
- // Start a request to obtain the |isSamlUserPasswordless_| value for the
- // current user. Once the response arrives, maybeCompleteAuth_() will be
- // called again.
+ // Start a request to obtain the |isSamlUserPasswordless_| value for
+ // the current user. Once the response arrives, maybeCompleteAuth_()
+ // will be called again.
this.getIsSamlUserPasswordlessCallback(
this.email_, this.gaiaId_,
this.onGotIsSamlUserPasswordless_.bind(
@@ -735,8 +846,8 @@ cr.define('cr.login', function() {
console.warn('Authenticator: No password scraped for SAML.');
} else if (this.needPassword) {
if (this.samlHandler_.scrapedPasswordCount == 1) {
- // If we scraped exactly one password, we complete the authentication
- // right away.
+ // If we scraped exactly one password, we complete the
+ // authentication right away.
this.password_ = this.samlHandler_.firstScrapedPassword;
this.onAuthCompleted_();
return;
@@ -755,9 +866,9 @@ cr.define('cr.login', function() {
}
/**
- * Invoked to complete the authentication using the password the user enters
- * manually for non-principals API SAML IdPs that we couldn't scrape their
- * password input.
+ * Invoked to complete the authentication using the password the user
+ * enters manually for non-principals API SAML IdPs that we couldn't
+ * scrape their password input.
*/
completeAuthWithManualPassword(password) {
this.password_ = password;
@@ -786,8 +897,8 @@ cr.define('cr.login', function() {
* @private
*/
assertStringArray_(arr, nameOfArr) {
- console.assert(Array.isArray(arr),
- 'FATAL: Bad %s type: %s', nameOfArr, typeof arr);
+ console.assert(
+ Array.isArray(arr), 'FATAL: Bad %s type: %s', nameOfArr, typeof arr);
for (let i = 0; i < arr.length; ++i) {
this.assertStringElement_(arr[i], nameOfArr, i);
}
@@ -798,8 +909,9 @@ cr.define('cr.login', function() {
* @private
*/
assertStringDict_(dict, nameOfDict) {
- console.assert(typeof dict == 'object',
- 'FATAL: Bad %s type: %s', nameOfDict, typeof dict);
+ console.assert(
+ typeof dict == 'object', 'FATAL: Bad %s type: %s', nameOfDict,
+ typeof dict);
for (const key in dict) {
this.assertStringElement_(dict[key], nameOfDict, key);
}
@@ -807,8 +919,9 @@ cr.define('cr.login', function() {
/** Asserts an element |elem| in a certain collection is a string. */
assertStringElement_(elem, nameOfCollection, index) {
- console.assert(typeof elem == 'string',
- 'FATAL: Bad %s[%s] type: %s', nameOfCollection, index, typeof elem);
+ console.assert(
+ typeof elem == 'string', 'FATAL: Bad %s[%s] type: %s',
+ nameOfCollection, index, typeof elem);
}
/**
@@ -907,9 +1020,9 @@ cr.define('cr.login', function() {
* @private
*/
onSamlApiPasswordAdded_(e) {
- // Saml API 'add' password might be received after the 'loadcommit' event.
- // In such case, maybeCompleteAuth_ should be attempted again if GAIA ID
- // is available.
+ // Saml API 'add' password might be received after the 'loadcommit'
+ // event. In such case, maybeCompleteAuth_ should be attempted again if
+ // GAIA ID is available.
if (this.gaiaId_) {
this.maybeCompleteAuth_();
}
@@ -938,8 +1051,8 @@ cr.define('cr.login', function() {
onContentLoad_(e) {
if (this.isConstrainedWindow_) {
// Signin content in constrained windows should not zoom. Isolate the
- // webview from the zooming of other webviews using the 'per-view' zoom
- // mode, and then set it to 100% zoom.
+ // webview from the zooming of other webviews using the 'per-view'
+ // zoom mode, and then set it to 100% zoom.
this.webview_.setZoomMode('per-view');
this.webview_.setZoom(1);
}
@@ -951,8 +1064,8 @@ cr.define('cr.login', function() {
'method': 'handshake',
};
- // |this.webview_.contentWindow| may be null after network error screen
- // is shown. See crbug.com/770999.
+ // |this.webview_.contentWindow| may be null after network error
+ // screen is shown. See crbug.com/770999.
if (this.webview_.contentWindow) {
this.webview_.contentWindow.postMessage(msg, currentUrl);
} else {
@@ -1029,7 +1142,5 @@ cr.define('cr.login', function() {
Authenticator.AuthMode = AuthMode;
Authenticator.SUPPORTED_PARAMS = SUPPORTED_PARAMS;
- return {
- Authenticator: Authenticator
- };
+ return {Authenticator: Authenticator};
});
diff --git a/chromium/chrome/browser/resources/hats/hats.html b/chromium/chrome/browser/resources/hats/hats.html
index 572ef43d43d..08793f12a1d 100644
--- a/chromium/chrome/browser/resources/hats/hats.html
+++ b/chromium/chrome/browser/resources/hats/hats.html
@@ -1,15 +1,69 @@
-<!doctype html>
<html>
-<head>
- <meta charset="utf-8">
- <script src="chrome://resources/js/cr.js"></script>
- <script src="chrome://resources/js/load_time_data.js"></script>
- <script src="chrome://resources/js/util.js"></script>
- <script src="strings.js"></script>
- <script src="hats.js"></script>
-</head>
-<body>
- <webview id="survey" src="http://surveys.google.com/unit?site=z4cctguzopq5x2ftal6vdgjrui">
- </webview>
-</body>
+ <head>
+ <style>
+ /**
+ * The style used to draw done-button.
+ * Use z-index to make sure the button is in front of the survey content.
+ * TODO(weili): we need to make it RTL friendly if we need to support RTL.
+ */
+ .done-button {
+ bottom: 17px;
+ color: rgb(33, 150, 243);
+ display: block;
+ font: 400 16px Roboto,RobotoDraft,Helvetica,sans-serif;
+ position: fixed;
+ right: 25px;
+ text-transform: uppercase;
+ z-index: 10;
+ }
+
+ #id-done-button[hidden] {
+ display: none;
+ }
+ </style>
+ <script>
+ /**
+ * Handles the callback when the survey is submitted or when the survey
+ * has already been submitted in the past.
+ * @param {boolean} isFirstRun Will be true when the user just earned
+ * access to the content and false if the user had already had access
+ * previously.
+ */
+ function didFinishSurvey(isFirstRun) {
+ if (!isFirstRun) {
+ return;
+ }
+
+ /* Display the done button at the end of the survey. */
+ document.getElementById('id-done-button').hidden = false;
+
+ /* Auto dismiss after two seconds. */
+ setTimeout(function(){ window.close(); }, 2000);
+ };
+
+ /**
+ * Called after the survey HTML is injected into the page.
+ */
+ function onSurveyShown() {
+ /* Don't show logo on the survey */
+ const elements = document.getElementsByClassName('t402-prompt-logo');
+ for (const element of elements)
+ element.style.display = 'none';
+ }
+
+ document.addEventListener('DOMContentLoaded', function() {
+ document.getElementById('id-link-done-button').onclick = function() {
+ window.close();
+ }
+ })
+ </script>
+ <script src="$SCRIPT_SRC"></script>
+ </head>
+ <body>
+ <a id="id-link-done-button" href="#" role="button">
+ <div id="id-done-button" class="done-button" hidden>
+ $DONE_BUTTON_LABEL
+ </div>
+ </a>
+ </body>
</html>
diff --git a/chromium/chrome/browser/resources/hats/hats.js b/chromium/chrome/browser/resources/hats/hats.js
deleted file mode 100644
index ab5da2262a6..00000000000
--- a/chromium/chrome/browser/resources/hats/hats.js
+++ /dev/null
@@ -1,27 +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.
-
-cr.define('hats', function() {
- 'use strict';
-
- // Install the survey script from HaTS.
- function setScript() {
- const webview = $('survey');
- const loadstop = function() {
- webview.executeScript({
- code: 'document.getElementById(\'contain-402\').style.position =' +
- ' \'static\''
- });
- chrome.send('afterShow');
- };
- webview.addEventListener('loadstop', loadstop);
- }
- // Return an object with all of the exports.
- return {
- setScript: setScript,
- };
-});
-
-
-document.addEventListener('DOMContentLoaded', hats.setScript);
diff --git a/chromium/chrome/browser/resources/history/app.html b/chromium/chrome/browser/resources/history/app.html
index 736edaf8f1d..2e14bd06efe 100644
--- a/chromium/chrome/browser/resources/history/app.html
+++ b/chromium/chrome/browser/resources/history/app.html
@@ -1,5 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr/ui.html">
<link rel="import" href="chrome://resources/html/cr/ui/command.html">
@@ -19,7 +20,7 @@
<dom-module id="history-app">
<template>
- <style include="shared-style">
+ <style include="cr-shared-style shared-style">
:host {
color: var(--cr-primary-text-color);
display: block;
@@ -48,10 +49,6 @@
height: 100%;
}
- #drop-shadow {
- @apply --cr-container-shadow;
- }
-
:host([toolbar-shadow_]) #drop-shadow {
opacity: var(--cr-container-shadow-max-opacity);
}
@@ -76,7 +73,7 @@
queryState_.searchTerm)]]">
</history-toolbar>
- <div id="drop-shadow"></div>
+ <div id="drop-shadow" class="cr-container-shadow"></div>
<div id="main-container">
<history-side-bar id="content-side-bar" selected-page="{{selectedPage_}}"
footer-info="[[footerInfo]]"
diff --git a/chromium/chrome/browser/resources/history/externs.js b/chromium/chrome/browser/resources/history/externs.js
index 91ffe032e7f..d772532ad2d 100644
--- a/chromium/chrome/browser/resources/history/externs.js
+++ b/chromium/chrome/browser/resources/history/externs.js
@@ -12,6 +12,7 @@
* chrome/browser/ui/webui/browsing_history_handler.cc:
* BrowsingHistoryHandler::HistoryEntry::ToValue()
* @typedef {{allTimestamps: Array<number>,
+ * isUrlInRemoteUserData: boolean,
* blockedVisit: boolean,
* dateRelativeDay: string,
* dateShort: string,
diff --git a/chromium/chrome/browser/resources/history/history.html b/chromium/chrome/browser/resources/history/history.html
index 18214b510f5..af0c23e206f 100644
--- a/chromium/chrome/browser/resources/history/history.html
+++ b/chromium/chrome/browser/resources/history/history.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
<meta charset="utf8">
<title>$i18n{title}</title>
@@ -63,8 +63,10 @@
padding-inline-start: 24px;
}
- html[dark] #loading-toolbar {
- color: rgb(232, 234, 237); /* --google-grey-200 */
+ @media (prefers-color-scheme: dark) {
+ #loading-toolbar {
+ color: rgb(232, 234, 237); /* --google-grey-200 */
+ }
}
#loading-message {
@@ -97,7 +99,6 @@
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="constants.html">
<script src="history.js"></script>
- <link rel="import" href="chrome://resources/html/dark_mode.html">
<link rel="import" href="app.html" async id="bundle">
</body>
diff --git a/chromium/chrome/browser/resources/history/history_item.html b/chromium/chrome/browser/resources/history/history_item.html
index d8a261a0b06..a8094b71a58 100644
--- a/chromium/chrome/browser/resources/history/history_item.html
+++ b/chromium/chrome/browser/resources/history/history_item.html
@@ -121,8 +121,10 @@
margin-inline-start: 77px;
}
- :host-context([dark]) #time-gap-separator {
- border-color: var(--google-grey-refresh-500);
+ @media (prefers-color-scheme: dark) {
+ #time-gap-separator {
+ border-color: var(--google-grey-refresh-500);
+ }
}
#background-clip {
diff --git a/chromium/chrome/browser/resources/history/history_item.js b/chromium/chrome/browser/resources/history/history_item.js
index 3e48c932e89..ad4a3f2a597 100644
--- a/chromium/chrome/browser/resources/history/history_item.js
+++ b/chromium/chrome/browser/resources/history/history_item.js
@@ -254,7 +254,8 @@ cr.define('history', function() {
* @private
*/
itemChanged_: function() {
- this.$.icon.style.backgroundImage = cr.icon.getFavicon(this.item.url);
+ this.$.icon.style.backgroundImage =
+ cr.icon.getFavicon(this.item.url, this.item.isUrlInRemoteUserData);
this.listen(this.$['time-accessed'], 'mouseover', 'addTimeTitle_');
},
diff --git a/chromium/chrome/browser/resources/history/history_list.html b/chromium/chrome/browser/resources/history/history_list.html
index e1934670427..cbd4f20d146 100644
--- a/chromium/chrome/browser/resources/history/history_list.html
+++ b/chromium/chrome/browser/resources/history/history_list.html
@@ -1,7 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-a11y-announcer/iron-a11y-announcer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
@@ -11,11 +10,11 @@
<link rel="import" href="history_item.html">
<link rel="import" href="shared_style.html">
-<!-- Lazy loaded: cr-dialog, cr-action-menu, paper-button. -->
+<!-- Lazy loaded: cr-dialog, cr-action-menu, cr-button. -->
<dom-module id="history-list">
<template>
- <style include="shared-style cr-shared-style paper-button-style">
+ <style include="shared-style cr-shared-style">
:host {
box-sizing: border-box;
display: block;
@@ -65,12 +64,12 @@
<div slot="title">$i18n{removeSelected}</div>
<div slot="body">$i18n{deleteWarning}</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onDialogCancelTap_">
+ <cr-button class="cancel-button" on-click="onDialogCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onDialogConfirmTap_">
+ </cr-button>
+ <cr-button class="action-button" on-click="onDialogConfirmTap_">
$i18n{deleteConfirm}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/history/history_toolbar.html b/chromium/chrome/browser/resources/history/history_toolbar.html
index cd86b39440a..9357ef7446d 100644
--- a/chromium/chrome/browser/resources/history/history_toolbar.html
+++ b/chromium/chrome/browser/resources/history/history_toolbar.html
@@ -12,6 +12,7 @@
<style include="shared-style">
:host {
display: flex;
+ overflow: hidden;
position: relative;
}
diff --git a/chromium/chrome/browser/resources/history/lazy_load.html b/chromium/chrome/browser/resources/history/lazy_load.html
index 53567c5d365..567691b16bb 100644
--- a/chromium/chrome/browser/resources/history/lazy_load.html
+++ b/chromium/chrome/browser/resources/history/lazy_load.html
@@ -3,11 +3,11 @@
<body>
<link rel="import" href="synced_device_manager.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+ <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_drawer/cr_drawer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar_selection_overlay.html">
- <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
</body>
</html>
diff --git a/chromium/chrome/browser/resources/history/shared_vars.html b/chromium/chrome/browser/resources/history/shared_vars.html
index 38997d3c893..ba04f03fcbe 100644
--- a/chromium/chrome/browser/resources/history/shared_vars.html
+++ b/chromium/chrome/browser/resources/history/shared_vars.html
@@ -32,13 +32,15 @@
--toolbar-height: 56px;
}
- html[dark] {
- --card-border-color: var(--cr-separator-color);
- --history-item-time-color: var(--cr-secondary-text-color);
- --interactive-color: var(--google-blue-refresh-300);
- --separator-color: var(--cr-separator-color);
- --sidebar-footer-text-color: rgba(255, 255, 255, 0.6);
- --sidebar-unselected-color: var(--cr-secondary-text-color);
+ @media (prefers-color-scheme: dark) {
+ html {
+ --card-border-color: var(--cr-separator-color);
+ --history-item-time-color: var(--cr-secondary-text-color);
+ --interactive-color: var(--google-blue-refresh-300);
+ --separator-color: var(--cr-separator-color);
+ --sidebar-footer-text-color: rgba(255, 255, 255, 0.6);
+ --sidebar-unselected-color: var(--cr-secondary-text-color);
+ }
}
</style>
</custom-style>
diff --git a/chromium/chrome/browser/resources/history/synced_device_card.js b/chromium/chrome/browser/resources/history/synced_device_card.js
index 083d18f4b4d..d1a1f8db25b 100644
--- a/chromium/chrome/browser/resources/history/synced_device_card.js
+++ b/chromium/chrome/browser/resources/history/synced_device_card.js
@@ -113,7 +113,10 @@ Polymer({
const icons = this.shadowRoot.querySelectorAll('.website-icon');
for (let i = 0; i < this.tabs.length; i++) {
- icons[i].style.backgroundImage = cr.icon.getFavicon(this.tabs[i].url);
+ // Entries on this UI are coming strictly from sync, so we can set
+ // |isSyncedUrlForHistoryUi| to true on the getFavicon call below.
+ icons[i].style.backgroundImage =
+ cr.icon.getFavicon(this.tabs[i].url, true);
}
});
},
diff --git a/chromium/chrome/browser/resources/history/synced_device_manager.html b/chromium/chrome/browser/resources/history/synced_device_manager.html
index 0d077c9d7ba..e6a4a15b001 100644
--- a/chromium/chrome/browser/resources/history/synced_device_manager.html
+++ b/chromium/chrome/browser/resources/history/synced_device_manager.html
@@ -2,10 +2,9 @@
<link rel="import" href="chrome://resources/html/cr/ui/focus_grid.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="shared_style.html">
@@ -14,7 +13,7 @@
<dom-module id="history-synced-device-manager">
<template>
- <style include="shared-style cr-shared-style paper-button-style">
+ <style include="shared-style cr-shared-style">
:host {
display: block;
overflow: auto;
@@ -28,8 +27,10 @@
width: 594.5px;
}
- :host-context([dark]) #illustration {
- background-image: url(images/sign_in_promo_dark.svg);
+ @media (prefers-color-scheme: dark) {
+ #illustration {
+ background-image: url(images/sign_in_promo_dark.svg);
+ }
}
#no-synced-tabs {
@@ -86,10 +87,10 @@
<div id="illustration"></div>
<div id="sign-in-promo">$i18n{signInPromo}</div>
<div id="sign-in-promo-desc">$i18n{signInPromoDesc}</div>
- <paper-button id="sign-in-button" class="action-button"
+ <cr-button id="sign-in-button" class="action-button"
on-click="onSignInTap_">
$i18n{signInButton}
- </paper-button>
+ </cr-button>
</div>
<cr-lazy-render id="menu">
diff --git a/chromium/chrome/browser/resources/identity_internals/identity_internals.css b/chromium/chrome/browser/resources/identity_internals/identity_internals.css
index 4d30370ae3e..e1b04cd7fa5 100644
--- a/chromium/chrome/browser/resources/identity_internals/identity_internals.css
+++ b/chromium/chrome/browser/resources/identity_internals/identity_internals.css
@@ -19,6 +19,7 @@ tr:nth-child(odd) {
td.label {
font-weight: bold;
vertical-align: top;
+ white-space: nowrap;
}
td.token-actions {
diff --git a/chromium/chrome/browser/resources/identity_internals/identity_internals.html b/chromium/chrome/browser/resources/identity_internals/identity_internals.html
index 537e7246602..d30fc010620 100644
--- a/chromium/chrome/browser/resources/identity_internals/identity_internals.html
+++ b/chromium/chrome/browser/resources/identity_internals/identity_internals.html
@@ -1,19 +1,17 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}">
+<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
- <title>$i18n{tokenCacheHeader}</title>
+ <title>Identity API Token Cache</title>
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
<link rel="stylesheet" href="identity_internals.css">
<script src="chrome://resources/js/cr.js"></script>
- <script src="chrome://resources/js/load_time_data.js"></script>
<script src="chrome://resources/js/cr/ui.js"></script>
<script src="chrome://resources/js/util.js"></script>
- <script src="strings.js"></script>
<script src="identity_internals.js"></script>
</head>
<body>
- <h2 class="header">$i18n{tokenCacheHeader}</h2>
+ <h2 class="header">Identity API Token Cache</h2>
<div id="token-list"></div>
</body>
</html>
diff --git a/chromium/chrome/browser/resources/identity_internals/identity_internals.js b/chromium/chrome/browser/resources/identity_internals/identity_internals.js
index b7d72473f68..23cb35553cf 100644
--- a/chromium/chrome/browser/resources/identity_internals/identity_internals.js
+++ b/chromium/chrome/browser/resources/identity_internals/identity_internals.js
@@ -29,15 +29,15 @@ cr.define('identity_internals', function() {
const table = this.ownerDocument.createElement('table');
const tbody = this.ownerDocument.createElement('tbody');
tbody.appendChild(this.createEntry_(
- 'accessToken', this.data_.accessToken, 'access-token'));
+ 'Access Token', this.data_.accessToken, 'access-token'));
tbody.appendChild(this.createEntry_(
- 'extensionName', this.data_.extensionName, 'extension-name'));
+ 'Extension Name', this.data_.extensionName, 'extension-name'));
tbody.appendChild(this.createEntry_(
- 'extensionId', this.data_.extensionId, 'extension-id'));
+ 'Extension Id', this.data_.extensionId, 'extension-id'));
tbody.appendChild(
- this.createEntry_('tokenStatus', this.data_.status, 'token-status'));
+ this.createEntry_('Token Status', this.data_.status, 'token-status'));
tbody.appendChild(this.createEntry_(
- 'expirationTime', this.data_.expirationTime, 'expiration-time'));
+ 'Expiration Time', this.data_.expirationTime, 'expiration-time'));
tbody.appendChild(this.createEntryForScopes_());
table.appendChild(tbody);
const tfoot = this.ownerDocument.createElement('tfoot');
@@ -48,7 +48,7 @@ cr.define('identity_internals', function() {
/**
* Creates an entry for a single property of the token.
- * @param {string} label An i18n label of the token's property name.
+ * @param {string} label A label of the token's property name.
* @param {string} value A value of the token property.
* @param {string} accessor Additional class to tag the field for testing.
* @return {HTMLElement} An HTML element with the property name and value.
@@ -57,7 +57,7 @@ cr.define('identity_internals', function() {
const row = this.ownerDocument.createElement('tr');
const labelField = this.ownerDocument.createElement('td');
labelField.classList.add('label');
- labelField.textContent = loadTimeData.getString(label);
+ labelField.textContent = label;
row.appendChild(labelField);
const valueField = this.ownerDocument.createElement('td');
valueField.classList.add('value');
@@ -75,7 +75,7 @@ cr.define('identity_internals', function() {
const row = this.ownerDocument.createElement('tr');
const labelField = this.ownerDocument.createElement('td');
labelField.classList.add('label');
- labelField.textContent = loadTimeData.getString('scopes');
+ labelField.textContent = 'Scopes';
row.appendChild(labelField);
const valueField = this.ownerDocument.createElement('td');
valueField.classList.add('value');
@@ -117,7 +117,7 @@ cr.define('identity_internals', function() {
'identityInternalsRevokeToken',
[this.data_.extensionId, this.data_.accessToken]);
}.bind(this));
- revokeButton.textContent = loadTimeData.getString('revoke');
+ revokeButton.textContent = 'Revoke';
return revokeButton;
},
};
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_header/BUILD.gn b/chromium/chrome/browser/resources/interventions_internals/BUILD.gn
index 20336476804..e6c48042880 100644
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_header/BUILD.gn
+++ b/chromium/chrome/browser/resources/interventions_internals/BUILD.gn
@@ -1,4 +1,4 @@
-# Copyright 2018 The Chromium Authors. All rights reserved.
+# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -6,14 +6,15 @@ import("//third_party/closure_compiler/compile_js.gni")
js_type_check("closure_compile") {
deps = [
- ":media_router_header",
+ ":index",
]
}
-js_library("media_router_header") {
+js_library("index") {
deps = [
- "../..:media_router_data",
- "//ui/webui/resources/js:i18n_behavior",
+ "//chrome/browser/ui/webui/interventions_internals:mojo_bindings_js_library_for_compile",
+ "//ui/webui/resources/js:assert",
+ "//ui/webui/resources/js:cr",
"//ui/webui/resources/js:util",
]
}
diff --git a/chromium/chrome/browser/resources/interventions_internals/index.js b/chromium/chrome/browser/resources/interventions_internals/index.js
index ebd00b9f9fa..c417033d8c4 100644
--- a/chromium/chrome/browser/resources/interventions_internals/index.js
+++ b/chromium/chrome/browser/resources/interventions_internals/index.js
@@ -284,7 +284,7 @@ function changeTab() {
* Helper function to check if all keywords, case insensitive, are in the given
* text.
*
- * @param {string[]} keywords The collection of keywords.
+ * @param {Array<string>} keywords The collection of keywords.
* @param {string} text The given text to search.
* @return True iff all keywords present in the given text.
*/
@@ -370,7 +370,7 @@ function setupExpandLogs() {
* Create and add a copy to clipboard button to a given node.
*
* @param {string} text The text that will be copied to the clipboard.
- * @param {element!} node The node that will have the button appended to.
+ * @param {Element} node The node that will have the button appended to.
*/
function appendCopyToClipBoardButton(text, node) {
if (!document.queryCommandSupported ||
@@ -449,15 +449,20 @@ function setupLogClear() {
$('clear-log-button').addEventListener('click', removeAllLogMessagesRows);
}
-/** @constructor */
-const InterventionsInternalPageImpl = function() {};
+/**
+ * @constructor
+ * @implements {mojom.InterventionsInternalsPageInterface}
+ */
+const InterventionsInternalPageImpl = function() {
+ this.receiver_ = new mojom.InterventionsInternalsPageReceiver(this);
+};
InterventionsInternalPageImpl.prototype = {
/**
* Post a new log message to the web page.
*
* @override
- * @param {!MessageLog} log The new log message recorded by
+ * @param {!mojom.MessageLog} log The new log message recorded by
* PreviewsLogger.
*/
logNewMessage: function(log) {
@@ -580,6 +585,14 @@ InterventionsInternalPageImpl.prototype = {
nqeCol.textContent = type;
nqeRow.appendChild(nqeCol);
},
+
+ /**
+ * Returns a remote interface to the receiver.
+ */
+ bindNewPipeAndPassRemote: function() {
+ const helper = this.receiver_.$;
+ return helper.bindNewPipeAndPassRemote();
+ },
};
cr.define('interventions_internals', () => {
@@ -600,23 +613,7 @@ cr.define('interventions_internals', () => {
}
/**
- * Sort keys by the value of each value by its description attribute of a
- * |mapObject|.
- *
- * @param mapObject {!Map<string, Object} A map where all values have a
- * description attribute.
- * @return A list of keys sorted by their descriptions.
- */
- function getSortedKeysByDescription(mapObject) {
- const sortedKeys = Array.from(mapObject.keys());
- sortedKeys.sort((a, b) => {
- return mapObject.get(a).description > mapObject.get(b).description;
- });
- return sortedKeys;
- }
-
- /**
- * Retrieves the statuses of previews (i.e. Offline, LoFi, AMP Redirection),
+ * Retrieves the statuses of previews (i.e. Offline, Lite Pages, etc),
* and posts them on chrome://intervention-internals.
*/
function getPreviewsEnabled() {
@@ -699,12 +696,11 @@ document.addEventListener('DOMContentLoaded', () => {
if (window.testPageHandler) {
pageHandler = window.testPageHandler;
} else {
- pageHandler = mojom.InterventionsInternalsPageHandler.getProxy();
+ pageHandler = mojom.InterventionsInternalsPageHandler.getRemote();
// Set up client side mojo interface.
pageImpl = new InterventionsInternalPageImpl();
- const client = new mojom.InterventionsInternalsPage(pageImpl);
- pageHandler.setClientPage(client.createProxy());
+ pageHandler.setClientPage(pageImpl.bindNewPipeAndPassRemote());
}
interventions_internals.init(pageHandler);
diff --git a/chromium/chrome/browser/resources/kiosk_next_internal_resources.grd b/chromium/chrome/browser/resources/kiosk_next_internal_resources.grd
deleted file mode 100644
index 6418df00224..00000000000
--- a/chromium/chrome/browser/resources/kiosk_next_internal_resources.grd
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<grit latest_public_release="0" current_release="1" output_all_resource_defines="false">
- <outputs>
- <output filename="grit/kiosk_next_internal_resources.h" type="rc_header">
- <emit emit_type='prepend'></emit>
- </output>
- <output filename="grit/kiosk_next_internal_resources_map.cc" type="resource_file_map_source" />
- <output filename="grit/kiosk_next_internal_resources_map.h" type="resource_map_header" />
- <output filename="kiosk_next_internal_resources.pak" type="data_package" />
- </outputs>
- <release seq="1">
- <includes>
- <part file="chromeos/kiosk_next_home/internal/kiosk_next_resources_internal.grdp" />
- </includes>
- </release>
-</grit>
diff --git a/chromium/chrome/browser/resources/local_discovery/local_discovery.js b/chromium/chrome/browser/resources/local_discovery/local_discovery.js
index 780d9abd46e..7094e5cec6b 100644
--- a/chromium/chrome/browser/resources/local_discovery/local_discovery.js
+++ b/chromium/chrome/browser/resources/local_discovery/local_discovery.js
@@ -15,24 +15,6 @@
cr.define('local_discovery', function() {
'use strict';
- // Histogram buckets for UMA tracking.
- /** @const */ const DEVICES_PAGE_EVENTS = {
- OPENED: 0,
- LOG_IN_STARTED_FROM_REGISTER_PROMO: 1,
- LOG_IN_STARTED_FROM_DEVICE_LIST_PROMO: 2,
- ADD_PRINTER_CLICKED: 3,
- REGISTER_CLICKED: 4,
- REGISTER_CONFIRMED: 5,
- REGISTER_SUCCESS: 6,
- REGISTER_CANCEL: 7,
- REGISTER_FAILURE: 8,
- MANAGE_CLICKED: 9,
- REGISTER_CANCEL_ON_PRINTER: 10,
- REGISTER_TIMEOUT: 11,
- LOG_IN_STARTED_FROM_REGISTER_OVERLAY_PROMO: 12,
- MAX_EVENT: 13,
- };
-
/**
* Map of service names to corresponding service objects.
* @type {Object<string,Service>}
@@ -121,7 +103,6 @@ cr.define('local_discovery', function() {
* Register the device.
*/
register: function() {
- recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_CONFIRMED);
chrome.send('registerDevice', [this.info.service_name]);
setRegisterPage('register-printer-page-adding1');
},
@@ -129,7 +110,6 @@ cr.define('local_discovery', function() {
* Show registrtation UI for device.
*/
showRegister: function() {
- recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_CLICKED);
$('register-continue').onclick = this.register.bind(this);
showRegisterOverlay();
@@ -220,8 +200,6 @@ cr.define('local_discovery', function() {
* Show the register overlay.
*/
function showRegisterOverlay() {
- recordUmaEvent(DEVICES_PAGE_EVENTS.ADD_PRINTER_CLICKED);
-
const registerOverlay = $('register-overlay');
registerOverlay.classList.add('showing');
registerOverlay.focus();
@@ -255,7 +233,6 @@ cr.define('local_discovery', function() {
$('error-message').textContent =
loadTimeData.getString('addingErrorMessage');
setRegisterPage('register-page-error');
- recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_FAILURE);
}
/**
@@ -265,7 +242,6 @@ cr.define('local_discovery', function() {
$('error-message').textContent =
loadTimeData.getString('addingCanceledMessage');
setRegisterPage('register-page-error');
- recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_CANCEL_ON_PRINTER);
}
/**
@@ -275,7 +251,6 @@ cr.define('local_discovery', function() {
$('error-message').textContent =
loadTimeData.getString('addingTimeoutMessage');
setRegisterPage('register-page-error');
- recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_TIMEOUT);
}
/**
@@ -405,7 +380,6 @@ cr.define('local_discovery', function() {
const deviceDOM = createCloudDeviceDOM(deviceData);
$('cloud-devices').insertBefore(deviceDOM, $('cloud-devices').firstChild);
- recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_SUCCESS);
}
/**
@@ -440,28 +414,15 @@ cr.define('local_discovery', function() {
* @param {string} deviceId ID of device.
*/
function manageCloudDevice(deviceId) {
- recordUmaEvent(DEVICES_PAGE_EVENTS.MANAGE_CLICKED);
chrome.send('openCloudPrintURL', [deviceId]);
}
/**
- * Record an event in the UMA histogram.
- * @param {number} eventId The id of the event to be recorded.
- * @private
- */
- function recordUmaEvent(eventId) {
- chrome.send(
- 'metricsHandler:recordInHistogram',
- ['LocalDiscovery.DevicesPage', eventId, DEVICES_PAGE_EVENTS.MAX_EVENT]);
- }
-
- /**
* Cancel the registration.
*/
function cancelRegistration() {
hideRegisterOverlay();
chrome.send('cancelRegistration');
- recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_CANCEL);
}
/**
@@ -513,18 +474,14 @@ cr.define('local_discovery', function() {
}
function registerLoginButtonClicked() {
- recordUmaEvent(DEVICES_PAGE_EVENTS.LOG_IN_STARTED_FROM_REGISTER_PROMO);
openSignInPage();
}
function registerOverlayLoginButtonClicked() {
- recordUmaEvent(
- DEVICES_PAGE_EVENTS.LOG_IN_STARTED_FROM_REGISTER_OVERLAY_PROMO);
openSignInPage();
}
function cloudDevicesLoginButtonClicked() {
- recordUmaEvent(DEVICES_PAGE_EVENTS.LOG_IN_STARTED_FROM_DEVICE_LIST_PROMO);
openSignInPage();
}
@@ -597,7 +554,6 @@ cr.define('local_discovery', function() {
focusManager.initialize();
chrome.send('start');
- recordUmaEvent(DEVICES_PAGE_EVENTS.OPENED);
});
return {
diff --git a/chromium/chrome/browser/resources/local_ntp/BUILD.gn b/chromium/chrome/browser/resources/local_ntp/BUILD.gn
index 22531ae249c..9b5c6384365 100644
--- a/chromium/chrome/browser/resources/local_ntp/BUILD.gn
+++ b/chromium/chrome/browser/resources/local_ntp/BUILD.gn
@@ -13,8 +13,8 @@ js_type_check("closure_compile") {
js_library("local_ntp") {
sources = [
"animations.js",
- "custom_backgrounds.js",
"custom_links_edit.js",
+ "customize.js",
"doodles.js",
"local_ntp.js",
"most_visited_single.js",
diff --git a/chromium/chrome/browser/resources/local_ntp/OWNERS b/chromium/chrome/browser/resources/local_ntp/OWNERS
index 81e7a847eda..a07a69b93f4 100644
--- a/chromium/chrome/browser/resources/local_ntp/OWNERS
+++ b/chromium/chrome/browser/resources/local_ntp/OWNERS
@@ -1,11 +1,5 @@
+file://components/search/OWNERS
fserb@chromium.org
-kmilka@chromium.org
-kristipark@chromium.org
-mathp@chromium.org
-ramyan@chromium.org
-treib@chromium.org
-
-per-file local_ntp_resources.grd=file://components/search/OWNERS
# TEAM: ntp-dev@chromium.org
# COMPONENT: UI>Browser>NewTabPage
diff --git a/chromium/chrome/browser/resources/local_ntp/animations.css b/chromium/chrome/browser/resources/local_ntp/animations.css
index 465d029a3ad..a6572eefd20 100644
--- a/chromium/chrome/browser/resources/local_ntp/animations.css
+++ b/chromium/chrome/browser/resources/local_ntp/animations.css
@@ -22,26 +22,30 @@
}
.ripple-effect {
- background-color: rgba(var(--GB600-rgb), 0.1);
+ background-color: rgba(var(--GB600-rgb), .1);
border-radius: 50%;
height: 1px;
pointer-events: none;
transition: width, height, margin, background-color 400ms 250ms;
transition-duration: 400ms;
- transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
width: 1px;
}
-html[darkmode=true] .ripple-effect {
- background-color: rgba(var(--GB300-rgb), 0.32);
+@media (prefers-color-scheme: dark) {
+ .ripple-effect {
+ background-color: rgba(var(--GB300-rgb), .32);
+ }
}
button.primary .ripple-effect {
- background-color: rgba(255, 255, 255, 0.32);
+ background-color: rgba(255, 255, 255, .32);
}
-html[darkmode=true] button.primary .ripple-effect {
- background-color: rgba(0, 0, 0, 0.08);
+@media (prefers-color-scheme: dark) {
+ button.primary .ripple-effect {
+ background-color: rgba(0, 0, 0, .08);
+ }
}
button.paper {
@@ -55,7 +59,11 @@ button.paper {
position: relative;
transition-duration: 200ms;
transition-property: background-color, color, box-shadow, border;
- transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
+ transition-timing-function: cubic-bezier(.4, 0, .2, 1);
+}
+
+button.paper:not(:disabled) {
+ cursor: pointer;
}
button.paper:disabled {
@@ -67,9 +75,11 @@ button.paper.primary {
color: white;
}
-html[darkmode=true] button.paper.primary {
- background-color: rgb(var(--GB300-rgb));
- color: rgb(var(--GG900-rgb));
+@media (prefers-color-scheme: dark) {
+ button.paper.primary {
+ background-color: rgb(var(--GB300-rgb));
+ color: rgb(var(--GG900-rgb));
+ }
}
button.paper.primary:disabled {
@@ -77,30 +87,36 @@ button.paper.primary:disabled {
color: rgb(var(--GG600-rgb));
}
-html[darkmode=true] button.paper.primary:disabled {
- background-color: rgb(var(--GG800-rgb));
- color: rgb(var(--GG600-rgb));
+@media (prefers-color-scheme: dark) {
+ button.paper.primary:disabled {
+ background-color: rgb(var(--GG800-rgb));
+ color: rgb(var(--GG600-rgb));
+ }
}
button.paper.primary:hover:not(:disabled) {
background-color: rgb(41, 123, 231);
- box-shadow: 0 1px 2px 0 rgba(var(--GB500-rgb), 0.3),
- 0 1px 3px 1px rgba(var(--GB500-rgb), 0.15);
+ box-shadow: 0 1px 2px 0 rgba(var(--GB500-rgb), .3),
+ 0 1px 3px 1px rgba(var(--GB500-rgb), .15);
}
-html[darkmode=true] button.paper.primary:hover:not(:disabled) {
- background-color: rgb(133, 173, 238);
+@media (prefers-color-scheme: dark) {
+ button.paper.primary:hover:not(:disabled) {
+ background-color: rgb(133, 173, 238);
+ }
}
button.paper.primary:active:not(:disabled) {
- box-shadow: 0 1px 2px 0 rgba(var(--GB500-rgb), 0.3),
- 0 3px 6px 2px rgba(var(--GB500-rgb), 0.15);
+ box-shadow: 0 1px 2px 0 rgba(var(--GB500-rgb), .3),
+ 0 3px 6px 2px rgba(var(--GB500-rgb), .15);
}
-html[darkmode=true] button.paper.primary:active:not(:disabled) {
- background-color: rgb(115, 160, 223);
- box-shadow: 0 1px 2px 0 rgba(var(--GB500-rgb), 0.3),
- 0 3px 6px 2px rgba(var(--GB500-rgb), 0.15);
+@media (prefers-color-scheme: dark) {
+ button.paper.primary:active:not(:disabled) {
+ background-color: rgb(115, 160, 223);
+ box-shadow: 0 1px 2px 0 rgba(var(--GB500-rgb), .3),
+ 0 3px 6px 2px rgba(var(--GB500-rgb), .15);
+ }
}
button.paper.secondary {
@@ -109,10 +125,12 @@ button.paper.secondary {
color: rgb(var(--GB600-rgb));
}
-html[darkmode=true] button.paper.secondary {
- background-color: transparent;
- border-color: rgb(var(--GG700-rgb));
- color: rgb(var(--GB300-rgb));
+@media (prefers-color-scheme: dark) {
+ button.paper.secondary {
+ background-color: transparent;
+ border-color: rgb(var(--GG700-rgb));
+ color: rgb(var(--GB300-rgb));
+ }
}
button.paper.secondary:disabled {
@@ -120,33 +138,39 @@ button.paper.secondary:disabled {
color: rgb(var(--GG600-rgb));
}
-html[darkmode=true] button.paper.secondary:disabled {
- border-color: rgb(var(--GG800-rgb));
- color: rgb(var(--GG600-rgb));
+@media (prefers-color-scheme: dark) {
+ button.paper.secondary:disabled {
+ border-color: rgb(var(--GG800-rgb));
+ color: rgb(var(--GG600-rgb));
+ }
}
button.paper.secondary:hover:not(:disabled) {
- background-color: rgba(var(--GB500-rgb), 0.04);
+ background-color: rgba(var(--GB500-rgb), .04);
border-color: rgb(var(--GB100-rgb));
}
-html[darkmode=true] button.paper.secondary:hover:not(:disabled) {
- background-color: rgba(var(--GB300-rgb), 0.04);
- border-color: rgba(var(--GB300-rgb), 0.5);
- box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.3),
- 0 1px 3px 1px rgba(0, 0, 0, 0.15);
+@media (prefers-color-scheme: dark) {
+ button.paper.secondary:hover:not(:disabled) {
+ background-color: rgba(var(--GB300-rgb), .04);
+ border-color: rgba(var(--GB300-rgb), .5);
+ box-shadow: 0 1px 2px 0 rgba(0, 0, 0, .3),
+ 0 1px 3px 1px rgba(0, 0, 0, .15);
+ }
}
button.paper.secondary:active:not(:disabled) {
background-color: white;
border-color: white;
- box-shadow: 0 1px 2px 0 rgba(var(--GG800-rgb), 0.3),
- 0 3px 6px 2px rgba(var(--GG800-rgb), 0.15);
+ box-shadow: 0 1px 2px 0 rgba(var(--GG800-rgb), .3),
+ 0 3px 6px 2px rgba(var(--GG800-rgb), .15);
}
-html[darkmode=true] button.paper.secondary:active:not(:disabled) {
- background-color: rgba(var(--GB300-rgb), 0.08);
- border-color: rgba(var(--GB300-rgb), 0.5);
- box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.3),
- 0 3px 6px 2px rgba(0, 0, 0, 0.15);
+@media (prefers-color-scheme: dark) {
+ button.paper.secondary:active:not(:disabled) {
+ background-color: rgba(var(--GB300-rgb), .08);
+ border-color: rgba(var(--GB300-rgb), .5);
+ box-shadow: 0 1px 2px 0 rgba(0, 0, 0, .3),
+ 0 3px 6px 2px rgba(0, 0, 0, .15);
+ }
}
diff --git a/chromium/chrome/browser/resources/local_ntp/animations.js b/chromium/chrome/browser/resources/local_ntp/animations.js
index 92f9b093d67..04f2b17f712 100644
--- a/chromium/chrome/browser/resources/local_ntp/animations.js
+++ b/chromium/chrome/browser/resources/local_ntp/animations.js
@@ -2,13 +2,11 @@
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
-
/**
* Contains common animations used in the main NTP page and its iframes.
*/
const animations = {};
-
/**
* Enum for classnames.
* @enum {string}
@@ -21,7 +19,6 @@ animations.CLASSES = {
RIPPLE_EFFECT: 'ripple-effect',
};
-
/**
* The duration of the ripple animation.
* @type {number}
@@ -29,7 +26,6 @@ animations.CLASSES = {
*/
animations.RIPPLE_DURATION_MS = 800;
-
/**
* The max size of the ripple animation.
* @type {number}
@@ -37,7 +33,6 @@ animations.RIPPLE_DURATION_MS = 800;
*/
animations.RIPPLE_MAX_RADIUS_PX = 300;
-
/**
* Enables ripple animations for elements with CLASSES.RIPPLE. The target
* element must have position relative or absolute.
diff --git a/chromium/chrome/browser/resources/local_ntp/custom_backgrounds.js b/chromium/chrome/browser/resources/local_ntp/custom_backgrounds.js
deleted file mode 100644
index 8b5ddd35d5f..00000000000
--- a/chromium/chrome/browser/resources/local_ntp/custom_backgrounds.js
+++ /dev/null
@@ -1,1489 +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.
-
-
-'use strict';
-
-// TODO(crbug.com/937570): After the RP launches this should be renamed to
-// customizationMenu along with the file, and large parts can be refactored/removed.
-const customBackgrounds = {};
-
-/**
- * The browser embeddedSearch.newTabPage object.
- * @type {Object}
- */
-let ntpApiHandle;
-
-/**
- * The different types of events that are logged from the NTP. This enum is
- * used to transfer information from the NTP JavaScript to the renderer and is
- * not used as a UMA enum histogram's logged value.
- * Note: Keep in sync with common/ntp_logging_events.h
- * @enum {number}
- * @const
- */
-const BACKGROUND_CUSTOMIZATION_LOG_TYPE = {
- // The 'Chrome backgrounds' menu item was clicked.
- NTP_CUSTOMIZE_CHROME_BACKGROUNDS_CLICKED: 40,
- // The 'Upload an image' menu item was clicked.
- NTP_CUSTOMIZE_LOCAL_IMAGE_CLICKED: 41,
- // The 'Restore default background' menu item was clicked.
- NTP_CUSTOMIZE_RESTORE_BACKGROUND_CLICKED: 42,
- // The attribution link on a customized background image was clicked.
- NTP_CUSTOMIZE_ATTRIBUTION_CLICKED: 43,
- // The 'Restore default shortcuts' menu item was clicked.
- NTP_CUSTOMIZE_RESTORE_SHORTCUTS_CLICKED: 46,
- // A collection was selected in the 'Chrome backgrounds' dialog.
- NTP_CUSTOMIZE_CHROME_BACKGROUND_SELECT_COLLECTION: 47,
- // An image was selected in the 'Chrome backgrounds' dialog.
- NTP_CUSTOMIZE_CHROME_BACKGROUND_SELECT_IMAGE: 48,
- // 'Cancel' was clicked in the 'Chrome backgrounds' dialog.
- NTP_CUSTOMIZE_CHROME_BACKGROUND_CANCEL: 49,
- // NOTE: NTP_CUSTOMIZE_CHROME_BACKGROUND_DONE (50) is logged on the backend
- // when the selected image is saved.
- // 'Cancel' was clicked in the 'Upload an image' dialog.
- NTP_CUSTOMIZE_LOCAL_IMAGE_CANCEL: 51,
- // 'Done' was clicked in the 'Upload an image' dialog.
- NTP_CUSTOMIZE_LOCAL_IMAGE_DONE: 52,
-};
-
-/**
- * Enum for key codes.
- * @enum {number}
- * @const
- */
-customBackgrounds.KEYCODES = {
- BACKSPACE: 8,
- DOWN: 40,
- ENTER: 13,
- ESC: 27,
- LEFT: 37,
- RIGHT: 39,
- SPACE: 32,
- TAB: 9,
- UP: 38,
-};
-
-/**
- * Enum for HTML element ids.
- * @enum {string}
- * @const
- */
-customBackgrounds.IDS = {
- ATTR1: 'attr1',
- ATTR2: 'attr2',
- ATTRIBUTIONS: 'custom-bg-attr',
- BACK_CIRCLE: 'bg-sel-back-circle',
- BACKGROUNDS_DEFAULT: 'backgrounds-default',
- BACKGROUNDS_DEFAULT_ICON: 'backgrounds-default-icon',
- BACKGROUNDS_BUTTON: 'backgrounds-button',
- BACKGROUNDS_IMAGE_MENU: 'backgrounds-image-menu',
- BACKGROUNDS_MENU: 'backgrounds-menu',
- BACKGROUNDS_UPLOAD: 'backgrounds-upload',
- CANCEL: 'bg-sel-footer-cancel',
- COLORS_BUTTON: 'colors-button',
- COLORS_MENU: 'colors-menu',
- CUSTOMIZATION_MENU: 'customization-menu',
- CUSTOM_LINKS_RESTORE_DEFAULT: 'custom-links-restore-default',
- CUSTOM_LINKS_RESTORE_DEFAULT_TEXT: 'custom-links-restore-default-text',
- DEFAULT_WALLPAPERS: 'edit-bg-default-wallpapers',
- DEFAULT_WALLPAPERS_TEXT: 'edit-bg-default-wallpapers-text',
- DONE: 'bg-sel-footer-done',
- EDIT_BG: 'edit-bg',
- EDIT_BG_DIALOG: 'edit-bg-dialog',
- EDIT_BG_DIVIDER: 'edit-bg-divider',
- EDIT_BG_ICON: 'edit-bg-icon',
- EDIT_BG_MENU: 'edit-bg-menu',
- EDIT_BG_TEXT: 'edit-bg-text',
- MENU_BACK_CIRCLE: 'menu-back-circle',
- MENU_CANCEL: 'menu-cancel',
- MENU_DONE: 'menu-done',
- MENU_TITLE: 'menu-title',
- LINK_ICON: 'link-icon',
- MENU: 'bg-sel-menu',
- OPTIONS_TITLE: 'edit-bg-title',
- RESTORE_DEFAULT: 'edit-bg-restore-default',
- RESTORE_DEFAULT_TEXT: 'edit-bg-restore-default-text',
- SHORTCUTS_BUTTON: 'shortcuts-button',
- SHORTCUTS_MENU: 'shortcuts-menu',
- UPLOAD_IMAGE: 'edit-bg-upload-image',
- UPLOAD_IMAGE_TEXT: 'edit-bg-upload-image-text',
- TILES: 'bg-sel-tiles',
- TITLE: 'bg-sel-title',
-};
-
-/**
- * Enum for classnames.
- * @enum {string}
- * @const
- */
-customBackgrounds.CLASSES = {
- ATTR_SMALL: 'attr-small',
- ATTR_COMMON: 'attr-common',
- ATTR_LINK: 'attr-link',
- COLLECTION_DIALOG: 'is-col-sel',
- COLLECTION_SELECTED: 'bg-selected', // Highlight selected tile
- COLLECTION_TILE: 'bg-sel-tile', // Preview tile for background customization
- COLLECTION_TILE_BG: 'bg-sel-tile-bg',
- COLLECTION_TITLE: 'bg-sel-tile-title', // Title of a background image
- // Extended and elevated style for entry point.
- ENTRY_POINT_ENHANCED: 'ep-enhanced',
- IMAGE_DIALOG: 'is-img-sel',
- ON_IMAGE_MENU: 'on-img-menu',
- OPTION: 'bg-option',
- OPTION_DISABLED: 'bg-option-disabled', // The menu option is disabled.
- MENU_SHOWN: 'menu-shown',
- MOUSE_NAV: 'using-mouse-nav',
- SELECTED: 'selected',
- SELECTED_BORDER: 'selected-border',
- SELECTED_CHECK: 'selected-check',
- SELECTED_CIRCLE: 'selected-circle',
- SINGLE_ATTR: 'single-attr'
-};
-
-/**
- * Enum for background sources.
- * @enum {number}
- * @const
- */
-customBackgrounds.SOURCES = {
- NONE: -1,
- CHROME_BACKGROUNDS: 0,
- IMAGE_UPLOAD: 1,
-};
-
-/**
- * Enum for background option menu entries, in the order they appear in the UI.
- * @enum {number}
- * @const
- */
-customBackgrounds.MENU_ENTRIES = {
- CHROME_BACKGROUNDS: 0,
- UPLOAD_IMAGE: 1,
- CUSTOM_LINKS_RESTORE_DEFAULT: 2,
- RESTORE_DEFAULT: 3,
-};
-
-customBackgrounds.CUSTOM_BACKGROUND_OVERLAY =
- 'linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.3))';
-
-// These shound match the corresponding values in local_ntp.js, that control the
-// mv-notice element.
-customBackgrounds.delayedHideNotification = -1;
-customBackgrounds.NOTIFICATION_TIMEOUT = 10000;
-
-/* Were the background tiles already created.
- * @type {bool}
- */
-customBackgrounds.builtTiles = false;
-
-/* Tile that was selected by the user.
- * @type {HTMLElement}
- */
-customBackgrounds.selectedTile = null;
-
-/**
- * Number of rows in the custom background dialog to preload.
- * @type {number}
- * @const
- */
-customBackgrounds.ROWS_TO_PRELOAD = 3;
-
-/* Type of collection that is being browsed, needed in order
- * to return from the image dialog.
- * @type {number}
- */
-customBackgrounds.dialogCollectionsSource = customBackgrounds.SOURCES.NONE;
-
-/*
- * Called when the error notification should be shown.
- * @type {?Function}
- * @private
- */
-customBackgrounds.showErrorNotification = null;
-
-/*
- * Called when the custom link notification should be hidden.
- * @type {?Function}
- * @private
- */
-customBackgrounds.hideCustomLinkNotification = null;
-
-/*
- * The currently selected option in the richer picker.
- * @type {?Element}
- * @private
- */
-customBackgrounds.richerPicker_selectedOption = null;
-
-/**
- * Sets the visibility of the settings menu and individual options depending on
- * their respective features.
- */
-customBackgrounds.setMenuVisibility = function() {
- // Reset all hidden values.
- $(customBackgrounds.IDS.EDIT_BG).hidden = false;
- $(customBackgrounds.IDS.DEFAULT_WALLPAPERS).hidden = false;
- $(customBackgrounds.IDS.UPLOAD_IMAGE).hidden = false;
- $(customBackgrounds.IDS.RESTORE_DEFAULT).hidden = false;
- $(customBackgrounds.IDS.EDIT_BG_DIVIDER).hidden = false;
- $(customBackgrounds.IDS.CUSTOM_LINKS_RESTORE_DEFAULT).hidden =
- configData.hideShortcuts;
- $(customBackgrounds.IDS.COLORS_BUTTON).hidden = !configData.chromeColors;
-};
-
-/**
- * Display custom background image attributions on the page.
- * @param {string} attributionLine1 First line of attribution.
- * @param {string} attributionLine2 Second line of attribution.
- * @param {string} attributionActionUrl Url to learn more about the image.
- */
-customBackgrounds.setAttribution = function(
- attributionLine1, attributionLine2, attributionActionUrl) {
- const attributionBox = $(customBackgrounds.IDS.ATTRIBUTIONS);
- const attr1 = document.createElement('span');
- attr1.id = customBackgrounds.IDS.ATTR1;
- const attr2 = document.createElement('span');
- attr2.id = customBackgrounds.IDS.ATTR2;
-
- if (attributionLine1 !== '') {
- // Shouldn't be changed from textContent for security assurances.
- attr1.textContent = attributionLine1;
- attr1.classList.add(customBackgrounds.CLASSES.ATTR_COMMON);
- $(customBackgrounds.IDS.ATTRIBUTIONS).appendChild(attr1);
- }
- if (attributionLine2 !== '') {
- // Shouldn't be changed from textContent for security assurances.
- attr2.textContent = attributionLine2;
- attr2.classList.add(customBackgrounds.CLASSES.ATTR_SMALL);
- attr2.classList.add(customBackgrounds.CLASSES.ATTR_COMMON);
- attributionBox.appendChild(attr2);
- }
- if (attributionActionUrl !== '') {
- const attr = (attributionLine2 !== '' ? attr2 : attr1);
- attr.classList.add(customBackgrounds.CLASSES.ATTR_LINK);
-
- const linkIcon = document.createElement('div');
- linkIcon.id = customBackgrounds.IDS.LINK_ICON;
- // Enlarge link-icon when there is only one line of attribution
- if (attributionLine2 === '') {
- linkIcon.classList.add(customBackgrounds.CLASSES.SINGLE_ATTR);
- }
- attr.insertBefore(linkIcon, attr.firstChild);
-
- attributionBox.classList.add(customBackgrounds.CLASSES.ATTR_LINK);
- attributionBox.href = attributionActionUrl;
- attributionBox.onclick = function() {
- ntpApiHandle.logEvent(
- BACKGROUND_CUSTOMIZATION_LOG_TYPE.NTP_CUSTOMIZE_ATTRIBUTION_CLICKED);
- };
- attributionBox.style.cursor = 'pointer';
- }
-};
-
-customBackgrounds.clearAttribution = function() {
- const attributions = $(customBackgrounds.IDS.ATTRIBUTIONS);
- attributions.removeAttribute('href');
- attributions.className = '';
- attributions.style.cursor = 'none';
- while (attributions.firstChild) {
- attributions.removeChild(attributions.firstChild);
- }
-};
-
-customBackgrounds.unselectTile = function() {
- $(customBackgrounds.IDS.DONE).disabled = true;
- customBackgrounds.selectedTile = null;
- $(customBackgrounds.IDS.DONE).tabIndex = -1;
-};
-
-/**
- * Remove all collection tiles from the container when the dialog
- * is closed.
- */
-customBackgrounds.resetSelectionDialog = function() {
- $(customBackgrounds.IDS.TILES).scrollTop = 0;
- const tileContainer = $(customBackgrounds.IDS.TILES);
- while (tileContainer.firstChild) {
- tileContainer.removeChild(tileContainer.firstChild);
- }
- customBackgrounds.unselectTile();
-};
-
-/**
- * Apply selected styling to |button| and make corresponding |menu| visible.
- * @param {?Element} button The button element to apply styling to.
- * @param {?Element} menu The menu element to apply styling to.
- */
-customBackgrounds.richerPicker_selectMenuOption = function(button, menu) {
- if (!button || !menu) {
- return;
- }
- button.classList.toggle(customBackgrounds.CLASSES.SELECTED, true);
- customBackgrounds.richerPicker_selectedOption = button;
- menu.classList.toggle(customBackgrounds.CLASSES.MENU_SHOWN, true);
-};
-
-/**
- * Remove image tiles and maybe swap back to main background menu.
- * @param {boolean} showMenu Whether the main background menu should be shown.
- */
-customBackgrounds.richerPicker_resetImageMenu = function(showMenu) {
- const backgroundMenu = $(customBackgrounds.IDS.BACKGROUNDS_MENU);
- const imageMenu = $(customBackgrounds.IDS.BACKGROUNDS_IMAGE_MENU);
- const menu = $(customBackgrounds.IDS.CUSTOMIZATION_MENU);
- const menuTitle = $(customBackgrounds.IDS.MENU_TITLE);
-
- imageMenu.innerHTML = '';
- imageMenu.classList.toggle(customBackgrounds.CLASSES.MENU_SHOWN, false);
- menuTitle.textContent = menuTitle.dataset.mainTitle;
- menu.classList.toggle(customBackgrounds.CLASSES.ON_IMAGE_MENU, false);
- backgroundMenu.classList.toggle(
- customBackgrounds.CLASSES.MENU_SHOWN, showMenu);
- backgroundMenu.scrollTop = 0;
-
- // Reset done button state.
- $(customBackgrounds.IDS.MENU_DONE).disabled = true;
- customBackgrounds.richerPicker_deselectTile(customBackgrounds.selectedTile);
- customBackgrounds.selectedTile = null;
- $(customBackgrounds.IDS.MENU_DONE).tabIndex = -1;
-};
-
-/* Close the collection selection dialog and cleanup the state
- * @param {dialog} menu The dialog to be closed
- */
-customBackgrounds.closeCollectionDialog = function(menu) {
- menu.close();
- customBackgrounds.dialogCollectionsSource = customBackgrounds.SOURCES.NONE;
- customBackgrounds.resetSelectionDialog();
-};
-
-/* Close and reset the dialog, and set the background.
- * @param {string} url The url of the selected background.
- */
-customBackgrounds.setBackground = function(
- url, attributionLine1, attributionLine2, attributionActionUrl) {
- if (configData.richerPicker) {
- $(customBackgrounds.IDS.CUSTOMIZATION_MENU).close();
- customBackgrounds.richerPicker_resetImageMenu(false);
- } else {
- customBackgrounds.closeCollectionDialog($(customBackgrounds.IDS.MENU));
- }
- window.chrome.embeddedSearch.newTabPage.setBackgroundURLWithAttributions(
- url, attributionLine1, attributionLine2, attributionActionUrl);
-};
-
-/**
- * Create a tile for a Chrome Backgrounds collection.
- */
-customBackgrounds.createChromeBackgroundTile = function(data) {
- const tile = document.createElement('div');
- tile.style.backgroundImage = 'url(' + data.previewImageUrl + ')';
- tile.dataset.id = data.collectionId;
- tile.dataset.name = data.collectionName;
- fadeInImageTile(tile, data.previewImageUrl, null);
- return tile;
-};
-
-/**
- * Get the number of tiles in a row according to current window width.
- * @return {number} the number of tiles per row
- */
-customBackgrounds.getTilesWide = function() {
- // Browser window can only fit two columns. Should match "#bg-sel-menu" width.
- if ($(customBackgrounds.IDS.MENU).offsetWidth < 517) {
- return 2;
- } else if ($(customBackgrounds.IDS.MENU).offsetWidth < 356) {
- // Browser window can only fit one column. Should match @media (max-width:
- // 356) "#bg-sel-menu" width.
- return 1;
- }
-
- return 3;
-};
-
-/* Get the next tile when the arrow keys are used to navigate the grid.
- * Returns null if the tile doesn't exist.
- * @param {number} deltaX Change in the x direction.
- * @param {number} deltaY Change in the y direction.
- * @param {string} current Number of the current tile.
- */
-customBackgrounds.getNextTile = function(deltaX, deltaY, current) {
- let idPrefix = 'coll_tile_';
- if ($(customBackgrounds.IDS.MENU)
- .classList.contains(customBackgrounds.CLASSES.IMAGE_DIALOG)) {
- idPrefix = 'img_tile_';
- }
-
- if (deltaX != 0) {
- const target = parseInt(current, /*radix=*/ 10) + deltaX;
- return $(idPrefix + target);
- } else if (deltaY != 0) {
- let target = parseInt(current, /*radix=*/ 10);
- let nextTile = $(idPrefix + target);
- const startingTop = nextTile.getBoundingClientRect().top;
- const startingLeft = nextTile.getBoundingClientRect().left;
-
- // Search until a tile in a different row and the same column is found.
- while (nextTile &&
- (nextTile.getBoundingClientRect().top == startingTop ||
- nextTile.getBoundingClientRect().left != startingLeft)) {
- target += deltaY;
- nextTile = $(idPrefix + target);
- }
- return nextTile;
- }
-};
-
-/**
- * Show dialog for selecting a Chrome background.
- * @param {number} collectionsSource The enum value of the source to fetch
- * collection data from.
- */
-customBackgrounds.showCollectionSelectionDialog = function(collectionsSource) {
- const tileContainer = configData.richerPicker ?
- $(customBackgrounds.IDS.BACKGROUNDS_MENU) :
- $(customBackgrounds.IDS.TILES);
- if (configData.richerPicker && customBackgrounds.builtTiles) {
- return;
- }
- customBackgrounds.builtTiles = true;
- const menu = configData.richerPicker ?
- $(customBackgrounds.IDS.CUSTOMIZATION_MENU) :
- $(customBackgrounds.IDS.MENU);
- if (collectionsSource != customBackgrounds.SOURCES.CHROME_BACKGROUNDS) {
- console.log(
- 'showCollectionSelectionDialog() called with invalid source=' +
- collectionsSource);
- return;
- }
- customBackgrounds.dialogCollectionsSource = collectionsSource;
-
- if (!menu.open) {
- menu.showModal();
- }
-
- // Create dialog header.
- $(customBackgrounds.IDS.TITLE).textContent =
- configData.translatedStrings.selectChromeWallpaper;
- if (!configData.richerPicker) {
- menu.classList.toggle(customBackgrounds.CLASSES.COLLECTION_DIALOG);
- menu.classList.remove(customBackgrounds.CLASSES.IMAGE_DIALOG);
- }
-
- // Create dialog tiles.
- for (let i = 0; i < coll.length; ++i) {
- const tileBackground = document.createElement('div');
- tileBackground.classList.add(
- customBackgrounds.CLASSES.COLLECTION_TILE_BG);
- const tile = customBackgrounds.createChromeBackgroundTile(coll[i]);
- tile.classList.add(customBackgrounds.CLASSES.COLLECTION_TILE);
- tile.id = 'coll_tile_' + i;
- tile.dataset.tile_num = i;
- tile.tabIndex = -1;
- // Accessibility support for screen readers.
- tile.setAttribute('role', 'button');
-
- const title = document.createElement('div');
- title.classList.add(customBackgrounds.CLASSES.COLLECTION_TITLE);
- title.textContent = tile.dataset.name;
-
- const tileInteraction = function(event) {
- let tile = event.target;
- if (tile.classList.contains(customBackgrounds.CLASSES.COLLECTION_TITLE)) {
- tile = tile.parentNode;
- }
-
- // Load images for selected collection.
- const imgElement = $('ntp-images-loader');
- if (imgElement) {
- imgElement.parentNode.removeChild(imgElement);
- }
- const imgScript = document.createElement('script');
- imgScript.id = 'ntp-images-loader';
- imgScript.src = 'chrome-search://local-ntp/ntp-background-images.js?' +
- 'collection_id=' + tile.dataset.id;
- ntpApiHandle.logEvent(
- BACKGROUND_CUSTOMIZATION_LOG_TYPE
- .NTP_CUSTOMIZE_CHROME_BACKGROUND_SELECT_COLLECTION);
-
- document.body.appendChild(imgScript);
-
- imgScript.onload = function() {
- // Verify that the individual image data was successfully loaded.
- const imageDataLoaded =
- (collImg.length > 0 && collImg[0].collectionId == tile.dataset.id);
-
- // Dependent upon the success of the load, populate the image selection
- // dialog or close the current dialog.
- if (imageDataLoaded) {
- $(customBackgrounds.IDS.BACKGROUNDS_MENU)
- .classList.toggle(customBackgrounds.CLASSES.MENU_SHOWN, false);
- $(customBackgrounds.IDS.BACKGROUNDS_IMAGE_MENU)
- .classList.toggle(customBackgrounds.CLASSES.MENU_SHOWN, true);
-
- // In the RP the upload or default tile may be selected.
- if (configData.richerPicker) {
- customBackgrounds.richerPicker_deselectTile(
- customBackgrounds.selectedTile);
- } else {
- customBackgrounds.resetSelectionDialog();
- }
- customBackgrounds.showImageSelectionDialog(tile.dataset.name);
- } else {
- customBackgrounds.handleError(collImgErrors);
- }
- };
- };
-
- tile.onclick = tileInteraction;
- tile.onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER) {
- event.preventDefault();
- event.stopPropagation();
- tileInteraction(event);
- } else if (
- event.keyCode === customBackgrounds.KEYCODES.LEFT ||
- event.keyCode === customBackgrounds.KEYCODES.UP ||
- event.keyCode === customBackgrounds.KEYCODES.RIGHT ||
- event.keyCode === customBackgrounds.KEYCODES.DOWN) {
- // Handle arrow key navigation.
- event.preventDefault();
- event.stopPropagation();
-
- let target = null;
- if (event.keyCode === customBackgrounds.KEYCODES.LEFT) {
- target = customBackgrounds.getNextTile(
- document.documentElement.classList.contains('rtl') ? 1 : -1, 0,
- event.currentTarget.dataset.tile_num);
- } else if (event.keyCode === customBackgrounds.KEYCODES.UP) {
- target = customBackgrounds.getNextTile(
- 0, -1, event.currentTarget.dataset.tile_num);
- } else if (event.keyCode === customBackgrounds.KEYCODES.RIGHT) {
- target = customBackgrounds.getNextTile(
- document.documentElement.classList.contains('rtl') ? -1 : 1, 0,
- event.currentTarget.dataset.tile_num);
- } else if (event.keyCode === customBackgrounds.KEYCODES.DOWN) {
- target = customBackgrounds.getNextTile(
- 0, 1, event.currentTarget.dataset.tile_num);
- }
- if (target) {
- target.focus();
- } else {
- event.currentTarget.focus();
- }
- }
- };
-
- tile.appendChild(title);
- tileBackground.appendChild(tile);
- tileContainer.appendChild(tileBackground);
- }
-
- $(customBackgrounds.IDS.TILES).focus();
-};
-
-/**
- * Apply styling to a selected tile in the richer picker and enable the done
- * button.
- * @param {!Element} tile The tile to apply styling to.
- */
-customBackgrounds.richerPicker_selectTile = function(tile) {
- tile.parentElement.classList.toggle(customBackgrounds.CLASSES.SELECTED, true);
- $(customBackgrounds.IDS.MENU_DONE).disabled = false;
- customBackgrounds.selectedTile = tile;
- $(customBackgrounds.IDS.MENU_DONE).tabIndex = 0;
-
- // Create and append selected check.
- const selectedCircle = document.createElement('div');
- const selectedCheck = document.createElement('div');
- selectedCircle.classList.add(customBackgrounds.CLASSES.SELECTED_CIRCLE);
- selectedCheck.classList.add(customBackgrounds.CLASSES.SELECTED_CHECK);
- selectedCircle.appendChild(selectedCheck);
- tile.appendChild(selectedCircle);
-};
-
-/**
- * Remove styling from a selected tile in the richer picker and disable the
- * done button.
- * @param {?Element} tile The tile to remove styling from.
- */
-customBackgrounds.richerPicker_deselectTile = function(tile) {
- if (tile === null) {
- return;
- }
- tile.parentElement.classList.toggle(
- customBackgrounds.CLASSES.SELECTED, false);
- $(customBackgrounds.IDS.MENU_DONE).disabled = true;
- customBackgrounds.selectedTile = null;
- $(customBackgrounds.IDS.MENU_DONE).tabIndex = -1;
-
- // Remove selected check and circle.
- for (let i = 0; i < tile.children.length; ++i) {
- if (tile.children[i].classList.contains(
- customBackgrounds.CLASSES.SELECTED_CHECK) ||
- tile.children[i].classList.contains(
- customBackgrounds.CLASSES.SELECTED_CIRCLE)) {
- tile.removeChild(tile.children[i]);
- --i;
- }
- }
-};
-
-
-/**
- * Apply border and checkmark when a tile is selected
- * @param {!Element} tile The tile to apply styling to.
- */
-customBackgrounds.applySelectedState = function(tile) {
- tile.classList.add(customBackgrounds.CLASSES.COLLECTION_SELECTED);
- const selectedBorder = document.createElement('div');
- const selectedCircle = document.createElement('div');
- const selectedCheck = document.createElement('div');
- selectedBorder.classList.add(customBackgrounds.CLASSES.SELECTED_BORDER);
- selectedCircle.classList.add(customBackgrounds.CLASSES.SELECTED_CIRCLE);
- selectedCheck.classList.add(customBackgrounds.CLASSES.SELECTED_CHECK);
- selectedBorder.appendChild(selectedCircle);
- selectedBorder.appendChild(selectedCheck);
- tile.appendChild(selectedBorder);
- tile.dataset.oldLabel = tile.getAttribute('aria-label');
- tile.setAttribute(
- 'aria-label',
- tile.dataset.oldLabel + ' ' + configData.translatedStrings.selectedLabel);
-};
-
-/**
- * Remove border and checkmark when a tile is un-selected
- * @param {!Element} tile The tile to remove styling from.
- */
-customBackgrounds.removeSelectedState = function(tile) {
- tile.classList.remove(customBackgrounds.CLASSES.COLLECTION_SELECTED);
- tile.removeChild(tile.firstChild);
- tile.setAttribute('aria-label', tile.dataset.oldLabel);
-};
-
-/**
- * Show dialog for selecting an image. Image data should previous have been
- * loaded into collImg via
- * chrome-search://local-ntp/ntp-background-images.js?collection_id=<collection_id>
- * @param {string} dialogTitle The title to be displayed at the top of the
- * dialog.
- */
-customBackgrounds.showImageSelectionDialog = function(dialogTitle) {
- const firstNTile = customBackgrounds.ROWS_TO_PRELOAD
- * customBackgrounds.getTilesWide();
- const tileContainer = configData.richerPicker ?
- $(customBackgrounds.IDS.BACKGROUNDS_IMAGE_MENU) :
- $(customBackgrounds.IDS.TILES);
- const menu = configData.richerPicker ?
- $(customBackgrounds.IDS.CUSTOMIZATION_MENU) :
- $(customBackgrounds.IDS.MENU);
-
- if (configData.richerPicker) {
- $(customBackgrounds.IDS.MENU_TITLE).textContent = dialogTitle;
- menu.classList.toggle(customBackgrounds.CLASSES.ON_IMAGE_MENU, true);
- } else {
- $(customBackgrounds.IDS.TITLE).textContent = dialogTitle;
- menu.classList.remove(customBackgrounds.CLASSES.COLLECTION_DIALOG);
- menu.classList.add(customBackgrounds.CLASSES.IMAGE_DIALOG);
- }
-
- const preLoadTiles = [];
- const postLoadTiles = [];
-
- for (let i = 0; i < collImg.length; ++i) {
- const tileBackground = document.createElement('div');
- tileBackground.classList.add(
- customBackgrounds.CLASSES.COLLECTION_TILE_BG);
- const tile = document.createElement('div');
- tile.classList.add(customBackgrounds.CLASSES.COLLECTION_TILE);
- // Accessibility support for screen readers.
- tile.setAttribute('role', 'button');
-
- // TODO(crbug.com/854028): Remove this hardcoded check when wallpaper
- // previews are supported.
- if (collImg[i].collectionId === 'solidcolors') {
- tile.dataset.attributionLine1 = '';
- tile.dataset.attributionLine2 = '';
- tile.dataset.attributionActionUrl = '';
- } else {
- tile.dataset.attributionLine1 =
- (collImg[i].attributions[0] !== undefined ?
- collImg[i].attributions[0] :
- '');
- tile.dataset.attributionLine2 =
- (collImg[i].attributions[1] !== undefined ?
- collImg[i].attributions[1] :
- '');
- tile.dataset.attributionActionUrl = collImg[i].attributionActionUrl;
- }
- tile.setAttribute('aria-label', collImg[i].attributions[0]);
- tile.dataset.url = collImg[i].imageUrl;
-
- tile.id = 'img_tile_' + i;
- tile.dataset.tile_num = i;
- tile.tabIndex = -1;
-
- // Load the first |ROWS_TO_PRELOAD| rows of tiles.
- if (i < firstNTile) {
- preLoadTiles.push(tile);
- } else {
- postLoadTiles.push(tile);
- }
-
- const tileInteraction = function(tile) {
- if (customBackgrounds.selectedTile) {
- if (configData.richerPicker) {
- const id = customBackgrounds.selectedTile.id;
- customBackgrounds.richerPicker_deselectTile(
- customBackgrounds.selectedTile);
- if (id === tile.id) {
- return;
- }
- } else {
- customBackgrounds.removeSelectedState(customBackgrounds.selectedTile);
- if (customBackgrounds.selectedTile.id === tile.id) {
- customBackgrounds.unselectTile();
- return;
- }
- }
- }
-
- if (configData.richerPicker) {
- customBackgrounds.richerPicker_selectTile(tile);
- } else {
- customBackgrounds.applySelectedState(tile);
- customBackgrounds.selectedTile = tile;
- }
-
- $(customBackgrounds.IDS.DONE).tabIndex = 0;
-
- // Turn toggle off when an image is selected.
- $(customBackgrounds.IDS.DONE).disabled = false;
- ntpApiHandle.logEvent(BACKGROUND_CUSTOMIZATION_LOG_TYPE
- .NTP_CUSTOMIZE_CHROME_BACKGROUND_SELECT_IMAGE);
- };
-
- tile.onclick = function(event) {
- const clickCount = event.detail;
- // Control + option + space will fire the onclick event with 0 clickCount.
- if (clickCount <= 1) {
- tileInteraction(event.currentTarget);
- } else if (
- clickCount === 2 &&
- customBackgrounds.selectedTile === event.currentTarget) {
- customBackgrounds.setBackground(
- event.currentTarget.dataset.url,
- event.currentTarget.dataset.attributionLine1,
- event.currentTarget.dataset.attributionLine2,
- event.currentTarget.dataset.attributionActionUrl);
- }
- };
- tile.onkeydown = function(event) {
-
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER) {
- event.preventDefault();
- event.stopPropagation();
- tileInteraction(event.currentTarget);
- } else if (
- event.keyCode === customBackgrounds.KEYCODES.LEFT ||
- event.keyCode === customBackgrounds.KEYCODES.UP ||
- event.keyCode === customBackgrounds.KEYCODES.RIGHT ||
- event.keyCode === customBackgrounds.KEYCODES.DOWN) {
- // Handle arrow key navigation.
- event.preventDefault();
- event.stopPropagation();
-
- let target = null;
- if (event.keyCode == customBackgrounds.KEYCODES.LEFT) {
- target = customBackgrounds.getNextTile(
- document.documentElement.classList.contains('rtl') ? 1 : -1, 0,
- event.currentTarget.dataset.tile_num);
- } else if (event.keyCode == customBackgrounds.KEYCODES.UP) {
- target = customBackgrounds.getNextTile(
- 0, -1, event.currentTarget.dataset.tile_num);
- } else if (event.keyCode == customBackgrounds.KEYCODES.RIGHT) {
- target = customBackgrounds.getNextTile(
- document.documentElement.classList.contains('rtl') ? -1 : 1, 0,
- event.currentTarget.dataset.tile_num);
- } else if (event.keyCode == customBackgrounds.KEYCODES.DOWN) {
- target = customBackgrounds.getNextTile(
- 0, 1, event.currentTarget.dataset.tile_num);
- }
- if (target) {
- target.focus();
- } else {
- event.currentTarget.focus();
- }
- }
- };
-
- tileBackground.appendChild(tile);
- tileContainer.appendChild(tileBackground);
- }
- let tileGetsLoaded = 0;
- for (const tile of preLoadTiles) {
- loadTile(tile, collImg, () => {
- // After the preloaded tiles finish loading, the rest of the tiles start
- // loading.
- if (++tileGetsLoaded === preLoadTiles.length) {
- postLoadTiles.forEach((tile) => loadTile(tile, collImg, null));
- }
- });
- }
-
- $(customBackgrounds.IDS.TILES).focus();
-};
-
-/**
- * Add background image src to the tile and add animation for the tile once it
- * successfully loaded.
- * @param {!Object} tile the tile that needs to be loaded.
- * @param {!Object} imageData the source imageData.
- * @param {?Function} countLoad If not null, called after the tile finishes
- * loading.
- */
-const loadTile = function(tile, imageData, countLoad) {
- if (imageData[tile.dataset.tile_num].collectionId === 'solidcolors') {
- tile.style.backgroundImage = [customBackgrounds.CUSTOM_BACKGROUND_OVERLAY,
- 'url(' + imageData[tile.dataset.tile_num].thumbnailImageUrl + ')'].join(
- ',').trim();
- } else {
- tile.style.backgroundImage =
- 'url(' + imageData[tile.dataset.tile_num].thumbnailImageUrl + ')';
- }
- fadeInImageTile(
- tile, imageData[tile.dataset.tile_num].thumbnailImageUrl, countLoad);
-};
-
-/**
- * Fade in effect for both collection and image tile. Once the image
- * successfully loads, we can assume the background image with the same source
- * has also loaded. Then, we set opacity for the tile to start the animation.
- * @param {!Object} tile The tile to add the fade in animation to.
- * @param {string} imageUrl the image url for the tile
- * @param {?Function} countLoad If not null, called after the tile finishes
- * loading.
- */
-const fadeInImageTile = function(tile, imageUrl, countLoad) {
- const image = new Image();
- image.onload = () => {
- tile.style.opacity = '1';
- if (countLoad) {
- countLoad();
- }
- };
- image.src = imageUrl;
-};
-
-/**
- * Load the NTPBackgroundCollections script. It'll create a global
- * variable name "coll" which is a dict of background collections data.
- * @private
- */
-customBackgrounds.loadChromeBackgrounds = function() {
- const collElement = $('ntp-collection-loader');
- if (collElement) {
- collElement.parentNode.removeChild(collElement);
- }
- const collScript = document.createElement('script');
- collScript.id = 'ntp-collection-loader';
- collScript.src = 'chrome-search://local-ntp/ntp-background-collections.js?' +
- 'collection_type=background';
- collScript.onload = function() {
- if (configData.richerPicker) {
- customBackgrounds.showCollectionSelectionDialog(
- customBackgrounds.SOURCES.CHROME_BACKGROUNDS);
- }
- };
- document.body.appendChild(collScript);
-};
-
-/* Close dialog when an image is selected via the file picker. */
-customBackgrounds.closeCustomizationDialog = function() {
- if (configData.richerPicker) {
- $(customBackgrounds.IDS.CUSTOMIZATION_MENU).close();
- } else {
- $(customBackgrounds.IDS.EDIT_BG_DIALOG).close();
- }
-};
-
-/*
- * Get the next visible option. There are times when various combinations of
- * options are hidden.
- * @param {number} current_index Index of the option the key press occurred on.
- * @param {number} deltaY Direction to search in, -1 for up, 1 for down.
- */
-customBackgrounds.getNextOption = function(current_index, deltaY) {
- // Create array corresponding to the menu. Important that this is in the same
- // order as the MENU_ENTRIES enum, so we can index into it.
- const entries = [];
- entries.push($(customBackgrounds.IDS.DEFAULT_WALLPAPERS));
- entries.push($(customBackgrounds.IDS.UPLOAD_IMAGE));
- entries.push($(customBackgrounds.IDS.CUSTOM_LINKS_RESTORE_DEFAULT));
- entries.push($(customBackgrounds.IDS.RESTORE_DEFAULT));
-
- let idx = current_index;
- do {
- idx = idx + deltaY;
- if (idx === -1) {
- idx = 3;
- }
- if (idx === 4) {
- idx = 0;
- }
- } while (idx !== current_index && (entries[idx].hidden ||
- entries[idx].classList.contains(
- customBackgrounds.CLASSES.OPTION_DISABLED)));
- return entries[idx];
-};
-
-/* Hide custom background options based on the network state
- * @param {bool} online The current state of the network
- */
-customBackgrounds.networkStateChanged = function(online) {
- $(customBackgrounds.IDS.DEFAULT_WALLPAPERS).hidden = !online;
-};
-
-/**
- * Set customization menu to default options (custom backgrounds).
- */
-customBackgrounds.richerPicker_setCustomizationMenuToDefaultState = function() {
- customBackgrounds.richerPicker_resetCustomizationMenu();
- $(customBackgrounds.IDS.BACKGROUNDS_MENU)
- .classList.toggle(customBackgrounds.CLASSES.MENU_SHOWN, true);
- customBackgrounds.richerPicker_selectedOption =
- $(customBackgrounds.IDS.BACKGROUNDS_BUTTON);
-};
-
-/**
- * Resets customization menu options.
- */
-customBackgrounds.richerPicker_resetCustomizationMenu = function() {
- customBackgrounds.richerPicker_resetImageMenu(false);
- $(customBackgrounds.IDS.BACKGROUNDS_MENU)
- .classList.toggle(customBackgrounds.CLASSES.MENU_SHOWN, false);
- $(customBackgrounds.IDS.SHORTCUTS_MENU)
- .classList.toggle(customBackgrounds.CLASSES.MENU_SHOWN, false);
- $(customBackgrounds.IDS.COLORS_MENU)
- .classList.toggle(customBackgrounds.CLASSES.MENU_SHOWN, false);
- if (customBackgrounds.richerPicker_selectedOption) {
- customBackgrounds.richerPicker_selectedOption.classList.toggle(
- customBackgrounds.CLASSES.SELECTED, false);
- customBackgrounds.richerPicker_selectedOption = null;
- }
-};
-
-/**
- * Initialize the settings menu, custom backgrounds dialogs, and custom
- * links menu items. Set the text and event handlers for the various
- * elements.
- * @param {!Function} showErrorNotification Called when the error notification
- * should be displayed.
- * @param {!Function} hideCustomLinkNotification Called when the custom link
- * notification should be hidden.
- */
-customBackgrounds.init = function(
- showErrorNotification, hideCustomLinkNotification) {
- ntpApiHandle = window.chrome.embeddedSearch.newTabPage;
- const editDialog = $(customBackgrounds.IDS.EDIT_BG_DIALOG);
- const menu = $(customBackgrounds.IDS.MENU);
-
- $(customBackgrounds.IDS.OPTIONS_TITLE).textContent =
- configData.translatedStrings.customizeBackground;
-
- // Store the main menu title so it can be restored if needed.
- $(customBackgrounds.IDS.MENU_TITLE).dataset.mainTitle =
- $(customBackgrounds.IDS.MENU_TITLE).textContent;
-
- $(customBackgrounds.IDS.EDIT_BG_ICON)
- .setAttribute(
- 'aria-label', configData.translatedStrings.customizeThisPage);
-
- $(customBackgrounds.IDS.EDIT_BG_ICON)
- .setAttribute('title', configData.translatedStrings.customizeBackground);
-
- // Edit gear icon interaction events.
- const editBackgroundInteraction = function() {
- if (configData.richerPicker) {
- customBackgrounds.richerPicker_setCustomizationMenuToDefaultState();
- customBackgrounds.loadChromeBackgrounds();
- $(customBackgrounds.IDS.CUSTOMIZATION_MENU).showModal();
- } else {
- editDialog.showModal();
- }
- };
- $(customBackgrounds.IDS.EDIT_BG).onclick = function(event) {
- editDialog.classList.add(customBackgrounds.CLASSES.MOUSE_NAV);
- editBackgroundInteraction();
- };
-
- $(customBackgrounds.IDS.MENU_CANCEL).onclick = function(event) {
- $(customBackgrounds.IDS.CUSTOMIZATION_MENU).close();
- customBackgrounds.richerPicker_resetCustomizationMenu();
- };
-
-
- // Find the first menu option that is not hidden or disabled.
- const findFirstMenuOption = () => {
- const editMenu = $(customBackgrounds.IDS.EDIT_BG_MENU);
- for (let i = 1; i < editMenu.children.length; i++) {
- const option = editMenu.children[i];
- if (option.classList.contains(customBackgrounds.CLASSES.OPTION)
- && !option.hidden && !option.classList.contains(
- customBackgrounds.CLASSES.OPTION_DISABLED)) {
- option.focus();
- return;
- }
- }
- };
-
- $(customBackgrounds.IDS.EDIT_BG).onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER ||
- event.keyCode === customBackgrounds.KEYCODES.SPACE) {
- // no default behavior for ENTER
- event.preventDefault();
- editDialog.classList.remove(customBackgrounds.CLASSES.MOUSE_NAV);
- editBackgroundInteraction();
- findFirstMenuOption();
- }
- };
-
- // Interactions to close the customization option dialog.
- const editDialogInteraction = function() {
- editDialog.close();
- };
- editDialog.onclick = function(event) {
- editDialog.classList.add(customBackgrounds.CLASSES.MOUSE_NAV);
- if (event.target === editDialog) {
- editDialogInteraction();
- }
- };
- editDialog.onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ESC) {
- editDialogInteraction();
- } else if (
- editDialog.classList.contains(customBackgrounds.CLASSES.MOUSE_NAV) &&
- (event.keyCode === customBackgrounds.KEYCODES.TAB ||
- event.keyCode === customBackgrounds.KEYCODES.UP ||
- event.keyCode === customBackgrounds.KEYCODES.DOWN)) {
- // When using tab in mouse navigation mode, select the first option
- // available.
- event.preventDefault();
- findFirstMenuOption();
- editDialog.classList.remove(customBackgrounds.CLASSES.MOUSE_NAV);
- } else if (event.keyCode === customBackgrounds.KEYCODES.TAB) {
- // If keyboard navigation is attempted, remove mouse-only mode.
- editDialog.classList.remove(customBackgrounds.CLASSES.MOUSE_NAV);
- } else if (
- event.keyCode === customBackgrounds.KEYCODES.LEFT ||
- event.keyCode === customBackgrounds.KEYCODES.UP ||
- event.keyCode === customBackgrounds.KEYCODES.RIGHT ||
- event.keyCode === customBackgrounds.KEYCODES.DOWN) {
- event.preventDefault();
- editDialog.classList.remove(customBackgrounds.CLASSES.MOUSE_NAV);
- }
- };
-
- customBackgrounds.initCustomLinksItems(hideCustomLinkNotification);
- customBackgrounds.initCustomBackgrounds(showErrorNotification);
-};
-
-/**
- * Initialize custom link items in the settings menu dialog. Set the text
- * and event handlers for the various elements.
- * @param {!Function} hideCustomLinkNotification Called when the custom link
- * notification should be hidden.
- */
-customBackgrounds.initCustomLinksItems = function(hideCustomLinkNotification) {
- customBackgrounds.hideCustomLinkNotification = hideCustomLinkNotification;
-
- const editDialog = $(customBackgrounds.IDS.EDIT_BG_DIALOG);
- const menu = $(customBackgrounds.IDS.MENU);
-
- $(customBackgrounds.IDS.CUSTOM_LINKS_RESTORE_DEFAULT_TEXT).textContent =
- configData.translatedStrings.restoreDefaultLinks;
-
- // Interactions with the "Restore default shortcuts" option.
- const customLinksRestoreDefaultInteraction = function() {
- editDialog.close();
- customBackgrounds.hideCustomLinkNotification();
- window.chrome.embeddedSearch.newTabPage.resetCustomLinks();
- ntpApiHandle.logEvent(BACKGROUND_CUSTOMIZATION_LOG_TYPE
- .NTP_CUSTOMIZE_RESTORE_SHORTCUTS_CLICKED);
- };
- $(customBackgrounds.IDS.CUSTOM_LINKS_RESTORE_DEFAULT).onclick = () => {
- if (!$(customBackgrounds.IDS.CUSTOM_LINKS_RESTORE_DEFAULT).classList.
- contains(customBackgrounds.CLASSES.OPTION_DISABLED)) {
- customLinksRestoreDefaultInteraction();
- }
- };
- $(customBackgrounds.IDS.CUSTOM_LINKS_RESTORE_DEFAULT).onkeydown = function(
- event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER) {
- customLinksRestoreDefaultInteraction();
- } else if (event.keyCode === customBackgrounds.KEYCODES.UP) {
- // Handle arrow key navigation.
- event.preventDefault();
- customBackgrounds
- .getNextOption(
- customBackgrounds.MENU_ENTRIES.CUSTOM_LINKS_RESTORE_DEFAULT, -1)
- .focus();
- } else if (event.keyCode === customBackgrounds.KEYCODES.DOWN) {
- event.preventDefault();
- customBackgrounds
- .getNextOption(
- customBackgrounds.MENU_ENTRIES.CUSTOM_LINKS_RESTORE_DEFAULT, 1)
- .focus();
- }
- };
-};
-
-/**
- * Initialize the settings menu and custom backgrounds dialogs. Set the
- * text and event handlers for the various elements.
- * @param {!Function} showErrorNotification Called when the error notification
- * should be displayed.
- */
-customBackgrounds.initCustomBackgrounds = function(showErrorNotification) {
- customBackgrounds.showErrorNotification = showErrorNotification;
-
- const editDialog = $(customBackgrounds.IDS.EDIT_BG_DIALOG);
- const menu = $(customBackgrounds.IDS.MENU);
-
- $(customBackgrounds.IDS.DEFAULT_WALLPAPERS_TEXT).textContent =
- configData.translatedStrings.defaultWallpapers;
- $(customBackgrounds.IDS.UPLOAD_IMAGE_TEXT).textContent =
- configData.translatedStrings.uploadImage;
- $(customBackgrounds.IDS.RESTORE_DEFAULT_TEXT).textContent =
- configData.translatedStrings.restoreDefaultBackground;
- $(customBackgrounds.IDS.DONE).textContent =
- configData.translatedStrings.selectionDone;
- $(customBackgrounds.IDS.CANCEL).textContent =
- configData.translatedStrings.selectionCancel;
-
- window.addEventListener('online', function(event) {
- customBackgrounds.networkStateChanged(true);
- });
-
- window.addEventListener('offline', function(event) {
- customBackgrounds.networkStateChanged(false);
- });
-
- if (!window.navigator.onLine) {
- customBackgrounds.networkStateChanged(false);
- }
-
- $(customBackgrounds.IDS.BACK_CIRCLE)
- .setAttribute('aria-label', configData.translatedStrings.backLabel);
- $(customBackgrounds.IDS.CANCEL)
- .setAttribute('aria-label', configData.translatedStrings.selectionCancel);
- $(customBackgrounds.IDS.DONE)
- .setAttribute('aria-label', configData.translatedStrings.selectionDone);
-
- $(customBackgrounds.IDS.DONE).disabled = true;
-
- // Interactions with the "Upload an image" option.
- const uploadImageInteraction = function() {
- window.chrome.embeddedSearch.newTabPage.selectLocalBackgroundImage();
- ntpApiHandle.logEvent(
- BACKGROUND_CUSTOMIZATION_LOG_TYPE.NTP_CUSTOMIZE_LOCAL_IMAGE_CLICKED);
- };
-
- $(customBackgrounds.IDS.UPLOAD_IMAGE).onclick = (event) => {
- if (!$(customBackgrounds.IDS.UPLOAD_IMAGE).classList.contains(
- customBackgrounds.CLASSES.OPTION_DISABLED)) {
- uploadImageInteraction();
- }
- };
- $(customBackgrounds.IDS.UPLOAD_IMAGE).onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER) {
- uploadImageInteraction();
- }
-
- // Handle arrow key navigation.
- if (event.keyCode === customBackgrounds.KEYCODES.UP) {
- event.preventDefault();
- customBackgrounds
- .getNextOption(customBackgrounds.MENU_ENTRIES.UPLOAD_IMAGE, -1)
- .focus();
- }
- if (event.keyCode === customBackgrounds.KEYCODES.DOWN) {
- event.preventDefault();
- customBackgrounds
- .getNextOption(customBackgrounds.MENU_ENTRIES.UPLOAD_IMAGE, 1)
- .focus();
- }
- };
-
- // Interactions with the "Restore default background" option.
- const restoreDefaultInteraction = function() {
- editDialog.close();
- customBackgrounds.clearAttribution();
- window.chrome.embeddedSearch.newTabPage.setBackgroundURL('');
- ntpApiHandle.logEvent(BACKGROUND_CUSTOMIZATION_LOG_TYPE
- .NTP_CUSTOMIZE_RESTORE_BACKGROUND_CLICKED);
- };
- $(customBackgrounds.IDS.RESTORE_DEFAULT).onclick = (event) => {
- if (!$(customBackgrounds.IDS.RESTORE_DEFAULT).classList.contains(
- customBackgrounds.CLASSES.OPTION_DISABLED)) {
- restoreDefaultInteraction();
- }
- };
- $(customBackgrounds.IDS.RESTORE_DEFAULT).onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER) {
- restoreDefaultInteraction();
- }
-
- // Handle arrow key navigation.
- if (event.keyCode === customBackgrounds.KEYCODES.UP) {
- event.preventDefault();
- customBackgrounds
- .getNextOption(customBackgrounds.MENU_ENTRIES.RESTORE_DEFAULT, -1)
- .focus();
- }
- if (event.keyCode === customBackgrounds.KEYCODES.DOWN) {
- event.preventDefault();
- customBackgrounds
- .getNextOption(customBackgrounds.MENU_ENTRIES.RESTORE_DEFAULT, 1)
- .focus();
- }
- };
-
- // Interactions with the "Chrome backgrounds" option.
- const defaultWallpapersInteraction = function(event) {
- customBackgrounds.loadChromeBackgrounds();
- $('ntp-collection-loader').onload = function() {
- editDialog.close();
- if (typeof coll != 'undefined' && coll.length > 0) {
- customBackgrounds.showCollectionSelectionDialog(
- customBackgrounds.SOURCES.CHROME_BACKGROUNDS);
- } else {
- customBackgrounds.handleError(collErrors);
- }
- };
- ntpApiHandle.logEvent(BACKGROUND_CUSTOMIZATION_LOG_TYPE
- .NTP_CUSTOMIZE_CHROME_BACKGROUNDS_CLICKED);
- };
- $(customBackgrounds.IDS.DEFAULT_WALLPAPERS).onclick = function(event) {
- $(customBackgrounds.IDS.MENU)
- .classList.add(customBackgrounds.CLASSES.MOUSE_NAV);
- defaultWallpapersInteraction(event);
- };
- $(customBackgrounds.IDS.DEFAULT_WALLPAPERS).onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER) {
- $(customBackgrounds.IDS.MENU)
- .classList.remove(customBackgrounds.CLASSES.MOUSE_NAV);
- defaultWallpapersInteraction(event);
- }
-
- // Handle arrow key navigation.
- if (event.keyCode === customBackgrounds.KEYCODES.UP) {
- event.preventDefault();
- customBackgrounds
- .getNextOption(customBackgrounds.MENU_ENTRIES.CHROME_BACKGROUNDS, -1)
- .focus();
- }
- if (event.keyCode === customBackgrounds.KEYCODES.DOWN) {
- event.preventDefault();
- customBackgrounds
- .getNextOption(customBackgrounds.MENU_ENTRIES.CHROME_BACKGROUNDS, 1)
- .focus();
- }
- };
-
- // Escape and Backspace handling for the background picker dialog.
- menu.onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.SPACE) {
- $(customBackgrounds.IDS.TILES).scrollTop +=
- $(customBackgrounds.IDS.TILES).offsetHeight;
- event.stopPropagation();
- event.preventDefault();
- }
- if (event.keyCode === customBackgrounds.KEYCODES.ESC ||
- event.keyCode === customBackgrounds.KEYCODES.BACKSPACE) {
- event.preventDefault();
- event.stopPropagation();
- if (menu.classList.contains(
- customBackgrounds.CLASSES.COLLECTION_DIALOG)) {
- menu.close();
- customBackgrounds.resetSelectionDialog();
- } else {
- customBackgrounds.resetSelectionDialog();
- customBackgrounds.showCollectionSelectionDialog(
- customBackgrounds.dialogCollectionsSource);
- }
- }
-
- // If keyboard navigation is attempted, remove mouse-only mode.
- if (event.keyCode === customBackgrounds.KEYCODES.TAB ||
- event.keyCode === customBackgrounds.KEYCODES.LEFT ||
- event.keyCode === customBackgrounds.KEYCODES.UP ||
- event.keyCode === customBackgrounds.KEYCODES.RIGHT ||
- event.keyCode === customBackgrounds.KEYCODES.DOWN) {
- menu.classList.remove(customBackgrounds.CLASSES.MOUSE_NAV);
- }
- };
-
- // Interactions with the back arrow on the image selection dialog.
- const backInteraction = function(event) {
- if (configData.richerPicker) {
- customBackgrounds.richerPicker_resetImageMenu(true);
- }
- customBackgrounds.resetSelectionDialog();
- customBackgrounds.showCollectionSelectionDialog(
- customBackgrounds.dialogCollectionsSource);
- };
- $(customBackgrounds.IDS.BACK_CIRCLE).onclick = backInteraction;
- $(customBackgrounds.IDS.MENU_BACK_CIRCLE).onclick = backInteraction;
- $(customBackgrounds.IDS.BACK_CIRCLE).onkeyup = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER ||
- event.keyCode === customBackgrounds.KEYCODES.SPACE) {
- backInteraction(event);
- }
- };
- // Pressing Spacebar on the back arrow shouldn't scroll the dialog.
- $(customBackgrounds.IDS.BACK_CIRCLE).onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.SPACE) {
- event.stopPropagation();
- }
- };
-
- // Interactions with the cancel button on the background picker dialog.
- $(customBackgrounds.IDS.CANCEL).onclick = function(event) {
- customBackgrounds.closeCollectionDialog(menu);
- ntpApiHandle.logEvent(BACKGROUND_CUSTOMIZATION_LOG_TYPE
- .NTP_CUSTOMIZE_CHROME_BACKGROUND_CANCEL);
- };
- $(customBackgrounds.IDS.CANCEL).onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER ||
- event.keyCode === customBackgrounds.KEYCODES.SPACE) {
- customBackgrounds.closeCollectionDialog(menu);
- ntpApiHandle.logEvent(BACKGROUND_CUSTOMIZATION_LOG_TYPE
- .NTP_CUSTOMIZE_CHROME_BACKGROUND_CANCEL);
- }
- };
-
- // Interactions with the done button on the background picker dialog.
- const doneInteraction = function(event) {
- const done = configData.richerPicker ? $(customBackgrounds.IDS.MENU_DONE) :
- $(customBackgrounds.IDS.DONE);
- if (done.disabled) {
- return;
- }
- customBackgrounds.setBackground(
- customBackgrounds.selectedTile.dataset.url,
- customBackgrounds.selectedTile.dataset.attributionLine1,
- customBackgrounds.selectedTile.dataset.attributionLine2,
- customBackgrounds.selectedTile.dataset.attributionActionUrl);
- };
- $(customBackgrounds.IDS.DONE).onclick = doneInteraction;
- $(customBackgrounds.IDS.MENU_DONE).onclick = doneInteraction;
- $(customBackgrounds.IDS.DONE).onkeyup = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER) {
- doneInteraction(event);
- }
- };
-
- // On any arrow key event in the tiles area, focus the first tile.
- $(customBackgrounds.IDS.TILES).onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.LEFT ||
- event.keyCode === customBackgrounds.KEYCODES.UP ||
- event.keyCode === customBackgrounds.KEYCODES.RIGHT ||
- event.keyCode === customBackgrounds.KEYCODES.DOWN) {
- event.preventDefault();
- if ($(customBackgrounds.IDS.MENU)
- .classList.contains(
- customBackgrounds.CLASSES.COLLECTION_DIALOG)) {
- $('coll_tile_0').focus();
- } else {
- $('img_tile_0').focus();
- }
- }
- };
-
- $(customBackgrounds.IDS.BACKGROUNDS_UPLOAD).onclick = uploadImageInteraction;
- $(customBackgrounds.IDS.BACKGROUNDS_UPLOAD).onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER ||
- event.keyCode === customBackgrounds.KEYCODES.SPACE) {
- uploadImageInteraction();
- }
- };
-
- $(customBackgrounds.IDS.BACKGROUNDS_DEFAULT).onclick = function() {
- const tile = $(customBackgrounds.IDS.BACKGROUNDS_DEFAULT_ICON);
- tile.dataset.url = '';
- tile.dataset.attributionLine1 = '';
- tile.dataset.attributionLine2 = '';
- tile.dataset.attributionActionUrl = '';
- customBackgrounds.richerPicker_selectTile(tile);
- };
-
- const richerPickerOpenBackgrounds = function() {
- customBackgrounds.richerPicker_resetCustomizationMenu();
- customBackgrounds.richerPicker_selectMenuOption(
- $(customBackgrounds.IDS.BACKGROUNDS_BUTTON),
- $(customBackgrounds.IDS.BACKGROUNDS_MENU));
- };
-
- $(customBackgrounds.IDS.BACKGROUNDS_BUTTON).onclick =
- richerPickerOpenBackgrounds;
- $(customBackgrounds.IDS.BACKGROUNDS_BUTTON).onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER ||
- event.keyCode === customBackgrounds.KEYCODES.SPACE) {
- richerPickerOpenBackgrounds();
- }
- };
-
- const richerPickerOpenShortcuts = function() {
- customBackgrounds.richerPicker_resetCustomizationMenu();
- customBackgrounds.richerPicker_selectMenuOption(
- $(customBackgrounds.IDS.SHORTCUTS_BUTTON),
- $(customBackgrounds.IDS.SHORTCUTS_MENU));
- };
-
- $(customBackgrounds.IDS.SHORTCUTS_BUTTON).onclick = richerPickerOpenShortcuts;
- $(customBackgrounds.IDS.SHORTCUTS_BUTTON).onkeydown = function(event) {
- if (event.keyCode === customBackgrounds.KEYCODES.ENTER ||
- event.keyCode === customBackgrounds.KEYCODES.SPACE) {
- richerPickerOpenShortcuts();
- }
- };
-
- $(customBackgrounds.IDS.COLORS_BUTTON).onclick = function() {
- customBackgrounds.richerPicker_resetCustomizationMenu();
- customBackgrounds.richerPicker_selectMenuOption(
- $(customBackgrounds.IDS.COLORS_BUTTON),
- $(customBackgrounds.IDS.COLORS_MENU));
- };
-};
-
-customBackgrounds.handleError = function(errors) {
- const unavailableString = configData.translatedStrings.backgroundsUnavailable;
-
- if (errors != 'undefined') {
- // Network errors.
- if (errors.net_error) {
- if (errors.net_error_no != 0) {
- const onClick = () => {
- window.open(
- 'https://chrome://network-error/' + errors.net_error_no,
- '_blank');
- };
- customBackgrounds.showErrorNotification(
- configData.translatedStrings.connectionError,
- configData.translatedStrings.moreInfo, onClick);
- } else {
- customBackgrounds.showErrorNotification(
- configData.translatedStrings.connectionErrorNoPeriod);
- }
- } else if (errors.service_error) { // Service errors.
- customBackgrounds.showErrorNotification(unavailableString);
- }
- return;
- }
-
- // Generic error when we can't tell what went wrong.
- customBackgrounds.showErrorNotification(unavailableString);
-};
diff --git a/chromium/chrome/browser/resources/local_ntp/custom_links_edit.css b/chromium/chrome/browser/resources/local_ntp/custom_links_edit.css
index 88fabe7081e..a8864a26d16 100644
--- a/chromium/chrome/browser/resources/local_ntp/custom_links_edit.css
+++ b/chromium/chrome/browser/resources/local_ntp/custom_links_edit.css
@@ -15,8 +15,8 @@ body {
border: none;
border-radius: 8px;
bottom: 0;
- box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), 0.3),
- 0 4px 8px 3px rgba(var(--GG800-rgb), 0.15);
+ box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), .3),
+ 0 4px 8px 3px rgba(var(--GG800-rgb), .15);
margin: auto;
min-width: 320px;
padding: 16px;
@@ -24,10 +24,11 @@ body {
z-index: 10000;
}
-html[darkmode=true] #edit-link-dialog {
- background-color: rgb(41, 42, 45);
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.3),
- 0 4px 8px 3px rgba(0, 0, 0, 0.15);
+@media (prefers-color-scheme: dark) {
+ #edit-link-dialog {
+ background-color: rgb(var(--dark-mode-dialog-rgb));
+ box-shadow: var(--dark-mode-shadow);
+ }
}
#edit-link-dialog::backdrop {
@@ -45,8 +46,10 @@ html[darkmode=true] #edit-link-dialog {
margin-bottom: 16px;
}
-html[darkmode=true] #dialog-title {
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ #dialog-title {
+ color: rgb(var(--GG200-rgb));
+ }
}
.field-container {
@@ -60,8 +63,10 @@ html[darkmode=true] #dialog-title {
margin-bottom: 4px;
}
-html[darkmode=true] .field-title {
- color: rgb(var(--GG400-rgb));
+@media (prefers-color-scheme: dark) {
+ .field-title {
+ color: rgb(var(--GG400-rgb));
+ }
}
.input-container {
@@ -87,18 +92,22 @@ html[dir=rtl] input {
text-align: right; /* csschecker-disable-line left-right */
}
-html[darkmode=true] input {
- background-color: rgba(0, 0, 0, 0.3);
- caret-color: rgb(var(--GB300-rgb));
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ input {
+ background-color: rgba(0, 0, 0, .3);
+ caret-color: rgb(var(--GB300-rgb));
+ color: rgb(var(--GG200-rgb));
+ }
}
input::placeholder {
- color: rgba(var(--GG900-rgb), 0.38);
+ color: rgba(var(--GG900-rgb), .38);
}
-html[darkmode=true] input::placeholder {
- color: rgb(var(--GG500-rgb));
+@media (prefers-color-scheme: dark) {
+ input::placeholder {
+ color: rgb(var(--GG500-rgb));
+ }
}
.underline {
@@ -114,8 +123,10 @@ html[darkmode=true] input::placeholder {
width: 0;
}
-html[darkmode=true] .underline {
- border-color: rgb(var(--GB300-rgb));
+@media (prefers-color-scheme: dark) {
+ .underline {
+ border-color: rgb(var(--GB300-rgb));
+ }
}
input:focus + .underline {
@@ -128,8 +139,10 @@ input:focus + .underline {
color: rgb(var(--GB600-rgb));
}
-html[darkmode=true] .field-title.focused {
- color: rgb(var(--GB300-rgb));
+@media (prefers-color-scheme: dark) {
+ .field-title.focused {
+ color: rgb(var(--GB300-rgb));
+ }
}
.error-msg {
@@ -140,16 +153,20 @@ html[darkmode=true] .field-title.focused {
margin-top: 6px;
}
-html[darkmode=true] .error-msg {
- color: rgb(var(--GR300-rgb));
+@media (prefers-color-scheme: dark) {
+ .error-msg {
+ color: rgb(var(--GR300-rgb));
+ }
}
.invalid label {
color: rgb(var(--GR600-rgb));
}
-html[darkmode=true] .invalid label {
- color: rgb(var(--GR300-rgb));
+@media (prefers-color-scheme: dark) {
+ .invalid label {
+ color: rgb(var(--GR300-rgb));
+ }
}
.invalid .error-msg {
@@ -163,8 +180,10 @@ html[darkmode=true] .invalid label {
width: 100%;
}
-html[darkmode=true] .invalid .underline {
- border-color: rgb(var(--GR300-rgb));
+@media (prefers-color-scheme: dark) {
+ .invalid .underline {
+ border-color: rgb(var(--GR300-rgb));
+ }
}
.buttons-container {
diff --git a/chromium/chrome/browser/resources/local_ntp/custom_links_edit.js b/chromium/chrome/browser/resources/local_ntp/custom_links_edit.js
index fd6e4d408e9..025d1e6ac1a 100644
--- a/chromium/chrome/browser/resources/local_ntp/custom_links_edit.js
+++ b/chromium/chrome/browser/resources/local_ntp/custom_links_edit.js
@@ -2,7 +2,6 @@
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
-
/**
* Enum for ids.
* @enum {string}
@@ -23,7 +22,6 @@ const IDS = {
URL_FIELD_NAME: 'url-field-name', // URL input field name.
};
-
/**
* Enum for key codes.
* @enum {number}
@@ -36,7 +34,6 @@ const KEYCODES = {
TAB: 9,
};
-
/**
* The origin of this request, i.e. 'https://www.google.TLD' for the remote NTP,
* or 'chrome-search://local-ntp' for the local NTP.
@@ -44,14 +41,12 @@ const KEYCODES = {
*/
const DOMAIN_ORIGIN = '{{ORIGIN}}';
-
/**
* List of parameters passed by query args.
* @type {Object}
*/
let queryArgs = {};
-
/**
* The prepopulated data for the form. Includes title, url, and rid.
* @type {Object}
@@ -62,28 +57,24 @@ const prepopulatedLink = {
url: '',
};
-
/**
* The title of the dialog when adding a link.
* @type {string}
*/
let addLinkTitle = '';
-
/**
* The title of the dialog when editing a link.
* @type {string}
*/
let editLinkTitle = '';
-
/**
* The accessibility title of remove link button.
* @type {string}
*/
let deleteLinkTitle = '';
-
/**
* Handler for the 'linkData' message from the host page. Pre-populates the url
* and title fields with link's data obtained using the rid. Called if we are
@@ -111,7 +102,6 @@ function prepopulateFields(rid) {
$(IDS.DONE).title = editLinkTitle;
}
-
/**
* Shows the invalid URL error message until the URL field is modified.
*/
@@ -124,7 +114,6 @@ function showInvalidUrlUntilTextInput() {
$(IDS.URL_FIELD).addEventListener('input', reenable);
}
-
/**
* Send a message to close the edit dialog. Called when the edit flow has been
* completed. If the fields were unchanged, does not update the link data.
@@ -159,7 +148,6 @@ function finishEditLink() {
closeDialog();
}
-
/**
* Call the EmbeddedSearchAPI to delete the link. Closes the dialog.
* @param {!Event} event The click event.
@@ -169,7 +157,6 @@ function deleteLink(event) {
closeDialog();
}
-
/**
* Send a message to close the edit dialog, clears the url and title fields, and
* resets the button statuses. Called when the edit flow has been completed.
@@ -189,7 +176,6 @@ function closeDialog() {
}, 10);
}
-
/**
* Send a message to refocus the edited tile's three dot menu or the add
* shortcut tile after the cancel button is clicked.
@@ -197,23 +183,13 @@ function closeDialog() {
*/
function focusBackOnCancel(event) {
if (event.keyCode === KEYCODES.ENTER || event.keyCode === KEYCODES.SPACE) {
- const message = {cmd: 'focusMenu', tid: prepopulatedLink.rid};
+ const message = {cmd: 'focusMenu', rid: prepopulatedLink.rid};
window.parent.postMessage(message, DOMAIN_ORIGIN);
event.preventDefault();
closeDialog();
}
}
-
-/**
- * Handler for the 'updateTheme' message from the host page.
- * @param {!Object} info Data received in the message.
- */
-function updateTheme(info) {
- document.documentElement.setAttribute('darkmode', info.isDarkMode);
-}
-
-
/**
* Event handler for messages from the host page.
* @param {Event} event Event received.
@@ -222,10 +198,10 @@ function handlePostMessage(event) {
const cmd = event.data.cmd;
const args = event.data;
if (cmd === 'linkData') {
- if (args.tid) { // We are editing a link, prepopulate the link data.
+ if (args.rid) { // We are editing a link, prepopulate the link data.
document.title = editLinkTitle;
$(IDS.DIALOG_TITLE).textContent = editLinkTitle;
- prepopulateFields(args.tid);
+ prepopulateFields(args.rid);
} else { // We are adding a link, disable the delete button.
document.title = addLinkTitle;
$(IDS.DIALOG_TITLE).textContent = addLinkTitle;
@@ -240,12 +216,9 @@ function handlePostMessage(event) {
window.setTimeout(() => {
$(IDS.TITLE_FIELD).select();
}, 10);
- } else if (cmd === 'updateTheme') {
- updateTheme(args);
}
}
-
/**
* Does some initialization and shows the dialog window.
*/
@@ -328,8 +301,10 @@ function init() {
$(IDS.URL_FIELD)
.addEventListener('blur', () => changeColor(IDS.URL_FIELD_NAME));
// Disables the "Done" button when the URL field is empty.
- $(IDS.URL_FIELD).addEventListener('input',
- () => $(IDS.DONE).disabled = ($(IDS.URL_FIELD).value.trim() === ''));
+ $(IDS.URL_FIELD)
+ .addEventListener(
+ 'input',
+ () => $(IDS.DONE).disabled = ($(IDS.URL_FIELD).value.trim() === ''));
utils.setPlatformClass(document.body);
@@ -338,5 +313,4 @@ function init() {
window.addEventListener('message', handlePostMessage);
}
-
window.addEventListener('DOMContentLoaded', init);
diff --git a/chromium/chrome/browser/resources/local_ntp/custom_backgrounds.css b/chromium/chrome/browser/resources/local_ntp/customize.css
index c719258454e..0022263c7be 100644
--- a/chromium/chrome/browser/resources/local_ntp/custom_backgrounds.css
+++ b/chromium/chrome/browser/resources/local_ntp/customize.css
@@ -2,7 +2,8 @@
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
-#custom-bg {
+#custom-bg,
+#custom-bg-preview {
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
@@ -21,6 +22,7 @@
align-items: center;
border-radius: 500px;
bottom: 16px;
+ cursor: pointer;
display: flex;
height: 32px;
justify-content: center;
@@ -32,8 +34,7 @@
#edit-bg.ep-enhanced {
background-color: rgb(255, 255, 255);
- box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 1px 2px rgba(0, 0, 0, 0.23);
- cursor: pointer;
+ box-shadow: 0 3px 6px rgba(0, 0, 0, .16), 0 1px 2px rgba(0, 0, 0, .23);
}
#edit-bg:hover,
@@ -46,12 +47,16 @@
}
-html[darkmode=true] #edit-bg.ep-enhanced {
- background-color: rgb(41, 42, 45);
+@media (prefers-color-scheme: dark) {
+ #edit-bg.ep-enhanced {
+ background-color: rgb(var(--dark-mode-dialog-rgb));
+ }
}
-html[darkmode=true] #edit-bg:hover.ep-enhanced {
- background-color: rgb(50, 51, 54);
+@media (prefers-color-scheme: dark) {
+ #edit-bg:hover.ep-enhanced {
+ background-color: rgb(50, 51, 54);
+ }
}
html[dir=rtl] #edit-bg {
@@ -80,8 +85,10 @@ html[dir=rtl] #edit-bg {
background-color: rgb(var(--GB600-rgb));
}
-html[darkmode=true] .ep-enhanced #edit-bg-icon {
- background-color: rgb(var(--GB300-rgb));
+@media (prefers-color-scheme: dark) {
+ .ep-enhanced #edit-bg-icon {
+ background-color: rgb(var(--GB300-rgb));
+ }
}
#edit-bg-text {
@@ -93,8 +100,10 @@ html[darkmode=true] .ep-enhanced #edit-bg-icon {
user-select: none;
}
-html[darkmode=true] .ep-enhanced #edit-bg-text {
- color: rgb(var(--GB300-rgb));
+@media (prefers-color-scheme: dark) {
+ .ep-enhanced #edit-bg-text {
+ color: rgb(var(--GB300-rgb));
+ }
}
@media (min-width: 550px) {
@@ -107,6 +116,12 @@ html[darkmode=true] .ep-enhanced #edit-bg-text {
}
}
+@media (max-height: 100px) {
+ #edit-bg {
+ display: none;
+ }
+}
+
#edit-bg-dialog::backdrop {
background: transparent;
}
@@ -117,18 +132,19 @@ html[darkmode=true] .ep-enhanced #edit-bg-text {
border-radius: 8px;
border-width: thin;
bottom: 44px;
- box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), 0.3),
- 0 4px 8px 3px rgba(var(--GG800-rgb), 0.15);
+ box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), .3),
+ 0 4px 8px 3px rgba(var(--GG800-rgb), .15);
left: auto;
padding: 0;
position: fixed;
right: 16px;
}
-html[darkmode=true] #edit-bg-dialog {
- background-color: rgb(41, 42, 45);
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.3),
- 0 4px 8px 3px rgba(0, 0, 0, 0.15);
+@media (prefers-color-scheme: dark) {
+ #edit-bg-dialog {
+ background-color: rgb(var(--dark-mode-dialog-rgb));
+ box-shadow: var(--dark-mode-shadow);
+ }
}
#edit-bg-menu {
@@ -152,8 +168,10 @@ html[dir=rtl] #edit-bg-title {
padding: 16px 16px 0 0;
}
-html[darkmode=true] #edit-bg-title {
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ #edit-bg-title {
+ color: rgb(var(--GG200-rgb));
+ }
}
.using-mouse-nav .bg-option:focus {
@@ -167,16 +185,20 @@ html[darkmode=true] #edit-bg-title {
line-height: 40px;
}
-html[darkmode=true] .bg-option {
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ .bg-option {
+ color: rgb(var(--GG200-rgb));
+ }
}
.bg-option:hover {
background-color: rgb(var(--GG100-rgb));
}
-html[darkmode=true] .bg-option:hover {
- background-color: rgb(var(--GG800-rgb));
+@media (prefers-color-scheme: dark) {
+ .bg-option:hover {
+ background-color: rgb(var(--GG800-rgb));
+ }
}
.bg-option-img {
@@ -195,19 +217,20 @@ html[dir=rtl] .bg-option-img {
}
.bg-option.bg-option-disabled {
- opacity: 0.28;
+ opacity: .28;
}
-html[darkmode=true] .bg-option.bg-option-disabled {
- opacity: 0.38;
+@media (prefers-color-scheme: dark) {
+ .bg-option.bg-option-disabled {
+ opacity: .38;
+ }
}
.bg-option.bg-option-disabled:focus {
outline: none;
}
-.bg-option.bg-option-disabled:hover,
-html[darkmode=true] .bg-option.bg-option-disabled:hover {
+.bg-option.bg-option-disabled:hover {
background-color: transparent;
}
@@ -226,8 +249,10 @@ html[darkmode=true] .bg-option.bg-option-disabled:hover {
width: 100%;
}
-html[darkmode=true] #edit-bg-divider {
- border-color: rgba(255, 255, 255, 0.1);
+@media (prefers-color-scheme: dark) {
+ #edit-bg-divider {
+ border-color: rgba(255, 255, 255, .1);
+ }
}
#custom-links-restore-default .bg-option-img {
@@ -258,8 +283,8 @@ html[darkmode=true] #edit-bg-divider {
border: none;
border-radius: 8px;
bottom: 0;
- box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), 0.3),
- 0 4px 8px 3px rgba(var(--GG800-rgb), 0.15);
+ box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), .3),
+ 0 4px 8px 3px rgba(var(--GG800-rgb), .15);
height: 400px;
padding: 0 0 0 0;
position: fixed;
@@ -270,10 +295,11 @@ html[darkmode=true] #edit-bg-divider {
z-index: 10000;
}
-html[darkmode=true] #bg-sel-menu {
- background-color: rgb(41, 42, 45);
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.3),
- 0 4px 8px 3px rgba(0, 0, 0, 0.15);
+@media (prefers-color-scheme: dark) {
+ #bg-sel-menu {
+ background-color: rgb(var(--dark-mode-dialog-rgb));
+ box-shadow: var(--dark-mode-shadow);
+ }
}
/* The width is decided by the longest text length plus 16px margin on the
@@ -307,8 +333,10 @@ right, so that every text can stay on its row even on the smallest window */
user-select: none;
}
-html[darkmode=true] #bg-sel-title-bar {
- border-color: rgba(255, 255, 255, 0.1);
+@media (prefers-color-scheme: dark) {
+ #bg-sel-title-bar {
+ border-color: rgba(255, 255, 255, .1);
+ }
}
#bg-sel-back {
@@ -321,23 +349,27 @@ html[darkmode=true] #bg-sel-title-bar {
width: 20px;
}
-html[darkmode=true] #bg-sel-back {
- background: transparent;
+@media (prefers-color-scheme: dark) {
+ #bg-sel-back {
+ background: transparent;
+ }
}
/* We use ::after without content to provide the masked arrow element. */
-html[darkmode=true] #bg-sel-back::after {
- -webkit-mask-image: url(../../../../ui/webui/resources/images/icon_arrow_back.svg);
- -webkit-mask-repeat: no-repeat;
- -webkit-mask-size: 20px;
- background-color: rgb(var(--GG200-rgb));
- content: '';
- display: block;
- height: 20px;
- left: 0;
- position: absolute;
- top: 0;
- width: 20px;
+@media (prefers-color-scheme: dark) {
+ #bg-sel-back::after {
+ -webkit-mask-image: url(../../../../ui/webui/resources/images/icon_arrow_back.svg);
+ -webkit-mask-repeat: no-repeat;
+ -webkit-mask-size: 20px;
+ background-color: rgb(var(--GG200-rgb));
+ content: '';
+ display: block;
+ height: 20px;
+ left: 0;
+ position: absolute;
+ top: 0;
+ width: 20px;
+ }
}
#bg-sel-back-circle {
@@ -356,9 +388,11 @@ html[darkmode=true] #bg-sel-back::after {
background-size: 36px 36px;
}
-html[darkmode=true] #bg-sel-back-circle:active,
-html[darkmode=true] #bg-sel-back-circle:focus {
- background: rgb(var(--GG800-rgb));
+@media (prefers-color-scheme: dark) {
+ #bg-sel-back-circle:active,
+ #bg-sel-back-circle:focus {
+ background: rgb(var(--GG800-rgb));
+ }
}
.is-col-sel #bg-sel-back {
@@ -404,8 +438,10 @@ html[dir=rtl] .is-img-sel #bg-sel-back {
text-align: center;
}
-html[darkmode=true] #bg-sel-title {
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ #bg-sel-title {
+ color: rgb(var(--GG200-rgb));
+ }
}
.is-col-sel #bg-sel-title {
@@ -436,8 +472,10 @@ html[dir=rtl] .is-img-sel #bg-sel-title {
width: 100%;
}
-html[darkmode=true] #bg-sel-footer {
- border-color: rgba(255, 255, 255, 0.1);
+@media (prefers-color-scheme: dark) {
+ #bg-sel-footer {
+ border-color: rgba(255, 255, 255, .1);
+ }
}
.bg-sel-footer-button {
@@ -479,8 +517,10 @@ html[dir=rtl] .bg-sel-tile-bg {
width: calc(33% - 8px);
}
-html[darkmode=true] .bg-sel-tile-bg {
- background-color: rgb(var(--GG900-rgb));
+@media (prefers-color-scheme: dark) {
+ .bg-sel-tile-bg {
+ background-color: rgb(var(--GG900-rgb));
+ }
}
/* The width here should match that used in customBackgrounds.getTilesWide. */
@@ -519,8 +559,10 @@ html[darkmode=true] .bg-sel-tile-bg {
width: 100%;
}
-html[darkmode=true] .selected-border {
- border-color: rgb(var(--GB300-rgb));
+@media (prefers-color-scheme: dark) {
+ .selected-border {
+ border-color: rgb(var(--GB300-rgb));
+ }
}
.selected-circle {
@@ -538,8 +580,10 @@ html[dir=rtl] .selected-circle {
right: 66px;
}
-html[darkmode=true] .selected-circle {
- background-color: rgb(var(--GG900-rgb));
+@media (prefers-color-scheme: dark) {
+ .selected-circle {
+ background-color: rgb(var(--GG900-rgb));
+ }
}
.selected-check {
@@ -557,27 +601,31 @@ html[dir=rtl] .selected-check {
right: 63px;
}
-html[darkmode=true] .selected-check {
- background: transparent;
+@media (prefers-color-scheme: dark) {
+ .selected-check {
+ background: transparent;
+ }
}
/* We use ::after without content to provide the masked check element. */
-html[darkmode=true] .selected-check::after {
- -webkit-mask-image: url(../../../../ui/webui/resources/images/check_circle.svg);
- -webkit-mask-repeat: no-repeat;
- -webkit-mask-size: 28px;
- background-color: rgb(var(--GB300-rgb));
- content: '';
- display: block;
- height: 28px;
- left: 0;
- position: absolute;
- top: 0;
- width: 28px;
+@media (prefers-color-scheme: dark) {
+ .selected-check::after {
+ -webkit-mask-image: url(../../../../ui/webui/resources/images/check_circle.svg);
+ -webkit-mask-repeat: no-repeat;
+ -webkit-mask-size: 28px;
+ background-color: rgb(var(--GB300-rgb));
+ content: '';
+ display: block;
+ height: 28px;
+ left: 0;
+ position: absolute;
+ top: 0;
+ width: 28px;
+ }
}
.bg-sel-tile-title {
- background-color: rgba(var(--GG900-rgb), 0.71);
+ background-color: rgba(var(--GG900-rgb), .71);
bottom: 0;
box-sizing: border-box;
color: #FFF;
@@ -608,7 +656,7 @@ html[darkmode=true] .selected-check::after {
max-width: 80%;
padding: 8px 8px 8px 8px;
position: fixed;
- text-shadow: 0 0 16px rgba(0, 0, 0, 0.3);
+ text-shadow: 0 0 16px rgba(0, 0, 0, .3);
z-index: -1;
}
diff --git a/chromium/chrome/browser/resources/local_ntp/customize.js b/chromium/chrome/browser/resources/local_ntp/customize.js
new file mode 100644
index 00000000000..658c6766a5f
--- /dev/null
+++ b/chromium/chrome/browser/resources/local_ntp/customize.js
@@ -0,0 +1,2432 @@
+// 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.
+
+'use strict';
+
+// TODO(crbug.com/937570): After the RP launches this should be renamed to
+// customizationMenu along with the file, and large parts can be
+// refactored/removed.
+const customize = {};
+
+/**
+ * The browser embeddedSearch.newTabPage object.
+ * @type {Object}
+ */
+let ntpApiHandle;
+
+/**
+ * The different types of events that are logged from the NTP. This enum is
+ * used to transfer information from the NTP JavaScript to the renderer and is
+ * not used as a UMA enum histogram's logged value.
+ * Note: Keep in sync with common/ntp_logging_events.h
+ * @enum {number}
+ * @const
+ */
+customize.LOG_TYPE = {
+ // The 'Chrome backgrounds' menu item was clicked.
+ NTP_CUSTOMIZE_CHROME_BACKGROUNDS_CLICKED: 40,
+ // The 'Upload an image' menu item was clicked.
+ NTP_CUSTOMIZE_LOCAL_IMAGE_CLICKED: 41,
+ // The 'Restore default background' menu item was clicked.
+ // NOTE: NTP_CUSTOMIZE_RESTORE_BACKGROUND_CLICKED (42) is logged on the
+ // backend.
+ // The attribution link on a customized background image was clicked.
+ NTP_CUSTOMIZE_ATTRIBUTION_CLICKED: 43,
+ // The 'Restore default shortcuts' menu item was clicked.
+ NTP_CUSTOMIZE_RESTORE_SHORTCUTS_CLICKED: 46,
+ // A collection was selected in the 'Chrome backgrounds' dialog.
+ NTP_CUSTOMIZE_CHROME_BACKGROUND_SELECT_COLLECTION: 47,
+ // An image was selected in the 'Chrome backgrounds' dialog.
+ NTP_CUSTOMIZE_CHROME_BACKGROUND_SELECT_IMAGE: 48,
+ // 'Cancel' was clicked in the 'Chrome backgrounds' dialog.
+ NTP_CUSTOMIZE_CHROME_BACKGROUND_CANCEL: 49,
+ // NOTE: NTP_CUSTOMIZE_CHROME_BACKGROUND_DONE (50) is logged on the backend.
+ // The richer picker was opened.
+ NTP_CUSTOMIZATION_MENU_OPENED: 64,
+ // 'Cancel' was clicked in the richer picker.
+ NTP_CUSTOMIZATION_MENU_CANCEL: 65,
+ // 'Done' was clicked in the richer picker.
+ NTP_CUSTOMIZATION_MENU_DONE: 66,
+ // 'Upload from device' selected in the richer picker.
+ NTP_BACKGROUND_UPLOAD_FROM_DEVICE: 67,
+ // A collection tile was selected in the richer picker.
+ NTP_BACKGROUND_OPEN_COLLECTION: 68,
+ // A image tile was selected in the richer picker.
+ NTP_BACKGROUND_SELECT_IMAGE: 69,
+ // The back arrow was clicked in the richer picker.
+ NTP_BACKGROUND_BACK_CLICK: 72,
+ // The 'No background' tile was selected in the richer picker.
+ NTP_BACKGROUND_DEFAULT_SELECTED: 73,
+ // The custom links option in the shortcuts submenu was clicked.
+ NTP_CUSTOMIZE_SHORTCUT_CUSTOM_LINKS_CLICKED: 78,
+ // The Most Visited option in the shortcuts submenu was clicked.
+ NTP_CUSTOMIZE_SHORTCUT_MOST_VISITED_CLICKED: 79,
+ // The visibility toggle in the shortcuts submenu was clicked.
+ NTP_CUSTOMIZE_SHORTCUT_VISIBILITY_TOGGLE_CLICKED: 80,
+ // The 'refresh daily' toggle was licked in the richer picker.
+ NTP_BACKGROUND_REFRESH_TOGGLE_CLICKED: 81,
+};
+
+/**
+ * Enum for key codes.
+ * @enum {number}
+ * @const
+ */
+customize.KEYCODES = {
+ BACKSPACE: 8,
+ DOWN: 40,
+ ENTER: 13,
+ ESC: 27,
+ LEFT: 37,
+ RIGHT: 39,
+ SPACE: 32,
+ TAB: 9,
+ UP: 38,
+};
+
+/**
+ * Array for keycodes corresponding to arrow keys.
+ * @type Array
+ * @const
+ */
+customize.arrowKeys = [/*Left*/ 37, /*Up*/ 38, /*Right*/ 39, /*Down*/ 40];
+
+/**
+ * Enum for HTML element ids.
+ * @enum {string}
+ * @const
+ */
+customize.IDS = {
+ ATTR1: 'attr1',
+ ATTR2: 'attr2',
+ ATTRIBUTIONS: 'custom-bg-attr',
+ BACK_CIRCLE: 'bg-sel-back-circle',
+ BACKGROUNDS_DEFAULT: 'backgrounds-default',
+ BACKGROUNDS_DEFAULT_ICON: 'backgrounds-default-icon',
+ BACKGROUNDS_BUTTON: 'backgrounds-button',
+ BACKGROUNDS_IMAGE_MENU: 'backgrounds-image-menu',
+ BACKGROUNDS_MENU: 'backgrounds-menu',
+ BACKGROUNDS_UPLOAD: 'backgrounds-upload',
+ BACKGROUNDS_UPLOAD_ICON: 'backgrounds-upload-icon',
+ CANCEL: 'bg-sel-footer-cancel',
+ COLOR_PICKER: 'color-picker',
+ COLOR_PICKER_TILE: 'color-picker-tile',
+ COLOR_PICKER_CONTAINER: 'color-picker-container',
+ COLOR_PICKER_ICON: 'color-picker-icon',
+ COLORS_BUTTON: 'colors-button',
+ COLORS_DEFAULT_ICON: 'colors-default-icon',
+ COLORS_THEME: 'colors-theme',
+ COLORS_THEME_NAME: 'colors-theme-name',
+ COLORS_THEME_UNINSTALL: 'colors-theme-uninstall',
+ COLORS_THEME_WEBSTORE_LINK: 'colors-theme-link',
+ COLORS_MENU: 'colors-menu',
+ CUSTOMIZATION_MENU: 'customization-menu',
+ CUSTOM_BG: 'custom-bg',
+ CUSTOM_BG_PREVIEW: 'custom-bg-preview',
+ CUSTOM_LINKS_RESTORE_DEFAULT: 'custom-links-restore-default',
+ CUSTOM_LINKS_RESTORE_DEFAULT_TEXT: 'custom-links-restore-default-text',
+ DEFAULT_WALLPAPERS: 'edit-bg-default-wallpapers',
+ DEFAULT_WALLPAPERS_TEXT: 'edit-bg-default-wallpapers-text',
+ DONE: 'bg-sel-footer-done',
+ EDIT_BG: 'edit-bg',
+ EDIT_BG_DIALOG: 'edit-bg-dialog',
+ EDIT_BG_DIVIDER: 'edit-bg-divider',
+ EDIT_BG_MENU: 'edit-bg-menu',
+ MENU_BACK_CIRCLE: 'menu-back-circle',
+ MENU_CANCEL: 'menu-cancel',
+ MENU_DONE: 'menu-done',
+ MENU_TITLE: 'menu-title',
+ LINK_ICON: 'link-icon',
+ MENU: 'bg-sel-menu',
+ OPTIONS_TITLE: 'edit-bg-title',
+ REFRESH_DAILY_WRAPPER: 'refresh-daily-wrapper',
+ REFRESH_TOGGLE: 'refresh-daily-toggle',
+ RESTORE_DEFAULT: 'edit-bg-restore-default',
+ RESTORE_DEFAULT_TEXT: 'edit-bg-restore-default-text',
+ SHORTCUTS_BUTTON: 'shortcuts-button',
+ SHORTCUTS_HIDE: 'sh-hide',
+ SHORTCUTS_HIDE_TOGGLE: 'sh-hide-toggle',
+ SHORTCUTS_MENU: 'shortcuts-menu',
+ SHORTCUTS_OPTION_CUSTOM_LINKS: 'sh-option-cl',
+ SHORTCUTS_OPTION_MOST_VISITED: 'sh-option-mv',
+ UPLOAD_IMAGE: 'edit-bg-upload-image',
+ UPLOAD_IMAGE_TEXT: 'edit-bg-upload-image-text',
+ TILES: 'bg-sel-tiles',
+ TITLE: 'bg-sel-title',
+};
+
+/**
+ * Enum for classnames.
+ * @enum {string}
+ * @const
+ */
+customize.CLASSES = {
+ ATTR_SMALL: 'attr-small',
+ ATTR_COMMON: 'attr-common',
+ ATTR_LINK: 'attr-link',
+ COLLECTION_DIALOG: 'is-col-sel',
+ COLLECTION_SELECTED: 'bg-selected', // Highlight selected tile
+ COLLECTION_TILE: 'bg-sel-tile', // Preview tile for background customization
+ COLLECTION_TILE_BG: 'bg-sel-tile-bg',
+ COLLECTION_TITLE: 'bg-sel-tile-title', // Title of a background image
+ IMAGE_DIALOG: 'is-img-sel',
+ ON_IMAGE_MENU: 'on-img-menu',
+ OPTION: 'bg-option',
+ OPTION_DISABLED: 'bg-option-disabled', // The menu option is disabled.
+ MENU_SHOWN: 'menu-shown',
+ MOUSE_NAV: 'using-mouse-nav',
+ SELECTED: 'selected',
+ SELECTED_BORDER: 'selected-border',
+ SELECTED_CHECK: 'selected-check',
+ SELECTED_CIRCLE: 'selected-circle',
+ SINGLE_ATTR: 'single-attr',
+ VISIBLE: 'visible'
+};
+
+/**
+ * Enum for background option menu entries, in the order they appear in the UI.
+ * @enum {number}
+ * @const
+ */
+customize.MENU_ENTRIES = {
+ CHROME_BACKGROUNDS: 0,
+ UPLOAD_IMAGE: 1,
+ CUSTOM_LINKS_RESTORE_DEFAULT: 2,
+ RESTORE_DEFAULT: 3,
+};
+
+/**
+ * The semi-transparent, gradient overlay for the custom background. Intended
+ * to improve readability of NTP elements/text.
+ * @type {string}
+ * @const
+ */
+customize.CUSTOM_BACKGROUND_OVERLAY =
+ 'linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.3))';
+
+/**
+ * Number of rows in the custom background dialog to preload.
+ * @type {number}
+ * @const
+ */
+customize.ROWS_TO_PRELOAD = 3;
+
+// These should match the corresponding values in local_ntp.js, that control the
+// mv-notice element.
+customize.delayedHideNotification = -1;
+customize.NOTIFICATION_TIMEOUT = 10000;
+
+/**
+ * Were the background tiles already created.
+ * @type {boolean}
+ */
+customize.builtTiles = false;
+
+/**
+ * The default title for the richer picker.
+ * @type {string}
+ */
+customize.richerPicker_defaultTitle = '';
+
+/**
+ * Called when the error notification should be shown.
+ * @type {?Function}
+ */
+customize.showErrorNotification = null;
+
+/**
+ * Called when the custom link notification should be hidden.
+ * @type {?Function}
+ */
+customize.hideCustomLinkNotification = null;
+
+/**
+ * Id of the currently open collection.
+ * @type {string}
+ */
+customize.currentCollectionId = '';
+
+/**
+ * The currently active Background submenu. This can be the collections page or
+ * a collection's image menu. Defaults to the collections page.
+ * @type {Object}
+ */
+customize.richerPicker_openBackgroundSubmenu = {
+ menuId: customize.IDS.BACKGROUNDS_MENU,
+ title: '',
+};
+
+/**
+ * The currently selected submenu (i.e. Background, Shortcuts, etc.) in the
+ * richer picker.
+ * @type {Object}
+ */
+customize.richerPicker_selectedSubmenu = {
+ menuButton: null, // The submenu's button element in the sidebar.
+ menu: null, // The submenu's menu element.
+ // The submenu's title. Will usually be |customize.richerPicker_defaultTitle|
+ // unless this is a background collection's image menu.
+ title: '',
+};
+
+/**
+ * The currently selected options in the customization menu.
+ * @type {Object}
+ */
+customize.selectedOptions = {
+ background: null, // Contains the background image tile.
+ // The data associated with a currently selected background.
+ backgroundData: null,
+ // Contains the selected shortcut type's DOM element, i.e. either custom links
+ // or most visited.
+ shortcutType: null,
+ shortcutsAreHidden: false,
+ color: null, // Contains the selected color tile's DOM element.
+};
+
+/**
+ * The preselected options in the richer picker.
+ * @type {Object}
+ */
+customize.preselectedOptions = {
+ // Contains the selected type's DOM element, i.e. either custom links or most
+ // visited.
+ shortcutType: null,
+ shortcutsAreHidden: false,
+ colorsMenuTile: null, // Selected tile for Colors menu.
+ backgroundsMenuTile: null, // Selected tile for Backgrounds menu.
+};
+
+/**
+ * Whether tiles for Colors menu already loaded.
+ * @type {boolean}
+ */
+customize.colorsMenuLoaded = false;
+
+
+/**
+ * Default color for custom color picker in hex format.
+ * @type {string}
+ */
+customize.defaultCustomColor = '#000000';
+
+/**
+ * Custom color picked in hex format.
+ * @type {string}
+ */
+customize.customColorPicked = customize.defaultCustomColor;
+
+/**
+ * Sets the visibility of the settings menu and individual options depending on
+ * their respective features.
+ */
+customize.setMenuVisibility = function() {
+ // Reset all hidden values.
+ $(customize.IDS.EDIT_BG).hidden = false;
+ $(customize.IDS.DEFAULT_WALLPAPERS).hidden = false;
+ $(customize.IDS.UPLOAD_IMAGE).hidden = false;
+ $(customize.IDS.RESTORE_DEFAULT).hidden = false;
+ $(customize.IDS.EDIT_BG_DIVIDER).hidden = false;
+ $(customize.IDS.CUSTOM_LINKS_RESTORE_DEFAULT).hidden =
+ configData.hideShortcuts;
+ $(customize.IDS.COLORS_BUTTON).hidden = !configData.chromeColors;
+ $(customize.IDS.COLOR_PICKER_CONTAINER)
+ .classList.toggle(
+ customize.CLASSES.VISIBLE, configData.chromeColorsCustomColorPicker);
+};
+
+/**
+ * Called when user changes the theme.
+ */
+customize.onThemeChange = function() {
+ // Hide the settings menu or individual options if the related features are
+ // disabled.
+ customize.setMenuVisibility();
+
+ // If theme changed after Colors menu was loaded, then reload theme info.
+ if (customize.colorsMenuLoaded) {
+ customize.colorsMenuOnThemeChange();
+ }
+};
+
+/**
+ * Display custom background image attributions on the page.
+ * @param {string} attributionLine1 First line of attribution.
+ * @param {string} attributionLine2 Second line of attribution.
+ * @param {string} attributionActionUrl Url to learn more about the image.
+ */
+customize.setAttribution = function(
+ attributionLine1, attributionLine2, attributionActionUrl) {
+ const attributionBox = $(customize.IDS.ATTRIBUTIONS);
+ const attr1 = document.createElement('span');
+ attr1.id = customize.IDS.ATTR1;
+ const attr2 = document.createElement('span');
+ attr2.id = customize.IDS.ATTR2;
+
+ if (attributionLine1 !== '') {
+ // Shouldn't be changed from textContent for security assurances.
+ attr1.textContent = attributionLine1;
+ attr1.classList.add(customize.CLASSES.ATTR_COMMON);
+ $(customize.IDS.ATTRIBUTIONS).appendChild(attr1);
+ }
+ if (attributionLine2 !== '') {
+ // Shouldn't be changed from textContent for security assurances.
+ attr2.textContent = attributionLine2;
+ attr2.classList.add(customize.CLASSES.ATTR_SMALL);
+ attr2.classList.add(customize.CLASSES.ATTR_COMMON);
+ attributionBox.appendChild(attr2);
+ }
+ if (attributionActionUrl !== '') {
+ const attr = (attributionLine2 !== '' ? attr2 : attr1);
+ attr.classList.add(customize.CLASSES.ATTR_LINK);
+
+ const linkIcon = document.createElement('div');
+ linkIcon.id = customize.IDS.LINK_ICON;
+ // Enlarge link-icon when there is only one line of attribution
+ if (attributionLine2 === '') {
+ linkIcon.classList.add(customize.CLASSES.SINGLE_ATTR);
+ }
+ attr.insertBefore(linkIcon, attr.firstChild);
+
+ attributionBox.classList.add(customize.CLASSES.ATTR_LINK);
+ attributionBox.href = attributionActionUrl;
+ attributionBox.onclick = function() {
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_CUSTOMIZE_ATTRIBUTION_CLICKED);
+ };
+ attributionBox.style.cursor = 'pointer';
+ }
+};
+
+customize.clearAttribution = function() {
+ const attributions = $(customize.IDS.ATTRIBUTIONS);
+ attributions.removeAttribute('href');
+ attributions.className = '';
+ attributions.style.cursor = 'default';
+ while (attributions.firstChild) {
+ attributions.removeChild(attributions.firstChild);
+ }
+};
+
+customize.unselectTile = function() {
+ $(customize.IDS.DONE).disabled = true;
+ customize.selectedOptions.background = null;
+ $(customize.IDS.DONE).tabIndex = -1;
+};
+
+/**
+ * Remove all collection tiles from the container when the dialog
+ * is closed.
+ */
+customize.resetSelectionDialog = function() {
+ $(customize.IDS.TILES).scrollTop = 0;
+ const tileContainer = $(customize.IDS.TILES);
+ while (tileContainer.firstChild) {
+ tileContainer.removeChild(tileContainer.firstChild);
+ }
+ customize.unselectTile();
+};
+
+/**
+ * Apply selected styling to |menuButton| and make corresponding |menu| visible.
+ * If |title| is not specified, the default title will be used.
+ * @param {?Element} menuButton The sidebar button element to apply styling to.
+ * @param {?Element} menu The submenu element to apply styling to.
+ * @param {string=} title The submenu's title.
+ */
+customize.richerPicker_showSubmenu = function(menuButton, menu, title = '') {
+ if (!menuButton || !menu) {
+ return;
+ }
+
+ customize.richerPicker_hideOpenSubmenu();
+
+ if (!title) { // Use the default title if not specified.
+ title = customize.richerPicker_defaultTitle;
+ }
+
+ // Save this as the currently open submenu.
+ customize.richerPicker_selectedSubmenu.menuButton = menuButton;
+ customize.richerPicker_selectedSubmenu.menu = menu;
+ customize.richerPicker_selectedSubmenu.title = title;
+
+ menuButton.classList.toggle(customize.CLASSES.SELECTED, true);
+ menu.classList.toggle(customize.CLASSES.MENU_SHOWN, true);
+ $(customize.IDS.MENU_TITLE).textContent = title;
+ menuButton.setAttribute('aria-selected', true);
+
+ // Indicate if this is a Background collection's image menu, which will enable
+ // the back button.
+ $(customize.IDS.CUSTOMIZATION_MENU)
+ .classList.toggle(
+ customize.CLASSES.ON_IMAGE_MENU,
+ menu.id === customize.IDS.BACKGROUNDS_IMAGE_MENU);
+};
+
+/**
+ * Hides the currently open submenu if any.
+ */
+customize.richerPicker_hideOpenSubmenu = function() {
+ if (!customize.richerPicker_selectedSubmenu.menuButton) {
+ return; // No submenu is open.
+ }
+
+ customize.richerPicker_selectedSubmenu.menuButton.classList.toggle(
+ customize.CLASSES.SELECTED, false);
+ customize.richerPicker_selectedSubmenu.menu.classList.toggle(
+ customize.CLASSES.MENU_SHOWN, false);
+ $(customize.IDS.MENU_TITLE).textContent = customize.richerPicker_defaultTitle;
+ customize.richerPicker_selectedSubmenu.menuButton.setAttribute(
+ 'aria-selected', false);
+
+ customize.richerPicker_selectedSubmenu.menuButton = null;
+ customize.richerPicker_selectedSubmenu.menu = null;
+ customize.richerPicker_selectedSubmenu.title =
+ customize.richerPicker_defaultTitle;
+};
+
+/**
+ * Remove image tiles and maybe swap back to main background menu.
+ */
+customize.richerPicker_resetImageMenu = function() {
+ const backgroundMenu = $(customize.IDS.BACKGROUNDS_MENU);
+ const imageMenu = $(customize.IDS.BACKGROUNDS_IMAGE_MENU);
+ const menu = $(customize.IDS.CUSTOMIZATION_MENU);
+ const menuTitle = $(customize.IDS.MENU_TITLE);
+
+ imageMenu.innerHTML = '';
+ menu.classList.toggle(customize.CLASSES.ON_IMAGE_MENU, false);
+ customize.richerPicker_showSubmenu(
+ $(customize.IDS.BACKGROUNDS_BUTTON), backgroundMenu);
+ customize.richerPicker_openBackgroundSubmenu.menuId =
+ customize.IDS.BACKGROUNDS_MENU;
+ customize.richerPicker_openBackgroundSubmenu.title = '';
+ backgroundMenu.scrollTop = 0;
+};
+
+/**
+ * Close the collection selection dialog and cleanup the state
+ * @param {?Element} menu The dialog to be closed
+ */
+customize.closeCollectionDialog = function(menu) {
+ if (!menu) {
+ return;
+ }
+ menu.close();
+ customize.resetSelectionDialog();
+};
+
+/**
+ * Close and reset the dialog if this is not the richer picker, and set the
+ * background.
+ * @param {string} url The url of the selected background.
+ */
+customize.setBackground = function(
+ url, attributionLine1, attributionLine2, attributionActionUrl,
+ collection_id) {
+ if (!configData.richerPicker) {
+ customize.closeCollectionDialog($(customize.IDS.MENU));
+ }
+ window.chrome.embeddedSearch.newTabPage.setBackgroundInfo(
+ url, attributionLine1, attributionLine2, attributionActionUrl,
+ collection_id);
+};
+
+/**
+ * Apply selected shortcut options.
+ */
+customize.richerPicker_setShortcutOptions = function() {
+ const shortcutTypeChanged = customize.preselectedOptions.shortcutType !==
+ customize.selectedOptions.shortcutType;
+ if (customize.preselectedOptions.shortcutsAreHidden !==
+ customize.selectedOptions.shortcutsAreHidden) {
+ // Only trigger a notification if |toggleMostVisitedOrCustomLinks| will not
+ // be called immediately after. Successive |onmostvisitedchange| events can
+ // interfere with each other.
+ chrome.embeddedSearch.newTabPage.toggleShortcutsVisibility(
+ !shortcutTypeChanged);
+ }
+ if (shortcutTypeChanged) {
+ chrome.embeddedSearch.newTabPage.toggleMostVisitedOrCustomLinks();
+ }
+};
+
+/**
+ * Creates a tile for the customization menu with a title.
+ * @param {string} id The id for the new element.
+ * @param {string} imageUrl The background image url for the new element.
+ * @param {string} name The name for the title of the new element.
+ * @param {Object} dataset The dataset for the new element.
+ * @param {?Function} onClickInteraction Function for onclick interaction.
+ * @param {?Function} onKeyInteraction Function for onkeydown interaction.
+ */
+customize.createTileWithTitle = function(
+ id, imageUrl, name, dataset, onClickInteraction, onKeyInteraction) {
+ const tile = customize.createTileThumbnail(
+ id, imageUrl, dataset, onClickInteraction, onKeyInteraction);
+ tile.setAttribute('aria-label', name);
+ tile.title = name;
+ customize.fadeInImageTile(tile, imageUrl, null);
+
+ const title = document.createElement('div');
+ title.classList.add(customize.CLASSES.COLLECTION_TITLE);
+ title.textContent = name;
+ tile.appendChild(title);
+
+ const tileBackground = document.createElement('div');
+ tileBackground.classList.add(customize.CLASSES.COLLECTION_TILE_BG);
+ tileBackground.appendChild(tile);
+ return tileBackground;
+};
+
+/**
+ * Creates a tile for the customization menu without a title.
+ * @param {string} id The id for the new element.
+ * @param {string} imageUrl The background image url for the new element.
+ * @param {Object} dataset The dataset for the new element.
+ * @param {?Function} onClickInteraction Function for onclick interaction.
+ * @param {?Function} onKeyInteraction Function for onkeydown interaction.
+ */
+customize.createTileWithoutTitle = function(
+ id, imageUrl, dataset, onClickInteraction, onKeyInteraction) {
+ const tile = customize.createTileThumbnail(
+ id, imageUrl, dataset, onClickInteraction, onKeyInteraction);
+ customize.fadeInImageTile(tile, imageUrl, null);
+
+ const tileBackground = document.createElement('div');
+ tileBackground.classList.add(customize.CLASSES.COLLECTION_TILE_BG);
+ tileBackground.appendChild(tile);
+ return tileBackground;
+};
+
+/**
+ * Create a tile thumbnail with image for customization menu.
+ * @param {string} id The id for the new element.
+ * @param {string} imageUrl The background image url for the new element.
+ * @param {Object} dataset The dataset for the new element.
+ * @param {?Function} onClickInteraction Function for onclick interaction.
+ * @param {?Function} onKeyInteraction Function for onkeydown interaction.
+ */
+customize.createTileThumbnail = function(
+ id, imageUrl, dataset, onClickInteraction, onKeyInteraction) {
+ const tile = document.createElement('div');
+ tile.id = id;
+ tile.classList.add(customize.CLASSES.COLLECTION_TILE);
+ tile.style.backgroundImage = 'url(' + imageUrl + ')';
+ for (const key in dataset) {
+ tile.dataset[key] = dataset[key];
+ }
+ tile.tabIndex = -1;
+
+ // Accessibility support for screen readers.
+ tile.setAttribute('role', 'button');
+ tile.setAttribute('aria-pressed', false);
+
+ tile.onclick = onClickInteraction;
+ tile.onkeydown = onKeyInteraction;
+ return tile;
+};
+
+/**
+ * Get the number of tiles in a row according to current window width.
+ * @return {number} the number of tiles per row
+ */
+customize.getTilesWide = function() {
+ // Browser window can only fit two columns. Should match "#bg-sel-menu" width.
+ if ($(customize.IDS.MENU).offsetWidth < 517) {
+ return 2;
+ } else if ($(customize.IDS.MENU).offsetWidth < 356) {
+ // Browser window can only fit one column. Should match @media (max-width:
+ // 356) "#bg-sel-menu" width.
+ return 1;
+ }
+
+ return 3;
+};
+
+/**
+ * @param {number} deltaX Change in the x direction.
+ * @param {number} deltaY Change in the y direction.
+ * @param {Element} current The current tile.
+ */
+customize.richerPicker_getNextTile = function(deltaX, deltaY, current) {
+ const menu = $(customize.IDS.CUSTOMIZATION_MENU);
+ const container = customize.richerPicker_selectedSubmenu.menu;
+
+ const tiles = Array.from(
+ container.getElementsByClassName(customize.CLASSES.COLLECTION_TILE_BG));
+ let nextIndex = tiles.indexOf(current.parentElement);
+ if (deltaX != 0) {
+ nextIndex += deltaX;
+ } else if (deltaY != 0) {
+ const startingTop = current.parentElement.getBoundingClientRect().top;
+ const startingLeft = current.parentElement.getBoundingClientRect().left;
+
+ // Search until a tile in a different row and the same column is found.
+ while (tiles[nextIndex] &&
+ (tiles[nextIndex].getBoundingClientRect().top == startingTop ||
+ tiles[nextIndex].getBoundingClientRect().left != startingLeft)) {
+ nextIndex += deltaY;
+ }
+ }
+ if (tiles[nextIndex]) {
+ return tiles[nextIndex].children[0];
+ }
+ return null;
+};
+
+/**
+ * Get the next tile when the arrow keys are used to navigate the grid.
+ * Returns null if the tile doesn't exist.
+ * @param {number} deltaX Change in the x direction.
+ * @param {number} deltaY Change in the y direction.
+ * @param {Element} currentElem The current tile.
+ */
+customize.getNextTile = function(deltaX, deltaY, currentElem) {
+ if (configData.richerPicker) {
+ return customize.richerPicker_getNextTile(deltaX, deltaY, currentElem);
+ }
+ const current = currentElem.dataset.tileIndex;
+ let idPrefix = 'coll_tile_';
+ if ($(customize.IDS.MENU)
+ .classList.contains(customize.CLASSES.IMAGE_DIALOG)) {
+ idPrefix = 'img_tile_';
+ }
+
+ if (deltaX != 0) {
+ const target = parseInt(current, /*radix=*/ 10) + deltaX;
+ return $(idPrefix + target);
+ } else if (deltaY != 0) {
+ let target = parseInt(current, /*radix=*/ 10);
+ let nextTile = $(idPrefix + target);
+ const startingTop = nextTile.getBoundingClientRect().top;
+ const startingLeft = nextTile.getBoundingClientRect().left;
+
+ // Search until a tile in a different row and the same column is found.
+ while (nextTile &&
+ (nextTile.getBoundingClientRect().top == startingTop ||
+ nextTile.getBoundingClientRect().left != startingLeft)) {
+ target += deltaY;
+ nextTile = $(idPrefix + target);
+ }
+ return nextTile;
+ }
+};
+
+/**
+ * Event handler when a key is pressed on a tile in customization menu.
+ * @param {Event} event The event attributes for the interaction.
+ */
+customize.tileOnKeyDownInteraction = function(event) {
+ const tile = event.currentTarget;
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ event.preventDefault();
+ event.stopPropagation();
+ if (tile.onClickOverride) {
+ tile.onClickOverride(event);
+ return;
+ }
+ tile.onclick(event);
+ } else if (customize.arrowKeys.includes(event.keyCode)) {
+ // Handle arrow key navigation.
+ event.preventDefault();
+
+ let target = null;
+ if (event.keyCode === customize.KEYCODES.LEFT) {
+ target = customize.getNextTile(
+ document.documentElement.classList.contains('rtl') ? 1 : -1, 0,
+ /** @type HTMLElement */ (tile));
+ } else if (event.keyCode === customize.KEYCODES.UP) {
+ target = customize.getNextTile(0, -1, /** @type HTMLElement */ (tile));
+ } else if (event.keyCode === customize.KEYCODES.RIGHT) {
+ target = customize.getNextTile(
+ document.documentElement.classList.contains('rtl') ? -1 : 1, 0,
+ /** @type HTMLElement */ (tile));
+ } else if (event.keyCode === customize.KEYCODES.DOWN) {
+ target = customize.getNextTile(0, 1, /** @type HTMLElement */ (tile));
+ }
+ if (target) {
+ target.focus();
+ } else {
+ tile.focus();
+ }
+ }
+};
+
+/**
+ * Show dialog for selecting a Chrome background.
+ */
+customize.showCollectionSelectionDialog = function() {
+ const tileContainer = configData.richerPicker ?
+ $(customize.IDS.BACKGROUNDS_MENU) :
+ $(customize.IDS.TILES);
+ if (configData.richerPicker && customize.builtTiles) {
+ return;
+ }
+ customize.builtTiles = true;
+ const menu = configData.richerPicker ? $(customize.IDS.CUSTOMIZATION_MENU) :
+ $(customize.IDS.MENU);
+ if (!menu.open) {
+ menu.showModal();
+ }
+
+ // Create dialog header.
+ $(customize.IDS.TITLE).textContent =
+ configData.translatedStrings.selectChromeWallpaper;
+ if (!configData.richerPicker) {
+ menu.classList.add(customize.CLASSES.COLLECTION_DIALOG);
+ menu.classList.remove(customize.CLASSES.IMAGE_DIALOG);
+ }
+
+ const tileOnClickInteraction = function(event) {
+ let tile = event.target;
+ if (tile.classList.contains(customize.CLASSES.COLLECTION_TITLE)) {
+ tile = tile.parentNode;
+ }
+
+ // Load images for selected collection.
+ const imgElement = $('ntp-images-loader');
+ if (imgElement) {
+ imgElement.parentNode.removeChild(imgElement);
+ }
+ const imgScript = document.createElement('script');
+ imgScript.id = 'ntp-images-loader';
+ imgScript.src = 'chrome-search://local-ntp/ntp-background-images.js?' +
+ 'collection_id=' + tile.dataset.id;
+
+ if (configData.richerPicker) {
+ ntpApiHandle.logEvent(customize.LOG_TYPE.NTP_BACKGROUND_OPEN_COLLECTION);
+ } else {
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_CUSTOMIZE_CHROME_BACKGROUND_SELECT_COLLECTION);
+ }
+
+ document.body.appendChild(imgScript);
+
+ imgScript.onload = function() {
+ // Verify that the individual image data was successfully loaded.
+ const imageDataLoaded =
+ (collImg.length > 0 && collImg[0].collectionId == tile.dataset.id);
+
+ // Dependent upon the success of the load, populate the image selection
+ // dialog or close the current dialog.
+ if (imageDataLoaded) {
+ $(customize.IDS.BACKGROUNDS_MENU)
+ .classList.toggle(customize.CLASSES.MENU_SHOWN, false);
+ $(customize.IDS.BACKGROUNDS_IMAGE_MENU)
+ .classList.toggle(customize.CLASSES.MENU_SHOWN, true);
+
+ // In the RP the upload or default tile may be selected.
+ if (!configData.richerPicker) {
+ customize.resetSelectionDialog();
+ }
+ customize.showImageSelectionDialog(
+ tile.dataset.name, tile.dataset.tileIndex);
+ } else {
+ customize.handleError(collImgErrors);
+ }
+ };
+ };
+
+ // Create dialog tiles.
+ for (let i = 0; i < coll.length; ++i) {
+ const id = coll[i].collectionId;
+ const name = coll[i].collectionName;
+ const imageUrl = coll[i].previewImageUrl;
+ const dataset = {'id': id, 'name': name, 'tileIndex': i};
+
+ const tile = customize.createTileWithTitle(
+ 'coll_tile_' + i, imageUrl, name, dataset, tileOnClickInteraction,
+ customize.tileOnKeyDownInteraction);
+ tileContainer.appendChild(tile);
+ }
+
+ // Attach event listeners for upload and default tiles
+ $(customize.IDS.BACKGROUNDS_UPLOAD_ICON).onkeydown =
+ customize.tileOnKeyDownInteraction;
+ $(customize.IDS.BACKGROUNDS_DEFAULT_ICON).onkeydown =
+ customize.tileOnKeyDownInteraction;
+ $(customize.IDS.BACKGROUNDS_UPLOAD_ICON).onClickOverride =
+ $(customize.IDS.BACKGROUNDS_UPLOAD).onkeydown;
+ $(customize.IDS.BACKGROUNDS_DEFAULT_ICON).onClickOverride =
+ $(customize.IDS.BACKGROUNDS_DEFAULT).onkeydown;
+
+ $(customize.IDS.TILES).focus();
+};
+
+/**
+ * Return true if any shortcut option is selected.
+ * Note: Shortcut options are preselected according to current user settings.
+ */
+customize.richerPicker_isShortcutOptionSelected = function() {
+ // Check if the currently selected options are not the preselection.
+ const notPreselectedType = customize.preselectedOptions.shortcutType !==
+ customize.selectedOptions.shortcutType;
+ const notPreselectedHidden =
+ customize.preselectedOptions.shortcutsAreHidden !==
+ customize.selectedOptions.shortcutsAreHidden;
+ return notPreselectedType || notPreselectedHidden;
+};
+
+/**
+ * Apply styling to a selected option in the richer picker (i.e. the selected
+ * background image, shortcut type, and color).
+ * @param {?Element} option The option to apply styling to.
+ */
+customize.richerPicker_applySelectedState = function(option) {
+ if (!option) {
+ return;
+ }
+
+ option.parentElement.classList.toggle(customize.CLASSES.SELECTED, true);
+ // Create and append a blue checkmark to the selected option.
+ const selectedCircle = document.createElement('div');
+ const selectedCheck = document.createElement('div');
+ selectedCircle.classList.add(customize.CLASSES.SELECTED_CIRCLE);
+ selectedCheck.classList.add(customize.CLASSES.SELECTED_CHECK);
+ option.appendChild(selectedCircle);
+ option.appendChild(selectedCheck);
+ option.setAttribute('aria-pressed', true);
+};
+
+/**
+ * Remove styling from a selected option in the richer picker (i.e. the selected
+ * background image, shortcut type, and color).
+ * @param {?Element} option The option to remove styling from.
+ */
+customize.richerPicker_removeSelectedState = function(option) {
+ if (!option) {
+ return;
+ }
+
+ option.parentElement.classList.toggle(customize.CLASSES.SELECTED, false);
+ // Remove all blue checkmarks from the selected option (this includes the
+ // checkmark and the encompassing circle).
+ const select = option.querySelectorAll(
+ '.' + customize.CLASSES.SELECTED_CHECK + ', .' +
+ customize.CLASSES.SELECTED_CIRCLE);
+ select.forEach((element) => {
+ element.remove();
+ });
+ option.setAttribute('aria-pressed', false);
+};
+
+/**
+ * Preview an image as a custom backgrounds.
+ * @param {!Element} tile The tile that was selected.
+ */
+customize.richerPicker_previewImage = function(tile) {
+ if (!configData.richerPicker) {
+ return;
+ }
+ // Set preview images at 720p by replacing the params in the url.
+ const background = $(customize.IDS.CUSTOM_BG);
+ const preview = $(customize.IDS.CUSTOM_BG_PREVIEW);
+ if (tile.id === customize.IDS.BACKGROUNDS_DEFAULT_ICON) {
+ preview.dataset.hasImage = false;
+ preview.style.backgroundImage = '';
+ preview.style.backgroundColor = document.body.style.backgroundColor;
+ } else if (tile.id === customize.IDS.BACKGROUNDS_UPLOAD_ICON) {
+ // No previews for uploaded images.
+ return;
+ } else {
+ preview.dataset.hasImage = true;
+
+ const re = /w\d+\-h\d+/;
+ preview.style.backgroundImage =
+ tile.style.backgroundImage.replace(re, 'w1280-h720');
+ }
+ background.style.opacity = 0;
+ preview.style.opacity = 1;
+ preview.dataset.hasPreview = true;
+
+ ntpApiHandle.onthemechange();
+};
+
+/**
+ * Remove a preview image of a custom backgrounds.
+ */
+customize.richerPicker_unpreviewImage = function() {
+ if (!configData.richerPicker) {
+ return;
+ }
+ const preview = $(customize.IDS.CUSTOM_BG_PREVIEW);
+ if (!preview.dataset || !preview.dataset.hasPreview) {
+ return;
+ }
+
+ preview.style.opacity = 0;
+ preview.style.backgroundImage = '';
+ preview.style.backgroundColor = 'transparent';
+ preview.dataset.hasPreview = false;
+ $(customize.IDS.CUSTOM_BG).style.opacity = 1;
+
+ ntpApiHandle.onthemechange();
+};
+
+/**
+ * Handles background selection. Apply styling to the selected background tile
+ * in the richer picker, preview the background, and enable the done button.
+ * @param {?Element} tile The selected background tile.
+ */
+customize.richerPicker_selectBackgroundTile = function(tile) {
+ if (!tile) {
+ return;
+ }
+
+ $(customize.IDS.REFRESH_TOGGLE).checked = false;
+
+ if (customize.selectedOptions.background &&
+ customize.selectedOptions.background.id == tile.id) {
+ // If the clicked tile is already selected do nothing.
+ return;
+ } else if (customize.selectedOptions.background) {
+ // Deselect any currently selected tile.
+ customize.richerPicker_removeSelectedState(
+ customize.selectedOptions.background);
+ }
+
+ // Remove any existing preview.
+ customize.richerPicker_unpreviewImage();
+
+ customize.selectedOptions.background = tile;
+ customize.selectedOptions.backgroundData = {
+ id: tile.id,
+ url: tile.dataset.url || '',
+ attr1: tile.dataset.attributionLine1 || '',
+ attr2: tile.dataset.attributionLine2 || '',
+ attrUrl: tile.dataset.attributionActionUrl || '',
+ collectionId: '',
+ };
+ customize.richerPicker_applySelectedState(tile);
+
+ // Don't apply a preview for a preselected image, as it's already the
+ // page background.
+ if (customize.preselectedOptions.backgroundsMenuTile !== tile) {
+ customize.richerPicker_previewImage(tile);
+ }
+};
+
+/**
+ * Handles shortcut type selection. Apply styling to a selected shortcut option
+ * and enable the done button.
+ * @param {?Element} shortcutType The shortcut type option's element.
+ */
+customize.richerPicker_selectShortcutType = function(shortcutType) {
+ if (!shortcutType ||
+ customize.selectedOptions.shortcutType === shortcutType) {
+ return; // The option has already been selected.
+ }
+
+ // Clear the previous selection, if any.
+ if (customize.selectedOptions.shortcutType) {
+ customize.richerPicker_removeSelectedState(
+ customize.selectedOptions.shortcutType);
+ }
+ customize.selectedOptions.shortcutType = shortcutType;
+ customize.richerPicker_applySelectedState(shortcutType);
+};
+
+/**
+ * Handles hide shortcuts toggle. Apply/remove styling for the toggle and
+ * enable/disable the done button.
+ * @param {boolean} areHidden True if the shortcuts are hidden, i.e. the toggle
+ * is on.
+ */
+customize.richerPicker_toggleShortcutHide = function(areHidden) {
+ // (De)select the shortcut hide option.
+ $(customize.IDS.SHORTCUTS_HIDE)
+ .classList.toggle(customize.CLASSES.SELECTED, areHidden);
+ $(customize.IDS.SHORTCUTS_HIDE_TOGGLE).checked = areHidden;
+
+ customize.selectedOptions.shortcutsAreHidden = areHidden;
+};
+
+/**
+ * Handles the "refresh daily" toggle.
+ * @param {boolean} toggledOn True if the toggle has been enabled.
+ */
+customize.richerPicker_toggleRefreshDaily = function(toggledOn) {
+ $(customize.IDS.REFRESH_TOGGLE).checked = toggledOn;
+ if (!toggledOn) {
+ customize.richerPicker_selectBackgroundTile(
+ $(customize.IDS.BACKGROUNDS_DEFAULT));
+ return;
+ }
+
+ if (customize.selectedOptions.background) {
+ customize.richerPicker_removeSelectedState(
+ customize.selectedOptions.background);
+ }
+
+ customize.selectedOptions.backgroundData = {
+ id: '',
+ url: '',
+ attr1: '',
+ attr2: '',
+ attrUrl: '',
+ collectionId: customize.currentCollectionId,
+ };
+};
+
+/**
+ * Apply border and checkmark when a tile is selected
+ * @param {!Element} tile The tile to apply styling to.
+ */
+customize.applySelectedState = function(tile) {
+ tile.classList.add(customize.CLASSES.COLLECTION_SELECTED);
+ const selectedBorder = document.createElement('div');
+ const selectedCircle = document.createElement('div');
+ const selectedCheck = document.createElement('div');
+ selectedBorder.classList.add(customize.CLASSES.SELECTED_BORDER);
+ selectedCircle.classList.add(customize.CLASSES.SELECTED_CIRCLE);
+ selectedCheck.classList.add(customize.CLASSES.SELECTED_CHECK);
+ selectedBorder.appendChild(selectedCircle);
+ selectedBorder.appendChild(selectedCheck);
+ tile.appendChild(selectedBorder);
+ tile.dataset.oldLabel = tile.getAttribute('aria-label');
+ tile.setAttribute(
+ 'aria-label',
+ tile.dataset.oldLabel + ' ' + configData.translatedStrings.selectedLabel);
+};
+
+/**
+ * Remove border and checkmark when a tile is un-selected
+ * @param {!Element} tile The tile to remove styling from.
+ */
+customize.removeSelectedState = function(tile) {
+ tile.classList.remove(customize.CLASSES.COLLECTION_SELECTED);
+ tile.removeChild(tile.firstChild);
+ tile.setAttribute('aria-label', tile.dataset.oldLabel);
+};
+
+/**
+ * Show dialog for selecting an image. Image data should previously have been
+ * loaded into collImg via
+ * chrome-search://local-ntp/ntp-background-images.js?collection_id=<collection_id>
+ * @param {string} dialogTitle The title to be displayed at the top of the
+ * dialog.
+ * @param {number} collIndex The index of the collection this image menu belongs
+ * to.
+ */
+customize.showImageSelectionDialog = function(dialogTitle, collIndex) {
+ const firstNTile = customize.ROWS_TO_PRELOAD * customize.getTilesWide();
+ const tileContainer = configData.richerPicker ?
+ $(customize.IDS.BACKGROUNDS_IMAGE_MENU) :
+ $(customize.IDS.TILES);
+ const menu = configData.richerPicker ? $(customize.IDS.CUSTOMIZATION_MENU) :
+ $(customize.IDS.MENU);
+
+ if (configData.richerPicker) {
+ menu.classList.toggle(customize.CLASSES.ON_IMAGE_MENU, true);
+ customize.richerPicker_showSubmenu(
+ $(customize.IDS.BACKGROUNDS_BUTTON), tileContainer, dialogTitle);
+ // Save the current image menu. Used to restore to when the Background
+ // submenu is reopened.
+ customize.richerPicker_openBackgroundSubmenu.menuId =
+ customize.IDS.BACKGROUNDS_IMAGE_MENU;
+ customize.richerPicker_openBackgroundSubmenu.title = dialogTitle;
+ } else {
+ $(customize.IDS.TITLE).textContent = dialogTitle;
+ menu.classList.remove(customize.CLASSES.COLLECTION_DIALOG);
+ menu.classList.add(customize.CLASSES.IMAGE_DIALOG);
+ }
+
+ const tileInteraction = function(tile) {
+ if (customize.selectedOptions.background && !configData.richerPicker) {
+ customize.removeSelectedState(customize.selectedOptions.background);
+ if (customize.selectedOptions.background.id === tile.id) {
+ customize.unselectTile();
+ return;
+ }
+ }
+
+ if (configData.richerPicker) {
+ if (!customize.selectedOptions.backgroundData ||
+ customize.selectedOptions.backgroundData.id !== tile.id) {
+ ntpApiHandle.logEvent(customize.LOG_TYPE.NTP_BACKGROUND_SELECT_IMAGE);
+ }
+ customize.richerPicker_selectBackgroundTile(tile);
+ } else {
+ customize.applySelectedState(tile);
+ customize.selectedOptions.background = tile;
+ }
+
+ $(customize.IDS.DONE).tabIndex = 0;
+
+ // Turn toggle off when an image is selected.
+ $(customize.IDS.DONE).disabled = false;
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_CUSTOMIZE_CHROME_BACKGROUND_SELECT_IMAGE);
+ };
+
+ const tileOnClickInteraction = function(event) {
+ const clickCount = event.detail;
+ // Control + option + space will fire the onclick event with 0 clickCount.
+ if (clickCount <= 1) {
+ tileInteraction(event.currentTarget);
+ } else if (
+ clickCount === 2 &&
+ customize.selectedOptions.background === event.currentTarget) {
+ customize.setBackground(
+ event.currentTarget.dataset.url,
+ event.currentTarget.dataset.attributionLine1,
+ event.currentTarget.dataset.attributionLine2,
+ event.currentTarget.dataset.attributionActionUrl,
+ /*collection_id=*/ '');
+ }
+ };
+
+ const preLoadTiles = [];
+ const postLoadTiles = [];
+
+ for (let i = 0; i < collImg.length; ++i) {
+ const dataset = {};
+
+ dataset.attributionLine1 =
+ (collImg[i].attributions[0] !== undefined ? collImg[i].attributions[0] :
+ '');
+ dataset.attributionLine2 =
+ (collImg[i].attributions[1] !== undefined ? collImg[i].attributions[1] :
+ '');
+ dataset.attributionActionUrl = collImg[i].attributionActionUrl;
+ dataset.url = collImg[i].imageUrl;
+ dataset.tileIndex = i;
+
+ let tileId = 'img_tile_' + i;
+ if (configData.richerPicker) {
+ tileId = 'coll_' + collIndex + '_' + tileId;
+ }
+ const tile = customize.createTileThumbnail(
+ tileId, collImg[i].imageUrl, dataset, tileOnClickInteraction,
+ customize.tileOnKeyDownInteraction);
+
+ tile.setAttribute('aria-label', collImg[i].attributions[0]);
+ tile.title = collImg[i].attributions[0];
+
+ // Load the first |ROWS_TO_PRELOAD| rows of tiles.
+ if (i < firstNTile) {
+ preLoadTiles.push(tile);
+ } else {
+ postLoadTiles.push(tile);
+ }
+
+ const tileBackground = document.createElement('div');
+ tileBackground.classList.add(customize.CLASSES.COLLECTION_TILE_BG);
+ tileBackground.appendChild(tile);
+ tileContainer.appendChild(tileBackground);
+ }
+ let tileGetsLoaded = 0;
+ for (const tile of preLoadTiles) {
+ customize.loadTile(tile, collImg, () => {
+ // After the preloaded tiles finish loading, the rest of the tiles start
+ // loading.
+ if (++tileGetsLoaded === preLoadTiles.length) {
+ postLoadTiles.forEach(
+ (tile) => customize.loadTile(tile, collImg, null));
+ }
+ });
+ }
+
+ customize.currentCollectionId = collImg[0].collectionId;
+ $(customize.IDS.REFRESH_TOGGLE).checked = false;
+ // If an image tile was previously selected re-select it now.
+ if (customize.selectedOptions.backgroundData) {
+ const selected = $(customize.selectedOptions.backgroundData.id);
+ if (selected) {
+ customize.richerPicker_selectBackgroundTile(selected);
+ } else if (
+ customize.selectedOptions.backgroundData.collectionId ===
+ customize.currentCollectionId) {
+ $(customize.IDS.REFRESH_TOGGLE).checked = true;
+ }
+ } else {
+ customize.richerPicker_preselectBackgroundOption();
+ }
+ $(customize.IDS.REFRESH_DAILY_WRAPPER).hidden = false;
+
+ if (configData.richerPicker) {
+ $(customize.IDS.BACKGROUNDS_IMAGE_MENU).focus();
+ } else {
+ $(customize.IDS.TILES).focus();
+ }
+};
+
+/**
+ * Add background image src to the tile and add animation for the tile once it
+ * successfully loaded.
+ * @param {!Object} tile the tile that needs to be loaded.
+ * @param {!Object} imageData the source imageData.
+ * @param {?Function} countLoad If not null, called after the tile finishes
+ * loading.
+ */
+customize.loadTile = function(tile, imageData, countLoad) {
+ tile.style.backgroundImage =
+ 'url(' + imageData[tile.dataset.tileIndex].thumbnailImageUrl + ')';
+ customize.fadeInImageTile(
+ tile, imageData[tile.dataset.tileIndex].thumbnailImageUrl, countLoad);
+};
+
+/**
+ * Fade in effect for both collection and image tile. Once the image
+ * successfully loads, we can assume the background image with the same source
+ * has also loaded. Then, we set opacity for the tile to start the animation.
+ * @param {!Object} tile The tile to add the fade in animation to.
+ * @param {string} imageUrl the image url for the tile
+ * @param {?Function} countLoad If not null, called after the tile finishes
+ * loading.
+ */
+customize.fadeInImageTile = function(tile, imageUrl, countLoad) {
+ const image = new Image();
+ image.onload = () => {
+ tile.style.opacity = '1';
+ if (countLoad) {
+ countLoad();
+ }
+ };
+ image.src = imageUrl;
+};
+
+/**
+ * Load the NTPBackgroundCollections script. It'll create a global
+ * variable name "coll" which is a dict of background collections data.
+ */
+customize.loadChromeBackgrounds = function() {
+ const collElement = $('ntp-collection-loader');
+ if (collElement) {
+ collElement.parentNode.removeChild(collElement);
+ }
+ const collScript = document.createElement('script');
+ collScript.id = 'ntp-collection-loader';
+ collScript.src = 'chrome-search://local-ntp/ntp-background-collections.js?' +
+ 'collection_type=background';
+ collScript.onload = function() {
+ if (configData.richerPicker) {
+ customize.showCollectionSelectionDialog();
+ }
+ };
+ document.body.appendChild(collScript);
+};
+
+/**
+ * Close dialog when an image is selected via the file picker.
+ */
+customize.closeCustomizationDialog = function() {
+ if (configData.richerPicker) {
+ $(customize.IDS.CUSTOMIZATION_MENU).close();
+ } else {
+ $(customize.IDS.EDIT_BG_DIALOG).close();
+ }
+};
+
+/**
+ * Get the next visible option. There are times when various combinations of
+ * options are hidden.
+ * @param {number} current_index Index of the option the key press occurred on.
+ * @param {number} deltaY Direction to search in, -1 for up, 1 for down.
+ */
+customize.getNextOption = function(current_index, deltaY) {
+ // Create array corresponding to the menu. Important that this is in the same
+ // order as the MENU_ENTRIES enum, so we can index into it.
+ const entries = [];
+ entries.push($(customize.IDS.DEFAULT_WALLPAPERS));
+ entries.push($(customize.IDS.UPLOAD_IMAGE));
+ entries.push($(customize.IDS.CUSTOM_LINKS_RESTORE_DEFAULT));
+ entries.push($(customize.IDS.RESTORE_DEFAULT));
+
+ let idx = current_index;
+ do {
+ idx = idx + deltaY;
+ if (idx === -1) {
+ idx = 3;
+ }
+ if (idx === 4) {
+ idx = 0;
+ }
+ } while (
+ idx !== current_index &&
+ (entries[idx].hidden ||
+ entries[idx].classList.contains(customize.CLASSES.OPTION_DISABLED)));
+ return entries[idx];
+};
+
+/**
+ * Hide custom background options based on the network state
+ * @param {boolean} online The current state of the network
+ */
+customize.networkStateChanged = function(online) {
+ $(customize.IDS.DEFAULT_WALLPAPERS).hidden = !online;
+};
+
+/**
+ * Open the customization menu and set it to the default submenu (Background).
+ */
+customize.richerPicker_openCustomizationMenu = function() {
+ ntpApiHandle.logEvent(customize.LOG_TYPE.NTP_CUSTOMIZATION_MENU_OPENED);
+ customize.richerPicker_showSubmenu(
+ $(customize.IDS.BACKGROUNDS_BUTTON), $(customize.IDS.BACKGROUNDS_MENU));
+
+ customize.richerPicker_preselectShortcutOptions();
+ customize.richerPicker_preselectBackgroundOption();
+ customize.loadChromeBackgrounds();
+ customize.loadColorsMenu();
+ if (!$(customize.IDS.CUSTOMIZATION_MENU).open) {
+ $(customize.IDS.CUSTOMIZATION_MENU).showModal();
+ }
+};
+
+/**
+ * Reset the selected options in the customization menu.
+ */
+customize.richerPicker_resetSelectedOptions = function() {
+ // Reset background selection.
+ customize.richerPicker_removeSelectedState(
+ customize.selectedOptions.background);
+ customize.selectedOptions.background = null;
+ customize.selectedOptions.backgroundData = null;
+
+ // Reset color selection.
+ customize.richerPicker_removeSelectedState(customize.selectedOptions.color);
+ customize.selectedOptions.color = null;
+ customize.preselectedOptions.colorsMenuTile = null;
+
+ customize.richerPicker_preselectShortcutOptions();
+};
+
+/**
+ * Preselect the shortcut type and visibility to reflect the current state on
+ * the page.
+ */
+customize.richerPicker_preselectShortcutOptions = function() {
+ const shortcutType = chrome.embeddedSearch.newTabPage.isUsingMostVisited ?
+ $(customize.IDS.SHORTCUTS_OPTION_MOST_VISITED) :
+ $(customize.IDS.SHORTCUTS_OPTION_CUSTOM_LINKS);
+ const shortcutsAreHidden =
+ !chrome.embeddedSearch.newTabPage.areShortcutsVisible;
+ customize.preselectedOptions.shortcutType = shortcutType;
+ customize.preselectedOptions.shortcutsAreHidden = shortcutsAreHidden;
+ customize.richerPicker_selectShortcutType(shortcutType);
+ customize.richerPicker_toggleShortcutHide(shortcutsAreHidden);
+};
+
+/**
+ * Preselect the background tile that corresponds to the current page
+ * background.
+ */
+customize.richerPicker_preselectBackgroundOption = function() {
+ if (!configData.richerPicker) {
+ return;
+ }
+
+ customize.preselectedOptions.backgroundsMenuTile = null;
+
+ const themeInfo = ntpApiHandle.themeBackgroundInfo;
+ if (!themeInfo.customBackgroundConfigured) {
+ // Default.
+ customize.preselectedOptions.backgroundsMenuTile =
+ $(customize.IDS.BACKGROUNDS_DEFAULT_ICON);
+ } else if (themeInfo.imageUrl.includes(
+ 'chrome-search://local-ntp/background.jpg')) {
+ // Local image.
+ customize.preselectedOptions.backgroundsMenuTile =
+ $(customize.IDS.BACKGROUNDS_UPLOAD_ICON);
+ } else if (
+ themeInfo.collectionId !== '' &&
+ customize.currentCollectionId == themeInfo.collectionId) {
+ // Daily refresh.
+ $(customize.IDS.REFRESH_TOGGLE).checked = true;
+ } else if (!customize.selectedOptions.backgroundData) {
+ // Image tile. Only if another background hasn't already been selected.
+ customize.preselectedOptions.backgroundsMenuTile =
+ document.querySelector('[data-url="' + themeInfo.imageUrl + '"]');
+ }
+
+ customize.richerPicker_selectBackgroundTile(
+ customize.preselectedOptions.backgroundsMenuTile);
+ customize.selectedOptions.backgroundData = null;
+};
+
+/**
+ * Resets the customization menu.
+ */
+customize.richerPicker_resetCustomizationMenu = function() {
+ customize.richerPicker_resetSelectedOptions();
+ customize.richerPicker_resetImageMenu();
+ customize.richerPicker_hideOpenSubmenu();
+ customize.resetColorsMenu();
+};
+
+/**
+ * Close and reset the customization menu.
+ */
+customize.richerPicker_closeCustomizationMenu = function() {
+ $(customize.IDS.BACKGROUNDS_MENU).scrollTop = 0;
+ $(customize.IDS.CUSTOMIZATION_MENU).close();
+ customize.richerPicker_resetCustomizationMenu();
+
+ customize.richerPicker_unpreviewImage();
+};
+
+/**
+ * Cancel customization, revert any changes, and close the richer picker.
+ */
+customize.richerPicker_cancelCustomization = function() {
+ ntpApiHandle.logEvent(customize.LOG_TYPE.NTP_CUSTOMIZATION_MENU_CANCEL);
+
+ if (customize.isColorOptionSelected()) {
+ customize.cancelColor();
+ }
+
+ customize.richerPicker_closeCustomizationMenu();
+};
+
+/**
+ * Apply the currently selected customization options and close the richer
+ * picker.
+ */
+customize.richerPicker_applyCustomization = function() {
+ if (customize.isBackgroundOptionSelected()) {
+ customize.setBackground(
+ customize.selectedOptions.backgroundData.url,
+ customize.selectedOptions.backgroundData.attr1,
+ customize.selectedOptions.backgroundData.attr2,
+ customize.selectedOptions.backgroundData.attrUrl,
+ customize.selectedOptions.backgroundData.collectionId);
+ }
+ if (customize.richerPicker_isShortcutOptionSelected()) {
+ customize.richerPicker_setShortcutOptions();
+ }
+ if (customize.isColorOptionSelected()) {
+ customize.confirmColor();
+ }
+ customize.richerPicker_closeCustomizationMenu();
+};
+
+/**
+ * Initialize the settings menu, custom backgrounds dialogs, and custom
+ * links menu items. Set the text and event handlers for the various
+ * elements.
+ * @param {!Function} showErrorNotification Called when the error notification
+ * should be displayed.
+ * @param {!Function} hideCustomLinkNotification Called when the custom link
+ * notification should be hidden.
+ */
+customize.init = function(showErrorNotification, hideCustomLinkNotification) {
+ ntpApiHandle = window.chrome.embeddedSearch.newTabPage;
+ const editDialog = $(customize.IDS.EDIT_BG_DIALOG);
+ const menu = $(customize.IDS.MENU);
+
+ $(customize.IDS.OPTIONS_TITLE).textContent =
+ configData.translatedStrings.customizeThisPage;
+
+ if (configData.richerPicker) {
+ // Store the main menu title so it can be restored if needed.
+ customize.richerPicker_defaultTitle =
+ $(customize.IDS.MENU_TITLE).textContent;
+ }
+
+ $(customize.IDS.EDIT_BG)
+ .setAttribute(
+ 'aria-label', configData.translatedStrings.customizeThisPage);
+
+ $(customize.IDS.EDIT_BG)
+ .setAttribute('title', configData.translatedStrings.customizeThisPage);
+
+ // Selecting a local image for the background should close the picker.
+ if (configData.richerPicker) {
+ ntpApiHandle.onlocalbackgroundselected = () => {
+ customize.selectedOptions.backgroundData = null;
+ customize.richerPicker_applyCustomization();
+ };
+ }
+
+ // Edit gear icon interaction events.
+ const editBackgroundInteraction = function() {
+ if (configData.richerPicker) {
+ customize.richerPicker_openCustomizationMenu();
+ } else {
+ editDialog.showModal();
+ }
+ };
+ $(customize.IDS.EDIT_BG).onclick = function(event) {
+ editDialog.classList.add(customize.CLASSES.MOUSE_NAV);
+ editBackgroundInteraction();
+ };
+
+ $(customize.IDS.MENU_CANCEL).onclick = function(event) {
+ customize.richerPicker_cancelCustomization();
+ };
+
+
+ // Find the first menu option that is not hidden or disabled.
+ const findFirstMenuOption = () => {
+ const editMenu = $(customize.IDS.EDIT_BG_MENU);
+ for (let i = 1; i < editMenu.children.length; i++) {
+ const option = editMenu.children[i];
+ if (option.classList.contains(customize.CLASSES.OPTION) &&
+ !option.hidden &&
+ !option.classList.contains(customize.CLASSES.OPTION_DISABLED)) {
+ option.focus();
+ return;
+ }
+ }
+ };
+
+ $(customize.IDS.EDIT_BG).onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ // no default behavior for ENTER
+ event.preventDefault();
+ editDialog.classList.remove(customize.CLASSES.MOUSE_NAV);
+ editBackgroundInteraction();
+ findFirstMenuOption();
+ }
+ };
+
+ // Interactions to close the customization option dialog.
+ const editDialogInteraction = function() {
+ editDialog.close();
+ };
+ editDialog.onclick = function(event) {
+ editDialog.classList.add(customize.CLASSES.MOUSE_NAV);
+ if (event.target === editDialog) {
+ editDialogInteraction();
+ }
+ };
+ editDialog.onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ESC) {
+ editDialogInteraction();
+ } else if (
+ editDialog.classList.contains(customize.CLASSES.MOUSE_NAV) &&
+ (event.keyCode === customize.KEYCODES.TAB ||
+ event.keyCode === customize.KEYCODES.UP ||
+ event.keyCode === customize.KEYCODES.DOWN)) {
+ // When using tab in mouse navigation mode, select the first option
+ // available.
+ event.preventDefault();
+ findFirstMenuOption();
+ editDialog.classList.remove(customize.CLASSES.MOUSE_NAV);
+ } else if (event.keyCode === customize.KEYCODES.TAB) {
+ // If keyboard navigation is attempted, remove mouse-only mode.
+ editDialog.classList.remove(customize.CLASSES.MOUSE_NAV);
+ } else if (customize.arrowKeys.includes(event.keyCode)) {
+ event.preventDefault();
+ editDialog.classList.remove(customize.CLASSES.MOUSE_NAV);
+ }
+ };
+
+ customize.initCustomLinksItems(hideCustomLinkNotification);
+ customize.initCustomBackgrounds(showErrorNotification);
+};
+
+/**
+ * Initialize custom link items in the settings menu dialog. Set the text
+ * and event handlers for the various elements.
+ * @param {!Function} hideCustomLinkNotification Called when the custom link
+ * notification should be hidden.
+ */
+customize.initCustomLinksItems = function(hideCustomLinkNotification) {
+ customize.hideCustomLinkNotification = hideCustomLinkNotification;
+
+ const editDialog = $(customize.IDS.EDIT_BG_DIALOG);
+ const menu = $(customize.IDS.MENU);
+
+ $(customize.IDS.CUSTOM_LINKS_RESTORE_DEFAULT_TEXT).textContent =
+ configData.translatedStrings.restoreDefaultLinks;
+
+ // Interactions with the "Restore default shortcuts" option.
+ const customLinksRestoreDefaultInteraction = function() {
+ editDialog.close();
+ customize.hideCustomLinkNotification();
+ window.chrome.embeddedSearch.newTabPage.resetCustomLinks();
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_CUSTOMIZE_RESTORE_SHORTCUTS_CLICKED);
+ };
+ $(customize.IDS.CUSTOM_LINKS_RESTORE_DEFAULT).onclick = () => {
+ if (!$(customize.IDS.CUSTOM_LINKS_RESTORE_DEFAULT)
+ .classList.contains(customize.CLASSES.OPTION_DISABLED)) {
+ customLinksRestoreDefaultInteraction();
+ }
+ };
+ $(customize.IDS.CUSTOM_LINKS_RESTORE_DEFAULT).onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER) {
+ customLinksRestoreDefaultInteraction();
+ } else if (event.keyCode === customize.KEYCODES.UP) {
+ // Handle arrow key navigation.
+ event.preventDefault();
+ customize
+ .getNextOption(
+ customize.MENU_ENTRIES.CUSTOM_LINKS_RESTORE_DEFAULT, -1)
+ .focus();
+ } else if (event.keyCode === customize.KEYCODES.DOWN) {
+ event.preventDefault();
+ customize
+ .getNextOption(customize.MENU_ENTRIES.CUSTOM_LINKS_RESTORE_DEFAULT, 1)
+ .focus();
+ }
+ };
+};
+
+/**
+ * Initialize the settings menu and custom backgrounds dialogs. Set the
+ * text and event handlers for the various elements.
+ * @param {!Function} showErrorNotification Called when the error notification
+ * should be displayed.
+ */
+customize.initCustomBackgrounds = function(showErrorNotification) {
+ customize.showErrorNotification = showErrorNotification;
+
+ const editDialog = $(customize.IDS.EDIT_BG_DIALOG);
+ const menu = $(customize.IDS.MENU);
+
+ $(customize.IDS.DEFAULT_WALLPAPERS_TEXT).textContent =
+ configData.translatedStrings.defaultWallpapers;
+ $(customize.IDS.UPLOAD_IMAGE_TEXT).textContent =
+ configData.translatedStrings.uploadImage;
+ $(customize.IDS.RESTORE_DEFAULT_TEXT).textContent =
+ configData.translatedStrings.restoreDefaultBackground;
+ $(customize.IDS.DONE).textContent =
+ configData.translatedStrings.selectionDone;
+ $(customize.IDS.CANCEL).textContent =
+ configData.translatedStrings.selectionCancel;
+
+ window.addEventListener('online', function(event) {
+ customize.networkStateChanged(true);
+ });
+
+ window.addEventListener('offline', function(event) {
+ customize.networkStateChanged(false);
+ });
+
+ if (!window.navigator.onLine) {
+ customize.networkStateChanged(false);
+ }
+
+ $(customize.IDS.BACK_CIRCLE)
+ .setAttribute('aria-label', configData.translatedStrings.backLabel);
+ $(customize.IDS.CANCEL)
+ .setAttribute('aria-label', configData.translatedStrings.selectionCancel);
+ $(customize.IDS.DONE)
+ .setAttribute('aria-label', configData.translatedStrings.selectionDone);
+
+ $(customize.IDS.DONE).disabled = true;
+
+ // Interactions with the "Upload an image" option.
+ const uploadImageInteraction = function() {
+ window.chrome.embeddedSearch.newTabPage.selectLocalBackgroundImage();
+ if (configData.richerPicker) {
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_BACKGROUND_UPLOAD_FROM_DEVICE);
+ } else {
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_CUSTOMIZE_LOCAL_IMAGE_CLICKED);
+ }
+ };
+
+ $(customize.IDS.UPLOAD_IMAGE).onclick = (event) => {
+ if (!$(customize.IDS.UPLOAD_IMAGE)
+ .classList.contains(customize.CLASSES.OPTION_DISABLED)) {
+ uploadImageInteraction();
+ }
+ };
+ $(customize.IDS.UPLOAD_IMAGE).onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER) {
+ uploadImageInteraction();
+ }
+
+ // Handle arrow key navigation.
+ if (event.keyCode === customize.KEYCODES.UP) {
+ event.preventDefault();
+ customize.getNextOption(customize.MENU_ENTRIES.UPLOAD_IMAGE, -1).focus();
+ }
+ if (event.keyCode === customize.KEYCODES.DOWN) {
+ event.preventDefault();
+ customize.getNextOption(customize.MENU_ENTRIES.UPLOAD_IMAGE, 1).focus();
+ }
+ };
+
+ // Interactions with the "Restore default background" option.
+ const restoreDefaultInteraction = function() {
+ editDialog.close();
+ customize.clearAttribution();
+ window.chrome.embeddedSearch.newTabPage.setBackgroundURL('');
+ };
+ $(customize.IDS.RESTORE_DEFAULT).onclick = (event) => {
+ if (!$(customize.IDS.RESTORE_DEFAULT)
+ .classList.contains(customize.CLASSES.OPTION_DISABLED)) {
+ restoreDefaultInteraction();
+ }
+ };
+ $(customize.IDS.RESTORE_DEFAULT).onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER) {
+ restoreDefaultInteraction();
+ }
+
+ // Handle arrow key navigation.
+ if (event.keyCode === customize.KEYCODES.UP) {
+ event.preventDefault();
+ customize.getNextOption(customize.MENU_ENTRIES.RESTORE_DEFAULT, -1)
+ .focus();
+ }
+ if (event.keyCode === customize.KEYCODES.DOWN) {
+ event.preventDefault();
+ customize.getNextOption(customize.MENU_ENTRIES.RESTORE_DEFAULT, 1)
+ .focus();
+ }
+ };
+
+ // Interactions with the "Chrome backgrounds" option.
+ const defaultWallpapersInteraction = function(event) {
+ customize.loadChromeBackgrounds();
+ $('ntp-collection-loader').onload = function() {
+ editDialog.close();
+ if (typeof coll != 'undefined' && coll.length > 0) {
+ customize.showCollectionSelectionDialog();
+ } else {
+ customize.handleError(collErrors);
+ }
+ };
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_CUSTOMIZE_CHROME_BACKGROUNDS_CLICKED);
+ };
+ $(customize.IDS.DEFAULT_WALLPAPERS).onclick = function(event) {
+ $(customize.IDS.MENU).classList.add(customize.CLASSES.MOUSE_NAV);
+ defaultWallpapersInteraction(event);
+ };
+ $(customize.IDS.DEFAULT_WALLPAPERS).onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER) {
+ $(customize.IDS.MENU).classList.remove(customize.CLASSES.MOUSE_NAV);
+ defaultWallpapersInteraction(event);
+ }
+
+ // Handle arrow key navigation.
+ if (event.keyCode === customize.KEYCODES.UP) {
+ event.preventDefault();
+ customize.getNextOption(customize.MENU_ENTRIES.CHROME_BACKGROUNDS, -1)
+ .focus();
+ }
+ if (event.keyCode === customize.KEYCODES.DOWN) {
+ event.preventDefault();
+ customize.getNextOption(customize.MENU_ENTRIES.CHROME_BACKGROUNDS, 1)
+ .focus();
+ }
+ };
+
+ // Escape and Backspace handling for the background picker dialog.
+ menu.onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.SPACE) {
+ $(customize.IDS.TILES).scrollTop += $(customize.IDS.TILES).offsetHeight;
+ event.stopPropagation();
+ event.preventDefault();
+ }
+ if (event.keyCode === customize.KEYCODES.ESC ||
+ event.keyCode === customize.KEYCODES.BACKSPACE) {
+ event.preventDefault();
+ event.stopPropagation();
+ if (menu.classList.contains(customize.CLASSES.COLLECTION_DIALOG)) {
+ menu.close();
+ customize.resetSelectionDialog();
+ } else {
+ customize.resetSelectionDialog();
+ customize.showCollectionSelectionDialog();
+ }
+ }
+
+ // If keyboard navigation is attempted, remove mouse-only mode.
+ if (event.keyCode === customize.KEYCODES.TAB ||
+ event.keyCode === customize.KEYCODES.LEFT ||
+ event.keyCode === customize.KEYCODES.UP ||
+ event.keyCode === customize.KEYCODES.RIGHT ||
+ event.keyCode === customize.KEYCODES.DOWN) {
+ menu.classList.remove(customize.CLASSES.MOUSE_NAV);
+ }
+ };
+
+ // Interactions with the back arrow on the image selection dialog.
+ const backInteraction = function(event) {
+ if (configData.richerPicker) {
+ ntpApiHandle.logEvent(customize.LOG_TYPE.NTP_BACKGROUND_BACK_CLICK);
+ customize.richerPicker_resetImageMenu();
+ }
+ customize.resetSelectionDialog();
+ customize.showCollectionSelectionDialog();
+ };
+ $(customize.IDS.BACK_CIRCLE).onclick = backInteraction;
+ $(customize.IDS.MENU_BACK_CIRCLE).onclick = backInteraction;
+ $(customize.IDS.BACK_CIRCLE).onkeyup = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ backInteraction(event);
+ }
+ };
+ $(customize.IDS.MENU_BACK_CIRCLE).onkeyup = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ backInteraction(event);
+ }
+ };
+ // Pressing Spacebar on the back arrow shouldn't scroll the dialog.
+ $(customize.IDS.BACK_CIRCLE).onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.SPACE) {
+ event.stopPropagation();
+ }
+ };
+
+ // Interactions with the cancel button on the background picker dialog.
+ $(customize.IDS.CANCEL).onclick = function(event) {
+ customize.closeCollectionDialog(menu);
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_CUSTOMIZE_CHROME_BACKGROUND_CANCEL);
+ };
+ $(customize.IDS.CANCEL).onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ customize.closeCollectionDialog(menu);
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_CUSTOMIZE_CHROME_BACKGROUND_CANCEL);
+ }
+ };
+
+ // Interactions with the done button on the background picker dialog.
+ const doneInteraction = function(event) {
+ const done = configData.richerPicker ? $(customize.IDS.MENU_DONE) :
+ $(customize.IDS.DONE);
+ if (configData.richerPicker) {
+ ntpApiHandle.logEvent(customize.LOG_TYPE.NTP_CUSTOMIZATION_MENU_DONE);
+ customize.richerPicker_applyCustomization();
+ } else if (customize.selectedOptions.background) {
+ // Also closes the customization menu.
+ customize.setBackground(
+ customize.selectedOptions.background.dataset.url,
+ customize.selectedOptions.background.dataset.attributionLine1,
+ customize.selectedOptions.background.dataset.attributionLine2,
+ customize.selectedOptions.background.dataset.attributionActionUrl,
+ '');
+ }
+ };
+ $(customize.IDS.DONE).onclick = doneInteraction;
+ $(customize.IDS.MENU_DONE).onclick = doneInteraction;
+ $(customize.IDS.DONE).onkeyup = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER) {
+ doneInteraction(event);
+ }
+ };
+
+ // On any arrow key event in the tiles area, focus the first tile.
+ $(customize.IDS.TILES).onkeydown = function(event) {
+ if (document.activeElement === $(customize.IDS.TILES) &&
+ customize.arrowKeys.includes(event.keyCode)) {
+ event.preventDefault();
+ if ($(customize.IDS.MENU)
+ .classList.contains(customize.CLASSES.COLLECTION_DIALOG)) {
+ $('coll_tile_0').focus();
+ } else {
+ document.querySelector('[id$="img_tile_0"]').focus();
+ }
+ }
+ };
+
+ $(customize.IDS.BACKGROUNDS_MENU).onkeydown = function(event) {
+ if (document.activeElement === $(customize.IDS.BACKGROUNDS_MENU) &&
+ customize.arrowKeys.includes(event.keyCode)) {
+ $(customize.IDS.BACKGROUNDS_UPLOAD_ICON).focus();
+ }
+ };
+
+ $(customize.IDS.BACKGROUNDS_IMAGE_MENU).onkeydown = function(event) {
+ if (document.activeElement === $(customize.IDS.BACKGROUNDS_IMAGE_MENU) &&
+ customize.arrowKeys.includes(event.keyCode)) {
+ document.querySelector('[id$="img_tile_0"]').focus();
+ }
+ };
+
+ $(customize.IDS.BACKGROUNDS_UPLOAD).onclick = uploadImageInteraction;
+ $(customize.IDS.BACKGROUNDS_UPLOAD).onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ uploadImageInteraction();
+ }
+ };
+
+ $(customize.IDS.BACKGROUNDS_DEFAULT).onclick = function(event) {
+ const tile = $(customize.IDS.BACKGROUNDS_DEFAULT_ICON);
+ tile.dataset.url = '';
+ tile.dataset.attributionLine1 = '';
+ tile.dataset.attributionLine2 = '';
+ tile.dataset.attributionActionUrl = '';
+ if (!$(customize.IDS.BACKGROUNDS_DEFAULT)
+ .classList.contains(customize.CLASSES.SELECTED)) {
+ ntpApiHandle.logEvent(customize.LOG_TYPE.NTP_BACKGROUND_DEFAULT_SELECTED);
+ customize.richerPicker_selectBackgroundTile(tile);
+ }
+ };
+ $(customize.IDS.BACKGROUNDS_DEFAULT).onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ $(customize.IDS.BACKGROUNDS_DEFAULT).onclick(event);
+ }
+ };
+
+ const richerPicker = $(customize.IDS.CUSTOMIZATION_MENU);
+ richerPicker.onclick = function(event) {
+ richerPicker.classList.add(customize.CLASSES.MOUSE_NAV);
+ };
+ richerPicker.onkeydown = function(event) {
+ richerPicker.classList.remove(customize.CLASSES.MOUSE_NAV);
+
+ if (event.keyCode === customize.KEYCODES.BACKSPACE &&
+ customize.richerPicker_selectedSubmenu.menu.id ===
+ customize.IDS.BACKGROUNDS_IMAGE_MENU) {
+ backInteraction(event);
+ } else if (
+ event.keyCode === customize.KEYCODES.ESC ||
+ event.keyCode === customize.KEYCODES.BACKSPACE) {
+ customize.richerPicker_cancelCustomization();
+ }
+ };
+
+ const richerPickerOpenBackgrounds = function() {
+ // Open the previously open Background submenu, if applicable.
+ customize.richerPicker_showSubmenu(
+ $(customize.IDS.BACKGROUNDS_BUTTON),
+ $(customize.richerPicker_openBackgroundSubmenu.menuId),
+ customize.richerPicker_openBackgroundSubmenu.title);
+ };
+
+ $(customize.IDS.BACKGROUNDS_BUTTON).onclick = richerPickerOpenBackgrounds;
+ $(customize.IDS.BACKGROUNDS_BUTTON).onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ richerPickerOpenBackgrounds();
+ }
+ };
+
+ const clOption = $(customize.IDS.SHORTCUTS_OPTION_CUSTOM_LINKS);
+ const mvOption = $(customize.IDS.SHORTCUTS_OPTION_MOST_VISITED);
+ const hideToggle = $(customize.IDS.SHORTCUTS_HIDE_TOGGLE);
+ $(customize.IDS.SHORTCUTS_MENU).onkeydown = function(event) {
+ if (customize.arrowKeys.includes(event.keyCode)) {
+ clOption.focus();
+ }
+ };
+
+ clOption.onclick = function() {
+ if (customize.selectedOptions.shortcutType !== clOption) {
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_CUSTOMIZE_SHORTCUT_CUSTOM_LINKS_CLICKED);
+ }
+ customize.richerPicker_selectShortcutType(clOption);
+ };
+ clOption.onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ clOption.click();
+ } else if (customize.arrowKeys.includes(event.keyCode)) {
+ // Handle arrow key navigation.
+ event.preventDefault();
+ event.stopPropagation();
+ if (event.keyCode === customize.KEYCODES.RIGHT) {
+ mvOption.focus();
+ } else if (event.keyCode === customize.KEYCODES.DOWN) {
+ hideToggle.focus();
+ }
+ }
+ };
+
+ mvOption.onclick = function() {
+ if (customize.selectedOptions.shortcutType !== mvOption) {
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_CUSTOMIZE_SHORTCUT_MOST_VISITED_CLICKED);
+ }
+ customize.richerPicker_selectShortcutType(mvOption);
+ };
+ mvOption.onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ mvOption.click();
+ } else if (customize.arrowKeys.includes(event.keyCode)) {
+ // Handle arrow key navigation.
+ event.preventDefault();
+ event.stopPropagation();
+ if (event.keyCode === customize.KEYCODES.LEFT) {
+ clOption.focus();
+ } else if (
+ event.keyCode === customize.KEYCODES.RIGHT ||
+ event.keyCode === customize.KEYCODES.DOWN) {
+ hideToggle.focus();
+ }
+ }
+ };
+
+ hideToggle.onchange = function(event) {
+ customize.richerPicker_toggleShortcutHide(hideToggle.checked);
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_CUSTOMIZE_SHORTCUT_VISIBILITY_TOGGLE_CLICKED);
+ };
+ hideToggle.onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ hideToggle.onchange(event);
+ } else if (customize.arrowKeys.includes(event.keyCode)) {
+ // Handle arrow key navigation.
+ event.preventDefault();
+ event.stopPropagation();
+ if (event.keyCode === customize.KEYCODES.LEFT ||
+ event.keyCode === customize.KEYCODES.UP) {
+ mvOption.focus();
+ }
+ }
+ };
+ hideToggle.onclick = function(event) {
+ // Enter and space fire the 'onclick' event (which will remove special
+ // keyboard navigation styling) unless propagation is stopped.
+ event.stopPropagation();
+ };
+
+ const refreshToggle = $(customize.IDS.REFRESH_TOGGLE);
+ refreshToggle.onchange = function(event) {
+ ntpApiHandle.logEvent(
+ customize.LOG_TYPE.NTP_BACKGROUND_REFRESH_TOGGLE_CLICKED);
+ customize.richerPicker_toggleRefreshDaily(refreshToggle.checked);
+ };
+ refreshToggle.onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ refreshToggle.onchange(event);
+ }
+ };
+ refreshToggle.onclick = function(event) {
+ // Enter and space fire the 'onclick' event (which will remove special
+ // keyboard navigation styling) unless propagation is stopped.
+ event.stopPropagation();
+ };
+
+
+ const richerPickerOpenShortcuts = function() {
+ customize.richerPicker_showSubmenu(
+ $(customize.IDS.SHORTCUTS_BUTTON), $(customize.IDS.SHORTCUTS_MENU));
+ };
+
+ $(customize.IDS.SHORTCUTS_BUTTON).onclick = richerPickerOpenShortcuts;
+ $(customize.IDS.SHORTCUTS_BUTTON).onkeydown = function(event) {
+ if (event.keyCode === customize.KEYCODES.ENTER ||
+ event.keyCode === customize.KEYCODES.SPACE) {
+ richerPickerOpenShortcuts();
+ }
+ };
+
+ $(customize.IDS.COLORS_BUTTON).onclick = function() {
+ customize.richerPicker_showSubmenu(
+ $(customize.IDS.COLORS_BUTTON), $(customize.IDS.COLORS_MENU));
+ ntpApiHandle.getColorsInfo();
+ };
+};
+
+customize.handleError = function(errors) {
+ const unavailableString = configData.translatedStrings.backgroundsUnavailable;
+
+ if (errors != 'undefined') {
+ // Network errors.
+ if (errors.net_error) {
+ if (errors.net_error_no != 0) {
+ const onClick = () => {
+ window.open(
+ 'https://chrome://network-error/' + errors.net_error_no,
+ '_blank');
+ };
+ customize.showErrorNotification(
+ configData.translatedStrings.connectionError,
+ configData.translatedStrings.moreInfo, onClick);
+ } else {
+ customize.showErrorNotification(
+ configData.translatedStrings.connectionErrorNoPeriod);
+ }
+ } else if (errors.service_error) { // Service errors.
+ customize.showErrorNotification(unavailableString);
+ }
+ return;
+ }
+
+ // Generic error when we can't tell what went wrong.
+ customize.showErrorNotification(unavailableString);
+};
+
+/**
+ * Handles color selection. Apply styling to the selected color in the richer
+ * picker and enable the done button.
+ * @param {?Element} tile The selected color tile.
+ */
+customize.updateColorsMenuTileSelection = function(tile) {
+ if (!tile) {
+ return;
+ }
+ // Clear the previous selection, if any.
+ if (customize.selectedOptions.color) {
+ customize.richerPicker_removeSelectedState(customize.selectedOptions.color);
+ }
+ customize.selectedOptions.color = tile;
+ customize.richerPicker_applySelectedState(tile);
+};
+
+/**
+ * Called when a color tile is clicked. Applies the color, and the selected
+ * style on the tile.
+ * @param {Event} event The event attributes for the interaction.
+ */
+customize.colorTileInteraction = function(event) {
+ customize.updateColorsMenuTileSelection(
+ /** @type HTMLElement */ (event.target));
+ const id = parseInt(event.target.dataset.id, 10);
+ if (id) {
+ ntpApiHandle.applyAutogeneratedTheme(
+ id, event.target.dataset.color.split(','));
+ }
+};
+
+/**
+ * Called when the default theme tile is clicked. Applies the default theme, and
+ * the selected style on the tile.
+ * @param {Event} event The event attributes for the interaction.
+ */
+customize.defaultThemeTileInteraction = function(event) {
+ customize.updateColorsMenuTileSelection(
+ /** @type HTMLElement */ (event.target));
+ ntpApiHandle.applyDefaultTheme();
+};
+
+/**
+ * Called when a new color is picked with color picker. Applies the color, and
+ * the selected style on the tile.
+ * @param {Event} event The event attributes for the interaction.
+ */
+customize.colorPickerTileInteraction = function(event) {
+ const hex = event.target.value;
+ const r = parseInt(hex.substring(1, 3), 16);
+ const g = parseInt(hex.substring(3, 5), 16);
+ const b = parseInt(hex.substring(5, 7), 16);
+ // If the picker is preselected and the user picks a new color, we need to
+ // treat the picker as a new selection and not a preselection.
+ if (customize.preselectedOptions.colorsMenuTile ===
+ $(customize.IDS.COLOR_PICKER_TILE)) {
+ customize.preselectedOptions.colorsMenuTile = null;
+ }
+ customize.updateColorsMenuTileSelection($(customize.IDS.COLOR_PICKER_TILE));
+ ntpApiHandle.applyAutogeneratedTheme(0, [r, g, b, 255]);
+};
+
+/**
+ * Loads Colors menu elements.
+ */
+customize.loadColorsMenu = function() {
+ if (customize.colorsMenuLoaded) {
+ customize.colorsMenuPreselectTile();
+ return;
+ }
+
+ const colorsColl = ntpApiHandle.getColorsInfo();
+ for (let i = 0; i < colorsColl.length; ++i) {
+ // After 4 color tiles create an empty tile to take the place of the color
+ // picker. This is done so that the rest of the colors don't move if color
+ // picker is not present.
+ if (!configData.chromeColorsCustomColorPicker && i == 4) {
+ $(customize.IDS.COLORS_MENU).appendChild(document.createElement('div'));
+ }
+ const id = 'color_' + i;
+ const imageUrl = colorsColl[i].icon;
+ const dataset = {'color': colorsColl[i].color, 'id': colorsColl[i].id};
+
+ const tile = customize.createTileWithoutTitle(
+ id, imageUrl, dataset, customize.colorTileInteraction,
+ customize.tileOnKeyDownInteraction);
+ const label = configData.translatedStrings.colorLabelPrefix + ' ' +
+ colorArrayToHex(colorsColl[i].color);
+ tile.firstElementChild.setAttribute('aria-label', label);
+ tile.firstElementChild.setAttribute('title', label);
+
+ $(customize.IDS.COLORS_MENU).appendChild(tile);
+ }
+
+ // Configure the default tile.
+ $(customize.IDS.COLORS_DEFAULT_ICON).onclick =
+ customize.defaultThemeTileInteraction;
+ $(customize.IDS.COLORS_DEFAULT_ICON).onkeydown =
+ customize.tileOnKeyDownInteraction;
+
+ // On arrow keys focus the first element.
+ $(customize.IDS.COLORS_MENU).onkeydown = function(event) {
+ if (document.activeElement === $(customize.IDS.COLORS_MENU) &&
+ customize.arrowKeys.includes(event.keyCode)) {
+ if (configData.chromeColorsCustomColorPicker) {
+ $(customize.IDS.COLOR_PICKER_TILE).focus();
+ } else {
+ $(customize.IDS.COLORS_DEFAULT_ICON).focus();
+ }
+ }
+ };
+
+ // Configure custom color picker.
+ if (configData.chromeColorsCustomColorPicker) {
+ $(customize.IDS.COLOR_PICKER_TILE).onclick = function(event) {
+ $(customize.IDS.COLOR_PICKER).value = customize.customColorPicked;
+ $(customize.IDS.COLOR_PICKER).click();
+ };
+ $(customize.IDS.COLOR_PICKER_TILE).onkeydown =
+ customize.tileOnKeyDownInteraction;
+ $(customize.IDS.COLOR_PICKER).onchange =
+ customize.colorPickerTileInteraction;
+ }
+
+ customize.colorsMenuOnThemeChange();
+
+ customize.colorsMenuLoaded = true;
+};
+
+/**
+ * Update webstore theme info and preselect Colors menu tile according to the
+ * theme update.
+ */
+customize.colorsMenuOnThemeChange = function() {
+ // Update webstore theme information.
+ const themeInfo = ntpApiHandle.themeBackgroundInfo;
+ if (themeInfo.themeId && themeInfo.themeName) {
+ $(customize.IDS.COLORS_THEME).classList.add(customize.CLASSES.VISIBLE);
+ $(customize.IDS.COLORS_THEME_NAME).innerHTML = themeInfo.themeName;
+ $(customize.IDS.COLORS_THEME_WEBSTORE_LINK).href =
+ 'https://chrome.google.com/webstore/detail/' + themeInfo.themeId;
+ $(customize.IDS.COLORS_THEME_UNINSTALL).onclick =
+ ntpApiHandle.useDefaultTheme;
+ } else {
+ $(customize.IDS.COLORS_THEME).classList.remove(customize.CLASSES.VISIBLE);
+ }
+
+ // Select the tile corresponding to the current theme/color.
+ customize.colorsMenuPreselectTile();
+};
+
+/**
+ * Preselect Colors menu tile according to the theme info.
+ */
+customize.colorsMenuPreselectTile = function() {
+ const themeInfo = ntpApiHandle.themeBackgroundInfo;
+
+ let tile;
+ if (themeInfo.usingDefaultTheme) {
+ tile = $(customize.IDS.COLORS_DEFAULT_ICON);
+ } else if (themeInfo.colorId && themeInfo.colorId > 0) {
+ // Color from predefined set is selected.
+ const tiles = Array.from(
+ $(customize.IDS.COLORS_MENU)
+ .getElementsByClassName(customize.CLASSES.COLLECTION_TILE));
+ for (let i = 0; i < tiles.length; i++) {
+ if (tiles[i].dataset && tiles[i].dataset.id == themeInfo.colorId) {
+ tile = tiles[i];
+ break;
+ }
+ }
+ } else if (
+ configData.chromeColorsCustomColorPicker && themeInfo.colorDark &&
+ themeInfo.colorLight && themeInfo.colorPicked) {
+ // Custom color is selected.
+ tile = $(customize.IDS.COLOR_PICKER_TILE);
+
+ // Update color picker tile colors.
+ customize.customColorPicked = colorArrayToHex(themeInfo.colorPicked);
+ $(customize.IDS.COLORS_MENU)
+ .style.setProperty(
+ '--custom-color-border', colorArrayToHex(themeInfo.colorDark));
+ $(customize.IDS.COLORS_MENU)
+ .style.setProperty(
+ '--custom-color-dark', colorArrayToHex(themeInfo.colorDark));
+ $(customize.IDS.COLORS_MENU)
+ .style.setProperty(
+ '--custom-color-light', colorArrayToHex(themeInfo.colorLight));
+ $(customize.IDS.COLOR_PICKER_ICON)
+ .classList.toggle('white', themeInfo.isNtpBackgroundDark);
+ }
+
+ if (tile && tile !== customize.selectedOptions.color) {
+ if (!customize.preselectedOptions.colorsMenuTile) {
+ customize.preselectedOptions.colorsMenuTile = tile;
+ }
+ customize.updateColorsMenuTileSelection(
+ /** @type HTMLElement */ (tile));
+ }
+};
+
+/**
+ * Indicates whether a color other then preselected one was selected on Colors
+ * menu.
+ */
+customize.isColorOptionSelected = function() {
+ return (!customize.preselectedOptions.colorsMenuTile &&
+ customize.selectedOptions.color) ||
+ (customize.preselectedOptions.colorsMenuTile &&
+ customize.selectedOptions.color.id !==
+ customize.preselectedOptions.colorsMenuTile.id);
+};
+
+/**
+ * Indicates whether a background tile other then the preselected one was
+ * selected on the backgrounds menu.
+ */
+customize.isBackgroundOptionSelected = function() {
+ return customize.selectedOptions.backgroundData &&
+ (!customize.preselectedOptions.backgroundsMenuTile ||
+ customize.selectedOptions.backgroundData.id !=
+ customize.preselectedOptions.backgroundsMenuTile.id);
+};
+
+/**
+ * Permanently applies the color changes. Called when the done button is
+ * pressed.
+ */
+customize.confirmColor = function() {
+ ntpApiHandle.confirmThemeChanges();
+};
+
+/**
+ * Reverts the applied (but not confirmed) color changes. Called when the cancel
+ * button is pressed.
+ */
+customize.cancelColor = function() {
+ ntpApiHandle.revertThemeChanges();
+};
+
+/**
+ * Reset Colors Menu elements to the default state, specifically the color
+ * picker.
+ */
+customize.resetColorsMenu = function() {
+ customize.customColorPicked = customize.defaultCustomColor;
+ $(customize.IDS.COLOR_PICKER).value = null;
+ $(customize.IDS.COLORS_MENU).style.setProperty('--custom-color-border', '');
+ $(customize.IDS.COLORS_MENU).style.setProperty('--custom-color-dark', '');
+ $(customize.IDS.COLORS_MENU).style.setProperty('--custom-color-light', '');
+ $(customize.IDS.COLOR_PICKER_ICON).classList.toggle('white', false);
+};
+
+/**
+ * Converts an RGBA component into hex format.
+ * @param {number} c RGBA component.
+ * @return {string} RGBA component in hex format.
+ */
+function rgbComponentToHex(c) {
+ const hex = c.toString(16);
+ return hex.length == 1 ? '0' + hex : hex;
+}
+
+/**
+ * Converts an Array of color components into hex format "#000000".
+ * @param {Array<number>} color Array of RGBA color components.
+ * @return {string} color in hex format.
+ */
+function colorArrayToHex(color) {
+ if (!color || color.length != 4) {
+ return '';
+ }
+
+ return '#' + rgbComponentToHex(color[0]) + rgbComponentToHex(color[1]) +
+ rgbComponentToHex(color[2]);
+}
diff --git a/chromium/chrome/browser/resources/local_ntp/doodles.css b/chromium/chrome/browser/resources/local_ntp/doodles.css
index 6e70f2b5e40..885619db2c1 100644
--- a/chromium/chrome/browser/resources/local_ntp/doodles.css
+++ b/chromium/chrome/browser/resources/local_ntp/doodles.css
@@ -30,7 +30,8 @@
}
#logo-doodle-container,
-#logo-doodle-iframe {
+#logo-doodle-iframe,
+#logo-doodle-wrapper {
display: none;
}
@@ -46,6 +47,18 @@
display: inline-block;
}
+.show-logo #logo-doodle-wrapper {
+ display: inline-block;
+}
+
+@media (prefers-color-scheme: dark) {
+ .show-logo #logo-doodle-wrapper {
+ border-radius: 20px;
+ display: inline-block;
+ padding: 16px 24px 16px 24px;
+ }
+}
+
#logo-doodle-image {
outline: none;
}
@@ -72,7 +85,7 @@ body.alternate-logo #logo-non-white {
url(../../../../ui/webui/resources/images/google_logo.svg);
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: 100%;
- background: #eee;
+ background: var(--logo-color);
}
#logo-default,
@@ -144,7 +157,7 @@ body.alternate-logo #logo-non-white {
width: 37.5%;
}
.use-notifier #logo-doodle-notifier .inner {
- animation: anim-pos 880ms cubic-bezier(0.445, 0.05, 0.55, 0.95)
+ animation: anim-pos 880ms cubic-bezier(.445, .05, .55, .95)
infinite alternate;
border-radius: 50%;
height: 100%;
@@ -189,7 +202,7 @@ body.alternate-logo #logo-non-white {
cursor: pointer;
display: inline-block;
height: 26px;
- opacity: 0.8;
+ opacity: .8;
position: absolute;
width: 26px;
}
@@ -210,7 +223,7 @@ body.alternate-logo #logo-non-white {
background: #fff;
border: none;
border-radius: 8px;
- box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
+ box-shadow: 0 4px 16px 0 rgba(0, 0, 0, .2);
left: 0;
margin: auto;
min-height: 100px;
@@ -224,7 +237,18 @@ body.alternate-logo #logo-non-white {
}
#ddlsd::backdrop {
- background-color: rgba(255, 255, 255, 0.9);
+ background-color: rgba(255, 255, 255, .9);
+}
+
+@media (prefers-color-scheme: dark) {
+ #ddlsd {
+ background-color: rgb(var(--dark-mode-dialog-rgb));
+ box-shadow: var(--dark-mode-shadow);
+ }
+
+ #ddlsd::backdrop {
+ background-color: rgba(0, 0, 0, 0.4);
+ }
}
#ddlsd button {
@@ -233,7 +257,7 @@ body.alternate-logo #logo-non-white {
}
#ddlsd button:hover {
- opacity: 0.8;
+ opacity: .8;
}
#ddlsd-title {
@@ -242,6 +266,12 @@ body.alternate-logo #logo-non-white {
padding: 0 40px 16px 0;
}
+@media (prefers-color-scheme: dark) {
+ #ddlsd-title {
+ color: rgb(var(--GG200-rgb));
+ }
+}
+
#ddlsd-close {
background: url(icons/close.svg) no-repeat;
height: 24px;
@@ -265,7 +295,7 @@ body.alternate-logo #logo-non-white {
#ddlsd-text {
border: 2px solid #aaa;
- border-color: rgba(0, 0, 0, 0.15);
+ border-color: rgba(0, 0, 0, .15);
border-radius: 4px;
color: #555;
display: inline-block;
@@ -274,6 +304,13 @@ body.alternate-logo #logo-non-white {
width: 100%;
}
+@media (prefers-color-scheme: dark) {
+ #ddlsd-text {
+ background-color: rgba(0, 0, 0, 0.3);
+ color: rgb(var(--GG200-rgb));
+ }
+}
+
#ddlsd-copy {
background: url(icons/copy.svg) no-repeat center;
background-size: contain;
diff --git a/chromium/chrome/browser/resources/local_ntp/doodles.js b/chromium/chrome/browser/resources/local_ntp/doodles.js
index 77865a37f3f..2e0543b4161 100644
--- a/chromium/chrome/browser/resources/local_ntp/doodles.js
+++ b/chromium/chrome/browser/resources/local_ntp/doodles.js
@@ -2,7 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-
const doodles = {};
doodles.numDdllogResponsesReceived = 0;
@@ -12,7 +11,6 @@ doodles.onDdllogResponse = null;
doodles.ei = null;
-
/**
* Enum for classnames.
* @enum {string}
@@ -23,7 +21,6 @@ doodles.CLASSES = {
SHOW_LOGO: 'show-logo', // Marks logo/doodle that should be shown.
};
-
/**
* Enum for HTML element ids.
* @enum {string}
@@ -47,9 +44,9 @@ doodles.IDS = {
LOGO_DOODLE_CONTAINER: 'logo-doodle-container',
LOGO_DOODLE_BUTTON: 'logo-doodle-button',
LOGO_DOODLE_NOTIFIER: 'logo-doodle-notifier',
+ LOGO_DOODLE_WRAPPER: 'logo-doodle-wrapper',
};
-
/**
* Counterpart of search_provider_logos::LogoType.
* @enum {string}
@@ -61,7 +58,6 @@ doodles.LOGO_TYPE = {
INTERACTIVE: 'INTERACTIVE',
};
-
/**
* Subset of gws.plugins.doodle.SharingLightbox.LogType in
* googledata/html/templates/gws/head/xjs/plugins/doodle/sharing_lightbox.js.
@@ -75,14 +71,12 @@ doodles.SHARE_TYPE = {
LINK_COPY: 6,
};
-
/**
* The ID of the doodle app for Facebook. Used to share doodles to Facebook.
* @type {number}
*/
doodles.FACEBOOK_APP_ID = 738026486351791;
-
/**
* The different types of events that are logged from the NTP. This enum is
* used to transfer information from the NTP JavaScript to the renderer and is
@@ -109,7 +103,6 @@ doodles.LOG_TYPE = {
NTP_ANIMATED_LOGO_CLICKED: 36,
};
-
/**
* Handle the resizeDoodle command sent from the fpdoodle page
* when an interactive doodle is clicked.
@@ -133,8 +126,7 @@ doodles.resizeDoodleHandler = function(args) {
document.body.style.setProperty('--logo-iframe-width', width);
};
-
-/*
+/**
* Fetch doodle data and display it if one is present.
*/
doodles.init = function() {
@@ -148,8 +140,12 @@ doodles.init = function() {
return;
}
+ const darkMode = window.matchMedia('(prefers-color-scheme: dark)');
+ darkMode.addListener(doodles.fadeToLogoOrDoodle);
+
// Got a (possibly empty) ddl object. Show logo or doodle.
doodles.targetDoodle.image = ddl.image || null;
+ doodles.targetDoodle.dark_image = ddl.dark_image || null;
doodles.targetDoodle.metadata = ddl.metadata || null;
doodles.showLogoOrDoodle(/*fromCache=*/ true);
// Never hide an interactive doodle if it was already shown.
@@ -161,6 +157,7 @@ doodles.init = function() {
doodles.loadDoodle(ddl.v, function(ddl2) {
if (ddl2.usable) {
doodles.targetDoodle.image = ddl2.image || null;
+ doodles.targetDoodle.dark_image = ddl2.dark_image || null;
doodles.targetDoodle.metadata = ddl2.metadata || null;
doodles.fadeToLogoOrDoodle();
}
@@ -184,6 +181,18 @@ doodles.init = function() {
});
};
+/**
+ * Get the doodle image for the current color scheme, either light or dark.
+ */
+doodles.getImageForColorScheme = function() {
+ // Only use a dark image if the browser is in dark mode and a dark image
+ // actually exists.
+ if (window.matchMedia('(prefers-color-scheme: dark)').matches &&
+ doodles.targetDoodle.dark_image) {
+ return doodles.targetDoodle.dark_image;
+ }
+ return doodles.targetDoodle.image;
+};
/**
* Loads the Doodle. On success, the loaded script declares a global variable
@@ -209,7 +218,6 @@ doodles.loadDoodle = function(v, onload) {
document.body.appendChild(ddlScript);
};
-
/**
* Handles the response of a doodle impression ping, i.e. stores the
* appropriate interactionLogUrl or onClickUrlExtraParams. Also stores
@@ -248,7 +256,6 @@ doodles.handleDdllogResponse = function(ddllog, isAnimated) {
}
};
-
/**
* Logs a doodle impression at the given logUrl, and handles the response via
* doodles.handleDdllogResponse.
@@ -290,7 +297,6 @@ doodles.logDoodleImpression = function(logUrl, isAnimated) {
});
};
-
/**
* Logs a doodle sharing event.
* Uses the ct param provided in metadata.onClickUrl to track the doodle.
@@ -315,7 +321,6 @@ doodles.logDoodleShare = function(platform) {
}
};
-
/**
* Returns true if the target doodle is currently visible. If |image| is null,
* returns true when the default logo is visible; if non-null, checks that it
@@ -328,7 +333,7 @@ doodles.isDoodleCurrentlyVisible = function() {
const haveDoodle = ($(doodles.IDS.LOGO_DOODLE)
.classList.contains(doodles.CLASSES.SHOW_LOGO));
const wantDoodle = (doodles.targetDoodle.metadata !== null) &&
- (doodles.targetDoodle.image !== null ||
+ (doodles.getImageForColorScheme() !== null ||
doodles.targetDoodle.metadata.type === doodles.LOGO_TYPE.INTERACTIVE);
if (!haveDoodle || !wantDoodle) {
return haveDoodle === wantDoodle;
@@ -343,12 +348,11 @@ doodles.isDoodleCurrentlyVisible = function() {
const logoDoodleImage = $(doodles.IDS.LOGO_DOODLE_IMAGE);
const logoDoodleContainer = $(doodles.IDS.LOGO_DOODLE_CONTAINER);
return logoDoodleContainer.classList.contains(doodles.CLASSES.SHOW_LOGO) &&
- ((logoDoodleImage.src === doodles.targetDoodle.image) ||
+ ((logoDoodleImage.src === doodles.getImageForColorScheme()) ||
(logoDoodleImage.src === doodles.targetDoodle.metadata.animatedUrl));
}
};
-
/**
* The image and metadata that should be shown, according to the latest fetch.
* After a logo fades out, doodles.onDoodleFadeOutComplete fades in a logo
@@ -364,7 +368,6 @@ doodles.targetDoodle = {
onClickUrlExtraParams: null,
};
-
doodles.getDoodleTargetUrl = function() {
const url = new URL(doodles.targetDoodle.metadata.onClickUrl);
if (doodles.targetDoodle.onClickUrlExtraParams) {
@@ -375,7 +378,6 @@ doodles.getDoodleTargetUrl = function() {
return url;
};
-
doodles.showLogoOrDoodle = function(fromCache) {
const cachedInteractiveOffline = fromCache &&
doodles.targetDoodle.metadata !== null &&
@@ -389,7 +391,13 @@ doodles.showLogoOrDoodle = function(fromCache) {
$(doodles.IDS.LOGO_DOODLE_IFRAME)
.classList.add(doodles.CLASSES.SHOW_LOGO);
} else {
- $(doodles.IDS.LOGO_DOODLE_IMAGE).src = doodles.targetDoodle.image;
+ const isDarkModeEnabled =
+ window.matchMedia('(prefers-color-scheme: dark)').matches;
+ if (isDarkModeEnabled) {
+ $(doodles.IDS.LOGO_DOODLE_WRAPPER).style.backgroundColor =
+ doodles.targetDoodle.metadata.darkBackgroundColor;
+ }
+ $(doodles.IDS.LOGO_DOODLE_IMAGE).src = doodles.getImageForColorScheme();
$(doodles.IDS.LOGO_DOODLE_CONTAINER)
.classList.add(doodles.CLASSES.SHOW_LOGO);
$(doodles.IDS.LOGO_DOODLE_IFRAME)
@@ -418,11 +426,9 @@ doodles.showLogoOrDoodle = function(fromCache) {
}
};
-
/**
* Starts fading out the given element, which should be either the default logo
* or the doodle.
- *
* @param {?Element} element
*/
doodles.startFadeOut = function(element) {
@@ -440,7 +446,6 @@ doodles.startFadeOut = function(element) {
element.addEventListener('transitionend', doodles.onDoodleFadeOutComplete);
};
-
/**
* Integrates a fresh doodle into the page as appropriate. If the correct logo
* or doodle is already shown, just updates the metadata. Otherwise, initiates
@@ -469,7 +474,6 @@ doodles.fadeToLogoOrDoodle = function() {
doodles.startFadeOut($(doodles.IDS.LOGO_DOODLE));
};
-
doodles.onDoodleFadeOutComplete = function(e) {
// Fade-out finished. Start fading in the appropriate logo.
$(doodles.IDS.LOGO_DOODLE).classList.add(doodles.CLASSES.FADE);
@@ -480,7 +484,6 @@ doodles.onDoodleFadeOutComplete = function(e) {
'transitionend', doodles.onDoodleFadeOutComplete);
};
-
doodles.applyDoodleMetadata = function() {
const logoDoodleImage = $(doodles.IDS.LOGO_DOODLE_IMAGE);
const logoDoodleButton = $(doodles.IDS.LOGO_DOODLE_BUTTON);
@@ -579,12 +582,23 @@ doodles.applyDoodleMetadata = function() {
* dialog upon click.
*/
doodles.insertShareButton = function() {
- // Terminates early if share button data are missing or incomplete.
- if (!doodles.targetDoodle.metadata ||
- !doodles.targetDoodle.metadata.shareButtonX ||
- !doodles.targetDoodle.metadata.shareButtonY ||
- !doodles.targetDoodle.metadata.shareButtonBg ||
- !doodles.targetDoodle.metadata.shareButtonIcon) {
+ // Terminates early if share button data for the current color scheme is
+ // missing or incomplete.
+ const isDarkModeEnabled =
+ window.matchMedia('(prefers-color-scheme: dark)').matches;
+ const lightShareButtonMissing = !isDarkModeEnabled &&
+ (!doodles.targetDoodle.metadata ||
+ !doodles.targetDoodle.metadata.shareButtonX ||
+ !doodles.targetDoodle.metadata.shareButtonY ||
+ !doodles.targetDoodle.metadata.shareButtonBg ||
+ !doodles.targetDoodle.metadata.shareButtonIcon);
+ const darkShareButtonMissing = isDarkModeEnabled &&
+ (!doodles.targetDoodle.metadata ||
+ !doodles.targetDoodle.metadata.darkShareButtonX ||
+ !doodles.targetDoodle.metadata.darkShareButtonY ||
+ !doodles.targetDoodle.metadata.darkShareButtonBg ||
+ !doodles.targetDoodle.metadata.darkShareButtonIcon);
+ if (lightShareButtonMissing || darkShareButtonMissing) {
return;
}
const shareDialog = $(doodles.IDS.DOODLE_SHARE_DIALOG);
@@ -596,27 +610,36 @@ doodles.insertShareButton = function() {
shareButtonWrapper.appendChild(shareButtonImg);
shareButtonWrapper.title = configData.translatedStrings.shareDoodle;
- shareButtonWrapper.style.left =
- doodles.targetDoodle.metadata.shareButtonX + 'px';
- shareButtonWrapper.style.top =
- doodles.targetDoodle.metadata.shareButtonY + 'px';
+ const shareButtonX = isDarkModeEnabled ?
+ doodles.targetDoodle.metadata.darkShareButtonX :
+ doodles.targetDoodle.metadata.shareButtonX;
+ shareButtonWrapper.style.left = shareButtonX + 'px';
+ const shareButtonY = isDarkModeEnabled ?
+ doodles.targetDoodle.metadata.darkShareButtonY :
+ doodles.targetDoodle.metadata.shareButtonY;
+ shareButtonWrapper.style.top = shareButtonY + 'px';
// Alpha-less background color represented as an RGB HEX string.
// Share button opacity represented as a double between 0 to 1.
// Final background color is an RGBA HEX string created by combining
// both.
- let backgroundColor = doodles.targetDoodle.metadata.shareButtonBg;
- if (!!doodles.targetDoodle.metadata.shareButtonOpacity ||
- doodles.targetDoodle.metadata.shareButtonOpacity == 0) {
+ let backgroundColor = isDarkModeEnabled ?
+ doodles.targetDoodle.metadata.darkShareButtonBg :
+ doodles.targetDoodle.metadata.shareButtonBg;
+ const shareButtonOpacity = isDarkModeEnabled ?
+ doodles.targetDoodle.metadata.darkShareButtonOpacity :
+ doodles.targetDoodle.metadata.shareButtonOpacity;
+ if (!!shareButtonOpacity || shareButtonOpacity == 0) {
const backgroundOpacityHex =
- parseInt(doodles.targetDoodle.metadata.shareButtonOpacity * 255, 10)
- .toString(16);
+ parseInt(shareButtonOpacity * 255, 10).toString(16);
backgroundColor += backgroundOpacityHex;
}
shareButtonWrapper.style.backgroundColor = backgroundColor;
- shareButtonImg.src =
- 'data:image/png;base64,' + doodles.targetDoodle.metadata.shareButtonIcon;
+ const shareButtonIcon = isDarkModeEnabled ?
+ doodles.targetDoodle.metadata.darkShareButtonIcon :
+ doodles.targetDoodle.metadata.shareButtonIcon;
+ shareButtonImg.src = 'data:image/png;base64,' + shareButtonIcon;
shareButtonWrapper.onclick = function() {
shareDialog.showModal();
};
diff --git a/chromium/chrome/browser/resources/local_ntp/externs.js b/chromium/chrome/browser/resources/local_ntp/externs.js
index b0a701b66ef..a520ad5e2e1 100644
--- a/chromium/chrome/browser/resources/local_ntp/externs.js
+++ b/chromium/chrome/browser/resources/local_ntp/externs.js
@@ -14,7 +14,7 @@
* InstantMostVisitedItem
* @typedef {{dataGenerationTime: Date,
* isAddButton: boolean,
- * tid: number,
+ * rid: number,
* tileSource: number,
* tileTitleSource: number,
* title: ?,
@@ -26,16 +26,15 @@ let MostVisitedData;
* The type of the config data object. The definition is based on
* chrome/browser/search/local_ntp_source.cc:
* LocalNtpSource::SearchConfigurationProvider::UpdateConfigData()
- * @typedef {{translatedStrings: Array<string>,
- * isGooglePage: boolean,
- * googleBaseUrl: string,
- * isAccessibleBrowser: boolean,
+ * @typedef {{chromeColors: boolean,
* enableShortcutsGrid: boolean,
- * removeFakebox: boolean,
- * alternateFakebox: boolean,
- * fakeboxSearchIcon: boolean,
+ * googleBaseUrl: string,
* hideShortcuts: boolean,
- * chromeColors: boolean}}
+ * isAccessibleBrowser: boolean,
+ * isGooglePage: boolean,
+ * richerPicker: boolean,
+ * showFakeboxPlaceholderOnFocus: boolean,
+ * translatedStrings: Array<string>}}
*/
let configData;
@@ -157,6 +156,21 @@ window.chrome.embeddedSearch;
window.chrome.embeddedSearch.newTabPage;
/**
+ * @param {Array} color
+ */
+window.chrome.embeddedSearch.newTabPage.applyAutogeneratedTheme;
+
+/**
+ * No params.
+ */
+window.chrome.embeddedSearch.newTabPage.applyDefaultTheme;
+
+/**
+ * @return {boolean} areShortcutsVisible
+ */
+window.chrome.embeddedSearch.newTabPage.areShortcutsVisible;
+
+/**
* @param {number} task_version
* @param {number} task_id
*/
@@ -170,7 +184,12 @@ window.chrome.embeddedSearch.newTabPage.blacklistSearchSuggestion;
window.chrome.embeddedSearch.newTabPage.blacklistSearchSuggestionWithHash;
/**
- * @param {number} tid
+ * No params.
+ */
+window.chrome.embeddedSearch.newTabPage.confirmThemeChanges;
+
+/**
+ * @param {number} rid
*/
window.chrome.embeddedSearch.newTabPage.deleteMostVisitedItem;
@@ -180,7 +199,12 @@ window.chrome.embeddedSearch.newTabPage.deleteMostVisitedItem;
window.chrome.embeddedSearch.newTabPage.fixupAndValidateUrl;
/**
- * @param {number} tid
+ * No params.
+ */
+window.chrome.embeddedSearch.newTabPage.getColorsInfo;
+
+/**
+ * @param {number} rid
*/
window.chrome.embeddedSearch.newTabPage.getMostVisitedItemData;
@@ -195,6 +219,11 @@ window.chrome.embeddedSearch.newTabPage.isCustomLinks;
window.chrome.embeddedSearch.newTabPage.isInputInProgress;
/**
+ * @return {boolean} isUsingMostVisited
+ */
+window.chrome.embeddedSearch.newTabPage.isUsingMostVisited;
+
+/**
* @param {number} event
*/
window.chrome.embeddedSearch.newTabPage.logEvent;
@@ -244,6 +273,11 @@ window.chrome.embeddedSearch.newTabPage.reorderCustomLink;
window.chrome.embeddedSearch.newTabPage.resetCustomLinks;
/**
+ * No params.
+ */
+window.chrome.embeddedSearch.newTabPage.revertThemeChanges;
+
+/**
* @param {number} task_version
* @param {number} task_id
* @param {string} hash
@@ -265,8 +299,9 @@ window.chrome.embeddedSearch.newTabPage.setBackgroundURL;
* @param {string} attribution_line_1
* @param {string} attribution_line_2
* @param {string} attribution_action_url
+ * @param {string} collection_id
*/
-window.chrome.embeddedSearch.newTabPage.setBackgroundURLWithAttributions;
+window.chrome.embeddedSearch.newTabPage.setBackgroundInfo;
/**
* @return {Object} theme_background_info
@@ -276,6 +311,21 @@ window.chrome.embeddedSearch.newTabPage.themeBackgroundInfo;
/**
* No params.
*/
+window.chrome.embeddedSearch.newTabPage.toggleMostVisitedOrCustomLinks;
+
+/**
+ * No params.
+ */
+window.chrome.embeddedSearch.newTabPage.toggleShortcutsVisibility;
+
+/**
+ * No params.
+ */
+window.chrome.embeddedSearch.newTabPage.useDefaultTheme;
+
+/**
+ * No params.
+ */
window.chrome.embeddedSearch.newTabPage.undoAllMostVisitedDeletions;
/**
@@ -321,13 +371,11 @@ configData.translatedStrings.audioError;
configData.translatedStrings.backLabel;
configData.translatedStrings.backgroundsUnavailable;
configData.translatedStrings.clickToViewDoodle;
+configData.translatedStrings.colorLabelPrefix;
configData.translatedStrings.connectionError;
configData.translatedStrings.connectionErrorNoPeriod;
configData.translatedStrings.copyLink;
-configData.translatedStrings.customizeBackground;
-configData.translatedStrings.customizeButtonLabel;
configData.translatedStrings.customizeThisPage;
-configData.translatedStrings.dailyRefresh;
configData.translatedStrings.defaultWallpapers;
configData.translatedStrings.details;
configData.translatedStrings.editLinkTitle;
diff --git a/chromium/chrome/browser/resources/local_ntp/icons/brush.svg b/chromium/chrome/browser/resources/local_ntp/icons/brush.svg
new file mode 100644
index 00000000000..75ff8383190
--- /dev/null
+++ b/chromium/chrome/browser/resources/local_ntp/icons/brush.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M7 14c-1.66 0-3 1.34-3 3 0 1.31-1.16 2-2 2 .92 1.22 2.49 2 4 2 2.21 0 4-1.79 4-4 0-1.66-1.34-3-3-3zm13.71-9.37l-1.34-1.34c-.39-.39-1.02-.39-1.41 0L9 12.25 11.75 15l8.96-8.96c.39-.39.39-1.02 0-1.41z"/></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/local_ntp/icons/check_circle.svg b/chromium/chrome/browser/resources/local_ntp/icons/check_circle.svg
new file mode 100644
index 00000000000..8ca0ca42a9e
--- /dev/null
+++ b/chromium/chrome/browser/resources/local_ntp/icons/check_circle.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="15" height="15"><defs><path d="M0 0h18v18H0V0z" id="a"/><path d="M10.12.47l1.16.55 1.05.74.91.91.74 1.04.55 1.17.35 1.27L15 7.5l-.12 1.35-.35 1.27-.55 1.16-.74 1.05-.91.91-1.05.74-1.16.55-1.27.35L7.5 15l-1.35-.12-1.27-.35-1.17-.55-1.04-.74-.91-.91-.74-1.05-.55-1.16-.35-1.27L0 7.5l.12-1.35.35-1.27.55-1.17.74-1.04.91-.91 1.04-.74L4.88.47 6.15.12 7.5 0l1.35.12 1.27.35zM3.31 6.44L2.25 7.5 6 11.25l6.75-6.75-1.06-1.06L6 9.13 3.31 6.44z" id="b"/></defs><use xlink:href="#a" fill-opacity="0"/><use xlink:href="#a" fill-opacity="0" stroke="#000" stroke-opacity="0"/><g><use xlink:href="#b" fill="#4285f4"/><use xlink:href="#b" fill-opacity="0" stroke="#000" stroke-opacity="0"/></g></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/local_ntp/icons/colored_header.svg b/chromium/chrome/browser/resources/local_ntp/icons/colored_header.svg
new file mode 100644
index 00000000000..288f6f4be2b
--- /dev/null
+++ b/chromium/chrome/browser/resources/local_ntp/icons/colored_header.svg
@@ -0,0 +1,96 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ width="130px"
+ height="40px"
+ viewBox="0 0 130 40"
+ version="1.1"
+ id="svg4765"
+ sodipodi:docname="colored-header.svg"
+ inkscape:version="0.92.3 (2405546, 2018-03-11)">
+ <metadata
+ id="metadata4771">
+ <rdf:RDF>
+ <cc:Work
+ rdf:about="">
+ <dc:format>image/svg+xml</dc:format>
+ <dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+ <dc:title>ic-ntp-shortcuts-header</dc:title>
+ </cc:Work>
+ </rdf:RDF>
+ </metadata>
+ <defs
+ id="defs4769" />
+ <sodipodi:namedview
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1"
+ objecttolerance="10"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
+ inkscape:pageshadow="2"
+ inkscape:window-width="1297"
+ inkscape:window-height="688"
+ id="namedview4767"
+ showgrid="false"
+ inkscape:zoom="4.8"
+ inkscape:cx="76.144652"
+ inkscape:cy="32.314819"
+ inkscape:window-x="3486"
+ inkscape:window-y="298"
+ inkscape:window-maximized="0"
+ inkscape:current-layer="svg4765" />
+ <!-- Generator: Sketch 54.1 (76490) - https://sketchapp.com -->
+ <title
+ id="title4758">ic-ntp-shortcuts-header</title>
+ <desc
+ id="desc4760">Created with Sketch.</desc>
+ <path
+ style="fill:#d93025;fill-opacity:1;stroke:#1a73e8;stroke-width:0.42092341;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0"
+ d="m 52.792125,16.638275 c -1.558053,-0.640709 -2.46799,-1.578762 -3.063032,-3.157678 -0.258437,-0.685749 -0.302859,-1.064041 -0.253341,-2.157386 0.07554,-1.6677974 0.544737,-2.7097496 1.692666,-3.7588922 1.12893,-1.0317787 2.113309,-1.3670063 3.799505,-1.2939114 1.164657,0.050487 1.439108,0.1180822 2.257734,0.5560648 1.700233,0.9096603 2.652276,2.4152882 2.778616,4.3942958 0.16603,2.600723 -1.339494,4.846853 -3.731181,5.566645 -1.067754,0.321347 -2.484458,0.260649 -3.480967,-0.149138 z m 3.677461,-2.238987 C 58.141804,13.055014 58.277858,10.477094 56.75087,9.0695662 55.705568,8.10604 54.548174,7.9476031 53.280665,8.5945264 c -0.664803,0.3393084 -0.94822,0.6565765 -1.321342,1.4791646 -0.598485,1.319424 -0.311237,3.055032 0.667322,4.032083 0.653851,0.652843 1.188222,0.836121 2.296145,0.787527 0.844457,-0.03704 1.066592,-0.107983 1.546796,-0.494013 z"
+ id="path4775"
+ inkscape:connector-curvature="0" />
+ <path
+ style="fill:#d93025;fill-opacity:1;stroke:#1a73e8;stroke-width:0.42092341;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0"
+ d="m 93.243638,16.791187 c -1.322385,-0.431646 -2.605435,-1.58809 -3.170464,-2.857618 -0.443424,-0.996302 -0.537766,-3.114174 -0.186146,-4.1787327 0.459731,-1.3918707 1.289274,-2.403738 2.498628,-3.0477998 0.656316,-0.3495315 0.897078,-0.3922845 2.209709,-0.3923856 1.750154,-1.347e-4 2.263078,0.211741 3.365322,1.3901286 0.739022,0.7900748 1.5471,2.3122585 1.328555,2.5026125 -0.06993,0.06091 -1.701563,0.761437 -3.625851,1.556728 -1.924288,0.795291 -3.498705,1.501853 -3.498705,1.570138 0,0.285461 1.0896,1.299941 1.564555,1.456691 0.644907,0.212838 1.770254,0.209983 2.343655,-0.0059 0.240652,-0.09062 0.683662,-0.403876 0.984466,-0.696115 l 0.546916,-0.531343 0.815738,0.541619 c 0.448656,0.29789 0.815737,0.60109 0.815737,0.673777 0,0.244635 -1.458021,1.445674 -2.168455,1.786257 -0.873904,0.41895 -2.878317,0.540562 -3.82366,0.231989 z m 1.314899,-6.424686 c 1.257312,-0.5311184 2.17288,-1.0008387 2.17288,-1.1147688 0,-0.3474108 -0.956531,-0.9438591 -1.67065,-1.04174 -0.932951,-0.1278751 -1.864461,0.242135 -2.510919,0.997376 -0.449206,0.5247962 -0.827104,1.4859958 -0.827104,2.1037728 0,0.266282 -0.145753,0.314835 2.835793,-0.94464 z"
+ id="path4777"
+ inkscape:connector-curvature="0" />
+ <path
+ style="fill:#1e8e3e;fill-opacity:1;stroke:#1a73e8;stroke-width:0.42092341;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0"
+ d="M 85.977501,8.5979031 V 0.64295185 h 1.104855 1.104854 V 8.5979031 16.552854 h -1.104854 -1.104855 z"
+ id="path4779"
+ inkscape:connector-curvature="0" />
+ <path
+ style="fill:#1a73e8;fill-opacity:1;stroke:#1a73e8;stroke-width:0.42092341;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0"
+ d="m 76.853462,21.598658 c -0.343214,-0.141956 -0.909847,-0.462726 -1.259185,-0.712823 -0.645316,-0.461992 -1.625016,-1.763251 -1.533724,-2.037126 0.02754,-0.08262 0.437826,-0.306096 0.911747,-0.49661 0.822217,-0.330527 0.868306,-0.334119 1.006551,-0.07845 0.07968,0.147368 0.394194,0.508587 0.698913,0.80271 0.996155,0.961517 2.691209,1.078986 3.833419,0.26566 0.566545,-0.403415 0.98745,-1.36764 1.104998,-2.531367 0.109543,-1.08448 -3.39e-4,-1.224342 -0.555555,-0.707086 -0.643892,0.599876 -1.324944,0.81664 -2.55194,0.812228 -1.054528,-0.0038 -1.276472,-0.05685 -2.109672,-0.504311 -3.862174,-2.074153 -3.866917,-7.5505053 -0.0084,-9.6505955 1.098347,-0.5977958 2.689293,-0.6943715 3.771247,-0.2289274 0.41605,0.1789801 0.870894,0.451871 1.010762,0.6064241 0.358633,0.3962852 0.503271,0.3500329 0.503271,-0.1609361 V 6.5355084 h 1.031197 1.031198 v 5.2960496 c 0,3.363351 -0.0605,5.580934 -0.165782,6.076699 -0.358712,1.689134 -1.289475,2.954312 -2.611208,3.549392 -0.95478,0.429866 -3.221381,0.507672 -4.107878,0.141009 z m 3.008287,-6.822942 c 1.131717,-0.427593 1.868493,-1.669606 1.873289,-3.157878 0.0028,-0.86476 -0.0659,-1.157805 -0.425589,-1.8156234 -0.676343,-1.2369441 -1.920296,-1.8165584 -3.204597,-1.4931677 -1.451145,0.3654025 -2.321474,1.597539 -2.321474,3.2865421 0,1.537167 0.698039,2.683174 1.936465,3.179195 0.475504,0.190451 1.638963,0.190957 2.141906,9.28e-4 z"
+ id="path5324"
+ inkscape:connector-curvature="0" />
+ <path
+ style="fill:#1a73e8;fill-opacity:1;stroke:#1a73e8;stroke-width:0.42092341;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0"
+ d="m 37.702732,16.572061 c -3.608224,-1.03865 -6.260841,-4.438713 -6.260841,-8.0249993 0,-2.2866039 0.798299,-4.1654259 2.489127,-5.8582377 3.117921,-3.12157795 7.698154,-3.49323118 11.097943,-0.9005189 l 0.704548,0.5372957 -0.760012,0.769572 -0.760013,0.769572 -0.462627,-0.352863 C 43.496412,3.317807 42.893279,2.9741312 42.410562,2.7481575 41.624111,2.3799977 41.37134,2.3372843 39.978457,2.3371791 c -1.500588,-1.131e-4 -1.59332,0.0191 -2.676931,0.5546499 -3.83901,1.8973419 -4.670343,7.0194203 -1.632356,10.057408 2.928466,2.928465 8.493062,1.988634 9.608529,-1.622829 0.16848,-0.545475 0.306327,-1.084227 0.306327,-1.197226 0,-0.16852 -0.50316,-0.2054536 -2.798964,-0.2054536 H 39.986098 V 8.818874 7.7140197 h 3.903818 3.903819 v 1.3185742 c 0,0.7252158 -0.07326,1.6698661 -0.162794,2.0992231 -0.548224,2.628905 -2.660726,4.780475 -5.382742,5.482292 -1.197723,0.308808 -3.397293,0.288461 -4.545467,-0.04205 z"
+ id="path5326"
+ inkscape:connector-curvature="0" />
+ <path
+ style="fill:#f9ab00;fill-opacity:1;stroke:#1a73e8;stroke-width:0.42092341;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0"
+ d="m 64.866306,16.647989 c -1.439659,-0.592221 -2.160555,-1.252384 -2.901767,-2.6573 -0.361404,-0.685017 -0.396953,-0.897517 -0.396953,-2.372851 0,-1.475786 0.03675,-1.6952858 0.41163,-2.4586817 0.535869,-1.0912251 1.754624,-2.2082083 2.866597,-2.6272209 0.69966,-0.2636455 1.07663,-0.309028 2.172388,-0.261528 1.164657,0.050487 1.439108,0.1180822 2.257735,0.5560648 1.687943,0.9030855 2.648433,2.4297048 2.782833,4.4230818 0.130768,1.939493 -0.710405,3.739671 -2.239559,4.79284 -1.466601,1.010086 -3.396096,1.246007 -4.952904,0.605595 z m 3.653558,-2.248701 c 1.16647,-0.93771 1.639777,-2.558997 1.164655,-3.989457 -0.890126,-2.6799185 -4.315102,-2.9848143 -5.575768,-0.4963623 -0.712317,1.4060553 -0.505574,3.0327553 0.523065,4.1155843 0.689046,0.725346 1.200834,0.914267 2.341252,0.864248 0.844457,-0.03704 1.066592,-0.107983 1.546796,-0.494013 z"
+ id="path5328"
+ inkscape:connector-curvature="0" />
+ <path
+ style="fill:#dadce0;fill-opacity:0;stroke:#1a73e8;stroke-width:0.42092341;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0"
+ d="M 3.7588617,39.742214 C 2.7434871,39.468647 2.1711297,39.11218 1.3945889,38.269732 0.42844335,37.221588 0.13699821,36.450285 0.14665102,34.967094 c 0.006563,-1.008469 0.0770533,-1.395522 0.36218888,-1.988738 0.5191587,-1.080096 1.671775,-2.172239 2.697566,-2.556037 l 0.849882,-0.317981 61.1647091,0.03753 61.164713,0.03753 0.77843,0.410145 c 1.9957,1.051511 3.04206,3.123768 2.65669,5.261441 -0.29425,1.632204 -1.31274,2.917822 -2.90184,3.662936 l -0.82791,0.388197 -60.766989,0.02759 C 12.45324,39.953695 4.4533772,39.929334 3.7588617,39.742214 Z"
+ id="path5330"
+ inkscape:connector-curvature="0" />
+ <path
+ style="fill:#dadce0;fill-opacity:1;stroke:none;stroke-width:0.59527564;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0"
+ d="M 3.5863687,39.610766 C 3.201034,39.47132 2.5199554,39.050116 2.072861,38.674757 -0.6345187,36.401774 -0.1604641,32.205634 2.9805331,30.640409 L 4.0562879,30.104338 H 64.980795 c 45.632965,0 61.127055,0.06068 61.731505,0.241783 0.44385,0.13298 1.17305,0.555106 1.62044,0.938057 2.8374,2.428712 1.9498,7.048709 -1.59742,8.314586 -1.09987,0.392503 -122.0649315,0.404292 -123.1489513,0.012 z"
+ id="path5391"
+ inkscape:connector-curvature="0" />
+</svg>
diff --git a/chromium/chrome/browser/resources/local_ntp/icons/colorize.svg b/chromium/chrome/browser/resources/local_ntp/icons/colorize.svg
new file mode 100644
index 00000000000..984de18801f
--- /dev/null
+++ b/chromium/chrome/browser/resources/local_ntp/icons/colorize.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"><path fill="none" d="M0 0h24v24H0V0z"/><path d="M17.66 5.41l.92.92-2.69 2.69-.92-.92 2.69-2.69M17.67 3c-.26 0-.51.1-.71.29l-3.12 3.12-1.93-1.91-1.41 1.41 1.42 1.42L3 16.25V21h4.75l8.92-8.92 1.42 1.42 1.41-1.41-1.92-1.92 3.12-3.12c.4-.4.4-1.03.01-1.42l-2.34-2.34c-.2-.19-.45-.29-.7-.29zM6.92 19L5 17.08l8.06-8.06 1.92 1.92L6.92 19z"/></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/local_ntp/icons/default_theme.svg b/chromium/chrome/browser/resources/local_ntp/icons/default_theme.svg
new file mode 100644
index 00000000000..6ec0f96c49a
--- /dev/null
+++ b/chromium/chrome/browser/resources/local_ntp/icons/default_theme.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="64" height="64"><defs><path d="M32 64C14.34 64 0 49.66 0 32S14.34 0 32 0s32 14.34 32 32-14.34 32-32 32z" id="a"/><linearGradient id="b" gradientUnits="userSpaceOnUse" x1="32" y1="32" x2="32.08" y2="32"><stop offset="0%" stop-color="#fff"/><stop offset="100%" stop-color="#dee1e6"/></linearGradient><clipPath id="c"><use xlink:href="#a"/></clipPath></defs><use xlink:href="#a" fill="url(#b)"/><g clip-path="url(#c)"><use xlink:href="#a" fill-opacity="0" stroke="#dee1e6" stroke-width="2"/></g></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/local_ntp/icons/default_theme_dark.svg b/chromium/chrome/browser/resources/local_ntp/icons/default_theme_dark.svg
new file mode 100644
index 00000000000..70f2abb8705
--- /dev/null
+++ b/chromium/chrome/browser/resources/local_ntp/icons/default_theme_dark.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="64" height="64"><defs><path d="M32 64C14.34 64 0 49.66 0 32S14.34 0 32 0s32 14.34 32 32-14.34 32-32 32z" id="a"/><linearGradient id="b" gradientUnits="userSpaceOnUse" x1="32" y1="32" x2="32.08" y2="32"><stop offset="0%" stop-color="#323639"/><stop offset="100%" stop-color="#202124"/></linearGradient><clipPath id="c"><use xlink:href="#a"/></clipPath></defs><use xlink:href="#a" fill="url(#b)"/><g clip-path="url(#c)"><use xlink:href="#a" fill-opacity="0" stroke="#202124" stroke-width="2"/></g></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp.css b/chromium/chrome/browser/resources/local_ntp/local_ntp.css
index 168a37d7d58..ee6457ca9e8 100644
--- a/chromium/chrome/browser/resources/local_ntp/local_ntp.css
+++ b/chromium/chrome/browser/resources/local_ntp/local_ntp.css
@@ -7,23 +7,18 @@ html {
--md-tile-margin: 16px;
--md-tile-size: 112px;
- /* This will be overridden based on the viewport width, see below.
- * TODO(kristipark): Combine these.
- */
- --column-count: 2;
- --shortcut-column-count: 3;
+ /* This will be overridden based on the viewport width, see below. */
+ --column-count: 3;
- --content-width: calc(
- (var(--column-count) * (var(--tile-width) + var(--tile-margin)))
+ --content-width: calc(var(--column-count) * var(--md-tile-size)
/* We add an extra pixel because rounding errors on different zooms can
* make the width shorter than it should be. */
+ 1px);
- --shortcuts-width: calc(var(--shortcut-column-count) * var(--md-tile-size));
-
+ --logo-color: #eee; /* Background color for alternative logo. */
--logo-height: 200px; /* Normal height of a doodle. */
--logo-margin-top: 56px; /* Expected OGB height, so logo doesn't overlap. */
- --logo-margin-bottom: 29px; /* Between logo and fakebox. */
+ --logo-margin-bottom: 38px; /* Between logo and fakebox. */
/* Initial height determines the margin between the logo and the fakebox. If
* the iframe height exceeds the normal --logo-height, the difference is
@@ -35,9 +30,6 @@ html {
--logo-iframe-height: var(--logo-height);
--logo-iframe-resize-duration: 150ms;
--logo-iframe-width: 500px;
- --tile-height: 128px;
- --tile-margin: 16px;
- --tile-width: 154px;
--mv-notice-time: 10s;
@@ -49,26 +41,26 @@ html {
height: 100%;
}
-html[darkmode=true] body:not(.light-chip) {
- /* These can be overridden by themes. */
- --text-color: rgb(var(--GG200-rgb));
- --text-color-light: rgb(var(--GG200-rgb));
- --text-color-link: rgb(var(--GB400-dark-rgb));
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) {
+ /* These can be overridden by themes. */
+ --text-color: rgb(var(--GG200-rgb));
+ --text-color-light: rgb(var(--GG200-rgb));
+ --text-color-link: rgb(var(--GB400-dark-rgb));
+ }
}
-/* width >= (3 cols * (16px + 154px) - 16px + 200px) */
-@media (min-width: 694px) {
+/* width >= (4 cols * 112px (tile width) + 112px (1 tile margin)) */
+@media (min-width: 560px) {
html {
- --column-count: 3;
- --shortcut-column-count: 4;
+ --column-count: 4;
}
}
-/* width >= (4 cols * (16px + 154px) - 16px + 200px) */
-@media (min-width: 864px) {
+/* width >= (5 cols * 112px (tile width) + 112px (1 tile margin)) */
+@media (min-width: 672px) {
html {
- --column-count: 4;
- --shortcut-column-count: 5;
+ --column-count: 5;
}
}
@@ -114,7 +106,7 @@ button {
* single row, but also works for a row of icons, and works well on small
* screens (like Pixelbook), as well as high-res screens. */
height: 155px;
- left: calc(50% - var(--shortcuts-width)/2);
+ left: calc(50% - var(--content-width)/2);
position: absolute;
top: calc(50% - 155px);
}
@@ -126,73 +118,31 @@ body.hide-fakebox #fakebox {
#fakebox-container {
margin: 0 auto 0 auto;
- width: var(--content-width);
-}
-
-body.remove-fakebox #fakebox-container {
- display: none;
-}
-
-.alternate-fakebox #fakebox-container {
- /* Increase min-width to account for larger font + increased padding: 341px
- * min-width + 50px */
- min-width: 390px;
-}
-
-.show-fakebox-icon.alternate-fakebox #fakebox-container {
/* Increase min-width again to account for the search icon: 390px new
* min-width + additional 20px */
min-width: 410px;
+ width: var(--content-width);
}
#fakebox {
- background-color: rgb(var(--GG100-rgb));
+ background: white;
border-radius: 22px;
+ box-shadow: 0 1px 6px 0 rgba(32, 33, 36, .28);
+ box-sizing: border-box;
cursor: text;
- font-size: 18px;
+ font-size: 16px;
height: 44px;
- line-height: 36px;
margin: 0 auto;
- max-width: 560px;
+ max-width: 584px;
opacity: 1;
position: relative;
- /* Transition should be similar to .mv-tile/.md-tile opacity transition. */
- transition: background-color 300ms ease-in-out, opacity 200ms
-}
-
-.alternate-fakebox-rect #fakebox {
- border-radius: 8px;
-}
-
-html[darkmode=true] body:not(.alternate-fakebox):not(.light-chip) #fakebox {
- background-color: rgb(var(--GG900-rgb));
-}
-
-.alternate-fakebox #fakebox {
- background: white;
- box-shadow: 0 1px 6px 0 rgba(32, 33, 36, .28);
- box-sizing: border-box;
- font-size: 16px;
- line-height: 21px;
- max-width: 584px;
transition: none;
}
-html[darkmode=true] .alternate-fakebox #fakebox {
- box-shadow: 0 1px 6px 0 rgba(32, 33, 36, .78);
-}
-
-#fakebox:hover {
- background-color: rgb(var(--GG200-rgb));
-}
-
-html[darkmode=true] body:not(.alternate-fakebox):not(.light-chip) #fakebox:hover {
- background-color: rgb(42, 43, 46);
-}
-
-.alternate-fakebox #fakebox:hover,
-.alternate-fakebox.fakebox-focused #fakebox {
- background: white;
+@media (prefers-color-scheme: dark) {
+ #fakebox {
+ box-shadow: 0 1px 6px 0 rgba(32, 33, 36, .78);
+ }
}
.non-google-page #fakebox-container {
@@ -222,7 +172,6 @@ html[dir=rtl] #fakebox > input {
-webkit-mask-size: 100%;
background: 24px 24px rgb(117, 117, 117);
bottom: 0;
- display: none;
height: 24px;
left: 0;
margin: auto 0;
@@ -232,59 +181,30 @@ html[dir=rtl] #fakebox > input {
width: 24px;
}
-#fakebox-search-icon.color {
- background-color: rgb(var(--GB600-rgb));
-}
-
-.show-fakebox-icon #fakebox-search-icon {
- display: block;
-}
-
html[dir=rtl] #fakebox-search-icon {
right: 0;
}
#fakebox-text {
- bottom: 4px;
- color: rgb(var(--GG700-rgb));
- font-size: 14px;
+ bottom: 0;
+ color: rgb(117, 117, 117);
+ font-size: 16px;
+ height: 44px;
left: 0;
- margin-top: 1px;
+ line-height: 44px;
+ margin: auto 0;
overflow: hidden;
- padding-inline-start: 20px;
+ padding-inline-start: 48px;
position: absolute;
right: 44px;
text-align: initial;
text-overflow: ellipsis;
- top: 4px;
+ top: 0;
vertical-align: middle;
visibility: inherit;
white-space: nowrap;
}
-html[darkmode=true] body:not(.alternate-fakebox):not(.light-chip) #fakebox-text {
- color: rgb(var(--GG200-rgb));
-}
-
-html[dir=rtl] #fakebox-text {
- left: auto;
- right: 0;
-}
-
-.alternate-fakebox #fakebox-text {
- bottom: 0;
- color: rgb(117, 117, 117);
- font-size: 16px;
- height: 21px;
- margin: auto 0;
- right: 44px;
- top: 0;
-}
-
-.show-fakebox-icon.alternate-fakebox #fakebox-text {
- padding-inline-start: 48px;
-}
-
html[dir=rtl] #fakebox-text {
left: 44px;
right: 0;
@@ -292,56 +212,31 @@ html[dir=rtl] #fakebox-text {
#fakebox-cursor {
background: #333;
- /* Total 20px height: 44px fakebox height - 12px top - 12px bottom */
- bottom: 12px;
- left: 20px;
- position: absolute;
- top: 12px;
- visibility: hidden;
- width: 1px;
-}
-
-html[dir=rtl] #fakebox-cursor {
- left: auto;
- right: 20px;
-}
-
-html[darkmode=true] body:not(.alternate-fakebox):not(.light-chip) #fakebox-cursor {
- background: rgb(var(--GB300-rgb));
-}
-
-.alternate-fakebox #fakebox-cursor {
/* Total 16px height: (46px fakebox height - 2px border) - 14px top - 14px
* bottom */
bottom: 14px;
- top: 14px;
-}
-
-.show-fakebox-icon.alternate-fakebox #fakebox-cursor {
left: 48px;
+ position: absolute;
+ top: 14px;
+ visibility: hidden;
+ width: 1px;
}
-html[dir=rtl] .show-fakebox-icon.alternate-fakebox #fakebox-cursor {
+html[dir=rtl] #fakebox-cursor {
left: auto;
right: 48px;
}
#fakebox-microphone {
background: url(icons/googlemic_clr_24px.svg) no-repeat center;
- background-size: 24px 24px;
+ background-size: 21px 21px;
bottom: 0;
cursor: pointer;
- margin-inline-end: 12px;
+ margin-inline-end: 16px;
padding: 22px 12px 0;
position: absolute;
right: 0;
top: 0;
- width: 28px;
-}
-
-.alternate-fakebox #fakebox-microphone {
- background-size: 21px 21px;
- margin-inline-end: 16px;
width: 21px;
}
@@ -373,17 +268,6 @@ body.fakebox-focused #fakebox-cursor {
visibility: inherit;
}
-.alternate-fakebox #user-content-wrapper {
- /* Reduce margin by new height of fakebox (46px) - old height (44px) = 2px */
- margin-top: -2px;
-}
-
-body.remove-fakebox #user-content {
- /* Total of 48px margin between the logo and MV tiles/suggestions: 29px logo
- * margin-bottom + 32px margin (from #most-visited or #suggestions) - 13px */
- margin-top: -13px;
-}
-
#most-visited {
/* Total of 40px margin between fakebox and MV tiles: 8px fakebox
* margin-bottom + 22px here margin-top + 10px MV margin-top */
@@ -407,7 +291,7 @@ body.remove-fakebox #user-content {
text-align: -webkit-auto;
/* Add 2*6px to account for drop shadow on the tiles. If you change this, also
* change the corresponding padding in most_visited_single.css. */
- width: calc(var(--shortcuts-width) + 12px);
+ width: calc(var(--content-width) + 12px);
}
#mv-notice-container {
@@ -444,16 +328,22 @@ body.remove-fakebox #user-content {
border: 1px solid rgb(var(--GG300-rgb));
/* Necessary for a "pill" shape. Using 50% creates an oval. */
border-radius: 16px;
+ box-sizing: border-box;
font-size: 12px;
height: fit-content;
margin: 0 auto;
+ /* Set min-height in order to prevent the border from disappearing at certain
+ zooms. */
+ min-height: 35px;
opacity: 1;
width: fit-content;
}
-html[darkmode=true] body:not(.light-chip) #mv-notice {
- background-color: rgb(var(--GG900-rgb));
- border-color: rgba(0, 0, 0, 0.1);
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) #mv-notice {
+ background-color: rgb(var(--GG900-rgb));
+ border-color: rgba(0, 0, 0, .1);
+ }
}
#mv-notice span {
@@ -461,12 +351,15 @@ html[darkmode=true] body:not(.light-chip) #mv-notice {
cursor: default;
display: inline-block;
height: auto;
- line-height: 32px;
+ /* Use odd height in order to prevent rounding errors at certain zooms. */
+ line-height: 33px;
vertical-align: unset;
}
-html[darkmode=true] body:not(.light-chip) #mv-notice span {
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) #mv-notice span {
+ color: rgb(var(--GG200-rgb));
+ }
}
/* Links in the notification. */
@@ -481,8 +374,10 @@ html[darkmode=true] body:not(.light-chip) #mv-notice span {
position: relative;
}
-html[darkmode=true] body:not(.light-chip) #mv-notice-links span {
- color: rgb(var(--GB400-dark-rgb));
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) #mv-notice-links span {
+ color: rgb(var(--GB400-dark-rgb));
+ }
}
#mv-notice-links span:focus {
@@ -491,14 +386,16 @@ html[darkmode=true] body:not(.light-chip) #mv-notice-links span {
#mv-notice-links span:hover,
#mv-notice-links span:active {
- background-color: rgba(var(--GB600-rgb), 0.1);
+ background-color: rgba(var(--GB600-rgb), .1);
text-decoration: none;
transition: background-color 200ms;
}
-html[darkmode=true] body:not(.light-chip) #mv-notice-links span:hover,
-html[darkmode=true] body:not(.light-chip) #mv-notice-links span:active {
- background-color: rgba(var(--GB400-dark-rgb), 0.1);
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) #mv-notice-links
+ :-webkit-any(span:hover, span:active) {
+ background-color: rgba(var(--GB400-dark-rgb), .1);
+ }
}
#mv-msg {
@@ -506,9 +403,11 @@ html[darkmode=true] body:not(.light-chip) #mv-notice-links span:active {
padding: 0 16px;
}
-html[darkmode=true] body:not(.light-chip) .default-theme.dark #mv-msg :not(),
-html[darkmode=true] body:not(.light-chip) .default-theme.dark #mv-notice-links :not() span {
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) .default-theme.dark #mv-msg,
+ body:not(.light-chip) .default-theme.dark #mv-notice-links span {
+ color: rgb(var(--GG200-rgb));
+ }
}
#mv-notice.mv-notice-delayed-hide:not(:focus-within) {
@@ -553,8 +452,10 @@ html[dir=rtl] #attribution,
background-color: rgba(255, 255, 255, .75);
}
-html[darkmode=true] .customize-dialog::backdrop {
- background-color: rgba(0, 0, 0, 0.4);
+@media (prefers-color-scheme: dark) {
+ .customize-dialog::backdrop {
+ background-color: rgba(0, 0, 0, .4);
+ }
}
#custom-links-edit-dialog {
@@ -585,68 +486,6 @@ html[darkmode=true] .customize-dialog::backdrop {
width: 100%;
}
-/* The box containing the slider */
-.switch {
- background-color: #fff;
- border-radius: 8px;
- display: inline-block;
- height: 12px;
- left: 3px;
- position: absolute;
- top: 2px;
- transition: background-color linear 80ms;
- width: 28px;
- z-index: 0;
-}
-
-/* Hide default checkbox */
-.switch input {
- display: none;
-}
-
-/* Rounded background element for the toggle */
-.toggle {
- background-color: #ccc;
- border-radius: 34px;
- bottom: 0;
- cursor: pointer;
- display: block;
- left: 0;
- position: absolute;
- right: 0;
- top: 0;
- transition: transform linear 80ms, background-color linear 80ms;
-}
-
-.toggle::before {
- background-color: #fff;
- border-radius: 50%;
- bottom: -2px;
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.4);
- content: '';
- display: block;
- height: 16px;
- left: -6px;
- position: absolute;
- transition: transform linear 80ms, background-color linear 80ms;
- width: 16px;
-}
-
-input:checked + .toggle {
- background-color: rgba(var(--GB600-rgb), .5);
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.4);
-}
-
-input:focus + .toggle {
- box-shadow: 0 0 1px rgb(33, 150, 243);
-}
-
-input:checked + .toggle::before {
- -webkit-transform: translateX(26px);
- background-color: rgb(var(--GB600-rgb));
- transform: translateX(26px);
-}
-
#error-notice-container {
bottom: -50px;
margin-bottom: 16px;
@@ -677,10 +516,12 @@ input:checked + .toggle::before {
width: fit-content;
}
-html[darkmode=true] body:not(.light-chip) #error-notice {
- background-color: rgb(var(--GG900-rgb));
- border-color: rgba(0, 0, 0, 0.1);
- color: rgb(var(--GR500-dark-rgb));
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) #error-notice {
+ background-color: rgb(var(--GG900-rgb));
+ border-color: rgba(0, 0, 0, .1);
+ color: rgb(var(--GR500-dark-rgb));
+ }
}
#error-notice.notice-hide {
@@ -725,8 +566,10 @@ html[dir=rtl] #error-notice.has-link #error-notice-msg {
position: relative;
}
-html[darkmode=true] body:not(.light-chip) #error-notice-link {
- color: rgb(var(--GB400-dark-rgb));
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) #error-notice-link {
+ color: rgb(var(--GB400-dark-rgb));
+ }
}
#error-notice:not(.has-link) #error-notice-link {
@@ -740,14 +583,16 @@ html[darkmode=true] body:not(.light-chip) #error-notice-link {
#error-notice-link:hover,
#error-notice-link:active {
- background-color: rgba(var(--GB600-rgb), 0.1);
+ background-color: rgba(var(--GB600-rgb), .1);
text-decoration: none;
transition: background-color 200ms;
}
-html[darkmode=true] body:not(.light-chip) #error-notice-link:hover,
-html[darkmode=true] body:not(.light-chip) #error-notice-link:active {
- background-color: rgba(var(--GB400-dark-rgb), 0.1);
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) #error-notice-link:hover,
+ body:not(.light-chip) #error-notice-link:active {
+ background-color: rgba(var(--GB400-dark-rgb), .1);
+ }
}
#promo {
@@ -783,10 +628,12 @@ html[darkmode=true] body:not(.light-chip) #error-notice-link:active {
white-space: nowrap;
}
-html[darkmode=true] body:not(.light-chip) #promo > div {
- background-color: rgb(var(--GG900-rgb));
- border-color: rgba(0, 0, 0, 0.1);
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) #promo > div {
+ background-color: rgb(var(--GG900-rgb));
+ border-color: rgba(0, 0, 0, .1);
+ color: rgb(var(--GG200-rgb));
+ }
}
/**
@@ -810,9 +657,10 @@ html[darkmode=true] body:not(.light-chip) #promo > div {
color: rgb(51, 103, 214) !important;
}
-html[darkmode=true] body:not(.light-chip) #promo > div > a,
-html[darkmode=true] body:not(.light-chip) #promo > div > a:visited {
- color: rgb(var(--GB400-dark-rgb)) !important;
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) #promo > div > :-webkit-any(a, a:visited) {
+ color: rgb(var(--GB400-dark-rgb)) !important;
+ }
}
#promo > div > img {
@@ -824,8 +672,10 @@ html[darkmode=true] body:not(.light-chip) #promo > div > a:visited {
width: 24px;
}
-html[darkmode=true] body:not(.light-chip) #promo > div > img {
- background-color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ body:not(.light-chip) #promo > div > img {
+ background-color: rgb(var(--GG200-rgb));
+ }
}
#one-google.show-element,
@@ -838,6 +688,8 @@ html[darkmode=true] body:not(.light-chip) #promo > div > img {
}
#user-content {
+ /* Reduce margin by new height of fakebox (46px) - old height (44px) = 2px */
+ margin-top: -2px;
z-index: -1;
}
@@ -847,56 +699,87 @@ html[darkmode=true] body:not(.light-chip) #promo > div > img {
box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), .3),
0 4px 8px 3px rgba(var(--GG800-rgb), .15);
color: rgb(var(--GG700-rgb));
+ font-size: 0; /* Remove extra spacing between inline-block elements. */
height: 528px;
+ min-width: 800px;
padding: 0;
- width: 800px;
+ user-select: none;
}
-html[darkmode=true] #customization-menu {
- background-color: rgb(41, 42, 45);
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.3),
- 0 4px 8px 3px rgba(0, 0, 0, 0.15);
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ #customization-menu {
+ background-color: rgb(var(--dark-mode-dialog-rgb));
+ box-shadow: var(--dark-mode-shadow);
+ color: rgb(var(--GG200-rgb));
+ }
+}
+
+#customization-menu > div {
+ font-size: 13px;
}
#menu-nav-panel {
display: inline-block;
height: 384px;
left: 0;
+ margin-top: 80px;
vertical-align: top;
width: 192px;
}
.menu-option {
border-radius: 0 16px 16px 0;
+ color: rgb(var(--GG700-rgb));
+ cursor: pointer;
font-size: 14px;
height: 32px;
left: 0;
line-height: 32px;
margin-bottom: 16px;
outline: none;
- user-select: none;
+ text-align: start;
width: 192px;
}
+@media (prefers-color-scheme: dark) {
+ .menu-option {
+ color: rgb(var(--GG200-rgb));
+ }
+}
+
html[dir=rtl] .menu-option {
border-radius: 16px 0 0 16px;
}
.menu-option:hover,
.menu-option:focus {
- background-color: rgba(var(--GB900-rgb), .1);
+ background-color: rgba(var(--GG900-rgb), .1);
+}
+
+@media (prefers-color-scheme: dark) {
+ .menu-option:hover,
+ .menu-option:focus {
+ background-color: rgba(var(--GG500-rgb), .12);
+ }
}
.menu-option:active,
.menu-option.selected {
background-color: rgb(232, 240, 254);
- color: rgb(var(--GB600-rgb));
+ color: rgb(var(--GB700-rgb));
+}
+
+@media (prefers-color-scheme: dark) {
+ .menu-option:active,
+ .menu-option.selected {
+ background-color: rgba(var(--GB200-rgb), .1);
+ color: rgb(var(--GB300-rgb));
+ }
}
.menu-option-icon-wrapper {
display: inline-block;
- height: 20px;
+ height: 32px;
margin-inline-start: 24px;
width: 20px;
}
@@ -913,8 +796,10 @@ html[dir=rtl] .menu-option {
width: 20px;
}
-html[darkmode=true] .menu-option-icon {
- background-color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ .menu-option-icon {
+ background-color: rgb(var(--GG200-rgb));
+ }
}
.menu-option:active .menu-option-icon-wrapper .menu-option-icon,
@@ -922,6 +807,13 @@ html[darkmode=true] .menu-option-icon {
background-color: rgb(var(--GB600-rgb));
}
+@media (prefers-color-scheme: dark) {
+ .menu-option:active .menu-option-icon-wrapper .menu-option-icon,
+ .menu-option.selected .menu-option-icon-wrapper .menu-option-icon {
+ background-color: rgb(var(--GB300-rgb));
+ }
+}
+
#shortcuts-icon {
-webkit-mask-image: url(icons/link.svg);
}
@@ -939,20 +831,18 @@ html[darkmode=true] .menu-option-icon {
height: 32px;
line-height: 32px;
margin-inline-start: 16px;
- text-align: center;
+ max-width: 126px;
+ overflow: hidden;
+ text-overflow: ellipsis;
user-select: none;
+ white-space: nowrap;
}
#menu-header {
- height: 80px;
-}
-
-#menu-title-wrapper {
- display: inline-block;
+ display: flex;
height: 80px;
line-height: 80px;
- position: absolute;
- vertical-align: center;
+ padding-inline-end: 24px;
}
#menu-title {
@@ -961,15 +851,14 @@ html[darkmode=true] .menu-option-icon {
width: fit-content;
}
-.on-img-menu #menu-title {
- margin-inline-start: 16px;
-}
-
#menu-footer {
border-top: 1px solid rgb(var(--GG200-rgb));
bottom: 0;
+ box-sizing: border-box;
color: rgb(var(--GG800-rgb));
+ display: flex;
height: 64px;
+ justify-content: flex-end;
left: 0;
padding-inline-start: 0;
position: absolute;
@@ -978,36 +867,45 @@ html[darkmode=true] .menu-option-icon {
width: 100%;
}
-html[darkmode=true] #menu-footer {
- border-color: rgba(255, 255, 255, 0.1);
+@media (prefers-color-scheme: dark) {
+ #menu-footer {
+ border-color: rgba(255, 255, 255, .1);
+ }
}
-#menu-done {
+#menu-footer > button {
height: 32px;
line-height: 32px;
+}
+
+#menu-done {
margin-inline-end: 16px;
}
#menu-cancel {
- height: 32px;
- line-height: 32px;
margin-inline-end: 8px;
}
#menu-contents {
display: inline-block;
- height: 384px;
- margin-inline-start: 20px;
+ height: 464px;
+ margin-inline-start: 40px;
position: relative;
- width: 584px;
+ width: 568px;
}
.menu-panel {
- height: 100%;
+ height: 384px;
left: 0;
- overflow-y: scroll;
+ /* Pad the content by 5px top/left. This will prevent the focus outline on
+ * tiles from being cut off by overflow-y. */
+ margin-inline-start: -5px;
+ margin-top: -5px;
+ overflow-y: auto;
+ padding-inline-start: 5px;
+ padding-top: 5px;
position: absolute;
- top: 0;
+ top: 80px;
visibility: hidden;
width: 100%;
}
@@ -1027,18 +925,33 @@ html[darkmode=true] #menu-footer {
width: 176px;
}
+/* Remove left/right spacing from the last tile in each row. */
+#backgrounds-menu .bg-sel-tile-bg:nth-of-type(3n),
+#backgrounds-image-menu .bg-sel-tile-bg:nth-of-type(3n) {
+ margin-inline-end: 0;
+}
+
#backgrounds-image-menu .bg-sel-tile-bg {
margin-bottom: 8px;
}
-.selected #backgrounds-default-icon,
+#backgrounds-menu .bg-sel-tile-bg.selected .bg-sel-tile,
#backgrounds-image-menu .bg-sel-tile-bg.selected .bg-sel-tile {
+ box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), .3),
+ 0 4px 8px 3px rgba(var(--GG800-rgb), .15);
height: 144px;
margin: 16px 16px 0 16px;
width: 144px;
}
-#backgrounds-image-menu .bg-sel-tile-bg.selected .bg-sel-tile:focus {
+@media (prefers-color-scheme: dark) {
+ #backgrounds-menu .bg-sel-tile-bg.selected .bg-sel-tile,
+ #backgrounds-image-menu .bg-sel-tile-bg.selected .bg-sel-tile {
+ box-shadow: var(--dark-mode-shadow);
+ }
+}
+
+.using-mouse-nav .bg-sel-tile:focus {
outline: none;
}
@@ -1046,46 +959,58 @@ html[darkmode=true] #menu-footer {
#backgrounds-image-menu .bg-sel-tile {
background-position: center;
border-radius: 4px;
+ cursor: pointer;
}
-#backgrounds-menu .bg-sel-tile-title {
+#customization-menu .bg-sel-tile-title {
background-color: unset;
color: rgb(var(--GG700-rgb));
font-size: 13px;
- height: 30px;
- margin-bottom: -28px;
- padding: 8px 0 24px 0;
+ margin-bottom: -34px;
+ min-height: 30px;
+ padding: 0;
}
-html[darkmode=true] #backgrounds-menu .bg-sel-tile-title {
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ #customization-menu .bg-sel-tile-title {
+ color: rgb(var(--GG200-rgb));
+ }
}
#backgrounds-default.bg-sel-tile-bg {
background-color: white;
- border: 1px solid rgb(var(--GG300-rgb));
- height: 174px;
- margin-inline-end: 6px;
- width: 174px;
+ height: 176px;
+ width: 176px;
}
-#backgrounds-default.selected,
-#backgrounds-image-menu .bg-sel-tile-bg.selected {
+@media (prefers-color-scheme: dark) {
+ #backgrounds-default.bg-sel-tile-bg {
+ background-color: transparent;
+ }
+}
+
+#backgrounds-menu .bg-sel-tile-bg.selected,
+#backgrounds-image-menu .bg-sel-tile-bg.selected {
background-color: rgba(var(--GB900-rgb), .08);
}
-#backgrounds-upload.bg-sel-tile-bg {
- background-color: white;
- border: 1px solid rgb(var(--GG300-rgb));
- height: 174px;
- margin-inline-end: 6px;
- vertical-align: top;
- width: 174px;
+@media (prefers-color-scheme: dark) {
+ #backgrounds-default.selected,
+ #backgrounds-menu .bg-sel-tile-bg.selected,
+ #backgrounds-image-menu .bg-sel-tile-bg.selected {
+ background-color: rgba(var(--GB200-rgb), .1);
+ }
}
-#menu-back-wrapper {
- display: inline-block;
- height: 80px;
+#backgrounds-menu,
+#colors-menu {
+ /* Remove extra spacing between inline-block elements. */
+ font-size: 0;
+}
+
+#backgrounds-upload.bg-sel-tile-bg {
+ background-color: transparent;
+ vertical-align: top;
}
#menu-back {
@@ -1093,6 +1018,7 @@ html[darkmode=true] #backgrounds-menu .bg-sel-tile-title {
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: 20px;
background-color: rgb(var(--GG900-rgb));
+ cursor: pointer;
height: 20px;
margin-inline-start: 8px;
margin-top: 8px;
@@ -1100,29 +1026,25 @@ html[darkmode=true] #backgrounds-menu .bg-sel-tile-title {
width: 20px;
}
-html[darkmode=true] #menu-back {
- background-color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ #menu-back {
+ background-color: rgb(var(--GG200-rgb));
+ }
}
#menu-back-circle {
border-radius: 50%;
- display: inline-block;
+ display: none;
height: 36px;
- margin-inline-start: 192px;
+ margin-inline-end: 4px;
+ margin-inline-start: -12px;
margin-top: 22px;
outline: none;
- visibility: hidden;
width: 36px;
}
-html[darkmode=true] #menu-back-circle:active,
-html[darkmode=true] #menu-back-circle:focus {
- background: rgb(var(--GG800-rgb));
-}
-
.on-img-menu #menu-back-circle {
- margin-inline-start: 212px;
- visibility: visible;
+ display: inline-block;
}
#menu-back-circle:active,
@@ -1132,8 +1054,15 @@ html[darkmode=true] #menu-back-circle:focus {
background-size: 36px 36px;
}
-html[darkmode=true] #menu-back {
- background-color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ #menu-back-circle:active,
+ #menu-back-circle:focus {
+ background: rgb(var(--GG800-rgb));
+ }
+
+ #menu-back {
+ background-color: rgb(var(--GG200-rgb));
+ }
}
html[dir=rtl] #menu-back {
@@ -1141,23 +1070,49 @@ html[dir=rtl] #menu-back {
}
#backgrounds-upload-icon {
+ background: white;
+ border: 1px solid rgb(var(--GG300-rgb));
+ box-sizing: border-box;
+ display: inline-block;
+ left: 0;
+ opacity: 1;
+ top: 0;
+}
+
+@media (prefers-color-scheme: dark) {
+ #backgrounds-upload-icon {
+ background-color: rgb(var(--dark-mode-bg-rgb));
+ border-color: rgb(var(--GG700-rgb));
+ }
+}
+
+#backgrounds-upload-arrow {
-webkit-mask-image: url(icons/upload.svg);
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: 100%;
background: 32px 32px rgb(var(--GG700-rgb));
height: 32px;
- margin-bottom: 8px;
- margin-inline-start: 72px;
- margin-top: 61px;
+ margin: 61px auto 8px;
width: 32px;
}
+.selected #backgrounds-upload-arrow {
+ margin-top: 45px;
+}
+
#backgrounds-upload-text {
color: rgb(var(--GG700-rgb));
+ font-size: 13px;
text-align: center;
width: 100%;
}
+@media (prefers-color-scheme: dark) {
+ #backgrounds-upload-text {
+ color: inherit;
+ }
+}
+
#customization-menu .bg-sel-tile .selected-circle {
height: 20px;
left: initial;
@@ -1174,58 +1129,99 @@ html[dir=rtl] #customization-menu .bg-sel-tile .selected-circle {
#customization-menu .bg-sel-tile .selected-check {
height: 24px;
left: initial;
- right: 0;
- top: 0;
+ right: 9px;
+ top: 7px;
width: 24px;
}
html[dir=rtl] #customization-menu .bg-sel-tile .selected-check {
- left: 0;
+ left: 9px;
right: initial;
}
#backgrounds-default-icon {
background-color: white;
background-repeat: no-repeat;
- height: 174px;
+ border: 1px solid rgb(var(--GG300-rgb));
+ box-sizing: border-box;
+ margin: auto;
opacity: 1;
- width: 174px;
}
-#backgrounds-default-icon-header {
+@media (prefers-color-scheme: dark) {
+ #backgrounds-default-icon {
+ background-color: rgb(var(--dark-mode-dialog-rgb));
+ border-color: rgb(var(--GG700-rgb));
+ }
+
+ .selected #backgrounds-default-icon {
+ border-color: transparent;
+ }
+}
+
+.mini-page {
+ margin: auto;
+ padding-top: 26px;
+ width: fit-content;
+}
+
+.mini-header {
-webkit-mask-image: url(icons/header.svg);
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: 100%;
- background-color: rgb(var(--GG500-rgb));
- height: 50px;
- margin-inline-start: 17px;
- margin-top: 24px;
- position: absolute;
- width: 140px;
+ background-color: rgb(var(--GG300-rgb));
+ height: 40px;
+ width: 130px;
}
-#backgrounds-default-icon-shortcuts {
+.mini-header-colorful {
+ background-image: url(icons/colored_header.svg);
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: 100%;
+ height: 40px;
+ width: 130px;
+}
+
+@media (prefers-color-scheme: dark) {
+ .mini-header-colorful {
+ -webkit-mask-image: url(icons/colored_header.svg);
+ -webkit-mask-repeat: no-repeat;
+ -webkit-mask-size: 100%;
+ background: white;
+ }
+}
+
+.mini-shortcuts {
-webkit-mask-image: url(icons/shortcut-circles.svg);
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: 100%;
- background-color: rgb(var(--GG500-rgb));
- height: 50px;
- margin-inline-start: 17px;
- margin-top: 86px;
- position: absolute;
- width: 140px;
+ background-color: rgb(var(--GG300-rgb));
+ height: 42px;
+ margin-inline-start: 7px;
+ margin-top: 12px;
+ width: 116px;
}
-.selected #backgrounds-default-icon-header,
-.selected #backgrounds-default-icon-shortcuts {
- margin-inline-start: 14px;
- width: 116px;
+#backgrounds-default:not(.selected) .mini-page {
+ padding-top: 32px;
+}
+
+#backgrounds-default:not(.selected) .mini-header,
+#backgrounds-default:not(.selected) .mini-header-colorful {
+ height: 48px;
+ width: 156px;
+}
+
+#backgrounds-default:not(.selected) .mini-shortcuts {
+ height: 50px;
+ margin-inline-start: 8px;
+ margin-top: 14px;
+ width: 140px;
}
#shortcuts-menu {
line-height: 20px;
- overflow-y: unset;
- width: calc(100% - 24px);
}
#sh-options {
@@ -1233,31 +1229,43 @@ html[dir=rtl] #customization-menu .bg-sel-tile .selected-check {
}
.sh-option {
- width: 268px;
-}
-
-#sh-option-cl {
margin-inline-end: 9px;
-}
-
-.sh-option-select {
- position: absolute;
- visibility: none;
+ width: 268px;
}
.sh-option-image {
- background-color: white;
border: 1px solid rgb(var(--GG300-rgb));
border-radius: 4px;
+ box-sizing: border-box;
+ cursor: pointer;
height: 176px;
position: relative;
width: 268px;
}
+@media (prefers-color-scheme: dark) {
+ .sh-option-image {
+ border-color: rgb(var(--GG700-rgb));
+ }
+}
+
+.selected .sh-option-image {
+ background-color: rgb(var(--GB050-rgb));
+ border-color: rgb(var(--GB600-rgb));
+}
+
+@media (prefers-color-scheme: dark) {
+ .selected .sh-option-image {
+ background-color: rgba(var(--GB200-rgb), .1);
+ border-color: rgb(var(--GB300-rgb));
+ }
+}
+
.sh-option-mini {
background-color: white;
border: 1px solid rgb(var(--GG300-rgb));
border-radius: 4px;
+ box-sizing: border-box;
height: 144px;
position: absolute;
right: 40px;
@@ -1265,11 +1273,44 @@ html[dir=rtl] #customization-menu .bg-sel-tile .selected-check {
width: 144px;
}
+@media (prefers-color-scheme: dark) {
+ .sh-option-mini {
+ background-color: rgb(var(--dark-mode-dialog-rgb));
+ border-color: rgb(var(--GG700-rgb));
+ }
+}
+
html[dir=rtl] .sh-option-mini {
left: 40px;
right: unset;
}
+.selected .sh-option-mini {
+ box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), .3),
+ 0 4px 8px 3px rgba(var(--GG800-rgb), .15);
+}
+
+@media (prefers-color-scheme: dark) {
+ .selected .sh-option-mini {
+ border-color: transparent;
+ box-shadow: var(--dark-mode-shadow);
+ }
+}
+
+.sh-option-mini .mini-shortcuts {
+ background-color: rgb(var(--GG500-rgb));
+}
+
+.selected .sh-option-mini .mini-shortcuts {
+ background-color: rgb(var(--GB600-rgb));
+}
+
+@media (prefers-color-scheme: dark) {
+ .selected .sh-option-mini .mini-shortcuts {
+ background-color: rgb(var(--GB300-rgb));
+ }
+}
+
.sh-option-icon {
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: 100%;
@@ -1293,15 +1334,56 @@ html[dir=rtl] .sh-option-icon {
right: 16px;
}
-.sh-title {
+@media (prefers-color-scheme: dark) {
+ .sh-option-icon {
+ background-color: rgb(var(--GG700-rgb));
+ }
+}
+
+.selected .sh-option-icon {
+ background-color: rgba(var(--GB600-rgb), .24);
+}
+
+@media (prefers-color-scheme: dark) {
+ .selected .sh-option-icon {
+ background-color: rgb(var(--GB300-rgb));
+ }
+}
+
+.sh-option-image .selected-circle {
+ box-shadow: 0 3px 6px 1px rgba(0, 0, 0, .16),
+ 0 1px 2px 1px rgba(0, 0, 0, .23);
+ height: 22px;
+ left: 209px;
+ top: 9px;
+ width: 22px;
+}
+
+html[dir=rtl] .sh-option-image .selected-circle {
+ left: 0;
+ right: 209px;
+}
+
+.sh-option-image .selected-check {
+ left: initial;
+ right: 32px;
+ top: 6px;
+}
+
+html[dir=rtl] .sh-option-image .selected-check {
+ left: 32px;
+ right: initial;
+}
+
+.sh-option-title {
font-weight: bold;
margin: 8px 0;
}
#sh-hide {
- background-color: white;
border: 1px solid rgb(var(--GG300-rgb));
border-radius: 4px;
+ box-sizing: border-box;
display: flex;
height: 64px;
margin-top: 24px;
@@ -1309,6 +1391,26 @@ html[dir=rtl] .sh-option-icon {
width: 100%;
}
+@media (prefers-color-scheme: dark) {
+ #sh-hide {
+ border-color: rgb(var(--GG700-rgb));
+ }
+}
+
+#sh-hide.selected {
+ background-color: rgb(var(--GB050-rgb));
+ border-color: rgb(var(--GB600-rgb));
+ color: rgb(var(--GB600-rgb));
+}
+
+@media (prefers-color-scheme: dark) {
+ #sh-hide.selected {
+ background-color: rgba(var(--GB200-rgb), .1);
+ border-color: rgb(var(--GB300-rgb));
+ color: rgb(var(--GB300-rgb));
+ }
+}
+
#sh-hide > div {
margin-bottom: auto;
margin-top: auto;
@@ -1325,11 +1427,366 @@ html[dir=rtl] .sh-option-icon {
width: 24px;
}
+.selected #sh-hide-icon {
+ background-color: rgb(var(--GB600-rgb));
+}
+
+@media (prefers-color-scheme: dark) {
+ .selected #sh-hide-icon {
+ background-color: rgb(var(--GB300-rgb));
+ }
+}
+
#sh-hide-title {
font-weight: bold;
}
-#sh-hide-toggle {
+#sh-hide-toggle-wrapper {
+ height: 16px;
margin-inline-end: 20px;
margin-inline-start: auto;
+ position: relative;
+ width: 34px;
+}
+
+/* The toggle's container. */
+.switch {
+ background-color: white;
+ border-radius: 8px;
+ display: inline-block;
+ height: 12px;
+ left: 3px;
+ position: absolute;
+ top: 2px;
+ transition: background-color linear 80ms;
+ width: 28px;
+ z-index: 0;
+}
+
+@media (prefers-color-scheme: dark) {
+ .switch {
+ background-color: rgb(var(--dark-mode-dialog-rgb));
+ }
+}
+
+/* Hide the toggle's default checkbox. */
+.switch input {
+ opacity: 0;
+}
+
+/* The slider for the toggle. */
+.toggle {
+ background-color: #ccc;
+ border-radius: 34px;
+ bottom: 0;
+ cursor: pointer;
+ display: block;
+ left: 0;
+ position: absolute;
+ right: 0;
+ top: 0;
+ transition: transform linear 80ms, background-color linear 80ms;
+}
+
+/* The knob for the toggle. */
+.toggle .knob {
+ background-color: white;
+ border-radius: 50%;
+ bottom: -2px;
+ box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .4);
+ content: '';
+ display: block;
+ height: 16px;
+ left: -3px;
+ position: absolute;
+ transition: transform linear 80ms, background-color linear 80ms;
+ width: 16px;
+}
+
+/* Gray/blue highlight around the knob. */
+.toggle .highlight {
+ background-color: rgb(128, 134, 139);
+ border-radius: 50%;
+ height: 40px;
+ left: -15px;
+ opacity: 0;
+ position: absolute;
+ top: -14px;
+ transition: transform linear 80ms, opacity linear 80ms;
+ width: 40px;
+}
+
+@media (prefers-color-scheme: dark) {
+ .toggle .highlight {
+ background-color: rgb(var(--GG300-rgb));
+ }
+}
+
+input:checked + .toggle {
+ background-color: rgba(var(--GB600-rgb), .5);
+}
+
+@media (prefers-color-scheme: dark) {
+ input:checked + .toggle {
+ background-color: rgba(var(--GB300-rgb), .5);
+ }
+}
+
+input:focus + .toggle {
+ box-shadow: 0 0 1px rgb(33, 150, 243);
+}
+
+input:active + .toggle .highlight,
+#customization-menu:not(.using-mouse-nav) input:focus + .toggle .highlight {
+ opacity: .15;
+}
+
+@media (prefers-color-scheme: dark) {
+ input:active + .toggle .highlight,
+ #customization-menu:not(.using-mouse-nav) input:focus + .toggle .highlight {
+ opacity: .4;
+ }
+}
+
+input:checked + .toggle .knob,
+input:checked + .toggle .highlight {
+ background-color: rgb(var(--GB600-rgb));
+ transform: translateX(18px);
+}
+
+@media (prefers-color-scheme: dark) {
+ input:checked + .toggle .knob,
+ input:checked + .toggle .highlight {
+ background-color: rgb(var(--GB300-rgb));
+ }
+}
+
+#colors-menu {
+ --check-mark-size: 20px;
+ --custom-color-border: rgb(var(--GG300-rgb));
+ --custom-color-dark: rgb(var(--GG100-rgb));
+ --custom-color-light: white;
+ --tile-size: 64px;
+ --tile-margin: 25px;
+}
+
+#colors-menu .bg-sel-tile-bg {
+ background-color: unset;
+ border-radius: 50%;
+ box-sizing: border-box;
+ cursor: pointer;
+ height: var(--tile-size);
+ margin-bottom: var(--tile-margin);
+ margin-inline-end: var(--tile-margin);
+ margin-inline-start: 0;
+ margin-top: 0;
+ width: var(--tile-size);
+}
+
+#colors-menu .bg-sel-tile-bg.selected {
+ box-shadow: 0 0 0 4px rgba(var(--GB600-rgb), .4);
+}
+
+@media (prefers-color-scheme: dark) {
+ #colors-menu .bg-sel-tile-bg.selected {
+ box-shadow: 0 0 0 4px rgba(var(--GB600-rgb), .4);
+ }
+}
+
+/*
+ To avoid circle showing behind the checkmark, draw it 2px smaller and 1px
+ below so that it is always 1px smaller then the checkmark from all sides.
+ */
+#colors-menu .bg-sel-tile .selected-circle {
+ height: calc(var(--check-mark-size) - 2px);
+ right: 0;
+ top: 1px;
+ width: calc(var(--check-mark-size) - 2px);
+}
+
+html[dir=rtl] #colors-menu .bg-sel-tile .selected-circle {
+ left: 0;
+}
+
+#colors-menu .bg-sel-tile .selected-check {
+ background: url(icons/check_circle.svg) no-repeat center;
+ background-size: var(--check-mark-size) var(--check-mark-size);
+ height: var(--check-mark-size);
+ right: 0;
+ top: 0;
+ width: var(--check-mark-size);
+}
+
+html[dir=rtl] #colors-menu .bg-sel-tile .selected-check {
+ left: 0;
+}
+
+@media (prefers-color-scheme: dark) {
+ #colors-menu .bg-sel-tile .selected-check::after {
+ -webkit-mask-image: url(icons/check_circle.svg);
+ -webkit-mask-size: var(--check-mark-size);
+ height: var(--check-mark-size);
+ width: var(--check-mark-size);
+ }
+}
+
+#colors-default-icon {
+ background-image: url(icons/default_theme.svg);
+ background-repeat: no-repeat;
+ background-size: contain;
+ opacity: 1;
+}
+
+@media (prefers-color-scheme: dark) {
+ #colors-default-icon {
+ background-image: url(icons/default_theme_dark.svg);
+ }
+}
+
+#colors-theme {
+ border: 1px solid rgb(var(--GG200-rgb));
+ border-radius: 4px;
+ display: none;
+ height: 64px;
+ margin-bottom: 24px;
+ max-width: 544px;
+ width: 100%;
+}
+
+@media (prefers-color-scheme: dark) {
+ #colors-theme {
+ border-color: rgb(var(--GG700-rgb));
+ }
+}
+
+#colors-theme.visible {
+ display: flex;
+ font-size: small;
+}
+
+#colors-theme > * {
+ margin-bottom: auto;
+ margin-top: auto;
+}
+
+#colors-theme-icon {
+ -webkit-mask-image: url(icons/brush.svg);
+ -webkit-mask-repeat: no-repeat;
+ -webkit-mask-size: 100%;
+ background-color: rgb(var(--GG700-rgb));
+ height: 24px;
+ margin-inline-end: 20px;
+ margin-inline-start: 24px;
+ width: 24px;
+}
+
+@media (prefers-color-scheme: dark) {
+ #colors-theme-icon {
+ background-color: rgb(var(--GG200-rgb));
+ }
+}
+
+#colors-theme-name {
+ font-weight: bold;
+}
+
+#colors-theme-link {
+ margin-inline-end: 24px;
+ margin-inline-start: auto;
+ text-decoration: none;
+}
+
+#colors-theme-link-icon {
+ -webkit-mask-image: url(../../../../ui/webui/resources/images/open_in_new.svg);
+ -webkit-mask-repeat: no-repeat;
+ -webkit-mask-size: 100%;
+ background-color: rgb(var(--GG700-rgb));
+ height: 20px;
+ width: 20px;
+}
+
+@media (prefers-color-scheme: dark) {
+ #colors-theme-link-icon {
+ background-color: rgb(var(--GG200-rgb));
+ }
+}
+
+#colors-theme-uninstall {
+ height: fit-content;
+ margin-inline-end: 16px;
+}
+
+#color-picker-container.visible {
+ display: inline-block;
+}
+
+#color-picker-container {
+ display: none;
+ vertical-align: top;
+}
+
+#color-picker-tile {
+ background-color: var(--custom-color-dark);
+ border: 1px solid var(--custom-color-border);
+ border-radius: 50%;
+ box-sizing: border-box;
+ opacity: 1;
+}
+
+#color-picker-icon {
+ -webkit-mask-image: url(icons/colorize.svg);
+ -webkit-mask-repeat: no-repeat;
+ -webkit-mask-size: 100%;
+ background-color: rgb(var(--GG700-rgb));
+ display: inline-block;
+ height: 20px;
+ /* Position the icon in the middle with offset of half its size. */
+ left: calc(50% - 10px);
+ position: absolute;
+ /* Position the icon in the middle with offset of half its size. */
+ top: calc(50% - 10px);
+ width: 20px;
+}
+
+#color-picker-icon.white {
+ background-color: white;
+}
+
+#left-semicircle {
+ background-color: var(--custom-color-light);
+ border-bottom-left-radius: var(--tile-size);
+ border-top-left-radius: var(--tile-size);
+ display: inline-block;
+ height: 100%;
+ width: 50%;
+}
+
+html[dir=rtl] #left-semicircle {
+ border-bottom-left-radius: 0;
+ border-bottom-right-radius: var(--tile-size);
+ border-top-left-radius: 0;
+ border-top-right-radius: var(--tile-size);
+}
+
+#refresh-daily-wrapper {
+ display: none;
+ margin-inline-start: auto;
+}
+
+.on-img-menu #refresh-daily-wrapper {
+ display: flex;
+}
+
+#refresh-toggle-wrapper {
+ height: 16px;
+ margin-inline-end: 12px;
+ margin-top: 31px;
+ position: relative;
+ width: 34px;
+}
+
+#refresh-text {
+ font-size: 16px;
+ user-select: none;
+ width: fit-content;
}
diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp.html b/chromium/chrome/browser/resources/local_ntp/local_ntp.html
index 5724a10816f..f394f37fe88 100644
--- a/chromium/chrome/browser/resources/local_ntp/local_ntp.html
+++ b/chromium/chrome/browser/resources/local_ntp/local_ntp.html
@@ -6,7 +6,7 @@
<head>
<link rel="stylesheet" href="chrome-search://local-ntp/animations.css"></link>
<link rel="stylesheet" href="chrome-search://local-ntp/local-ntp-common.css"></link>
- <link rel="stylesheet" href="chrome-search://local-ntp/custom-backgrounds.css"></link>
+ <link rel="stylesheet" href="chrome-search://local-ntp/customize.css"></link>
<link rel="stylesheet" href="chrome-search://local-ntp/doodles.css"></link>
<link rel="stylesheet" href="chrome-search://local-ntp/local-ntp.css"></link>
<link rel="stylesheet" href="chrome-search://local-ntp/theme.css"></link>
@@ -18,8 +18,8 @@
integrity="$i18n{animationsIntegrity}"></script>
<script src="chrome-search://local-ntp/config.js"
integrity="$i18n{configDataIntegrity}"></script>
- <script src="chrome-search://local-ntp/custom-backgrounds.js"
- integrity="$i18n{localNtpCustomBgIntegrity}"></script>
+ <script src="chrome-search://local-ntp/customize.js"
+ integrity="$i18n{localNtpCustomizeIntegrity}"></script>
<script src="chrome-search://local-ntp/doodles.js"
integrity="$i18n{doodlesIntegrity}"></script>
<script src="chrome-search://local-ntp/local-ntp.js"
@@ -32,6 +32,7 @@
</head>
<body>
<div id="custom-bg"></div>
+ <div id="custom-bg-preview"></div>
<!-- Container for the OneGoogleBar HTML. -->
<div id="one-google"></div>
@@ -44,9 +45,11 @@
<!-- A doodle, if any: its link and image. -->
<div id="logo-doodle">
<div id="logo-doodle-container">
- <button id="logo-doodle-button">
- <img id="logo-doodle-image" tabindex="-1"></img>
- </button>
+ <div id="logo-doodle-wrapper">
+ <button id="logo-doodle-button">
+ <img id="logo-doodle-image" tabindex="-1"></img>
+ </button>
+ </div>
</div>
<iframe id="logo-doodle-iframe" scrolling="no"></iframe>
<!-- A spinner, prompting the doodle. Visible on NTPs with customized
@@ -71,14 +74,11 @@
</div>
</div>
- <!-- TODO(crbug/944624): Remove wrapper after experiment is complete. -->
- <div id="user-content-wrapper">
- <div id="user-content">
- <!-- Search suggestions will be inserted here. -->
- <div id="most-visited">
- <!-- The container for the tiles. The MV iframe goes in here. -->
- <div id="mv-tiles"></div>
- </div>
+ <div id="user-content">
+ <!-- Search suggestions will be inserted here. -->
+ <div id="most-visited">
+ <!-- The container for the tiles. The MV iframe goes in here. -->
+ <div id="mv-tiles"></div>
</div>
</div>
@@ -106,7 +106,7 @@
<div id="edit-bg" tabindex="0" role="button" hidden>
<div id="edit-bg-icon"></div>
- <span id="edit-bg-text"></span>
+ <span id="edit-bg-text">$i18n{customizeButton}</span>
</div>
<a id="custom-bg-attr"></a>
@@ -170,70 +170,121 @@
</dialog>
<dialog id="customization-menu" class="customize-dialog">
- <div id="menu-header">
- <div id="menu-back-wrapper">
- <div id="menu-back-circle" tabindex="0">
- <div id="menu-back"></div>
- </div>
- </div>
- <div id="menu-title-wrapper">
- <div id="menu-title">$i18n{customizeMenuTitle}</div>
- </div>
- </div>
- <div id="menu-nav-panel">
- <div id="backgrounds-button" class="menu-option selected" tabindex="0">
+ <div id="menu-nav-panel" role="tablist" aria-label="$i18n{customizeMenu}">
+ <button id="backgrounds-button" class="menu-option" tabindex="0"
+ role="tab" aria-controls="backgrounds-menu backgrounds-image-menu"
+ aria-selected="true" aria-labelledby="backgrounds-menu-option"
+ title="$i18n{backgroundsOption}">
<div class="menu-option-icon-wrapper">
<div id="backgrounds-icon" class="menu-option-icon"></div>
</div>
- <div class="menu-option-label">$i18n{backgroundsOption}</div>
- </div>
- <div id="shortcuts-button" class="menu-option" tabindex="0">
+ <div id="backgrounds-menu-option" class="menu-option-label">
+ $i18n{backgroundsOption}
+ </div>
+ </button>
+ <button id="shortcuts-button" class="menu-option" tabindex="0" role="tab"
+ aria-controls="shortcuts-menu" aria-selected="false"
+ aria-labelledby="shortcuts-menu-option"
+ title="$i18n{shortcutsOption}">
<div class="menu-option-icon-wrapper">
<div id="shortcuts-icon" class="menu-option-icon"></div>
</div>
- <div class="menu-option-label">$i18n{shortcutsOption}</div>
- </div>
- <div id="colors-button" class="menu-option" tabindex="0">
+ <div id="shortcuts-menu-option" class="menu-option-label">
+ $i18n{shortcutsOption}
+ </div>
+ </button>
+ <button id="colors-button" class="menu-option" tabindex="0" role="tab"
+ aria-controls="colors-menu" aria-selected="false"
+ aria-labelledby="colors-menu-option" title="$i18n{colorsOption}">
<div class="menu-option-icon-wrapper">
<div id="colors-icon" class="menu-option-icon"></div>
</div>
- <div class="menu-option-label">$i18n{colorsOption}</div>
- </div>
+ <div id="colors-menu-option" class="menu-option-label">
+ $i18n{colorsOption}
+ </div>
+ </button>
</div>
<div id="menu-contents">
- <div id="backgrounds-menu" class="menu-panel">
+ <div id="menu-header">
+ <div id="menu-back-circle" tabindex="0" role="button"
+ aria-label="$i18n{backLabel}" title="$i18n{backLabel}">
+ <div id="menu-back"></div>
+ </div>
+ <div id="menu-title">$i18n{customizeMenu}</div>
+ <div id="refresh-daily-wrapper">
+ <div id="refresh-toggle-wrapper" title="$i18n{refreshDaily}">
+ <label class="switch">
+ <input id="refresh-daily-toggle" type="checkbox"
+ aria-labelledby="refresh-text"></input>
+ <span class="toggle">
+ <div class="knob"></div>
+ <div class="highlight"></div>
+ </span>
+ </label>
+ </div>
+ <div id="refresh-text">$i18n{refreshDaily}</div>
+ </div>
+ </div>
+ <div id="backgrounds-menu" class="menu-panel" tabindex="0"
+ role="tabpanel" aria-label="$i18n{backgroundsOption}">
<div id="backgrounds-upload" class="bg-sel-tile-bg">
- <div id="backgrounds-upload-icon"></div>
- <div id="backgrounds-upload-text">$i18n{uploadImage}</div>
+ <div id="backgrounds-upload-icon" class="bg-sel-tile" tabindex="-1"
+ role="button" aria-label="$i18n{uploadImage}"
+ title="$i18n{uploadImage}" aria-pressed="false">
+ <div id="backgrounds-upload-arrow"></div>
+ <div id="backgrounds-upload-text">$i18n{uploadImage}</div>
+ </div>
</div>
<div id="backgrounds-default" class="bg-sel-tile-bg">
- <div id="backgrounds-default-icon" class="bg-sel-tile">
- <div id="backgrounds-default-icon-header"></div>
- <div id="backgrounds-default-icon-shortcuts"></div>
+ <div id="backgrounds-default-icon" class="bg-sel-tile" tabindex="-1"
+ role="button" aria-label="$i18n{noBackground}"
+ title="$i18n{noBackground}" aria-pressed="false">
+ <div class="mini-page">
+ <div class="mini-header-colorful"></div>
+ <div class="mini-shortcuts"></div>
+ </div>
</div>
<div class="bg-sel-tile-title">$i18n{noBackground}</div>
</div>
</div>
- <div id="backgrounds-image-menu" class="menu-panel"></div>
- <div id="shortcuts-menu" class="menu-panel">
+ <div id="backgrounds-image-menu" class="menu-panel" tabindex="0"
+ role="tabpanel" aria-label="$i18n{backgroundsOption}"></div>
+ <div id="shortcuts-menu" class="menu-panel" tabindex="0" role="tabpanel"
+ aria-label="$i18n{shortcutsOption}">
<div id="sh-options">
- <div id="sh-option-cl" class="sh-option">
- <div class="sh-option-image">
+ <div class="sh-option">
+ <div id="sh-option-cl" class="sh-option-image" tabindex="-1"
+ role="button" aria-pressed="false"
+ aria-labelledby="sh-option-cl-title" title="$i18n{myShortcuts}">
<div class="sh-option-icon"></div>
- <div class="sh-option-mini"></div>
- <div class="sh-option-select"></div>
+ <div class="sh-option-mini">
+ <div class="mini-page">
+ <div class="mini-header"></div>
+ <div class="mini-shortcuts"></div>
+ </div>
+ </div>
</div>
- <div class="sh-title">$i18n{myShortcuts}</div>
- $i18n{shortcutsCurated}
+ <div id="sh-option-cl-title" class="sh-option-title">
+ $i18n{myShortcuts}
+ </div>
+ $i18n{shortcutsCurated}
</div>
- <div id="sh-option-mv" class="sh-option">
- <div class="sh-option-image">
+ <div class="sh-option">
+ <div id="sh-option-mv" class="sh-option-image" tabindex="-1"
+ role="button" aria-pressed="false"
+ aria-labelledby="sh-option-mv-title" title="$i18n{mostVisited}">
<div class="sh-option-icon"></div>
- <div class="sh-option-mini"></div>
- <div class="sh-option-select"></div>
+ <div class="sh-option-mini">
+ <div class="mini-page">
+ <div class="mini-header"></div>
+ <div class="mini-shortcuts"></div>
+ </div>
+ </div>
+ </div>
+ <div id="sh-option-mv-title" class="sh-option-title">
+ $i18n{mostVisited}
</div>
- <div class="sh-title">$i18n{mostVisited}</div>
- $i18n{shortcutsSuggested}
+ $i18n{shortcutsSuggested}
</div>
</div>
<div id="sh-hide">
@@ -242,18 +293,58 @@
<div id="sh-hide-title">$i18n{hideShortcuts}</div>
$i18n{hideShortcutsDesc}
</div>
- <div id="sh-hide-toggle">
- <input type="checkbox"></input>
+ <div id="sh-hide-toggle-wrapper" title="$i18n{hideShortcuts}">
+ <label class="switch">
+ <input id="sh-hide-toggle" type="checkbox" tabindex="-1"
+ aria-labelledby="sh-hide-title"></input>
+ <span class="toggle">
+ <div class="knob"></div>
+ <div class="highlight"></div>
+ </span>
+ </label>
+ </div>
+ </div>
+ </div>
+ <div id="colors-menu" class="menu-panel" tabindex="0" role="tabpanel"
+ aria-label="$i18n{colorsOption}">
+ <div id="colors-theme" tabindex="0">
+ <div id="colors-theme-icon"></div>
+ <div>
+ <div id="colors-theme-name"></div>
+ $i18n{installedThemeDesc}
+ </div>
+ <a id="colors-theme-link" target="_blank">
+ <div id="colors-theme-link-icon" > </div>
+ </a>
+ <button id="colors-theme-uninstall" class="paper secondary">
+ $i18n{uninstallButton}
+ </button>
+ </div>
+ <div id="color-picker-container" class="bg-sel-tile-bg">
+ <div id="color-picker-tile" class="bg-sel-tile" tabindex="-1"
+ aria-label="$i18n{colorPickerLabel}"
+ title="$i18n{colorPickerLabel}"
+ role="button" aria-pressed="false">
+ <div id="left-semicircle"></div>
+ <div id="color-picker-icon"></div>
+ <input id="color-picker" type="color" style="display:none">
+ </input>
</div>
</div>
+ <div id="colors-default" class="bg-sel-tile-bg">
+ <div id="colors-default-icon" class="bg-sel-tile" tabindex="-1"
+ aria-label="$i18n{defaultThemeLabel}"
+ title="$i18n{defaultThemeLabel}"
+ role="button" aria-pressed="false"></div>
+ </div>
</div>
- <div id="colors-menu" class="menu-panel"></div>
</div>
<div id="menu-footer">
- <button id="menu-cancel" class="bg-sel-footer-button paper secondary
- ripple">$i18n{cancelButton}</button>
+ <button id="menu-cancel"
+ class="bg-sel-footer-button paper secondary ripple"
+ title="$i18n{cancelButton}">$i18n{cancelButton}</button>
<button id="menu-done" class="bg-sel-footer-button paper primary ripple"
- disabled>$i18n{doneButton}</button>
+ title="$i18n{doneButton}">$i18n{doneButton}</button>
</div>
</dialog>
diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp.js b/chromium/chrome/browser/resources/local_ntp/local_ntp.js
index b0cb0024333..0622671e086 100644
--- a/chromium/chrome/browser/resources/local_ntp/local_ntp.js
+++ b/chromium/chrome/browser/resources/local_ntp/local_ntp.js
@@ -2,12 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-
/**
* @fileoverview The local InstantExtended NTP.
*/
-
/**
* Whether the most visited tiles have finished loading, i.e. we've received the
* 'loaded' postMessage from the iframe. Used by tests to detect that loading
@@ -16,7 +14,6 @@
*/
let tilesAreLoaded = false;
-
/**
* Whether the Most Visited and edit custom link iframes should be created while
* running tests. Currently the SimpleJavascriptTests are flaky due to some
@@ -25,7 +22,6 @@ let tilesAreLoaded = false;
*/
let iframesAndVoiceSearchDisabledForTesting = false;
-
/**
* Controls rendering the new tab page for InstantExtended.
* @return {Object} A limited interface for testing the local NTP.
@@ -33,7 +29,6 @@ let iframesAndVoiceSearchDisabledForTesting = false;
function LocalNTP() {
'use strict';
-
/**
* Called by tests to disable the creation of Most Visited and edit custom link
* iframes.
@@ -42,48 +37,53 @@ function disableIframesAndVoiceSearchForTesting() {
iframesAndVoiceSearchDisabledForTesting = true;
}
-
/**
* Specifications for an NTP design (not comprehensive).
*
+ * backgroundColor: The 4-component color of default background,
+ * darkBackgroundColor: The 4-component color of default dark background,
+ * iconBackgroundColor: The 4-component color of default dark icon background,
+ * iconDarkBackgroundColor: The 4-component color of default icon background,
* numTitleLines: Number of lines to display in titles.
* titleColor: The 4-component color of title text.
* titleColorAgainstDark: The 4-component color of title text against a dark
* theme.
*
* @type {{
+ * backgroundColor: Array<number>,
+ * darkBackgroundColor: Array<number>,
+ * iconBackgroundColor: Array<number>,
+ * iconDarkBackgroundColor: Array<number>,
* numTitleLines: number,
* titleColor: Array<number>,
* titleColorAgainstDark: Array<number>,
* }}
*/
const NTP_DESIGN = {
+ backgroundColor: [255, 255, 255, 255],
+ darkBackgroundColor: [50, 54, 57, 255],
+ iconBackgroundColor: [241, 243, 244, 255], /** GG100 */
+ iconDarkBackgroundColor: [32, 33, 36, 255], /** GG900 */
numTitleLines: 1,
titleColor: [60, 64, 67, 255], /** GG800 */
titleColorAgainstDark: [248, 249, 250, 255], /** GG050 */
};
-
/**
* Enum for classnames.
* @enum {string}
* @const
*/
const CLASSES = {
- // Shows a Google search style fakebox.
- ALTERNATE_FAKEBOX: 'alternate-fakebox',
- // Shows a rectangular Google search style fakebox with rounded corners.
- ALTERNATE_FAKEBOX_RECT: 'alternate-fakebox-rect',
ALTERNATE_LOGO: 'alternate-logo', // Shows white logo if required by theme
// Applies styles to dialogs used in customization.
CUSTOMIZE_DIALOG: 'customize-dialog',
DARK: 'dark',
DEFAULT_THEME: 'default-theme',
DELAYED_HIDE_NOTIFICATION: 'mv-notice-delayed-hide',
- FAKEBOX_ICON_COLOR: 'color', // Use a blue search icon for the fakebox.
+ // Extended and elevated style for customization entry point.
+ ENTRY_POINT_ENHANCED: 'ep-enhanced',
FAKEBOX_FOCUS: 'fakebox-focused', // Applies focus styles to the fakebox
- // Shows a search icon in the fakebox.
- SHOW_FAKEBOX_ICON: 'show-fakebox-icon',
// Applied when the fakebox placeholder text should not be hidden on focus.
SHOW_PLACEHOLDER: 'show-placeholder',
// Applies float animations to the Most Visited notification
@@ -100,14 +100,12 @@ const CLASSES = {
// Vertically centers the most visited section for a non-Google provided page.
NON_GOOGLE_PAGE: 'non-google-page',
NON_WHITE_BG: 'non-white-bg',
- REMOVE_FAKEBOX: 'remove-fakebox', // Hides the fakebox from the page.
- RTL: 'rtl', // Right-to-left language text.
+ RTL: 'rtl', // Right-to-left language text.
SHOW_ELEMENT: 'show-element',
// Applied when the doodle notifier should be shown instead of the doodle.
USE_NOTIFIER: 'use-notifier',
};
-
/**
* Enum for HTML element ids.
* @enum {string}
@@ -143,7 +141,6 @@ const IDS = {
USER_CONTENT: 'user-content',
};
-
/**
* The different types of events that are logged from the NTP. This enum is
* used to transfer information from the NTP JavaScript to the renderer and is
@@ -153,22 +150,6 @@ const IDS = {
* @const
*/
const LOG_TYPE = {
- // A static Doodle was shown, coming from cache.
- NTP_STATIC_LOGO_SHOWN_FROM_CACHE: 30,
- // A static Doodle was shown, coming from the network.
- NTP_STATIC_LOGO_SHOWN_FRESH: 31,
- // A call-to-action Doodle image was shown, coming from cache.
- NTP_CTA_LOGO_SHOWN_FROM_CACHE: 32,
- // A call-to-action Doodle image was shown, coming from the network.
- NTP_CTA_LOGO_SHOWN_FRESH: 33,
-
- // A static Doodle was clicked.
- NTP_STATIC_LOGO_CLICKED: 34,
- // A call-to-action Doodle was clicked.
- NTP_CTA_LOGO_CLICKED: 35,
- // An animated Doodle was clicked.
- NTP_ANIMATED_LOGO_CLICKED: 36,
-
// The One Google Bar was shown.
NTP_ONE_GOOGLE_BAR_SHOWN: 37,
@@ -183,7 +164,6 @@ const LOG_TYPE = {
NTP_MIDDLE_SLOT_PROMO_LINK_CLICKED: 61,
};
-
/**
* The maximum number of tiles to show in the Most Visited section.
* @type {number}
@@ -191,7 +171,6 @@ const LOG_TYPE = {
*/
const MAX_NUM_TILES_MOST_VISITED = 8;
-
/**
* The maximum number of tiles to show in the Most Visited section if custom
* links is enabled.
@@ -200,17 +179,14 @@ const MAX_NUM_TILES_MOST_VISITED = 8;
*/
const MAX_NUM_TILES_CUSTOM_LINKS = 10;
-
/**
* Background colors considered "white". Used to determine if it is possible to
* display a Google Doodle, or if the notifier should be used instead. Also used
* to determine if a colored or white logo should be used.
- * @type {Array<string>}
* @const
*/
const WHITE_BACKGROUND_COLORS = ['rgba(255,255,255,1)', 'rgba(0,0,0,0)'];
-
/**
* Background color for Chrome dark mode. Used to determine if it is possible to
* display a Google Doodle, or if the notifier should be used instead.
@@ -219,7 +195,6 @@ const WHITE_BACKGROUND_COLORS = ['rgba(255,255,255,1)', 'rgba(0,0,0,0)'];
*/
const DARK_MODE_BACKGROUND_COLOR = 'rgba(50,54,57,1)';
-
/**
* Enum for keycodes.
* @enum {number}
@@ -227,14 +202,12 @@ const DARK_MODE_BACKGROUND_COLOR = 'rgba(50,54,57,1)';
*/
const KEYCODE = {ENTER: 13, SPACE: 32};
-
/**
* The period of time (ms) before the Most Visited notification is hidden.
* @type {number}
*/
const NOTIFICATION_TIMEOUT = 10000;
-
/**
* The period of time (ms) before transitions can be applied to a toast
* notification after modifying the "display" property.
@@ -242,7 +215,6 @@ const NOTIFICATION_TIMEOUT = 10000;
*/
const DISPLAY_TIMEOUT = 20;
-
/**
* The last blacklisted tile rid if any, which by definition should not be
* filler.
@@ -250,7 +222,6 @@ const DISPLAY_TIMEOUT = 20;
*/
let lastBlacklistedTile = null;
-
/**
* The timeout function for automatically hiding the pop-up notification. Only
* set if a notification is visible.
@@ -258,7 +229,6 @@ let lastBlacklistedTile = null;
*/
let delayedHideNotification = null;
-
/**
* The currently visible notification element. Null if no notification is
* present.
@@ -266,29 +236,18 @@ let delayedHideNotification = null;
*/
let currNotification = null;
-
/**
* The browser embeddedSearch.newTabPage object.
* @type {Object}
*/
let ntpApiHandle;
-
/**
* True if dark mode is enabled.
* @type {boolean}
*/
let isDarkModeEnabled = false;
-
-/**
- * True if dark colored chips should be used instead of light mode chips when
- * dark mode is enabled.
- * @type {boolean}
- */
-let useDarkChips = false;
-
-
/**
* Returns a timeout that can be executed early. Calls back true if this was
* an early execution, false otherwise.
@@ -311,7 +270,6 @@ function createExecutableTimeout(timeout, delay) {
};
}
-
/**
* Called by tests to override the executable timeout with a test timeout.
* @param {!Function} timeout The timeout function. Requires a boolean param.
@@ -320,7 +278,6 @@ function overrideExecutableTimeoutForTesting(timeout) {
createExecutableTimeout = timeout;
}
-
/**
* Returns theme background info, first checking for history.state.notheme. If
* the page has notheme set, returns a fallback light-colored theme (or dark-
@@ -332,16 +289,36 @@ function getThemeBackgroundInfo() {
return {
alternateLogo: false,
backgroundColorRgba:
- (isDarkModeEnabled ? [50, 54, 57, 255] : [255, 255, 255, 255]),
+ (isDarkModeEnabled ? NTP_DESIGN.darkBackgroundColor :
+ NTP_DESIGN.backgroundColor),
+ customBackgroundConfigured: false,
+ iconBackgroundColor:
+ (isDarkModeEnabled ? NTP_DESIGN.iconDarkBackgroundColor :
+ NTP_DESIGN.iconBackgroundColor),
+ isNtpBackgroundDark: isDarkModeEnabled,
textColorLightRgba: [102, 102, 102, 255],
- textColorRgba: [0, 0, 0, 255],
+ textColorRgba:
+ (isDarkModeEnabled ? NTP_DESIGN.titleColorAgainstDark :
+ NTP_DESIGN.titleColor),
+ useTitleContainer: false,
+ useWhiteAddIcon: isDarkModeEnabled,
usingDarkMode: isDarkModeEnabled,
usingDefaultTheme: true,
};
}
- return ntpApiHandle.themeBackgroundInfo;
-}
+ const info = window.chrome.embeddedSearch.newTabPage.themeBackgroundInfo;
+ const preview = $(customize.IDS.CUSTOM_BG_PREVIEW);
+ if (preview.dataset.hasPreview === 'true') {
+ info.isNtpBackgroundDark = preview.dataset.hasImage === 'true';
+ info.customBackgroundConfigured = preview.dataset.hasImage === 'true';
+ info.alternateLogo = preview.dataset.hasImage === 'true';
+ // backgroundImage is in the form: url("actual url"). Remove everything
+ // except the actual url.
+ info.imageUrl = preview.style.backgroundImage.slice(5, -2);
+ }
+ return info;
+}
/**
* Determine whether dark chips should be used if dark mode is enabled. This is
@@ -350,16 +327,14 @@ function getThemeBackgroundInfo() {
*
* @param {!Object} info Theme background information.
* @return {boolean} Whether the chips should be dark.
- * @private
*/
function getUseDarkChips(info) {
- return info.usingDarkMode && !info.imageUrl;
+ return window.matchMedia('(prefers-color-scheme: dark)').matches &&
+ !info.imageUrl;
}
-
/**
* Updates the NTP based on the current theme.
- * @private
*/
function renderTheme() {
const info = getThemeBackgroundInfo();
@@ -370,10 +345,8 @@ function renderTheme() {
$(IDS.NTP_CONTENTS).classList.toggle(CLASSES.DARK, info.isNtpBackgroundDark);
// Update dark mode styling.
- isDarkModeEnabled = info.usingDarkMode;
- useDarkChips = getUseDarkChips(info);
- document.documentElement.setAttribute('darkmode', isDarkModeEnabled);
- document.body.classList.toggle('light-chip', !useDarkChips);
+ isDarkModeEnabled = window.matchMedia('(prefers-color-scheme: dark)').matches;
+ document.body.classList.toggle('light-chip', !getUseDarkChips(info));
const background = [
convertToRGBAColor(info.backgroundColorRgba), info.imageUrl,
@@ -393,6 +366,11 @@ function renderTheme() {
const isNonWhiteBackground = !WHITE_BACKGROUND_COLORS.includes(background);
document.body.classList.toggle(CLASSES.NON_WHITE_BG, isNonWhiteBackground);
+ if (info.logoColor) {
+ document.body.style.setProperty(
+ '--logo-color', convertToRGBAColor(info.logoColor));
+ }
+
// The doodle notifier should be shown for non-default backgrounds. This
// includes non-white backgrounds, excluding dark mode gray if dark mode is
// enabled.
@@ -404,57 +382,57 @@ function renderTheme() {
setCustomThemeStyle(info);
if (info.customBackgroundConfigured) {
- const imageWithOverlay = [
- customBackgrounds.CUSTOM_BACKGROUND_OVERLAY, 'url(' + info.imageUrl + ')'
- ].join(',').trim();
+ // Do anything only if the custom background changed.
+ if (!$(IDS.CUSTOM_BG).style.backgroundImage.includes(info.imageUrl)) {
+ const imageWithOverlay = [
+ customize.CUSTOM_BACKGROUND_OVERLAY, 'url(' + info.imageUrl + ')'
+ ].join(',').trim();
+ // If the theme update is because of uploading a local image then we
+ // should close the customization menu. Closing the menu before the image
+ // is selected doesn't look good.
+ const localImageFileName = 'background.jpg';
+ if (!configData.richerPicker &&
+ imageWithOverlay.includes(localImageFileName) &&
+ !$(IDS.CUSTOM_BG)
+ .style.backgroundImage.includes(localImageFileName)) {
+ customize.closeCustomizationDialog();
+ }
+ // |image| and |imageWithOverlay| use the same url as their source.
+ // Waiting to display the custom background until |image| is fully
+ // loaded ensures that |imageWithOverlay| is also loaded.
+ $(IDS.CUSTOM_BG).style.backgroundImage = imageWithOverlay;
+ const image = new Image();
+ image.onload = function() {
+ $(IDS.CUSTOM_BG).style.opacity = '1';
+ };
+ image.src = info.imageUrl;
- if (imageWithOverlay != $(IDS.CUSTOM_BG).style.backgroundImage) {
- customBackgrounds.closeCustomizationDialog();
- customBackgrounds.clearAttribution();
+ customize.clearAttribution();
+ customize.setAttribution(
+ info.attribution1, info.attribution2, info.attributionActionUrl);
}
-
- // |image| and |imageWithOverlay| use the same url as their source. Waiting
- // to display the custom background until |image| is fully loaded ensures
- // that |imageWithOverlay| is also loaded.
- $(IDS.CUSTOM_BG).style.backgroundImage = imageWithOverlay;
- const image = new Image();
- image.onload = function() {
- $(IDS.CUSTOM_BG).style.opacity = '1';
- };
- image.src = info.imageUrl;
-
- customBackgrounds.setAttribution(
- info.attribution1, info.attribution2, info.attributionActionUrl);
} else {
$(IDS.CUSTOM_BG).style.opacity = '0';
- window.setTimeout(function() {
- $(IDS.CUSTOM_BG).style.backgroundImage = '';
- }, 1000);
- customBackgrounds.clearAttribution();
+ customize.clearAttribution();
}
- $(customBackgrounds.IDS.RESTORE_DEFAULT)
+ $(customize.IDS.RESTORE_DEFAULT)
.classList.toggle(
- customBackgrounds.CLASSES.OPTION_DISABLED,
- !info.customBackgroundConfigured);
- $(customBackgrounds.IDS.RESTORE_DEFAULT).tabIndex =
+ customize.CLASSES.OPTION_DISABLED, !info.customBackgroundConfigured);
+ $(customize.IDS.RESTORE_DEFAULT).tabIndex =
(info.customBackgroundConfigured ? 0 : -1);
- $(customBackgrounds.IDS.EDIT_BG)
+ $(customize.IDS.EDIT_BG)
.classList.toggle(
- customBackgrounds.CLASSES.ENTRY_POINT_ENHANCED,
- !info.customBackgroundConfigured);
+ CLASSES.ENTRY_POINT_ENHANCED, !info.customBackgroundConfigured);
if (configData.isGooglePage) {
- // Hide the settings menu or individual options if the related features are
- // disabled.
- customBackgrounds.setMenuVisibility();
+ customize.onThemeChange();
}
}
/**
* Sends the current theme info to the most visited iframe.
- * @private
*/
function sendThemeInfoToMostVisitedIframe() {
const info = getThemeBackgroundInfo();
@@ -466,7 +444,6 @@ function sendThemeInfoToMostVisitedIframe() {
message.isThemeDark = info.isNtpBackgroundDark;
message.customBackground = info.customBackgroundConfigured;
message.useTitleContainer = info.useTitleContainer;
- message.isDarkMode = getUseDarkChips(info);
message.iconBackgroundColor = convertToRGBAColor(info.iconBackgroundColor);
message.useWhiteAddIcon = info.useWhiteAddIcon;
@@ -478,35 +455,15 @@ function sendThemeInfoToMostVisitedIframe() {
}
message.tileTitleColor = convertToRGBAColor(titleColor);
- $(IDS.TILES_IFRAME).contentWindow.postMessage(message, '*');
-}
-
-
-/**
- * Sends the current theme info to the edit custom link iframe.
- * @private
- */
-function sendThemeInfoToEditCustomLinkIframe() {
- if (!configData.isGooglePage) {
- return;
+ const iframe = $(IDS.TILES_IFRAME);
+ if (iframe) {
+ iframe.contentWindow.postMessage(message, '*');
}
-
- const info = getThemeBackgroundInfo();
- if (!info) {
- return;
- }
-
- const message = {cmd: 'updateTheme'};
- message.isDarkMode = info.usingDarkMode;
-
- $(IDS.CUSTOM_LINKS_EDIT_IFRAME).contentWindow.postMessage(message, '*');
}
-
/**
* Updates the OneGoogleBar (if it is loaded) based on the current theme.
* TODO(crbug.com/918582): Add support for OGB dark mode.
- * @private
*/
function renderOneGoogleBarTheme() {
if (!window.gbar) {
@@ -524,32 +481,18 @@ function renderOneGoogleBarTheme() {
}
}
-
/**
* Callback for embeddedSearch.newTabPage.onthemechange.
- * @private
*/
function onThemeChange() {
- // Save the current dark mode state to check if dark mode has changed.
- const usingDarkChips = useDarkChips;
-
renderTheme();
renderOneGoogleBarTheme();
sendThemeInfoToMostVisitedIframe();
- sendThemeInfoToEditCustomLinkIframe();
-
- // If dark mode has been changed, refresh the MV tiles to render the
- // appropriate icon.
- if (usingDarkChips != useDarkChips) {
- reloadTiles();
- }
}
-
/**
* Updates the NTP style according to theme.
* @param {Object} themeInfo The information about the theme.
- * @private
*/
function setCustomThemeStyle(themeInfo) {
let textColor = '';
@@ -570,13 +513,11 @@ function setCustomThemeStyle(themeInfo) {
document.body.style.setProperty('--text-color-link', textColorLight);
}
-
/**
* Renders the attribution if the URL is present, otherwise hides it.
* @param {string} url The URL of the attribution image, if any.
* @param {string} themeBackgroundAlignment The alignment of the theme
- * background image. This is used to compute the attribution's alignment.
- * @private
+ * background image. This is used to compute the attribution's alignment.
*/
function updateThemeAttribution(url, themeBackgroundAlignment) {
if (!url) {
@@ -594,34 +535,29 @@ function updateThemeAttribution(url, themeBackgroundAlignment) {
// To avoid conflicts, place the attribution on the left for themes that
// right align their background images.
- attribution.classList.toggle(CLASSES.LEFT_ALIGN_ATTRIBUTION,
- themeBackgroundAlignment == 'right');
+ attribution.classList.toggle(
+ CLASSES.LEFT_ALIGN_ATTRIBUTION, themeBackgroundAlignment == 'right');
setAttributionVisibility_(true);
}
-
/**
* Sets the visibility of the theme attribution.
* @param {boolean} show True to show the attribution.
- * @private
*/
function setAttributionVisibility_(show) {
$(IDS.ATTRIBUTION).style.display = show ? '' : 'none';
}
-
/**
* Converts an Array of color components into RGBA format "rgba(R,G,B,A)".
* @param {Array<number>} color Array of rgba color components.
* @return {string} CSS color in RGBA format.
- * @private
*/
function convertToRGBAColor(color) {
return 'rgba(' + color[0] + ',' + color[1] + ',' + color[2] + ',' +
- color[3] / 255 + ')';
+ color[3] / 255 + ')';
}
-
/**
* Callback for embeddedSearch.newTabPage.onmostvisitedchange. Called when the
* NTP tiles are updated.
@@ -630,7 +566,6 @@ function onMostVisitedChange() {
reloadTiles();
}
-
/**
* Fetches new data (RIDs) from the embeddedSearch.newTabPage API and passes
* them to the iframe.
@@ -647,17 +582,19 @@ function reloadTiles() {
const pages = ntpApiHandle.mostVisited;
const cmds = [];
- const maxNumTiles = configData.isGooglePage ? MAX_NUM_TILES_CUSTOM_LINKS :
- MAX_NUM_TILES_MOST_VISITED;
+ const maxNumTiles = customLinksEnabled() ? MAX_NUM_TILES_CUSTOM_LINKS :
+ MAX_NUM_TILES_MOST_VISITED;
for (let i = 0; i < Math.min(maxNumTiles, pages.length); ++i) {
- cmds.push({cmd: 'tile', rid: pages[i].rid, darkMode: useDarkChips});
+ cmds.push({cmd: 'tile', rid: pages[i].rid});
}
cmds.push({cmd: 'show'});
- $(IDS.TILES_IFRAME).contentWindow.postMessage(cmds, '*');
+ const iframe = $(IDS.TILES_IFRAME);
+ if (iframe) {
+ iframe.contentWindow.postMessage(cmds, '*');
+ }
}
-
/**
* Callback for embeddedSearch.newTabPage.onaddcustomlinkdone. Called when the
* custom link was successfully added. Shows the "Shortcut added" notification.
@@ -673,7 +610,6 @@ function onAddCustomLinkDone(success) {
ntpApiHandle.logEvent(LOG_TYPE.NTP_CUSTOMIZE_SHORTCUT_DONE);
}
-
/**
* Callback for embeddedSearch.newTabPage.onupdatecustomlinkdone. Called when
* the custom link was successfully updated. Shows the "Shortcut edited"
@@ -689,7 +625,6 @@ function onUpdateCustomLinkDone(success) {
}
}
-
/**
* Callback for embeddedSearch.newTabPage.ondeletecustomlinkdone. Called when
* the custom link was successfully deleted. Shows the "Shortcut deleted"
@@ -705,7 +640,6 @@ function onDeleteCustomLinkDone(success) {
}
}
-
/**
* Shows the Most Visited pop-up notification and triggers a delay to hide it.
* The message will be set to |msg|.
@@ -713,11 +647,13 @@ function onDeleteCustomLinkDone(success) {
*/
function showNotification(msg) {
$(IDS.NOTIFICATION_MESSAGE).textContent = msg;
+ $(IDS.RESTORE_ALL_LINK).textContent = customLinksEnabled() ?
+ configData.translatedStrings.restoreDefaultLinks :
+ configData.translatedStrings.restoreThumbnailsShort;
floatUpNotification($(IDS.NOTIFICATION), $(IDS.NOTIFICATION_CONTAINER));
$(IDS.UNDO_LINK).focus();
}
-
/**
* Hides the Most Visited pop-up notification.
*/
@@ -726,7 +662,6 @@ function hideNotification() {
$(IDS.NOTIFICATION), $(IDS.NOTIFICATION_CONTAINER), /*showPromo=*/ true);
}
-
/**
* Shows the error pop-up notification and triggers a delay to hide it. The
* message will be set to |msg|. If |linkName| and |linkOnClick| are present,
@@ -750,7 +685,6 @@ function showErrorNotification(msg, linkName, linkOnClick) {
floatUpNotification(notification, $(IDS.ERROR_NOTIFICATION_CONTAINER));
}
-
/**
* Animates the specified notification to float up. Automatically hides any
* pre-existing notification and sets a delayed timer to hide the new
@@ -806,7 +740,6 @@ function floatUpNotification(notification, notificationContainer) {
currNotification = notificationContainer;
}
-
/**
* Animates the pop-up notification to float down, and clears the timeout to
* hide the notification.
@@ -861,6 +794,14 @@ function floatDownNotification(notification, notificationContainer, showPromo) {
notificationContainer.classList.remove(CLASSES.FLOAT_UP);
}
+/**
+ * Return true if custom links are enabled.
+ * @return {boolean}
+ */
+function customLinksEnabled() {
+ return configData.isGooglePage &&
+ !chrome.embeddedSearch.newTabPage.isUsingMostVisited;
+}
/**
* Handles a click on the notification undo link by hiding the notification and
@@ -870,14 +811,13 @@ function onUndo() {
hideNotification();
// Focus on the omnibox after the notification is hidden.
window.chrome.embeddedSearch.searchBox.startCapturingKeyStrokes();
- if (configData.isGooglePage) {
+ if (customLinksEnabled()) {
ntpApiHandle.undoCustomLinkAction();
} else if (lastBlacklistedTile != null) {
ntpApiHandle.undoMostVisitedDeletion(lastBlacklistedTile);
}
}
-
/**
* Handles a click on the restore all notification link by hiding the
* notification and informing Chrome.
@@ -886,14 +826,13 @@ function onRestoreAll() {
hideNotification();
// Focus on the omnibox after the notification is hidden.
window.chrome.embeddedSearch.searchBox.startCapturingKeyStrokes();
- if (configData.isGooglePage) {
+ if (customLinksEnabled()) {
ntpApiHandle.resetCustomLinks();
} else {
ntpApiHandle.undoAllMostVisitedDeletions();
}
}
-
/**
* Callback for embeddedSearch.newTabPage.oninputstart. Handles new input by
* disposing the NTP, according to where the input was entered.
@@ -906,7 +845,6 @@ function onInputStart() {
}
}
-
/**
* Callback for embeddedSearch.newTabPage.oninputcancel. Restores the NTP
* (re-enables the fakebox and unhides the logo.)
@@ -915,7 +853,6 @@ function onInputCancel() {
setFakeboxVisibility(true);
}
-
/**
* @param {boolean} focus True to focus the fakebox.
*/
@@ -938,7 +875,6 @@ function isFakeboxFocused() {
document.body.classList.contains(CLASSES.FAKEBOX_DRAG_FOCUS);
}
-
/**
* @param {!Event} event The click event.
* @return {boolean} True if the click occurred in an enabled fakebox.
@@ -949,7 +885,6 @@ function isFakeboxClick(event) {
.contains(/** @type HTMLElement */ (event.target));
}
-
/**
* @param {boolean} show True to show the fakebox and logo.
*/
@@ -957,7 +892,6 @@ function setFakeboxVisibility(show) {
document.body.classList.toggle(CLASSES.HIDE_FAKEBOX, !show);
}
-
/**
* @param {!Element} element The element to register the handler for.
* @param {number} keycode The keycode of the key to register.
@@ -971,7 +905,6 @@ function registerKeyHandler(element, keycode, handler) {
});
}
-
/**
* Event handler for messages from the most visited and edit custom link iframe.
* @param {Event} event Event received.
@@ -990,31 +923,30 @@ function handlePostMessage(event) {
if ($(IDS.PROMO)) {
$(IDS.PROMO).classList.add(CLASSES.SHOW_ELEMENT);
}
- if (!configData.hideShortcuts) {
- $(customBackgrounds.IDS.CUSTOM_LINKS_RESTORE_DEFAULT)
+ if (customLinksEnabled() && !configData.hideShortcuts) {
+ $(customize.IDS.CUSTOM_LINKS_RESTORE_DEFAULT)
.classList.toggle(
- customBackgrounds.CLASSES.OPTION_DISABLED,
- !args.showRestoreDefault);
- $(customBackgrounds.IDS.CUSTOM_LINKS_RESTORE_DEFAULT).tabIndex =
+ customize.CLASSES.OPTION_DISABLED, !args.showRestoreDefault);
+ $(customize.IDS.CUSTOM_LINKS_RESTORE_DEFAULT).tabIndex =
(args.showRestoreDefault ? 0 : -1);
}
$(IDS.OGB).classList.add(CLASSES.SHOW_ELEMENT);
}
} else if (cmd === 'tileBlacklisted') {
- if (configData.isGooglePage) {
+ if (customLinksEnabled()) {
showNotification(configData.translatedStrings.linkRemovedMsg);
} else {
showNotification(
configData.translatedStrings.thumbnailRemovedNotification);
}
- lastBlacklistedTile = args.tid;
+ lastBlacklistedTile = args.rid;
- ntpApiHandle.deleteMostVisitedItem(args.tid);
+ ntpApiHandle.deleteMostVisitedItem(args.rid);
} else if (cmd === 'resizeDoodle') {
doodles.resizeDoodleHandler(args);
} else if (cmd === 'startEditLink') {
$(IDS.CUSTOM_LINKS_EDIT_IFRAME)
- .contentWindow.postMessage({cmd: 'linkData', tid: args.tid}, '*');
+ .contentWindow.postMessage({cmd: 'linkData', rid: args.rid}, '*');
// Small delay to allow the dialog to finish setting up before displaying.
window.setTimeout(function() {
$(IDS.CUSTOM_LINKS_EDIT_IFRAME_DIALOG).showModal();
@@ -1024,8 +956,10 @@ function handlePostMessage(event) {
} else if (cmd === 'focusMenu') {
// Focus the edited tile's menu or the add shortcut tile after closing the
// custom link edit dialog without saving.
- $(IDS.TILES_IFRAME)
- .contentWindow.postMessage({cmd: 'focusMenu', tid: args.tid}, '*');
+ const iframe = $(IDS.TILES_IFRAME);
+ if (iframe) {
+ iframe.contentWindow.postMessage({cmd: 'focusMenu', rid: args.rid}, '*');
+ }
}
}
@@ -1068,7 +1002,6 @@ function requestAndInsertGoogleResources() {
}
}
-
/**
* Prepares the New Tab Page by adding listeners, the most visited pages
* section, and Google-specific elements for a Google-provided page.
@@ -1100,10 +1033,6 @@ function init() {
restoreAllLink.addEventListener('click', onRestoreAll);
registerKeyHandler(restoreAllLink, KEYCODE.ENTER, onRestoreAll);
registerKeyHandler(restoreAllLink, KEYCODE.SPACE, onRestoreAll);
- restoreAllLink.textContent =
- (configData.isGooglePage ?
- configData.translatedStrings.restoreDefaultLinks :
- configData.translatedStrings.restoreThumbnailsShort);
$(IDS.ATTRIBUTION_TEXT).textContent =
configData.translatedStrings.attributionIntro;
@@ -1126,94 +1055,75 @@ function init() {
ntpApiHandle.onupdatecustomlinkdone = onUpdateCustomLinkDone;
ntpApiHandle.ondeletecustomlinkdone = onDeleteCustomLinkDone;
- customBackgrounds.init(showErrorNotification, hideNotification);
+ customize.init(showErrorNotification, hideNotification);
- if (configData.alternateFakebox) {
- document.body.classList.add(CLASSES.ALTERNATE_FAKEBOX);
- }
- if (configData.alternateFakeboxRect) {
- document.body.classList.add(CLASSES.ALTERNATE_FAKEBOX_RECT);
- }
- if (configData.fakeboxSearchIcon) {
- document.body.classList.add(CLASSES.SHOW_FAKEBOX_ICON);
- }
- if (configData.fakeboxSearchIconColor) {
- $(IDS.FAKEBOX_ICON).classList.add(CLASSES.FAKEBOX_ICON_COLOR);
- }
if (configData.showFakeboxPlaceholderOnFocus) {
$(IDS.FAKEBOX_TEXT).classList.add(CLASSES.SHOW_PLACEHOLDER);
}
- if (configData.removeFakebox) {
- document.body.classList.add(CLASSES.REMOVE_FAKEBOX);
- } else {
- // Set up the fakebox (which only exists on the Google NTP).
- ntpApiHandle.oninputstart = onInputStart;
- ntpApiHandle.oninputcancel = onInputCancel;
+ // Set up the fakebox (which only exists on the Google NTP).
+ ntpApiHandle.oninputstart = onInputStart;
+ ntpApiHandle.oninputcancel = onInputCancel;
- if (ntpApiHandle.isInputInProgress) {
- onInputStart();
- }
-
- $(IDS.FAKEBOX_TEXT).textContent =
- configData.translatedStrings.searchboxPlaceholder;
+ if (ntpApiHandle.isInputInProgress) {
+ onInputStart();
+ }
- if (!iframesAndVoiceSearchDisabledForTesting) {
- speech.init(
- configData.googleBaseUrl, configData.translatedStrings,
- $(IDS.FAKEBOX_MICROPHONE), searchboxApiHandle);
- }
+ $(IDS.FAKEBOX_TEXT).textContent =
+ configData.translatedStrings.searchboxPlaceholder;
- // Listener for updating the key capture state.
- document.body.onmousedown = function(event) {
- if (isFakeboxClick(event)) {
- searchboxApiHandle.startCapturingKeyStrokes();
- } else if (isFakeboxFocused()) {
- searchboxApiHandle.stopCapturingKeyStrokes();
- }
- };
- searchboxApiHandle.onkeycapturechange = function() {
- setFakeboxFocus(searchboxApiHandle.isKeyCaptureEnabled);
- };
- const inputbox = $(IDS.FAKEBOX_INPUT);
- inputbox.onpaste = function(event) {
- event.preventDefault();
- // Send pasted text to Omnibox.
- const text = event.clipboardData.getData('text/plain');
- if (text) {
- searchboxApiHandle.paste(text);
- }
- };
- inputbox.ondrop = function(event) {
- event.preventDefault();
- const text = event.dataTransfer.getData('text/plain');
- if (text) {
- searchboxApiHandle.paste(text);
- }
- setFakeboxDragFocus(false);
- };
- inputbox.ondragenter = function() {
- setFakeboxDragFocus(true);
- };
- inputbox.ondragleave = function() {
- setFakeboxDragFocus(false);
- };
- utils.disableOutlineOnMouseClick($(IDS.FAKEBOX_MICROPHONE));
+ if (!iframesAndVoiceSearchDisabledForTesting) {
+ speech.init(
+ configData.googleBaseUrl, configData.translatedStrings,
+ $(IDS.FAKEBOX_MICROPHONE), searchboxApiHandle);
+ }
- // Update the fakebox style to match the current key capturing state.
- setFakeboxFocus(searchboxApiHandle.isKeyCaptureEnabled);
- // Also tell the browser that we're capturing, otherwise it's possible
- // that both fakebox and Omnibox have visible focus at the same time, see
- // crbug.com/792850.
- if (searchboxApiHandle.isKeyCaptureEnabled) {
+ // Listener for updating the key capture state.
+ document.body.onmousedown = function(event) {
+ if (isFakeboxClick(event)) {
searchboxApiHandle.startCapturingKeyStrokes();
+ } else if (isFakeboxFocused()) {
+ searchboxApiHandle.stopCapturingKeyStrokes();
+ }
+ };
+ searchboxApiHandle.onkeycapturechange = function() {
+ setFakeboxFocus(searchboxApiHandle.isKeyCaptureEnabled);
+ };
+ const inputbox = $(IDS.FAKEBOX_INPUT);
+ inputbox.onpaste = function(event) {
+ event.preventDefault();
+ // Send pasted text to Omnibox.
+ const text = event.clipboardData.getData('text/plain');
+ if (text) {
+ searchboxApiHandle.paste(text);
+ }
+ };
+ inputbox.ondrop = function(event) {
+ event.preventDefault();
+ const text = event.dataTransfer.getData('text/plain');
+ if (text) {
+ searchboxApiHandle.paste(text);
}
+ setFakeboxDragFocus(false);
+ };
+ inputbox.ondragenter = function() {
+ setFakeboxDragFocus(true);
+ };
+ inputbox.ondragleave = function() {
+ setFakeboxDragFocus(false);
+ };
+ utils.disableOutlineOnMouseClick($(IDS.FAKEBOX_MICROPHONE));
+
+ // Update the fakebox style to match the current key capturing state.
+ setFakeboxFocus(searchboxApiHandle.isKeyCaptureEnabled);
+ // Also tell the browser that we're capturing, otherwise it's possible
+ // that both fakebox and Omnibox have visible focus at the same time, see
+ // crbug.com/792850.
+ if (searchboxApiHandle.isKeyCaptureEnabled) {
+ searchboxApiHandle.startCapturingKeyStrokes();
}
doodles.init();
-
- $(customBackgrounds.IDS.EDIT_BG_TEXT).textContent =
- configData.translatedStrings.customizeButtonLabel;
} else {
document.body.classList.add(CLASSES.NON_GOOGLE_PAGE);
}
@@ -1234,11 +1144,10 @@ function init() {
}
utils.setPlatformClass(document.body);
- utils.disableOutlineOnMouseClick($(customBackgrounds.IDS.EDIT_BG));
+ utils.disableOutlineOnMouseClick($(customize.IDS.EDIT_BG));
document.body.classList.add(CLASSES.INITED);
}
-
/**
* Create the Most Visited and edit custom links iframes.
*/
@@ -1258,7 +1167,8 @@ function createIframes() {
args.push(
'title=' +
encodeURIComponent(configData.translatedStrings.mostVisitedTitle));
- args.push('removeTooltip=' +
+ args.push(
+ 'removeTooltip=' +
encodeURIComponent(configData.translatedStrings.removeThumbnailTooltip));
if (configData.isGooglePage) {
@@ -1335,10 +1245,6 @@ function createIframes() {
clIframeDialog.appendChild(clIframe);
document.body.appendChild(clIframeDialog);
- clIframe.onload = () => {
- sendThemeInfoToEditCustomLinkIframe();
- };
-
if (configData.hideShortcuts) {
$(IDS.TILES).style.display = 'none';
clIframeDialog.style.display = 'none';
@@ -1348,7 +1254,6 @@ function createIframes() {
window.addEventListener('message', handlePostMessage);
}
-
/**
* Binds event listeners.
*/
@@ -1356,7 +1261,6 @@ function listen() {
document.addEventListener('DOMContentLoaded', init);
}
-
/**
* Injects a middle-slot promo into the page. Called asynchronously, so that it
* doesn't block the main page load.
@@ -1383,8 +1287,12 @@ function injectPromo(promo) {
ntpApiHandle.logEvent(LOG_TYPE.NTP_MIDDLE_SLOT_PROMO_LINK_CLICKED);
};
}
-}
+ // The the MV tiles are already loaded show the promo immediately.
+ if (tilesAreLoaded) {
+ promoContainer.classList.add(CLASSES.SHOW_ELEMENT);
+ }
+}
/**
* Injects search suggestions into the page. Called *synchronously* with cached
@@ -1408,7 +1316,6 @@ function injectSearchSuggestions(suggestions) {
document.body.appendChild(endOfBodyScript);
}
-
/**
* Injects the One Google Bar into the page. Called asynchronously, so that it
* doesn't block the main page load.
@@ -1448,7 +1355,6 @@ function injectOneGoogleBar(ogb) {
ntpApiHandle.logEvent(LOG_TYPE.NTP_ONE_GOOGLE_BAR_SHOWN);
}
-
return {
init: init, // Exposed for testing.
listen: listen,
diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp_common.css b/chromium/chrome/browser/resources/local_ntp/local_ntp_common.css
index ece31d7174a..102d85b4595 100644
--- a/chromium/chrome/browser/resources/local_ntp/local_ntp_common.css
+++ b/chromium/chrome/browser/resources/local_ntp/local_ntp_common.css
@@ -6,6 +6,7 @@ html {
/* Material Design colors. Keep in sync with ui/gfx/color_palette.h. */
--dark-mode-bg-rgb: 50, 54, 57;
+ --dark-mode-dialog-rgb: 41, 42, 45;
/* Google Grey */
--GG050-rgb: 248, 249, 250;
@@ -47,6 +48,9 @@ html {
--GR500-dark-rgb: 230, 106, 94;
--GR600-dark-rgb: 211, 59, 48;
--GR800-dark-rgb: 180, 27, 26;
+
+ --dark-mode-shadow: 0 1px 3px 0 rgba(0, 0, 0, .3),
+ 0 4px 8px 3px rgba(0, 0, 0, .15);
}
body * {
@@ -67,4 +71,4 @@ body * {
/* Removes blue focus ring on mouse navigation */
.mouse-navigation {
outline: none;
-} \ No newline at end of file
+}
diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp_resources.grd b/chromium/chrome/browser/resources/local_ntp/local_ntp_resources.grd
index edb2d73194e..ade6f647ab8 100644
--- a/chromium/chrome/browser/resources/local_ntp/local_ntp_resources.grd
+++ b/chromium/chrome/browser/resources/local_ntp/local_ntp_resources.grd
@@ -18,8 +18,8 @@
<include name="IDR_LOCAL_NTP_ANIMATIONS_CSS" file="animations.css" flattenhtml="true" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ANIMATIONS_JS" file="animations.js" flattenhtml="true" type="BINDATA" />
<include name="IDR_LOCAL_NTP_CSS" file="local_ntp.css" flattenhtml="true" type="BINDATA" />
- <include name="IDR_LOCAL_NTP_CUSTOM_BACKGROUNDS_CSS" file="custom_backgrounds.css" flattenhtml="true" type="BINDATA" />
- <include name="IDR_LOCAL_NTP_CUSTOM_BACKGROUNDS_JS" file="custom_backgrounds.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_LOCAL_NTP_CUSTOMIZE_CSS" file="customize.css" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_LOCAL_NTP_CUSTOMIZE_JS" file="customize.js" flattenhtml="true" type="BINDATA" />
<include name="IDR_LOCAL_NTP_DOODLES_CSS" file="doodles.css" flattenhtml="true" type="BINDATA" />
<include name="IDR_LOCAL_NTP_DOODLES_JS" file="doodles.js" flattenhtml="true" type="BINDATA" />
<include name="IDR_LOCAL_NTP_HTML" file="local_ntp.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
diff --git a/chromium/chrome/browser/resources/local_ntp/most_visited_single.css b/chromium/chrome/browser/resources/local_ntp/most_visited_single.css
index c2bd7de53e3..51a006495b6 100644
--- a/chromium/chrome/browser/resources/local_ntp/most_visited_single.css
+++ b/chromium/chrome/browser/resources/local_ntp/most_visited_single.css
@@ -4,7 +4,6 @@
html {
/* Material Design constants */
- --md-add-size: 24px;
--md-edit-menu-size: 20px;
--md-fallback-letter-size: 16px;
--md-favicon-size: 32px;
@@ -14,12 +13,9 @@ html {
--md-menu-margin-side: 2px;
--md-menu-margin-top: 4px;
--md-menu-size: 12px;
- --md-tile-height: 112px;
--md-tile-margin: 16px;
- --md-tile-padding-bottom: 10px;
- --md-tile-padding-horizontal: 4px;
--md-tile-padding-top: 16px;
- --md-tile-width: 112px;
+ --md-tile-size: 112px;
--md-title-font-size: 12px;
--md-title-height: 24px;
--md-title-max-height: 28px;
@@ -46,11 +42,15 @@ a,
a:active,
a:hover,
a:visited {
- color: inherit;
text-decoration: none;
}
+body.hide {
+ display: none;
+}
+
#most-visited {
+ margin-top: 10px;
text-align: -webkit-center;
user-select: none;
width: 100%;
@@ -64,9 +64,8 @@ a:visited {
justify-content: center;
/* 5 112px tiles per row. If you change this, also change the corresponding
* values in local_ntp.css. */
- max-width: calc(var(--md-tile-width) * var(--md-max-tiles-row));
+ max-width: calc(var(--md-tile-size) * var(--md-max-tiles-row));
opacity: 0;
- padding: 10px 6px 0;
position: static;
/* This align correctly for both LTR and RTL */
text-align: -webkit-auto;
@@ -107,87 +106,85 @@ html:not(.no-initial-fade) :-webkit-any(#mv-tiles, .mv-tiles-old) {
transition: transform 300ms ease-in-out;
}
-/* Prevent navigation while we're reordering the tiles. */
-body.reordering .grid-tile {
- pointer-events: none;
-}
-
/* Prevent transitions on the held tile in order for it to smoothly follow the
* mouse. */
.grid-reorder .grid-tile {
transition-duration: 0s;
}
-.grid-tile-container.grid-reorder {
+.grid-reorder {
z-index: 10; /* Ensure the held tile is visible. */
}
-.md-tile-container {
+.md-tile {
border-radius: 4px;
box-sizing: border-box;
- height: var(--md-tile-height);
+ color: rgb(var(--tile-title-color));
+ cursor: pointer;
+ height: var(--md-tile-size);
margin-bottom: var(--md-tile-margin);
opacity: 1;
+ padding-top: var(--md-tile-padding-top);
position: relative;
transition-property:
background, background-color, border-color, box-shadow, opacity, filter;
- width: var(--md-tile-width);
+ width: var(--md-tile-size);
}
-.md-tile-container.reorder .md-tile {
+.reorder {
background-color: white;
border-radius: 4px;
- box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), 0.3),
- 0 4px 8px 3px rgba(var(--GG800-rgb), 0.15);
+ box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), .3),
+ 0 4px 8px 3px rgba(var(--GG800-rgb), .15);
+ color: rgb(var(--GG800-rgb));
transition-duration: 200ms;
}
-html[darkmode=true] .md-tile-container.reorder .md-tile {
- background-color: rgb(var(--dark-mode-bg-rgb));
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.4),
- 0 4px 8px 3px rgba(0, 0, 0, 0.25);
+@media (prefers-color-scheme: dark) {
+ .reorder {
+ background-color: rgb(var(--dark-mode-bg-rgb));
+ box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .4),
+ 0 4px 8px 3px rgba(0, 0, 0, .25);
+ color: rgb(var(--GG100-rgb));
+ }
}
-.md-tile-container.reorder .md-tile .md-tile-inner {
+.reorder .md-tile-inner {
z-index: unset;
}
-.md-tile {
- cursor: pointer;
- padding: var(--md-tile-padding-top) var(--md-tile-padding-horizontal)
- var(--md-tile-padding-bottom);
-}
-
.md-empty-tile {
display: none;
}
-body:not(.reordering) .md-tile-container:hover,
-.grid-tile-container.grid-reorder .md-tile-container {
- background-color: rgba(var(--GG900-rgb), 0.06);
+body:not(.reordering) .md-tile:hover,
+.grid-reorder .md-tile {
+ background-color: rgba(var(--GG900-rgb), .06);
}
-html[darkmode=true] body:not(.reordering) .md-tile-container:hover,
-html[darkmode=true] .grid-tile-container.grid-reorder .md-tile-container {
- background-color: rgba(255, 255, 255, 0.1);
+@media (prefers-color-scheme: dark) {
+ body:not(.reordering) .md-tile:hover,
+ .grid-reorder .md-tile {
+ background-color: rgba(255, 255, 255, .1);
+ }
}
-body.dark-theme:not(.reordering) .md-tile-container:hover,
-body.dark-theme .grid-tile-container.grid-reorder .md-tile-container {
- background-color: rgba(255, 255, 255, 0.1);
+body.dark-theme:not(.reordering) .md-tile:hover,
+body.dark-theme .grid-reorder .md-tile {
+ background-color: rgba(255, 255, 255, .1);
}
-body:not(.reordering) .md-tile-container:hover .md-menu {
+body:not(.reordering) .md-tile:hover .md-menu {
opacity: 1;
transition-delay: 500ms;
}
-body.dark-theme:not(.reordering) .md-tile-container:active + .md-menu::after {
+body.dark-theme:not(.reordering) .md-tile:active + .md-menu::after {
background-color: rgb(var(--GG400-rgb));
transition-delay: 0ms;
}
-.md-tile-container.blacklisted {
+.blacklisted {
margin: 0;
padding: 0;
transform: scale(0, 0);
@@ -207,34 +204,24 @@ body.dark-theme:not(.reordering) .md-tile-container:active + .md-menu::after {
}
.md-icon {
- margin-bottom: var(--md-icon-margin-bottom);
- pointer-events: none;
-}
-
-.md-icon img {
- /* Icons returned by the NTP Icon Source are always of this size. */
- height: var(--md-icon-size);
- width: var(--md-icon-size);
-}
-
-.md-icon-background {
align-items: center;
background-color: var(--icon-background-color);
border-radius: 50%;
display: flex;
height: var(--md-icon-size);
justify-content: center;
+ margin-bottom: var(--md-icon-margin-bottom);
width: var(--md-icon-size);
}
.md-add-icon {
- background: url(chrome-search://most-visited/add_link.svg) no-repeat center;
- height: var(--md-add-size);
- width: var(--md-add-size);
+ background-image: url(chrome-search://most-visited/add_link.svg);
+ background-position: center;
+ background-repeat: no-repeat;
}
.use-white-add-icon .md-add-icon {
- background: url(chrome-search://most-visited/add_link_white.svg) no-repeat center;
+ background-image: url(chrome-search://most-visited/add_link_white.svg);
}
.md-fallback-letter {
@@ -253,7 +240,6 @@ body.dark-theme:not(.reordering) .md-tile-container:active + .md-menu::after {
}
.md-title {
- color: rgb(var(--tile-title-color));
font-size: var(--md-title-font-size);
font-weight: 500;
max-height: var(--md-title-max-height);
@@ -264,18 +250,6 @@ body.dark-theme:not(.reordering) .md-tile-container:active + .md-menu::after {
width: 88px;
}
-/* During reorder background is white. Therefore use dark grey for
- * title. */
-.reorder .md-title {
- color: rgb(var(--GG800-rgb));
-}
-
-/* During reorder in dark mode background is dark. Therefore use light
- * grey for title. */
-html[darkmode=true] .reorder .md-title {
- color: rgb(var(--GG100-rgb));
-}
-
.md-title span {
line-height: var(--md-title-height);
}
@@ -287,19 +261,19 @@ body.mac-chromeos .md-title {
}
/* Apply when a custom background is set. */
-body.custom-background .md-tile-container:not(.reorder) .md-title {
- filter: drop-shadow(0 0 6px rgba(0, 0, 0, 0.35));
+body.custom-background .md-tile:not(.reorder) .md-title {
+ filter: drop-shadow(0 0 6px rgba(0, 0, 0, .35));
}
/* Apply only when a theme with image is installed. */
-body.use-title-container .md-title-container {
+body.use-title-container .md-title {
background-color: white;
/* Necessary for a "pill" shape. Using 50% creates an oval. */
border-radius: 500px;
padding: 0 8px;
}
-body.use-title-container .md-tile-container:not(.reorder) .md-title {
+body.use-title-container .md-tile:not(.reorder) {
color: rgb(var(--GG800-rgb));
filter: unset;
}
@@ -345,8 +319,10 @@ body:not(.reordering) .md-menu:focus:not(.mouse-navigation) {
width: var(--md-menu-size);
}
-html[darkmode=true] .md-menu::after {
- background-color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ .md-menu::after {
+ background-color: rgb(var(--GG200-rgb));
+ }
}
.md-edit-menu {
@@ -366,19 +342,24 @@ body:not(.reordering) .md-menu:focus::after {
background-color: rgb(var(--GG700-rgb));
}
-html[darkmode=true] body:not(.reordering) .md-menu:hover::after,
-html[darkmode=true] body:not(.reordering) .md-menu:focus::after {
- background-color: rgb(var(--GG400-rgb));
+@media (prefers-color-scheme: dark) {
+ body:not(.reordering) .md-menu:hover::after,
+ body:not(.reordering) .md-menu:focus::after {
+ background-color: rgb(var(--GG400-rgb));
+ }
}
-body.dark-theme .md-tile-container:not(.reorder) .md-menu::after,
+body.dark-theme .md-tile:not(.reorder) .md-menu::after,
body.dark-theme:not(.reordering) .md-menu:focus:not(.mouse-navigation)::after {
background-color: white;
}
-html[darkmode=true] body.dark-theme .md-tile-container:not(.reorder) .md-menu::after,
-html[darkmode=true] body.dark-theme:not(.reordering) .md-menu:focus:not(.mouse-navigation)::after {
- background-color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ body.dark-theme .md-tile:not(.reorder) .md-menu::after,
+ body.dark-theme:not(.reordering)
+ .md-menu:focus:not(.mouse-navigation)::after {
+ background-color: rgb(var(--GG200-rgb));
+ }
}
body.dark-theme:not(.reordering) .md-menu:active::after,
@@ -387,8 +368,10 @@ body.dark-theme:not(.reordering) .md-menu.mouse-navigation:focus::after {
background-color: rgb(var(--GG300-rgb));
}
-html[darkmode=true] body.dark-theme:not(.reordering) .md-menu:active::after,
-html[darkmode=true] body.dark-theme:not(.reordering) .md-menu:hover::after,
-html[darkmode=true] body.dark-theme:not(.reordering) .md-menu.mouse-navigation:focus::after {
- background-color: rgb(var(--GG400-rgb));
+@media (prefers-color-scheme: dark) {
+ body.dark-theme:not(.reordering) .md-menu:active::after,
+ body.dark-theme:not(.reordering) .md-menu:hover::after,
+ body.dark-theme:not(.reordering) .md-menu.mouse-navigation:focus::after {
+ background-color: rgb(var(--GG400-rgb));
+ }
}
diff --git a/chromium/chrome/browser/resources/local_ntp/most_visited_single.js b/chromium/chrome/browser/resources/local_ntp/most_visited_single.js
index 4fc4e5d6c7f..f26d493e0c4 100644
--- a/chromium/chrome/browser/resources/local_ntp/most_visited_single.js
+++ b/chromium/chrome/browser/resources/local_ntp/most_visited_single.js
@@ -11,7 +11,6 @@
function MostVisited() {
'use strict';
-
/**
* Enum for key codes.
* @enum {number}
@@ -40,7 +39,6 @@ const IDS = {
MV_TILES: 'mv-tiles', // Most Visited tiles container.
};
-
/**
* Enum for classnames.
* @enum {string}
@@ -53,28 +51,24 @@ const CLASSES = {
GRID_REORDER: 'grid-reorder',
GRID_TILE: 'grid-tile',
GRID_TILE_CONTAINER: 'grid-tile-container',
+ HIDE: 'hide', // Applied when the tiles are hidden by the user.
REORDER: 'reorder', // Applied to the tile being moved while reordering.
// Applied while we are reordering. Disables hover styling.
REORDERING: 'reordering',
MAC_CHROMEOS: 'mac-chromeos', // Reduces font weight for MacOS and ChromeOS.
// Material Design classes.
MD_EMPTY_TILE: 'md-empty-tile',
- MD_ICON_BACKGROUND: 'md-icon-background',
MD_FALLBACK_LETTER: 'md-fallback-letter',
- MD_FAVICON: 'md-favicon',
MD_ICON: 'md-icon',
MD_ADD_ICON: 'md-add-icon',
MD_MENU: 'md-menu',
MD_EDIT_MENU: 'md-edit-menu',
MD_TILE: 'md-tile',
- MD_TILE_CONTAINER: 'md-tile-container',
MD_TILE_INNER: 'md-tile-inner',
MD_TITLE: 'md-title',
- MD_TITLE_CONTAINER: 'md-title-container',
NO_INITIAL_FADE: 'no-initial-fade',
};
-
/**
* The different types of events that are logged from the NTP. This enum is
* used to transfer information from the NTP JavaScript to the renderer and is
@@ -86,21 +80,12 @@ const CLASSES = {
const LOG_TYPE = {
// All NTP tiles have finished loading (successfully or failing).
NTP_ALL_TILES_LOADED: 11,
- // The data for all NTP tiles (title, URL, etc, but not the thumbnail image)
- // has been received. In contrast to NTP_ALL_TILES_LOADED, this is recorded
- // before the actual DOM elements have loaded (in particular the thumbnail
- // images).
- NTP_ALL_TILES_RECEIVED: 12,
-
- // Shortcuts have been customized.
- NTP_SHORTCUT_CUSTOMIZED: 39,
// The 'Add shortcut' link was clicked.
NTP_CUSTOMIZE_ADD_SHORTCUT_CLICKED: 44,
// The 'Edit shortcut' link was clicked.
NTP_CUSTOMIZE_EDIT_SHORTCUT_CLICKED: 45,
};
-
/**
* The different (visual) types that an NTP tile can have.
* Note: Keep in sync with components/ntp_tiles/tile_visual_type.h
@@ -116,7 +101,6 @@ const TileVisualType = {
THUMBNAIL_FAILED: 8,
};
-
/**
* Timeout delay for the window.onresize event throttle. Set to 15 frame per
* second.
@@ -124,28 +108,18 @@ const TileVisualType = {
*/
const RESIZE_TIMEOUT_DELAY = 66;
-
-/**
- * Timeout delay in ms before starting the reorder flow.
- * @const {number}
- */
-const REORDER_TIMEOUT_DELAY = 1000;
-
-
/**
* Maximum number of tiles if custom links is enabled.
* @const {number}
*/
const MD_MAX_NUM_CUSTOM_LINK_TILES = 10;
-
/**
* Maximum number of tiles per row for Material Design.
* @const {number}
*/
const MD_MAX_TILES_PER_ROW = 5;
-
/**
* Height of a tile for Material Design. Keep in sync with
* most_visited_single.css.
@@ -153,7 +127,6 @@ const MD_MAX_TILES_PER_ROW = 5;
*/
const MD_TILE_HEIGHT = 128;
-
/**
* Width of a tile for Material Design. Keep in sync with
* most_visited_single.css.
@@ -161,7 +134,6 @@ const MD_TILE_HEIGHT = 128;
*/
const MD_TILE_WIDTH = 112;
-
/**
* Number of tiles that will always be visible for Material Design. Calculated
* by dividing minimum |--content-width| (see local_ntp.css) by |MD_TILE_WIDTH|
@@ -170,7 +142,6 @@ const MD_TILE_WIDTH = 112;
*/
const MD_NUM_TILES_ALWAYS_VISIBLE = 6;
-
/**
* The origin of this request, i.e. 'https://www.google.TLD' for the remote NTP,
* or 'chrome-search://local-ntp' for the local NTP.
@@ -178,7 +149,6 @@ const MD_NUM_TILES_ALWAYS_VISIBLE = 6;
*/
const DOMAIN_ORIGIN = '{{ORIGIN}}';
-
/**
* Counter for DOM elements that we are waiting to finish loading. Starts out
* at 1 because initially we're waiting for the "show" message from the parent.
@@ -186,7 +156,6 @@ const DOMAIN_ORIGIN = '{{ORIGIN}}';
*/
let loadedCounter = 1;
-
/**
* DOM element containing the tiles we are going to present next.
* Works as a double-buffer that is shown when we receive a "show" postMessage.
@@ -194,7 +163,6 @@ let loadedCounter = 1;
*/
let tiles = null;
-
/**
* Maximum number of MostVisited tiles to show at any time. If the host page
* doesn't send enough tiles and custom links is not enabled, we fill them blank
@@ -204,21 +172,18 @@ let tiles = null;
*/
let maxNumTiles = 8;
-
/**
* List of parameters passed by query args.
* @type {Object}
*/
let queryArgs = {};
-
/**
* True if we are currently reordering the tiles.
* @type {boolean}
*/
let reordering = false;
-
/**
* The tile that is being moved during the reorder flow. Null if we are
* currently not reordering.
@@ -226,13 +191,12 @@ let reordering = false;
*/
let elementToReorder = null;
-
/**
- * True if custom links is enabled.
+ * True if the custom links feature is enabled, i.e. when this is a Google NTP.
+ * Set when the iframe is initialized.
* @type {boolean}
*/
-let isCustomLinksEnabled = false;
-
+let customLinksFeatureEnabled = false;
/**
* True if the grid layout is enabled.
@@ -240,14 +204,12 @@ let isCustomLinksEnabled = false;
*/
let isGridEnabled = false;
-
/**
* The current grid of tiles.
* @type {?Grid}
*/
let currGrid = null;
-
/**
* Called by tests to enable the grid layout.
*/
@@ -256,7 +218,6 @@ function enableGridLayoutForTesting() {
document.body.classList.add(CLASSES.GRID_LAYOUT);
}
-
/**
* Additional API for Array. Moves the item at index |from| to index |to|.
* @param {number} from Index of the item to move.
@@ -266,7 +227,6 @@ Array.prototype.move = function(from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
-
/**
* Class that handles layouts and animations for the tile grid. This includes
* animations for adding, deleting, and reordering.
@@ -317,8 +277,10 @@ class Grid {
this.itemToReorder_ = -1;
/** @private {number} The index to move the tile we're reordering to. */
this.newIndexOfItemToReorder_ = -1;
- }
+ /** @private {boolean} True if the user is currently touching a tile. */
+ this.touchStarted_ = false;
+ }
/**
* Sets up the grid for the new tileset in |container|. The old tileset is
@@ -353,7 +315,7 @@ class Grid {
this.order_[i] = i;
}
- if (isCustomLinksEnabled || params.enableReorder) {
+ if (isCustomLinksEnabled() || params.enableReorder) {
// Set up reordering for all tiles except the add shortcut button.
for (let i = 0; i < this.tiles_.length; i++) {
if (this.tiles_[i].getAttribute('add') !== 'true') {
@@ -365,7 +327,6 @@ class Grid {
this.updateLayout();
}
-
/**
* Returns a grid tile wrapper that contains |tile|.
* @param {!Element} tile The tile element.
@@ -385,7 +346,6 @@ class Grid {
return gridTileContainer;
}
-
/**
* Updates the layout of the tiles. This is called for new tilesets and when
* the window is resized or zoomed. Translates each tile's
@@ -424,7 +384,6 @@ class Grid {
}
}
-
/**
* Called when the window is resized/zoomed. Recalculates maximums for the new
* window size and calls |updateLayout| if necessary.
@@ -439,7 +398,6 @@ class Grid {
}
}
-
/**
* Returns the number of tiles per row. This may be balanced in order to make
* even rows.
@@ -461,7 +419,6 @@ class Grid {
}
}
-
/**
* Returns the maximum number of tiles per row allowed by the window size.
* @return {number} The maximum number of tiles per row.
@@ -471,7 +428,6 @@ class Grid {
return Math.floor(window.innerWidth / this.tileWidth_);
}
-
/**
* Returns row 2's x offset from row 1 in px. This will either be 0 or half a
* tile length.
@@ -488,7 +444,6 @@ class Grid {
return 0;
}
-
/**
* Returns true if the browser is in RTL.
* @return {boolean}
@@ -498,7 +453,6 @@ class Grid {
return document.documentElement.dir === 'rtl';
}
-
/**
* Translates the |element| by (x, y).
* @param {?Element} element The element to apply the transform to.
@@ -514,7 +468,6 @@ class Grid {
element.style.transform = 'translate(' + rtlX + 'px, ' + y + 'px)';
}
-
/**
* Sets up event listeners necessary for tile reordering.
* @param {!Element} tile Tile on which to set the event listeners.
@@ -523,30 +476,82 @@ class Grid {
*/
setupReorder_(tile, index) {
tile.setAttribute('index', index);
+
+ // Set up mouse support.
// Listen for the drag event on the tile instead of the tile container. The
// tile container remains static during the reorder flow.
tile.firstChild.draggable = true;
+ // Prevent default drag events on the shortcut link.
+ const tileItem = tile.firstChild.firstChild;
+ tileItem.draggable = false;
tile.firstChild.addEventListener('dragstart', (event) => {
- this.startReorder_(tile, event);
+ // Support link dragging (i.e. dragging the URL to the omnibox).
+ event.dataTransfer.setData('text/uri-list', tileItem.href);
+ // Remove the ghost image that appears when dragging.
+ const emptyImg = new Image();
+ event.dataTransfer.setDragImage(emptyImg, 0, 0);
+
+ this.startReorder_(tile, event, /*mouseMode=*/ true);
+ });
+ // Show a 'move' cursor while dragging the tile within the grid bounds. This
+ // is mostly intended for Windows, which will otherwise show a 'prohibited'
+ // cursor.
+ tile.addEventListener('dragover', (event) => {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = 'move';
});
- // Listen for the mouseover event on the tile container. If this is placed
- // on the tile instead, it can be triggered while the tile is translated to
- // its new position.
- tile.addEventListener('mouseover', (event) => {
- this.reorderToIndex_(index);
+
+ // Set up touch support.
+ tile.firstChild.addEventListener('touchstart', (startEvent) => {
+ // Ignore subsequent touchstart events, which can be triggered if a
+ // different finger is placed on this tile.
+ if (this.touchStarted_) {
+ return;
+ }
+ this.touchStarted_ = true;
+
+ // Start the reorder flow once the user moves their finger.
+ const startReorder = (moveEvent) => {
+ // Use the cursor position from 'touchstart' as the starting location.
+ this.startReorder_(tile, startEvent, /*mouseMode=*/ false);
+ };
+ // Insert the held tile at the index we are hovering over.
+ const moveOver = (moveEvent) => {
+ // Touch events do not have a 'mouseover' equivalent, so we need to
+ // manually check if we are hovering over a tile. If so, insert the held
+ // tile there.
+ // Note: The first item in |changedTouches| is the current position.
+ const x = moveEvent.changedTouches[0].pageX;
+ const y = moveEvent.changedTouches[0].pageY;
+ this.reorderToIndexAtPoint_(x, y);
+ };
+ // Allow 'touchstart' events again when reordering stops/was never
+ // started.
+ const touchEnd = (endEvent) => {
+ tile.firstChild.removeEventListener('touchmove', startReorder);
+ tile.firstChild.removeEventListener('touchmove', moveOver);
+ tile.firstChild.removeEventListener('touchend', touchEnd);
+ tile.firstChild.removeEventListener('touchcancel', touchEnd);
+ this.touchStarted_ = false;
+ };
+
+ tile.firstChild.addEventListener('touchmove', startReorder, {once: true});
+ tile.firstChild.addEventListener('touchmove', moveOver);
+ tile.firstChild.addEventListener('touchend', touchEnd, {once: true});
+ tile.firstChild.addEventListener('touchcancel', touchEnd, {once: true});
});
}
-
/**
* Starts the reorder flow. Updates the visual style of the held tile to
* indicate that it is being moved and sets up the relevant event listeners.
* @param {!Element} tile Tile that is being moved.
- * @param {!Event} event The 'dragstart' event. Used to obtain the current
- * cursor position
+ * @param {!Event} event The 'dragstart'/'touchmove' event. Used to obtain the
+ * current cursor position
+ * @param {boolean} mouseMode True if the user is using a mouse.
* @private
*/
- startReorder_(tile, event) {
+ startReorder_(tile, event, mouseMode) {
const index = Number(tile.getAttribute('index'));
this.itemToReorder_ = index;
@@ -557,16 +562,44 @@ class Grid {
// Disable other hover/active styling for all tiles.
document.body.classList.add(CLASSES.REORDERING);
- // Set up event listeners for the reorder flow.
- const mouseMove = this.trackCursor_(tile, event.pageX, event.pageY);
- document.addEventListener('mousemove', mouseMove);
- document.addEventListener('mouseup', () => {
- document.removeEventListener('mousemove', mouseMove);
- this.stopReorder_(tile);
- }, {once: true});
+ // Set up event listeners for the reorder flow. Listen for drag events if
+ // |mouseMode|, touch events otherwise.
+ if (mouseMode) {
+ const trackCursor =
+ this.trackCursor_(tile, event.pageX, event.pageY, true);
+ // The 'dragover' event must be tracked at the document level, since the
+ // currently dragged tile will interfere with 'dragover' events on the
+ // other tiles.
+ const dragOver = (dragOverEvent) => {
+ trackCursor(dragOverEvent);
+ // Since the 'dragover' event is not tied to a specific tile, we need to
+ // manually check if we are hovering over a tile. If so, insert the held
+ // tile there.
+ this.reorderToIndexAtPoint_(dragOverEvent.pageX, dragOverEvent.pageY);
+ };
+ document.addEventListener('dragover', dragOver);
+ document.addEventListener('dragend', () => {
+ document.removeEventListener('dragover', dragOver);
+ this.stopReorder_(tile);
+ }, {once: true});
+ } else {
+ // Track the cursor on subsequent 'touchmove' events (the first
+ // 'touchmove' event that starts the reorder flow is ignored).
+ const trackCursor = this.trackCursor_(
+ tile, event.changedTouches[0].pageX, event.changedTouches[0].pageY,
+ false);
+ const touchEnd = (touchEndEvent) => {
+ tile.firstChild.removeEventListener('touchmove', trackCursor);
+ tile.firstChild.removeEventListener('touchend', touchEnd);
+ tile.firstChild.removeEventListener('touchcancel', touchEnd);
+ this.stopReorder_(tile); // Stop the reorder flow.
+ };
+ tile.firstChild.addEventListener('touchmove', trackCursor);
+ tile.firstChild.addEventListener('touchend', touchEnd, {once: true});
+ tile.firstChild.addEventListener('touchcancel', touchEnd, {once: true});
+ }
}
-
/**
* Stops the reorder flow. Resets the held tile's visual style and tells the
* EmbeddedSearchAPI that a tile has been moved.
@@ -591,6 +624,24 @@ class Grid {
this.newIndexOfItemToReorder_ = -1;
}
+ /**
+ * Attempts to insert the currently held tile at the index located at (x, y).
+ * Does nothing if there is no tile at (x, y) or the reorder flow is not
+ * ongoing.
+ * @param {number} x The x coordinate.
+ * @param {number} y The y coordinate.
+ * @private
+ */
+ reorderToIndexAtPoint_(x, y) {
+ const elements = document.elementsFromPoint(x, y);
+ for (let i = 0; i < elements.length; i++) {
+ if (elements[i].classList.contains('grid-tile-container') &&
+ elements[i].getAttribute('index') !== null) {
+ this.reorderToIndex_(Number(elements[i].getAttribute('index')));
+ return;
+ }
+ }
+ }
/**
* Executed only when the reorder flow is ongoing. Inserts the currently held
@@ -619,7 +670,6 @@ class Grid {
}
}
-
/**
* Translates the |tile|'s |CLASSES.GRID_TILE| from |index| to |newIndex|.
* This is done to prevent interference with event listeners on the |tile|'s
@@ -638,7 +688,6 @@ class Grid {
this.translate_(tile.children[0], x, y);
}
-
/**
* Moves |tile| so that it tracks the cursor's position. This is done by
* translating the |tile|'s |CLASSES.GRID_TILE|, which prevents interference
@@ -646,9 +695,10 @@ class Grid {
* @param {!Element} tile Tile that is being moved.
* @param {number} origCursorX Original x cursor position.
* @param {number} origCursorY Original y cursor position.
+ * @param {boolean} mouseMode True if the user is using a mouse.
* @private
*/
- trackCursor_(tile, origCursorX, origCursorY) {
+ trackCursor_(tile, origCursorX, origCursorY, mouseMode) {
const index = Number(tile.getAttribute('index'));
// RTL positions align with the right side of the grid. Therefore, the x
// value must be recalculated to align with the left.
@@ -668,15 +718,16 @@ class Grid {
const minY = 0 - origPosY;
return (event) => {
+ const currX = mouseMode ? event.pageX : event.changedTouches[0].pageX;
+ const currY = mouseMode ? event.pageY : event.changedTouches[0].pageY;
// Do not exceed the iframe borders.
- const x = Math.max(Math.min(event.pageX - origCursorX, maxX), minX);
- const y = Math.max(Math.min(event.pageY - origCursorY, maxY), minY);
+ const x = Math.max(Math.min(currX - origCursorX, maxX), minX);
+ const y = Math.max(Math.min(currY - origCursorY, maxY), minY);
tile.firstChild.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
};
}
}
-
/**
* Log an event on the NTP.
* @param {number} eventType Event from LOG_TYPE.
@@ -689,12 +740,12 @@ function logEvent(eventType) {
* Log impression of an NTP tile.
* @param {number} tileIndex Position of the tile, >= 0 and < |maxNumTiles|.
* @param {number} tileTitleSource The source of the tile's title as received
- * from getMostVisitedItemData.
+ * from getMostVisitedItemData.
* @param {number} tileSource The tile's source as received from
- * getMostVisitedItemData.
+ * getMostVisitedItemData.
* @param {number} tileType The tile's visual type from TileVisualType.
* @param {Date} dataGenerationTime Timestamp representing when the tile was
- * produced by a ranking algorithm.
+ * produced by a ranking algorithm.
*/
function logMostVisitedImpression(
tileIndex, tileTitleSource, tileSource, tileType, dataGenerationTime) {
@@ -706,12 +757,12 @@ function logMostVisitedImpression(
* Log click on an NTP tile.
* @param {number} tileIndex Position of the tile, >= 0 and < |maxNumTiles|.
* @param {number} tileTitleSource The source of the tile's title as received
- * from getMostVisitedItemData.
+ * from getMostVisitedItemData.
* @param {number} tileSource The tile's source as received from
- * getMostVisitedItemData.
+ * getMostVisitedItemData.
* @param {number} tileType The tile's visual type from TileVisualType.
* @param {Date} dataGenerationTime Timestamp representing when the tile was
- * produced by a ranking algorithm.
+ * produced by a ranking algorithm.
*/
function logMostVisitedNavigation(
tileIndex, tileTitleSource, tileSource, tileType, dataGenerationTime) {
@@ -720,6 +771,14 @@ function logMostVisitedNavigation(
}
/**
+ * Returns true if custom links are enabled.
+ */
+function isCustomLinksEnabled() {
+ return customLinksFeatureEnabled &&
+ !chrome.embeddedSearch.newTabPage.isUsingMostVisited;
+}
+
+/**
* Down counts the DOM elements that we are waiting for the page to load.
* When we get to 0, we send a message to the parent window.
* This is usually used as an EventListener of onload/onerror.
@@ -729,14 +788,8 @@ function countLoad() {
if (loadedCounter <= 0) {
swapInNewTiles();
logEvent(LOG_TYPE.NTP_ALL_TILES_LOADED);
- let tilesAreCustomLinks =
- isCustomLinksEnabled && chrome.embeddedSearch.newTabPage.isCustomLinks;
- // Note that it's easiest to capture this when all custom links are loaded,
- // rather than when the impression for each link is logged.
- if (tilesAreCustomLinks) {
- chrome.embeddedSearch.newTabPage.logEvent(
- LOG_TYPE.NTP_SHORTCUT_CUSTOMIZED);
- }
+ let tilesAreCustomLinks = isCustomLinksEnabled() &&
+ chrome.embeddedSearch.newTabPage.isCustomLinks;
// Tell the parent page whether to show the restore default shortcuts option
// in the menu.
window.parent.postMessage(
@@ -749,7 +802,6 @@ function countLoad() {
}
}
-
/**
* Handles postMessages coming from the host page to the iframe.
* Mostly, it dispatches every command to handleCommand.
@@ -764,7 +816,6 @@ function handlePostMessage(event) {
}
}
-
/**
* Handles a single command coming from the host page to the iframe.
* We try to keep the logic here to a minimum and just dispatch to the relevant
@@ -789,18 +840,18 @@ function handleCommand(data) {
}
}
-
/**
* Handler for the 'show' message from the host page.
* @param {!Object} info Data received in the message.
*/
function showTiles(info) {
- logEvent(LOG_TYPE.NTP_ALL_TILES_RECEIVED);
+ document.body.classList.toggle(
+ CLASSES.HIDE, !chrome.embeddedSearch.newTabPage.areShortcutsVisible);
+
utils.setPlatformClass(document.body);
countLoad();
}
-
/**
* Handler for the 'updateTheme' message from the host page.
* @param {!Object} info Data received in the message.
@@ -813,7 +864,6 @@ function updateTheme(info) {
document.body.classList.toggle('use-title-container', info.useTitleContainer);
document.body.classList.toggle('custom-background', info.customBackground);
document.body.classList.toggle('use-white-add-icon', info.useWhiteAddIcon);
- document.documentElement.setAttribute('darkmode', info.isDarkMode);
// Reduce font weight on the default(white) background for Mac and CrOS.
document.body.classList.toggle(
@@ -823,7 +873,6 @@ function updateTheme(info) {
navigator.userAgent.indexOf('CrOS') > -1));
}
-
/**
* Handler for 'focusMenu' message from the host page. Focuses the edited tile's
* menu or the add shortcut tile after closing the custom link edit dialog
@@ -831,15 +880,14 @@ function updateTheme(info) {
* @param {!Object} info Data received in the message.
*/
function focusTileMenu(info) {
- const tile = document.querySelector(`a.md-tile[data-tid="${info.tid}"]`);
- if (info.tid === -1 /* Add shortcut tile */) {
+ const tile = document.querySelector(`a.md-tile[data-rid="${info.rid}"]`);
+ if (info.rid === -1 /* Add shortcut tile */) {
tile.focus();
} else {
tile.parentNode.childNodes[1].focus();
}
}
-
/**
* Removes all old instances of |IDS.MV_TILES| that are pending for deletion.
*/
@@ -851,7 +899,6 @@ function removeAllOldTiles() {
}
}
-
/**
* Called when all tiles have finished loading (successfully or not), including
* their thumbnail images, and we are ready to show the new tiles and drop the
@@ -863,9 +910,9 @@ function swapInNewTiles() {
// Add an "add new custom link" button if we haven't reached the maximum
// number of tiles.
- if (isCustomLinksEnabled && cur.childNodes.length < maxNumTiles) {
+ if (isCustomLinksEnabled() && cur.childNodes.length < maxNumTiles) {
const data = {
- 'tid': -1,
+ 'rid': -1,
'title': queryArgs['addLink'],
'url': '',
'isAddButton': true,
@@ -903,7 +950,7 @@ function swapInNewTiles() {
// Re-balance the tiles if there are more than |MD_MAX_TILES_PER_ROW| in
// order to make even rows.
if (cur.childNodes.length > MD_MAX_TILES_PER_ROW) {
- cur.style.maxWidth = 'calc(var(--md-tile-width) * ' +
+ cur.style.maxWidth = 'calc(var(--md-tile-size) * ' +
Math.ceil(cur.childNodes.length / 2) + ')';
}
}
@@ -925,14 +972,13 @@ function swapInNewTiles() {
tiles = document.createElement('div');
}
-
/**
* Explicitly hide tiles that are not visible in order to prevent keyboard
* navigation.
*/
function updateTileVisibility() {
- const allTiles = document.querySelectorAll(
- '#' + IDS.MV_TILES + ' .' + CLASSES.MD_TILE_CONTAINER);
+ const allTiles =
+ document.querySelectorAll('#' + IDS.MV_TILES + ' .' + CLASSES.MD_TILE);
if (allTiles.length === 0) {
return;
}
@@ -945,7 +991,6 @@ function updateTileVisibility() {
}
}
-
/**
* Handler for the 'show' message from the host page, called when it wants to
* add a suggestion tile.
@@ -961,10 +1006,9 @@ function addTile(args) {
return;
}
- data.tid = data.rid;
if (!data.faviconUrl) {
data.faviconUrl = 'chrome-search://favicon/size/16@' +
- window.devicePixelRatio + 'x/' + data.renderViewId + '/' + data.tid;
+ window.devicePixelRatio + 'x/' + data.renderViewId + '/' + data.rid;
}
tiles.appendChild(renderTile(data));
} else {
@@ -980,10 +1024,10 @@ function addTile(args) {
* @param {Element} tile DOM node of the tile we want to remove.
*/
function blacklistTile(tile) {
- const tid = Number(tile.firstChild.getAttribute('data-tid'));
+ const rid = Number(tile.getAttribute('data-rid'));
- if (isCustomLinksEnabled) {
- chrome.embeddedSearch.newTabPage.deleteMostVisitedItem(tid);
+ if (isCustomLinksEnabled()) {
+ chrome.embeddedSearch.newTabPage.deleteMostVisitedItem(rid);
} else {
tile.classList.add('blacklisted');
tile.addEventListener('transitionend', function(ev) {
@@ -991,22 +1035,20 @@ function blacklistTile(tile) {
return;
}
window.parent.postMessage(
- {cmd: 'tileBlacklisted', tid: Number(tid)}, DOMAIN_ORIGIN);
+ {cmd: 'tileBlacklisted', rid: Number(rid)}, DOMAIN_ORIGIN);
});
}
}
-
/**
* Starts edit custom link flow. Tells host page to show the edit custom link
* dialog and pre-populate it with data obtained using the link's id.
- * @param {?number} tid Restricted id of the tile we want to edit.
+ * @param {?number} rid Restricted id of the tile we want to edit.
*/
-function editCustomLink(tid) {
- window.parent.postMessage({cmd: 'startEditLink', tid: tid}, DOMAIN_ORIGIN);
+function editCustomLink(rid) {
+ window.parent.postMessage({cmd: 'startEditLink', rid: rid}, DOMAIN_ORIGIN);
}
-
/**
* Starts the reorder flow. Updates the visual style of the held tile to
* indicate that it is being moved.
@@ -1025,7 +1067,6 @@ function startReorder(tile) {
}, {once: true});
}
-
/**
* Stops the reorder flow. Resets the held tile's visual style and tells the
* EmbeddedSearchAPI that a tile has been moved.
@@ -1045,50 +1086,19 @@ function stopReorder(tile) {
allTiles[i].setAttribute('data-pos', i);
}
chrome.embeddedSearch.newTabPage.reorderCustomLink(
- Number(tile.firstChild.getAttribute('data-tid')),
- Number(tile.firstChild.getAttribute('data-pos')));
+ Number(tile.getAttribute('data-rid')),
+ Number(tile.getAttribute('data-pos')));
}
-
/**
* Sets up event listeners necessary for tile reordering.
* @param {!Element} tile Tile on which to set the event listeners.
*/
function setupReorder(tile) {
- // Starts the reorder flow after the user has held the mouse button down for
- // |REORDER_TIMEOUT_DELAY|.
- tile.addEventListener('mousedown', (event) => {
- // Do not reorder if the edit menu was clicked or if ctrl/shift/alt/meta is
- // also held down.
- if (event.button == 0 /* LEFT CLICK */ && !event.ctrlKey &&
- !event.shiftKey && !event.altKey && !event.metaKey &&
- !event.target.classList.contains(CLASSES.MD_MENU)) {
- let timeout = -1;
-
- // Cancel the timeout if the user drags the mouse off the tile and
- // releases or if the mouse if released.
- const dragend = () => {
- window.clearTimeout(timeout);
- };
- document.addEventListener('dragend', dragend, {once: true});
-
- const mouseup = () => {
- if (event.button == 0 /* LEFT CLICK */) {
- window.clearTimeout(timeout);
- }
- };
- document.addEventListener('mouseup', mouseup, {once: true});
-
- const timeoutFunc = (dragend_in, mouseup_in) => {
- if (!reordering) {
- startReorder(tile);
- }
- document.removeEventListener('dragend', dragend_in);
- document.removeEventListener('mouseup', mouseup_in);
- };
- // Wait for |REORDER_TIMEOUT_DELAY| before starting the reorder flow.
- timeout = window.setTimeout(
- timeoutFunc.bind(dragend, mouseup), REORDER_TIMEOUT_DELAY);
+ // Starts the reorder flow.
+ tile.addEventListener('dragstart', (event) => {
+ if (!reordering) {
+ startReorder(tile);
}
});
@@ -1113,7 +1123,6 @@ function setupReorder(tile) {
});
}
-
/**
* Renders a MostVisited tile to the DOM.
* @param {?MostVisitedData} data Object containing rid, url, title, favicon,
@@ -1126,7 +1135,6 @@ function renderTile(data) {
return renderMaterialDesignTile(data);
}
-
/**
* Renders a MostVisited tile with Material Design styles.
* @param {?MostVisitedData} data Object containing rid, url, title, favicon,
@@ -1136,24 +1144,19 @@ function renderTile(data) {
* @return {Element}
*/
function renderMaterialDesignTile(data) {
- const mdTileContainer = document.createElement('div');
- mdTileContainer.role = 'none';
-
+ const mdTile = document.createElement('a');
if (data == null) {
- mdTileContainer.className = CLASSES.MD_EMPTY_TILE;
- return mdTileContainer;
+ mdTile.className = CLASSES.MD_EMPTY_TILE;
+ return mdTile;
}
- mdTileContainer.className = CLASSES.MD_TILE_CONTAINER;
+ mdTile.className = CLASSES.MD_TILE;
- // The tile will be appended to tiles.
+ // The tile will be appended to |tiles|.
const position = tiles.children.length;
// This is set in the load/error event for the favicon image.
let tileType = TileVisualType.NONE;
- const mdTile = document.createElement('a');
- mdTile.className = CLASSES.MD_TILE;
- mdTile.tabIndex = 0;
- mdTile.setAttribute('data-tid', data.tid);
+ mdTile.setAttribute('data-rid', data.rid);
mdTile.setAttribute('data-pos', position);
if (utils.isSchemeAllowed(data.url)) {
mdTile.href = data.url;
@@ -1177,7 +1180,7 @@ function renderMaterialDesignTile(data) {
!data.isAddButton) {
event.preventDefault();
event.stopPropagation();
- blacklistTile(mdTileContainer);
+ blacklistTile(mdTile);
} else if (
event.keyCode === KEYCODES.ENTER || event.keyCode === KEYCODES.SPACE) {
event.preventDefault();
@@ -1199,29 +1202,26 @@ function renderMaterialDesignTile(data) {
const mdTileInner = document.createElement('div');
mdTileInner.className = CLASSES.MD_TILE_INNER;
- const mdIcon = document.createElement('div');
- mdIcon.classList.add(CLASSES.MD_ICON);
- mdIcon.classList.add(CLASSES.MD_ICON_BACKGROUND);
-
if (data.isAddButton) {
- const mdAdd = document.createElement('div');
- mdAdd.className = CLASSES.MD_ADD_ICON;
- const addBackground = document.createElement('div');
- addBackground.className = CLASSES.MD_ICON_BACKGROUND;
+ mdTile.tabIndex = 0;
- addBackground.appendChild(mdAdd);
- mdIcon.appendChild(addBackground);
+ const mdIconAdd = document.createElement('div');
+ mdIconAdd.classList.add(CLASSES.MD_ICON);
+ mdIconAdd.classList.add(CLASSES.MD_ADD_ICON);
+
+ mdTileInner.appendChild(mdIconAdd);
} else {
- const fi = document.createElement('img');
+ const mdIcon = document.createElement('img');
+ mdIcon.classList.add(CLASSES.MD_ICON);
// Set title and alt to empty so screen readers won't say the image name.
- fi.title = '';
- fi.alt = '';
+ mdIcon.title = '';
+ mdIcon.alt = '';
const url = new URL('chrome-search://ntpicon/');
url.searchParams.set('size', '24@' + window.devicePixelRatio + 'x');
url.searchParams.set('url', data.url);
- fi.src = url.toString();
+ mdIcon.src = url.toString();
loadedCounter += 1;
- fi.addEventListener('load', function(ev) {
+ mdIcon.addEventListener('load', function(ev) {
// Store the type for a potential later navigation.
tileType = TileVisualType.ICON_REAL;
logMostVisitedImpression(
@@ -1232,17 +1232,16 @@ function renderMaterialDesignTile(data) {
// log.
countLoad();
});
- fi.addEventListener('error', function(ev) {
+ mdIcon.addEventListener('error', function(ev) {
const fallbackBackground = document.createElement('div');
- fallbackBackground.className = CLASSES.MD_ICON_BACKGROUND;
+ fallbackBackground.className = CLASSES.MD_ICON;
const fallbackLetter = document.createElement('div');
fallbackLetter.className = CLASSES.MD_FALLBACK_LETTER;
fallbackLetter.textContent = data.title.charAt(0).toUpperCase();
- mdIcon.classList.add(CLASSES.FAILED_FAVICON);
+ fallbackBackground.classList.add(CLASSES.FAILED_FAVICON);
fallbackBackground.appendChild(fallbackLetter);
- mdIcon.removeChild(fi);
- mdIcon.appendChild(fallbackBackground);
+ mdTileInner.replaceChild(fallbackBackground, mdIcon);
// Store the type for a potential later navigation.
tileType = TileVisualType.ICON_DEFAULT;
@@ -1255,35 +1254,29 @@ function renderMaterialDesignTile(data) {
countLoad();
});
- mdIcon.appendChild(fi);
+ mdTileInner.appendChild(mdIcon);
}
- mdTileInner.appendChild(mdIcon);
-
- const mdTitleContainer = document.createElement('div');
- mdTitleContainer.className = CLASSES.MD_TITLE_CONTAINER;
const mdTitle = document.createElement('div');
mdTitle.className = CLASSES.MD_TITLE;
+ mdTitle.style.direction = data.direction || 'ltr';
const mdTitleTextwrap = document.createElement('span');
mdTitleTextwrap.innerText = data.title;
- mdTitle.style.direction = data.direction || 'ltr';
- mdTitleContainer.appendChild(mdTitle);
- mdTileInner.appendChild(mdTitleContainer);
- mdTile.appendChild(mdTileInner);
- mdTileContainer.appendChild(mdTile);
mdTitle.appendChild(mdTitleTextwrap);
+ mdTileInner.appendChild(mdTitle);
+ mdTile.appendChild(mdTileInner);
if (!data.isAddButton) {
const mdMenu = document.createElement('button');
mdMenu.className = CLASSES.MD_MENU;
- if (isCustomLinksEnabled) {
+ if (isCustomLinksEnabled()) {
mdMenu.classList.add(CLASSES.MD_EDIT_MENU);
mdMenu.title = queryArgs['editLinkTooltip'] || '';
mdMenu.setAttribute(
'aria-label',
(queryArgs['editLinkTooltip'] || '') + ' ' + data.title);
mdMenu.addEventListener('click', function(ev) {
- editCustomLink(data.tid);
+ editCustomLink(data.rid);
ev.preventDefault();
ev.stopPropagation();
logEvent(LOG_TYPE.NTP_CUSTOMIZE_EDIT_SHORTCUT_CLICKED);
@@ -1294,7 +1287,7 @@ function renderMaterialDesignTile(data) {
'aria-label', (queryArgs['removeTooltip'] || '') + ' ' + data.title);
mdMenu.addEventListener('click', function(ev) {
removeAllOldTiles();
- blacklistTile(mdTileContainer);
+ blacklistTile(mdTile);
ev.preventDefault();
ev.stopPropagation();
});
@@ -1306,23 +1299,21 @@ function renderMaterialDesignTile(data) {
});
utils.disableOutlineOnMouseClick(mdMenu);
- mdTileContainer.appendChild(mdMenu);
+ mdTile.appendChild(mdMenu);
}
if (isGridEnabled) {
- return currGrid.createGridTile(
- mdTileContainer, data.tid, !!data.isAddButton);
+ return currGrid.createGridTile(mdTile, data.rid, !!data.isAddButton);
} else {
// Enable reordering.
- if (isCustomLinksEnabled && !data.isAddButton) {
- mdTileContainer.draggable = 'true';
- setupReorder(mdTileContainer);
+ if (isCustomLinksEnabled() && !data.isAddButton) {
+ mdTile.draggable = 'true';
+ setupReorder(mdTile);
}
- return mdTileContainer;
+ return mdTile;
}
}
-
/**
* Does some initialization and parses the query arguments passed to the iframe.
*/
@@ -1353,7 +1344,7 @@ function init() {
// Enable custom links.
if (queryArgs['enableCustomLinks'] == '1') {
- isCustomLinksEnabled = true;
+ customLinksFeatureEnabled = true;
}
// Enable grid layout.
@@ -1363,7 +1354,7 @@ function init() {
}
// Set the maximum number of tiles to show.
- if (isCustomLinksEnabled) {
+ if (isCustomLinksEnabled()) {
maxNumTiles = MD_MAX_NUM_CUSTOM_LINK_TILES;
}
@@ -1388,7 +1379,6 @@ function init() {
window.addEventListener('message', handlePostMessage);
}
-
/**
* Binds event listeners.
*/
@@ -1396,7 +1386,6 @@ function listen() {
document.addEventListener('DOMContentLoaded', init);
}
-
return {
Grid: Grid, // Exposed for testing.
init: init, // Exposed for testing.
diff --git a/chromium/chrome/browser/resources/local_ntp/most_visited_title.js b/chromium/chrome/browser/resources/local_ntp/most_visited_title.js
index f25e46d5eed..a4264625091 100644
--- a/chromium/chrome/browser/resources/local_ntp/most_visited_title.js
+++ b/chromium/chrome/browser/resources/local_ntp/most_visited_title.js
@@ -2,7 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-
/**
* @fileoverview Rendering for iframed most visited titles.
*/
diff --git a/chromium/chrome/browser/resources/local_ntp/most_visited_util.js b/chromium/chrome/browser/resources/local_ntp/most_visited_util.js
index db4744306fb..0ee762a9f45 100644
--- a/chromium/chrome/browser/resources/local_ntp/most_visited_util.js
+++ b/chromium/chrome/browser/resources/local_ntp/most_visited_util.js
@@ -2,19 +2,16 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-
/**
* @fileoverview Utilities for rendering most visited thumbnails and titles.
*/
-
/**
* The origin of this request.
* @const {string}
*/
const MV_DOMAIN_ORIGIN = '{{ORIGIN}}';
-
/**
* Converts an RGB color number to a hex color string if valid.
* @param {number} color A 6-digit hex RGB color code as a number.
@@ -32,7 +29,6 @@ function convertToHexColor(color) {
return null;
}
-
/**
* Validates a RGBA color component. It must be a number between 0 and 255.
* @param {number} component An RGBA component.
@@ -42,7 +38,6 @@ function isValidRBGAComponent(component) {
return isFinite(component) && component >= 0 && component <= 255;
}
-
/**
* Converts an Array of color components into RGBA format "rgba(R,G,B,A)".
* @param {Array<number>} rgbaColor Array of rgba color components.
@@ -61,7 +56,6 @@ function convertArrayToRGBAColor(rgbaColor) {
return null;
}
-
/**
* Parses query parameters from Location.
* @param {!Location} location The URL to generate the CSS url for.
@@ -86,7 +80,6 @@ function parseQueryParams(location) {
return params;
}
-
/**
* Creates a new most visited link element.
* @param {Object} params URL parameters containing styles for the link.
@@ -156,7 +149,6 @@ function createMostVisitedLink(params, href, title, text, direction) {
return link;
}
-
/**
* Returns the color to display string with, depending on whether title is
* displayed, the current theme, and URL parameters.
@@ -188,7 +180,6 @@ function getTextColor(params, isTitle) {
return c;
}
-
/**
* Decodes most visited styles from URL parameters.
* - c: A hexadecimal number interpreted as a hex color code.
@@ -231,7 +222,6 @@ function getMostVisitedStyles(params, isTitle) {
return styles;
}
-
/**
* Returns whether the given URL has a known, safe scheme.
* @param {string} url URL to check.
@@ -241,7 +231,6 @@ const isSchemeAllowed = function(url) {
url.startsWith('ftp://') || url.startsWith('chrome-extension://');
};
-
/**
* @param {!Location} location A location containing URL parameters.
* @param {function(Object, Object)} fill A function called with styles and
diff --git a/chromium/chrome/browser/resources/local_ntp/utils.js b/chromium/chrome/browser/resources/local_ntp/utils.js
index 5b6f6b34d43..fdd0c6938d1 100644
--- a/chromium/chrome/browser/resources/local_ntp/utils.js
+++ b/chromium/chrome/browser/resources/local_ntp/utils.js
@@ -13,7 +13,6 @@ const CLASSES = {
MOUSE_NAVIGATION: 'mouse-navigation', // Removes blue focus ring.
};
-
/**
* Alias for document.getElementById.
* @param {string} id The ID of the element to find.
@@ -24,13 +23,11 @@ function $(id) {
return document.getElementById(id);
}
-
/**
* Contains common functions used in the main NTP page and its iframes.
*/
const utils = {};
-
/**
* Disables the focus outline for |element| on mousedown.
* @param {Element} element The element to remove the focus outline from.
@@ -44,7 +41,6 @@ utils.disableOutlineOnMouseClick = function(element) {
});
};
-
/**
* Returns whether the given URL has a known, safe scheme.
* @param {string} url URL to check.
@@ -54,7 +50,6 @@ utils.isSchemeAllowed = function(url) {
url.startsWith('ftp://') || url.startsWith('chrome-extension://');
};
-
/**
* Sets CSS class for |element| corresponding to the current platform.
* @param {Element} element The element to set the current platform.
diff --git a/chromium/chrome/browser/resources/local_ntp/voice.css b/chromium/chrome/browser/resources/local_ntp/voice.css
index 57c350ab3c6..a3118e7f2cf 100644
--- a/chromium/chrome/browser/resources/local_ntp/voice.css
+++ b/chromium/chrome/browser/resources/local_ntp/voice.css
@@ -55,8 +55,12 @@
background-color: white;
}
-html[darkmode=true] .overlay-dialog::backdrop {
- background-color: rgb(41, 42, 45);
+@media (prefers-color-scheme: dark) {
+ .overlay-dialog::backdrop {
+ /* Equivalent to --dark-mode-dialog-rgb. CSS variables cannot be used in
+ * pseudo elements. */
+ background-color: rgb(41, 42, 45);
+ }
}
/* The background element. */
@@ -70,9 +74,11 @@ html[darkmode=true] .overlay-dialog::backdrop {
z-index: 10000;
}
-html[darkmode=true] .overlay,
-html[darkmode=true] .overlay-hidden {
- background-color: rgb(41, 42, 45);
+@media (prefers-color-scheme: dark) {
+ .overlay,
+ .overlay-hidden {
+ background-color: rgb(var(--dark-mode-dialog-rgb));
+ }
}
/* Full Page visible style for the background element. */
@@ -104,8 +110,10 @@ html[dir=rtl] .close-button {
right: auto;
}
-html[darkmode=true] .close-button {
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ .close-button {
+ color: rgb(var(--GG200-rgb));
+ }
}
.close-button:hover {
@@ -172,10 +180,13 @@ html[darkmode=true] .close-button {
transition: background-color 218ms, border 218ms, box-shadow 218ms;
}
-html[darkmode=true] .button {
- background-color: rgb(var(--GG900-rgb));
- border-color: rgba(0, 0, 0, 0.1);
- box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.3), 0 4px 8px 3px rgba(0, 0, 0, 0.15);
+@media (prefers-color-scheme: dark) {
+ .button {
+ background-color: rgb(var(--GG900-rgb));
+ border-color: rgba(0, 0, 0, .1);
+ box-shadow: 0 1px 2px 0 rgba(0, 0, 0, .3),
+ 0 4px 8px 3px rgba(0, 0, 0, .15);
+ }
}
/* Button state when speech recognition is inactive. */
@@ -201,8 +212,10 @@ html[darkmode=true] .button {
box-shadow: none;
}
-html[darkmode=true] .voice-rs .button {
- background-color: rgb(var(--GR300-rgb));
+@media (prefers-color-scheme: dark) {
+ .voice-rs .button {
+ background-color: rgb(var(--GR300-rgb));
+ }
}
/* Vibrating input volume level. */
@@ -221,8 +234,10 @@ html[darkmode=true] .voice-rs .button {
width: 301px;
}
-html[darkmode=true] .level {
- background-color: rgb(var(--GG700-rgb));
+@media (prefers-color-scheme: dark) {
+ .level {
+ background-color: rgb(var(--GG700-rgb));
+ }
}
/* Container for scaling and positioning of the button. */
@@ -262,8 +277,10 @@ html[dir=rtl] .overlay-hidden .button-container {
background-color: var(--dark_red);
}
-html[darkmode=true] .voice-rs .button:active {
- background-color: rgb(223, 128, 119);
+@media (prefers-color-scheme: dark) {
+ .voice-rs .button:active {
+ background-color: rgb(223, 128, 119);
+ }
}
/* Style applied to the button when clicked. */
@@ -271,8 +288,10 @@ html[darkmode=true] .voice-rs .button:active {
background-color: var(--light_grey);
}
-html[darkmode=true] .button:active {
- background-color: rgb(53, 54, 57);
+@media (prefers-color-scheme: dark) {
+ .button:active {
+ background-color: rgb(53, 54, 57);
+ }
}
/* TEXT */
@@ -350,8 +369,10 @@ html[dir=rtl] .overlay .voice-text {
color: var(--grey);
}
-html[darkmode=true] #voice-text-i {
- color: rgb(var(--GG500-rgb));
+@media (prefers-color-scheme: dark) {
+ #voice-text-i {
+ color: rgb(var(--GG500-rgb));
+ }
}
/* Final (high confidence) text. */
@@ -359,8 +380,10 @@ html[darkmode=true] #voice-text-i {
color: black;
}
-html[darkmode=true] #voice-text-f {
- color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ #voice-text-f {
+ color: rgb(var(--GG200-rgb));
+ }
}
/* Text area links. */
@@ -373,8 +396,10 @@ html[darkmode=true] #voice-text-f {
text-decoration: underline;
}
-html[darkmode=true] .voice-text-link {
- color: rgb(var(--GB300-rgb));
+@media (prefers-color-scheme: dark) {
+ .voice-text-link {
+ color: rgb(var(--GB300-rgb));
+ }
}
/* Range of motion for the typing animation. */
@@ -460,8 +485,10 @@ html[darkmode=true] .voice-text-link {
width: 24px;
}
-html[darkmode=true] .receiver {
- background-color: rgb(var(--GG500-rgb));
+@media (prefers-color-scheme: dark) {
+ .receiver {
+ background-color: rgb(var(--GG500-rgb));
+ }
}
/* Part 2 of CSS-only microphone icon: the shell and stem wrapper element.
@@ -489,8 +516,10 @@ html[darkmode=true] .receiver {
z-index: 1; /* z-index is only used to specify position relative to stem. */
}
-html[darkmode=true] .stem {
- background-color: rgb(var(--GG500-rgb));
+@media (prefers-color-scheme: dark) {
+ .stem {
+ background-color: rgb(var(--GG500-rgb));
+ }
}
/* Part 4 of CSS-only microphone icon: shell that holds the receiver.
@@ -506,8 +535,10 @@ html[darkmode=true] .stem {
z-index: 0; /* z-index is only used to specify position relative to stem. */
}
-html[darkmode=true] .shell {
- border-color: rgb(var(--GG500-rgb));
+@media (prefers-color-scheme: dark) {
+ .shell {
+ border-color: rgb(var(--GG500-rgb));
+ }
}
/* The .voice-ml style is applied when the UI is in
@@ -517,17 +548,21 @@ html[darkmode=true] .shell {
background-color: var(--listening_icon_color);
}
-html[darkmode=true] .voice-ml .receiver,
-html[darkmode=true] .voice-ml .stem {
- background-color: rgb(var(--GR300-rgb));
+@media (prefers-color-scheme: dark) {
+ .voice-ml .receiver,
+ .voice-ml .stem {
+ background-color: rgb(var(--GR300-rgb));
+ }
}
.voice-ml .shell {
border-color: var(--listening_icon_color);
}
-html[darkmode=true] .voice-ml .shell {
- border-color: rgb(var(--GR300-rgb));
+@media (prefers-color-scheme: dark) {
+ .voice-ml .shell {
+ border-color: rgb(var(--GR300-rgb));
+ }
}
/* The .voice-rs style is applied when the UI is in
@@ -537,15 +572,19 @@ html[darkmode=true] .voice-ml .shell {
background-color: var(--active_icon_color);
}
-html[darkmode=true] .voice-rs .receiver,
-html[darkmode=true] .voice-rs .stem {
- background-color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ .voice-rs .receiver,
+ .voice-rs .stem {
+ background-color: rgb(var(--GG200-rgb));
+ }
}
.voice-rs .shell {
border-color: var(--active_icon_color);
}
-html[darkmode=true] .voice-rs .shell {
- border-color: rgb(var(--GG200-rgb));
+@media (prefers-color-scheme: dark) {
+ .voice-rs .shell {
+ border-color: rgb(var(--GG200-rgb));
+ }
}
diff --git a/chromium/chrome/browser/resources/local_ntp/voice.js b/chromium/chrome/browser/resources/local_ntp/voice.js
index bb16fc896ff..46497631c86 100644
--- a/chromium/chrome/browser/resources/local_ntp/voice.js
+++ b/chromium/chrome/browser/resources/local_ntp/voice.js
@@ -2,10 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-
'use strict';
-
/**
* Get the preferred language for UI localization. Represents Chrome's UI
* language, which might not coincide with the user's "preferred" language
@@ -23,7 +21,6 @@ function getChromeUILanguage() {
return window.navigator.language;
}
-
/**
* The different types of user action and error events that are logged
* from Voice Search. This enum is used to transfer information to
@@ -60,7 +57,6 @@ const LOG_TYPE = {
ERROR_OTHER: 29
};
-
/**
* Enum for keyboard event codes.
* @enum {!string}
@@ -75,7 +71,6 @@ const KEYCODE = {
TAB: 'Tab'
};
-
/**
* The set of possible recognition errors.
* @enum {!number}
@@ -94,7 +89,6 @@ const RecognitionError = {
OTHER: 9
};
-
/**
* Provides methods for communicating with the <a
* href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API">
@@ -102,7 +96,6 @@ const RecognitionError = {
*/
const speech = {};
-
/**
* Localized translations for messages used in the Speech UI.
* @type {{
@@ -137,7 +130,6 @@ speech.messages = {
waiting: ''
};
-
/**
* The set of controller states.
* @enum {number}
@@ -181,7 +173,6 @@ speech.State_ = {
STOPPED: 6
};
-
/**
* Threshold for considering an interim speech transcript result as "confident
* enough". The more confident the API is about a transcript, the higher the
@@ -199,7 +190,6 @@ speech.RECOGNITION_CONFIDENCE_THRESHOLD_ = 0.5;
*/
speech.ERROR_TIMEOUT_SHORT_MS_ = 3000;
-
/**
* Time in milliseconds to wait before closing the UI after an error has
* occured. This is a longer timeout used when there is a click-target is
@@ -209,7 +199,6 @@ speech.ERROR_TIMEOUT_SHORT_MS_ = 3000;
*/
speech.ERROR_TIMEOUT_LONG_MS_ = 8000;
-
/**
* Time in milliseconds to wait before closing the UI if no interaction has
* occured.
@@ -218,7 +207,6 @@ speech.ERROR_TIMEOUT_LONG_MS_ = 8000;
*/
speech.IDLE_TIMEOUT_MS_ = 8000;
-
/**
* Maximum number of characters recognized before force-submitting a query.
* Includes characters of non-confident recognition transcripts.
@@ -227,7 +215,6 @@ speech.IDLE_TIMEOUT_MS_ = 8000;
*/
speech.QUERY_LENGTH_LIMIT_ = 120;
-
/**
* Specifies the current state of the controller.
* Note: Different than the UI state.
@@ -235,14 +222,12 @@ speech.QUERY_LENGTH_LIMIT_ = 120;
*/
speech.currentState_ = speech.State_.UNINITIALIZED;
-
/**
* The ID for the error timer.
* @private {number}
*/
speech.errorTimer_;
-
/**
* The duration of the timeout for the UI elements during an error state.
* Depending on the error state, we have different durations for the timeout.
@@ -250,7 +235,6 @@ speech.errorTimer_;
*/
speech.errorTimeoutMs_ = 0;
-
/**
* The last high confidence voice transcript received from the Web Speech API.
* This is the actual query that could potentially be submitted to Search.
@@ -258,42 +242,36 @@ speech.errorTimeoutMs_ = 0;
*/
speech.finalResult_;
-
/**
* Base URL for sending queries to Search. Includes trailing forward slash.
* @private {string}
*/
speech.googleBaseUrl_;
-
/**
* The ID for the idle timer.
* @private {number}
*/
speech.idleTimer_;
-
/**
* The last low confidence voice transcript received from the Web Speech API.
* @private {string}
*/
speech.interimResult_;
-
/**
* The Web Speech API object driving the speech recognition transaction.
* @private {!webkitSpeechRecognition}
*/
speech.recognition_;
-
/**
* Indicates if the user is using keyboard navigation (i.e. tab).
* @private {boolean}
*/
speech.usingKeyboardNavigation_ = false;
-
/**
* Log an event from Voice Search.
* @param {number} eventType Event from |LOG_TYPE|.
@@ -302,7 +280,6 @@ speech.logEvent = function(eventType) {
window.chrome.embeddedSearch.newTabPage.logEvent(eventType);
};
-
/**
* Initialize the speech module as part of the local NTP. Adds event handlers
* and shows the fakebox microphone icon.
@@ -368,7 +345,6 @@ speech.init = function(
speech.reset_();
};
-
/**
* Initializes and configures the speech recognition API.
* @private
@@ -386,7 +362,6 @@ speech.initWebkitSpeech_ = function() {
speech.recognition_.onspeechstart = speech.handleRecognitionSpeechStart_;
};
-
/**
* Sets up the necessary states for voice search and then starts the
* speech recognition interface.
@@ -421,7 +396,6 @@ speech.start = function() {
}
};
-
/**
* Hides the overlay and resets the speech state.
*/
@@ -432,7 +406,6 @@ speech.stop = function() {
speech.reset_();
};
-
/**
* Resets the internal state to the READY state.
* @private
@@ -450,7 +423,6 @@ speech.reset_ = function() {
speech.usingKeyboardNavigation_ = false;
};
-
/**
* Informs the view that the browser is receiving audio input.
* @param {Event=} opt_event Emitted event for audio start.
@@ -462,7 +434,6 @@ speech.handleRecognitionAudioStart_ = function(opt_event) {
view.setReadyForSpeech();
};
-
/**
* Function is called when the user starts speaking.
* @param {Event=} opt_event Emitted event for speech start.
@@ -474,7 +445,6 @@ speech.handleRecognitionSpeechStart_ = function(opt_event) {
view.setReceivingSpeech();
};
-
/**
* Processes the recognition results arriving from the Web Speech API.
* @param {SpeechRecognitionEvent} responseEvent Event coming from the API.
@@ -540,7 +510,6 @@ speech.handleRecognitionResult_ = function(responseEvent) {
}
};
-
/**
* Convert a |RecognitionError| to a |LOG_TYPE| error constant,
* for UMA logging.
@@ -572,7 +541,6 @@ speech.errorToLogType_ = function(error) {
}
};
-
/**
* Handles state transition for the controller when an error occurs
* during speech recognition.
@@ -592,7 +560,6 @@ speech.onErrorReceived_ = function(error) {
}
};
-
/**
* Called when an error from Web Speech API is received.
* @param {SpeechRecognitionError} error The error event.
@@ -602,7 +569,6 @@ speech.handleRecognitionError_ = function(error) {
speech.onErrorReceived_(speech.getRecognitionError_(error.error));
};
-
/**
* Stops speech recognition when no matches are found.
* @private
@@ -611,7 +577,6 @@ speech.handleRecognitionOnNoMatch_ = function() {
speech.onErrorReceived_(RecognitionError.NO_MATCH);
};
-
/**
* Stops the UI when the Web Speech API reports that it has halted speech
* recognition.
@@ -647,7 +612,6 @@ speech.handleRecognitionEnd_ = function() {
speech.currentState_ = speech.State_.STOPPED;
};
-
/**
* Determines whether the user's browser is probably running on a Mac.
* @return {boolean} True iff the user's browser is running on a Mac.
@@ -657,7 +621,6 @@ speech.isUserAgentMac_ = function() {
return window.navigator.userAgent.includes('Macintosh');
};
-
/**
* Determines, if the given KeyboardEvent |code| is a space or enter key.
* @param {string} code A KeyboardEvent's |code| property.
@@ -675,7 +638,6 @@ speech.isSpaceOrEnter_ = function(code) {
}
};
-
/**
* Determines if the given event's target id is for a button or navigation link.
* @param {string} id An event's target id.
@@ -693,7 +655,6 @@ speech.isButtonOrLink_ = function(id) {
}
};
-
/**
* Handles the following keyboard actions.
* - <CTRL> + <SHIFT> + <.> starts voice input(<CMD> + <SHIFT> + <.> on mac).
@@ -733,7 +694,6 @@ speech.onKeyDown = function(event) {
}
};
-
/**
* Displays the no match error if no interactions occur after some time while
* the interface is active. This is a safety net in case the onend event
@@ -759,7 +719,6 @@ speech.onIdleTimeout_ = function() {
}
};
-
/**
* Aborts the speech recognition interface when the user switches to a new
* tab or window.
@@ -775,7 +734,6 @@ speech.onVisibilityChange_ = function() {
}
};
-
/**
* Aborts the speech session if the UI is showing and omnibox gets focused. Does
* not abort if the user is using keyboard navigation (i.e. tab).
@@ -787,7 +745,6 @@ speech.onOmniboxFocused = function() {
}
};
-
/**
* Change the location of this tab to the new URL. Used for query submission.
* @param {!URL} url The URL to navigate to.
@@ -797,7 +754,6 @@ speech.navigateToUrl_ = function(url) {
window.location.href = url.href;
};
-
/**
* Submits the final spoken speech query to perform a search.
* @private
@@ -824,7 +780,6 @@ speech.submitFinalResult_ = function() {
speech.navigateToUrl_(queryUrl);
};
-
/**
* Returns the error type based on the error string received from the webkit
* speech recognition API.
@@ -877,7 +832,6 @@ speech.getRecognitionErrorTimeout_ = function(error) {
}
};
-
/**
* Resets the idle state timeout.
* @param {number} duration The duration after which to close the UI.
@@ -888,7 +842,6 @@ speech.resetIdleTimer_ = function(duration) {
speech.idleTimer_ = window.setTimeout(speech.onIdleTimeout_, duration);
};
-
/**
* Resets the idle error state timeout.
* @param {number} duration The duration after which to close the UI during an
@@ -900,7 +853,6 @@ speech.resetErrorTimer_ = function(duration) {
speech.errorTimer_ = window.setTimeout(speech.stop, duration);
};
-
/**
* Check to see if the speech recognition interface is running, and has
* received any results.
@@ -911,7 +863,6 @@ speech.hasReceivedResults = function() {
return speech.currentState_ == speech.State_.RESULT_RECEIVED;
};
-
/**
* Check to see if the speech recognition interface is running.
* @return {boolean} True, if the speech recognition interface is running.
@@ -927,7 +878,6 @@ speech.isRecognizing = function() {
return false;
};
-
/**
* Check if the controller is in a state where the UI is definitely hidden.
* Since we show the UI for a few seconds after we receive an error from the
@@ -946,7 +896,6 @@ speech.isUiDefinitelyHidden_ = function() {
return false;
};
-
/**
* Handles click events during speech recognition.
* @param {boolean} shouldSubmit True if a query should be submitted.
@@ -970,36 +919,32 @@ speech.onClick_ = function(shouldSubmit, shouldRetry, navigatingAway) {
}
};
-
/* TEXT VIEW */
+
/**
* Provides methods for styling and animating the text areas
* left of the microphone button.
*/
const text = {};
-
/**
* ID for the "Try Again" link shown in error output.
* @const
*/
text.RETRY_LINK_ID = 'voice-retry-link';
-
/**
* ID for the Voice Search support site link shown in error output.
* @const
*/
text.SUPPORT_LINK_ID = 'voice-support-link';
-
/**
* Class for the links shown in error output.
* @const @private
*/
text.ERROR_LINK_CLASS_ = 'voice-text-link';
-
/**
* Class name for the speech recognition result output area.
* @const @private
@@ -1012,49 +957,42 @@ text.TEXT_AREA_CLASS_ = 'voice-text';
*/
text.LISTENING_ANIMATION_CLASS_ = 'listening-animation';
-
/**
* ID of the final / high confidence speech recognition results element.
* @const @private
*/
text.FINAL_TEXT_AREA_ID_ = 'voice-text-f';
-
/**
* ID of the interim / low confidence speech recognition results element.
* @const @private
*/
text.INTERIM_TEXT_AREA_ID_ = 'voice-text-i';
-
/**
* The line height of the speech recognition results text.
* @const @private
*/
text.LINE_HEIGHT_ = 1.2;
-
/**
* Font size in the full page view in pixels.
* @const @private
*/
text.FONT_SIZE_ = 32;
-
/**
* Delay in milliseconds before showing the initializing message.
* @const @private
*/
text.INITIALIZING_TIMEOUT_MS_ = 300;
-
/**
* Delay in milliseconds before showing the listening message.
* @const @private
*/
text.LISTENING_TIMEOUT_MS_ = 2000;
-
/**
* Base link target for help regarding voice search. To be appended
* with a locale string for proper target site localization.
@@ -1063,35 +1001,30 @@ text.LISTENING_TIMEOUT_MS_ = 2000;
text.SUPPORT_LINK_BASE_ =
'https://support.google.com/chrome/?p=ui_voice_search&hl=';
-
/**
* The final / high confidence speech recognition result element.
* @private {Element}
*/
text.final_;
-
/**
* The interim / low confidence speech recognition result element.
* @private {Element}
*/
text.interim_;
-
/**
* Stores the ID of the initializing message timer.
* @private {number}
*/
text.initializingTimer_;
-
/**
* Stores the ID of the listening message timer.
* @private {number}
*/
text.listeningTimer_;
-
/**
* Finds the text view elements.
*/
@@ -1101,7 +1034,6 @@ text.init = function() {
text.clear();
};
-
/**
* Updates the text elements with new recognition results.
* @param {string} interimText Low confidence speech recognition result text.
@@ -1118,7 +1050,6 @@ text.updateTextArea = function(interimText, opt_finalText = '') {
text.interim_.className = text.final_.className = text.getTextClassName_();
};
-
/**
* Sets the text view to the initializing state. The initializing message
* shown while waiting for permission is not displayed immediately, but after
@@ -1140,7 +1071,6 @@ text.showInitializingMessage = function() {
window.setTimeout(displayMessage, text.INITIALIZING_TIMEOUT_MS_);
};
-
/**
* Sets the text view to the ready state.
*/
@@ -1151,7 +1081,6 @@ text.showReadyMessage = function() {
text.startListeningMessageAnimation_();
};
-
/**
* Display an error message in the text area for the given error.
* @param {RecognitionError} error The error that occured.
@@ -1167,7 +1096,6 @@ text.showErrorMessage = function(error) {
}
};
-
/**
* Returns an error message based on the error.
* @param {RecognitionError} error The error that occured.
@@ -1193,7 +1121,6 @@ text.getErrorMessage_ = function(error) {
}
};
-
/**
* Returns an error message help link based on the error.
* @param {RecognitionError} error The error that occured.
@@ -1229,7 +1156,6 @@ text.getErrorLink_ = function(error) {
}
};
-
/**
* Clears the text elements.
*/
@@ -1243,7 +1169,6 @@ text.clear = function() {
text.final_.className = text.TEXT_AREA_CLASS_;
};
-
/**
* Cancels listening message display.
*/
@@ -1251,7 +1176,6 @@ text.clearListeningTimeout = function() {
window.clearTimeout(text.listeningTimer_);
};
-
/**
* Determines the class name of the text output Elements.
* @return {string} The class name.
@@ -1279,7 +1203,6 @@ text.getTextClassName_ = function() {
return className;
};
-
/**
* Displays the listening message animation after the ready message has been
* shown for |text.LISTENING_TIMEOUT_MS_| milliseconds without further user
@@ -1298,87 +1221,77 @@ text.startListeningMessageAnimation_ = function() {
text.listeningTimer_ =
window.setTimeout(animateListeningText, text.LISTENING_TIMEOUT_MS_);
};
-/* END TEXT VIEW */
+/* END TEXT VIEW */
/* MICROPHONE VIEW */
+
/**
* Provides methods for animating the microphone button and icon
* on the Voice Search full screen overlay.
*/
const microphone = {};
-
/**
* ID for the button Element.
* @const
*/
microphone.RED_BUTTON_ID = 'voice-button';
-
/**
* ID for the level animations Element that indicates input volume.
* @const @private
*/
microphone.LEVEL_ID_ = 'voice-level';
-
/**
* ID for the container of the microphone, red button and level animations.
* @const @private
*/
microphone.CONTAINER_ID_ = 'voice-button-container';
-
/**
* The minimum transform scale for the volume rings.
* @const @private
*/
microphone.LEVEL_SCALE_MINIMUM_ = 0.5;
-
/**
* The range of the transform scale for the volume rings.
* @const @private
*/
microphone.LEVEL_SCALE_RANGE_ = 0.55;
-
/**
* The minimum transition time (in milliseconds) for the volume rings.
* @const @private
*/
microphone.LEVEL_TIME_STEP_MINIMUM_ = 170;
-
/**
* The range of the transition time for the volume rings.
* @const @private
*/
microphone.LEVEL_TIME_STEP_RANGE_ = 10;
-
/**
* The button with the microphone icon.
* @private {Element}
*/
microphone.button_;
-
/**
* The voice level element that is displayed when the user starts speaking.
* @private {Element}
*/
microphone.level_;
-
/**
* Variable to indicate whether level animations are underway.
* @private {boolean}
*/
microphone.isLevelAnimating_ = false;
-
/**
* Creates/finds the output elements for the microphone rendering and animation.
*/
@@ -1390,7 +1303,6 @@ microphone.init = function() {
microphone.level_ = $(microphone.LEVEL_ID_);
};
-
/**
* Starts the volume circles animations, if it has not started yet.
*/
@@ -1401,7 +1313,6 @@ microphone.startInputAnimation = function() {
}
};
-
/**
* Stops the volume circles animations.
*/
@@ -1409,7 +1320,6 @@ microphone.stopInputAnimation = function() {
microphone.isLevelAnimating_ = false;
};
-
/**
* Runs the volume level animation.
* @private
@@ -1431,31 +1341,29 @@ microphone.runLevelAnimation_ = function() {
microphone.level_.style.setProperty('transform', 'scale(' + scale + ')');
window.setTimeout(microphone.runLevelAnimation_, timeStep);
};
-/* END MICROPHONE VIEW */
+/* END MICROPHONE VIEW */
/* VIEW */
+
/**
* Provides methods for manipulating and animating the Voice Search
* full screen overlay.
*/
const view = {};
-
/**
* ID for the close button in the speech output container.
* @const
*/
view.CLOSE_BUTTON_ID = 'voice-close-button';
-
/**
* Class name of the speech recognition interface on the homepage.
* @const @private
*/
view.OVERLAY_CLASS_ = 'overlay';
-
/**
* Class name of the speech recognition interface when it is hidden on the
* homepage.
@@ -1463,91 +1371,78 @@ view.OVERLAY_CLASS_ = 'overlay';
*/
view.OVERLAY_HIDDEN_CLASS_ = 'overlay-hidden';
-
/**
* ID for the dialog that contains the speech recognition interface.
* @const @private
*/
view.DIALOG_ID_ = 'voice-overlay-dialog';
-
/**
* ID for the speech output background.
* @const @private
*/
view.BACKGROUND_ID_ = 'voice-overlay';
-
/**
* ID for the speech output container.
* @const @private
*/
view.CONTAINER_ID_ = 'voice-outer';
-
/**
* Class name used to modify the UI to the 'listening' state.
* @const @private
*/
view.MICROPHONE_LISTENING_CLASS_ = 'outer voice-ml';
-
/**
* Class name used to modify the UI to the 'receiving speech' state.
* @const @private
*/
view.RECEIVING_SPEECH_CLASS_ = 'outer voice-rs';
-
/**
* Class name used to modify the UI to the 'error received' state.
* @const @private
*/
view.ERROR_RECEIVED_CLASS_ = 'outer voice-er';
-
/**
* Class name used to modify the UI to the inactive state.
* @const @private
*/
view.INACTIVE_CLASS_ = 'outer';
-
/**
* Background element and container of all other elements.
* @private {Element}
*/
view.background_;
-
/**
* The container used to position the microphone and text output area.
* @private {Element}
*/
view.container_;
-
/**
* True if the the last error message shown was for the 'no-match' error.
* @private {boolean}
*/
view.isNoMatchShown_ = false;
-
/**
* True if the UI elements are visible.
* @private {boolean}
*/
view.isVisible_ = false;
-
/**
* The function to call when there is a click event.
* @private {Function}
*/
view.onClick_;
-
/**
* Displays the UI.
*/
@@ -1570,7 +1465,6 @@ view.setReadyForSpeech = function() {
}
};
-
/**
* Shows the pulsing animation emanating from the microphone. This should only
* be called when the Web Speech API starts receiving speech input (i.e.,
@@ -1586,7 +1480,6 @@ view.setReceivingSpeech = function() {
}
};
-
/**
* Updates the speech recognition results output with the latest results.
* @param {string} interimResultText Low confidence recognition text (grey).
@@ -1603,7 +1496,6 @@ view.updateSpeechResult = function(interimResultText, finalResultText) {
}
};
-
/**
* Hides the UI and stops animations.
*/
@@ -1615,7 +1507,6 @@ view.hide = function() {
text.clear();
};
-
/**
* Find the page elements that will be used to render the speech recognition
* interface area.
@@ -1633,7 +1524,6 @@ view.init = function(onClick) {
microphone.init();
};
-
/**
* Sets accessibility titles/labels for the page elements.
* @param {!Object} translatedStrings Dictionary of localized title strings.
@@ -1644,7 +1534,6 @@ view.setTitles = function(translatedStrings) {
closeButton.setAttribute('aria-label', translatedStrings.voiceCloseTooltip);
};
-
/**
* Displays an error message and stops animations.
* @param {RecognitionError} error The error type.
@@ -1656,7 +1545,6 @@ view.showError = function(error) {
view.isNoMatchShown_ = (error == RecognitionError.NO_MATCH);
};
-
/**
* Makes the view visible.
* @private
@@ -1670,7 +1558,6 @@ view.showView_ = function() {
}
};
-
/**
* Hides the view.
* @private
@@ -1683,7 +1570,6 @@ view.hideView_ = function() {
view.isVisible_ = false;
};
-
/**
* Stops the animations in the microphone view.
* @private
@@ -1692,7 +1578,6 @@ view.stopMicrophoneAnimations_ = function() {
microphone.stopInputAnimation();
};
-
/**
* Makes sure that a click anywhere closes the UI when it is active.
* @param {!Event} event The click event.
@@ -1726,4 +1611,5 @@ view.onWindowClick_ = function(event) {
view.onClick_(submitQuery, shouldRetry, navigatingAway);
};
+
/* END VIEW */
diff --git a/chromium/chrome/browser/resources/management/icons.html b/chromium/chrome/browser/resources/management/icons.html
index dc4ca72a8f0..2311bf2ec29 100644
--- a/chromium/chrome/browser/resources/management/icons.html
+++ b/chromium/chrome/browser/resources/management/icons.html
@@ -12,6 +12,7 @@
<g id="report"><path d="M15.73 3H8.27L3 8.27v7.46L8.27 21h7.46L21 15.73V8.27L15.73 3zM12 17.3c-.72 0-1.3-.58-1.3-1.3 0-.72.58-1.3 1.3-1.3.72 0 1.3.58 1.3 1.3 0 .72-.58 1.3-1.3 1.3zm1-4.3h-2V7h2v6z"></path></g>
<g id="supervised-user"><path d="M11.99 2c-5.52 0-10 4.48-10 10s4.48 10 10 10 10-4.48 10-10-4.48-10-10-10zm3.61 6.34c1.07 0 1.93.86 1.93 1.93 0 1.07-.86 1.93-1.93 1.93-1.07 0-1.93-.86-1.93-1.93-.01-1.07.86-1.93 1.93-1.93zm-6-1.58c1.3 0 2.36 1.06 2.36 2.36 0 1.3-1.06 2.36-2.36 2.36s-2.36-1.06-2.36-2.36c0-1.31 1.05-2.36 2.36-2.36zm0 9.13v3.75c-2.4-.75-4.3-2.6-5.14-4.96 1.05-1.12 3.67-1.69 5.14-1.69.53 0 1.2.08 1.9.22-1.64.87-1.9 2.02-1.9 2.68zM11.99 20c-.27 0-.53-.01-.79-.04v-4.07c0-1.42 2.94-2.13 4.4-2.13 1.07 0 2.92.39 3.84 1.15-1.17 2.97-4.06 5.09-7.45 5.09z"></path></g>
<g id="timelapse"><path d="M16.24 7.76C15.07 6.59 13.54 6 12 6v6l-4.24 4.24c2.34 2.34 6.14 2.34 8.49 0 2.34-2.34 2.34-6.14-.01-8.48zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"></path></g>
+ <g id="linux"><path d="M 6.9375 22.042969 C 3.867188 20.457031 1.886719 17.347656 1.824219 13.234375 C 1.527344 13.378906 1.1875 13.402344 0.800781 13.265625 C -0.3125 12.875 -0.0625 11.578125 0.34375 10.421875 C 0.683594 9.460938 1.835938 8.761719 2.402344 8.613281 C 3.71875 3.78125 6.804688 0 12 0 C 17.257812 0 20.367188 3.625 21.644531 8.628906 C 22.222656 8.796875 23.324219 9.484375 23.65625 10.421875 C 24.0625 11.578125 24.3125 12.875 23.199219 13.265625 C 22.8125 13.402344 22.472656 13.378906 22.175781 13.234375 C 22.117188 17.375 20.140625 20.472656 17.070312 22.046875 C 17.257812 22.191406 17.363281 22.375 17.363281 22.613281 C 17.363281 23.378906 17.75 24 14.898438 24 C 12.8125 24 12.457031 23.578125 12.417969 23.117188 C 12.28125 23.035156 12.140625 22.910156 12 22.910156 C 11.859375 22.910156 11.71875 23.042969 11.582031 23.128906 C 11.535156 23.582031 11.171875 24 9.101562 24 C 6.25 24 6.636719 23.378906 6.636719 22.613281 C 6.636719 22.371094 6.746094 22.183594 6.9375 22.042969 Z M 12 21.222656 C 17.929688 21.222656 20.070312 17.1875 20.070312 11.820312 C 20.070312 7.371094 18.125 3.28125 14.898438 2.597656 C 13.863281 2.378906 13.136719 4.761719 12 4.761719 C 10.863281 4.761719 10.035156 2.378906 9.101562 2.597656 C 5.863281 3.359375 3.929688 7.605469 3.929688 11.820312 C 3.929688 16.882812 6.070312 21.222656 12 21.222656 Z M 8.277344 9.324219 C 7.589844 9.324219 7.035156 8.789062 7.035156 8.132812 C 7.035156 7.476562 7.589844 6.941406 8.277344 6.941406 C 8.960938 6.941406 9.515625 7.476562 9.515625 8.132812 C 9.515625 8.789062 8.960938 9.324219 8.277344 9.324219 Z M 15.722656 9.324219 C 15.039062 9.324219 14.484375 8.789062 14.484375 8.132812 C 14.484375 7.476562 15.039062 6.941406 15.722656 6.941406 C 16.410156 6.941406 16.964844 7.476562 16.964844 8.132812 C 16.964844 8.789062 16.410156 9.324219 15.722656 9.324219 Z M 12.226562 9.964844 L 13.929688 10.683594 C 14.222656 10.804688 14.355469 11.132812 14.226562 11.414062 C 14.199219 11.46875 14.164062 11.519531 14.121094 11.5625 L 12.425781 13.308594 C 12.210938 13.535156 11.839844 13.546875 11.601562 13.339844 C 11.589844 13.332031 11.578125 13.320312 11.566406 13.308594 L 9.878906 11.558594 C 9.660156 11.332031 9.675781 10.980469 9.914062 10.773438 C 9.960938 10.734375 10.011719 10.703125 10.070312 10.679688 L 11.75 9.964844 C 11.898438 9.902344 12.074219 9.902344 12.226562 9.964844 Z M 12.226562 9.964844"></path></g>
</if>
<g id="account-circle"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"></path><path d="M0 0h24v24H0z" fill="none"></path></g>
<g id="public"><path d="M0 0h24v24H0z" fill="none"></path><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"></path></g>
diff --git a/chromium/chrome/browser/resources/management/management.html b/chromium/chrome/browser/resources/management/management.html
index 62a62bf9147..8b4f15545d9 100644
--- a/chromium/chrome/browser/resources/management/management.html
+++ b/chromium/chrome/browser/resources/management/management.html
@@ -1,6 +1,5 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading"
- $i18n{dark}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=yes">
diff --git a/chromium/chrome/browser/resources/management/management_browser_proxy.js b/chromium/chrome/browser/resources/management/management_browser_proxy.js
index 3d73753a3e6..0633bdcb930 100644
--- a/chromium/chrome/browser/resources/management/management_browser_proxy.js
+++ b/chromium/chrome/browser/resources/management/management_browser_proxy.js
@@ -2,69 +2,69 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.exportPath('management');
-/**
- * @typedef {{
- * name: string,
- * permissions: !Array<string>
- * }}
- */
-management.Extension;
-
-/** @enum {string} */
-management.ReportingType = {
- SECURITY: 'security',
- DEVICE: 'device',
- USER: 'user',
- USER_ACTIVITY: 'user-activity',
- EXTENSIONS: 'extensions'
-};
-
-/**
- * @typedef {{
- * messageId: string,
- * reportingType: !management.ReportingType,
- * }}
- */
-management.BrowserReportingResponse;
-
-/**
- * @typedef {{
- * browserManagementNotice: string,
- * extensionReportingTitle: string,
- * pageSubtitle: string,
- * managed: boolean,
- * overview: string,
- * customerLogo: string,
- * }}
- */
-management.ManagedDataResponse;
-
-// <if expr="chromeos">
-/**
- * @enum {string} Look at ToJSDeviceReportingType usage in
- * management_ui_handler.cc for more details.
- */
-management.DeviceReportingType = {
- SUPERVISED_USER: 'supervised user',
- DEVICE_ACTIVITY: 'device activity',
- STATISTIC: 'device statistics',
- DEVICE: 'device',
- LOGS: 'logs',
- PRINT: 'print'
-};
-
-
-/**
- * @typedef {{
- * messageId: string,
- * reportingType: !management.DeviceReportingType,
- * }}
- */
-management.DeviceReportingResponse;
-// </if>
-
cr.define('management', function() {
+ /**
+ * @typedef {{
+ * name: string,
+ * permissions: !Array<string>
+ * }}
+ */
+ let Extension;
+
+ /** @enum {string} */
+ const ReportingType = {
+ SECURITY: 'security',
+ DEVICE: 'device',
+ USER: 'user',
+ USER_ACTIVITY: 'user-activity',
+ EXTENSIONS: 'extensions'
+ };
+
+ /**
+ * @typedef {{
+ * messageId: string,
+ * reportingType: !management.ReportingType,
+ * }}
+ */
+ let BrowserReportingResponse;
+
+ /**
+ * @typedef {{
+ * browserManagementNotice: string,
+ * extensionReportingTitle: string,
+ * pageSubtitle: string,
+ * managed: boolean,
+ * overview: string,
+ * customerLogo: string,
+ * }}
+ */
+ let ManagedDataResponse;
+
+ // <if expr="chromeos">
+ /**
+ * @enum {string} Look at ToJSDeviceReportingType usage in
+ * management_ui_handler.cc for more details.
+ */
+ const DeviceReportingType = {
+ SUPERVISED_USER: 'supervised user',
+ DEVICE_ACTIVITY: 'device activity',
+ STATISTIC: 'device statistics',
+ DEVICE: 'device',
+ LOGS: 'logs',
+ PRINT: 'print',
+ CROSTINI: 'crostini'
+ };
+
+
+ /**
+ * @typedef {{
+ * messageId: string,
+ * reportingType: !management.DeviceReportingType,
+ * }}
+ */
+ let DeviceReportingResponse;
+ // </if>
+
/** @interface */
class ManagementBrowserProxy {
/** @return {!Promise<!Array<!management.Extension>>} */
@@ -127,7 +127,15 @@ cr.define('management', function() {
cr.addSingletonGetter(ManagementBrowserProxyImpl);
return {
+ BrowserReportingResponse: BrowserReportingResponse,
+ // <if expr="chromeos">
+ DeviceReportingResponse: DeviceReportingResponse,
+ DeviceReportingType: DeviceReportingType,
+ // </if>
+ Extension: Extension,
+ ManagedDataResponse: ManagedDataResponse,
+ ManagementBrowserProxyImpl: ManagementBrowserProxyImpl,
ManagementBrowserProxy: ManagementBrowserProxy,
- ManagementBrowserProxyImpl: ManagementBrowserProxyImpl
+ ReportingType: ReportingType,
};
});
diff --git a/chromium/chrome/browser/resources/management/management_ui.html b/chromium/chrome/browser/resources/management/management_ui.html
index ee5a1aa1b05..725e38c4263 100644
--- a/chromium/chrome/browser/resources/management/management_ui.html
+++ b/chromium/chrome/browser/resources/management/management_ui.html
@@ -2,6 +2,7 @@
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_page_host_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
@@ -14,9 +15,9 @@
<dom-module id="management-ui">
<template>
- <style include="cr-icons cr-hidden-style">
+ <style include="cr-icons cr-hidden-style cr-page-host-style
+ cr-shared-style">
:host {
- @apply --cr-page-host;
color: var(--cr-secondary-text-color);
display: flex;
flex-direction: column;
@@ -92,15 +93,6 @@
font-weight: 500;
}
- h2 {
- @apply --cr-title-text;
- font-size: 13px;
- }
-
- .page-subtitle h2 {
- font-size: 14px;
- }
-
.subtitle {
margin-top: 16px;
}
@@ -116,6 +108,7 @@
}
section:not(.page-subtitle) h2 {
+ font-size: 100%;
margin: 0;
}
@@ -190,7 +183,7 @@
<cr-icon-button class="icon-arrow-back" id="closeButton"
on-click="onTapBack_" aria-label="$i18n{backButton}">
</cr-icon-button>
- <h2>
+ <h2 class="cr-title-text">
[[subtitle_]]
</h2>
</section>
@@ -209,7 +202,7 @@
<if expr="chromeos">
<div hidden="[[!localTrustRoots_]]">
<section>
- <h2>$i18n{localTrustRoots}</h2>
+ <h2 class="cr-title-text">$i18n{localTrustRoots}</h2>
<div class="subtitle" id="trust-roots-configuration">
[[localTrustRoots_]]</div>
</section>
@@ -217,7 +210,7 @@
<template is="dom-if"
if="[[showDeviceReportingInfo_(deviceReportingInfo_)]]">
<section>
- <h2>$i18n{deviceReporting}</h2>
+ <h2 class="cr-title-text">$i18n{deviceReporting}</h2>
<div class="subtitle">
$i18n{deviceConfiguration}
</div>
@@ -237,7 +230,7 @@
<template is="dom-if"
if="[[showBrowserReportingInfo_(browserReportingInfo_)]]">
<section>
- <h2>$i18n{browserReporting}</h2>
+ <h2 class="cr-title-text">$i18n{browserReporting}</h2>
<div class="subtitle">
$i18n{browserReportingExplanation}
</div>
@@ -260,7 +253,7 @@
<template is="dom-if"
if="[[showExtensionReportingInfo_(extensions_)]]">
<section class="extension-reporting">
- <h2>$i18n{extensionReporting}</h2>
+ <h2 class="cr-title-text">$i18n{extensionReporting}</h2>
<div class="subtitle">
[[extensionReportingSubtitle_]]
</div>
diff --git a/chromium/chrome/browser/resources/management/management_ui.js b/chromium/chrome/browser/resources/management/management_ui.js
index afc2712d517..a4984aa83d7 100644
--- a/chromium/chrome/browser/resources/management/management_ui.js
+++ b/chromium/chrome/browser/resources/management/management_ui.js
@@ -2,262 +2,270 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.exportPath('management');
-/**
- * @typedef {{
- * messageIds: !Array<string>,
- * icon: string,
- * }}
- */
-management.BrowserReportingData;
-
-Polymer({
- is: 'management-ui',
-
- behaviors: [
- I18nBehavior,
- WebUIListenerBehavior,
- ],
-
- properties: {
- /**
- * List of messages related to browser reporting.
- * @private {?Array<!management.BrowserReportingData>}
- */
- browserReportingInfo_: Array,
+cr.define('management', function() {
+ /**
+ * @typedef {{
+ * messageIds: !Array<string>,
+ * icon: string,
+ * }}
+ */
+ let BrowserReportingData;
- /**
- * List of messages related to browser reporting.
- * @private {?Array<!management.Extension>}
- */
- extensions_: Array,
+ Polymer({
+ is: 'management-ui',
- // <if expr="chromeos">
- /**
- * List of messages related to device reporting.
- * @private {?Array<!management.DeviceReportingResponse>}
- */
- deviceReportingInfo_: Array,
+ behaviors: [
+ I18nBehavior,
+ WebUIListenerBehavior,
+ ],
- /**
- * Message stating if the Trust Roots are configured.
- * @private
- */
- localTrustRoots_: String,
+ properties: {
+ /**
+ * List of messages related to browser reporting.
+ * @private {?Array<!management.BrowserReportingData>}
+ */
+ browserReportingInfo_: Array,
- /** @private */
- customerLogo_: String,
+ /**
+ * List of messages related to browser reporting.
+ * @private {?Array<!management.Extension>}
+ */
+ extensions_: Array,
- /** @private */
- managementOverview_: String,
+ // <if expr="chromeos">
+ /**
+ * List of messages related to device reporting.
+ * @private {?Array<!management.DeviceReportingResponse>}
+ */
+ deviceReportingInfo_: Array,
- // </if>
+ /**
+ * Message stating if the Trust Roots are configured.
+ * @private
+ */
+ localTrustRoots_: String,
- /** @private */
- subtitle_: String,
+ /** @private */
+ customerLogo_: String,
- // <if expr="not chromeos">
- /** @private */
- managementNoticeHtml_: String,
- // </if>
+ /** @private */
+ managementOverview_: String,
- /** @private */
- managed_: Boolean,
+ // </if>
- /** @private */
- extensionReportingSubtitle_: String,
- },
+ /** @private */
+ subtitle_: String,
+
+ // <if expr="not chromeos">
+ /** @private */
+ managementNoticeHtml_: String,
+ // </if>
- /** @private {?management.ManagementBrowserProxy} */
- browserProxy_: null,
+ /** @private */
+ managed_: Boolean,
- /** @override */
- attached() {
- document.documentElement.classList.remove('loading');
- this.browserProxy_ = management.ManagementBrowserProxyImpl.getInstance();
- this.updateManagedFields_();
- this.initBrowserReportingInfo_();
+ /** @private */
+ extensionReportingSubtitle_: String,
+ },
- this.addWebUIListener(
- 'browser-reporting-info-updated',
- reportingInfo => this.onBrowserReportingInfoReceived_(reportingInfo));
+ /** @private {?management.ManagementBrowserProxy} */
+ browserProxy_: null,
- this.addWebUIListener('managed_data_changed', () => {
+ /** @override */
+ attached() {
+ document.documentElement.classList.remove('loading');
+ this.browserProxy_ = management.ManagementBrowserProxyImpl.getInstance();
this.updateManagedFields_();
- });
+ this.initBrowserReportingInfo_();
- this.getExtensions_();
- // <if expr="chromeos">
- this.getDeviceReportingInfo_();
- this.getLocalTrustRootsInfo_();
- // </if>
- },
+ this.addWebUIListener(
+ 'browser-reporting-info-updated',
+ reportingInfo => this.onBrowserReportingInfoReceived_(reportingInfo));
- /** @private */
- initBrowserReportingInfo_() {
- this.browserProxy_.initBrowserReportingInfo().then(
- reportingInfo => this.onBrowserReportingInfoReceived_(reportingInfo));
- },
+ this.addWebUIListener('managed_data_changed', () => {
+ this.updateManagedFields_();
+ });
- /**
- * @param {!Array<!management.BrowserReportingResponse>} reportingInfo
- * @private
- */
- onBrowserReportingInfoReceived_(reportingInfo) {
- const reportingInfoMap = reportingInfo.reduce((info, response) => {
- info[response.reportingType] = info[response.reportingType] || {
- icon: this.getIconForReportingType_(response.reportingType),
- messageIds: []
+ this.getExtensions_();
+ // <if expr="chromeos">
+ this.getDeviceReportingInfo_();
+ this.getLocalTrustRootsInfo_();
+ // </if>
+ },
+
+ /** @private */
+ initBrowserReportingInfo_() {
+ this.browserProxy_.initBrowserReportingInfo().then(
+ reportingInfo => this.onBrowserReportingInfoReceived_(reportingInfo));
+ },
+
+ /**
+ * @param {!Array<!management.BrowserReportingResponse>} reportingInfo
+ * @private
+ */
+ onBrowserReportingInfoReceived_(reportingInfo) {
+ const reportingInfoMap = reportingInfo.reduce((info, response) => {
+ info[response.reportingType] = info[response.reportingType] || {
+ icon: this.getIconForReportingType_(response.reportingType),
+ messageIds: []
+ };
+ info[response.reportingType].messageIds.push(response.messageId);
+ return info;
+ }, {});
+
+ const reportingTypeOrder = {
+ [management.ReportingType.SECURITY]: 1,
+ [management.ReportingType.EXTENSIONS]: 2,
+ [management.ReportingType.USER]: 3,
+ [management.ReportingType.USER_ACTIVITY]: 4,
+ [management.ReportingType.DEVICE]: 5,
};
- info[response.reportingType].messageIds.push(response.messageId);
- return info;
- }, {});
-
- const reportingTypeOrder = {
- [management.ReportingType.SECURITY]: 1,
- [management.ReportingType.EXTENSIONS]: 2,
- [management.ReportingType.USER]: 3,
- [management.ReportingType.USER_ACTIVITY]: 4,
- [management.ReportingType.DEVICE]: 5,
- };
-
- this.browserReportingInfo_ =
- Object.keys(reportingInfoMap)
- .sort((a, b) => reportingTypeOrder[a] - reportingTypeOrder[b])
- .map(reportingType => reportingInfoMap[reportingType]);
- },
-
- /** @private */
- getExtensions_() {
- this.browserProxy_.getExtensions().then(extensions => {
- this.extensions_ = extensions;
- });
- },
-
- // <if expr="chromeos">
- /** @private */
- getLocalTrustRootsInfo_() {
- this.browserProxy_.getLocalTrustRootsInfo().then(trustRootsConfigured => {
- this.localTrustRoots_ = trustRootsConfigured ?
- loadTimeData.getString('managementTrustRootsConfigured') :
- '';
- });
- },
-
- /** @private */
- getDeviceReportingInfo_() {
- this.browserProxy_.getDeviceReportingInfo().then(reportingInfo => {
- this.deviceReportingInfo_ = reportingInfo;
- });
- },
- /**
- * @return {boolean} True of there are device reporting info to show.
- * @private
- */
- showDeviceReportingInfo_() {
- return !!this.deviceReportingInfo_ && this.deviceReportingInfo_.length > 0;
- },
+ this.browserReportingInfo_ =
+ Object.keys(reportingInfoMap)
+ .sort((a, b) => reportingTypeOrder[a] - reportingTypeOrder[b])
+ .map(reportingType => reportingInfoMap[reportingType]);
+ },
- /**
- * @param {management.DeviceReportingType} reportingType
- * @return {string} The associated icon.
- * @private
- */
- getIconForDeviceReportingType_(reportingType) {
- switch (reportingType) {
- case management.DeviceReportingType.SUPERVISED_USER:
- return 'management:supervised-user';
- case management.DeviceReportingType.DEVICE_ACTIVITY:
- return 'management:timelapse';
- case management.DeviceReportingType.STATISTIC:
- return 'management:bar-chart';
- case management.DeviceReportingType.DEVICE:
- return 'cr:computer';
- case management.DeviceReportingType.LOGS:
- return 'management:report';
- case management.DeviceReportingType.PRINT:
- return 'cr:print';
- default:
- return 'cr:computer';
- }
- },
- // </if>
+ /** @private */
+ getExtensions_() {
+ this.browserProxy_.getExtensions().then(extensions => {
+ this.extensions_ = extensions;
+ });
+ },
- /**
- * @return {boolean} True of there are browser reporting info to show.
- * @private
- */
- showBrowserReportingInfo_() {
- return !!this.browserReportingInfo_ &&
- this.browserReportingInfo_.length > 0;
- },
+ // <if expr="chromeos">
+ /** @private */
+ getLocalTrustRootsInfo_() {
+ this.browserProxy_.getLocalTrustRootsInfo().then(trustRootsConfigured => {
+ this.localTrustRoots_ = trustRootsConfigured ?
+ loadTimeData.getString('managementTrustRootsConfigured') :
+ '';
+ });
+ },
- /**
- * @return {boolean} True of there are extension reporting info to show.
- * @private
- */
- showExtensionReportingInfo_() {
- return !!this.extensions_ && this.extensions_.length > 0;
- },
+ /** @private */
+ getDeviceReportingInfo_() {
+ this.browserProxy_.getDeviceReportingInfo().then(reportingInfo => {
+ this.deviceReportingInfo_ = reportingInfo;
+ });
+ },
- /**
- * @param {management.ReportingType} reportingType
- * @returns {string} The associated icon.
- * @private
- */
- getIconForReportingType_(reportingType) {
- switch (reportingType) {
- case management.ReportingType.SECURITY:
- return 'cr:security';
- case management.ReportingType.DEVICE:
- return 'cr:computer';
- case management.ReportingType.EXTENSIONS:
- return 'cr:extension';
- case management.ReportingType.USER:
- return 'management:account-circle';
- case management.ReportingType.USER_ACTIVITY:
- return 'management:public';
- default:
- return 'cr:security';
- }
- },
+ /**
+ * @return {boolean} True of there are device reporting info to show.
+ * @private
+ */
+ showDeviceReportingInfo_() {
+ return !!this.deviceReportingInfo_ &&
+ this.deviceReportingInfo_.length > 0;
+ },
- /**
- * Handles the 'search-changed' event fired from the toolbar.
- * Redirects to the settings page initialized the the current
- * search query.
- * @param {!CustomEvent<string>} e
- * @private
- */
- onSearchChanged_: function(e) {
- const query = e.detail;
- window.location.href =
- `chrome://settings?search=${encodeURIComponent(query)}`;
- },
-
- /** @private */
- onTapBack_() {
- if (history.length > 1) {
- history.back();
- } else {
- window.location.href = 'chrome://settings/help';
- }
- },
-
- /** @private */
- updateManagedFields_() {
- this.browserProxy_.getContextualManagedData().then(data => {
- this.managed_ = data.managed;
- this.extensionReportingSubtitle_ = data.extensionReportingTitle;
- this.subtitle_ = data.pageSubtitle;
- // <if expr="chromeos">
- this.customerLogo_ = data.customerLogo;
- this.managementOverview_ = data.overview;
- // </if>
- // <if expr="not chromeos">
- this.managementNoticeHtml_ = data.browserManagementNotice;
- // </if>
- });
- },
+ /**
+ * @param {management.DeviceReportingType} reportingType
+ * @return {string} The associated icon.
+ * @private
+ */
+ getIconForDeviceReportingType_(reportingType) {
+ switch (reportingType) {
+ case management.DeviceReportingType.SUPERVISED_USER:
+ return 'management:supervised-user';
+ case management.DeviceReportingType.DEVICE_ACTIVITY:
+ return 'management:timelapse';
+ case management.DeviceReportingType.STATISTIC:
+ return 'management:bar-chart';
+ case management.DeviceReportingType.DEVICE:
+ return 'cr:computer';
+ case management.DeviceReportingType.LOGS:
+ return 'management:report';
+ case management.DeviceReportingType.PRINT:
+ return 'cr:print';
+ case management.DeviceReportingType.CROSTINI:
+ return 'management:linux';
+ default:
+ return 'cr:computer';
+ }
+ },
+ // </if>
+
+ /**
+ * @return {boolean} True of there are browser reporting info to show.
+ * @private
+ */
+ showBrowserReportingInfo_() {
+ return !!this.browserReportingInfo_ &&
+ this.browserReportingInfo_.length > 0;
+ },
+
+ /**
+ * @return {boolean} True of there are extension reporting info to show.
+ * @private
+ */
+ showExtensionReportingInfo_() {
+ return !!this.extensions_ && this.extensions_.length > 0;
+ },
+
+ /**
+ * @param {management.ReportingType} reportingType
+ * @returns {string} The associated icon.
+ * @private
+ */
+ getIconForReportingType_(reportingType) {
+ switch (reportingType) {
+ case management.ReportingType.SECURITY:
+ return 'cr:security';
+ case management.ReportingType.DEVICE:
+ return 'cr:computer';
+ case management.ReportingType.EXTENSIONS:
+ return 'cr:extension';
+ case management.ReportingType.USER:
+ return 'management:account-circle';
+ case management.ReportingType.USER_ACTIVITY:
+ return 'management:public';
+ default:
+ return 'cr:security';
+ }
+ },
+
+ /**
+ * Handles the 'search-changed' event fired from the toolbar.
+ * Redirects to the settings page initialized the the current
+ * search query.
+ * @param {!CustomEvent<string>} e
+ * @private
+ */
+ onSearchChanged_: function(e) {
+ const query = e.detail;
+ window.location.href =
+ `chrome://settings?search=${encodeURIComponent(query)}`;
+ },
+
+ /** @private */
+ onTapBack_() {
+ if (history.length > 1) {
+ history.back();
+ } else {
+ window.location.href = 'chrome://settings/help';
+ }
+ },
+
+ /** @private */
+ updateManagedFields_() {
+ this.browserProxy_.getContextualManagedData().then(data => {
+ this.managed_ = data.managed;
+ this.extensionReportingSubtitle_ = data.extensionReportingTitle;
+ this.subtitle_ = data.pageSubtitle;
+ // <if expr="chromeos">
+ this.customerLogo_ = data.customerLogo;
+ this.managementOverview_ = data.overview;
+ // </if>
+ // <if expr="not chromeos">
+ this.managementNoticeHtml_ = data.browserManagementNotice;
+ // </if>
+ });
+ },
+ });
+
+ return {
+ BrowserReportingData: BrowserReportingData,
+ };
});
diff --git a/chromium/chrome/browser/resources/media_router/BUILD.gn b/chromium/chrome/browser/resources/media_router/BUILD.gn
deleted file mode 100644
index ad4aebea658..00000000000
--- a/chromium/chrome/browser/resources/media_router/BUILD.gn
+++ /dev/null
@@ -1,58 +0,0 @@
-# Copyright 2018 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import("//third_party/closure_compiler/compile_js.gni")
-
-group("closure_compile") {
- deps = [
- ":media_router_resources",
- "elements/issue_banner:closure_compile",
- "elements/media_router_container:closure_compile",
- "elements/media_router_header:closure_compile",
- "elements/media_router_search_highlighter:closure_compile",
- "elements/route_controls:closure_compile",
- "elements/route_details:closure_compile",
- ]
-}
-
-js_type_check("media_router_resources") {
- deps = [
- ":media_router",
- ":media_router_browser_api",
- ":media_router_data",
- ":media_router_ui_interface",
- ]
-}
-
-js_library("media_router") {
- deps = [
- ":media_router_ui_interface",
- "elements/media_router_container:media_router_container_interface",
- "elements/media_router_header:media_router_header",
- "//ui/webui/resources/js:cr",
- ]
-}
-
-js_library("media_router_browser_api") {
- deps = [
- ":media_router_data",
- ]
- externs_list = [ "$externs_path/chrome_send.js" ]
-}
-
-js_library("media_router_data") {
- deps = [
- "//ui/webui/resources/js:cr",
- "//ui/webui/resources/js:load_time_data",
- ]
-}
-
-js_library("media_router_ui_interface") {
- deps = [
- ":media_router_browser_api",
- "elements/media_router_container:media_router_container_interface",
- "elements/media_router_header:media_router_header",
- "elements/route_controls:route_controls_interface",
- ]
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/issue_banner/BUILD.gn b/chromium/chrome/browser/resources/media_router/elements/issue_banner/BUILD.gn
deleted file mode 100644
index 0994f8c3196..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/issue_banner/BUILD.gn
+++ /dev/null
@@ -1,18 +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("//third_party/closure_compiler/compile_js.gni")
-
-js_type_check("closure_compile") {
- deps = [
- ":issue_banner",
- ]
-}
-
-js_library("issue_banner") {
- deps = [
- "../..:media_router_data",
- "//ui/webui/resources/js:i18n_behavior",
- ]
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.css b/chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.css
deleted file mode 100644
index 42347f5fbc5..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.css
+++ /dev/null
@@ -1,61 +0,0 @@
-/* Copyright 2015 The Chromium Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file. */
-
-.blocking {
- background-color: white;
- overflow: hidden;
- position: relative;
- text-align: center;
-}
-
-.blocking > #buttons {
- padding-bottom: 24px;
- padding-top: 20px;
-}
-
-.blocking > div > #title {
- color: rgba(0, 0, 0, 0.87);
- line-height: 1.125em;
- padding: 10px;
- vertical-align: middle;
-}
-
-#blocking-icon {
- color: var(--google-red-500);
- height: 75px;
- padding-top: 24px;
- width: 75px;
-}
-
-.non-blocking {
- background-color: var(--paper-grey-800);
- padding: 16px;
- width: inherit;
-}
-
-.non-blocking > #buttons {
- display: flex;
- flex-direction: row;
- justify-content: flex-end;
- width: 100%;
-}
-
-.non-blocking > #buttons > .button {
- color: var(--paper-blue-300);
-}
-
-.non-blocking > #buttons > #default-button {
- margin-inline-end: 24px;
-}
-
-.non-blocking > div > #title {
- color: rgba(255, 255, 255, 0.87);
- margin-inline-end: 12px;
- overflow: hidden;
- padding-inline-end: 12px;
-}
-
-paper-button {
- margin: 0;
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.html b/chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.html
deleted file mode 100644
index eb9c718b797..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<dom-module id="issue-banner">
- <link rel="import" type="css" href="../../media_router_common.css">
- <link rel="import" type="css" href="issue_banner.css">
- <template>
- <div class$="[[computeIssueClass_(issue)]]">
- <div>
- <div hidden$="[[computeIsBlockingIssueHidden_(issue)]]">
- <iron-icon icon="cr:error-outline" id="blocking-icon">
- </iron-icon>
- </div>
- <div id="title" aria-live="polite" tabindex="0">[[issue.title]]</div>
- </div>
- <div id="buttons">
- <paper-button flat id="opt-button" class="button"
- on-tap="onClickOptAction_"
- hidden$="[[computeOptionalActionHidden_(issue)]]">
- <span>[[secondaryActionButtonText_]]</span>
- </paper-button>
- <paper-button flat id="default-button"
- class="button action" on-tap="onClickDefaultAction_">
- <span>[[defaultActionButtonText_]]</span>
- </paper-button>
- </div>
- </div>
- </template>
-<script src="issue_banner.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.js b/chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.js
deleted file mode 100644
index 21bed916968..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.js
+++ /dev/null
@@ -1,145 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This Polymer element is used to show information about issues related
-// to casting.
-Polymer({
- is: 'issue-banner',
-
- properties: {
- /**
- * Maps an issue action type to the resource identifier of the text shown
- * in the action button.
- * This is a property of issue-banner because it is used in tests. This
- * property should always be set before |issue| is set or updated.
- * @private {!Array<string>}
- */
- actionTypeToButtonTextResource_: {
- type: Array,
- readOnly: true,
- value: function() {
- return ['dismissButton', 'learnMoreText'];
- },
- },
-
- /**
- * The text shown in the default action button.
- * @private {string|undefined}
- */
- defaultActionButtonText_: {
- type: String,
- },
-
- /**
- * The issue to show.
- * @type {?media_router.Issue|undefined}
- */
- issue: {
- type: Object,
- observer: 'updateActionButtonText_',
- },
-
- /**
- * The text shown in the secondary action button.
- * @private {string|undefined}
- */
- secondaryActionButtonText_: {
- type: String,
- },
- },
-
- behaviors: [
- I18nBehavior,
- ],
-
- /**
- * @param {?media_router.Issue} issue
- * @return {boolean} Whether or not to hide the blocking issue UI.
- * @private
- */
- computeIsBlockingIssueHidden_: function(issue) {
- return !issue || !issue.isBlocking;
- },
-
- /**
- * @param {?media_router.Issue} issue The current issue.
- * @return {string} The class for the overall issue-banner.
- * @private
- */
- computeIssueClass_: function(issue) {
- if (!issue) {
- return '';
- }
-
- return issue.isBlocking ? 'blocking' : 'non-blocking';
- },
-
- /**
- * @param {?media_router.Issue} issue
- * @return {boolean} Whether or not to hide the non-blocking issue UI.
- * @private
- */
- computeOptionalActionHidden_: function(issue) {
- return !issue || issue.secondaryActionType === undefined;
- },
-
- /**
- * Fires an issue-action-click event.
- *
- * @param {number} actionType The type of issue action.
- * @private
- */
- fireIssueActionClick_: function(actionType) {
- this.fire('issue-action-click', {
- id: this.issue.id,
- actionType: actionType,
- helpPageId: this.issue.helpPageId
- });
- },
-
- /**
- * Called when a default issue action is clicked.
- *
- * @param {!Event} event The event object.
- * @private
- */
- onClickDefaultAction_: function(event) {
- this.fireIssueActionClick_(this.issue.defaultActionType);
- },
-
- /**
- * Called when an optional issue action is clicked.
- *
- * @param {!Event} event The event object.
- * @private
- */
- onClickOptAction_: function(event) {
- this.fireIssueActionClick_(
- /** @type {number} */ (this.issue.secondaryActionType));
- },
-
- /**
- * Called when |issue| is updated. This updates the default and secondary
- * action button text.
- *
- * @private
- */
- updateActionButtonText_: function() {
- var defaultText = '';
- var secondaryText = '';
- if (this.issue) {
- defaultText = this.i18n(
- this.actionTypeToButtonTextResource_[this.issue.defaultActionType]);
-
- if (this.issue.secondaryActionType !== undefined) {
- secondaryText = this.i18n(
- this.actionTypeToButtonTextResource_[this.issue
- .secondaryActionType]);
- }
- }
-
- this.defaultActionButtonText_ = defaultText;
- this.secondaryActionButtonText_ = secondaryText;
- },
-});
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_container/BUILD.gn b/chromium/chrome/browser/resources/media_router/elements/media_router_container/BUILD.gn
deleted file mode 100644
index be701f7ec4a..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_container/BUILD.gn
+++ /dev/null
@@ -1,39 +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("//third_party/closure_compiler/compile_js.gni")
-
-js_type_check("closure_compile") {
- deps = [
- ":media_router_container",
- ":media_router_container_interface",
- ":pseudo_sink_search_state",
- ]
-}
-
-js_library("media_router_container") {
- deps = [
- ":pseudo_sink_search_state",
- "../..:media_router_browser_api",
- "../..:media_router_data",
- "../../elements/issue_banner:issue_banner",
- "../../elements/media_router_header:media_router_header",
- "../../elements/media_router_search_highlighter:media_router_search_highlighter",
- "../../elements/route_details:route_details",
- ]
- externs_list = [ "../../externs.js" ]
-}
-
-js_library("media_router_container_interface") {
- deps = [
- "../..:media_router_data",
- "../../elements/media_router_header:media_router_header",
- ]
-}
-
-js_library("pseudo_sink_search_state") {
- deps = [
- "../..:media_router_data",
- ]
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.css b/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.css
deleted file mode 100644
index 1c9b605e3cc..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.css
+++ /dev/null
@@ -1,283 +0,0 @@
-/* Copyright 2015 The Chromium Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file. */
-
-.active-sink {
- color: var(--paper-blue-700);
-}
-
-.cast-mode-icon,
-.sink-icon {
- height: var(--non-navigation-icon-size);
- padding-inline-end: 12px;
- padding-inline-start: var(--dialog-padding-start);
- width: var(--non-navigation-icon-size);
-}
-
-#container-header {
- position: fixed;
- width: 100%;
-}
-
-#content {
- position: relative;
-}
-
-#device-missing {
- align-items: center;
- background-color: white;
- display: flex;
- justify-content: center;
- padding: 60px 0;
-}
-
-#device-missing a {
- color: var(--paper-blue-700);
- margin: 8px 0;
- text-align: center;
- text-decoration: none;
-}
-
-#first-run-button {
- background-color: white;
-}
-
-#first-run-button-container {
- display: flex;
- flex-direction: row;
- justify-content: flex-end;
-}
-
-#first-run-cloud-checkbox,
-#first-run-flow-cloud-pref,
-#first-run-text {
- font-size: 1.0em;
- line-height: 1.5em;
-}
-
-#first-run-cloud-checkbox,
-#first-run-text,
-#first-run-title {
- color: white;
- padding-bottom: 24px;
-}
-
-#first-run-cloud-checkbox::shadow #checkboxLabel {
- padding-inline-start: var(-dialog-padding-start);
-}
-
-#first-run-flow {
- background-color: var(--paper-blue-700);
- box-sizing: border-box;
- padding: 24px 16px 4px 16px;
- position: fixed;
- width: 100%;
-}
-
-#first-run-flow a {
- color: white;
- text-decoration: none;
-}
-
-#first-run-flow-cloud-pref {
- color: white;
- display: flex;
-}
-
-.first-run-learn-more {
- font-weight: bold;
- text-transform: uppercase;
-}
-
-#first-run-title {
- font-size: 1.25em;
-}
-
-#issue-banner {
- width: 100%;
-}
-
-#issue-banner.non-blocking {
- bottom: 0;
- display: block;
- margin-top: 0;
-}
-
-#no-search-matches {
- color: rgb(112, 112, 112);
- display: block;
- font-size: 1.2 em;
- padding-bottom: 20px;
- padding-top: 20px;
- text-align: center;
-}
-
-cr-checkbox {
- --cr-checkbox-checked-box-color: white;
- --cr-checkbox-label-color: white;
- --cr-checkbox-mark-color: var(--paper-blue-700);
- --cr-checkbox-ripple-checked-color: white;
- --cr-checkbox-ripple-unchecked-color: white;
- --cr-checkbox-unchecked-box-color: white;
- --cr-checkbox-ripple-opacity: 0.25;
-}
-
-.selectable-item {
- -webkit-appearance: none;
- align-items: center;
- background: none;
- border: none;
- cursor: pointer;
- display: flex;
- font-family: inherit;
- font-size: 1.0em;
- line-height: 0;
- min-height: 0;
- outline: 0;
- padding: 12px 0;
- text-align: initial;
- width: 100%;
-}
-
-.selectable-item:hover,
-.selectable-item:focus {
- background-color: rgb(238, 238, 238);
- border: 0;
-}
-
-.selectable-item.iron-selected {
- font-weight: bold;
-}
-
-iron-selector {
- color: rgba(0, 0, 0, 0.87);
- display: block;
- overflow-x: hidden;
- overflow-y: auto;
- padding-bottom: 0;
- padding-top: 4px;
- user-select: none;
-}
-
-iron-selector#cast-mode-list {
- padding-bottom: 12px;
- padding-top: 4px;
-}
-
-#search-input-container {
- flex-grow: 1;
-}
-
-#search-results {
- overflow-x: hidden;
- overflow-y: auto;
-}
-
-#search-results-container {
- bottom: 0;
- left: 0;
- overflow-x: hidden;
- overflow-y: hidden;
- position: absolute;
- right: 0;
- top: 100%;
-}
-
-#searching-devices-spinner {
- height: 30px;
- width: 30px;
-}
-
-.subheading-text {
- color: var(--paper-grey-600);
- cursor: default;
- font-weight: normal;
- padding-bottom: 4px;
- padding-inline-start: var(--dialog-padding-start);
- padding-top: 12px;
-}
-
-#share-screen-text::after {
- background-color: white;
- font-weight: normal;
-}
-
-.sink-content {
- display: flex;
- flex-direction: row;
- font-weight: normal;
-}
-
-.sink-domain {
- color: var(--paper-grey-600);
- padding-inline-start: 6px;
- /* TODO(crbug/589697): Handle overflow of very long domain names. */
-}
-
-#sink-list {
- overflow-x: hidden;
- overflow-y: auto;
-}
-
-#sink-list-view {
- margin-bottom: 12px;
- position: relative;
-}
-
-.sink-name {
- min-width: 10%;
-}
-
-#search-input-container {
- flex-grow: 1;
-}
-
-#sink-search {
- padding-bottom: 0;
- padding-top: 4px;
- position: absolute;
- top: 100%;
- width: 100%;
- z-index: 1;
-}
-
-/* Separate icon class is a consequence of box-sizing: border-box set by
- * paper-icon-button. This should achieve the same dimensions as .sink-icon. */
-#sink-search-icon {
- margin-inline-start: 4px;
- padding-inline-end: 12px;
- padding-inline-start: 12px;
-}
-
-#sink-search-input {
- --cr-input-background-color: white;
- --cr-input-container: {
- border-radius: 0;
- }
- --cr-input-error-display: none;
- --cr-input-input: {
- border-bottom: 1px solid var(--paper-grey-800);
- }
- --cr-input-padding-end: 0;
- --cr-input-padding-start: 0;
- --cr-input-padding-bottom: 2px;
- --cr-input-padding-top: 2px;
- align-self: center;
- flex-grow: 1;
- font-size: 12px;
- margin-inline-end: 31px;
-}
-
-.sink-subtext {
- color: var(--paper-grey-600);
- padding-top: 8px;
-}
-
-.sink-text {
- flex-flow: row nowrap;
- line-height: normal;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- width: 275px;
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.html b/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.html
deleted file mode 100644
index 393f05c7ed6..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.html
+++ /dev/null
@@ -1,240 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
-<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/iron-selector/iron-selector.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
-<link rel="import" href="../media_router_header/media_router_header.html">
-<link rel="import" href="../route_details/route_details.html">
-<link rel="import" href="../../icons/media_router_icons.html">
-<dom-module id="media-router-container">
- <link rel="import" type="css" href="../../media_router_common.css">
- <link rel="import" type="css" href="media_router_container.css">
- <template>
- <div id="focus-placeholder" tabindex="0"></div>
- <template is="dom-if"
- if="[[computeShowFirstRunFlow_(showFirstRunFlow, currentView_)]]">
- <div id="first-run-flow">
- <div id="first-run-title">[[i18n('firstRunFlowTitle')]]</div>
- <div id="first-run-text">
- <span>[[i18n('firstRunFlowText')]]</span>
- <a href="[[firstRunFlowLearnMoreUrl]]" class="first-run-learn-more"
- target="_blank">
- [[i18n('learnMoreText')]]
- </a>
- </div>
- <div id="first-run-flow-cloud-pref"
- hidden$="[[!showFirstRunFlowCloudPref]]">
- <cr-checkbox checked id="first-run-cloud-checkbox">
- <span>[[getFirstRunFlowCloudPrefText_()]]</span>
- <a href="[[firstRunFlowCloudPrefLearnMoreUrl]]"
- class="first-run-learn-more" target="_blank">
- [[i18n('learnMoreText')]]
- </a>
- </cr-checkbox>
- </div>
- <div id="first-run-button-container">
- <paper-button id="first-run-button" class="button"
- on-tap="acknowledgeFirstRunFlow_">
- <span>[[i18n('firstRunFlowButtonText')]]</span>
- </paper-button>
- </div>
- </div>
- </template>
- <media-router-header id="container-header"
- class$="[[currentView_]]" view="[[currentView_]]"
- heading-text="[[computeHeaderText_(currentView_, headerText)]]"
- arrow-drop-icon-disabled="[[computeIsLaunching_(currentLaunchingSinkId_)]]"
- tooltip="[[computeHeaderTooltip_(currentView_, headerTextTooltip)]]"
- on-back-click="showSinkList_">
- </media-router-header>
- <div id="content">
- <template is="dom-if" if="[[!computeCastModeListHidden_(currentView_)]]">
- <iron-selector id="cast-mode-list" role="presentation"
- selectable=".selectable-item"
- selected="{{selectedCastModeMenuItem_}}">
- <template is="dom-repeat" id="presentationCastModeList"
- items="[[computePresentationCastModeList_(castModeList)]]">
- <button class="selectable-item" on-click="onCastModeClick_">
- <iron-icon class="cast-mode-icon"
- icon="[[computeCastModeIcon_(item)]]">
- </iron-icon>
- <div><span>[[item.host]]</span></div>
- </button>
- </template>
- <div id="share-screen-text" class="subheading-text"
- hidden$="[[computeShareScreenSubheadingHidden_(castModeList)]]">
- <span>[[i18n('shareYourScreenSubheadingText')]]</span>
- </div>
- <template is="dom-repeat" id="shareScreenCastModeList"
- items="[[computeShareScreenCastModeList_(castModeList)]]">
- <button class="selectable-item" on-click="onCastModeClick_">
- <iron-icon class="cast-mode-icon"
- icon="[[computeCastModeIcon_(item)]]">
- </iron-icon>
- <div><span>[[item.description]]</span></div>
- </button>
- </template>
- <div id="cast-local-media-text" class="subheading-text"
- hidden$="[[computeLocalMediaSubheadingHidden_(castModeList)]]">
- <span>[[i18n('castLocalMediaSubheadingText')]]</span>
- </div>
- <template is="dom-repeat" id="localMediaCastModeList"
- items="[[computeLocalMediaCastModeList_(castModeList)]]">
- <button class="selectable-item" on-click="onCastModeClick_">
- <iron-icon class="cast-mode-icon"
- icon="[[computeCastModeIcon_(item)]]">
- </iron-icon>
- <div><span>[[item.description]]</span></div>
- </button>
- </template>
- </iron-selector>
- </template>
- <template is="dom-if"
- if="[[!computeRouteDetailsHidden_(currentView_, issue)]]">
- <route-details id="route-details" route="[[currentRoute_]]"
- shown-cast-mode-value="[[shownCastModeValue_]]"
- sink="[[getSinkForRoute_(currentRoute_)]]"
- is-any-sink-currently-launching=
- "[[computeIsLaunching_(currentLaunchingSinkId_)]]"
- on-change-route-source-click="onChangeRouteSourceClick_"
- on-close-route="onCloseRoute_">
- </route-details>
- </template>
- <div id="sink-list-view"
- hidden$="[[computeSinkListViewHidden_(currentView_, issue)]]">
- <div id="device-missing"
- hidden$="[[computeDeviceMissingHidden_(sinksToShow_)]]">
- <paper-spinner-lite id="searching-devices-spinner" active
- hidden$="[[computeSpinnerHidden_(justOpened_)]]">
- </paper-spinner-lite>
- <a href="[[deviceMissingUrl]]" target="_blank"
- hidden$="[[!computeSpinnerHidden_(justOpened_)]]">
- [[i18n('destinationMissingText')]]
- </a>
- </div>
- <template is="dom-if" if="[[!computeSinkListHidden_(sinksToShow_)]]">
- <div id="sink-list" hidden$="[[hideSinkListForAnimation_]]">
- <iron-selector id="sink-list-paper-menu" role="presentation"
- selectable=".selectable-item">
- <template is="dom-repeat" id="sinkList" items="[[sinksToShow_]]">
- <button class="selectable-item" on-click="onSinkClick_">
- <div class="sink-content">
- <div>
- <iron-icon icon="[[computeSinkIcon_(item)]]"
- hidden$="[[computeSinkIsLaunching_(currentLaunchingSinkId_, item.id)]]"
- class$="[[computeSinkIconClass_(item.id, sinkToRouteMap_)]]">
- </iron-icon>
- <template is="dom-if"
- if="[[computeSinkIsLaunching_(currentLaunchingSinkId_, item.id)]]">
- <paper-spinner-lite class="sink-icon" active>
- </paper-spinner-lite>
- </template>
- </div>
- <div>
- <div class="sink-text">
- <span dir="auto" class="sink-name" title="[[item.name]]">
- [[item.name]]
- </span>
- <template is="dom-if"
- if="[[!computeSinkDomainHidden_(item)]]">
- <span class="sink-domain" title="[[item.domain]]">
- [[item.domain]]
- </span>
- </template>
- </div>
- <template is="dom-if"
- if="[[!computeSinkSubtextHidden_(item, sinkToRouteMap_)]]">
- <div class="sink-text sink-subtext">
- <span>[[computeSinkSubtext_(item, sinkToRouteMap_)]]</span>
- </div>
- </template>
- </div>
- </div>
- </button>
- </template>
- </iron-selector>
- </div>
- </template>
- <template is="dom-if" if="[[searchEnabled_]]">
- <div id="sink-search">
- <div class="sink-content">
- <cr-icon-button id="sink-search-icon"
- iron-icon="media-router:search" on-tap="searchButtonClick_"
- title="[[i18n('searchButtonTitle')]]">
- </cr-icon-button>
- <cr-input id="sink-search-input" value="{{searchInputText_}}"
- placeholder="[[i18n('searchInputLabel')]]">
- </cr-input>
- </div>
- </div>
- </template>
- <template is="dom-if" if="[[!isSearchListHidden_]]">
- <div id="search-results-container">
- <div id="no-search-matches"
- hidden$="[[computeNoMatchesHidden_(searchResultsToShow_, isSearchListHidden_)]]">
- <span>[[i18n('searchNoMatchesText')]]</span>
- </div>
- <div id="search-results"
- hidden$="[[computeSearchResultsHidden_(searchResultsToShow_, isSearchListHidden_)]]">
- <iron-selector id="search-results-paper-menu" selected="0"
- role="presentation" selectable=".selectable-item">
- <template is="dom-repeat" id="searchResults"
- items="[[searchResultsToShow_]]">
- <button class="search-item selectable-item"
- on-click="onSinkClick_">
- <div class="sink-content">
- <div>
- <iron-icon icon="[[computeSinkIcon_(item.sinkItem)]]"
- hidden$="[[computeSinkIsLaunching_(currentLaunchingSinkId_, item.sinkItem.id)]]"
- class$="[[computeSinkIconClass_(item.sinkItem.id, sinkToRouteMap_)]]">
- </iron-icon>
- <template is="dom-if"
- if="[[computeSinkIsLaunching_(currentLaunchingSinkId_, item.sinkItem.id)]]">
- <paper-spinner-lite class="sink-icon" active>
- </paper-spinner-lite>
- </template>
- </div>
- <div>
- <div class="sink-text">
- <media-router-search-highlighter class="sink-name"
- data="[[computeSinkMatchingText_(item)]]"
- title="[[item.sinkItem.name]]">
- </media-router-search-highlighter>
- <template is="dom-if"
- if="[[!computeSinkDomainHidden_(item.sinkItem)]]">
- <span class="sink-domain" title="[[item.sinkItem.domain]]">
- [[item.sinkItem.domain]]
- </span>
- </template>
- </div>
- <template is="dom-if"
- if="[[!computeSinkSubtextHidden_(item.sinkItem, sinkToRouteMap_)]]">
- <div class="sink-text sink-subtext">
- <span>
- [[computeSinkSubtext_(item.sinkItem, sinkToRouteMap_)]]
- </span>
- </div>
- </template>
- </div>
- </div>
- </button>
- </template>
- </iron-selector>
- </div>
- </div>
- </template>
- </div>
- <template is="dom-if"
- if="[[computeIssueBannerShown_(currentView_, issue)]]">
- <issue-banner id="issue-banner" issue="[[issue]]"
- class$="[[computeIssueBannerClass_(issue)]]">
- </issue-banner>
- </template>
- </div>
- </template>
- <script src="pseudo_sink_search_state.js"></script>
- <script src="media_router_container.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js b/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js
deleted file mode 100644
index 830b41b4517..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js
+++ /dev/null
@@ -1,2624 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-/**
- * This Polymer element contains the entire media router interface. It handles
- * hiding and showing specific components.
- * @implements {MediaRouterContainerInterface}
- */
-Polymer({
- is: 'media-router-container',
-
- properties: {
- /**
- * The list of available sinks.
- * @type {!Array<!media_router.Sink>}
- */
- allSinks: {
- type: Array,
- value: [],
- observer: 'reindexSinksAndRebuildSinksToShow_',
- },
-
- /**
- * The last promise in a chain that will be fulfilled when the current
- * animation has finished. It does not return a value; it is strictly a
- * synchronization mechanism.
- * @private {!Promise}
- */
- animationPromise_: {
- type: Object,
- value: function() {
- return Promise.resolve();
- },
- },
-
- /**
- * The list of CastModes to show.
- * @type {!Array<!media_router.CastMode>|undefined}
- */
- castModeList: {
- type: Array,
- observer: 'checkCurrentCastMode_',
- },
-
- /**
- * The ID of the Sink currently being launched.
- * @private {string}
- * TODO(crbug.com/616604): Use per-sink route creation state.
- */
- currentLaunchingSinkId_: {
- type: String,
- value: '',
- },
-
- /**
- * The current route.
- * @private {?media_router.Route|undefined}
- */
- currentRoute_: {
- type: Object,
- },
-
- /**
- * The current view to be shown.
- * @private {?media_router.MediaRouterView|undefined}
- */
- currentView_: {
- type: String,
- observer: 'currentViewChanged_',
- },
-
- /**
- * The URL to open when the device missing link is clicked.
- * @type {string|undefined}
- */
- deviceMissingUrl: {
- type: String,
- },
-
- /**
- * The height of the dialog.
- * @private {number}
- */
- dialogHeight_: {
- type: Number,
- value: 330,
- },
-
- /**
- * The time |this| element calls ready().
- * @private {number|undefined}
- */
- elementReadyTimeMs_: {
- type: Number,
- },
-
- /**
- * Animation player used for running filter transition animations.
- * @private {?Animation}
- */
- filterTransitionPlayer_: {
- type: Object,
- value: null,
- },
-
- /**
- * The URL to open when the cloud services pref learn more link is clicked.
- * @type {string|undefined}
- */
- firstRunFlowCloudPrefLearnMoreUrl: {
- type: String,
- },
-
- /**
- * The URL to open when the first run flow learn more link is clicked.
- * @type {string|undefined}
- */
- firstRunFlowLearnMoreUrl: {
- type: String,
- },
-
- /**
- * The header text for the sink list.
- * @type {string|undefined}
- */
- headerText: {
- type: String,
- },
-
- /**
- * The header text tooltip. This would be descriptive of the
- * source origin, whether a host name, tab URL, etc.
- * @type {string|undefined}
- */
- headerTextTooltip: {
- type: String,
- },
-
- /**
- * An animation player that is used for running dialog height adjustments.
- * @private {?Animation}
- */
- heightAdjustmentPlayer_: {
- type: Object,
- value: null,
- },
-
- /**
- * Whether the sink list is being hidden for animation purposes.
- * @private {boolean}
- */
- hideSinkListForAnimation_: {
- type: Boolean,
- value: false,
- },
-
- /**
- * Records whether the search input is focused when a window blur event is
- * received. This is used to handle search focus edge cases. See
- * |setSearchFocusHandlers_| for details.
- * @private {boolean}
- */
- isSearchFocusedOnWindowBlur_: {
- type: Boolean,
- value: false,
- },
-
- /**
- * Whether the search list is currently hidden.
- * @private {boolean}
- */
- isSearchListHidden_: {
- type: Boolean,
- value: true,
- },
-
- /**
- * The issue to show.
- * @type {?media_router.Issue}
- */
- issue: {
- type: Object,
- value: null,
- observer: 'maybeShowIssueView_',
- },
-
- /**
- * Whether the MR UI was just opened.
- * @private {boolean}
- */
- justOpened_: {
- type: Boolean,
- value: true,
- },
-
- /**
- * Whether the user's mouse is positioned over the dialog.
- * @private {boolean|undefined}
- */
- mouseIsPositionedOverDialog_: {
- type: Boolean,
- },
-
- /**
- * The ID of the route that is currently being created. This is set when
- * route creation is resolved but not ready for its controls to be
- * displayed.
- * @private {string|undefined}
- */
- pendingCreatedRouteId_: {
- type: String,
- },
-
- /**
- * The time the sink list was shown and populated with at least one sink.
- * This is reset whenever the user switches views or there are no sinks
- * available for display.
- * @private {number}
- */
- populatedSinkListSeenTimeMs_: {
- type: Number,
- value: -1,
- },
-
- /**
- * Pseudo sinks from MRPs that represent their ability to accept sink search
- * requests.
- * @private {!Array<!media_router.Sink>}
- */
- pseudoSinks_: {
- type: Array,
- value: [],
- },
-
- /**
- * Helps manage the state of creating a sink and a route from a pseudo sink.
- * @private {PseudoSinkSearchState|undefined}
- */
- pseudoSinkSearchState_: {
- type: Object,
- },
-
- /**
- * Whether the next character input should cause a filter action metric to
- * be sent.
- * @type {boolean}
- * @private
- */
- reportFilterOnInput_: {
- type: Boolean,
- value: false,
- },
-
- /**
- * The list of current routes.
- * @type {!Array<!media_router.Route>|undefined}
- */
- routeList: {
- type: Array,
- observer: 'rebuildRouteMaps_',
- },
-
- /**
- * Maps media_router.Route.id to corresponding media_router.Route.
- * @private {!Object<!string, !media_router.Route>|undefined}
- */
- routeMap_: {
- type: Object,
- },
-
- /**
- * Whether the search feature is enabled and we should show the search
- * input.
- * @private {boolean}
- */
- searchEnabled_: {
- type: Boolean,
- value: false,
- observer: 'searchEnabledChanged_',
- },
-
- /**
- * Search text entered by the user into the sink search input.
- * @private {string}
- */
- searchInputText_: {
- type: String,
- value: '',
- observer: 'searchInputTextChanged_',
- },
-
- /**
- * Sinks to display that match |searchInputText_|.
- * @private {!Array<!{sinkItem: !media_router.Sink,
- * substrings: Array<!Array<number>>}>|undefined}
- */
- searchResultsToShow_: {
- type: Array,
- },
-
- /**
- * The selected cast mode menu item. The item with this index is bolded in
- * the cast mode menu.
- * @private {number|undefined}
- */
- selectedCastModeMenuItem_: {
- type: Number,
- observer: 'updateSelectedCastModeMenuItem_',
- },
-
- /**
- * Whether to show the user domain of sinks associated with identity.
- * @type {boolean|undefined}
- */
- showDomain: {
- type: Boolean,
- },
-
- /**
- * Whether to show the first run flow.
- * @type {boolean|undefined}
- */
- showFirstRunFlow: {
- type: Boolean,
- observer: 'updateElementPositioning_',
- },
-
- /**
- * Whether to show the cloud preference setting in the first run flow.
- * @type {boolean|undefined}
- */
- showFirstRunFlowCloudPref: {
- type: Boolean,
- },
-
- /**
- * The cast mode shown to the user. Initially populated within
- * |rebuildSinksToShow_()|.
- * This value may be changed in one of the following ways:
- * 1) The user explicitly selected a cast mode.
- * 2) The user selected cast mode is no longer available for the associated
- * WebContents. In this case, the container will reset to auto mode. Note
- * that |userHasSelectedCastMode_| will switch back to false.
- * 3) The sink list changed, and the user had not explicitly selected a cast
- * mode. If the sinks support exactly 1 cast mode, the container will
- * switch to that cast mode. Otherwise, the container will reset to auto
- * mode.
- * @private {number}
- */
- shownCastModeValue_: Number,
-
- /**
- * Max height for the sink list.
- * @private {number}
- */
- sinkListMaxHeight_: {
- type: Number,
- value: 0,
- },
-
- /**
- * Maps media_router.Sink.id to corresponding media_router.Sink.
- * @private {!Object<!string, !media_router.Sink>|undefined}
- */
- sinkMap_: {
- type: Object,
- },
-
- /**
- * Maps media_router.Sink.id to corresponding media_router.Route.
- * @private {!Object<!string, !media_router.Route>}
- */
- sinkToRouteMap_: {
- type: Object,
- value: {},
- },
-
- /**
- * Sinks to show for the currently selected cast mode.
- * @private {!Array<!media_router.Sink>|undefined}
- */
- sinksToShow_: {
- type: Array,
- observer: 'updateElementPositioning_',
- },
-
- /**
- * Whether the user has explicitly selected a cast mode.
- * @private {boolean}
- */
- userHasSelectedCastMode_: {
- type: Boolean,
- value: false,
- },
-
- /**
- * Whether the user has already taken an action.
- * @type {boolean}
- */
- userHasTakenInitialAction_: {
- type: Boolean,
- value: false,
- },
- },
-
- behaviors: [
- I18nBehavior,
- ],
-
- observers: [
- 'maybeUpdateStartSinkDisplayStartTime_(currentView_, sinksToShow_)',
- ],
-
- ready: function() {
- this.elementReadyTimeMs_ = window.performance.now();
- this.showSinkList_();
-
- Polymer.RenderStatus.afterNextRender(this, function() {
- // Import the elements that aren't needed at startup. This reduces
- // initial load time. Delayed loading interferes with getting the
- // offsetHeight of the first-run-flow element in updateElementPositioning_
- // though, so we also make sure it is called after the last load.
- var that = this;
- var loadsRemaining = 3;
- var onload = function() {
- loadsRemaining--;
- if (loadsRemaining > 0) {
- return;
- }
- that.updateElementPositioning_();
- if (that.currentView_ == media_router.MediaRouterView.SINK_LIST) {
- that.putSearchAtBottom_();
- }
- };
- this.importHref(
- 'chrome://resources/polymer/v1_0/neon-animation/' +
- 'web-animations.html',
- onload);
- this.importHref(
- this.resolveUrl('../issue_banner/issue_banner.html'), onload);
- this.importHref(
- this.resolveUrl(
- '../media_router_search_highlighter/' +
- 'media_router_search_highlighter.html'),
- onload);
-
- // If this is not on a Mac platform, remove the placeholder. See
- // onFocus_() for more details. ready() is only called once, so no need
- // to check if the placeholder exist before removing.
- if (!cr.isMac) {
- this.$$('#focus-placeholder').remove();
- }
-
- document.addEventListener('keydown', this.onKeydown_.bind(this), true);
- this.listen(this, 'focus', 'onFocus_');
- this.listen(this, 'header-height-changed', 'updateElementPositioning_');
- this.listen(this, 'header-or-arrow-click', 'toggleCastModeHidden_');
- this.listen(this, 'mouseleave', 'onMouseLeave_');
- this.listen(this, 'mouseenter', 'onMouseEnter_');
-
- // Turn off the spinner after 3 seconds, then report the current number of
- // sinks.
- this.async(function() {
- this.justOpened_ = false;
- // |pseudoSinks_| does not contain pseudo sinks without a domain, so it
- // cannot be used for calculating the number of real sinks.
- var realSinks = this.allSinks.filter(function(sink) {
- return !sink.isPseudoSink;
- });
- this.fire('report-sink-count', {
- sinkCount: realSinks.length,
- });
- }, 3000 /* 3 seconds */);
-
- // For Mac platforms, request data after a short delay after load. This
- // appears to speed up initial data load time on Mac.
- if (cr.isMac) {
- this.async(function() {
- this.fire('request-initial-data');
- }, 25 /* 0.025 seconds */);
- }
- });
- },
-
- /**
- * Fires an acknowledge-first-run-flow event and hides the first run flow.
- * This is call when the first run flow button is clicked.
- *
- * @private
- */
- acknowledgeFirstRunFlow_: function() {
- // Only set |userOptedIntoCloudServices| if the user was shown the cloud
- // services preferences option.
- var userOptedIntoCloudServices = this.showFirstRunFlowCloudPref ?
- this.$$('#first-run-cloud-checkbox').checked :
- undefined;
- this.fire('acknowledge-first-run-flow', {
- optedIntoCloudServices: userOptedIntoCloudServices,
- });
-
- this.showFirstRunFlow = false;
- this.showFirstRunFlowCloudPref = false;
- },
-
- /**
- * Fires a 'report-initial-action' event when the user takes their first
- * action after the dialog opens. Also fires a 'report-initial-action-close'
- * event if that initial action is to close the dialog.
- * @param {!media_router.MediaRouterUserAction} initialAction
- */
- maybeReportUserFirstAction: function(initialAction) {
- if (this.userHasTakenInitialAction_) {
- return;
- }
-
- this.fire('report-initial-action', {
- action: initialAction,
- });
-
- if (initialAction == media_router.MediaRouterUserAction.CLOSE) {
- var timeToClose = window.performance.now() - this.elementReadyTimeMs_;
- this.fire('report-initial-action-close', {
- timeMs: timeToClose,
- });
- }
-
- this.userHasTakenInitialAction_ = true;
- },
-
- get header() {
- return this.$['container-header'];
- },
-
- /**
- * Calls all the functions to set the UI to a given cast mode.
- * @param {!media_router.CastMode} castMode The cast mode to set things to.
- * @private
- */
- castModeSelected_(castMode) {
- this.selectCastMode(castMode.type);
- this.fire('cast-mode-selected', {castModeType: castMode.type});
- this.showSinkList_();
- this.maybeReportUserFirstAction(
- media_router.MediaRouterUserAction.CHANGE_MODE);
- },
-
- /**
- * Checks that the currently selected cast mode is still in the
- * updated list of available cast modes. If not, then update the selected
- * cast mode to the first available cast mode on the list.
- */
- checkCurrentCastMode_: function() {
- if (!this.castModeList.length) {
- return;
- }
-
- // If there is a forced mode make sure it is shown.
- if (this.findForcedCastMode_()) {
- this.rebuildSinksToShow_();
- }
-
- // If we are currently showing auto mode, then nothing needs to be done.
- // Otherwise, if the cast mode currently shown no longer exists (regardless
- // of whether it was selected by user), then switch back to auto cast mode.
- if (this.shownCastModeValue_ != media_router.CastModeType.AUTO &&
- !this.findCastModeByType_(this.shownCastModeValue_)) {
- this.setShownCastMode_(media_router.AUTO_CAST_MODE);
- this.rebuildSinksToShow_();
- }
- },
-
- /**
- * Compares two search match objects for sorting. Earlier and longer matches
- * are prioritized.
- *
- * @param {!{sinkItem: !media_router.Sink,
- * substrings: Array<!Array<number>>}} resultA
- * Parameters in |resultA|:
- * sinkItem - sink object.
- * substrings - start-end index pairs of substring matches.
- * @param {!{sinkItem: !media_router.Sink,
- * substrings: Array<!Array<number>>}} resultB
- * Parameters in |resultB|:
- * sinkItem - sink object.
- * substrings - start-end index pairs of substring matches.
- * @return {number} -1 if |resultA| should come before |resultB|, 1 if
- * |resultB| should come before |resultA|, and 0 if they are considered
- * equal.
- */
- compareSearchMatches_: function(resultA, resultB) {
- var substringsA = resultA.substrings;
- var substringsB = resultB.substrings;
- var numberSubstringsA = substringsA.length;
- var numberSubstringsB = substringsB.length;
-
- if (numberSubstringsA == 0 && numberSubstringsB == 0) {
- return 0;
- } else if (numberSubstringsA == 0) {
- return 1;
- } else if (numberSubstringsB == 0) {
- return -1;
- }
-
- var loopMax = Math.min(numberSubstringsA, numberSubstringsB);
- for (var i = 0; i < loopMax; ++i) {
- var [matchStartA, matchEndA] = substringsA[i];
- var [matchStartB, matchEndB] = substringsB[i];
-
- if (matchStartA < matchStartB) {
- return -1;
- } else if (matchStartA > matchStartB) {
- return 1;
- }
-
- if (matchEndA > matchEndB) {
- return -1;
- } else if (matchEndA < matchEndB) {
- return 1;
- }
- }
-
- if (numberSubstringsA > numberSubstringsB) {
- return -1;
- } else if (numberSubstringsA < numberSubstringsB) {
- return 1;
- }
- return 0;
- },
-
- /**
- * Returns a duration in ms from a distance in pixels using a default speed of
- * 1000 pixels per second.
- * @param {number} distance Number of pixels that will be traveled.
- * @private
- */
- computeAnimationDuration_: function(distance) {
- // The duration of the animation can be found by abs(distance)/speed, where
- // speed is fixed at 1000 pixels per second, or 1 pixel per millisecond.
- return Math.abs(distance);
- },
-
- /**
- * If there is a forced cast mode, returns that cast mode. If |allSinks|
- * supports only a single cast mode, returns that cast mode. Otherwise,
- * returns AUTO_MODE. Only called if |userHasSelectedCastMode_| is |false|.
- *
- * @return {!media_router.CastMode} The single cast mode supported by
- * |allSinks|, or AUTO_MODE.
- */
- computeCastMode_: function() {
- /** @const */ var forcedMode = this.findForcedCastMode_();
- if (forcedMode) {
- return forcedMode;
- }
-
- var allCastModes = this.allSinks.reduce(function(castModesSoFar, sink) {
- // Ignore pseudo sinks in the cast mode computation.
- return castModesSoFar | (sink.isPseudoSink ? 0 : sink.castModes);
- }, 0);
-
- // This checks whether |castModes| does not consist of exactly 1 cast mode.
- if (!allCastModes || allCastModes & (allCastModes - 1)) {
- return media_router.AUTO_CAST_MODE;
- }
-
- var castMode = this.findCastModeByType_(allCastModes);
- if (castMode) {
- return castMode;
- }
-
- console.error('Cast mode ' + allCastModes + ' not in castModeList');
- return media_router.AUTO_CAST_MODE;
- },
-
- /**
- * @param {?media_router.MediaRouterView} view The current view.
- * @return {boolean} Whether or not to hide the cast mode list.
- * @private
- */
- computeCastModeListHidden_: function(view) {
- return view != media_router.MediaRouterView.CAST_MODE_LIST;
- },
-
- /**
- * @param {!media_router.CastMode} castMode The cast mode to determine an
- * icon for.
- * @return {string} The icon to use.
- * @private
- */
- computeCastModeIcon_: function(castMode) {
- switch (castMode.type) {
- case media_router.CastModeType.PRESENTATION:
- return 'media-router:web';
- case media_router.CastModeType.TAB_MIRROR:
- return 'media-router:tab';
- case media_router.CastModeType.DESKTOP_MIRROR:
- return 'media-router:laptop';
- case media_router.CastModeType.LOCAL_FILE:
- return 'media-router:folder';
- default:
- return '';
- }
- },
-
- /**
- * @param {!Array<!media_router.CastMode>} castModeList The current list of
- * cast modes.
- * @return {!Array<!media_router.CastMode>} The list of PRESENTATION cast
- * modes.
- * @private
- */
- computePresentationCastModeList_: function(castModeList) {
- return castModeList.filter(function(mode) {
- return mode.type == media_router.CastModeType.PRESENTATION;
- });
- },
-
- /**
- * @param {!Array<!media_router.Sink>} sinksToShow The list of sinks.
- * @return {boolean} Whether or not to hide the 'devices missing' message.
- * @private
- */
- computeDeviceMissingHidden_: function(sinksToShow) {
- return sinksToShow.length != 0;
- },
-
- /**
- * @param {?Element} element Element to compute padding for.
- * @return {number} Computes the amount of vertical padding (top + bottom) on
- * |element|.
- * @private
- */
- computeElementVerticalPadding_: function(element) {
- var paddingBottom, paddingTop;
- [paddingBottom, paddingTop] = this.getElementVerticalPadding_(element);
- return paddingBottom + paddingTop;
- },
-
- /**
- * @param {?media_router.MediaRouterView} view The current view.
- * @param {?media_router.Issue} issue The current issue.
- * @return {boolean} Whether or not to hide the header.
- * @private
- */
- computeHeaderHidden_: function(view, issue) {
- return view == media_router.MediaRouterView.ROUTE_DETAILS ||
- (view == media_router.MediaRouterView.SINK_LIST && !!issue &&
- issue.isBlocking);
- },
-
- /**
- * @param {?media_router.MediaRouterView} view The current view.
- * @param {string} headerText The header text for the sink list.
- * @return {string|undefined} The text for the header.
- * @private
- */
- computeHeaderText_: function(view, headerText) {
- switch (view) {
- case media_router.MediaRouterView.CAST_MODE_LIST:
- return this.i18n('selectCastModeHeaderText');
- case media_router.MediaRouterView.ISSUE:
- return this.i18n('issueHeaderText');
- case media_router.MediaRouterView.ROUTE_DETAILS:
- return this.currentRoute_ && this.sinkMap_[this.currentRoute_.sinkId] ?
- this.sinkMap_[this.currentRoute_.sinkId].name :
- '';
- case media_router.MediaRouterView.SINK_LIST:
- case media_router.MediaRouterView.FILTER:
- return this.headerText;
- default:
- return '';
- }
- },
-
- /**
- * @param {?media_router.MediaRouterView} view The current view.
- * @param {string} headerTooltip The tooltip for the header for the sink
- * list.
- * @return {string} The tooltip for the header.
- * @private
- */
- computeHeaderTooltip_: function(view, headerTooltip) {
- return view == media_router.MediaRouterView.SINK_LIST ? headerTooltip : '';
- },
-
- /**
- * @param {string} currentLaunchingSinkId ID of the sink that is currently
- * launching, or empty string if none exists.
- * @private
- */
- computeIsLaunching_: function(currentLaunchingSinkId) {
- return currentLaunchingSinkId != '';
- },
-
- /**
- * @param {?media_router.Issue} issue The current issue.
- * @return {string} The class for the issue banner.
- * @private
- */
- computeIssueBannerClass_: function(issue) {
- return issue && !issue.isBlocking ? 'non-blocking' : '';
- },
-
- /**
- * @param {?media_router.MediaRouterView} view The current view.
- * @param {?media_router.Issue} issue The current issue.
- * @return {boolean} Whether or not to show the issue banner.
- * @private
- */
- computeIssueBannerShown_: function(view, issue) {
- return !!issue &&
- (view == media_router.MediaRouterView.CAST_MODE_LIST ||
- view == media_router.MediaRouterView.SINK_LIST ||
- view == media_router.MediaRouterView.FILTER ||
- view == media_router.MediaRouterView.ISSUE);
- },
-
- /**
- * @param {!Array<!{sinkItem: !media_router.Sink,
- * substrings: Array<!Array<number>>}>} searchResultsToShow
- * The sinks currently matching the search text.
- * @param {boolean} isSearchListHidden Whether the search list is hidden.
- * @return {boolean} Whether or not the 'no matches' message is hidden.
- * @private
- */
- computeNoMatchesHidden_: function(searchResultsToShow, isSearchListHidden) {
- return isSearchListHidden || this.searchInputText_.length == 0 ||
- searchResultsToShow.length != 0;
- },
-
- /**
- * @param {!Array<!media_router.CastMode>} castModeList The current list of
- * cast modes.
- * @return {!Array<!media_router.CastMode>} The list of non-PRESENTATION cast
- * modes. Also excludes LOCAL_FILE.
- * @private
- */
- computeShareScreenCastModeList_: function(castModeList) {
- return castModeList.filter(function(mode) {
- return mode.type == media_router.CastModeType.DESKTOP_MIRROR ||
- mode.type == media_router.CastModeType.TAB_MIRROR;
- });
- },
-
- /**
- * @param {!Array<!media_router.CastMode>} castModeList The current list of
- * cast modes.
- * @return {!Array<!media_router.CastMode>} The list of local media cast
- * modes.
- * @private
- */
- computeLocalMediaCastModeList_: function(castModeList) {
- return castModeList.filter(function(mode) {
- return mode.type == media_router.CastModeType.LOCAL_FILE;
- });
- },
-
- /**
- * @param {?media_router.MediaRouterView} view The current view.
- * @param {?media_router.Issue} issue The current issue.
- * @return {boolean} Whether or not to hide the route details.
- * @private
- */
- computeRouteDetailsHidden_: function(view, issue) {
- return view != media_router.MediaRouterView.ROUTE_DETAILS ||
- (!!issue && issue.isBlocking);
- },
-
- /**
- * Computes an array of substring indices that mark where substrings of
- * |searchString| occur in |sinkName|.
- *
- * @param {string} searchString Search string entered by user.
- * @param {string} sinkName Sink name being filtered.
- * @return {Array<!Array<number>>} Array of substring start-end (inclusive)
- * index pairs if every character in |searchString| was matched, in order,
- * in |sinkName|. Otherwise it returns null.
- * @private
- */
- computeSearchMatches_: function(searchString, sinkName) {
- var i = 0;
- var matchStart = -1;
- var matchEnd = -1;
- var matchPairs = [];
- for (var j = 0; i < searchString.length && j < sinkName.length; ++j) {
- if (searchString[i].toLocaleLowerCase() ==
- sinkName[j].toLocaleLowerCase()) {
- if (matchStart == -1) {
- matchStart = j;
- }
- ++i;
- } else if (matchStart != -1) {
- matchEnd = j - 1;
- matchPairs.push([matchStart, matchEnd]);
- matchStart = -1;
- }
- }
- if (matchStart != -1) {
- matchEnd = j - 1;
- matchPairs.push([matchStart, matchEnd]);
- }
- return (i == searchString.length) ? matchPairs : null;
- },
-
- /**
- * Computes whether the search results list should be hidden.
- * @param {!Array<!{sinkItem: !media_router.Sink,
- * substrings: Array<!Array<number>>}>} searchResultsToShow
- * The sinks currently matching the search text.
- * @param {boolean} isSearchListHidden Whether the search list is hidden.
- * @return {boolean} Whether the search results list should be hidden.
- * @private
- */
- computeSearchResultsHidden_: function(
- searchResultsToShow, isSearchListHidden) {
- return isSearchListHidden || searchResultsToShow.length == 0;
- },
-
- /**
- * @param {!Array<!media_router.CastMode>} castModeList The current list of
- * cast modes.
- * @return {boolean} Whether or not to hide the share screen subheading text.
- * @private
- */
- computeShareScreenSubheadingHidden_: function(castModeList) {
- return this.computeShareScreenCastModeList_(castModeList).length == 0;
- },
-
- /**
- * @param {!Array<!media_router.CastMode>} castModeList The current list of
- * cast modes.
- * @return {boolean} Whether or not to hide the local media subheading text.
- * @private
- */
- computeLocalMediaSubheadingHidden_: function(castModeList) {
- return this.computeLocalMediaCastModeList_(castModeList).length == 0;
- },
-
- /**
- * @param {boolean} showFirstRunFlow Whether or not to show the first run
- * flow.
- * @param {?media_router.MediaRouterView} currentView The current view.
- * @private
- */
- computeShowFirstRunFlow_: function(showFirstRunFlow, currentView) {
- return showFirstRunFlow &&
- currentView == media_router.MediaRouterView.SINK_LIST;
- },
-
- /**
- * @param {!media_router.Sink} sink The sink to determine an icon for.
- * @return {string} The icon to use.
- * @private
- */
- computeSinkIcon_: function(sink) {
- switch (sink.iconType) {
- case media_router.SinkIconType.CAST:
- return 'media-router:chromecast';
- case media_router.SinkIconType.CAST_AUDIO_GROUP:
- return 'media-router:speaker-group';
- case media_router.SinkIconType.CAST_AUDIO:
- return 'media-router:speaker';
- case media_router.SinkIconType.MEETING:
- return 'media-router:meeting';
- case media_router.SinkIconType.HANGOUT:
- return 'media-router:hangout';
- case media_router.SinkIconType.EDUCATION:
- return 'media-router:education';
- case media_router.SinkIconType.WIRED_DISPLAY:
- return 'media-router:tv';
- case media_router.SinkIconType.GENERIC:
- return 'media-router:tv';
- default:
- return 'media-router:tv';
- }
- },
-
- /**
- * @param {!string} sinkId A sink ID.
- * @param {!Object<!string, ?media_router.Route>} sinkToRouteMap
- * Maps media_router.Sink.id to corresponding media_router.Route.
- * @return {string} The class for the sink icon.
- * @private
- */
- computeSinkIconClass_: function(sinkId, sinkToRouteMap) {
- return sinkToRouteMap[sinkId] ? 'sink-icon active-sink' : 'sink-icon';
- },
-
- /**
- * @param {!string} currentLaunchingSinkId The ID of the sink that is
- * currently launching.
- * @param {!string} sinkId A sink ID.
- * @return {boolean} |true| if given sink is currently launching.
- * @private
- */
- computeSinkIsLaunching_: function(currentLaunchingSinkId, sinkId) {
- return currentLaunchingSinkId == sinkId;
- },
-
- /**
- * @param {!Array<!media_router.Sink>} sinksToShow The list of sinks.
- * @return {boolean} Whether or not to hide the sink list.
- * @private
- */
- computeSinkListHidden_: function(sinksToShow) {
- return sinksToShow.length == 0;
- },
-
- /**
- * @param {?media_router.MediaRouterView} view The current view.
- * @param {?media_router.Issue} issue The current issue.
- * @return {boolean} Whether or not to hide entire the sink list view.
- * @private
- */
- computeSinkListViewHidden_: function(view, issue) {
- return (view != media_router.MediaRouterView.SINK_LIST &&
- view != media_router.MediaRouterView.FILTER) ||
- (!!issue && issue.isBlocking);
- },
-
- /**
- * Returns whether the sink domain for |sink| should be hidden.
- * @param {!media_router.Sink} sink
- * @return {boolean} |true| if the domain should be hidden.
- * @private
- */
- computeSinkDomainHidden_: function(sink) {
- return !this.showDomain || this.isEmptyOrWhitespace_(sink.domain);
- },
-
- /**
- * Computes which portions of a sink name, if any, should be highlighted when
- * displayed in the filter view. Any substrings matching the search text
- * should be highlighted.
- *
- * The order the strings are combined is plainText[0] highlightedText[0]
- * plainText[1] highlightedText[1] etc.
- *
- * @param {!{sinkItem: !media_router.Sink,
- * substrings: !Array<!Array<number>>}} matchedItem
- * Parameters in matchedItem:
- * sinkItem - Original !media_router.Sink from the sink list.
- * substrings - List of index pairs denoting substrings of sinkItem.name
- * that match |searchInputText_|.
- * @return {!{highlightedText: !Array<string>, plainText: !Array<string>}}
- * highlightedText - Array of strings that should be displayed highlighted.
- * plainText - Array of strings that should be displayed normally.
- * @private
- */
- computeSinkMatchingText_: function(matchedItem) {
- if (!matchedItem.substrings) {
- return {highlightedText: [null], plainText: [matchedItem.sinkItem.name]};
- }
- var lastMatchIndex = -1;
- var nameIndex = 0;
- var sinkName = matchedItem.sinkItem.name;
- var highlightedText = [];
- var plainText = [];
- for (var i = 0; i < matchedItem.substrings.length; ++i) {
- var [matchStart, matchEnd] = matchedItem.substrings[i];
- if (lastMatchIndex + 1 < matchStart) {
- plainText.push(sinkName.substring(lastMatchIndex + 1, matchStart));
- } else {
- plainText.push(null);
- }
- highlightedText.push(sinkName.substring(matchStart, matchEnd + 1));
- lastMatchIndex = matchEnd;
- }
- if (lastMatchIndex + 1 < sinkName.length) {
- highlightedText.push(null);
- plainText.push(sinkName.substring(lastMatchIndex + 1));
- }
- return {highlightedText: highlightedText, plainText: plainText};
- },
-
- /**
- * Returns the subtext to be shown for |sink|. Only called if
- * |computeSinkSubtextHidden_| returns false for the same |sink| and
- * |sinkToRouteMap|.
- * @param {!media_router.Sink} sink
- * @param {!Object<!string, ?media_router.Route>} sinkToRouteMap
- * @return {?string} The subtext to be shown.
- * @private
- */
- computeSinkSubtext_: function(sink, sinkToRouteMap) {
- var route = sinkToRouteMap[sink.id];
- if (route && !this.isEmptyOrWhitespace_(route.description)) {
- return route.description;
- }
-
- return sink.description;
- },
-
- /**
- * Returns whether the sink subtext for |sink| should be hidden.
- * @param {!media_router.Sink} sink
- * @param {!Object<!string, ?media_router.Route>} sinkToRouteMap
- * @return {boolean} |true| if the subtext should be hidden.
- * @private
- */
- computeSinkSubtextHidden_: function(sink, sinkToRouteMap) {
- if (!this.isEmptyOrWhitespace_(sink.description)) {
- return false;
- }
-
- var route = sinkToRouteMap[sink.id];
- return !route || this.isEmptyOrWhitespace_(route.description);
- },
-
- /**
- * @param {boolean} justOpened Whether the MR UI was just opened.
- * @return {boolean} Whether or not to hide the spinner.
- * @private
- */
- computeSpinnerHidden_: function(justOpened) {
- return !justOpened;
- },
-
- /**
- * Computes the height of the sink list view element when search results are
- * being shown.
- *
- * @param {?Element} deviceMissing No devices message element.
- * @param {?Element} noMatches No search matches element.
- * @param {?Element} results Search results list element.
- * @param {number} searchOffsetHeight Search input container element height.
- * @param {number} maxHeight Max height of the list elements.
- * @return {number} The height of the sink list view when search results are
- * being shown.
- * @private
- */
- computeTotalSearchHeight_: function(
- deviceMissing, noMatches, results, searchOffsetHeight, maxHeight) {
- var contentHeight = deviceMissing.offsetHeight +
- ((noMatches.hasAttribute('hidden')) ? results.offsetHeight :
- noMatches.offsetHeight);
- return Math.min(contentHeight, maxHeight) + searchOffsetHeight;
- },
-
- /**
- * Updates element positioning when the view changes and possibly triggers
- * reporting of a user filter action. If there is no filter text, it defers
- * the reporting until some text is entered, but otherwise it reports the
- * filter action here.
- * @param {?media_router.MediaRouterView} currentView The current view of the
- * dialog.
- * @param {?media_router.MediaRouterView} previousView The previous
- * |currentView|.
- * @private
- */
- currentViewChanged_: function(currentView, previousView) {
- if (currentView == media_router.MediaRouterView.FILTER) {
- this.reportFilterOnInput_ = true;
- this.maybeReportFilter_();
- }
- this.updateElementPositioning_();
-
- if (previousView == media_router.MediaRouterView.ROUTE_DETAILS) {
- media_router.browserApi.onMediaControllerClosed();
- if (this.$$('route-details')) {
- this.$$('route-details').onClosed();
- }
- }
- },
-
- /**
- * Filters all sinks based on fuzzy matching to the currently entered search
- * text.
- * @param {string} searchInputText The currently entered search text.
- * @private
- */
- filterSinks_: function(searchInputText) {
- if (searchInputText.length == 0) {
- this.searchResultsToShow_ = this.sinksToShow_.map(function(item) {
- return {sinkItem: item, substrings: null};
- });
- return;
- }
-
- var searchResultsToShow = [];
- for (var i = 0; i < this.sinksToShow_.length; ++i) {
- var matchSubstrings = this.computeSearchMatches_(
- searchInputText, this.sinksToShow_[i].name);
- if (!matchSubstrings) {
- continue;
- }
- searchResultsToShow.push(
- {sinkItem: this.sinksToShow_[i], substrings: matchSubstrings});
- }
- searchResultsToShow.sort(this.compareSearchMatches_);
-
- var pendingPseudoSink = (this.pseudoSinkSearchState_) ?
- this.pseudoSinkSearchState_.getPseudoSink() :
- null;
- // We may need to add pseudo sinks to the filter results. A pseudo sink will
- // be shown if there is no real sink with the same icon and name exactly
- // matching the filter text. The map() call transforms any pseudo sink
- // objects that will be shown to the search result format, where we know
- // that the entire sink name will be a match.
- //
- // The exception to this is when there is a pending pseudo sink search. Then
- // the pseudo sink for the search will be treated like a real sink because
- // it will actually be in |sinksToShow_| until a real sink is returned by
- // search. So the filter here shouldn't treat it like a pseudo sink.
- searchResultsToShow =
- this.pseudoSinks_
- .filter(function(pseudoSink) {
- return (!pendingPseudoSink ||
- pseudoSink.id != pendingPseudoSink.id) &&
- !searchResultsToShow.find(function(searchResult) {
- return searchResult.sinkItem.name == searchInputText &&
- searchResult.sinkItem.iconType == pseudoSink.iconType;
- });
- })
- .map(function(pseudoSink) {
- pseudoSink.name = searchInputText;
- return {
- sinkItem: pseudoSink,
- substrings: [[0, searchInputText.length - 1]]
- };
- })
- .concat(searchResultsToShow);
- this.searchResultsToShow_ = searchResultsToShow;
- },
-
- /**
- * Helper function to locate the CastMode object with the given type in
- * castModeList.
- *
- * @param {number} castModeType Type of cast mode to look for.
- * @return {media_router.CastMode|undefined} CastMode object with the given
- * type in castModeList, or undefined if not found.
- * @private
- */
- findCastModeByType_: function(castModeType) {
- return this.castModeList.find(function(element, index, array) {
- return element.type == castModeType;
- });
- },
-
- /**
- * Helper function to locate the position in the |castModeList| of the
- * CastMode object with the given type.
- *
- * @param {number} castModeType Type of cast mode to look for.
- * @return {number} index of the given type, or -1 if not found.
- * @private
- */
- findCastModeIndexByType_: function(castModeType) {
- return this.castModeList
- .map(function(element) {
- return element.type;
- })
- .indexOf(castModeType);
- },
-
-
- /**
- * Helper function to return a forced CastMode, if any.
- *
- * @return {media_router.CastMode|undefined} CastMode object with
- * isForced = true, or undefined if not found.
- * @private
- */
- findForcedCastMode_: function() {
- return this.castModeList &&
- this.castModeList.find(element => element.isForced);
- },
-
- /**
- * @param {?Element} element Element to compute padding for.
- * @return {!Array<number>} Array containing the element's bottom padding
- * value and the element's top padding value, in that order.
- * @private
- */
- getElementVerticalPadding_: function(element) {
- var style = window.getComputedStyle(element);
- return [
- parseInt(style.getPropertyValue('padding-bottom'), 10) || 0,
- parseInt(style.getPropertyValue('padding-top'), 10) || 0
- ];
- },
-
- /**
- * Retrieves the first run flow cloud preferences text, if it exists. On
- * non-officially branded builds, the string is not defined.
- *
- * @return {string} Cloud preferences text.
- */
- getFirstRunFlowCloudPrefText_: function() {
- return loadTimeData.valueExists('firstRunFlowCloudPrefText') ?
- this.i18n('firstRunFlowCloudPrefText') :
- '';
- },
-
- /**
- * @param {?media_router.Route} route Route to get the sink for.
- * @return {?media_router.Sink} Sink associated with |route| or
- * undefined if we don't have data for the sink.
- */
- getSinkForRoute_: function(route) {
- return route ? this.sinkMap_[route.sinkId] : null;
- },
-
- /**
- * @param {?Element} element Conditionally-templated element to check.
- * @return {boolean} Whether |element| is considered present in the document
- * as a conditionally-templated element. This does not check the |hidden|
- * attribute.
- */
- hasConditionalElement_: function(element) {
- return !!element &&
- (!element.style.display || element.style.display != 'none');
- },
-
- /**
- * Returns whether given string is undefined, null, empty, or whitespace only.
- * @param {?string} str String to be tested.
- * @return {boolean} |true| if the string is undefined, null, empty, or
- * whitespace.
- * @private
- */
- isEmptyOrWhitespace_: function(str) {
- return str === undefined || str === null || (/^\s*$/).test(str);
- },
-
- /**
- * Reports a user filter action if |searchInputText_| is not empty and the
- * filter action hasn't been reported since the view changed to the filter
- * view.
- * @private
- */
- maybeReportFilter_: function() {
- if (this.reportFilterOnInput_ && this.searchInputText_.length != 0) {
- this.reportFilterOnInput_ = false;
- this.fire('report-filter');
- }
- },
-
- /**
- * Updates |currentView_| if the dialog had just opened and there's
- * only one local route.
- */
- maybeShowRouteDetailsOnOpen: function() {
- var localRoute = null;
- for (var i = 0; i < this.routeList.length; i++) {
- var route = this.routeList[i];
- if (!route.isLocal) {
- continue;
- }
- if (!localRoute) {
- localRoute = route;
- } else {
- // Don't show route details if there are more than one local route.
- localRoute = null;
- break;
- }
- }
-
- if (localRoute) {
- this.showRouteDetails_(localRoute);
- }
- this.fire('show-initial-state', {currentView: this.currentView_});
- },
-
- /**
- * Updates |currentView_| if there is a new blocking issue or a blocking
- * issue is resolved. Clears any pending route creation properties if the
- * issue corresponds with |pendingCreatedRouteId_|.
- *
- * @param {?media_router.Issue} issue The new issue, or null if the
- * blocking issue was resolved.
- * @private
- */
- maybeShowIssueView_: function(issue) {
- if (issue) {
- if (issue.isBlocking) {
- this.currentView_ = media_router.MediaRouterView.ISSUE;
- } else if (this.currentView_ == media_router.MediaRouterView.SINK_LIST) {
- // Make space for the non-blocking issue in the sink list.
- this.updateElementPositioning_();
- }
- } else if (this.currentView_ == media_router.MediaRouterView.ISSUE) {
- // Switch back to the sink list if the issue was cleared and it was
- // showing an issue. It is expected that the only way to clear an issue is
- // by user action; the IssueManager (C++ side) does not clear issues in
- // the UI.
- this.showSinkList_();
- }
-
- if (this.pendingCreatedRouteId_ && issue &&
- issue.routeId == this.pendingCreatedRouteId_) {
- this.resetRouteCreationProperties_(false);
- }
- },
-
- /**
- * If an element in the search results list has keyboard focus when we are
- * transitioning from the filter view to the sink list view, give focus to the
- * same sink in the sink list. Otherwise we leave the keyboard focus where it
- * is.
- * @private
- */
- maybeUpdateFocusOnFilterViewExit_: function() {
- var searchSinks =
- this.$$('#search-results').querySelectorAll('.selectable-item');
- var focusedElem = Array.prototype.find.call(searchSinks, function(sink) {
- return sink.matches(':focus');
- });
- if (!focusedElem) {
- return;
- }
- var focusedSink =
- this.$$('#searchResults').itemForElement(focusedElem).sinkItem;
- setTimeout(function() {
- var sinkListPaperMenu = this.$$('#sink-list-paper-menu');
- var sinks = sinkListPaperMenu.children;
- var sinkList = this.$$('#sinkList');
- for (var i = 0; i < sinks.length; i++) {
- if (sinkList.itemForElement(sinks[i]).id == focusedSink.id) {
- sinkListPaperMenu.selectIndex(i);
- break;
- }
- }
- }.bind(this));
- },
-
- /**
- * May update |populatedSinkListSeenTimeMs_| depending on |currentView| and
- * |sinksToShow|.
- * Called when |currentView_| or |sinksToShow_| is updated.
- *
- * @param {?media_router.MediaRouterView} currentView The current view of the
- * dialog.
- * @param {!Array<!media_router.Sink>} sinksToShow The sinks to display.
- * @private
- */
- maybeUpdateStartSinkDisplayStartTime_: function(currentView, sinksToShow) {
- if (currentView == media_router.MediaRouterView.SINK_LIST &&
- sinksToShow.length != 0) {
- // Only set |populatedSinkListSeenTimeMs_| if it has not already been set.
- if (this.populatedSinkListSeenTimeMs_ == -1) {
- this.populatedSinkListSeenTimeMs_ = window.performance.now();
- }
- } else {
- // Reset |populatedSinkListLastSeen_| if the sink list isn't being shown
- // or if there aren't any sinks available for display.
- this.populatedSinkListSeenTimeMs_ = -1;
- }
- },
-
- /**
- * Animates the transition from the filter view, where the search field is at
- * the top of the list, to the sink list view, where the search field is at
- * the bottom of the list.
- *
- * If this is called while another animation is in progress, it queues itself
- * to be run at the end of the current animation.
- *
- * @param {!function()} resolve Resolves the animation promise that is waiting
- * on this animation.
- * @private
- */
- moveSearchToBottom_: function(resolve) {
- var deviceMissing = this.$['device-missing'];
- var list = this.$$('#sink-list');
- var resultsContainer = this.$$('#search-results-container');
- var search = this.$$('#sink-search');
- var view = this.$['sink-list-view'];
-
- var hasList = this.hasConditionalElement_(list);
- var initialHeight = view.offsetHeight;
- // Force the view height to be max dialog height.
- view.style['overflow'] = 'hidden';
-
- var searchInitialOffsetHeight = search.offsetHeight;
- var searchInitialPaddingBottom, searchInitialPaddingTop;
- [searchInitialPaddingBottom, searchInitialPaddingTop] =
- this.getElementVerticalPadding_(search);
- var searchPadding = searchInitialPaddingBottom + searchInitialPaddingTop;
- var searchHeight = search.offsetHeight - searchPadding;
- var searchFinalPaddingBottom, searchFinalPaddingTop;
- [searchFinalPaddingBottom, searchFinalPaddingTop] =
- this.getElementVerticalPadding_(search);
- var searchFinalOffsetHeight =
- searchHeight + searchFinalPaddingBottom + searchFinalPaddingTop;
-
- var resultsInitialTop = 0;
- var finalHeight = 0;
- // Get final view height ahead of animation.
- if (hasList) {
- list.style['position'] = 'absolute';
- list.style['opacity'] = '0';
- this.hideSinkListForAnimation_ = false;
- finalHeight += list.offsetHeight;
- list.style['position'] = 'relative';
- } else {
- resultsInitialTop +=
- deviceMissing.offsetHeight + searchInitialOffsetHeight;
- finalHeight += deviceMissing.offsetHeight;
- }
-
- var searchInitialTop = hasList ? 0 : deviceMissing.offsetHeight;
- var searchFinalTop = hasList ? list.offsetHeight - search.offsetHeight :
- deviceMissing.offsetHeight;
- resultsContainer.style['position'] = 'absolute';
-
- var duration =
- this.computeAnimationDuration_(searchFinalTop - searchInitialTop);
- var timing = {duration: duration, easing: 'ease-in-out', fill: 'forwards'};
-
- // This GroupEffect does the reverse of |moveSearchToTop_|. It fades the
- // sink list in while sliding the search input and search results list down.
- // The dialog height is also adjusted smoothly to the sink list height.
- var deviceMissingEffect = new KeyframeEffect(
- deviceMissing,
- [
- {'marginBottom': searchInitialOffsetHeight},
- {'marginBottom': searchFinalOffsetHeight}
- ],
- timing);
- var listEffect =
- new KeyframeEffect(list, [{'opacity': '0'}, {'opacity': '1'}], timing);
- var resultsEffect = new KeyframeEffect(
- resultsContainer,
- [
- {
- 'top': resultsInitialTop + 'px',
- 'paddingTop': resultsContainer.style['padding-top']
- },
- {'top': '100%', 'paddingTop': '0px'}
- ],
- timing);
- var searchEffect = new KeyframeEffect(
- search,
- [
- {
- 'top': searchInitialTop + 'px',
- 'marginTop': '0px',
- 'paddingBottom': searchInitialPaddingBottom + 'px',
- 'paddingTop': searchInitialPaddingTop + 'px'
- },
- {
- 'top': '100%',
- 'marginTop': '-' + searchFinalOffsetHeight + 'px',
- 'paddingBottom': searchFinalPaddingBottom + 'px',
- 'paddingTop': searchFinalPaddingTop + 'px'
- }
- ],
- timing);
- var viewEffect = new KeyframeEffect(
- view,
- [
- {'height': initialHeight + 'px', 'paddingBottom': '0px'}, {
- 'height': finalHeight + 'px',
- 'paddingBottom': searchFinalOffsetHeight + 'px'
- }
- ],
- timing);
- var player = document.timeline.play(new GroupEffect(
- hasList ?
- [listEffect, resultsEffect, searchEffect, viewEffect] :
- [deviceMissingEffect, resultsEffect, searchEffect, viewEffect]));
-
- var that = this;
- var finalizeAnimation = function() {
- view.style['overflow'] = '';
- that.putSearchAtBottom_();
- that.filterTransitionPlayer_.cancel();
- that.filterTransitionPlayer_ = null;
- that.isSearchListHidden_ = true;
- resolve();
- };
-
- player.finished.then(finalizeAnimation);
- this.filterTransitionPlayer_ = player;
- },
-
- /**
- * Animates the transition from the sink list view, where the search field is
- * at the bottom of the list, to the filter view, where the search field is at
- * the top of the list.
- *
- * If this is called while another animation is in progress, it queues itself
- * to be run at the end of the current animation.
- *
- * @param {!function()} resolve Resolves the animation promise that is waiting
- * on this animation.
- * @private
- */
- moveSearchToTop_: function(resolve) {
- var deviceMissing = this.$['device-missing'];
- var list = this.$$('#sink-list');
- var noMatches = this.$$('#no-search-matches');
- var results = this.$$('#search-results');
- var resultsContainer = this.$$('#search-results-container');
- var search = this.$$('#sink-search');
- var view = this.$['sink-list-view'];
-
- // Set the max height for the results list before it's shown.
- results.style.maxHeight = this.sinkListMaxHeight_ + 'px';
-
- // Saves current search container |offsetHeight| which includes bottom
- // padding.
- var searchInitialOffsetHeight = search.offsetHeight;
- var hasList = this.hasConditionalElement_(list);
- var searchInitialTop = hasList ?
- list.offsetHeight - searchInitialOffsetHeight :
- deviceMissing.offsetHeight;
- var searchFinalTop = hasList ? 0 : deviceMissing.offsetHeight;
- var searchInitialPaddingBottom, searchInitialPaddingTop;
- [searchInitialPaddingBottom, searchInitialPaddingTop] =
- this.getElementVerticalPadding_(search);
- var searchPadding = searchInitialPaddingBottom + searchInitialPaddingTop;
- var searchHeight = search.offsetHeight - searchPadding;
- var searchFinalPaddingBottom, searchFinalPaddingTop;
- [searchFinalPaddingBottom, searchFinalPaddingTop] =
- this.getElementVerticalPadding_(search);
- var searchFinalOffsetHeight =
- searchHeight + searchFinalPaddingBottom + searchFinalPaddingTop;
-
- // Omitting |search.offsetHeight| because it is handled by view animation
- // separately.
- var initialHeight =
- hasList ? list.offsetHeight : deviceMissing.offsetHeight;
- view.style['overflow'] = 'hidden';
-
- var resultsPadding = this.computeElementVerticalPadding_(results);
- var finalHeight = this.computeTotalSearchHeight_(
- deviceMissing, noMatches, results, searchFinalOffsetHeight,
- this.sinkListMaxHeight_ + resultsPadding);
-
- var duration =
- this.computeAnimationDuration_(searchFinalTop - searchInitialTop);
- var timing = {duration: duration, easing: 'ease-in-out', fill: 'forwards'};
-
- // This GroupEffect will cause the sink list to fade out while the search
- // input and search results list slide up. The dialog will also resize
- // smoothly to the new search result list height.
- var deviceMissingEffect = new KeyframeEffect(
- deviceMissing,
- [
- {'marginBottom': searchInitialOffsetHeight},
- {'marginBottom': searchFinalOffsetHeight}
- ],
- timing);
- var listEffect =
- new KeyframeEffect(list, [{'opacity': '1'}, {'opacity': '0'}], timing);
- var resultsEffect = new KeyframeEffect(
- resultsContainer,
- [
- {'top': '100%', 'paddingTop': '0px'}, {
- 'top': searchFinalTop + 'px',
- 'paddingTop': searchFinalOffsetHeight + 'px'
- }
- ],
- timing);
- var searchEffect = new KeyframeEffect(
- search,
- [
- {
- 'top': '100%',
- 'marginTop': '-' + searchInitialOffsetHeight + 'px',
- 'paddingBottom': searchInitialPaddingBottom + 'px',
- 'paddingTop': searchInitialPaddingTop + 'px'
- },
- {
- 'top': searchFinalTop + 'px',
- 'marginTop': '0px',
- 'paddingBottom': searchFinalPaddingBottom + 'px',
- 'paddingTop': searchFinalPaddingTop + 'px'
- }
- ],
- timing);
- var viewEffect = new KeyframeEffect(
- view,
- [
- {
- 'height': initialHeight + 'px',
- 'paddingBottom': searchInitialOffsetHeight + 'px'
- },
- {'height': finalHeight + 'px', 'paddingBottom': '0px'}
- ],
- timing);
- var player = document.timeline.play(new GroupEffect(
- hasList ?
- [listEffect, resultsEffect, searchEffect, viewEffect] :
- [deviceMissingEffect, resultsEffect, searchEffect, viewEffect]));
-
- var that = this;
- var finalizeAnimation = function() {
- // When we are moving the search results up into view, the user may type
- // more text or delete text which may change the height of the search
- // results list. In this case, the dialog height that the animation ends
- // on will now be wrong. In order to correct this smoothly,
- // |putSearchAtTop_| will queue another animation just to adjust the
- // dialog height.
- //
- // The |filterTransitionPlayer_| will hold all of the animated elements in
- // their final keyframe state until it is canceled or another player
- // overrides it because we used |fill: 'forwards'| in all of the effects.
- // So unlike |moveSearchToBottom_|, we don't know for sure whether we want
- // to cancel |filterTransitionPlayer_| after |putSearchAtTop_| because
- // another animation may have been run to correct the dialog height.
- //
- // If |putSearchAtTop_| has to adjust the dialog height, it also queues
- // itself to run again when that animation is finished. When the height is
- // finally correct at the end of an animation, it will cancel
- // |filterTransitionPlayer_| itself.
- that.putSearchAtTop_(resolve);
- };
-
- player.finished.then(finalizeAnimation);
- this.filterTransitionPlayer_ = player;
- },
-
- /**
- * Handles a cast mode selection. Updates |headerText|, |headerTextTooltip|,
- * and |shownCastModeValue_|.
- *
- * @param {!Event} event The event object.
- * @private
- */
- onCastModeClick_: function(event) {
- // The clicked cast mode can come from one of three lists,
- // presentationCastModeList, shareScreenCastModeList, and
- // localMediaCastModeList.
- var clickedMode =
- this.$$('#presentationCastModeList').itemForElement(event.target) ||
- this.$$('#shareScreenCastModeList').itemForElement(event.target) ||
- this.$$('#localMediaCastModeList').itemForElement(event.target);
-
- if (!clickedMode) {
- return;
- }
-
- // If the user selects LOCAL_FILE, some additional steps are required
- // (selecting the file), before the cast mode has been officially
- // selected.
- if (clickedMode.type == media_router.CastModeType.LOCAL_FILE) {
- this.selectLocalMediaFile_();
- } else {
- this.castModeSelected_(clickedMode);
- }
- },
-
- /**
- * Handles a change-route-source-click event. Sets the currently launching
- * sink to be the current route's sink and shows the sink list.
- *
- * @param {!Event} event The event object.
- * Parameters in |event|.detail:
- * route - route to modify.
- * selectedCastMode - cast mode to use for the new source.
- * @private
- */
- onChangeRouteSourceClick_: function(event) {
- /** @type {{route: !media_router.Route, selectedCastMode: number}} */
- var detail = event.detail;
- this.currentLaunchingSinkId_ = detail.route.sinkId;
- var sink = this.sinkMap_[detail.route.sinkId];
- this.showSinkList_();
- this.maybeReportUserFirstAction(
- media_router.MediaRouterUserAction.REPLACE_LOCAL_ROUTE);
- },
-
- /**
- * Handles a close-route event. Shows the sink list and starts a timer to
- * close the dialog if there is no click within three seconds.
- *
- * @param {!Event} event The event object.
- * Parameters in |event|.detail:
- * route - route to close.
- * @private
- */
- onCloseRoute_: function(event) {
- /** @type {{route: media_router.Route}} */
- var detail = event.detail;
- this.showSinkList_();
- this.startTapTimer_();
-
- if (detail.route.isLocal) {
- this.maybeReportUserFirstAction(
- media_router.MediaRouterUserAction.STOP_LOCAL);
- }
- },
-
- /**
- * Handles response of previous create route attempt.
- *
- * @param {string} sinkId The ID of the sink to which the Media Route was
- * creating a route.
- * @param {?media_router.Route} route The newly created route that
- * corresponds to the sink if route creation succeeded; null otherwise.
- * @param {boolean} isForDisplay Whether or not |route| is for display.
- */
- onCreateRouteResponseReceived: function(sinkId, route, isForDisplay) {
- // The provider will handle sending an issue for a failed route request.
- if (!route) {
- this.resetRouteCreationProperties_(false);
- this.fire('report-resolved-route', {
- outcome: media_router.MediaRouterRouteCreationOutcome.FAILURE_NO_ROUTE
- });
- return;
- }
-
- // Check that |sinkId| exists and corresponds to |currentLaunchingSinkId_|.
- if (!this.sinkMap_[sinkId] || this.currentLaunchingSinkId_ != sinkId) {
- this.fire('report-resolved-route', {
- outcome:
- media_router.MediaRouterRouteCreationOutcome.FAILURE_INVALID_SINK
- });
- return;
- }
-
- // Regardless of whether the route is for display, it was resolved
- // successfully.
- this.fire(
- 'report-resolved-route',
- {outcome: media_router.MediaRouterRouteCreationOutcome.SUCCESS});
-
- if (isForDisplay) {
- this.showRouteDetails_(route);
- this.startTapTimer_();
- this.resetRouteCreationProperties_(true);
- } else {
- this.pendingCreatedRouteId_ = route.id;
- }
- },
-
- /**
- * Sets up the LOCAL_FILE cast mode for display after a specific file has been
- * selected.
- *
- * @param {string} fileName The name of the file that has been selected.
- */
- onFileDialogSuccess(fileName) {
- /** @const */ var mode =
- this.findCastModeByType_(media_router.CastModeType.LOCAL_FILE);
-
- if (!mode) {
- return;
- }
-
- this.castModeSelected_(mode);
- this.headerText =
- loadTimeData.getStringF('castLocalMediaSelectedFileTitle', fileName);
-
- this.updateSelectedCastModeMenuItem_();
- },
-
- /**
- * Called when a focus event is triggered.
- *
- * @param {!Event} event The event object.
- * @private
- */
- onFocus_: function(event) {
- // If the focus event was automatically fired by Polymer, remove focus from
- // the element. This prevents unexpected focusing when the dialog is
- // initially loaded. This only happens on mac.
- if (cr.isMac && !event.sourceCapabilities) {
- // Adding a focus placeholder element is part of the workaround for
- // handling unexpected focusing, which only happens once on dialog open.
- // Since the placeholder is focus-enabled as denoted by its tabindex
- // value, the focus will not appear in other elements.
- var placeholder = this.$$('#focus-placeholder');
- // Check that the placeholder is the currently focused element. In some
- // tests, other elements are non-user-triggered focused.
- if (placeholder && this.shadowRoot.activeElement == placeholder) {
- event.path[0].blur();
- // Remove the placeholder since we have no more use for it.
- placeholder.remove();
- }
- }
- },
-
- /**
- * Called when a keydown event is fired.
- * @param {!Event} e Keydown event object for the event.
- */
- onKeydown_: function(e) {
- // The ESC key may be pressed with a combination of other keys. It is
- // handled on the C++ side instead of the JS side on non-mac platforms,
- // which uses toolkit-views. Handle the expected behavior on all platforms
- // here.
- if (e.key == media_router.KEY_ESC && !e.shiftKey && !e.ctrlKey &&
- !e.altKey && !e.metaKey) {
- // When searching, allow ESC as a mechanism to leave the filter view.
- if (this.currentView_ == media_router.MediaRouterView.FILTER) {
- // If the user tabbed to an item in the search results, or otherwise has
- // an item in the list focused, focus will seem to vanish when we
- // transition back to the sink list. Instead we should move focus to the
- // appropriate item in the sink list.
- this.maybeUpdateFocusOnFilterViewExit_();
- this.showSinkList_();
- e.preventDefault();
- } else {
- this.fire('close-dialog', {
- pressEscToClose: true,
- });
- }
- }
- },
-
- /**
- * Called when a mouseleave event is triggered.
- *
- * @private
- */
- onMouseLeave_: function() {
- this.mouseIsPositionedOverDialog_ = false;
- },
-
- /**
- * Called when a mouseenter event is triggered.
- *
- * @private
- */
- onMouseEnter_: function() {
- this.mouseIsPositionedOverDialog_ = true;
- },
-
- /**
- * Called when a search has completed up to route creation. |sinkId|
- * identifies the sink that should be in |allSinks|, if a sink was found.
- *
- * @param {string} sinkId The ID of the sink that is the result of the
- * currently pending search.
- */
- onReceiveSearchResult: function(sinkId) {
- this.pseudoSinkSearchState_.receiveSinkResponse(sinkId);
- this.currentLaunchingSinkId_ =
- this.pseudoSinkSearchState_.checkForRealSink(this.allSinks);
- this.rebuildSinksToShow_();
- // If we're in filter view, make sure the |sinksToShow_| change is picked
- // up.
- if (this.currentView_ == media_router.MediaRouterView.FILTER) {
- this.filterSinks_(this.searchInputText_);
- }
- },
-
- /**
- * Called when the connection to the route controller is invalidated. Switches
- * from route details view to the sink list view.
- */
- onRouteControllerInvalidated: function() {
- if (this.currentView_ == media_router.MediaRouterView.ROUTE_DETAILS) {
- this.currentRoute_ = null;
- this.showSinkList_();
- }
- },
-
- /**
- * Called when a sink is clicked.
- *
- * @param {!Event} event The event object.
- * @private
- */
- onSinkClick_: function(event) {
- var clickedSink =
- (this.currentView_ == media_router.MediaRouterView.FILTER) ?
- this.$$('#searchResults').itemForElement(event.target).sinkItem :
- this.$$('#sinkList').itemForElement(event.target);
- this.showOrCreateRoute_(clickedSink);
- this.fire('sink-click', {index: event['model'].index});
- },
-
- /**
- * Sets the positioning of the sink list, search input, and search results so
- * that everything is in the correct state for the sink list view.
- *
- * @private
- */
- putSearchAtBottom_: function() {
- var search = this.$$('#sink-search');
- if (!this.hasConditionalElement_(search)) {
- return;
- }
- var deviceMissing = this.$['device-missing'];
- var list = this.$$('#sink-list');
- var resultsContainer = this.$$('#search-results-container');
- var view = this.$['sink-list-view'];
- search.style['top'] = '';
- if (resultsContainer) {
- resultsContainer.style['position'] = '';
- resultsContainer.style['padding-top'] = '';
- resultsContainer.style['top'] = '';
- }
- this.hideSinkListForAnimation_ = false;
- var hasList = this.hasConditionalElement_(list);
- if (hasList) {
- search.style['margin-top'] = '-' + search.offsetHeight + 'px';
- view.style['padding-bottom'] = search.offsetHeight + 'px';
- list.style['opacity'] = '';
- } else {
- var bottomMargin = 12;
- deviceMissing.style['margin-bottom'] =
- (search.offsetHeight + bottomMargin) + 'px';
- search.style['margin-top'] = '';
- view.style['padding-bottom'] = '';
- }
- },
-
- /**
- * Sets the positioning of the sink list, search input, and search results so
- * that everything is in the correct state for the filter view.
- *
- * If the user was searching while the |moveSearchToTop_| animation was
- * happening then the dialog height that animation ends at could be different
- * than the current height of the search results. If this is the case, this
- * function first spawns a new animation that smoothly corrects the height
- * problem. This is iterative, but once we enter a call where the heights
- * match up, the elements will become static again.
- *
- * @param {!function()} resolve Resolves the animation promise that is waiting
- * on this animation.
- * @private
- */
- putSearchAtTop_: function(resolve) {
- var deviceMissing = this.$['device-missing'];
- var list = this.$$('#sink-list');
- var noMatches = this.$$('#no-search-matches');
- var results = this.$$('#search-results');
- var resultsContainer = this.$$('#search-results-container');
- var search = this.$$('#sink-search');
- var view = this.$['sink-list-view'];
-
- // Set the max height for the results list before it's shown.
- results.style.maxHeight = this.sinkListMaxHeight_ + 'px';
-
- // If there is a height mismatch between where the animation calculated the
- // height should be and where it is now because the search results changed
- // during the animation, correct it with... another animation.
- var resultsPadding = this.computeElementVerticalPadding_(results);
- var finalHeight = this.computeTotalSearchHeight_(
- deviceMissing, noMatches, results, search.offsetHeight,
- this.sinkListMaxHeight_ + resultsPadding);
- if (finalHeight != view.offsetHeight) {
- var viewEffect = new KeyframeEffect(
- view,
- [
- {'height': view.offsetHeight + 'px'},
- {'height': finalHeight + 'px'}
- ],
- {
- duration:
- this.computeAnimationDuration_(finalHeight - view.offsetHeight),
- easing: 'ease-in-out',
- fill: 'forwards'
- });
- var player = document.timeline.play(viewEffect);
- if (this.heightAdjustmentPlayer_) {
- this.heightAdjustmentPlayer_.cancel();
- }
- this.heightAdjustmentPlayer_ = player;
- player.finished.then(this.putSearchAtTop_.bind(this, resolve));
- return;
- }
-
- var hasList = this.hasConditionalElement_(list);
- search.style['margin-top'] = '';
- deviceMissing.style['margin-bottom'] = search.offsetHeight + 'px';
- var searchFinalTop = hasList ? 0 : deviceMissing.offsetHeight;
- var resultsPaddingTop = hasList ? search.offsetHeight + 'px' : '0px';
- search.style['top'] = searchFinalTop + 'px';
- this.hideSinkListForAnimation_ = true;
- resultsContainer.style['position'] = 'relative';
- resultsContainer.style['padding-top'] = resultsPaddingTop;
- resultsContainer.style['top'] = '';
-
- view.style['overflow'] = '';
- view.style['padding-bottom'] = '';
- if (this.filterTransitionPlayer_) {
- this.filterTransitionPlayer_.cancel();
- this.filterTransitionPlayer_ = null;
- }
-
- if (this.heightAdjustmentPlayer_) {
- this.heightAdjustmentPlayer_.cancel();
- this.heightAdjustmentPlayer_ = null;
- }
-
- resolve();
- },
-
- /**
- * Queues a call to |moveSearchToBottom_| by adding it as a continuation to
- * |animationPromise_| and updating |animationPromise_|.
- */
- queueMoveSearchToBottom_: function() {
- var oldPromise = this.animationPromise_;
- var that = this;
- this.animationPromise_ = new Promise(function(resolve) {
- oldPromise.then(that.moveSearchToBottom_.bind(that, resolve));
- });
- },
-
- /**
- * Queues a call to |moveSearchToTop_| by adding it as a continuation to
- * |animationPromise_| and updating |animationPromise_|. The new promise will
- * not resolve until |putSearchAtTop_| is finished, including any potential
- * dialog height adjustment animations.
- */
- queueMoveSearchToTop_: function() {
- var oldPromise = this.animationPromise_;
- var that = this;
- this.animationPromise_ = new Promise(function(resolve) {
- oldPromise.then(function() {
- that.isSearchListHidden_ = false;
- setTimeout(that.moveSearchToTop_.bind(that, resolve));
- });
- });
- },
-
- /**
- * Queues a call to |putSearchAtTop_| by adding it as a continuation to
- * |animationPromise_| and updating |animationPromise_|.
- */
- queuePutSearchAtTop_: function() {
- var that = this;
- var oldPromise = this.animationPromise_;
- this.animationPromise_ = new Promise(function(resolve) {
- oldPromise.then(that.putSearchAtTop_.bind(that, resolve));
- });
- },
-
- /**
- * Called when |routeList| is updated. Rebuilds |routeMap_| and
- * |sinkToRouteMap_|.
- *
- * @private
- */
- rebuildRouteMaps_: function() {
- this.routeMap_ = {};
-
- // Rebuild |sinkToRouteMap_| with a temporary map to avoid firing the
- // computed functions prematurely.
- var tempSinkToRouteMap = {};
-
- // We expect that each route in |routeList| maps to a unique sink.
- this.routeList.forEach(function(route) {
- this.routeMap_[route.id] = route;
- tempSinkToRouteMap[route.sinkId] = route;
- }, this);
-
- // If there is route creation in progress, check if any of the route ids
- // correspond to |pendingCreatedRouteId_|. If so, the newly created route
- // is ready to be displayed; switch to route details view.
- if (this.currentLaunchingSinkId_ != '' &&
- this.pendingCreatedRouteId_ != '') {
- var route = tempSinkToRouteMap[this.currentLaunchingSinkId_];
- if (route && this.pendingCreatedRouteId_ == route.id) {
- this.showRouteDetails_(route);
- this.startTapTimer_();
- this.resetRouteCreationProperties_(true);
- }
- } else {
- // If |currentRoute_| is no longer active, clear |currentRoute_|. Also
- // switch back to the SINK_PICKER view if the user is currently in the
- // ROUTE_DETAILS view.
- if (this.currentRoute_) {
- this.currentRoute_ = this.routeMap_[this.currentRoute_.id] || null;
- }
- if (!this.currentRoute_ &&
- this.currentView_ == media_router.MediaRouterView.ROUTE_DETAILS) {
- this.showSinkList_();
- }
- }
-
- this.sinkToRouteMap_ = tempSinkToRouteMap;
- this.rebuildSinksToShow_();
- },
-
- /**
- * Rebuilds the list of sinks to be shown for the current cast mode.
- * A sink should be shown if it is compatible with the current cast mode, or
- * if the sink is associated with a route. The resulting list is sorted by
- * name.
- */
- rebuildSinksToShow_: function() {
- var updatedSinkList = this.allSinks.filter(function(sink) {
- return !sink.isPseudoSink;
- }, this);
-
- if (this.pseudoSinkSearchState_) {
- var pendingPseudoSink = this.pseudoSinkSearchState_.getPseudoSink();
- // Here we will treat the pseudo sink that launched the search as a real
- // sink until one is returned by search. This way it isn't possible to
- // ever reach a UI state where there is no spinner being shown in the sink
- // list but |currentLaunchingSinkId_| is non-empty (thereby preventing any
- // other sink from launching).
- if (pendingPseudoSink.id == this.currentLaunchingSinkId_) {
- updatedSinkList.unshift(pendingPseudoSink);
- }
- }
- // If user did not select a cast mode, then:
- // - If there is a forced cast mode, it is shown.
- // - If all sinks support only a single cast mode, then the cast mode is
- // switched to that mode.
- // - Otherwise, the cast mode becomes AUTO mode.
- if (!this.userHasSelectedCastMode_) {
- this.setShownCastMode_(this.computeCastMode_());
- }
-
- // Non-AUTO modes may show a subset of sinks based on compatibility with the
- // shown value.
- if (this.shownCastModeValue_ != media_router.CastModeType.AUTO) {
- updatedSinkList = updatedSinkList.filter(function(element) {
- return (element.castModes & this.shownCastModeValue_) ||
- this.sinkToRouteMap_[element.id];
- }, this);
- }
-
- // When there's an updated list of sinks, append any new sinks to the end
- // of the existing list. This prevents sinks randomly jumping around the
- // dialog, which can surprise users / lead to inadvertently casting to the
- // wrong sink.
- if (this.sinksToShow_) {
- for (var i = this.sinksToShow_.length - 1; i >= 0; i--) {
- var index = updatedSinkList.findIndex(function(updatedSink) {
- return this.sinksToShow_[i].id == updatedSink.id;
- }.bind(this));
- if (index < 0) {
- // Remove any sinks that are no longer discovered.
- this.sinksToShow_.splice(i, 1);
- } else {
- // If the sink exists, move it from |updatedSinkList| to
- // |sinksToShow_| in the same position, as the cast modes or other
- // fields may have been updated.
- this.sinksToShow_[i] = updatedSinkList[index];
- updatedSinkList.splice(index, 1);
- }
- }
-
- updatedSinkList = this.sinksToShow_.concat(updatedSinkList);
- }
- this.sinksToShow_ = updatedSinkList;
- },
-
- /**
- * Called when |allSinks| is updated.
- *
- * @private
- */
- reindexSinksAndRebuildSinksToShow_: function() {
- this.sinkMap_ = {};
-
- this.allSinks.forEach(function(sink) {
- if (!sink.isPseudoSink) {
- this.sinkMap_[sink.id] = sink;
- }
- }, this);
-
- if (this.pseudoSinkSearchState_) {
- this.currentLaunchingSinkId_ =
- this.pseudoSinkSearchState_.checkForRealSink(this.allSinks);
- }
- this.pseudoSinks_ = this.allSinks.filter(function(sink) {
- return sink.isPseudoSink && !!sink.domain;
- });
- this.rebuildSinksToShow_();
- this.searchEnabled_ = this.searchEnabled_ || this.pseudoSinks_.length > 0 ||
- this.sinksToShow_.length >= media_router.MINIMUM_SINKS_FOR_SEARCH;
- this.filterSinks_(this.searchInputText_ || '');
- if (this.currentView_ != media_router.MediaRouterView.FILTER) {
- // This code is in the unique position of seeing |animationPromise_| as
- // null on startup. |allSinks| is initialized before |animationPromise_|
- // and this listener runs when |allSinks| is initialized.
- if (this.animationPromise_) {
- this.animationPromise_ =
- this.animationPromise_.then(this.putSearchAtBottom_.bind(this));
- } else {
- this.putSearchAtBottom_();
- }
- } else {
- this.queuePutSearchAtTop_();
- }
- },
-
- /**
- * Resets the properties relevant to creating a new route. Fires an event
- * indicating whether or not route creation was successful.
- * Clearing |currentLaunchingSinkId_| hides the spinner indicating there is
- * a route creation in progress and show the device icon instead.
- * @param {boolean} creationSuccess Whether route creation succeeded.
- *
- * @private
- */
- resetRouteCreationProperties_: function(creationSuccess) {
- this.pseudoSinkSearchState_ = null;
- this.currentLaunchingSinkId_ = '';
- this.pendingCreatedRouteId_ = '';
- // If it was a search that failed we need to refresh the filtered sinks now
- // that |pseudoSinkSearchState_| is null.
- if (!creationSuccess &&
- this.currentView_ == media_router.MediaRouterView.FILTER) {
- this.filterSinks_(this.searchInputText_);
- }
-
- this.fire('report-route-creation', {success: creationSuccess});
- },
-
- /**
- * Responds to a click on the search button by toggling sink filtering.
- */
- searchButtonClick_: function() {
- // Redundancy needed because focus() only fires event if input is not
- // already focused. In the case that user typed text, hit escape, then
- // clicks the search button, a focus event will not fire and so its event
- // handler from ready() will not run.
- this.showSearchResults_();
- this.$$('#sink-search-input').focus();
- },
-
- /**
- * Initializes the position of the search input if search becomes enabled.
- * @param {boolean} searchEnabled The new value of |searchEnabled_|.
- * @private
- */
- searchEnabledChanged_: function(searchEnabled) {
- if (searchEnabled) {
- this.async(function() {
- this.setSearchFocusHandlers_();
- this.putSearchAtBottom_();
- });
- }
- },
-
- /**
- * Filters the sink list when the input text changes and shows the search
- * results if |searchInputText| is not empty.
- * @param {string} searchInputText The currently entered search text.
- * @private
- */
- searchInputTextChanged_: function(searchInputText) {
- this.filterSinks_(searchInputText);
- if (searchInputText.length != 0) {
- this.showSearchResults_();
- this.maybeReportFilter_();
- }
- },
-
- /**
- * Sets the selected cast mode to the one associated with |castModeType|,
- * and rebuilds sinks to reflect the change.
- * @param {number} castModeType The type of the selected cast mode.
- */
- selectCastMode: function(castModeType) {
- var castMode = this.findCastModeByType_(castModeType);
- if (castMode && castModeType != this.shownCastModeValue_) {
- this.setShownCastMode_(castMode);
- this.userHasSelectedCastMode_ = true;
- this.rebuildSinksToShow_();
- }
- },
-
- /**
- * Fires the command to open a file dialog.
- *
- * @private
- */
- selectLocalMediaFile_() {
- this.fire('select-local-media-file');
- },
-
- /**
- * Sets various focus and blur event handlers to handle showing search results
- * when the search input is focused.
- * @private
- */
- setSearchFocusHandlers_: function() {
- var searchInput = this.$$('#sink-search-input');
- var that = this;
-
- // The window can see a blur event for two important cases: the window is
- // actually losing focus or keyboard focus is wrapping from the end of the
- // document to the beginning. To handle both cases, we save whether the
- // search input was focused during the window blur event.
- //
- // When the search input receives focus, it could be as part of window
- // focus. If the search input was also focused on window blur, it shouldn't
- // show search results if they aren't already being shown. Otherwise,
- // focusing the search input should activate the FILTER view by calling
- // |showSearchResults_()|.
- window.addEventListener('blur', function() {
- that.isSearchFocusedOnWindowBlur_ =
- that.shadowRoot.activeElement == searchInput;
- });
- searchInput.addEventListener('focus', function() {
- if (!that.isSearchFocusedOnWindowBlur_) {
- that.showSearchResults_();
- }
- });
- },
-
- /**
- * Updates the shown cast mode, and updates the header text fields
- * according to the cast mode. If |castMode| type is AUTO, then set
- * |userHasSelectedCastMode_| to false.
- *
- * @param {!media_router.CastMode} castMode
- */
- setShownCastMode_: function(castMode) {
- if (this.shownCastModeValue_ == castMode.type) {
- return;
- }
-
- this.shownCastModeValue_ = castMode.type;
- this.headerText = castMode.description;
- this.headerTextTooltip = castMode.host || '';
- if (castMode.type == media_router.CastModeType.AUTO) {
- this.userHasSelectedCastMode_ = false;
- }
- },
-
- /**
- * Shows the cast mode list.
- *
- * @private
- */
- showCastModeList_: function() {
- this.currentView_ = media_router.MediaRouterView.CAST_MODE_LIST;
- },
-
- /**
- * Creates a new route if there is no route to the |sink| . Otherwise,
- * shows the route details.
- *
- * @param {!media_router.Sink} sink The sink to use.
- * @private
- */
- showOrCreateRoute_: function(sink) {
- var route = this.sinkToRouteMap_[sink.id];
- if (route) {
- this.showRouteDetails_(route);
- this.fire('navigate-sink-list-to-details');
- this.maybeReportUserFirstAction(
- media_router.MediaRouterUserAction.STATUS_REMOTE);
- } else if (this.currentLaunchingSinkId_ == '') {
- // Allow one launch at a time.
- var selectedCastModeValue =
- this.shownCastModeValue_ == media_router.CastModeType.AUTO ?
- sink.castModes & -sink.castModes :
- this.shownCastModeValue_;
- if (sink.isPseudoSink) {
- this.pseudoSinkSearchState_ = new PseudoSinkSearchState(sink);
- this.fire('search-sinks-and-create-route', {
- id: sink.id,
- name: sink.name,
- domain: sink.domain,
- selectedCastMode: selectedCastModeValue
- });
- } else {
- this.fire('create-route', {
- sinkId: sink.id,
- // If user selected a cast mode, then we will create a route using
- // that cast mode. Otherwise, the UI is in "auto" cast mode and will
- // use the preferred cast mode compatible with the sink. The preferred
- // cast mode value is the least significant bit on the bitset.
- selectedCastModeValue: selectedCastModeValue
- });
-
- var timeToSelectSink =
- window.performance.now() - this.populatedSinkListSeenTimeMs_;
- this.fire('report-sink-click-time', {timeMs: timeToSelectSink});
- }
- this.currentLaunchingSinkId_ = sink.id;
- if (sink.isPseudoSink) {
- this.rebuildSinksToShow_();
- }
-
- this.maybeReportUserFirstAction(
- media_router.MediaRouterUserAction.START_LOCAL);
- }
- },
-
- /**
- * Shows the route details.
- *
- * @param {!media_router.Route} route The route to show.
- * @private
- */
- showRouteDetails_: function(route) {
- this.currentRoute_ = route;
- this.currentView_ = media_router.MediaRouterView.ROUTE_DETAILS;
- if (route.supportsWebUiController) {
- media_router.browserApi.onMediaControllerAvailable(route.id);
- }
- if (this.$$('route-details')) {
- this.$$('route-details').onOpened();
- }
- },
-
- /**
- * Shows the search results.
- *
- * @private
- */
- showSearchResults_: function() {
- if (this.currentView_ != media_router.MediaRouterView.FILTER) {
- this.currentView_ = media_router.MediaRouterView.FILTER;
- this.queueMoveSearchToTop_();
- }
- },
-
- /**
- * Shows the sink list.
- *
- * @private
- */
- showSinkList_: function() {
- if (this.currentView_ == media_router.MediaRouterView.FILTER) {
- this.queueMoveSearchToBottom_();
- this.currentView_ = media_router.MediaRouterView.SINK_LIST;
- } else {
- this.currentView_ = media_router.MediaRouterView.SINK_LIST;
- this.putSearchAtBottom_();
- }
- },
-
- /**
- * Starts a timer which fires a close-dialog event if the user's mouse is
- * not positioned over the dialog after three seconds.
- *
- * @private
- */
- startTapTimer_: function() {
- var id = setTimeout(function() {
- if (!this.mouseIsPositionedOverDialog_) {
- this.fire('close-dialog', {
- pressEscToClose: false,
- });
- }
- }.bind(this), 3000 /* 3 seconds */);
- },
-
- /**
- * Toggles |currentView_| between CAST_MODE_LIST and SINK_LIST.
- *
- * @private
- */
- toggleCastModeHidden_: function() {
- if (this.currentView_ == media_router.MediaRouterView.CAST_MODE_LIST) {
- this.showSinkList_();
- } else if (this.currentView_ == media_router.MediaRouterView.SINK_LIST) {
- this.showCastModeList_();
- this.fire('navigate-to-cast-mode-list');
- }
- },
-
- /**
- * Update the position-related styling of some elements.
- *
- * @private
- */
- updateElementPositioning_: function() {
- // Ensures that conditionally templated elements have finished stamping.
- this.async(function() {
- var headerHeight = this.header.offsetHeight;
- // Unlike the other elements whose heights are fixed, the first-run-flow
- // element can have a fractional height. So we use getBoundingClientRect()
- // to avoid rounding errors.
- var firstRunFlowHeight = this.$$('#first-run-flow') &&
- this.$$('#first-run-flow').style.display != 'none' ?
- this.$$('#first-run-flow').getBoundingClientRect().height :
- 0;
- var issueHeight = this.$$('#issue-banner') &&
- this.$$('#issue-banner').style.display != 'none' ?
- this.$$('#issue-banner').offsetHeight :
- 0;
- var search = this.$$('#sink-search');
- var hasSearch = this.hasConditionalElement_(search);
- var searchHeight = hasSearch ? search.offsetHeight : 0;
- var searchPadding =
- hasSearch ? this.computeElementVerticalPadding_(search) : 0;
-
- this.header.style.marginTop = firstRunFlowHeight + 'px';
- this.$['content'].style.marginTop =
- firstRunFlowHeight + headerHeight + 'px';
-
- var sinkList = this.$$('#sink-list');
- var sinkListPadding =
- sinkList ? this.computeElementVerticalPadding_(sinkList) : 0;
-
- this.sinkListMaxHeight_ = this.dialogHeight_ - headerHeight -
- firstRunFlowHeight - issueHeight - searchHeight + searchPadding -
- sinkListPadding;
-
- // Limit the height of the dialog to ten items, including search.
- var sinkItemHeight = 41;
- var maxSinkItems = hasSearch ? 9 : 10;
- this.sinkListMaxHeight_ =
- Math.min(sinkItemHeight * maxSinkItems, this.sinkListMaxHeight_);
- if (sinkList) {
- sinkList.style.maxHeight = this.sinkListMaxHeight_ + 'px';
- }
- });
- },
-
- /**
- * Update the max dialog height and update the positioning of the elements.
- *
- * @param {number} height The max height of the Media Router dialog.
- */
- updateMaxDialogHeight: function(height) {
- this.dialogHeight_ = height;
- this.updateElementPositioning_();
- },
-
- /**
- * Sets the selected cast mode menu item to be in sync with the current cast
- * mode.
- * @private
- */
- updateSelectedCastModeMenuItem_: function() {
- /** @const */ var curIndex =
- this.findCastModeIndexByType_(this.shownCastModeValue_);
- if (this.selectedCastModeMenuItem_ != curIndex) {
- this.selectedCastModeMenuItem_ = curIndex;
- }
- },
-});
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container_interface.js b/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container_interface.js
deleted file mode 100644
index 052d81d4811..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_container/media_router_container_interface.js
+++ /dev/null
@@ -1,176 +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.
-
-/**
- * This Polymer element contains the entire media router interface. It handles
- * hiding and showing specific components.
- * @record
- */
-function MediaRouterContainerInterface() {}
-
-/**
- * The list of available sinks.
- * @type {!Array<!media_router.Sink>}
- */
-MediaRouterContainerInterface.prototype.allSinks;
-
-/**
- * The list of CastModes to show.
- * @type {!Array<!media_router.CastMode>|undefined}
- */
-MediaRouterContainerInterface.prototype.castModeList;
-
-/**
- * The URL to open when the device missing link is clicked.
- * @type {string|undefined}
- */
-MediaRouterContainerInterface.prototype.deviceMissingUrl;
-
-/**
- * The URL to open when the cloud services pref learn more link is clicked.
- * @type {string|undefined}
- */
-MediaRouterContainerInterface.prototype.firstRunFlowCloudPrefLearnMoreUrl;
-
-/**
- * The URL to open when the first run flow learn more link is clicked.
- * @type {string|undefined}
- */
-MediaRouterContainerInterface.prototype.firstRunFlowLearnMoreUrl;
-
-/**
- * The header element.
- * @type {!MediaRouterHeaderElement}
- */
-MediaRouterContainerInterface.prototype.header;
-
-/**
- * The header text for the sink list.
- * @type {string|undefined}
- */
-MediaRouterContainerInterface.prototype.headerText;
-
-/**
- * The header text tooltip. This would be descriptive of the
- * source origin, whether a host name, tab URL, etc.
- * @type {string|undefined}
- */
-MediaRouterContainerInterface.prototype.headerTextTooltip;
-
-/**
- * The issue to show.
- * @type {?media_router.Issue}
- */
-MediaRouterContainerInterface.prototype.issue;
-
-/**
- * The list of current routes.
- * @type {!Array<!media_router.Route>|undefined}
- */
-MediaRouterContainerInterface.prototype.routeList;
-
-/**
- * Whether the search input should be padded as if it were at the bottom of
- * the dialog.
- * @type {boolean}
- */
-MediaRouterContainerInterface.prototype.searchUseBottomPadding;
-
-/**
- * Whether to show the user domain of sinks associated with identity.
- * @type {boolean|undefined}
- */
-MediaRouterContainerInterface.prototype.showDomain;
-
-/**
- * Whether to show the first run flow.
- * @type {boolean|undefined}
- */
-MediaRouterContainerInterface.prototype.showFirstRunFlow;
-
-/**
- * Whether to show the cloud preference setting in the first run flow.
- * @type {boolean|undefined}
- */
-MediaRouterContainerInterface.prototype.showFirstRunFlowCloudPref;
-
-/**
- * Whether the WebUI route controls should be shown instead of the
- * extensionview in the route details view.
- * @type {boolean}
- */
-MediaRouterContainerInterface.prototype.useWebUiRouteControls;
-
-/**
- * Adds an event listener callback for an event.
- * @param {string} eventName
- * @param {function(!Event)} callback
- */
-MediaRouterContainerInterface.prototype.addEventListener = function(
- eventName, callback) {};
-
-/**
- * Fires a 'report-initial-action' event when the user takes their first
- * action after the dialog opens. Also fires a 'report-initial-action-close'
- * event if that initial action is to close the dialog.
- * @param {!media_router.MediaRouterUserAction} initialAction
- */
-MediaRouterContainerInterface.prototype.maybeReportUserFirstAction = function(
- initialAction) {};
-
-/**
- * Updates |currentView_| if the dialog had just opened and there's
- * only one local route.
- */
-MediaRouterContainerInterface.prototype.maybeShowRouteDetailsOnOpen =
- function() {};
-
-/**
- * Handles response of previous create route attempt.
- * @param {string} sinkId The ID of the sink to which the Media Route was
- * creating a route.
- * @param {?media_router.Route} route The newly created route that
- * corresponds to the sink if route creation succeeded; null otherwise.
- * @param {boolean} isForDisplay Whether or not |route| is for display.
- */
-MediaRouterContainerInterface.prototype.onCreateRouteResponseReceived =
- function(sinkId, route, isForDisplay) {};
-
-/**
- * Handles the result of a requested file dialog.
- * @param {string} fileName The name of the file that has been selected.
- */
-MediaRouterContainerInterface.prototype.onFileDialogSuccess = function(
- fileName) {};
-
-/**
- * Called when a search has completed up to route creation. |sinkId|
- * identifies the sink that should be in |allSinks|, if a sink was found.
- * @param {string} sinkId The ID of the sink that is the result of the
- * currently pending search.
- */
-MediaRouterContainerInterface.prototype.onReceiveSearchResult = function(
- sinkId) {};
-
-/**
- * Called when the connection to the route controller is invalidated. Switches
- * from route details view to the sink list view.
- */
-MediaRouterContainerInterface.prototype.onRouteControllerInvalidated =
- function() {};
-
-/**
- * Sets the selected cast mode to the one associated with |castModeType|,
- * and rebuilds sinks to reflect the change.
- * @param {number} castModeType The type of the selected cast mode.
- */
-MediaRouterContainerInterface.prototype.selectCastMode = function(
- castModeType) {};
-
-/**
- * Update the max dialog height and update the positioning of the elements.
- * @param {number} height The max height of the Media Router dialog.
- */
-MediaRouterContainerInterface.prototype.updateMaxDialogHeight = function(
- height) {};
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_container/pseudo_sink_search_state.js b/chromium/chrome/browser/resources/media_router/elements/media_router_container/pseudo_sink_search_state.js
deleted file mode 100644
index b0c97cccdfa..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_container/pseudo_sink_search_state.js
+++ /dev/null
@@ -1,73 +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.
-
-/**
- * This class holds state that is relevant to the search process from the UI's
- * perspective. It primarily handles the spinner logic while waiting for a
- * search to complete. The spinner first needs to start on the pseudo sink, but
- * when a real sink arrives to replace it the spinner should transfer to the
- * real sink.
- *
- * Additionally, this class provides a method for
- * onCreateRouteResponseReceived() that maps the pseudo sink ID that started the
- * search to the real sink that was produced by the search. This helps check
- * whether a received route is valid.
- *
- * @param {!media_router.Sink} pseudoSink Pseudo sink that started the search.
- * @constructor
- */
-var PseudoSinkSearchState = function(pseudoSink) {
- /**
- * Pseudo sink that started the search.
- * @private {!media_router.Sink}
- */
- this.pseudoSink_ = pseudoSink;
-
- /**
- * The ID of the sink that is found by search.
- * @private {string}
- */
- this.realSinkId_ = '';
-
- /**
- * Whether we have received a sink in the sink list with ID |realSinkId_|.
- * @private {boolean}
- */
- this.hasRealSink_ = false;
-};
-
-/**
- * Record the real sink ID returned from the Media Router.
- * @param {string} sinkId Real sink ID that is the result of the search.
- */
-PseudoSinkSearchState.prototype.receiveSinkResponse = function(sinkId) {
- this.realSinkId_ = sinkId;
-};
-
-/**
- * Checks whether we have a sink in |sinkList| that is our search result then
- * computes the value for |currentLaunchingSinkId_| based on the state of the
- * search. It should be the pseudo sink ID until the real sink arrives, then the
- * real sink ID.
- * @param {!Array<!media_router.Sink>} sinkList List of all sinks to check.
- * @return {string} New value for |currentLaunchingSinkId_|.
- */
-PseudoSinkSearchState.prototype.checkForRealSink = function(sinkList) {
- if (!this.hasRealSink_) {
- this.hasRealSink_ = !!this.realSinkId_ && sinkList.some(function(sink) {
- return (sink.id == this.realSinkId_);
- }, this);
- return !this.hasRealSink_ ? this.pseudoSink_.id : this.realSinkId_;
- }
- return this.realSinkId_;
-};
-
-/**
- * Returns the pseudo sink for the current search. This is used to enforce
- * freezing its name in filter view and displaying it in the sink list view.
- * @return {!media_router.Sink}
- */
-PseudoSinkSearchState.prototype.getPseudoSink = function() {
- return this.pseudoSink_;
-};
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.css b/chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.css
deleted file mode 100644
index 124b120cd1d..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.css
+++ /dev/null
@@ -1,83 +0,0 @@
-/* Copyright 2015 The Chromium Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file. */
-
-#arrow-drop-container {
- flex-grow: 1;
-}
-
-#arrow-drop-icon {
- height: var(--navigation-icon-button-size);
- width: var(--navigation-icon-button-size);
-}
-
-#back-button {
- height: var(--navigation-icon-button-size);
- width: var(--navigation-icon-button-size);
-}
-
-#back-button-container {
- padding-inline-end: 4px;
-}
-
-#close-button {
- height: 31px;
- margin-inline-start: auto;
- width: 31px;
-}
-
-#close-button-container {
- margin-inline-start: auto;
- padding-inline-end: 16px;
- padding-inline-start: 24px;
-}
-
-#header {
- align-items: center;
- color: white;
- padding-inline-start: 8px;
-}
-
-#header-and-arrow-container {
- display: flex;
- overflow: hidden;
- white-space: nowrap;
-}
-
-cr-icon-button {
- --cr-icon-button-color: currentColor;
-}
-
-#header-text {
- font-size: 1.175em;
- line-height: 36px;
- margin: 0 8px;
- overflow: hidden;
- padding-inline-end: 4px;
- text-overflow: ellipsis;
-}
-
-.issue {
- background-color: var(--paper-red-700);
-}
-
-#main-container {
- display: flex;
- padding-top: 10px;
-}
-
-.cast-mode-list,
-.filter,
-.route-details,
-.sink-list {
- background-color: var(--paper-blue-700);
-}
-
-#user-email-container {
- bottom: 0;
- font-size: 0.917em;
- left: auto;
- padding-bottom: 12px;
- padding-inline-start: 8px;
- position: absolute;
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.html b/chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.html
deleted file mode 100644
index 5b9189bf3a8..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.html
+++ /dev/null
@@ -1,43 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
-<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="../../icons/media_router_icons.html">
-<dom-module id="media-router-header">
- <link rel="import" type="css" href="../../media_router_common.css">
- <link rel="import" type="css" href="media_router_header.css">
- <template>
- <div id="header" class$="[[view]]">
- <div id="main-container">
- <template is="dom-if" if="[[computeBackButtonShown_(view)]]">
- <div id="back-button-container">
- <cr-icon-button id="back-button" iron-icon="[[arrowDropIcon_]]"
- on-tap="onBackButtonClick_" title="[[i18n('backButtonTitle')]]">
- </cr-icon-button>
- </div>
- </template>
- <div id="header-and-arrow-container" on-tap="onHeaderOrArrowClick_">
- <span id="header-text" title="[[tooltip]]">
- [[headingText]]</span>
- <div id="arrow-drop-container">
- <cr-icon-button iron-icon="[[computeArrowDropIcon_(view)]]"
- id="arrow-drop-icon" disabled$="[[arrowDropIconDisabled]]"
- hidden$="[[computeArrowDropIconHidden_(view)]]"
- title="[[computeArrowDropTitle_(view)]]">
- </cr-icon-button>
- </div>
- </div>
- <div id="close-button-container">
- <cr-icon-button iron-icon="cr:close" id="close-button"
- on-tap="onCloseButtonClick_" title="[[i18n('closeButtonTitle')]]">
- </cr-icon-button>
- </div>
- </div>
- <template is="dom-if" if="[[showEmail]]">
- <div id="user-email-container">[[userEmail]]</div>
- </template>
- </div>
- </template>
-<script src="media_router_header.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.js b/chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.js
deleted file mode 100644
index 138238acc7e..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.js
+++ /dev/null
@@ -1,233 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This Polymer element is used as a header for the media router interface.
-Polymer({
- is: 'media-router-header',
-
- properties: {
- /**
- * The name of the icon used as the back button. This is set once, when
- * the |this| is ready.
- * @private {string|undefined}
- */
- arrowDropIcon_: {
- type: String,
- },
-
- /**
- * Whether or not the arrow drop icon should be disabled.
- * @type {boolean}
- */
- arrowDropIconDisabled: {
- type: Boolean,
- value: false,
- },
-
- /**
- * The header text to show.
- * @type {string|undefined}
- */
- headingText: {
- type: String,
- },
-
- /**
- * The height of the header when it shows the user email.
- * @private {number}
- */
- headerWithEmailHeight_: {
- type: Number,
- readOnly: true,
- value: 62,
- },
-
- /**
- * The height of the header when it doesn't show the user email.
- * @private {number}
- */
- headerWithoutEmailHeight_: {
- type: Number,
- readOnly: true,
- value: 52,
- },
-
- /**
- * Whether to show the user email in the header.
- * @type {boolean|undefined}
- */
- showEmail: {
- type: Boolean,
- observer: 'maybeChangeHeaderHeight_',
- },
-
- /**
- * The text to show in the tooltip.
- * @type {string|undefined}
- */
- tooltip: {
- type: String,
- },
-
- /**
- * The user email if they are signed in.
- * @type {string|undefined}
- */
- userEmail: {
- type: String,
- },
-
- /**
- * The current view that this header should reflect.
- * @type {?media_router.MediaRouterView|undefined}
- */
- view: {
- type: String,
- observer: 'updateHeaderCursorStyle_',
- },
- },
-
- behaviors: [
- I18nBehavior,
- ],
-
- ready: function() {
- this.$$('#header').style.height = this.headerWithoutEmailHeight_ + 'px';
- },
-
- attached: function() {
- // isRTL() only works after <html dir> is set.
- // Set the back button icon based on text direction.
- this.arrowDropIcon_ = isRTL() ? 'cr:arrow-forward' : 'cr:arrow-back';
- },
-
- /**
- * @param {?media_router.MediaRouterView} view The current view.
- * @return {string} The icon to use.
- * @private
- */
- computeArrowDropIcon_: function(view) {
- return view == media_router.MediaRouterView.CAST_MODE_LIST ?
- 'cr:arrow-drop-up' :
- 'cr:arrow-drop-down';
- },
-
- /**
- * @param {?media_router.MediaRouterView} view The current view.
- * @return {boolean} Whether or not the arrow drop icon should be hidden.
- * @private
- */
- computeArrowDropIconHidden_: function(view) {
- return view != media_router.MediaRouterView.SINK_LIST &&
- view != media_router.MediaRouterView.CAST_MODE_LIST;
- },
-
- /**
- * @param {?media_router.MediaRouterView} view The current view.
- * @return {string} The title text for the arrow drop button.
- * @private
- */
- computeArrowDropTitle_: function(view) {
- return view == media_router.MediaRouterView.CAST_MODE_LIST ?
- this.i18n('viewDeviceListButtonTitle') :
- this.i18n('viewCastModeListButtonTitle');
- },
-
- /**
- * @param {?media_router.MediaRouterView} view The current view.
- * @return {boolean} Whether or not the back button should be shown.
- * @private
- */
- computeBackButtonShown_: function(view) {
- return view == media_router.MediaRouterView.ROUTE_DETAILS ||
- view == media_router.MediaRouterView.FILTER;
- },
-
- /**
- * Returns whether given string is undefined, null, empty, or whitespace only.
- * @param {?string} str String to be tested.
- * @return {boolean} |true| if the string is undefined, null, empty, or
- * whitespace.
- * @private
- */
- isEmptyOrWhitespace_: function(str) {
- return str === undefined || str === null || (/^\s*$/).test(str);
- },
-
- /**
- * Handles a click on the back button by firing a back-click event.
- *
- * @private
- */
- onBackButtonClick_: function() {
- this.fire('back-click');
- },
-
- /**
- * Handles a click on the close button by firing a close-button-click event.
- *
- * @private
- */
- onCloseButtonClick_: function() {
- this.fire('close-dialog', {
- pressEscToClose: false,
- });
- },
-
- /**
- * Handles a click on the arrow button by firing an arrow-click event.
- *
- * @private
- */
- onHeaderOrArrowClick_: function() {
- if (this.view == media_router.MediaRouterView.SINK_LIST ||
- this.view == media_router.MediaRouterView.CAST_MODE_LIST) {
- this.fire('header-or-arrow-click');
- }
- },
-
- /**
- * Updates header height to accomodate email text. This is called on changes
- * to |showEmail| and will return early if the value has not changed.
- *
- * @param {boolean} newValue The new value of |showEmail|.
- * @param {boolean} oldValue The previous value of |showEmail|.
- * @private
- */
- maybeChangeHeaderHeight_: function(newValue, oldValue) {
- if (oldValue == newValue) {
- return;
- }
-
- // Ensures conditional templates are stamped.
- this.async(function() {
- var currentHeight = this.offsetHeight;
-
- this.$$('#header').style.height =
- this.showEmail && !this.isEmptyOrWhitespace_(this.userEmail) ?
- this.headerWithEmailHeight_ + 'px' :
- this.headerWithoutEmailHeight_ + 'px';
-
- // Only fire if height actually changed.
- if (currentHeight != this.offsetHeight) {
- this.fire('header-height-changed');
- }
- });
- },
-
- /**
- * Updates the cursor style for the header text when the view changes. When
- * the drop arrow is also shown, the header text is also clickable.
- *
- * @param {?media_router.MediaRouterView} view The current view.
- * @private
- */
- updateHeaderCursorStyle_: function(view) {
- this.$$('#header-text').style.cursor =
- view == media_router.MediaRouterView.SINK_LIST ||
- view == media_router.MediaRouterView.CAST_MODE_LIST ?
- 'pointer' :
- 'auto';
- },
-});
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/BUILD.gn b/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/BUILD.gn
deleted file mode 100644
index 7881aba419e..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/BUILD.gn
+++ /dev/null
@@ -1,17 +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("//third_party/closure_compiler/compile_js.gni")
-
-js_type_check("closure_compile") {
- deps = [
- ":media_router_search_highlighter",
- ]
-}
-
-js_library("media_router_search_highlighter") {
- deps = [
- "//ui/webui/resources/js:util",
- ]
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.css b/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.css
deleted file mode 100644
index 39b1c2f334c..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.css
+++ /dev/null
@@ -1,7 +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. */
-
-.highlight {
- font-weight: bold;
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.html b/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.html
deleted file mode 100644
index dbb9334ae99..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-<dom-module id="media-router-search-highlighter">
- <link rel="import" type="css" href="media_router_search_highlighter.css">
- <template>
- <span id="text" dir="auto"></span>
- </template>
-</dom-module>
-<script src="media_router_search_highlighter.js"></script>
diff --git a/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.js b/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.js
deleted file mode 100644
index b3d8e17187e..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.js
+++ /dev/null
@@ -1,79 +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.
-
-// This Polymer element displays text that needs sections of it highlighted.
-// This is useful, for example, for displaying which portions of a string were
-// matched by some filter text.
-Polymer({
- is: 'media-router-search-highlighter',
-
- properties: {
- /**
- * The text that this element should display, split it into highlighted and
- * normal text. The displayed text will alternate between plainText and
- * highlightedText.
- *
- * Example: You have a sink with the name 'living room'.
- * When your seach text is 'living', the resulting arrays will be:
- * plainText: [null, ' room'], highlightedText: ['living', null]
- *
- * When your search text is 'room', the resulting arrays will be:
- * plainText: ['living ', null], highlightedText: [null, 'room']
- *
- * null corresponds to an empty string when the arrays are being combined.
- * So both examples reproduce the text 'living room', but with different
- * words highlighted.
- * @type {{highlightedText: !Array<?string>,
- * plainText: !Array<?string>}|undefined}
- */
- data: {
- type: Object,
- observer: 'dataChanged_',
- },
-
- /**
- * The text that this element is displaying as a plain string. The primary
- * purpose for this property is to make getting this element's textContent
- * easy for testing.
- * @type {string|undefined}
- */
- text: {
- type: String,
- readOnly: true,
- notify: false,
- },
- },
-
- /**
- * Update the element text if |data| changes.
- *
- * The order the strings are combined is plainText[0] highlightedText[0]
- * plainText[1] highlightedText[1] etc.
- *
- * @param {{highlightedText: !Array<?string>, plainText: !Array<?string>}}
- * data
- * Parameters in |data|:
- * highlightedText - Array of strings that should be displayed highlighted.
- * plainText - Array of strings that should be displayed normally.
- */
- dataChanged_: function(data) {
- if (!data || !data.highlightedText || !data.plainText) {
- return;
- }
-
- var text = '';
- for (var i = 0; i < data.highlightedText.length; ++i) {
- if (data.plainText[i]) {
- text += HTMLEscape(/** @type {!string} */ (data.plainText[i]));
- }
- if (data.highlightedText[i]) {
- text += '<span class="highlight">' +
- HTMLEscape(/** @type {!string} */ (data.highlightedText[i])) +
- '</span>';
- }
- }
- this.$.text.innerHTML = text;
- this._setText(this.$.text.textContent);
- },
-});
diff --git a/chromium/chrome/browser/resources/media_router/elements/route_controls/BUILD.gn b/chromium/chrome/browser/resources/media_router/elements/route_controls/BUILD.gn
deleted file mode 100644
index 0b21078a54b..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/route_controls/BUILD.gn
+++ /dev/null
@@ -1,28 +0,0 @@
-# Copyright 2018 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import("//third_party/closure_compiler/compile_js.gni")
-
-js_type_check("closure_compile") {
- deps = [
- ":route_controls",
- ":route_controls_interface",
- ]
-}
-
-js_library("route_controls") {
- deps = [
- "../..:media_router_browser_api",
- "../..:media_router_data",
- "../..:media_router_ui_interface",
- "//ui/webui/resources/js:i18n_behavior",
- "//ui/webui/resources/js:load_time_data",
- ]
-}
-
-js_library("route_controls_interface") {
- deps = [
- "../..:media_router_data",
- ]
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.css b/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.css
deleted file mode 100644
index 811d8db7825..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.css
+++ /dev/null
@@ -1,114 +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. */
-
-#button-holder {
- float: left;
-}
-
-#current-time {
- left: 20px;
- position: absolute;
-}
-
-#duration {
- position: absolute;
- right: 20px;
-}
-
-:host-context([dir='rtl']) #play-pause-volume-hangouts-controls {
- transform: scaleX(-1);
-}
-
-:host-context([dir='rtl']) #route-play-pause-button {
- transform: scaleX(-1);
-}
-
-:host-context([dir='rtl']) #volume-holder {
- transform: scaleX(-1);
-}
-
-#media-controls {
- font-size: 1.25em;
- margin: 0 8px;
-}
-
-#play-pause-volume-hangouts-controls {
- display: block;
- margin-top: 13px;
- overflow: hidden;
-}
-
-#route-description {
- margin: 15px 8px 3px 8px;
- width: 90%;
-}
-
-#route-time-controls {
- display: block;
- margin-top: 3px;
- overflow: hidden;
-}
-
-#route-time-slider {
- --cr-slider-active-color: rgb(16, 16, 16);
- --cr-slider-container-color: rgba(16, 16, 16, .24);
- --cr-slider-knob-color: rgb(16, 16, 16);
- width: 100%;
-}
-
-#route-title {
- color: rgb(125, 125, 125);
- margin: 3px 8px;
-}
-
-#route-volume-slider {
- --cr-slider-active-color: rgb(33, 150, 243);
- --cr-slider-container-color: rgba(16, 16, 16, .24);
- --cr-slider-knob-color: rgb(16, 16, 16);
- width: 100%;
-}
-
-#timeline {
- font-size: 0.75em;
-}
-
-#volume-holder {
- display: block;
- overflow: hidden;
- padding: 0.3em 0;
-}
-
-#hangouts-local-present-controls {
- cursor: pointer;
- display: inline-block;
- float: right;
- padding-top: 10.5px;
- white-space: nowrap;
-}
-
-#hangouts-local-present-checkbox {
- --cr-checkbox-label-container: {
- padding-inline-start: 14px;
- }
- align-items: start;
-}
-
-#hangouts-local-present-checkbox-subtitle {
- display: block;
- font-size: 0.8em;
- margin-top: 2px;
- width: 249px;
-}
-
-#mirroring-fullscreen-video-controls {
- display: inline-block;
- font-size: 0.8em;
- margin: 15px 8px 3px 8px;
- vertical-align: middle;
-}
-
-#mirroring-fullscreen-video-dropdown {
- margin-inline-start: 8px;
- width: auto;
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.html b/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.html
deleted file mode 100644
index c60d15d518f..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.html
+++ /dev/null
@@ -1,114 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_slider/cr_slider.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
-<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/iron-iconset-svg/iron-iconset-svg.html">
-
-<iron-iconset-svg name="route-controls" size="24">
-<svg><defs>
- <g id="play-arrow"><path d="M8 5v14l11-7z"></path></g>
- <g id="pause"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"></path></g>
- <g id="volume-off"><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"></path></g>
- <g id="volume-up"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"></path></g>
-</defs></svg>
-</iron-iconset-svg>
-
-<dom-module id="route-controls">
- <link rel="import" type="css" href="../../media_router_common.css">
- <link rel="import" type="css" href="route_controls.css">
- <template>
- <style include="md-select"></style>
- <div id="media-controls">
- <div class="ellipsis" id="route-description"
- title="[[routeDescription_]]">
- [[routeDescription_]]
- </div>
- <div class="ellipsis" id="route-title" title="[[routeStatus.title]]"
- hidden$="[[!shouldShowRouteStatusTitle_]]">
- [[routeStatus.title]]
- </div>
- <div>
- <div id="route-time-controls" hidden="[[!routeStatus.canSeek]]">
- <cr-slider
- aria-valuetext$="[[getTimeSliderValueText_(displayedCurrentTime_)]]"
- dir="ltr"
- id="route-time-slider"
- on-dragging-changed="onSeekingChanged_"
- on-cr-slider-value-changed="onSeekSliderValueChanged_"
- min="0" max="[[routeStatus.duration]]"
- title="[[i18n('seekTitle')]]"
- value="[[displayedCurrentTime_]]"></cr-slider>
- <div id="timeline">
- <span id="current-time"
- aria-label$="[[getCurrentTimeLabel_(displayedCurrentTime_)]]">
- [[getFormattedTime_(displayedCurrentTime_)]]
- </span>
- <span id="duration"
- aria-label$="[[getDurationLabel_(routeStatus.duration)]]">
- [[getFormattedTime_(routeStatus.duration)]]
- </span>
- </div>
- </div>
- <div id="play-pause-volume-hangouts-controls">
- <span id="button-holder" dir="ltr">
- <cr-icon-button
- id="route-play-pause-button"
- hidden="[[!routeStatus.canPlayPause]]"
- disabled="[[!routeStatus.canPlayPause]]"
- iron-icon="[[getPlayPauseIcon_(routeStatus)]]"
- title="[[getPlayPauseTitle_(routeStatus)]]"
- on-click="onPlayPause_"></cr-icon-button>
- <cr-icon-button
- id="route-volume-button"
- hidden="[[!routeStatus.canMute]]"
- disabled="[[!routeStatus.canMute]]"
- iron-icon="[[getMuteUnmuteIcon_(routeStatus)]]"
- title="[[getMuteUnmuteTitle_(routeStatus)]]"
- on-click="onMuteUnmute_"></cr-icon-button>
- </span>
- <span id="volume-holder" hidden="[[!routeStatus.canSetVolume]]">
- <cr-slider
- aria-valuetext$="[[getVolumeSliderValueText_(displayedVolume_)]]"
- id="route-volume-slider"
- disabled="[[!routeStatus.canSetVolume]]"
- on-cr-slider-value-changed="onVolumeChanged_"
- on-dragging-changed="onVolumeDraggingChanged_"
- title="[[i18n('volumeTitle')]]"></cr-slider>
- </span>
- <div id="hangouts-local-present-controls"
- hidden="[[!routeStatus.hangoutsExtraData]]">
- <cr-checkbox
- checked="[[hangoutsLocalPresent_]]"
- id="hangouts-local-present-checkbox"
- on-change="onHangoutsLocalPresentChange_">
- <span id='hangouts-local-present-checkbox-title'>
- [[i18n('hangoutsLocalPresentTitle')]]
- </span>
- <span id="hangouts-local-present-checkbox-subtitle">
- [[i18n('hangoutsLocalPresentSubtitle')]]
- </span>
- </cr-checkbox>
- </div>
- </div>
- <div id="mirroring-fullscreen-video-controls"
- hidden="[[!routeStatus.mirroringExtraData]]">
- [[i18n('fullscreenVideosDropdownTitle')]]
- <select class="md-select"
- id="mirroring-fullscreen-video-dropdown"
- on-change="onFullscreenVideoDropdownChange_">
- <option value="[[FullscreenVideoOption_.REMOTE_SCREEN]]">
- [[i18n('fullscreenVideosRemoteScreen')]]
- </option>
- <option value="[[FullscreenVideoOption_.BOTH_SCREENS]]">
- [[i18n('fullscreenVideosBothScreens')]]
- </option>
- </select>
- </div>
- </div>
- </div>
- </template>
-<script src="route_controls.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.js b/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.js
deleted file mode 100644
index e6769007457..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls.js
+++ /dev/null
@@ -1,547 +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.
-
-/**
- * This Polymer element shows media controls for a route that is currently cast
- * to a device.
- * @implements {RouteControlsInterface}
- */
-Polymer({
- is: 'route-controls',
-
- properties: {
- /**
- * Set of possible options for playing fullscreen videos when mirroring.
- * @private {!Object}
- */
- FullscreenVideoOption_: {
- type: Object,
- value: {
- // Play on remote screen only.
- REMOTE_SCREEN: 'remote_screen',
- // Play on both remote and local screens.
- BOTH_SCREENS: 'both_screens'
- }
- },
-
- /**
- * The current time displayed in seconds, before formatting.
- * @private {number}
- */
- displayedCurrentTime_: {
- type: Number,
- value: 0,
- },
-
- /**
- * The volume shown in the volume control, between 0 and 1.
- * @private {number}
- */
- displayedVolume_: {
- type: Number,
- value: 0,
- },
-
- /**
- * True if the Hangouts route is currently using local present mode.
- * Valid for Hangouts routes only.
- * @private {boolean}
- */
- hangoutsLocalPresent_: {
- type: Boolean,
- value: false,
- },
-
- /**
- * The timestamp for when the initial media status was loaded.
- * @private {number}
- */
- initialLoadTime_: {
- type: Number,
- value: 0,
- },
-
- /**
- * Set to true when the user is dragging the seek bar. Updates for the
- * current time from the browser will be ignored when set to true.
- * @private {boolean}
- */
- isSeeking_: {
- type: Boolean,
- value: false,
- },
-
- /**
- * Set to true when the user is dragging the volume bar. Volume updates from
- * the browser will be ignored when set to true.
- * @private
- */
- isVolumeChanging_: {
- type: Boolean,
- value: false,
- },
-
- /**
- * The timestamp for when the controller last submitted a seek request.
- * @private
- */
- lastSeekByUser_: {
- type: Number,
- value: 0,
- },
-
- /**
- * The timestamp for when |routeStatus| was last updated.
- * @private
- */
- lastStatusUpdate_: {
- type: Number,
- value: 0,
- },
-
- /**
- * The timestamp for when the controller last submitted a volume change
- * request.
- * @private
- */
- lastVolumeChangeByUser_: {
- type: Number,
- value: 0,
- },
-
- /**
- * Keep in sync with media remoting individual user setting.
- * @private
- */
- mediaRemotingEnabled_: {
- type: Boolean,
- value: true,
- },
-
- /**
- * The route currently associated with this controller.
- * @type {?media_router.Route|undefined}
- */
- route: {
- type: Object,
- observer: 'onRouteUpdated_',
- },
-
- /**
- * The route description to display. Uses the media route description if
- * none is provided by the media route status object.
- * @private {string}
- */
- routeDescription_: {
- type: String,
- value: '',
- },
-
- /**
- * The timestamp for when the route details view was opened.
- * @type {number}
- */
- routeDetailsOpenTime: {
- type: Number,
- value: 0,
- },
-
- /**
- * The status of the media route shown.
- * @type {!media_router.RouteStatus}
- */
- routeStatus: {
- type: Object,
- observer: 'onRouteStatusChange_',
- value: new media_router.RouteStatus(),
- },
-
- /**
- * The ID of the timer currently set to increment the current time of the
- * media, or 0 if the current time is not being incremented.
- * @private {number}
- */
- timeIncrementsTimeoutId_: {
- type: Number,
- value: 0,
- },
-
- /**
- * Whether the controls should show the media title.
- * @private {boolean}
- */
- shouldShowRouteStatusTitle_: {
- type: Boolean,
- value: false,
- },
- },
-
- behaviors: [
- I18nBehavior,
- ],
-
- /**
- * Called by Polymer when the element loads. Registers the element to be
- * notified of route status updates.
- */
- ready: function() {
- media_router.ui.setRouteControls(
- /** @type {RouteControlsInterface} */ (this));
- },
-
- /**
- * Current time can be incremented if the media is playing, and either the
- * duration is 0 or current time is less than the duration.
- * @return {boolean}
- * @private
- */
- canIncrementCurrentTime_: function() {
- return !this.isSeeking_ &&
- this.routeStatus.playState === media_router.PlayState.PLAYING &&
- (this.routeStatus.duration === 0 ||
- this.displayedCurrentTime_ < this.routeStatus.duration);
- },
-
- /**
- * Creates an accessibility label for the element showing the media's current
- * time.
- * @param {number} displayedCurrentTime
- * @return {string}
- * @private
- */
- getCurrentTimeLabel_: function(displayedCurrentTime) {
- return `${
- this.i18n('currentTimeLabel')
- } ${this.getFormattedTime_(displayedCurrentTime)}`;
- },
-
- /**
- * Creates an accessibility label for the element showing the media's
- * duration.
- * @param {number} duration
- * @return {string}
- * @private
- */
- getDurationLabel_: function(duration) {
- return `${this.i18n('durationLabel')} ${this.getFormattedTime_(duration)}`;
- },
-
- /**
- * Converts a number representing an interval of seconds to a string with
- * HH:MM:SS format.
- * @param {number} timeInSec Must be non-negative. Intervals longer than 100
- * hours get truncated silently.
- * @return {string}
- * @private
- */
- getFormattedTime_: function(timeInSec) {
- if (timeInSec < 0) {
- return '';
- }
- var hours = Math.floor(timeInSec / 3600);
- var minutes = Math.floor(timeInSec / 60) % 60;
- var seconds = Math.floor(timeInSec) % 60;
- // Show the hours only if it is nonzero.
- return (hours ? ('0' + hours).substr(-2) + ':' : '') +
- ('0' + minutes).substr(-2) + ':' + ('0' + seconds).substr(-2);
- },
-
- /**
- * @param {!media_router.RouteStatus} routeStatus
- * @return {string} The value for the icon attribute of the mute/unmute
- * button.
- * @private
- */
- getMuteUnmuteIcon_: function(routeStatus) {
- return routeStatus.isMuted ? 'route-controls:volume-off' :
- 'route-controls:volume-up';
- },
-
- /**
- * @param {!media_router.RouteStatus} routeStatus
- * @return {string} Localized title for the mute/unmute button.
- * @private
- */
- getMuteUnmuteTitle_: function(routeStatus) {
- return routeStatus.isMuted ? this.i18n('unmuteTitle') :
- this.i18n('muteTitle');
- },
-
- /**
- * @param {!media_router.RouteStatus} routeStatus
- * @return {string}The value for the icon attribute of the play/pause button.
- * @private
- */
- getPlayPauseIcon_: function(routeStatus) {
- return routeStatus.playState === media_router.PlayState.PAUSED ?
- 'route-controls:play-arrow' :
- 'route-controls:pause';
- },
-
- /**
- * @param {!media_router.RouteStatus} routeStatus
- * @return {string} Localized title for the play/pause button.
- * @private
- */
- getPlayPauseTitle_: function(routeStatus) {
- return routeStatus.playState === media_router.PlayState.PAUSED ?
- this.i18n('playTitle') :
- this.i18n('pauseTitle');
- },
-
- /**
- * @return {string} Text representing the current position on the seek slider.
- * @private
- */
- getTimeSliderValueText_: function(displayedCurrentTime) {
- if (!this.routeStatus) {
- return '';
- }
- return `${
- this.getFormattedTime_(displayedCurrentTime)
- } / ${this.getFormattedTime_(this.routeStatus.duration)}`;
- },
-
- /**
- * @param {number} volume
- * @return {string} The volume as a percentage.
- * @private
- */
- getVolumeSliderValueText_: function(volume) {
- return String(Math.round(volume * 100)) + '%';
- },
-
- /**
- * Checks whether the media is still playing, and if so, sends a media status
- * update incrementing the current time and schedules another call for a
- * second later.
- * @private
- */
- maybeIncrementCurrentTime_: function() {
- if (this.canIncrementCurrentTime_()) {
- var updatedCurrentTime = this.routeStatus.currentTime +
- Math.floor((Date.now() - this.lastStatusUpdate_) / 1000);
- this.displayedCurrentTime_ = this.routeStatus.duration === 0 ?
- updatedCurrentTime :
- Math.min(updatedCurrentTime, this.routeStatus.duration);
- if (this.routeStatus.duration === 0 ||
- this.displayedCurrentTime_ < this.routeStatus.duration) {
- this.timeIncrementsTimeoutId_ =
- setTimeout(() => this.maybeIncrementCurrentTime_(), 1000);
- }
- } else {
- this.timeIncrementsTimeoutId_ = 0;
- }
- },
-
- /**
- * Called when the "smooth motion" box for Hangouts is changed by the user.
- * @param {!{target: !HTMLElement}} e
- * @private
- */
- onHangoutsLocalPresentChange_: function(e) {
- media_router.browserApi.setHangoutsLocalPresent(e.target.checked);
- },
-
- /**
- * Called when the user toggles the mute status of the media. Sends a mute or
- * unmute command to the browser.
- * @private
- */
- onMuteUnmute_: function() {
- media_router.browserApi.setCurrentMediaMute(!this.routeStatus.isMuted);
- },
-
- /**
- * Called when the user toggles between playing and pausing the media. Sends a
- * play or pause command to the browser.
- * @private
- */
- onPlayPause_: function() {
- if (this.routeStatus.playState === media_router.PlayState.PAUSED) {
- media_router.browserApi.playCurrentMedia();
- } else {
- media_router.browserApi.pauseCurrentMedia();
- }
- },
-
- /**
- * Updates seek and volume bars if the user is not currently dragging on
- * them.
- * @param {!media_router.RouteStatus} newRouteStatus
- * @private
- */
- onRouteStatusChange_: function(newRouteStatus) {
- this.lastStatusUpdate_ = Date.now();
- if (this.shouldAcceptCurrentTimeUpdates_()) {
- this.displayedCurrentTime_ = newRouteStatus.currentTime;
- }
- if (this.shouldAcceptVolumeUpdates_()) {
- const volume = Math.round(newRouteStatus.volume * 100);
- this.$['route-volume-slider'].value = volume;
- this.displayedVolume_ = volume / 100;
- }
- if (!this.initialLoadTime_) {
- this.initialLoadTime_ = Date.now();
- media_router.browserApi.reportWebUIRouteControllerLoaded(
- this.initialLoadTime_ - this.routeDetailsOpenTime);
- }
- this.stopIncrementingCurrentTime_();
- if (this.canIncrementCurrentTime_()) {
- this.timeIncrementsTimeoutId_ =
- setTimeout(() => this.maybeIncrementCurrentTime_(), 1000);
- }
- this.hangoutsLocalPresent_ = !!newRouteStatus.hangoutsExtraData &&
- newRouteStatus.hangoutsExtraData.localPresent;
- if (newRouteStatus.mirroringExtraData) {
- // Manually update the selected value on the
- // mirroring-fullscreen-video-dropdown dropbox.
- // TODO(imcheng): Avoid doing this by wrapping the dropbox in a Polymer
- // template, or introduce <paper-dropdown-menu> to the Polymer library.
- this.$['mirroring-fullscreen-video-dropdown'].value =
- newRouteStatus.mirroringExtraData.mediaRemotingEnabled ?
- this.FullscreenVideoOption_.REMOTE_SCREEN :
- this.FullscreenVideoOption_.BOTH_SCREENS;
- }
- this.shouldShowRouteStatusTitle_ = !!newRouteStatus.title &&
- newRouteStatus.title != '' &&
- newRouteStatus.title != this.routeDescription_;
- },
-
- /**
- * Called when the route is updated. Updates the description shown if it has
- * not been provided by status updates.
- * @param {?media_router.Route} route
- * @private
- */
- onRouteUpdated_: function(route) {
- if (!route) {
- this.stopIncrementingCurrentTime_();
- }
- if (route) {
- this.routeDescription_ = route.description;
- }
- },
-
- /** @private */
- updateTime_: function() {
- this.stopIncrementingCurrentTime_();
- this.displayedCurrentTime_ = this.$['route-time-slider'].value;
- if (!this.isSeeking_) {
- media_router.browserApi.seekCurrentMedia(this.displayedCurrentTime_);
- this.lastSeekByUser_ = Date.now();
- }
- },
-
- /**
- * @param {!CustomEvent<{value: boolean}>} e
- * @private
- */
- onSeekingChanged_: function(e) {
- this.isSeeking_ = e.detail.value;
- this.updateTime_();
- },
-
- /** @private */
- onSeekSliderValueChanged_: function() {
- this.updateTime_();
- },
-
- /** @private */
- updateVolume_: function() {
- this.lastVolumeChangeByUser_ = Date.now();
- const volume = this.$['route-volume-slider'].value / 100;
- if (volume == this.displayedVolume_) {
- return;
- }
- this.displayedVolume_ = volume;
- media_router.browserApi.setCurrentMediaVolume(volume);
- },
-
- /**
- * Called when the user updates volume with the slider.
- * @private
- */
- onVolumeChanged_: function() {
- /** @const */ var currentTime = Date.now();
- // We limit the frequency of volume change requests during dragging to
- // limit the number of Mojo calls to the component extension.
- if (currentTime - this.lastVolumeChangeByUser_ < 300) {
- return;
- }
- this.updateVolume_();
- },
-
- /**
- * @param {!CustomEvent<{value: boolean}>} e
- * @private
- */
- onVolumeDraggingChanged_: function(e) {
- if (!!this.isVolumeChanging_ == !!e.detail.value) {
- return;
- }
- this.isVolumeChanging_ = e.detail.value;
- if (!this.isVolumeChanging_) {
- this.updateVolume_();
- }
- },
-
- /**
- * Called when the value on the mirroring-fullscreen-video-dropdown dropdown
- * menu changes.
- * @param {!Event} e
- * @private
- */
- onFullscreenVideoDropdownChange_: function(e) {
- /** @const */ var dropdownValue =
- this.$['mirroring-fullscreen-video-dropdown'].value;
- media_router.browserApi.setMediaRemotingEnabled(
- dropdownValue == this.FullscreenVideoOption_.REMOTE_SCREEN);
- },
-
- /**
- * Resets the route controls. Called when the route details view is closed.
- */
- reset: function() {
- this.routeStatus = new media_router.RouteStatus();
- media_router.ui.setRouteControls(null);
- },
-
- /**
- * @return {boolean} Whether external current time updates should be reflected
- * on the seek slider.
- * @private
- */
- shouldAcceptCurrentTimeUpdates_: function() {
- // Ignore external updates immediately after internal updates, because it's
- // likely to just be internal updates coming back from the device, and could
- // make the slider knob jump around.
- return !this.isSeeking_ && Date.now() - this.lastSeekByUser_ > 1000;
- },
-
- /**
- * @return {boolean} Whether external volume updates should be reflected on
- * the volume slider.
- * @private
- */
- shouldAcceptVolumeUpdates_: function() {
- // Ignore external updates immediately after internal updates, because it's
- // likely to just be internal updates coming back from the device, and could
- // make the slider knob jump around.
- return !this.isVolumeChanging_ &&
- Date.now() - this.lastVolumeChangeByUser_ > 1000;
- },
-
- /**
- * If it is currently incrementing the current time shown, then stops doing
- * so.
- * @private
- */
- stopIncrementingCurrentTime_: function() {
- if (this.timeIncrementsTimeoutId_) {
- clearTimeout(this.timeIncrementsTimeoutId_);
- this.timeIncrementsTimeoutId_ = 0;
- }
- }
-});
diff --git a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls_interface.js b/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls_interface.js
deleted file mode 100644
index 53e5a481271..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/route_controls/route_controls_interface.js
+++ /dev/null
@@ -1,20 +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.
-
-/**
- * Interface for the Polymer element that shows media controls for a route that
- * is currently cast to a device.
- * @record
- */
-function RouteControlsInterface() {}
-
-/**
- * @type {!media_router.RouteStatus}
- */
-RouteControlsInterface.prototype.routeStatus;
-
-/**
- * Resets the route controls. Called when the route details view is closed.
- */
-RouteControlsInterface.prototype.reset = function() {};
diff --git a/chromium/chrome/browser/resources/media_router/elements/route_details/BUILD.gn b/chromium/chrome/browser/resources/media_router/elements/route_details/BUILD.gn
deleted file mode 100644
index b7559add3ca..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/route_details/BUILD.gn
+++ /dev/null
@@ -1,21 +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("//third_party/closure_compiler/compile_js.gni")
-
-js_type_check("closure_compile") {
- deps = [
- ":route_details",
- ]
-}
-
-js_library("route_details") {
- deps = [
- "../..:media_router_data",
- "../..:media_router_ui_interface",
- "../route_controls:route_controls",
- "//ui/webui/resources/js:i18n_behavior",
- "//ui/webui/resources/js:load_time_data",
- ]
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/route_details/route_details.css b/chromium/chrome/browser/resources/media_router/elements/route_details/route_details.css
deleted file mode 100644
index e48b7c24ad9..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/route_details/route_details.css
+++ /dev/null
@@ -1,26 +0,0 @@
-/* Copyright 2015 The Chromium Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file. */
-
-#route-action-buttons {
- @apply --layout-horizontal;
- @apply --layout-end-justified;
- margin: 0 10px;
- padding: 0;
- white-space: nowrap;
-}
-
-.route-button {
- background-color: white;
- line-height: 12px;
- margin: 12px 0;
- text-align: end;
-}
-
-#route-description {
- font-size: 1.2em;
- line-height: 1.5em;
- margin-top: 16px;
- padding-inline-end: var(--dialog-padding-end);
- padding-inline-start: 44px;
-}
diff --git a/chromium/chrome/browser/resources/media_router/elements/route_details/route_details.html b/chromium/chrome/browser/resources/media_router/elements/route_details/route_details.html
deleted file mode 100644
index fe9ef05807b..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/route_details/route_details.html
+++ /dev/null
@@ -1,34 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="../route_controls/route_controls.html">
-<dom-module id="route-details">
- <link rel="import" type="css" href="../../media_router_common.css">
- <link rel="import" type="css" href="route_details.css">
- <template>
- <div class="ellipsis" id="route-description"
- title="[[routeDescription_]]"
- hidden$="[[shouldShowWebUiControls_(route)]]">
- [[routeDescription_]]
- </div>
- <template is="dom-if" if="[[shouldShowWebUiControls_(route)]]">
- <route-controls id="route-controls"
- route-details-open-time="[[openTime_]]"
- route="[[route]]"></route-controls>
- </template>
- <div id="route-action-buttons" class="layout">
- <paper-button flat class="route-button button"
- id="start-casting-to-route-button"
- hidden$="[[computeCastButtonHidden_(route, changeRouteSourceAvailable_)]]"
- on-tap="startCastingToRoute_">
- <span>[[i18n('startCastingButtonText')]]</span>
- </paper-button>
- <paper-button flat class="route-button button"
- id="close-route-button"
- on-tap="closeRoute_">
- <span>[[i18n('stopCastingButtonText')]]</span>
- </paper-button>
- <div>
- </template>
-<script src="route_details.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/media_router/elements/route_details/route_details.js b/chromium/chrome/browser/resources/media_router/elements/route_details/route_details.js
deleted file mode 100644
index ec58fd88189..00000000000
--- a/chromium/chrome/browser/resources/media_router/elements/route_details/route_details.js
+++ /dev/null
@@ -1,221 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This Polymer element shows information from media that is currently cast
-// to a device.
-Polymer({
- is: 'route-details',
-
- properties: {
- /**
- * Description of the current casting activity, e.g. "Casting YouTube".
- * @private {string|undefined}
- */
- routeDescription_: {
- type: String,
- },
-
- /**
- * Whether the external container will accept change-route-source-click
- * events.
- * @private {boolean}
- */
- changeRouteSourceAvailable_: {
- type: Boolean,
- computed: 'computeChangeRouteSourceAvailable_(route, sink,' +
- 'isAnySinkCurrentlyLaunching, shownCastModeValue)',
- },
-
- /**
- * Whether a sink is currently launching in the container.
- * @type {boolean}
- */
- isAnySinkCurrentlyLaunching: {
- type: Boolean,
- value: false,
- },
-
- /**
- * The timestamp for when the route details view was opened. We initialize
- * the value in a function so that the value is set when the element is
- * loaded, rather than at page load.
- * @private {number}
- */
- openTime_: {
- type: Number,
- value: function() {
- return Date.now();
- },
- },
-
- /**
- * The route to show.
- * @type {?media_router.Route|undefined}
- */
- route: {
- type: Object,
- observer: 'onRouteChange_',
- },
-
- /**
- * The cast mode shown to the user. Initially set to auto mode. (See
- * media_router.CastMode documentation for details on auto mode.)
- * @type {number}
- */
- shownCastModeValue: {
- type: Number,
- value: media_router.AUTO_CAST_MODE.type,
- },
-
- /**
- * Sink associated with |route|.
- * @type {?media_router.Sink}
- */
- sink: {
- type: Object,
- value: null,
- },
- },
-
- behaviors: [
- I18nBehavior,
- ],
-
- /**
- * Fires a close-route event. This is called when the button to close
- * the current route is clicked.
- *
- * @private
- */
- closeRoute_: function() {
- this.fire('close-route', {route: this.route});
- },
-
- /**
- * @param {?media_router.Route|undefined} route
- * @param {boolean} changeRouteSourceAvailable
- * @return {boolean} Whether to show the button that allows casting to the
- * current route or the current route's sink.
- */
- computeCastButtonHidden_: function(route, changeRouteSourceAvailable) {
- if (route === undefined || changeRouteSourceAvailable === undefined) {
- return false;
- }
-
- return !((route && route.canJoin) || changeRouteSourceAvailable);
- },
-
- /**
- * @param {?media_router.Route|undefined} route The current route for the
- * route details view.
- * @param {?media_router.Sink|undefined} sink Sink associated with |route|.
- * @param {boolean} isAnySinkCurrentlyLaunching Whether a sink is launching
- * now.
- * @param {number} shownCastModeValue Currently selected cast mode value or
- * AUTO if no value has been explicitly selected.
- * @return {boolean} Whether the change route source function should be
- * available when displaying |currentRoute| in the route details view.
- * Changing the route source should not be available when the currently
- * selected source that would be cast is the same as the route's current
- * source.
- * @private
- */
- computeChangeRouteSourceAvailable_: function(
- route, sink, isAnySinkCurrentlyLaunching, shownCastModeValue) {
- if (isAnySinkCurrentlyLaunching || !route || !sink) {
- return false;
- }
- if (!route.currentCastMode) {
- return true;
- }
- var selectedCastMode =
- this.computeSelectedCastMode_(shownCastModeValue, sink);
- return (selectedCastMode != 0) &&
- (selectedCastMode != route.currentCastMode);
- },
-
- /**
- * @param {number} castMode User selected cast mode or AUTO.
- * @param {?media_router.Sink} sink Sink to which we will cast.
- * @return {number} The selected cast mode when |castMode| is selected in the
- * dialog and casting to |sink|. Returning 0 means there is no cast mode
- * available to |sink| and therefore the start-casting-to-route button
- * will not be shown.
- */
- computeSelectedCastMode_: function(castMode, sink) {
- // |sink| can be null when there is a local route, which is shown in the
- // dialog, but the sink to which it is connected isn't in the current set of
- // sinks known to the dialog. This can happen, for example, with DIAL
- // devices. A route is created to a DIAL device, but opening the dialog on
- // a tab that only supports mirroring will not show the DIAL device. The
- // route will be shown in route details if it is the only local route, so
- // you arrive at this function with a null |sink|.
- if (!sink) {
- return 0;
- }
- if (castMode == media_router.CastModeType.AUTO) {
- return sink.castModes & -sink.castModes;
- }
- return castMode & sink.castModes;
- },
-
- /**
- * Called when the route details view is closed. Resets route-controls.
- */
- onClosed: function() {
- if (this.$$('route-controls')) {
- this.$$('route-controls').reset();
- }
- },
-
- /**
- * Called when the route details view is opened.
- */
- onOpened: function() {
- if (this.$$('route-controls')) {
- media_router.ui.setRouteControls(
- /** @type {RouteControlsInterface} */ (this.$$('route-controls')));
- }
- },
-
- /**
- * Updates |routeDescription_| for the default view.
- * @param {?media_router.Route} route
- * @private
- */
- onRouteChange_: function(route) {
- this.routeDescription_ = route ? route.description : '';
- },
-
- /**
- * @param {?media_router.Route} route
- * @return {boolean} Whether the WebUI route controller should be shown
- * instead of the default route description element.
- * @private
- */
- shouldShowWebUiControls_: function(route) {
- return !!route && !!route.supportsWebUiController;
- },
-
- /**
- * Fires a join-route-click event if the current route is joinable, otherwise
- * it fires a change-route-source-click event, which changes the source of the
- * current route. This may cause the current route to be closed and a new
- * route to be started. This is called when the button to start casting to the
- * current route is clicked.
- *
- * @private
- */
- startCastingToRoute_: function() {
- if (this.route.canJoin) {
- this.fire('join-route-click', {route: this.route});
- } else {
- this.fire('change-route-source-click', {
- route: this.route,
- selectedCastMode:
- this.computeSelectedCastMode_(this.shownCastModeValue, this.sink)
- });
- }
- },
-});
diff --git a/chromium/chrome/browser/resources/media_router/externs.js b/chromium/chrome/browser/resources/media_router/externs.js
deleted file mode 100644
index 9e7ccd838cb..00000000000
--- a/chromium/chrome/browser/resources/media_router/externs.js
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-/** @interface */
-var InputDeviceCapabilities;
-
-/** @type {?InputDeviceCapabilities} */
-Event.prototype.sourceCapabilities;
-
-/**
- * @interface
- */
-var AnimationEffect = function() {};
-
-/**
- * @param {Element} target
- * @param {!Array<!Object>} frames
- * @param {(number|Object)=} timing
- * @constructor
- * @implements {AnimationEffect}
- */
-var KeyframeEffect = function(target, frames, timing) {};
-
-/**
- * @param {!Array<!AnimationEffect>} group
- * @constructor
- * @implements {AnimationEffect}
- */
-var GroupEffect = function(group) {};
-
-/**
- * @interface
- */
-var Animation = function() {};
-
-/**
- * @return {undefined}
- */
-Animation.prototype.cancel = function() {};
-
-/**
- * @type {!Promise}
- */
-Animation.prototype.finished;
-
-document.timeline = {};
-
-/**
- * @param {!AnimationEffect} effect
- * @return {!Animation}
- */
-document.timeline.play = function(effect) {};
-
-/**
- * @param {!number} index
- * @return {undefined}
- */
-Element.prototype.selectIndex = function(index) {};
diff --git a/chromium/chrome/browser/resources/media_router/icons/media_router_icons.html b/chromium/chrome/browser/resources/media_router/icons/media_router_icons.html
deleted file mode 100644
index 7d98ad6d2fa..00000000000
--- a/chromium/chrome/browser/resources/media_router/icons/media_router_icons.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<!-- The following icons are duplicated to avoid pulling in unused icons,
- e.g. the entire cr_elements/icons.html file. -->
-<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/iron-iconset-svg/iron-iconset-svg.html">
-<iron-iconset-svg name="media-router" size="24">
-<svg><defs>
- <!-- third_party/polymer/v1_0/components-chromium/iron-icons/iron-icons.html -->
- <g id="folder"><path d="M0 0h24v24H0z" fill="none"></path><path d="M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z"></path></g>
- <g id="search"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path></g>
- <g id="tab"><path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h10v4h8v10z"></path></g>
-
- <!-- third_party/polymer/v1_0/components-chromium/iron-icons/av-icons.html -->
- <g id="web"><path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 14H4v-4h11v4zm0-5H4V9h11v4zm5 5h-4V9h4v9z"></path></g>
-
- <!-- third_party/polymer/v1_0/components-chromium/iron-icons/hardware-icons.html -->
- <g id="laptop"><path d="M20 18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z"></path></g>
- <g id="speaker"><path d="M17 2H7c-1.1 0-2 .9-2 2v16c0 1.1.9 1.99 2 1.99L17 22c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5 2c1.1 0 2 .9 2 2s-.9 2-2 2c-1.11 0-2-.9-2-2s.89-2 2-2zm0 16c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"></path></g>
- <g id="speaker-group"><path d="M18.2 1H9.8C8.81 1 8 1.81 8 2.8v14.4c0 .99.81 1.79 1.8 1.79l8.4.01c.99 0 1.8-.81 1.8-1.8V2.8c0-.99-.81-1.8-1.8-1.8zM14 3c1.1 0 2 .89 2 2s-.9 2-2 2-2-.89-2-2 .9-2 2-2zm0 13.5c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"></path><circle cx="14" cy="12.5" r="2.5"></circle><path d="M6 5H4v16c0 1.1.89 2 2 2h10v-2H6V5z"></path></g>
- <g id="tv"><path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12z"></path></g>
-
- <!-- Icons below are swapped out in branded builds. -->
- <!-- copy of third_party/polymer/v1_0/components-chromium/iron-icons/hardware-icons.html hardware:tv icon -->
- <g id="chromecast"><path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12z"></path></g>
- <g id="education"><path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12z"></path></g>
- <!-- copy of third_party/polymer/v1_0/components-chromium/iron-icons/hardware-icons.html communication:message icon -->
- <g id="hangout"><path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"></path></g>
- <g id="meeting"><path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"></path></g>
-</defs></svg>
-</iron-iconset-svg>
diff --git a/chromium/chrome/browser/resources/media_router/media_router.css b/chromium/chrome/browser/resources/media_router/media_router.css
deleted file mode 100644
index 6b6092e2769..00000000000
--- a/chromium/chrome/browser/resources/media_router/media_router.css
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Copyright 2015 The Chromium Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file. */
-
-html {
- /* Remove 300ms delay for 'click' event, when using touch interface. */
- touch-action: manipulation;
-}
-
-body {
- font-size: 0.75em;
- margin: 0;
-}
-
-#media-router-container {
- background-color: white;
- box-shadow: 0 3px 4px 0 rgba(0, 0, 0, 0.14),
- 0 1px 8px 0 rgba(0, 0, 0, 0.12),
- 0 3px 3px -2px rgba(0, 0, 0, 0.4);
- display: flex;
- flex-direction: column;
- margin-bottom: 1px;
- width: calc(var(--dialog-width) - 1px);
-}
diff --git a/chromium/chrome/browser/resources/media_router/media_router.html b/chromium/chrome/browser/resources/media_router/media_router.html
deleted file mode 100644
index f40477a696c..00000000000
--- a/chromium/chrome/browser/resources/media_router/media_router.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<!DOCTYPE HTML>
-<html dir="$i18n{textdirection}" lang="$i18n{language}">
-<head>
- <meta charset="utf-8">
- <title>$i18n{mediaRouterTitle}</title>
-
- <link rel="stylesheet" href="chrome://resources/css/roboto.css">
- <link rel="stylesheet" href="media_router_common.css">
- <link rel="stylesheet" href="media_router.css">
- <link rel="import" href="chrome://resources/html/cr.html">
- <link rel="import" href="chrome://resources/html/load_time_data.html">
- <link rel="import" href="chrome://resources/html/util.html">
- <script src="chrome://media-router/strings.js"></script>
- <script src="chrome://media-router/media_router.js"></script>
- <link rel="import" href="chrome://media-router/elements/media_router_container/media_router_container.html">
-</head>
-<body>
- <media-router-container id="media-router-container"></media-router-container>
-</body>
-</html>
diff --git a/chromium/chrome/browser/resources/media_router/media_router.js b/chromium/chrome/browser/resources/media_router/media_router.js
deleted file mode 100644
index 79a31235675..00000000000
--- a/chromium/chrome/browser/resources/media_router/media_router.js
+++ /dev/null
@@ -1,397 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// <include src="media_router_browser_api.js">
-// <include src="media_router_data.js">
-// <include src="media_router_ui_interface.js">
-
-// Handles user events for the Media Router UI.
-cr.define('media_router', function() {
- 'use strict';
-
- /**
- * The media-router-container element. Initialized after polymer is ready.
- * @type {?MediaRouterContainerInterface}
- */
- var container = null;
-
- /**
- * Initializes the Media Router WebUI and requests initial media
- * router content, such as the media sink and media route lists.
- */
- function initialize() {
- // For non-Mac platforms, request data immediately after initialization.
- if (!cr.isMac) {
- onRequestInitialData();
- }
-
- container = /** @type {!MediaRouterContainerInterface} */
- ($('media-router-container'));
-
- media_router.ui.setElements(container, container.header);
-
- container.addEventListener(
- 'acknowledge-first-run-flow', onAcknowledgeFirstRunFlow);
- container.addEventListener('back-click', onNavigateToSinkList);
- container.addEventListener('cast-mode-selected', onCastModeSelected);
- container.addEventListener(
- 'change-route-source-click', onChangeRouteSourceClick);
- container.addEventListener('close-dialog', onCloseDialog);
- container.addEventListener('close-route', onCloseRoute);
- container.addEventListener('create-route', onCreateRoute);
- container.addEventListener('issue-action-click', onIssueActionClick);
- container.addEventListener('join-route-click', onJoinRouteClick);
- container.addEventListener(
- 'navigate-sink-list-to-details', onNavigateToDetails);
- container.addEventListener(
- 'navigate-to-cast-mode-list', onNavigateToCastMode);
- container.addEventListener(
- 'select-local-media-file', onSelectLocalMediaFile);
- container.addEventListener('report-filter', onFilter);
- container.addEventListener('report-initial-action', onInitialAction);
- container.addEventListener(
- 'report-initial-action-close', onInitialActionClose);
- container.addEventListener('report-route-creation', onReportRouteCreation);
- container.addEventListener(
- 'report-sink-click-time', onSinkClickTimeReported);
- container.addEventListener('report-sink-count', onSinkCountReported);
- container.addEventListener(
- 'report-resolved-route', onReportRouteCreationOutcome);
- container.addEventListener('request-initial-data', onRequestInitialData);
- container.addEventListener(
- 'search-sinks-and-create-route', onSearchSinksAndCreateRoute);
- container.addEventListener('show-initial-state', onShowInitialState);
- container.addEventListener('sink-click', onSinkClick);
-
- window.addEventListener('blur', onWindowBlur);
- }
-
- /**
- * Requests that the Media Router searches for a sink with criteria
- * |event.detail.name|.
- * @param {!Event} event
- * Parameters in |event|.detail:
- * id - id of the pseudo sink generating the request.
- * name - sink search criteria.
- * domain - user's current domain.
- * selectedCastMode - type of cast mode selected by the user.
- */
- function onSearchSinksAndCreateRoute(event) {
- /** @type {{id: string, domain: string, name: string,
- * selectedCastMode: number}} */
- var detail = event.detail;
- media_router.browserApi.searchSinksAndCreateRoute(
- detail.id, detail.name, detail.domain, detail.selectedCastMode);
- }
-
- /**
- * Reports the selected cast mode.
- * Called when the user selects a cast mode from the picker.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * castModeType - type of cast mode selected by the user.
- */
- function onCastModeSelected(event) {
- /** @type {{castModeType: number}} */
- var detail = event.detail;
- media_router.browserApi.reportSelectedCastMode(detail.castModeType);
- }
-
- /**
- * Reports the route for which the users wants to replace the source and the
- * cast mode that should be used for the new source.
- *
- * @param {!Event} event The event object.
- * Parameters in |event|.detail:
- * route - route to modify.
- * selectedCastMode - type of cast mode selected by the user.
- */
- function onChangeRouteSourceClick(event) {
- /** @type {{route: !media_router.Route, selectedCastMode: number}} */
- var detail = event.detail;
- media_router.browserApi.changeRouteSource(
- detail.route, detail.selectedCastMode);
- }
-
- /**
- * Sends a request to the browser to select a local file.
- */
- function onSelectLocalMediaFile() {
- media_router.browserApi.selectLocalMediaFile();
- }
-
- /**
- * Updates the preference that the user has seen the first run flow.
- * Called when the user clicks on the acknowledgement button on the first run
- * flow.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * optedIntoCloudServices - whether or not the user opted into cloud
- * services.
- */
- function onAcknowledgeFirstRunFlow(event) {
- /** @type {{optedIntoCloudServices: boolean}} */
- var detail = event.detail;
- media_router.browserApi.acknowledgeFirstRunFlow(
- detail.optedIntoCloudServices);
- }
-
- /**
- * Closes the dialog.
- * Called when the user clicks the close button on the dialog. Reports
- * whether the user closed the dialog via the ESC key.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * pressEscToClose - whether or not the user pressed ESC to close the
- * dialog.
- */
- function onCloseDialog(event) {
- /** @type {{pressEscToClose: boolean}} */
- var detail = event.detail;
- container.maybeReportUserFirstAction(
- media_router.MediaRouterUserAction.CLOSE);
- media_router.browserApi.closeDialog(detail.pressEscToClose);
- }
-
- /**
- * Reports when the user uses the filter input to filter the sink list. This
- * is reported at most once each time the user enters the filter view, and
- * only if text is actually entered in the filter input.
- */
- function onFilter() {
- media_router.browserApi.reportFilter();
- }
-
- /**
- * Reports the first action the user takes after opening the dialog.
- * Called when the user explicitly interacts with the dialog to perform an
- * action.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * action - the first action taken by the user.
- */
- function onInitialAction(event) {
- /** @type {{action: number}} */
- var detail = event.detail;
- media_router.browserApi.reportInitialAction(detail.action);
- }
-
- /**
- * Reports the time it took for the user to close the dialog if that was the
- * first action the user took after opening the dialog.
- * Called when the user closes the dialog without taking any other action.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * timeMs - time in ms for the user to close the dialog.
- */
- function onInitialActionClose(event) {
- /** @type {{timeMs: number}} */
- var detail = event.detail;
- media_router.browserApi.reportTimeToInitialActionClose(detail.timeMs);
- }
-
- /**
- * Acts on an issue and dismisses it from the UI.
- * Called when the user performs an action on an issue.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * id - issue ID.
- * actionType - type of action performed by the user.
- * helpPageId - the numeric help center ID.
- */
- function onIssueActionClick(event) {
- /** @type {{id: number, actionType: number, helpPageId: number}} */
- var detail = event.detail;
- media_router.browserApi.actOnIssue(
- detail.id, detail.actionType, detail.helpPageId);
- container.issue = null;
- }
-
- /**
- * Creates a media route.
- * Called when the user requests to create a media route.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * sinkId - sink ID selected by the user.
- * selectedCastModeValue - cast mode selected by the user.
- */
- function onCreateRoute(event) {
- /** @type {{sinkId: string, selectedCastModeValue: number}} */
- var detail = event.detail;
- media_router.browserApi.requestRoute(
- detail.sinkId, detail.selectedCastModeValue);
- }
-
- /**
- * Stops a route.
- * Called when the user requests to stop a media route.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * route - The route to close.
- */
- function onCloseRoute(event) {
- /** @type {{route: !media_router.Route}} */
- var detail = event.detail;
- media_router.browserApi.closeRoute(detail.route);
- }
-
- /**
- * Starts casting to an existing route.
- * Called when the user requests to start casting to a media route that is
- * joinable.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * route - The route to connect to if possible.
- */
- function onJoinRouteClick(event) {
- /** @type {{route: !media_router.Route}} */
- var detail = event.detail;
- media_router.browserApi.joinRoute(detail.route);
- }
-
- /**
- * Reports the user navigation to the cast mode view.
- * Called when the user clicks the drop arrow to navigate to the cast mode
- * view on the dialog.
- */
- function onNavigateToCastMode() {
- media_router.browserApi.reportNavigateToView(
- media_router.MediaRouterView.CAST_MODE_LIST);
- }
-
- /**
- * Reports the user navigation the route details view.
- * Called when the user clicks on a sink to navigate to the route details
- * view.
- */
- function onNavigateToDetails() {
- media_router.browserApi.reportNavigateToView(
- media_router.MediaRouterView.ROUTE_DETAILS);
- }
-
- /**
- * Reports the user navigation the sink list view.
- * Called when the user clicks on the back button from the route details view
- * to the sink list view.
- */
- function onNavigateToSinkList() {
- media_router.browserApi.reportNavigateToView(
- media_router.MediaRouterView.SINK_LIST);
- }
-
- /**
- * Reports whether or not the route creation was successful.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * success - whether or not the route creation was successful.
- */
- function onReportRouteCreation(event) {
- /** @type {{success: boolean}} */
- var detail = event.detail;
- media_router.browserApi.reportRouteCreation(detail.success);
- }
-
- /**
- * Reports success or the type of failure for route creation response.
- * Called when the route is resolved; either the route creation was a success
- * or if there was no route or the route's corresponding sink is invalid;
- * either the sink does not exist or was not the sink we were looking for.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * outcome - the outcome of a create route response.
- *
- */
- function onReportRouteCreationOutcome(event) {
- /** @type {{outcome: number}} */
- var detail = event.detail;
- media_router.browserApi.reportRouteCreationOutcome(detail.outcome);
- }
-
- /**
- * Requests for initial data to load into the dialog.
- */
- function onRequestInitialData() {
- media_router.browserApi.requestInitialData();
- }
-
- /**
- * Reports the initial state of the dialog after it is opened.
- * Called after initial data is populated.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * currentView - the current dialog's current view.
- */
- function onShowInitialState(event) {
- /** @type {{currentView: string}} */
- var detail = event.detail;
- media_router.browserApi.reportInitialState(detail.currentView);
- }
-
- /**
- * Reports the index of the sink that was clicked.
- * Called when the user selects a sink on the sink list.
- *
- * @param {!Event} event
- * Paramters in |event|.detail:
- * index - the index of the clicked sink.
- */
- function onSinkClick(event) {
- /** @type {{index: number}} */
- var detail = event.detail;
- media_router.browserApi.reportClickedSinkIndex(detail.index);
- }
-
- /**
- * Reports the time it took for the user to select a sink to create a route
- * after the list was popuated and shown.
- *
- * @param {!Event} event
- * Paramters in |event|.detail:
- * timeMs - the time it took for the user to select a sink.
- */
- function onSinkClickTimeReported(event) {
- /** @type {{timeMs: number}} */
- var detail = event.detail;
- media_router.browserApi.reportTimeToClickSink(detail.timeMs);
- }
-
- /**
- * Reports the current sink count.
- * Called 3 seconds after the dialog is initially opened.
- *
- * @param {!Event} event
- * Parameters in |event|.detail:
- * sinkCount - the number of sinks.
- */
- function onSinkCountReported(event) {
- /** @type {{sinkCount: number}} */
- var detail = event.detail;
- media_router.browserApi.reportSinkCount(detail.sinkCount);
- }
-
- /**
- * Reports when the user clicks outside the dialog.
- */
- function onWindowBlur() {
- media_router.browserApi.reportBlur();
- }
-
- return {
- initialize: initialize,
- };
-});
-
-window.addEventListener('load', media_router.initialize);
diff --git a/chromium/chrome/browser/resources/media_router/media_router_browser_api.js b/chromium/chrome/browser/resources/media_router/media_router_browser_api.js
deleted file mode 100644
index 9b5724b7401..00000000000
--- a/chromium/chrome/browser/resources/media_router/media_router_browser_api.js
+++ /dev/null
@@ -1,359 +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.
-
-// API invoked by this UI to communicate with the browser WebUI message handler.
-cr.define('media_router.browserApi', function() {
- 'use strict';
-
- /**
- * Indicates that the user has acknowledged the first run flow.
- *
- * @param {boolean} optedIntoCloudServices Whether or not the user opted into
- * cloud services.
- */
- function acknowledgeFirstRunFlow(optedIntoCloudServices) {
- chrome.send('acknowledgeFirstRunFlow', [optedIntoCloudServices]);
- }
-
- /**
- * Acts on the given issue.
- *
- * @param {number} issueId
- * @param {number} actionType Type of action that the user clicked.
- * @param {?number} helpPageId The numeric help center ID.
- */
- function actOnIssue(issueId, actionType, helpPageId) {
- chrome.send(
- 'actOnIssue',
- [{issueId: issueId, actionType: actionType, helpPageId: helpPageId}]);
- }
-
- /**
- * Modifies |route| by changing its source to the one identified by
- * |selectedCastMode|.
- *
- * @param {!media_router.Route} route The route being modified.
- * @param {number} selectedCastMode The value of the cast mode the user
- * selected.
- */
- function changeRouteSource(route, selectedCastMode) {
- chrome.send(
- 'requestRoute',
- [{sinkId: route.sinkId, selectedCastMode: selectedCastMode}]);
- }
-
- /**
- * Closes the dialog.
- *
- * @param {boolean} pressEscToClose Whether the user pressed ESC to close the
- * dialog.
- */
- function closeDialog(pressEscToClose) {
- chrome.send('closeDialog', [pressEscToClose]);
- }
-
- /**
- * Closes the given route.
- *
- * @param {!media_router.Route} route
- */
- function closeRoute(route) {
- chrome.send('closeRoute', [{routeId: route.id, isLocal: route.isLocal}]);
- }
-
- /**
- * Joins the given route.
- *
- * @param {!media_router.Route} route
- */
- function joinRoute(route) {
- chrome.send('joinRoute', [{sinkId: route.sinkId, routeId: route.id}]);
- }
-
- /**
- * Indicates that the initial data has been received.
- */
- function onInitialDataReceived() {
- chrome.send('onInitialDataReceived');
- }
-
- /**
- * Reports that the route details view was closed.
- */
- function onMediaControllerClosed() {
- chrome.send('onMediaControllerClosed');
- }
-
- /**
- * Reports that the route details view was opened for |routeId|.
- *
- * @param {string} routeId
- */
- function onMediaControllerAvailable(routeId) {
- chrome.send('onMediaControllerAvailable', [{routeId: routeId}]);
- }
-
- /**
- * Sends a command to pause the route shown in the route details view.
- */
- function pauseCurrentMedia() {
- chrome.send('pauseCurrentMedia');
- }
-
- /**
- * Sends a command to play the route shown in the route details view.
- */
- function playCurrentMedia() {
- chrome.send('playCurrentMedia');
- }
-
- /**
- * Reports when the user clicks outside the dialog.
- */
- function reportBlur() {
- chrome.send('reportBlur');
- }
-
- /**
- * Reports the index of the selected sink.
- *
- * @param {number} sinkIndex
- */
- function reportClickedSinkIndex(sinkIndex) {
- chrome.send('reportClickedSinkIndex', [sinkIndex]);
- }
-
- /**
- * Reports that the user used the filter input.
- */
- function reportFilter() {
- chrome.send('reportFilter');
- }
-
- /**
- * Reports the initial dialog view.
- *
- * @param {string} view
- */
- function reportInitialState(view) {
- chrome.send('reportInitialState', [view]);
- }
-
- /**
- * Reports the initial action the user took.
- *
- * @param {number} action
- */
- function reportInitialAction(action) {
- chrome.send('reportInitialAction', [action]);
- }
-
- /**
- * Reports the navigation to the specified view.
- *
- * @param {string} view
- */
- function reportNavigateToView(view) {
- chrome.send('reportNavigateToView', [view]);
- }
-
- /**
- * Reports whether or not a route was created successfully.
- *
- * @param {boolean} success
- */
- function reportRouteCreation(success) {
- chrome.send('reportRouteCreation', [success]);
- }
-
- /**
- * Reports the outcome of a create route response.
- *
- * @param {number} outcome
- */
- function reportRouteCreationOutcome(outcome) {
- chrome.send('reportRouteCreationOutcome', [outcome]);
- }
-
- /**
- * Reports the cast mode that the user selected.
- *
- * @param {number} castModeType
- */
- function reportSelectedCastMode(castModeType) {
- chrome.send('reportSelectedCastMode', [castModeType]);
- }
-
- /**
- * Reports the current number of sinks.
- *
- * @param {number} sinkCount
- */
- function reportSinkCount(sinkCount) {
- chrome.send('reportSinkCount', [sinkCount]);
- }
-
- /**
- * Reports the time it took for the user to select a sink after the sink list
- * is populated and shown.
- *
- * @param {number} timeMs
- */
- function reportTimeToClickSink(timeMs) {
- chrome.send('reportTimeToClickSink', [timeMs]);
- }
-
- /**
- * Reports the time, in ms, it took for the user to close the dialog without
- * taking any other action.
- *
- * @param {number} timeMs
- */
- function reportTimeToInitialActionClose(timeMs) {
- chrome.send('reportTimeToInitialActionClose', [timeMs]);
- }
-
- /**
- * Reports the time, in ms, it took the WebUI route controller to load media
- * status info.
- *
- * @param {number} timeMs
- */
- function reportWebUIRouteControllerLoaded(timeMs) {
- chrome.send('reportWebUIRouteControllerLoaded', [timeMs]);
- }
-
- /**
- * Requests data to initialize the WebUI with.
- * The data will be returned via media_router.ui.setInitialData.
- */
- function requestInitialData() {
- chrome.send('requestInitialData');
- }
-
- /**
- * Requests that a media route be started with the given sink.
- *
- * @param {string} sinkId The sink ID.
- * @param {number} selectedCastMode The value of the cast mode the user
- * selected.
- */
- function requestRoute(sinkId, selectedCastMode) {
- chrome.send(
- 'requestRoute', [{sinkId: sinkId, selectedCastMode: selectedCastMode}]);
- }
-
- /**
- * Requests that the media router search all providers for a sink matching
- * |searchCriteria| that can be used with the media source associated with the
- * cast mode |selectedCastMode|. If such a sink is found, a route is also
- * created between the sink and the media source.
- *
- * @param {string} sinkId Sink ID of the pseudo sink generating the request.
- * @param {string} searchCriteria Search criteria for the route providers.
- * @param {string} domain User's current hosted domain.
- * @param {number} selectedCastMode The value of the cast mode to be used with
- * the sink.
- */
- function searchSinksAndCreateRoute(
- sinkId, searchCriteria, domain, selectedCastMode) {
- chrome.send('searchSinksAndCreateRoute', [{
- sinkId: sinkId,
- searchCriteria: searchCriteria,
- domain: domain,
- selectedCastMode: selectedCastMode
- }]);
- }
-
- /**
- * Sends a command to seek the route shown in the route details view.
- *
- * @param {number} time The new current time in seconds.
- */
- function seekCurrentMedia(time) {
- chrome.send('seekCurrentMedia', [{time: time}]);
- }
-
- /**
- * Sends a command to open a file dialog and allow the user to choose a local
- * media file.
- */
- function selectLocalMediaFile() {
- chrome.send('selectLocalMediaFile');
- }
-
- /**
- * Sends a command to mute or unmute the route shown in the route details
- * view.
- *
- * @param {boolean} mute Mute the route if true, unmute it if false.
- */
- function setCurrentMediaMute(mute) {
- chrome.send('setCurrentMediaMute', [{mute: mute}]);
- }
-
- /**
- * Sends a command to change the volume of the route shown in the route
- * details view.
- *
- * @param {number} volume The volume between 0 and 1.
- */
- function setCurrentMediaVolume(volume) {
- chrome.send('setCurrentMediaVolume', [{volume: volume}]);
- }
-
- /**
- * Sets the local present mode of the Hangouts associated with the current
- * route.
- * @param {boolean} localPresent
- */
- function setHangoutsLocalPresent(localPresent) {
- chrome.send('hangouts.setLocalPresent', [localPresent]);
- }
-
- /**
- * Sends a command to change the Media Remoting enabled value associated with
- * current route.
- * @param {boolean} enabled
- */
- function setMediaRemotingEnabled(enabled) {
- chrome.send('setMediaRemotingEnabled', [enabled]);
- }
-
- return {
- acknowledgeFirstRunFlow: acknowledgeFirstRunFlow,
- actOnIssue: actOnIssue,
- changeRouteSource: changeRouteSource,
- closeDialog: closeDialog,
- closeRoute: closeRoute,
- joinRoute: joinRoute,
- onInitialDataReceived: onInitialDataReceived,
- onMediaControllerClosed: onMediaControllerClosed,
- onMediaControllerAvailable: onMediaControllerAvailable,
- pauseCurrentMedia: pauseCurrentMedia,
- playCurrentMedia: playCurrentMedia,
- reportBlur: reportBlur,
- reportClickedSinkIndex: reportClickedSinkIndex,
- reportFilter: reportFilter,
- reportInitialAction: reportInitialAction,
- reportInitialState: reportInitialState,
- reportNavigateToView: reportNavigateToView,
- reportRouteCreation: reportRouteCreation,
- reportRouteCreationOutcome: reportRouteCreationOutcome,
- reportSelectedCastMode: reportSelectedCastMode,
- reportSinkCount: reportSinkCount,
- reportTimeToClickSink: reportTimeToClickSink,
- reportTimeToInitialActionClose: reportTimeToInitialActionClose,
- reportWebUIRouteControllerLoaded: reportWebUIRouteControllerLoaded,
- requestInitialData: requestInitialData,
- requestRoute: requestRoute,
- searchSinksAndCreateRoute: searchSinksAndCreateRoute,
- seekCurrentMedia: seekCurrentMedia,
- selectLocalMediaFile: selectLocalMediaFile,
- setCurrentMediaMute: setCurrentMediaMute,
- setCurrentMediaVolume: setCurrentMediaVolume,
- setHangoutsLocalPresent: setHangoutsLocalPresent,
- setMediaRemotingEnabled: setMediaRemotingEnabled
- };
-});
diff --git a/chromium/chrome/browser/resources/media_router/media_router_common.css b/chromium/chrome/browser/resources/media_router/media_router_common.css
deleted file mode 100644
index 7dba9da3369..00000000000
--- a/chromium/chrome/browser/resources/media_router/media_router_common.css
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Copyright 2015 The Chromium Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file. */
-
-:host > * {
- --dialog-padding-end: 26px;
- --dialog-padding-start: 16px;
- --dialog-width: 340px;
- --navigation-icon-button-size: 36px;
- --non-navigation-icon-size: 16px;
- -webkit-font-smoothing: antialiased;
- -webkit-tap-highlight-color: transparent;
- font-family: 'Roboto', 'Noto', sans-serif;
-}
-
-.button {
- color: var(--paper-blue-700);
- cursor: pointer;
- text-align: center;
-}
-
-[hidden] {
- display: none !important;
-}
-
-.ellipsis {
- overflow: hidden;
- padding: 0 1%;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-cr-icon-button {
- --cr-icon-button-color: black;
- margin: 0;
-}
diff --git a/chromium/chrome/browser/resources/media_router/media_router_data.js b/chromium/chrome/browser/resources/media_router/media_router_data.js
deleted file mode 100644
index b9944d2ed43..00000000000
--- a/chromium/chrome/browser/resources/media_router/media_router_data.js
+++ /dev/null
@@ -1,355 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Any strings used here will already be localized. Values such as
-// CastMode.type or IDs will be defined elsewhere and determined later.
-
-cr.exportPath('media_router');
-
-/**
- * This corresponds to the C++ MediaCastMode, with the exception of AUTO.
- * See below for details. Note to support fast bitset operations, the values
- * here are (1 << [corresponding value in MR]).
- * @enum {number}
- */
-media_router.CastModeType = {
- // Note: AUTO mode is only used to configure the sink list container to show
- // all sinks. Individual sinks are configured with a specific cast mode
- // (PRESENTATION, TAB_MIRROR, DESKTOP_MIRROR).
- AUTO: -1,
- PRESENTATION: 0x1,
- TAB_MIRROR: 0x2,
- DESKTOP_MIRROR: 0x4,
- LOCAL_FILE: 0x8,
-};
-
-/**
- * The ESC key maps to KeyboardEvent.key value 'Escape'.
- * @const {string}
- */
-media_router.KEY_ESC = 'Escape';
-
-/**
- * This corresponds to the C++ MediaRouterMetrics
- * MediaRouterRouteCreationOutcome.
- * @enum {number}
- */
-media_router.MediaRouterRouteCreationOutcome = {
- SUCCESS: 0,
- FAILURE_NO_ROUTE: 1,
- FAILURE_INVALID_SINK: 2,
-};
-
-/**
- * This corresponds to the C++ MediaRouterMetrics MediaRouterUserAction.
- * @enum {number}
- */
-media_router.MediaRouterUserAction = {
- CHANGE_MODE: 0,
- START_LOCAL: 1,
- STOP_LOCAL: 2,
- CLOSE: 3,
- STATUS_REMOTE: 4,
- REPLACE_LOCAL_ROUTE: 5,
-};
-
-/**
- * The possible states of the Media Router dialog. Used to determine which
- * components to show.
- * @enum {string}
- */
-media_router.MediaRouterView = {
- CAST_MODE_LIST: 'cast-mode-list',
- FILTER: 'filter',
- ISSUE: 'issue',
- ROUTE_DETAILS: 'route-details',
- SINK_LIST: 'sink-list',
-};
-
-/**
- * The minimum number of sinks to have to enable the search input strictly for
- * filtering (i.e. the Media Router doesn't support search so the search input
- * only filters existing sinks).
- * @const {number}
- */
-media_router.MINIMUM_SINKS_FOR_SEARCH = 20;
-
-/**
- * The states that media can be in.
- * @enum {number}
- */
-media_router.PlayState = {
- PLAYING: 0,
- PAUSED: 1,
- BUFFERING: 2,
-};
-
-/**
- * This corresponds to the C++ MediaSink IconType, and the order must stay in
- * sync.
- * @enum {number}
- */
-media_router.SinkIconType = {
- CAST: 0,
- CAST_AUDIO_GROUP: 1,
- CAST_AUDIO: 2,
- MEETING: 3,
- HANGOUT: 4,
- EDUCATION: 5,
- WIRED_DISPLAY: 6,
- GENERIC: 7,
-};
-
-/**
- * @enum {string}
- */
-media_router.SinkStatus = {
- IDLE: 'idle',
- ACTIVE: 'active',
- REQUEST_PENDING: 'request_pending'
-};
-
-cr.define('media_router', function() {
- 'use strict';
-
- /**
- * @param {number} type The type of cast mode.
- * @param {string} description The description of the cast mode.
- * @param {?string} host The hostname of the site to cast.
- * @param {boolean} isForced True if the mode is forced.
- * @constructor
- * @struct
- */
- var CastMode = function(type, description, host, isForced) {
- /** @type {number} */
- this.type = type;
-
- /** @type {string} */
- this.description = description;
-
- /** @type {?string} */
- this.host = host || null;
-
- /** @type {boolean} */
- this.isForced = isForced;
- };
-
- /**
- * Placeholder object for AUTO cast mode. See comment in CastModeType.
- * @const {!media_router.CastMode}
- */
- var AUTO_CAST_MODE = new CastMode(
- media_router.CastModeType.AUTO, loadTimeData.getString('autoCastMode'),
- null, false);
-
- /**
- * @param {number} id The ID of this issue.
- * @param {string} title The issue title.
- * @param {string} message The issue message.
- * @param {number} defaultActionType The type of default action.
- * @param {number|undefined} secondaryActionType The type of optional action.
- * @param {?string} routeId The route ID to which this issue
- * pertains. If not set, this is a global issue.
- * @param {boolean} isBlocking True if this issue blocks other UI.
- * @param {?number} helpPageId The numeric help center ID.
- * @constructor
- * @struct
- */
- var Issue = function(
- id, title, message, defaultActionType, secondaryActionType, routeId,
- isBlocking, helpPageId) {
- /** @type {number} */
- this.id = id;
-
- /** @type {string} */
- this.title = title;
-
- /** @type {string} */
- this.message = message;
-
- /** @type {number} */
- this.defaultActionType = defaultActionType;
-
- /** @type {number|undefined} */
- this.secondaryActionType = secondaryActionType;
-
- /** @type {?string} */
- this.routeId = routeId;
-
- /** @type {boolean} */
- this.isBlocking = isBlocking;
-
- /** @type {?number} */
- this.helpPageId = helpPageId;
- };
-
- /**
- * @param {string} id The media route ID.
- * @param {string} sinkId The ID of the media sink running this route.
- * @param {string} description The short description of this route.
- * @param {?number} tabId The ID of the tab in which web app is running and
- * accessing the route.
- * @param {boolean} isLocal True if this is a locally created route.
- * @param {boolean} canJoin True if this route can be joined.
- * @param {?string} customControllerPath non-empty if this route has custom
- * controller.
- * @constructor
- * @struct
- */
- var Route = function(
- id, sinkId, description, tabId, isLocal, canJoin, customControllerPath) {
- /** @type {string} */
- this.id = id;
-
- /** @type {string} */
- this.sinkId = sinkId;
-
- /** @type {string} */
- this.description = description;
-
- /** @type {?number} */
- this.tabId = tabId;
-
- /** @type {boolean} */
- this.isLocal = isLocal;
-
- /** @type {boolean} */
- this.canJoin = canJoin;
-
- /** @type {number|undefined} */
- this.currentCastMode = undefined;
-
- /** @type {?string} */
- this.customControllerPath = customControllerPath;
-
- /** @type {boolean} */
- this.supportsWebUiController = false;
- };
-
- /**
- * @param {string} title The title of the route.
- * @param {boolean} canPlayPause Whether the route can be played/paused.
- * @param {boolean} canMute Whether the route can be muted/unmuted.
- * @param {boolean} canSetVolume Whether the route volume can be changed.
- * @param {boolean} canSeek Whether the route's playback position can be
- * changed.
- * @param {boolean} isPaused Whether the route is paused.
- * @param {boolean} isMuted Whether the route is muted.
- * @param {number} volume The route's volume, between 0 and 1.
- * @param {number} duration The route's duration in seconds.
- * @param {number} currentTime The route's current position in seconds.
- * Must not be greater than |duration|.
- * @param {!{mediaRemotingEnabled: boolean}=} mirroringExtraData Only set for
- * mirroring routes.
- * @param {!{localPresent: boolean}=} hangoutsExtraData Only set for Hangouts
- * routes.
- * @constructor
- * @struct
- */
- var RouteStatus = function(
- title = '', canPlayPause = false, canMute = false, canSetVolume = false,
- canSeek = false, playState = media_router.PlayState.PLAYING,
- isPaused = false, isMuted = false, volume = 0, duration = 0,
- currentTime = 0, hangoutsExtraData = undefined,
- mirroringExtraData = undefined) {
-
- /** @type {string} */
- this.title = title;
-
- /** @type {boolean} */
- this.canPlayPause = canPlayPause;
-
- /** @type {boolean} */
- this.canMute = canMute;
-
- /** @type {boolean} */
- this.canSetVolume = canSetVolume;
-
- /** @type {boolean} */
- this.canSeek = canSeek;
-
- /** @type {media_router.PlayState} */
- this.playState = playState;
-
- /** @type {boolean} */
- this.isMuted = isMuted;
-
- /** @type {number} */
- this.volume = volume;
-
- /** @type {number} */
- this.duration = duration;
-
- /** @type {number} */
- this.currentTime = currentTime;
-
- /** @type {!{localPresent: boolean}|undefined} */
- this.hangoutsExtraData = hangoutsExtraData;
-
- /** @type {!{mediaRemotingEnabled: boolean}|undefined} */
- this.mirroringExtraData = mirroringExtraData;
- };
-
- /**
- * @param {string} id The ID of the media sink.
- * @param {string} name The name of the sink.
- * @param {?string} description Optional description of the sink.
- * @param {?string} domain Optional domain of the sink.
- * @param {media_router.SinkIconType} iconType the type of icon for the sink.
- * @param {media_router.SinkStatus} status The readiness state of the sink.
- * @param {number} castModes Bitset of cast modes compatible with the sink.
- * @constructor
- * @struct
- */
- var Sink = function(
- id, name, description, domain, iconType, status, castModes) {
- /** @type {string} */
- this.id = id;
-
- /** @type {string} */
- this.name = name;
-
- /** @type {?string} */
- this.description = description;
-
- /** @type {?string} */
- this.domain = domain;
-
- /** @type {!media_router.SinkIconType} */
- this.iconType = iconType;
-
- /** @type {!media_router.SinkStatus} */
- this.status = status;
-
- /** @type {number} */
- this.castModes = castModes;
-
- /** @type {boolean} */
- this.isPseudoSink = false;
- };
-
- /**
- * @param {number} tabId The current tab ID.
- * @param {string} domain The domain of the current tab.
- * @constructor
- * @struct
- */
- var TabInfo = function(tabId, domain) {
- /** @type {number} */
- this.tabId = tabId;
-
- /** @type {string} */
- this.domain = domain;
- };
-
- return {
- AUTO_CAST_MODE: AUTO_CAST_MODE,
- CastMode: CastMode,
- Issue: Issue,
- Route: Route,
- RouteStatus: RouteStatus,
- Sink: Sink,
- TabInfo: TabInfo,
- };
-});
diff --git a/chromium/chrome/browser/resources/media_router/media_router_ui_interface.js b/chromium/chrome/browser/resources/media_router/media_router_ui_interface.js
deleted file mode 100644
index 1ffbb771af5..00000000000
--- a/chromium/chrome/browser/resources/media_router/media_router_ui_interface.js
+++ /dev/null
@@ -1,234 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// API invoked by the browser MediaRouterWebUIMessageHandler to communicate
-// with this UI.
-cr.define('media_router.ui', function() {
- 'use strict';
-
- // The media-router-container element.
- var container = null;
-
- // The media-router-header element.
- var header = null;
-
- // The route-controls element. Is null if the route details view isn't open.
- var routeControls = null;
-
- // The initial height for |container|.
- var initialMaxHeight = 0;
-
- /**
- * Handles response of previous create route attempt.
- *
- * @param {string} sinkId The ID of the sink to which the Media Route was
- * creating a route.
- * @param {?media_router.Route} route The newly created route that
- * corresponds to the sink if route creation succeeded; null otherwise.
- * @param {boolean} isForDisplay Whether or not |route| is for display.
- */
- function onCreateRouteResponseReceived(sinkId, route, isForDisplay) {
- container.onCreateRouteResponseReceived(sinkId, route, isForDisplay);
- }
-
- /**
- * Called when the route controller for the route that is currently selected
- * is invalidated.
- */
- function onRouteControllerInvalidated() {
- container.onRouteControllerInvalidated();
- }
-
- /**
- * Handles the search response by forwarding |sinkId| to the container.
- *
- * @param {string} sinkId The ID of the sink found by search.
- */
- function receiveSearchResult(sinkId) {
- container.onReceiveSearchResult(sinkId);
- }
-
- /**
- * Sets the cast mode list.
- *
- * @param {!Array<!media_router.CastMode>} castModeList
- */
- function setCastModeList(castModeList) {
- container.castModeList = castModeList;
- }
-
- /**
- * Sets |container| and |header|.
- *
- * @param {!MediaRouterContainerInterface} mediaRouterContainer
- * @param {!MediaRouterHeaderElement} mediaRouterHeader
- */
- function setElements(mediaRouterContainer, mediaRouterHeader) {
- container = mediaRouterContainer;
- header = mediaRouterHeader;
-
- if (initialMaxHeight) {
- container.updateMaxDialogHeight(initialMaxHeight);
- initialMaxHeight = 0;
- }
- }
-
- /**
- * Populates the WebUI with data obtained about the first run flow.
- *
- * @param {{firstRunFlowCloudPrefLearnMoreUrl: string,
- * firstRunFlowLearnMoreUrl: string,
- * wasFirstRunFlowAcknowledged: boolean,
- * showFirstRunFlowCloudPref: boolean}} data
- * Parameters in data:
- * firstRunFlowCloudPrefLearnMoreUrl - url to open when the cloud services
- * pref learn more link is clicked.
- * firstRunFlowLearnMoreUrl - url to open when the first run flow learn
- * more link is clicked.
- * wasFirstRunFlowAcknowledged - true if first run flow was previously
- * acknowledged by user.
- * showFirstRunFlowCloudPref - true if the cloud pref option should be
- * shown.
- */
- function setFirstRunFlowData(data) {
- container.firstRunFlowCloudPrefLearnMoreUrl =
- data['firstRunFlowCloudPrefLearnMoreUrl'];
- container.firstRunFlowLearnMoreUrl = data['firstRunFlowLearnMoreUrl'];
- container.showFirstRunFlowCloudPref = data['showFirstRunFlowCloudPref'];
- // Some users acknowledged the first run flow before the cloud prefs
- // setting was implemented. These users will see the first run flow
- // again.
- container.showFirstRunFlow = !data['wasFirstRunFlowAcknowledged'] ||
- container.showFirstRunFlowCloudPref;
- }
-
- /**
- * Populates the WebUI with data obtained from Media Router.
- *
- * @param {{deviceMissingUrl: string,
- * sinksAndIdentity: {
- * sinks: !Array<!media_router.Sink>,
- * showEmail: boolean,
- * userEmail: string,
- * showDomain: boolean
- * },
- * routes: !Array<!media_router.Route>,
- * castModes: !Array<!media_router.CastMode>,
- * useTabMirroring: boolean}} data
- * Parameters in data:
- * deviceMissingUrl - url to be opened on "Device missing?" clicked.
- * sinksAndIdentity - list of sinks to be displayed and user identity.
- * useWebUiRouteControls - whether new WebUI route controls should be used.
- * routes - list of routes that are associated with the sinks.
- * castModes - list of available cast modes.
- * useTabMirroring - whether the cast mode should be set to TAB_MIRROR.
- */
- function setInitialData(data) {
- container.deviceMissingUrl = data['deviceMissingUrl'];
- container.castModeList = data['castModes'];
- this.setSinkListAndIdentity(data['sinksAndIdentity']);
- container.routeList = data['routes'];
- container.maybeShowRouteDetailsOnOpen();
- if (data['useTabMirroring']) {
- container.selectCastMode(media_router.CastModeType.TAB_MIRROR);
- }
- media_router.browserApi.onInitialDataReceived();
- }
-
- /**
- * Sets current issue to |issue|, or clears the current issue if |issue| is
- * null.
- *
- * @param {?media_router.Issue} issue
- */
- function setIssue(issue) {
- container.issue = issue;
- }
-
- /**
- * Sets |routeControls|. The argument may be null if the route details view is
- * getting closed.
- *
- * @param {?RouteControlsInterface} mediaRouterRouteControls
- */
- function setRouteControls(mediaRouterRouteControls) {
- routeControls = mediaRouterRouteControls;
- }
-
- /**
- * Sets the list of currently active routes.
- *
- * @param {!Array<!media_router.Route>} routeList
- */
- function setRouteList(routeList) {
- container.routeList = routeList;
- }
-
- /**
- * Sets the list of discovered sinks along with properties of whether to hide
- * identity of the user email and domain.
- *
- * @param {{sinks: !Array<!media_router.Sink>,
- * showEmail: boolean,
- * userEmail: string,
- * showDomain: boolean}} data
- * Parameters in data:
- * sinks - list of sinks to be displayed.
- * showEmail - true if the user email should be shown.
- * userEmail - email of the user if the user is signed in.
- * showDomain - true if the user domain should be shown.
- */
- function setSinkListAndIdentity(data) {
- container.showDomain = data['showDomain'];
- container.allSinks = data['sinks'];
- header.userEmail = data['userEmail'];
- header.showEmail = data['showEmail'];
- }
-
- /**
- * Updates the max height of the dialog
- *
- * @param {number} height
- */
- function updateMaxHeight(height) {
- if (container) {
- container.updateMaxDialogHeight(height);
- } else {
- // Update the max height once |container| gets set.
- initialMaxHeight = height;
- }
- }
-
- /**
- * Updates the route status shown in the route controls.
- *
- * @param {!media_router.RouteStatus} status
- */
- function updateRouteStatus(status) {
- if (routeControls) {
- routeControls.routeStatus = status;
- }
- }
-
- function userSelectedLocalMediaFile(fileName) {
- container.onFileDialogSuccess(fileName);
- }
-
- return {
- onCreateRouteResponseReceived: onCreateRouteResponseReceived,
- onRouteControllerInvalidated: onRouteControllerInvalidated,
- receiveSearchResult: receiveSearchResult,
- setCastModeList: setCastModeList,
- setElements: setElements,
- setFirstRunFlowData: setFirstRunFlowData,
- setInitialData: setInitialData,
- setIssue: setIssue,
- setRouteControls: setRouteControls,
- setRouteList: setRouteList,
- setSinkListAndIdentity: setSinkListAndIdentity,
- updateMaxHeight: updateMaxHeight,
- updateRouteStatus: updateRouteStatus,
- userSelectedLocalMediaFile: userSelectedLocalMediaFile,
- };
-});
diff --git a/chromium/chrome/browser/resources/notifications_internals/BUILD.gn b/chromium/chrome/browser/resources/notifications_internals/BUILD.gn
new file mode 100644
index 00000000000..bd68968e98d
--- /dev/null
+++ b/chromium/chrome/browser/resources/notifications_internals/BUILD.gn
@@ -0,0 +1,27 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/closure_compiler/compile_js.gni")
+
+js_type_check("closure_compile") {
+ deps = [
+ ":notifications_internals",
+ ":notifications_internals_browser_proxy",
+ ]
+}
+
+js_library("notifications_internals") {
+ deps = [
+ ":notifications_internals_browser_proxy",
+ "//ui/webui/resources/js:assert",
+ "//ui/webui/resources/js:cr",
+ "//ui/webui/resources/js:util",
+ ]
+}
+
+js_library("notifications_internals_browser_proxy") {
+ deps = [
+ "//ui/webui/resources/js:cr",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome.css b/chromium/chrome/browser/resources/notifications_internals/notifications_internals.css
index 6eb7d706567..aa7e8f93e4b 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome.css
+++ b/chromium/chrome/browser/resources/notifications_internals/notifications_internals.css
@@ -1,7 +1,9 @@
-/* Copyright 2018 The Chromium Authors. All rights reserved.
+/* Copyright 2019 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
-body {
+h1 {
+ color: rgb(74, 142, 230);
margin: 0;
-}
+ padding: 0;
+} \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/notifications_internals/notifications_internals.html b/chromium/chrome/browser/resources/notifications_internals/notifications_internals.html
new file mode 100644
index 00000000000..ef676a97e5e
--- /dev/null
+++ b/chromium/chrome/browser/resources/notifications_internals/notifications_internals.html
@@ -0,0 +1,42 @@
+<!doctype html>
+<html lang="en" dir="ltr">
+ <head>
+ <meta charset="utf-8">
+ <title>Notifications Internals</title>
+ <meta name="viewport" content="width=device-width">
+ <link rel="stylesheet" href="chrome://resources/css/list.css">
+ <link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
+ <link rel="stylesheet" href="notifications_internals.css">
+ </head>
+ <body>
+ <h1>Notifications Internals</h1>
+ <h4>Notification Scheduler</h4>
+ <table id="notification-scheduler-request">
+ <tr>
+ <td>Url:</td>
+ <td>
+ <input id="notification-scheduler-url" type="url"
+ placeholder="http://www.example.com">
+ </td>
+ </tr>
+ <tr>
+ <td>Title:</td><td><input id="notification-scheduler-title"
+ type="text" placeholder="Notification title">
+ </td>
+ </tr>
+ <tr>
+ <td>Message:</td><td><input id="notification-scheduler-message"
+ type="text" placeholder="Notification message">
+ </td>
+ </tr>
+ </table>
+ <div>
+ <button id="schedule-notification">Schedule</button>
+ </div>
+ <script src="chrome://resources/js/cr.js"></script>
+ <script src="chrome://resources/js/promise_resolver.js"></script>
+ <script src="chrome://resources/js/util.js"></script>
+ <script src="notifications_internals_browser_proxy.js"></script>
+ <script src="notifications_internals.js"></script>
+ </body>
+</html>
diff --git a/chromium/chrome/browser/resources/notifications_internals/notifications_internals.js b/chromium/chrome/browser/resources/notifications_internals/notifications_internals.js
new file mode 100644
index 00000000000..1fc271771f6
--- /dev/null
+++ b/chromium/chrome/browser/resources/notifications_internals/notifications_internals.js
@@ -0,0 +1,28 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+cr.define('notificationsInternals', function() {
+ 'use strict';
+
+ const browserProxy =
+ notificationsInternals.NotificationsInternalsBrowserProxyImpl
+ .getInstance();
+
+ function initialize() {
+ // Register all event listeners.
+ $('schedule-notification').onclick = function() {
+ browserProxy.scheduleNotification(
+ $('notification-scheduler-url').value,
+ $('notification-scheduler-title').value,
+ $('notification-scheduler-message').value);
+ };
+ }
+
+ return {
+ initialize: initialize,
+ };
+});
+
+document.addEventListener(
+ 'DOMContentLoaded', notificationsInternals.initialize);
diff --git a/chromium/chrome/browser/resources/notifications_internals/notifications_internals_browser_proxy.js b/chromium/chrome/browser/resources/notifications_internals/notifications_internals_browser_proxy.js
new file mode 100644
index 00000000000..0c30a8e30d3
--- /dev/null
+++ b/chromium/chrome/browser/resources/notifications_internals/notifications_internals_browser_proxy.js
@@ -0,0 +1,34 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+cr.define('notificationsInternals', function() {
+ /** @interface */
+ class NotificationsInternalsBrowserProxy {
+ /**
+ * Schedules a notification through notification schedule service.
+ * @param {string} url URL to open after clicking the notification.
+ * @param {string} title Title of the notification.
+ * @param {string} message Message of the notification.
+ */
+ scheduleNotification(url, title, message) {}
+ }
+
+ /**
+ * @implements {notificationsInternals.NotificationsInternalsBrowserProxy}
+ */
+ class NotificationsInternalsBrowserProxyImpl {
+ /** @override */
+ scheduleNotification(url, title, message) {
+ return cr.sendWithPromise('scheduleNotification', url, title, message);
+ }
+ }
+
+ cr.addSingletonGetter(NotificationsInternalsBrowserProxyImpl);
+
+ return {
+ NotificationsInternalsBrowserProxy: NotificationsInternalsBrowserProxy,
+ NotificationsInternalsBrowserProxyImpl:
+ NotificationsInternalsBrowserProxyImpl
+ };
+});
diff --git a/chromium/chrome/browser/resources/ntp4/BUILD.gn b/chromium/chrome/browser/resources/ntp4/BUILD.gn
index a32be737dff..46b421ab6cc 100644
--- a/chromium/chrome/browser/resources/ntp4/BUILD.gn
+++ b/chromium/chrome/browser/resources/ntp4/BUILD.gn
@@ -32,6 +32,7 @@ js_library("apps_page") {
"//ui/webui/resources/js/cr/ui/position_util.js",
"//ui/webui/resources/js/cr/ui/touch_handler.js",
"//ui/webui/resources/js/event_tracker.js",
+ "//ui/webui/resources/js/icon.js",
"//ui/webui/resources/js/load_time_data.js",
"//ui/webui/resources/js/parse_html_subset.js",
"//ui/webui/resources/js/promise_resolver.js",
diff --git a/chromium/chrome/browser/resources/ntp4/apps_page.js b/chromium/chrome/browser/resources/ntp4/apps_page.js
index 5c1415068cd..026b45813c5 100644
--- a/chromium/chrome/browser/resources/ntp4/apps_page.js
+++ b/chromium/chrome/browser/resources/ntp4/apps_page.js
@@ -261,6 +261,10 @@ cr.define('ntp', function() {
/**
* Initialize the app object.
* @param {Object} appData The data object that describes the app.
+ *
+ * TODO(crbug.com/425829): This function makes use of deprecated getter or
+ * setter functions.
+ * @suppress {deprecated}
*/
initialize: function(appData) {
this.appData = appData;
@@ -310,6 +314,10 @@ cr.define('ntp', function() {
// This hack is here so that appContents.contextMenu will be the same as
// this.contextMenu.
const self = this;
+
+ // TODO(crbug.com/425829): Remove above suppression once we no longer use
+ // deprecated function defineGetter.
+ // eslint-disable-next-line no-restricted-properties
this.appContents_.__defineGetter__('contextMenu', function() {
return self.contextMenu;
});
diff --git a/chromium/chrome/browser/resources/ntp4/guest_tab.html b/chromium/chrome/browser/resources/ntp4/guest_tab.html
index 1807bfc1891..a89226c66f4 100644
--- a/chromium/chrome/browser/resources/ntp4/guest_tab.html
+++ b/chromium/chrome/browser/resources/ntp4/guest_tab.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
<meta charset="utf-8">
<title>$i18n{title}</title>
diff --git a/chromium/chrome/browser/resources/ntp4/images/2x/disclosure_triangle_mask.png b/chromium/chrome/browser/resources/ntp4/images/2x/disclosure_triangle_mask.png
deleted file mode 100644
index 72b4f2bfe0c..00000000000
--- a/chromium/chrome/browser/resources/ntp4/images/2x/disclosure_triangle_mask.png
+++ /dev/null
Binary files differ
diff --git a/chromium/chrome/browser/resources/ntp4/images/disclosure_triangle_mask.png b/chromium/chrome/browser/resources/ntp4/images/disclosure_triangle_mask.png
deleted file mode 100644
index 7b70a3e4c5b..00000000000
--- a/chromium/chrome/browser/resources/ntp4/images/disclosure_triangle_mask.png
+++ /dev/null
Binary files differ
diff --git a/chromium/chrome/browser/resources/ntp4/images/trash.png b/chromium/chrome/browser/resources/ntp4/images/trash.png
new file mode 100644
index 00000000000..ef1e62a1b3b
--- /dev/null
+++ b/chromium/chrome/browser/resources/ntp4/images/trash.png
Binary files differ
diff --git a/chromium/chrome/browser/resources/ntp4/incognito_and_guest_tab.css b/chromium/chrome/browser/resources/ntp4/incognito_and_guest_tab.css
index d6d9d7774fc..1e2b3cc2b3c 100644
--- a/chromium/chrome/browser/resources/ntp4/incognito_and_guest_tab.css
+++ b/chromium/chrome/browser/resources/ntp4/incognito_and_guest_tab.css
@@ -9,9 +9,11 @@ body {
font-size: 85%;
}
-[dark] {
- background: rgb(50, 54, 57);
- color: rgb(232, 234, 237); /* --google-grey-200 */
+@media (prefers-color-scheme: dark) {
+ html {
+ background: rgb(50, 54, 57);
+ color: rgb(232, 234, 237); /* --google-grey-200 */
+ }
}
h1 {
@@ -44,8 +46,10 @@ a:hover {
text-decoration: none;
}
-[dark] :-webkit-any(a, .learn-more-button) {
- color: rgb(138, 180, 248); /* --google-blue-refresh-300 */
+@media (prefers-color-scheme: dark) {
+ :-webkit-any(a, .learn-more-button) {
+ color: rgb(138, 180, 248); /* --google-blue-refresh-300 */
+ }
}
.content {
diff --git a/chromium/chrome/browser/resources/ntp4/incognito_tab.css b/chromium/chrome/browser/resources/ntp4/incognito_tab.css
index e4bdbe6257c..c2beff126d3 100644
--- a/chromium/chrome/browser/resources/ntp4/incognito_tab.css
+++ b/chromium/chrome/browser/resources/ntp4/incognito_tab.css
@@ -100,14 +100,14 @@ em {
/* Align the content, icon, and title to to the center. */
.content {
- margin-left: auto;
- margin-right: auto;
+ margin-inline-end: auto;
+ margin-inline-start: auto;
max-width: 600px;
}
.icon {
- margin-left: auto;
- margin-right: auto;
+ margin-inline-end: auto;
+ margin-inline-start: auto;
}
h1 {
@@ -115,24 +115,20 @@ h1 {
}
/* Align the two columns of bulletpoints next to each other. */
-.bulletpoints {
- float: left;
-}
-
-html[dir=rtl] .bulletpoints {
- float: right;
-}
-
-.bulletpoints + .bulletpoints {
- clear: right;
+#bulletpoints-wrapper {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: space-between;
}
-html[dir=rtl] .bulletpoints + .bulletpoints {
- clear: left;
+.bulletpoints {
+ flex-basis: 285px; /* (600px - 30px) / 2. */
+ flex-grow: 1;
+ flex-shrink: 0;
}
-.clearer {
- clear: both;
+.bulletpoints.first {
+ margin-inline-end: 30px;
}
/* On narrow screens, align everything to the left. */
@@ -150,11 +146,6 @@ html[dir=rtl] .bulletpoints + .bulletpoints {
h1 {
text-align: start;
}
-
- .bulletpoints + .bulletpoints,
- html[dir=rtl] .bulletpoints + .bulletpoints {
- clear: both;
- }
}
/** Paddings and margins ---------------------------------------------------- */
@@ -164,31 +155,22 @@ html[dir=rtl] .bulletpoints + .bulletpoints {
padding-inline-start: 16px;
}
-/* Margins of floating elements don't collapse. The margin for bulletpoints
- * will usually be provided by a neighboring element. */
-.bulletpoints {
- margin: 0;
-}
-
-.bulletpoints + .bulletpoints {
- margin-inline-start: 40px;
-}
-
-.bulletpoints + .bulletpoints.too-wide {
- margin-inline-start: 0;
- margin-top: 1.5rem;
-}
-
/* Wide screens. */
@media (min-width: 720px) {
.icon,
h1,
#subtitle,
.learn-more-button {
- margin-bottom: 1.5rem;
margin-top: 1.5rem;
}
+ .icon,
+ h1,
+ #subtitle,
+ .bulletpoints {
+ margin-bottom: 1.5rem;
+ }
+
.content {
margin-top: 40px;
min-width: 240px;
@@ -220,12 +202,13 @@ html[dir=rtl] .bulletpoints + .bulletpoints {
/* Smaller vertical margins on very short screens. */
@media (max-height: 320px) {
h1,
- #subtitle,
- .learn-more-button {
+ #subtitle {
margin-bottom: 16px;
margin-top: 16px;
}
+ .learn-more-button,
+ .bulletpoints,
.icon {
margin-bottom: 16px;
}
@@ -235,22 +218,20 @@ html[dir=rtl] .bulletpoints + .bulletpoints {
/* Narrow screens */
@media (max-width: 720px) {
.content {
- padding: 72px 32px;
min-width: 176px;
+ padding: 72px 32px;
}
.icon,
h1,
- #subtitle,
- .learn-more-button {
+ #subtitle {
margin-bottom: 1.5rem;
margin-top: 1.5rem;
}
- /* The two columns of bulletpoints are moved under each other. */
- .bulletpoints + .bulletpoints {
- margin-inline-start: 0;
- margin-top: 1.5rem;
+ .bulletpoints,
+ .learn-more-button {
+ margin-bottom: 1.5rem;
}
/* Smaller offsets on smaller screens. */
@@ -261,14 +242,14 @@ html[dir=rtl] .bulletpoints + .bulletpoints {
.icon,
h1,
- #subtitle,
- .learn-more-button {
+ #subtitle {
margin-bottom: 1rem;
margin-top: 1rem;
}
- .bulletpoints + .bulletpoints {
- margin-top: 1rem;
+ .bulletpoints,
+ .learn-more-button {
+ margin-bottom: 1rem;
}
}
@@ -293,7 +274,7 @@ html[dir=rtl] .bulletpoints + .bulletpoints {
@media (max-width: 240px) {
.content {
min-width: 192px;
- padding-left: 24px;
- padding-right: 24px;
+ padding-inline-end: 24px;
+ padding-inline-start: 24px;
}
}
diff --git a/chromium/chrome/browser/resources/ntp4/incognito_tab.html b/chromium/chrome/browser/resources/ntp4/incognito_tab.html
index 52dce6e017b..888489f7ccb 100644
--- a/chromium/chrome/browser/resources/ntp4/incognito_tab.html
+++ b/chromium/chrome/browser/resources/ntp4/incognito_tab.html
@@ -26,10 +26,9 @@ document.write('<link id="incognitothemecss" rel="stylesheet" ' +
<a class="learn-more-button"
href="$i18n{learnMoreLink}">$i18n{learnMore}</a>
</p>
- <div>
- <div class="bulletpoints">$i18nRaw{incognitoTabFeatures}</div>
+ <div id="bulletpoints-wrapper">
+ <div class="bulletpoints first">$i18nRaw{incognitoTabFeatures}</div>
<div class="bulletpoints">$i18nRaw{incognitoTabWarning}</div>
- <div class="clearer"></div>
</div>
<a class="learn-more-button" href="$i18n{learnMoreLink}">$i18n{learnMore}</a>
</div>
diff --git a/chromium/chrome/browser/resources/ntp4/incognito_tab.js b/chromium/chrome/browser/resources/ntp4/incognito_tab.js
index b2d5eb74e24..bca80d57e69 100644
--- a/chromium/chrome/browser/resources/ntp4/incognito_tab.js
+++ b/chromium/chrome/browser/resources/ntp4/incognito_tab.js
@@ -2,39 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// Let the width of two lists of bulletpoints in a horizontal alignment
-// determine the maximum content width.
-function recomputeLayoutWidth() {
- const bulletpoints = document.querySelectorAll('.bulletpoints');
- const content = document.querySelector('.content');
-
- // Unless this is the first load of the Incognito NTP in this session and
- // with this font size, we already have the maximum content width determined.
- const fontSize = window.getComputedStyle(document.body).fontSize;
- let maxWidth = localStorage[fontSize] ||
- (bulletpoints[0].offsetWidth + bulletpoints[1].offsetWidth +
- 40 /* margin */ + 2 /* offsetWidths may be rounded down */);
-
- // Save the data for quicker access when the NTP is reloaded. Note that since
- // we're in the Incognito mode, the local storage is ephemeral and the data
- // will be discarded when the session ends.
- localStorage[fontSize] = maxWidth;
-
- // Limit the maximum width to 600px. That might force the two lists
- // of bulletpoints under each other, in which case we must swap the left
- // and right margin.
- const MAX_ALLOWED_WIDTH = 600;
- const tooWide = maxWidth > MAX_ALLOWED_WIDTH;
- bulletpoints[1].classList.toggle('too-wide', tooWide);
- if (tooWide) {
- maxWidth = MAX_ALLOWED_WIDTH;
- }
-
- content.style.maxWidth = maxWidth + 'px';
-}
-
window.addEventListener('load', function() {
- recomputeLayoutWidth();
chrome.send('observeThemeChanges');
});
@@ -53,8 +21,4 @@ const ntp = {
$('incognitothemecss').href =
'chrome://theme/css/incognito_new_tab_theme.css?' + Date.now();
},
-
- defaultFontSizeChanged: function() {
- setTimeout(recomputeLayoutWidth, 100);
- }
};
diff --git a/chromium/chrome/browser/resources/ntp4/new_tab.html b/chromium/chrome/browser/resources/ntp4/new_tab.html
index d47c1c8e2b3..2cc968e011d 100644
--- a/chromium/chrome/browser/resources/ntp4/new_tab.html
+++ b/chromium/chrome/browser/resources/ntp4/new_tab.html
@@ -20,12 +20,12 @@
<link rel="stylesheet" href="../../../../ui/webui/resources/css/bubble.css">
<link rel="stylesheet" href="../../../../ui/webui/resources/css/menu.css">
<link rel="stylesheet" href="../../../../ui/webui/resources/css/menu_button.css">
-<link rel="stylesheet" href="../../../../ui/webui/resources/css/trash.css">
<link rel="stylesheet" href="../../../../ui/webui/resources/css/widgets.css">
<link rel="stylesheet" href="apps_page.css">
<link rel="stylesheet" href="nav_dot.css">
<link rel="stylesheet" href="new_tab.css">
<link rel="stylesheet" href="tile_page.css">
+<link rel="stylesheet" href="trash.css">
<script>
// Until themes can clear the cache, force-reload the theme stylesheet.
document.write('<link id="themecss" rel="stylesheet" ' +
@@ -34,6 +34,7 @@ document.write('<link id="themecss" rel="stylesheet" ' +
<script src="../../../../ui/webui/resources/js/action_link.js"></script>
<script src="../../../../ui/webui/resources/js/event_tracker.js"></script>
<script src="../../../../ui/webui/resources/js/util.js"></script>
+<script src="../../../../ui/webui/resources/js/icon.js"></script>
<script src="../../../../ui/webui/resources/js/cr.js"></script>
<script src="../../../../ui/webui/resources/js/cr/event_target.js"></script>
diff --git a/chromium/chrome/browser/resources/ntp4/new_tab.js b/chromium/chrome/browser/resources/ntp4/new_tab.js
index dff11852eff..0be7cd9f7a7 100644
--- a/chromium/chrome/browser/resources/ntp4/new_tab.js
+++ b/chromium/chrome/browser/resources/ntp4/new_tab.js
@@ -258,7 +258,7 @@ cr.define('ntp', function() {
const headerContainer = $('login-status-header-container');
headerContainer.classList.toggle('login-status-icon', !!iconURL);
headerContainer.style.backgroundImage =
- iconURL ? getUrlForCss(iconURL) : 'none';
+ iconURL ? cr.icon.getUrlForCss(iconURL) : 'none';
}
}
diff --git a/chromium/chrome/browser/resources/ntp4/trash.css b/chromium/chrome/browser/resources/ntp4/trash.css
new file mode 100644
index 00000000000..0945863f894
--- /dev/null
+++ b/chromium/chrome/browser/resources/ntp4/trash.css
@@ -0,0 +1,59 @@
+/* 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. */
+
+.trash {
+ -webkit-appearance: none;
+ background: none;
+ border: none;
+ cursor: pointer;
+ display: inline-block;
+ outline: none;
+ padding: 0;
+ position: relative;
+ width: 30px;
+}
+
+.trash > span {
+ display: inline-block;
+}
+
+.trash > .can,
+.trash > .lid {
+ background: url(./images/trash.png) 0 0 no-repeat;
+ left: 8px;
+ position: absolute;
+ right: 8px;
+ top: 2px;
+}
+
+.trash > .lid {
+ height: 6px;
+ transform-origin: -7% 100%;
+ transition: transform 150ms;
+ width: 14px;
+}
+
+html[dir='rtl'] .trash > .lid {
+ transform-origin: 107% 100%;
+}
+
+.trash:-webkit-any(:focus, :hover, .open) > .lid {
+ transform: rotate(-45deg);
+ transition: transform 250ms;
+}
+
+html[dir='rtl'] .trash:-webkit-any(:focus, :hover, .open) > .lid {
+ transform: rotate(45deg);
+}
+
+.trash > .can {
+ background-position: -1px -4px;
+ height: 12px;
+ /* The margins match the background position offsets. */
+ margin-left: 1px;
+ /* The right margin is one greater due to a shadow on the trash image. */
+ margin-right: 2px;
+ margin-top: 4px;
+ width: 11px;
+}
diff --git a/chromium/chrome/browser/resources/omnibox/BUILD.gn b/chromium/chrome/browser/resources/omnibox/BUILD.gn
index 10b877724d9..0465f914112 100644
--- a/chromium/chrome/browser/resources/omnibox/BUILD.gn
+++ b/chromium/chrome/browser/resources/omnibox/BUILD.gn
@@ -16,6 +16,7 @@ js_library("omnibox") {
":omnibox_input",
":omnibox_output",
"//chrome/browser/ui/webui/omnibox:mojo_bindings_js_library_for_compile",
+ "//ui/webui/resources/js:load_time_data",
]
}
diff --git a/chromium/chrome/browser/resources/omnibox/omnibox.html b/chromium/chrome/browser/resources/omnibox/omnibox.html
index 679a77d7e70..1f9f1f8e96b 100644
--- a/chromium/chrome/browser/resources/omnibox/omnibox.html
+++ b/chromium/chrome/browser/resources/omnibox/omnibox.html
@@ -8,12 +8,14 @@
<link rel="stylesheet" href="omnibox.css">
<script src="chrome://resources/js/cr.js"></script>
<script src="chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js"></script>
+ <script src="chrome://resources/js/load_time_data.js"></script>
<script src="chrome://resources/js/util.js"></script>
<script src="chrome/browser/ui/webui/omnibox/omnibox.mojom-lite.js"></script>
<script src="omnibox_element.js"></script>
<script src="omnibox_input.js"></script>
<script src="omnibox_output.js"></script>
<script src="omnibox.js"></script>
+ <script src="strings.js"></script>
</head>
<body>
@@ -29,74 +31,61 @@
<span class="arrow-padding"></span>
<span class="arrow-up">â–²</span>
</div>
- <div class="row">
- <label class="checkbox-container"
- title="When checked, interacting with the real omnibox of any browser window will update the debug page's output. Incognito window omnibox results will update only debug pages open in incognito windows. Likewise, normal window omnibox results will update only debug pages open in normal windows. When unfocusing the browser omnibox, the autocomplete controller sends a response with no combined results. This response is ignored in order to prevent the previous non-empty response from being hidden and because these results wouldn't normally be displayed by the browser window omnibox.">
+ <label class="row checkbox-container"
+ title="When checked, interacting with the real omnibox of any browser window will update the debug page's output. Incognito window omnibox results will update only debug pages open in incognito windows. Likewise, normal window omnibox results will update only debug pages open in normal windows. When unfocusing the browser omnibox, the autocomplete controller sends a response with no combined results. This response is ignored in order to prevent the previous non-empty response from being hidden and because these results wouldn't normally be displayed by the browser window omnibox.">
<input id="connect-window-omnibox" type="checkbox" accesskey="w">
<span>
Connect <span class="accesskey">w</span>indow omnibox
</span>
</label>
- </div>
<div class="row response-selection-container">
<span>Quer<span class="accesskey">y</span></span>
<input id="response-selection" type="number" accesskey="y" value="0"
min="0" max="0">
<span>of <span id="responses-count">0</span></span>
</div>
- <div id="history-warning" class="row" hidden>
- <span class="warning-text"
- title="The output you are currently viewing is historical and may not reflect the current inputs.">
+ <span id="history-warning" class="row warning-text"
+ title="The output you are currently viewing is historical and may not reflect the current inputs."
+ hidden>
Viewing historical data
</span>
- </div>
</div>
<div class="top-column">
<p class="row section-header">Input parameters</p>
- <div class="row">
- <label class="checkbox-container">
+ <label class="row checkbox-container">
<input id="reset-autocomplete-controller" type="checkbox"
accesskey="r">
<span>
<span class="accesskey">R</span>eset autocomplete controller
</span>
</label>
- </div>
- <div class="row">
- <label class="checkbox-container">
+ <label class="row checkbox-container">
<input id="lock-cursor-position" type="checkbox" accesskey="x">
<span>
Lock cursor position to end of input
[<span class="accesskey">x</span>]
</span>
</label>
- </div>
- <div class="row">
- <label class="checkbox-container">
+ <label class="row checkbox-container">
<input id="zero-suggest" type="checkbox" accesskey="z">
<span>
<span class="accesskey">Z</span>ero suggest
</span>
</label>
- </div>
- <div class="row">
- <label class="checkbox-container">
+ <label class="row checkbox-container">
<input id="prevent-inline-autocomplete" type="checkbox"
accesskey="a">
<span>
Prevent inline <span class="accesskey">a</span>utocomplete
</span>
</label>
- </div>
- <div class="row">
- <label class="checkbox-container">
+ <label class="row checkbox-container">
<input id="prefer-keyword" type="checkbox" accesskey="k">
<span>
In <span class="accesskey">k</span>eyword mode
</span>
</label>
- </div>
</div>
<div class="top-column">
@@ -125,37 +114,41 @@
<div class="top-column">
<p class="row section-header">Display paramters</p>
- <div class="row">
- <label class="checkbox-container">
+ <label class="row checkbox-container">
<input id="show-incomplete-results" type="checkbox" accesskey="i">
<span>
Show <span class="accesskey">i</span>ncomplete results
</span>
</label>
- </div>
- <div class="row">
- <label class="checkbox-container">
+ <label class="row checkbox-container">
<input id="show-details" type="checkbox" accesskey="t">
<span>
Show all de<span class="accesskey">t</span>ails
</span>
</label>
- </div>
- <div class="row">
- <label class="checkbox-container">
+ <label class="row checkbox-container">
<input id="show-all-providers" type="checkbox" accesskey="p">
<span>
Show results per <span class="accesskey">p</span>rovider
</span>
</label>
- </div>
- <div class="row">
- <label class="checkbox-container">
- <input id="elide-cells" type="checkbox" accesskey="s">
- <span>
- Elide Cell<span class="accesskey">s</span>
- </span>
- </label>
+ <div class="column-container">
+ <div class="column">
+ <label class="row checkbox-container">
+ <input id="elide-cells" type="checkbox" accesskey="s">
+ <span>
+ Elide cell<span class="accesskey">s</span>
+ </span>
+ </label>
+ </div>
+ <div class="column">
+ <label class="row checkbox-container">
+ <input id="thin-rows" type="checkbox" accesskey="h">
+ <span>
+ T<span class="accesskey">h</span>in rows
+ </span>
+ </label>
+ </div>
</div>
</div>
@@ -166,8 +159,8 @@
autocomplete="off"
placeholder="Enter filter (e.g. 'google', 'is:star', 'not:del') [Alt+G]"
title="Checks each cell individually; i.e. filter text should not span multiple columns. Supports fuzzyness; each character of filter text must be present in the cell, either adjacent to the previous matched character, or at the start of a new word. Words are defined as being delimited by either capital letters, groups of digits, or non alpha characters. E.g. 'abc' matches 'abc', 'a big cat', 'a-bigCat', 'a very big cat', and 'an amBer cat'; but does not match 'abigcat' or 'an amber cat'. 'green rainbow' is matched by 'gre rain', but not by 'gre bow'. One exception is the first character, which may be matched mid-word. E.g. 'een rain' can also match 'green rainbow'. Boolean properties can be searched for via the property name prefixed by 'is:' or 'not:'. Boolean property names are: 'Can Be Default', 'Starred', 'Has Tab Match', 'Del', 'Prev', and 'Done'.">
- <div class="buttons-container">
- <div class="buttons-column">
+ <div class="column-container">
+ <div class="column">
<span id="export-clipboard" class="row button" accesskey="c"
tabindex="0"
title="Copy responses in JSON format. This is not affected by the visibility of output and will include responses in their entirety as well as query and display inputs.">
@@ -180,7 +173,7 @@
<span>Dow<span class="accesskey">n</span>load</span>
</span>
</div>
- <div class="buttons-column">
+ <div class="column">
<label id="import-clipboard"
class="row icon-button button drag-container" accesskey="v"
tabindex="0"
@@ -206,12 +199,11 @@
</label>
</div>
</div>
- <div id="imported-warning" class="row" hidden>
- <span class="warning-text"
- title="The output you are currently viewing is imported and may not be the same as if you had entered these inputs now.">
+ <span id="imported-warning" class="row warning-text"
+ title="The output you are currently viewing is imported and may not be the same as if you had entered these inputs now."
+ hidden>
Viewing imported data
</span>
- </div>
</div>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/omnibox/omnibox.js b/chromium/chrome/browser/resources/omnibox/omnibox.js
index 190b77c24b0..5c2c818e7ec 100644
--- a/chromium/chrome/browser/resources/omnibox/omnibox.js
+++ b/chromium/chrome/browser/resources/omnibox/omnibox.js
@@ -66,9 +66,10 @@ class BrowserProxy {
this.callbackRouter_.handleAnswerImageData.addListener(
omniboxOutput.updateAnswerImage.bind(omniboxOutput));
- /** @private {!mojom.OmniboxPageHandlerProxy} */
- this.handler_ = mojom.OmniboxPageHandler.getProxy();
- this.handler_.setClientPage(this.callbackRouter_.createProxy());
+ /** @private {!mojom.OmniboxPageHandlerRemote} */
+ this.handler_ = mojom.OmniboxPageHandler.getRemote();
+ this.handler_.setClientPage(
+ this.callbackRouter_.$.bindNewPipeAndPassRemote());
/** @private {Request} */
this.lastRequest;
@@ -212,8 +213,9 @@ class ExportDelegate {
* This is the worker function that transforms query inputs to accumulate
* batch exports, then finally initiates a download for the complete set.
* @param {!Array<!QueryInputs>} batchQueryInputs
+ * @param {string} batchName
*/
- async processBatch(batchQueryInputs) {
+ async processBatch(batchQueryInputs, batchName) {
const batchExports = [];
for (const queryInputs of batchQueryInputs) {
const omniboxResponse = await browserProxy
@@ -232,8 +234,21 @@ class ExportDelegate {
};
batchExports.push(exportData);
}
- const fileName = `omnibox_batch_${ExportDelegate.getTimeStamp()}.json`;
- const batchData = { appVersion: navigator.appVersion, batchExports };
+ const now = new Date();
+ const fileName = `omnibox_batch_${ExportDelegate.getTimeStamp(now)}.json`;
+ // If this data format changes, please roll schemaVersion.
+ const batchData = {
+ schemaKind: 'Omnibox Batch Export',
+ schemaVersion: 2,
+ dateCreated: now.toISOString(),
+ author: '',
+ description: '',
+ authorTool: 'chrome://omnibox',
+ batchName,
+ versionDetails: window.loadTimeData.data_,
+ appVersion: navigator.appVersion,
+ batchExports
+ };
ExportDelegate.download_(batchData, fileName);
}
@@ -243,11 +258,14 @@ class ExportDelegate {
* @param {!BatchSpecifier} processBatchData
*/
processBatchData(processBatchData) {
- if (processBatchData.batchMode && processBatchData.batchQueryInputs) {
- this.processBatch(processBatchData.batchQueryInputs);
+ if (processBatchData.batchMode && processBatchData.batchQueryInputs &&
+ processBatchData.batchName) {
+ this.processBatch(
+ processBatchData.batchQueryInputs, processBatchData.batchName);
} else {
const expected = {
batchMode: "combined",
+ batchName: "name for this batch of queries",
batchQueryInputs: [
{
inputText: "example input text",
@@ -260,7 +278,7 @@ class ExportDelegate {
currentUrl: "",
pageClassification: "4"
}
- ],
+ ],
};
console.error(`Invalid batch specifier data. Expected format: \n${
JSON.stringify(expected, null, 2)}`);
@@ -304,9 +322,15 @@ class ExportDelegate {
a.click();
}
- /** @return {string} A sortable timestamp string for use in filenames. */
- static getTimeStamp() {
- const iso = new Date().toISOString();
+ /**
+ * @param {Date=} date
+ * @return {string} A sortable timestamp string for use in filenames.
+ */
+ static getTimeStamp(date) {
+ if (!date) {
+ date = new Date();
+ }
+ const iso = date.toISOString();
return iso.replace(/:/g, '').split('.')[0];
}
}
diff --git a/chromium/chrome/browser/resources/omnibox/omnibox_input.css b/chromium/chrome/browser/resources/omnibox/omnibox_input.css
index 249e1b90584..29fb73454f4 100644
--- a/chromium/chrome/browser/resources/omnibox/omnibox_input.css
+++ b/chromium/chrome/browser/resources/omnibox/omnibox_input.css
@@ -2,6 +2,10 @@
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
+[hidden] {
+ display: none !important;
+}
+
:host {
--hover-color: #f5f5f5;
--input-alignment-indentation: 9px;
@@ -51,11 +55,11 @@ select {
margin-inline-start: var(--input-alignment-indentation);
}
-.buttons-container {
+.column-container {
display: flex;
}
-.buttons-column {
+.column {
display: flex;
flex-direction: column;
}
diff --git a/chromium/chrome/browser/resources/omnibox/omnibox_input.js b/chromium/chrome/browser/resources/omnibox/omnibox_input.js
index 5ce07fc9552..9d07a1a8003 100644
--- a/chromium/chrome/browser/resources/omnibox/omnibox_input.js
+++ b/chromium/chrome/browser/resources/omnibox/omnibox_input.js
@@ -23,6 +23,7 @@ let QueryInputs;
* showDetails: boolean,
* showAllProviders: boolean,
* elideCells: boolean,
+ * thinRows: boolean,
* }}
*/
let DisplayInputs;
@@ -68,6 +69,7 @@ class OmniboxInput extends OmniboxElement {
'#show-details',
'#show-all-providers',
'#elide-cells',
+ '#thin-rows',
].forEach(query => {
this.$$(query).addEventListener(
'input', this.onDisplayInputsChanged_.bind(this));
@@ -218,6 +220,7 @@ class OmniboxInput extends OmniboxElement {
showDetails: this.$$('#show-details').checked,
showAllProviders: this.$$('#show-all-providers').checked,
elideCells: this.$$('#elide-cells').checked,
+ thinRows: this.$$('#thin-rows').checked,
};
}
@@ -228,6 +231,7 @@ class OmniboxInput extends OmniboxElement {
this.$$('#show-details').checked = displayInputs.showDetails;
this.$$('#show-all-providers').checked = displayInputs.showAllProviders;
this.$$('#elide-cells').checked = displayInputs.elideCells;
+ this.$$('#thin-rows').checked = displayInputs.thinRows;
}
/** @private */
@@ -336,6 +340,7 @@ class OmniboxInput extends OmniboxElement {
showDetails: false,
showAllProviders: true,
elideCells: true,
+ thinRows: false,
};
}
}
diff --git a/chromium/chrome/browser/resources/omnibox/omnibox_output.js b/chromium/chrome/browser/resources/omnibox/omnibox_output.js
index 48c19794b1a..fb578cadce8 100644
--- a/chromium/chrome/browser/resources/omnibox/omnibox_output.js
+++ b/chromium/chrome/browser/resources/omnibox/omnibox_output.js
@@ -14,9 +14,6 @@ cr.define('omnibox_output', function() {
*/
let ResultsDetails;
- /** @typedef {Array<{key: string, value: string}>} */
- let KeyValuePair;
-
/** @param {!Element} element*/
function clearChildren(element) {
while (element.firstChild) {
@@ -50,8 +47,7 @@ cr.define('omnibox_output', function() {
/** @param {!DisplayInputs} displayInputs */
updateDisplayInputs(displayInputs) {
this.displayInputs_ = displayInputs;
- this.updateVisibility_();
- this.updateEliding_();
+ this.updateDisplay_();
}
/** @param {string} filterText */
@@ -112,8 +108,7 @@ cr.define('omnibox_output', function() {
this.resultsGroups_.push(resultsGroup);
this.$$('#contents').appendChild(resultsGroup);
- this.updateVisibility_();
- this.updateEliding_();
+ this.updateDisplay_();
this.updateFilterHighlights_();
}
@@ -126,6 +121,13 @@ cr.define('omnibox_output', function() {
match => match.updateAnswerImage(url, data));
}
+ /** @private */
+ updateDisplay_() {
+ this.updateVisibility_();
+ this.updateEliding_();
+ this.updateRowHeights_();
+ }
+
/**
* Show or hide various output elements depending on display inputs.
* 1) Show non-last result groups only if showIncompleteResults is true.
@@ -158,6 +160,13 @@ cr.define('omnibox_output', function() {
}
/** @private */
+ updateRowHeights_() {
+ this.resultsGroups_.forEach(
+ resultsGroup =>
+ resultsGroup.updateRowHeights(this.displayInputs_.thinRows));
+ }
+
+ /** @private */
updateFilterHighlights_() {
this.autocompleteMatches.forEach(match => match.filter(this.filterText_));
}
@@ -310,6 +319,12 @@ cr.define('omnibox_output', function() {
match => match.updateEliding(elideCells));
}
+ /** @param {boolean} thinRows */
+ updateRowHeights(thinRows) {
+ this.autocompleteMatches.forEach(
+ match => match.classList.toggle('thin', thinRows));
+ }
+
/**
* @private
* @return {boolean}
@@ -806,48 +821,73 @@ cr.define('omnibox_output', function() {
* @return {string|undefined}
*/
static classifyJsonWord(word) {
- if (/^\d+$/.test(word)) {
+ // Statically creating the regexes only once.
+ OutputJsonProperty.classifications =
+ OutputJsonProperty.classifications || [
+ {re: /^"[^]*":$/, clazz: 'key'},
+ {re: /^"[^]*"$/, clazz: 'string'},
+ {re: /true|false/, clazz: 'boolean'},
+ {re: /null/, clazz: 'null'},
+ ];
+ OutputJsonProperty.spaceRegex = OutputJsonProperty.spaceRegex || /^\s*$/;
+
+ // Using isNaN, because Number.isNaN checks explicitly for NaN whereas
+ // isNaN coerces the param to a Number. I.e. isNaN('3') === false, while
+ // Number.isNaN('3') === true.
+ if (isNaN(word)) {
+ const classification =
+ OutputJsonProperty.classifications.find(({re}) => re.test(word));
+ return classification && classification.clazz;
+ } else if (!OutputJsonProperty.spaceRegex.test(word)) {
return 'number';
}
- if (/^"[^]*":$/.test(word)) {
- return 'key';
- }
- if (/^"[^]*"$/.test(word)) {
- return 'string';
- }
- if (/true|false/.test(word)) {
- return 'boolean';
- }
- if (/null/.test(word)) {
- return 'null';
- }
}
}
- class OutputAdditionalInfoProperty extends OutputJsonProperty {
+ class OutputAdditionalInfoProperty extends OutputProperty {
+ constructor() {
+ super();
+ const container = document.createElement('div');
+
+ /** @private {!Element} */
+ this.pre_ = document.createElement('pre');
+ this.pre_.classList.add('json');
+ container.appendChild(this.pre_);
+
+ /** @private {!Element} */
+ this.link_ = document.createElement('a');
+ this.link_.download = 'AdditionalInfo.json';
+
+ container.appendChild(this.link_);
+ this.appendChild(container);
+ }
+
/** @private @override */
render_() {
clearChildren(this.pre_);
- this.tuples_.forEach(({key, value}) => {
+ this.value.forEach(({key, value}) => {
this.pre_.appendChild(
OutputJsonProperty.renderJsonWord(key + ': ', ['key']));
this.pre_.appendChild(
OutputJsonProperty.renderJsonWord(value + '\n', ['number']));
});
+ this.link_.href = this.createDownloadLink_();
}
/** @override @return {string} */
get text() {
- return this.tuples_.reduce(
+ return this.value.reduce(
(prev, {key, value}) => `${prev}${key}: ${value}\n`, '');
}
- /** @private @return {!KeyValuePair} */
- get tuples_() {
- return [
- .../** @type {!KeyValuePair} */ (this.value),
- {key: 'document_type', value: this.values_[1]}
- ];
+ /** @private @return {string} */
+ createDownloadLink_() {
+ const obj = this.value.reduce((obj, {key, value}) => {
+ obj[key] = value;
+ return obj;
+ }, {});
+ const obj64 = btoa(unescape(encodeURIComponent(JSON.stringify(obj))));
+ return `data:application/json;base64,${obj64}`;
}
}
@@ -1079,7 +1119,7 @@ cr.define('omnibox_output', function() {
new Column(
['Additional Info'], '', 'additionalInfo', false,
'Additional Info\nProvider-specific information about the result.',
- ['additionalInfo', 'documentType'], OutputAdditionalInfoProperty)
+ ['additionalInfo'], OutputAdditionalInfoProperty)
];
/** @type {!Column} */
diff --git a/chromium/chrome/browser/resources/omnibox/output_results_group.css b/chromium/chrome/browser/resources/omnibox/output_results_group.css
index cb3059424ea..56f5d510296 100644
--- a/chromium/chrome/browser/resources/omnibox/output_results_group.css
+++ b/chromium/chrome/browser/resources/omnibox/output_results_group.css
@@ -19,7 +19,7 @@ output-results-details {
table {
--header-bg-color: #fafafa;
- --row-hover-color: #fafafa;
+ --row-hover-color: #f5f5f5;
background-color: white;
border: 1px solid var(--border-color);
@@ -35,6 +35,7 @@ table {
}
.body tr {
+ /* sufficient to display 4 lines at 14px with 5px vert padding */
height: 66px;
}
@@ -43,6 +44,15 @@ table {
max-height: 56px;
}
+.body tr.thin {
+ /* sufficient to display 2 lines at 14px with 5px vert padding */
+ height: 38px;
+}
+
+.body tr.thin td > * {
+ max-height: 28px;
+}
+
.body td {
word-break: break-all;
}
@@ -73,7 +83,13 @@ table {
white-space: pre-wrap;
}
-.body tr:hover td {
+.body tr.thin:nth-child(even) {
+ background-color: #fafafa;
+}
+
+.body tr:hover,
+/* must explicitly select .thin tr's to override above .thin styling */
+.body tr.thin:hover {
background-color: var(--row-hover-color);
}
@@ -87,6 +103,10 @@ th {
text-align: start;
}
+tbody.head th {
+ border-top: 1px solid var(--border-color);
+}
+
.header-container {
display: block;
overflow: hidden;
@@ -212,6 +232,20 @@ th {
color: red;
}
+.cell-additional-info a {
+ background-image: url(../../../../third_party/blink/renderer/modules/media_controls/resources/ic_download.svg);
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: contain;
+ display: block;
+ height: 16px;
+ width: 16px;
+}
+
+.cell-additional-info:not(:hover) a {
+ visibility: hidden;
+}
+
/* boolean cells */
.check-mark,
@@ -265,10 +299,10 @@ img:not([src]),
/* filter */
-.filtered-highlighted {
+.body tr.filtered-highlighted:not(:hover) {
background-color: rgb(208, 240, 255);
}
-.filtered-highlighted-nested {
+.body tr.filtered-highlighted:not(:hover) td.filtered-highlighted-nested {
background-color: rgb(208, 255, 208);
}
diff --git a/chromium/chrome/browser/resources/page_not_available_for_guest/app.html b/chromium/chrome/browser/resources/page_not_available_for_guest/app.html
index 9e8736a40bb..9d08222ee9a 100644
--- a/chromium/chrome/browser/resources/page_not_available_for_guest/app.html
+++ b/chromium/chrome/browser/resources/page_not_available_for_guest/app.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
<meta charset="utf-8">
<title>$i18n{pageTitle}</title>
@@ -20,6 +20,5 @@
</head>
<body>
<h1>$i18n{pageHeading}</h1>
- <link rel="import" href="chrome://resources/html/dark_mode.html">
</body>
</html>
diff --git a/chromium/chrome/browser/resources/pdf/browser_api.js b/chromium/chrome/browser/resources/pdf/browser_api.js
index 5736cb21b43..6127ce44228 100644
--- a/chromium/chrome/browser/resources/pdf/browser_api.js
+++ b/chromium/chrome/browser/resources/pdf/browser_api.js
@@ -89,15 +89,6 @@ class BrowserApi {
}
/**
- * Aborts the stream.
- */
- abortStream() {
- if (chrome.mimeHandlerPrivate) {
- chrome.mimeHandlerPrivate.abortStream();
- }
- }
-
- /**
* Sets the browser zoom.
*
* @param {number} zoom The zoom factor to send to the browser.
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.html b/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.html
index d3c11673161..ae14eeb289f 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.html
@@ -2,6 +2,7 @@
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-ripple/paper-ripple.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
@@ -17,7 +18,7 @@
}
#item:hover {
- background-color: rgb(237, 237, 237);
+ background-color: var(--cr-menu-background-focus-color);
}
paper-ripple {
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen/viewer-error-screen.html b/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen/viewer-error-screen.html
index 97ddcc14898..25737d45127 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen/viewer-error-screen.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen/viewer-error-screen.html
@@ -1,20 +1,19 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<dom-module id="viewer-error-screen">
<template>
- <style include="paper-button-style cr-hidden-style"></style>
+ <style include="cr-hidden-style"></style>
<cr-dialog id="dialog" no-cancel>
<div slot="title">[[strings.errorDialogTitle]]</div>
<div slot="body">[[strings.pageLoadFailed]]</div>
<div slot="button-container" hidden$="[[!reloadFn]]">
- <paper-button class="action-button" on-click="reload">
+ <cr-button class="action-button" on-click="reload">
[[strings.pageReload]]
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning/viewer-form-warning.html b/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning/viewer-form-warning.html
index e86b7915e37..1e9e1ee4f67 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning/viewer-form-warning.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning/viewer-form-warning.html
@@ -1,23 +1,22 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<dom-module id="viewer-form-warning">
<template>
- <style include="paper-button-style cr-hidden-style"></style>
+ <style include="cr-hidden-style"></style>
<cr-dialog id="dialog" no-cancel>
<div slot="title">[[strings.annotationFormWarningTitle]]</div>
<div slot="body">[[strings.annotationFormWarningDetail]]</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancel">
+ <cr-button class="cancel-button" on-click="onCancel">
[[strings.annotationFormWarningKeepEditing]]
- </paper-button>
- <paper-button class="action-button" on-click="onAction">
+ </cr-button>
+ <cr-button class="action-button" on-click="onAction">
[[strings.annotationFormWarningDiscard]]
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.html b/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.html
index e815e1cbc57..70ad2578685 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.html
@@ -7,6 +7,7 @@
<style>
:host {
display: flex;
+ opacity: 0;
pointer-events: none;
position: fixed;
right: 0;
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js b/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js
index c0a3e0bac1d..50ad4f4cb49 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js
@@ -18,18 +18,14 @@ Polymer({
/** @override */
ready: function() {
- const callback = this.fadeIn.bind(this, 2000);
+ const callback = this.fadeIn_.bind(this);
window.addEventListener('scroll', function() {
requestAnimationFrame(callback);
});
},
- initialFadeIn: function() {
- this.fadeIn(6000);
- },
-
- /** @param {number} displayTime */
- fadeIn: function(displayTime) {
+ /** @private */
+ fadeIn_: function() {
const percent = window.scrollY /
(document.scrollingElement.scrollHeight -
document.documentElement.clientHeight);
@@ -55,7 +51,7 @@ Polymer({
this.timerId = setTimeout(() => {
this.style.opacity = 0;
this.timerId = undefined;
- }, displayTime);
+ }, 2000);
},
pageLabelsChanged: function() {
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.html b/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.html
index d7c9c12b887..e1fdc869efe 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.html
@@ -7,6 +7,7 @@
<style>
:host {
color: #fff;
+ display: flex;
font-size: 0.81rem;
}
@@ -14,58 +15,39 @@
background: rgba(255, 255, 255, 0.3);
}
+ #pageselector-container,
+ #pagelength-spacer {
+ padding: 0 3px;
+ text-align: start;
+ /* --page-length-digits is set through JavaScript */
+ width: calc(var(--page-length-digits, 1) * 1ch);
+ }
+
+ #pageselector-container:focus-within,
+ #pageselector-container:hover {
+ background: rgba(0, 0, 0, 0.5);
+ }
+
#pageselector {
--cr-input-focus-color: transparent;
- --cr-input-container: {
- overflow: initial;
- }
--cr-input-error-display: none;
--cr-input-background-color: transparent;
--cr-input-color: white;
- --cr-input-inner-container: {
- margin-inline-end: -3px;
- }
- --cr-input-input: {
- text-align: end;
- caret-color: #fff;
- border-radius: 2px;
- box-sizing: content-box;
- margin-inline-start: -3px;
- }
- --cr-input-padding-end: 3px;
- --cr-input-padding-start: 3px;
- --cr-input-padding-bottom: 0;
- --cr-input-padding-top: 0;
- height: 100%;
- margin-inline-start: -3px;
- width: 1ch;
- }
-
- #pageselector[focused_],
- #pageselector:hover {
- --cr-input-background-color: rgba(0, 0, 0, 0.5);
}
- #slash {
- padding: 0 3px;
- }
-
- #pagelength-spacer {
- margin-inline-start: -2px;
- text-align: start;
- }
-
- #pageselector,
- #slash,
- #pagelength-spacer {
- display: inline-block;
+ #pageselector::part(input) {
+ caret-color: var(--cr-input-color);
+ padding: 0;
+ text-align: end;
}
</style>
- <cr-input id="pageselector" value="[[pageNo]]" on-mouseup="select"
- on-value-changed="onInputValueChange_" on-change="pageNoCommitted"
- aria-label$="{{strings.labelPageNumber}}">
- </cr-input>
- <span id="slash"> / </span>
+ <div id="pageselector-container">
+ <cr-input id="pageselector" value="[[pageNo]]" on-mouseup="select"
+ on-value-changed="onInputValueChange_" on-change="pageNoCommitted"
+ aria-label$="{{strings.labelPageNumber}}">
+ </cr-input>
+ </div>
+ <span id="slash">/</span>
<span id="pagelength-spacer">
<span id="pagelength">{{docLength}}</span>
</span>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.js b/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.js
index c4483e97d6b..b7999237a98 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.js
@@ -43,12 +43,7 @@ Polymer({
/** @private */
docLengthChanged_: function() {
const numDigits = this.docLength.toString().length;
- // Set both sides of the slash to the same width, so that the layout is
- // exactly centered. We add 1px because the unit `ch` does not provide
- // exact whole number pixels, and therefore seems to have 1px-off bugginess.
- const width = `calc(${numDigits}ch + 1px)`;
- this.pageSelector.style.width = width;
- this.$['pagelength-spacer'].style.width = width;
+ this.style.setProperty('--page-length-digits', `${numDigits}`);
},
select: function() {
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen/viewer-password-screen.html b/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen/viewer-password-screen.html
index 5120c53c078..aebc16bf138 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen/viewer-password-screen.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen/viewer-password-screen.html
@@ -1,15 +1,14 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<dom-module id="viewer-password-screen">
<template>
- <style include="cr-shared-style paper-button-style">
+ <style include="cr-shared-style">
#password {
margin-top: var(--cr-form-field-bottom-spacing);
}
@@ -26,9 +25,9 @@
</cr-input>
</div>
<div slot="button-container">
- <paper-button id="submit" class="action-button" on-click="submit">
+ <cr-button id="submit" class="action-button" on-click="submit">
[[strings.passwordSubmit]]
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.html b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.html
index 2f87e5efc14..f6454c97a5c 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.html
@@ -204,8 +204,8 @@
title$="{{strings.tooltipDownload}}"></cr-icon-button>
<cr-icon-button id="print" iron-icon="cr:print" on-click="print"
- aria-label$="{{strings.tooltipPrint}}"
- title$="{{strings.tooltipPrint}}"></cr-icon-button>
+ hidden="[[!printingEnabled]]" title$="{{strings.tooltipPrint}}"
+ aria-label$="{{strings.tooltipPrint}}"></cr-icon-button>
<viewer-toolbar-dropdown id="bookmarks"
selected
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js
index 8e18564aa75..006aa5ca5b8 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js
@@ -80,6 +80,14 @@ Polymer({
value: false,
},
+ /**
+ * Whether the Printing feature is enabled.
+ */
+ printingEnabled: {
+ type: Boolean,
+ value: false,
+ },
+
strings: Object,
},
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.html b/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.html
index 50dadbe03bd..c1964a19a20 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.html
@@ -1,6 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
@@ -33,8 +33,7 @@
}
#dropdown {
- @apply --shadow-elevation-2dp;
- background-color: rgb(256, 256, 256);
+ background-color: var(--cr-menu-background-color);
border-radius: 4px;
color: var(--cr-primary-text-color);
overflow-y: hidden;
@@ -42,6 +41,20 @@
width: var(--dropdown-width);
}
+ @media (prefers-color-scheme: light) {
+ #dropdown {
+ @apply --shadow-elevation-2dp;
+ }
+ }
+
+ @media (prefers-color-scheme: dark) {
+ #dropdown {
+ background-image: linear-gradient(var(--cr-menu-background-sheen),
+ var(--cr-menu-background-sheen));
+ box-shadow: var(--cr-menu-shadow);
+ }
+ }
+
#scroll-container {
max-height: 300px;
overflow-y: auto;
@@ -49,23 +62,11 @@
}
#button {
- border-radius: 4px;
- cursor: pointer;
- display: inline-block;
- height: 32px;
+ --cr-icon-button-color: currentColor;
+ --cr-icon-button-height: 32px;
+ --cr-icon-button-icon-start-offset: 4px;
+ --cr-icon-button-width: 48px;
margin: 0;
- min-width: 48px;
- opacity: 0.38;
- padding-bottom: 6px;
- padding-inline-end: 2px;
- padding-inline-start: 6px;
- padding-top: 6px;
- width: 48px;
- }
-
- #button:focus {
- background-color: rgba(255, 255, 255, 0.24);
- opacity: 1;
}
#button:hover {
@@ -82,18 +83,16 @@
}
h1 {
- border-bottom: 1px solid rgb(219, 219, 219);
+ border-bottom: var(--cr-separator-line);
font-size: 0.87rem;
font-weight: 500;
margin: 0;
padding: 14px 28px;
}
</style>
- <paper-button on-click="toggleDropdown" id="button"
- aria-label$="{{header}}" title$="{{header}}">
- <iron-icon icon="[[dropdownIcon]]"></iron-icon>
- <iron-icon icon="cr:arrow-drop-down"></iron-icon>
- </paper-button>
+ <cr-icon-button on-click="toggleDropdown" id="button"
+ iron-icon="[[dropdownIcon]],cr:arrow-drop-down" title$="[[header]]">
+ </cr-icon-button>
<div id="container">
<div id="dropdown" style="display: none">
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.html b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.html
index be487dc81a0..a3ae841c93f 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.html
@@ -54,13 +54,17 @@
color: white;
}
- :host-context(:not([dark])):host([new-print-preview]) cr-icon-button {
- --cr-icon-button-ripple-opacity: .5;
+ @media (prefers-color-scheme: light) {
+ :host([new-print-preview]) cr-icon-button {
+ --cr-icon-button-ripple-opacity: .5;
+ }
}
- :host-context([dark]):host([new-print-preview]) cr-icon-button {
- background-color: var(--google-grey-900);
- color: var(--google-grey-200);
+ @media (prefers-color-scheme: dark) {
+ :host([new-print-preview]) cr-icon-button {
+ background-color: var(--google-grey-900);
+ color: var(--google-grey-200);
+ }
}
:host([keyboard-navigation-active]) cr-icon-button:focus {
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js
index 1b17b8b130a..fb817a5a01d 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js
@@ -28,10 +28,6 @@ Polymer({
computed: 'computeShowOnLeft_(newPrintPreview)',
reflectToAttribute: true,
},
-
- strings: {type: Object, observer: 'updateTooltips_'},
-
- visible_: {type: Boolean, value: true}
},
listeners: {
@@ -40,25 +36,50 @@ Polymer({
'pointerdown': 'onPointerDown_',
},
+ /** @private {boolean} */
+ isPrintPreview_: false,
+
+ /** @private {boolean} */
+ visible_: true,
+
+ /** @param {boolean} isPrintPreview */
+ setIsPrintPreview: function(isPrintPreview) {
+ this.isPrintPreview_ = isPrintPreview;
+ },
+
+ /** @return {boolean} */
+ isPrintPreview: function() {
+ return this.isPrintPreview_;
+ },
+
isVisible: function() {
return this.visible_;
},
/** @private */
onFocus_: function() {
- // This can only happen when the plugin is shown within Print Preview.
+ // This can only happen when the plugin is shown within Print Preview using
+ // keyboard navigation.
if (!this.visible_) {
+ assert(this.isPrintPreview_);
+ this.fire('keyboard-navigation-active', true);
this.show();
}
},
/** @private */
onKeyUp_: function() {
+ if (this.isPrintPreview_) {
+ this.fire('keyboard-navigation-active', true);
+ }
this.keyboardNavigationActive_ = true;
},
/** @private */
onPointerDown_: function() {
+ if (this.isPrintPreview_) {
+ this.fire('keyboard-navigation-active', false);
+ }
this.keyboardNavigationActive_ = false;
},
@@ -72,14 +93,14 @@ Polymer({
},
/**
- * @private
* Change button tooltips to match any changes to localized strings.
+ * @param {!Object} strings
*/
- updateTooltips_: function() {
+ setStrings: function(strings) {
this.$['fit-button'].tooltips =
- [this.strings.tooltipFitToPage, this.strings.tooltipFitToWidth];
- this.$['zoom-in-button'].tooltips = [this.strings.tooltipZoomIn];
- this.$['zoom-out-button'].tooltips = [this.strings.tooltipZoomOut];
+ [strings.tooltipFitToPage, strings.tooltipFitToWidth];
+ this.$['zoom-in-button'].tooltips = [strings.tooltipZoomIn];
+ this.$['zoom-out-button'].tooltips = [strings.tooltipZoomOut];
},
/**
diff --git a/chromium/chrome/browser/resources/pdf/pdf_viewer.js b/chromium/chrome/browser/resources/pdf/pdf_viewer.js
index 942761c08a2..02763ae00c9 100644
--- a/chromium/chrome/browser/resources/pdf/pdf_viewer.js
+++ b/chromium/chrome/browser/resources/pdf/pdf_viewer.js
@@ -240,6 +240,7 @@ function PDFViewer(browserApi) {
// Setup the button event listeners.
this.zoomToolbar_ = $('zoom-toolbar');
+ this.zoomToolbar_.setIsPrintPreview(this.isPrintPreview_);
this.zoomToolbar_.addEventListener(
'fit-to-changed', this.fitToChanged_.bind(this));
this.zoomToolbar_.addEventListener(
@@ -746,7 +747,7 @@ PDFViewer.prototype = {
sendBackgroundColorForPrintPreview_: function() {
this.pluginController_.postMessage({
type: 'backgroundColorChanged',
- backgroundColor: document.documentElement.hasAttribute('dark') ?
+ backgroundColor: this.dark_ ?
PDFViewer.PRINT_PREVIEW_DARK_BACKGROUND_COLOR :
PDFViewer.PRINT_PREVIEW_BACKGROUND_COLOR,
});
@@ -776,7 +777,8 @@ PDFViewer.prototype = {
$('toolbar').strings = strings;
$('toolbar').pdfAnnotationsEnabled =
loadTimeData.getBoolean('pdfAnnotationsEnabled');
- $('zoom-toolbar').strings = strings;
+ $('toolbar').printingEnabled = loadTimeData.getBoolean('printingEnabled');
+ $('zoom-toolbar').setStrings(strings);
$('password-screen').strings = strings;
$('error-screen').strings = strings;
if ($('form-warning')) {
@@ -1014,7 +1016,7 @@ PDFViewer.prototype = {
this.toolbarManager_.resetKeyboardNavigationAndHideToolbars();
return true;
case 'darkModeChanged':
- document.documentElement.toggleAttribute('dark', message.data.darkMode);
+ this.dark_ = message.data.darkMode;
if (this.isPrintPreview_) {
this.sendBackgroundColorForPrintPreview_();
}
@@ -1091,10 +1093,6 @@ PDFViewer.prototype = {
this.passwordScreen_.close();
}
- if (this.pageIndicator_) {
- this.pageIndicator_.initialFadeIn();
- }
-
if (this.toolbar_) {
this.toolbar_.docLength = this.documentDimensions_.pageDimensions.length;
}
@@ -1622,9 +1620,6 @@ class PluginController extends ContentController {
case 'scrollBy':
this.viewport_.scrollBy(/** @type {!Point} */ (message.data));
break;
- case 'cancelStreamUrl':
- chrome.mimeHandlerPrivate.abortStream();
- break;
case 'metadata':
this.viewer_.setDocumentMetadata(
message.data.title, message.data.bookmarks,
diff --git a/chromium/chrome/browser/resources/pdf/toolbar_manager.js b/chromium/chrome/browser/resources/pdf/toolbar_manager.js
index 4b47da225bc..255bc3394f1 100644
--- a/chromium/chrome/browser/resources/pdf/toolbar_manager.js
+++ b/chromium/chrome/browser/resources/pdf/toolbar_manager.js
@@ -76,6 +76,12 @@ function ToolbarManager(window, toolbar, zoomToolbar) {
this.window_.addEventListener('resize', this.resizeDropdowns_.bind(this));
this.resizeDropdowns_();
+
+ if (zoomToolbar.isPrintPreview()) {
+ this.zoomToolbar_.addEventListener('keyboard-navigation-active', e => {
+ this.keyboardNavigationActive = e.detail;
+ });
+ }
}
ToolbarManager.prototype = {
diff --git a/chromium/chrome/browser/resources/policy/policy.html b/chromium/chrome/browser/resources/policy/policy.html
index e043cb9ab7f..b059bc46a4e 100644
--- a/chromium/chrome/browser/resources/policy/policy.html
+++ b/chromium/chrome/browser/resources/policy/policy.html
@@ -109,6 +109,14 @@
<div class="label">$i18n{labelStatus}</div>
<div class="status"></div>
</div>
+ <div class="status-entry" hidden>
+ <div class="label">$i18n{labelIsAffiliated}</div>
+ <div class="is-affiliated"></div>
+ </div>
+ <div class="status-entry" hidden>
+ <div class="label">$i18n{labelIsOffHoursActive}</div>
+ <div class="is-offhours-active"></div>
+ </div>
</fieldset>
<div class="policy-table" id="policy-table-template">
diff --git a/chromium/chrome/browser/resources/policy/policy_base.js b/chromium/chrome/browser/resources/policy/policy_base.js
index 31c815afad0..cd3dd432178 100644
--- a/chromium/chrome/browser/resources/policy/policy_base.js
+++ b/chromium/chrome/browser/resources/policy/policy_base.js
@@ -42,6 +42,7 @@ policy.Conflict;
* source: string,
* error: string,
* value: any,
+ * allSourcesMerged: ?boolean,
* conflicts: ?Array<!Conflict>,
* }}
*/
@@ -124,6 +125,13 @@ cr.define('policy', function() {
this.setLabelAndShow_(
'.directory-api-id', status.directoryApiId || notSpecifiedString);
this.setLabelAndShow_('.client-id', status.clientId);
+ //For off-hours policy, indicate if it's active or not.
+ if (status.isOffHoursActive != null) {
+ this.setLabelAndShow_(
+ '.is-offhours-active',
+ loadTimeData.getString(
+ status.isOffHoursActive ? 'offHoursActive' : 'offHoursNotActive'));
+ }
} else if (scope == 'machine') {
// For machine policy, set the appropriate title and populate
// machine enrollment status with the information that applies
@@ -145,6 +153,12 @@ cr.define('policy', function() {
// Populate the user gaia id.
this.setLabelAndShow_('.gaia-id', status.gaiaId || notSpecifiedString);
this.setLabelAndShow_('.client-id', status.clientId);
+ if (status.isAffiliated != null) {
+ this.setLabelAndShow_(
+ '.is-affiliated',
+ loadTimeData.getString(
+ status.isAffiliated ? 'isAffiliatedYes' : 'isAffiliatedNo'));
+ }
}
this.setLabelAndShow_(
'.time-since-last-refresh', status.timeSinceLastRefresh, false);
@@ -228,6 +242,9 @@ cr.define('policy', function() {
/** @private {boolean} */
this.hasConflicts_ = !!policy.conflicts;
+ /** @private {boolean} */
+ this.isMergedValue_ = !!policy.allSourcesMerged;
+
// Populate the name column.
const nameDisplay = this.querySelector('.name .link span');
nameDisplay.textContent = policy.name;
@@ -277,8 +294,9 @@ cr.define('policy', function() {
this.hasErrors_ ? loadTimeData.getString('error') : '';
const warningsNotice =
this.hasWarnings_ ? loadTimeData.getString('warning') : '';
- const conflictsNotice =
- this.hasConflicts_ ? loadTimeData.getString('conflict') : '';
+ const conflictsNotice = this.hasConflicts_ && !this.isMergedValue_ ?
+ loadTimeData.getString('conflict') :
+ '';
const ignoredNotice =
this.policy.ignored ? loadTimeData.getString('ignored') : '';
const notice =
@@ -492,7 +510,7 @@ cr.define('policy', function() {
link:
knownPolicyNames === policyNames.chrome.policyNames &&
knownPolicyNamesSet.has(name) ?
- `https://chromium.org/administrators/policy-list-3#${
+ `https://cloud.google.com/docs/chrome-enterprise/policies/?policy=${
name}` :
undefined,
},
diff --git a/chromium/chrome/browser/resources/print_preview/BUILD.gn b/chromium/chrome/browser/resources/print_preview/BUILD.gn
index 9f756a1adb4..fe72fb197fb 100644
--- a/chromium/chrome/browser/resources/print_preview/BUILD.gn
+++ b/chromium/chrome/browser/resources/print_preview/BUILD.gn
@@ -67,6 +67,7 @@ js_type_check("print_preview_resources") {
":cloud_print_interface_js",
":cloud_print_interface_manager",
":cloud_print_interface_native",
+ ":dark_mode_behavior",
":metrics",
":native_layer",
":print_preview_utils",
@@ -75,7 +76,7 @@ js_type_check("print_preview_resources") {
js_library("print_preview_utils") {
deps = [
- "//ui/webui/resources/js:dark_mode",
+ ":dark_mode_behavior",
"//ui/webui/resources/js:util",
]
externs_list = [ "$externs_path/pending.js" ]
@@ -130,3 +131,10 @@ js_library("native_layer") {
"//ui/webui/resources/js:cr",
]
}
+
+js_library("dark_mode_behavior") {
+ deps = [
+ "//ui/webui/resources/js:assert",
+ "//ui/webui/resources/js:cr",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/print_preview/cloud_print_interface.js b/chromium/chrome/browser/resources/print_preview/cloud_print_interface.js
index 7fb4b8d1d18..477efe90a78 100644
--- a/chromium/chrome/browser/resources/print_preview/cloud_print_interface.js
+++ b/chromium/chrome/browser/resources/print_preview/cloud_print_interface.js
@@ -2,72 +2,70 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.exportPath('cloudprint');
-
-/**
- * Event types dispatched by the cloudprint interface.
- * @enum {string}
- */
-cloudprint.CloudPrintInterfaceEventType = {
- INVITES_DONE: 'cloudprint.CloudPrintInterface.INVITES_DONE',
- INVITES_FAILED: 'cloudprint.CloudPrintInterface.INVITES_FAILED',
- PRINTER_DONE: 'cloudprint.CloudPrintInterface.PRINTER_DONE',
- PRINTER_FAILED: 'cloudprint.CloudPrintInterface.PRINTER_FAILED',
- PROCESS_INVITE_DONE: 'cloudprint.CloudPrintInterface.PROCESS_INVITE_DONE',
- SEARCH_DONE: 'cloudprint.CloudPrintInterface.SEARCH_DONE',
- SEARCH_FAILED: 'cloudprint.CloudPrintInterface.SEARCH_FAILED',
- SUBMIT_DONE: 'cloudprint.CloudPrintInterface.SUBMIT_DONE',
- SUBMIT_FAILED: 'cloudprint.CloudPrintInterface.SUBMIT_FAILED',
- UPDATE_USERS: 'cloudprint.CloudPrintInterface.UPDATE_USERS',
-};
+cr.define('cloudprint', function() {
+ /**
+ * Event types dispatched by the cloudprint interface.
+ * @enum {string}
+ */
+ const CloudPrintInterfaceEventType = {
+ INVITES_DONE: 'cloudprint.CloudPrintInterface.INVITES_DONE',
+ INVITES_FAILED: 'cloudprint.CloudPrintInterface.INVITES_FAILED',
+ PRINTER_DONE: 'cloudprint.CloudPrintInterface.PRINTER_DONE',
+ PRINTER_FAILED: 'cloudprint.CloudPrintInterface.PRINTER_FAILED',
+ PROCESS_INVITE_DONE: 'cloudprint.CloudPrintInterface.PROCESS_INVITE_DONE',
+ SEARCH_DONE: 'cloudprint.CloudPrintInterface.SEARCH_DONE',
+ SEARCH_FAILED: 'cloudprint.CloudPrintInterface.SEARCH_FAILED',
+ SUBMIT_DONE: 'cloudprint.CloudPrintInterface.SUBMIT_DONE',
+ SUBMIT_FAILED: 'cloudprint.CloudPrintInterface.SUBMIT_FAILED',
+ UPDATE_USERS: 'cloudprint.CloudPrintInterface.UPDATE_USERS',
+ };
-/**
- * @typedef {{
- * status: number,
- * errorCode: number,
- * message: string,
- * origin: !print_preview.DestinationOrigin,
- * }}
- */
-cloudprint.CloudPrintInterfaceErrorEventDetail;
+ /**
+ * @typedef {{
+ * status: number,
+ * errorCode: number,
+ * message: string,
+ * origin: !print_preview.DestinationOrigin,
+ * }}
+ */
+ let CloudPrintInterfaceErrorEventDetail;
-/**
- * @typedef {{
- * user: string,
- * origin: !print_preview.DestinationOrigin,
- * printers: (!Array<!print_preview.Destination>|undefined),
- * searchDone: boolean,
- * }}
- */
-cloudprint.CloudPrintInterfaceSearchDoneDetail;
+ /**
+ * @typedef {{
+ * user: string,
+ * origin: !print_preview.DestinationOrigin,
+ * printers: (!Array<!print_preview.Destination>|undefined),
+ * searchDone: boolean,
+ * }}
+ */
+ let CloudPrintInterfaceSearchDoneDetail;
-/**
- * @typedef {{
- * destinationId: string,
- * origin: !print_preview.DestinationOrigin,
- * }}
- */
-cloudprint.CloudPrintInterfacePrinterFailedDetail;
+ /**
+ * @typedef {{
+ * destinationId: string,
+ * origin: !print_preview.DestinationOrigin,
+ * }}
+ */
+ let CloudPrintInterfacePrinterFailedDetail;
-/**
- * @typedef {{
- * invitations: !Array<!print_preview.Invitation>,
- * user: string,
- * }}
- */
-cloudprint.CloudPrintInterfaceInvitesDoneDetail;
+ /**
+ * @typedef {{
+ * invitations: !Array<!print_preview.Invitation>,
+ * user: string,
+ * }}
+ */
+ let CloudPrintInterfaceInvitesDoneDetail;
-/**
- * @typedef {{
- * invitation: !print_preview.Invitation,
- * printer: ?print_preview.Destination,
- * accept: boolean,
- * user: string,
- * }}
- */
-cloudprint.CloudPrintInterfaceProcessInviteDetail;
+ /**
+ * @typedef {{
+ * invitation: !print_preview.Invitation,
+ * printer: ?print_preview.Destination,
+ * accept: boolean,
+ * user: string,
+ * }}
+ */
+ let CloudPrintInterfaceProcessInviteDetail;
-cr.define('cloudprint', function() {
/** @interface */
class CloudPrintInterface {
/**
@@ -89,6 +87,12 @@ cr.define('cloudprint', function() {
search(opt_account, opt_origin) {}
/**
+ * Sets the currently active users.
+ * @param {!Array<string>} users
+ */
+ setUsers(users) {}
+
+ /**
* Sends Google Cloud Print printer sharing invitations API requests.
* @param {string} account Account the request is sent for.
*/
@@ -127,5 +131,13 @@ cr.define('cloudprint', function() {
// Export
return {
CloudPrintInterface: CloudPrintInterface,
+ CloudPrintInterfaceErrorEventDetail: CloudPrintInterfaceErrorEventDetail,
+ CloudPrintInterfaceEventType: CloudPrintInterfaceEventType,
+ CloudPrintInterfaceInvitesDoneDetail: CloudPrintInterfaceInvitesDoneDetail,
+ CloudPrintInterfacePrinterFailedDetail:
+ CloudPrintInterfacePrinterFailedDetail,
+ CloudPrintInterfaceProcessInviteDetail:
+ CloudPrintInterfaceProcessInviteDetail,
+ CloudPrintInterfaceSearchDoneDetail: CloudPrintInterfaceSearchDoneDetail,
};
});
diff --git a/chromium/chrome/browser/resources/print_preview/cloud_print_interface_js.js b/chromium/chrome/browser/resources/print_preview/cloud_print_interface_js.js
index 8ede13afff5..cde3343dcc4 100644
--- a/chromium/chrome/browser/resources/print_preview/cloud_print_interface_js.js
+++ b/chromium/chrome/browser/resources/print_preview/cloud_print_interface_js.js
@@ -18,8 +18,9 @@ cr.define('cloudprint', function() {
* Auth2 tokens.
* @param {boolean} isInAppKioskMode Whether the print preview is in App
* Kiosk mode.
+ * @param {string} uiLocale The UI locale.
*/
- constructor(baseUrl, nativeLayer, isInAppKioskMode) {
+ constructor(baseUrl, nativeLayer, isInAppKioskMode, uiLocale) {
/**
* The base URL of the Google Cloud Print API.
* @private {string}
@@ -40,6 +41,13 @@ cr.define('cloudprint', function() {
this.isInAppKioskMode_ = isInAppKioskMode;
/**
+ * The UI locale, used to get printer information in the correct locale
+ * from Google Cloud Print.
+ * @private {string}
+ */
+ this.uiLocale_ = uiLocale;
+
+ /**
* Currently logged in users (identified by email) mapped to the Google
* session index.
* @private {!Object<number>}
@@ -198,29 +206,35 @@ cr.define('cloudprint', function() {
* @private
*/
buildRequest_(method, action, params, origin, account, callback) {
- let url = this.baseUrl_ + '/' + action + '?xsrf=';
+ const url = new URL(this.baseUrl_ + '/' + action);
+ const searchParams = url.searchParams;
if (origin == print_preview.DestinationOrigin.COOKIES) {
const xsrfToken = this.xsrfTokens_[account];
if (!xsrfToken) {
+ searchParams.append('xsrf', '');
// TODO(rltoscano): Should throw an error if not a read-only action or
// issue an xsrf token request.
} else {
- url = url + xsrfToken;
+ searchParams.append('xsrf', xsrfToken);
}
if (account) {
const index = this.userSessionIndex_[account] || 0;
if (index > 0) {
- url += '&authuser=' + index;
+ searchParams.append('authuser', index.toString());
}
}
+ } else {
+ searchParams.append('xsrf', '');
}
+
+ // Add locale
+ searchParams.append('hl', this.uiLocale_);
let body = null;
if (params) {
if (method == 'GET') {
- url = params.reduce(function(partialUrl, param) {
- return partialUrl + '&' + param.name + '=' +
- encodeURIComponent(param.value);
- }, url);
+ params.forEach(param => {
+ searchParams.append(param.name, encodeURIComponent(param.value));
+ });
} else if (method == 'POST') {
body = params.reduce(function(partialBody, param) {
return partialBody + 'Content-Disposition: form-data; name=\"' +
@@ -239,7 +253,7 @@ cr.define('cloudprint', function() {
}
const xhr = new XMLHttpRequest();
- xhr.open(method, url, true);
+ xhr.open(method, url.toString(), true);
xhr.withCredentials = (origin == print_preview.DestinationOrigin.COOKIES);
for (const header in headers) {
xhr.setRequestHeader(header, headers[header]);
@@ -325,10 +339,15 @@ cr.define('cloudprint', function() {
setUsers_(request) {
if (request.origin == print_preview.DestinationOrigin.COOKIES) {
const users = request.result['request']['users'] || [];
- this.userSessionIndex_ = {};
- for (let i = 0; i < users.length; i++) {
- this.userSessionIndex_[users[i]] = i;
- }
+ this.setUsers(users);
+ }
+ }
+
+ /** @param {!Array<string>} users */
+ setUsers(users) {
+ this.userSessionIndex_ = {};
+ for (let i = 0; i < users.length; i++) {
+ this.userSessionIndex_[users[i]] = i;
}
}
@@ -551,13 +570,13 @@ cr.define('cloudprint', function() {
// this point, whether printer was found or not.
if (request.origin == print_preview.DestinationOrigin.COOKIES &&
request.result && request.result['request']['user'] &&
- request.result['request']['users'] &&
- request.account != request.result['request']['user']) {
+ request.result['request']['users']) {
const users = request.result['request']['users'];
this.setUsers_(request);
// In case the user account is known, but not the primary one,
// activate it.
- if (this.userSessionIndex_[request.account] > 0 && request.account) {
+ if (request.account != request.result['request']['user'] &&
+ this.userSessionIndex_[request.account] > 0 && request.account) {
this.dispatchUserUpdateEvent_(request.account, users);
// Repeat the request for the newly activated account.
this.printer(
diff --git a/chromium/chrome/browser/resources/print_preview/cloud_print_interface_manager.js b/chromium/chrome/browser/resources/print_preview/cloud_print_interface_manager.js
index fcf792397f4..83d98d45bfe 100644
--- a/chromium/chrome/browser/resources/print_preview/cloud_print_interface_manager.js
+++ b/chromium/chrome/browser/resources/print_preview/cloud_print_interface_manager.js
@@ -15,15 +15,17 @@ cr.define('cloudprint', function() {
* @param {!print_preview.NativeLayer} nativeLayer Native layer instance.
* @param {boolean} isInAppKioskMode Whether the print preview is in App
* Kiosk mode.
+ * @param {string} uiLocale The UI locale, for example "en-US" or "fr".
* @return {!cloudprint.CloudPrintInterface}
*/
- function getCloudPrintInterface(baseUrl, nativeLayer, isInAppKioskMode) {
+ function getCloudPrintInterface(
+ baseUrl, nativeLayer, isInAppKioskMode, uiLocale) {
if (instance === null) {
if (loadTimeData.getBoolean('cloudPrinterHandlerEnabled')) {
instance = new cloudprint.CloudPrintInterfaceNative();
} else {
instance = new cloudprint.CloudPrintInterfaceJS(
- baseUrl, nativeLayer, isInAppKioskMode);
+ baseUrl, nativeLayer, isInAppKioskMode, uiLocale);
}
}
return instance;
diff --git a/chromium/chrome/browser/resources/print_preview/cloud_print_interface_native.js b/chromium/chrome/browser/resources/print_preview/cloud_print_interface_native.js
index 5455aabb6d7..c12f2847fdd 100644
--- a/chromium/chrome/browser/resources/print_preview/cloud_print_interface_native.js
+++ b/chromium/chrome/browser/resources/print_preview/cloud_print_interface_native.js
@@ -19,6 +19,9 @@ cr.define('cloudprint', function() {
search(opt_account, opt_origin) {}
/** @override */
+ setUsers(users) {}
+
+ /** @override */
invites(account) {}
/** @override */
diff --git a/chromium/chrome/browser/resources/print_preview/dark_mode_behavior.html b/chromium/chrome/browser/resources/print_preview/dark_mode_behavior.html
new file mode 100644
index 00000000000..b8924f4f921
--- /dev/null
+++ b/chromium/chrome/browser/resources/print_preview/dark_mode_behavior.html
@@ -0,0 +1,4 @@
+<link rel="import" href="chrome://resources/html/assert.html">
+<link rel="import" href="chrome://resources/html/cr.html">
+
+<script src="dark_mode_behavior.js"></script>
diff --git a/chromium/chrome/browser/resources/print_preview/dark_mode_behavior.js b/chromium/chrome/browser/resources/print_preview/dark_mode_behavior.js
new file mode 100644
index 00000000000..f25bbb38b10
--- /dev/null
+++ b/chromium/chrome/browser/resources/print_preview/dark_mode_behavior.js
@@ -0,0 +1,39 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+cr.exportPath('print_preview');
+
+(function() {
+
+const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
+
+/** @polymerBehavior */
+print_preview.DarkModeBehavior = {
+ properties: {
+ /** Whether or not the OS is in dark mode. */
+ inDarkMode: {
+ type: Boolean,
+ value: prefersDark.matches,
+ },
+ },
+
+ /** @override */
+ attached() {
+ this.boundOnChange_ = this.boundOnChange_ || this.onChange_.bind(this);
+ prefersDark.addListener(this.boundOnChange_);
+ },
+
+ /** @override */
+ detached() {
+ prefersDark.removeListener(assert(this.boundOnChange_));
+ },
+
+ /** @private */
+ onChange_() {
+ this.inDarkMode = prefersDark.matches;
+ },
+};
+
+print_preview.DarkModeBehavior.inDarkMode = () => prefersDark.matches;
+}());
diff --git a/chromium/chrome/browser/resources/print_preview/data/destination_store.html b/chromium/chrome/browser/resources/print_preview/data/destination_store.html
index e66bea9ac25..9d6e788612c 100644
--- a/chromium/chrome/browser/resources/print_preview/data/destination_store.html
+++ b/chromium/chrome/browser/resources/print_preview/data/destination_store.html
@@ -1,4 +1,5 @@
<link rel="import" href="chrome://resources/html/cr.html">
+<link rel="import" href="chrome://resources/html/event_tracker.html">
<link rel="import" href="../cloud_print_interface.html">
<link rel="import" href="../metrics.html">
<link rel="import" href="../native_layer.html">
diff --git a/chromium/chrome/browser/resources/print_preview/data/destination_store.js b/chromium/chrome/browser/resources/print_preview/data/destination_store.js
index 2d92b167108..61402a2561f 100644
--- a/chromium/chrome/browser/resources/print_preview/data/destination_store.js
+++ b/chromium/chrome/browser/resources/print_preview/data/destination_store.js
@@ -280,8 +280,6 @@ cr.define('print_preview', function() {
loadTimeData.getBoolean('useSystemDefaultPrinter');
addListenerCallback('printers-added', this.onPrintersAdded_.bind(this));
- addListenerCallback(
- 'user-accounts-updated', this.onDestinationsReload.bind(this));
}
/**
@@ -291,12 +289,10 @@ cr.define('print_preview', function() {
* accessible by the {@code account}.
*/
destinations(opt_account) {
- if (opt_account) {
- return this.destinations_.filter(function(destination) {
- return !destination.account || destination.account == opt_account;
- });
- }
- return this.destinations_.slice(0);
+ return this.destinations_.filter(function(destination) {
+ return !destination.account ||
+ (!!opt_account && destination.account == opt_account);
+ });
}
/**
@@ -806,9 +802,8 @@ cr.define('print_preview', function() {
* Attempts to select system default destination with a fallback to the
* 'Save to PDF' destination and a final fallback to the first destination
* in the store.
- * @private
*/
- selectDefaultDestination_() {
+ selectDefaultDestination() {
// Try the system default, if it isn't the destination that was
// supposed to be autoselected and failed.
if (this.autoSelectMatchingDestination_ &&
@@ -823,7 +818,8 @@ cr.define('print_preview', function() {
/**
* Initiates loading of destinations.
- * @param{print_preview.PrinterType} type The type of destinations to load.
+ * @param {!print_preview.PrinterType} type The type of destinations to
+ * load.
* @private
*/
startLoadDestinations_(type) {
@@ -1083,7 +1079,7 @@ cr.define('print_preview', function() {
this.autoSelectMatchingDestination_.matchOrigin(
print_preview.DestinationOrigin.EXTENSION) &&
this.selectedDestination_ && this.selectedDestination_.isExtension) {
- this.selectDefaultDestination_();
+ this.selectDefaultDestination();
}
}
@@ -1137,29 +1133,11 @@ cr.define('print_preview', function() {
startAutoSelectTimeout_() {
clearTimeout(this.autoSelectTimeout_);
this.autoSelectTimeout_ = setTimeout(
- this.selectDefaultDestination_.bind(this),
+ this.selectDefaultDestination.bind(this),
DestinationStore.AUTO_SELECT_TIMEOUT_);
}
/**
- * Resets the state of the destination store to its initial state.
- * @private
- */
- reset_() {
- this.destinations_ = [];
- this.destinationMap_.clear();
- this.inFlightCloudPrintRequests_.clear();
- this.loadedCloudOrigins_.clear();
- this.destinationSearchStatus_.forEach((status, type) => {
- this.destinationSearchStatus_.set(
- type, print_preview.DestinationStorePrinterSearchStatus.START);
- });
- this.startAutoSelectTimeout_();
- this.dispatchEvent(
- new CustomEvent(DestinationStore.EventType.DESTINATIONS_RESET));
- }
-
- /**
* Called when destination search is complete for some type of printer.
* @param {!print_preview.PrinterType} type The type of printers that are
* done being retreived.
@@ -1240,7 +1218,7 @@ cr.define('print_preview', function() {
if (this.autoSelectMatchingDestination_ &&
this.autoSelectMatchingDestination_.matchIdAndOrigin(
destinationId, origin)) {
- this.selectDefaultDestination_();
+ this.selectDefaultDestination();
}
}
@@ -1326,7 +1304,7 @@ cr.define('print_preview', function() {
console.warn(
'Failed to fetch last used printer caps: ' +
event.detail.destinationId);
- this.selectDefaultDestination_();
+ this.selectDefaultDestination();
} else {
// Log the failure
console.warn(
@@ -1351,7 +1329,7 @@ cr.define('print_preview', function() {
/**
* Called when a printer or printers are detected after sending getPrinters
* from the native layer.
- * @param {print_preview.PrinterType} type The type of printer(s) added.
+ * @param {!print_preview.PrinterType} type The type of printer(s) added.
* @param {!Array<!print_preview.LocalDestinationInfo |
* !print_preview.PrivetPrinterDescription |
* !print_preview.ProvisionalDestinationInfo>} printers
@@ -1367,18 +1345,6 @@ cr.define('print_preview', function() {
this.selectFirstDestination_ = false;
}
}
-
- /**
- * Called from print preview after the user was requested to sign in, and
- * did so successfully.
- */
- onDestinationsReload() {
- this.reset_();
- this.autoSelectMatchingDestination_ =
- this.convertPreselectedToDestinationMatch_();
- this.createLocalPdfPrintDestination_();
- this.startLoadAllDestinations();
- }
}
/**
@@ -1391,7 +1357,6 @@ cr.define('print_preview', function() {
DESTINATION_SELECT: 'print_preview.DestinationStore.DESTINATION_SELECT',
DESTINATIONS_INSERTED:
'print_preview.DestinationStore.DESTINATIONS_INSERTED',
- DESTINATIONS_RESET: 'print_preview.DestinationStore.DESTINATIONS_RESET',
ERROR: 'print_preview.DestinationStore.ERROR',
SELECTED_DESTINATION_CAPABILITIES_READY: 'print_preview.DestinationStore' +
'.SELECTED_DESTINATION_CAPABILITIES_READY',
diff --git a/chromium/chrome/browser/resources/print_preview/data/document_info.js b/chromium/chrome/browser/resources/print_preview/data/document_info.js
index aa87754d5a6..67ce1c952af 100644
--- a/chromium/chrome/browser/resources/print_preview/data/document_info.js
+++ b/chromium/chrome/browser/resources/print_preview/data/document_info.js
@@ -17,6 +17,22 @@ cr.exportPath('print_preview');
*/
print_preview.DocumentSettings;
+/**
+ * @typedef {{
+ * marginTop: number,
+ * marginLeft: number,
+ * marginBottom: number,
+ * marginRight: number,
+ * contentWidth: number,
+ * contentHeight: number,
+ * printableAreaX: number,
+ * printableAreaY: number,
+ * printableAreaWidth: number,
+ * printableAreaHeight: number,
+ * }}
+ */
+print_preview.PageLayoutInfo;
+
Polymer({
is: 'print-preview-document-info',
@@ -122,17 +138,8 @@ Polymer({
/**
* Called when the page layout of the document is ready. Always occurs
* as a result of a preview request.
- * @param {{marginTop: number,
- * marginLeft: number,
- * marginBottom: number,
- * marginRight: number,
- * contentWidth: number,
- * contentHeight: number,
- * printableAreaX: number,
- * printableAreaY: number,
- * printableAreaWidth: number,
- * printableAreaHeight: number,
- * }} pageLayout Layout information about the document.
+ * @param {!print_preview.PageLayoutInfo} pageLayout Layout information
+ * about the document.
* @param {boolean} hasCustomPageSizeStyle Whether this document has a
* custom page size or style to use.
* @private
diff --git a/chromium/chrome/browser/resources/print_preview/data/model.js b/chromium/chrome/browser/resources/print_preview/data/model.js
index cfd4184a9a8..a576e86a07b 100644
--- a/chromium/chrome/browser/resources/print_preview/data/model.js
+++ b/chromium/chrome/browser/resources/print_preview/data/model.js
@@ -14,6 +14,7 @@ cr.exportPath('print_preview');
* valid: boolean,
* available: boolean,
* setByPolicy: boolean,
+ * setFromUi: boolean,
* key: string,
* updatesPreview: boolean,
* }}
@@ -193,15 +194,17 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: '',
updatesPreview: false,
},
copies: {
- value: '1',
- unavailableValue: '1',
+ value: 1,
+ unavailableValue: 1,
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: '',
updatesPreview: false,
},
@@ -211,6 +214,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: 'isCollateEnabled',
updatesPreview: false,
},
@@ -220,6 +224,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: 'isLandscapeEnabled',
updatesPreview: true,
},
@@ -229,6 +234,7 @@ Polymer({
valid: true,
available: false,
setByPolicy: false,
+ setFromUi: false,
key: 'isColorEnabled',
updatesPreview: true,
},
@@ -241,6 +247,7 @@ Polymer({
valid: true,
available: false,
setByPolicy: false,
+ setFromUi: false,
key: 'mediaSize',
updatesPreview: true,
},
@@ -251,6 +258,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: 'marginsType',
updatesPreview: true,
},
@@ -260,6 +268,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: 'customMargins',
updatesPreview: true,
},
@@ -269,6 +278,7 @@ Polymer({
valid: true,
available: false,
setByPolicy: false,
+ setFromUi: false,
key: 'dpi',
updatesPreview: false,
},
@@ -278,6 +288,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: 'isFitToPageEnabled',
updatesPreview: true,
},
@@ -287,6 +298,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: 'scaling',
updatesPreview: true,
},
@@ -296,6 +308,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: 'customScaling',
updatesPreview: true,
},
@@ -305,6 +318,7 @@ Polymer({
valid: true,
available: false,
setByPolicy: false,
+ setFromUi: false,
key: 'isDuplexEnabled',
updatesPreview: false,
},
@@ -314,6 +328,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: 'isDuplexShortEdge',
updatesPreview: false,
},
@@ -323,6 +338,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: 'isCssBackgroundEnabled',
updatesPreview: true,
},
@@ -332,6 +348,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: '',
updatesPreview: true,
},
@@ -341,6 +358,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: 'isHeaderFooterEnabled',
updatesPreview: true,
},
@@ -350,6 +368,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: '',
updatesPreview: true,
},
@@ -359,6 +378,7 @@ Polymer({
valid: true,
available: false,
setByPolicy: false,
+ setFromUi: false,
key: 'vendorOptions',
updatesPreview: false,
},
@@ -368,6 +388,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: '',
updatesPreview: true,
},
@@ -379,6 +400,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: '',
updatesPreview: false,
},
@@ -390,6 +412,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: '',
updatesPreview: true,
},
@@ -399,6 +422,7 @@ Polymer({
valid: true,
available: true,
setByPolicy: false,
+ setFromUi: false,
key: 'recentDestinations',
updatesPreview: false,
},
@@ -409,6 +433,7 @@ Polymer({
valid: true,
available: false,
setByPolicy: false,
+ setFromUi: false,
key: 'isPinEnabled',
updatesPreview: false,
},
@@ -418,6 +443,7 @@ Polymer({
valid: true,
available: false,
setByPolicy: false,
+ setFromUi: false,
key: 'pinValue',
updatesPreview: false,
},
@@ -523,17 +549,22 @@ Polymer({
* Sets settings.settingName.value to |value|, unless updating the setting is
* disallowed by enterprise policy. Fires preview-setting-changed and
* sticky-setting-changed events if the update impacts the preview or requires
- * an update to sticky settings.
+ * an update to sticky settings. Used for setting settings from UI elements.
* @param {string} settingName Name of the setting to set
* @param {*} value The value to set the setting to.
+ * @param {boolean=} noSticky Whether to avoid stickying the setting. Defaults
+ * to false.
*/
- setSetting: function(settingName, value) {
+ setSetting: function(settingName, value, noSticky) {
const setting = this.getSetting(settingName);
if (setting.setByPolicy) {
return;
}
- const fireStickyEvent = setting.value !== value && setting.key;
+ const fireStickyEvent = !noSticky && setting.value !== value && setting.key;
this.setSettingPath_(`${settingName}.value`, value);
+ if (!noSticky) {
+ this.setSettingPath_(`${settingName}.setFromUi`, true);
+ }
if (fireStickyEvent && this.initialized_) {
this.fire('sticky-setting-changed', this.getStickySettings_());
}
@@ -544,8 +575,10 @@ Polymer({
* @param {number} start
* @param {number} end
* @param {*} newValue The value to add (if any).
+ * @param {boolean=} noSticky Whether to avoid stickying the setting. Defaults
+ * to false.
*/
- setSettingSplice: function(settingName, start, end, newValue) {
+ setSettingSplice: function(settingName, start, end, newValue, noSticky) {
const setting = this.getSetting(settingName);
if (setting.setByPolicy) {
return;
@@ -555,7 +588,10 @@ Polymer({
} else {
this.splice(`settings.${settingName}.value`, start, end);
}
- if (setting.key && this.initialized_) {
+ if (!noSticky) {
+ this.setSettingPath_(`${settingName}.setFromUi`, true);
+ }
+ if (!noSticky && setting.key && this.initialized_) {
this.fire('sticky-setting-changed', this.getStickySettings_());
}
},
@@ -795,40 +831,41 @@ Polymer({
// If the setting does not have a valid value, the UI has just started so
// do not try to get a matching value; just set the printer default in
// case the user doesn't have sticky settings.
- if (this.settings.mediaSize.value.height_microns !== undefined) {
+ if (this.settings.mediaSize.setFromUi) {
const currentMediaSize = this.getSettingValue('mediaSize');
matchingOption = caps.media_size.option.find(o => {
return o.height_microns === currentMediaSize.height_microns &&
o.width_microns === currentMediaSize.width_microns;
});
}
- this.setSetting('mediaSize', matchingOption || defaultOption);
+ this.setSetting('mediaSize', matchingOption || defaultOption, true);
}
if (this.settings.dpi.available) {
const defaultOption =
caps.dpi.option.find(o => !!o.is_default) || caps.dpi.option[0];
let matchingOption = null;
- if (this.settings.dpi.value.horizontal_dpi !== undefined) {
+ if (this.settings.dpi.setFromUi) {
const currentDpi = this.getSettingValue('dpi');
matchingOption = caps.dpi.option.find(o => {
return o.horizontal_dpi === currentDpi.horizontal_dpi &&
o.vertical_dpi === currentDpi.vertical_dpi;
});
}
- this.setSetting('dpi', matchingOption || defaultOption);
+ this.setSetting('dpi', matchingOption || defaultOption, true);
} else if (
caps && caps.dpi && caps.dpi.option && caps.dpi.option.length > 0) {
this.setSettingPath_('dpi.unavailableValue', caps.dpi.option[0]);
}
- if (!this.initialized_ && this.settings.color.available) {
+ if (!this.settings.color.setFromUi && this.settings.color.available) {
const defaultOption = this.destination.defaultColorOption;
if (defaultOption) {
this.setSetting(
'color',
!['STANDARD_MONOCHROME', 'CUSTOM_MONOCHROME'].includes(
- defaultOption.type));
+ defaultOption.type),
+ true);
}
} else if (
!this.settings.color.available &&
@@ -848,19 +885,21 @@ Polymer({
this.setSettingPath_('color.unavailableValue', false);
}
- if (!this.initialized_ && this.settings.duplex.available) {
+ if (!this.settings.duplex.setFromUi && this.settings.duplex.available) {
const defaultOption = caps.duplex.option.find(o => !!o.is_default);
this.setSetting(
'duplex',
defaultOption ?
(defaultOption.type == print_preview.DuplexType.LONG_EDGE ||
defaultOption.type == print_preview.DuplexType.SHORT_EDGE) :
- false);
+ false,
+ true);
this.setSetting(
'duplexShortEdge',
defaultOption ?
defaultOption.type == print_preview.DuplexType.SHORT_EDGE :
- false);
+ false,
+ true);
if (!this.settings.duplexShortEdge.available) {
// Duplex is available, so must have only one two sided printing option.
@@ -911,7 +950,7 @@ Polymer({
vendorSettings[item.id] = defaultValue;
}
}
- this.setSetting('vendorItems', vendorSettings);
+ this.setSetting('vendorItems', vendorSettings, true);
}
},
@@ -968,17 +1007,21 @@ Polymer({
},
applyStickySettings: function() {
+ const defaultScaling = '100';
if (this.stickySettings_) {
STICKY_SETTING_NAMES.forEach(settingName => {
const setting = this.get(settingName, this.settings);
const value = this.stickySettings_[setting.key];
if (value != undefined) {
this.setSetting(settingName, value);
- } else if (settingName === 'customScaling') {
- // Use the stored scaling value instead of resetting users with an
- // older set of sticky settings.
- this.setSetting(
- settingName, this.stickySettings_['scaling'] !== '100');
+ } else if (
+ settingName === 'customScaling' &&
+ !!this.stickySettings_['scaling']) {
+ // If users with an old set of sticky settings intentionally set a non
+ // default value, set customScaling to true so the value is restored.
+ // Otherwise, set to false with noSticky=true.
+ const scalingIsDefault = this.stickySettings_['scaling'] === '100';
+ this.setSetting(settingName, !scalingIsDefault, scalingIsDefault);
}
});
}
@@ -986,7 +1029,7 @@ Polymer({
for (const [settingName, policy] of Object.entries(
this.policySettings_)) {
if (policy.value !== undefined) {
- this.setSetting(settingName, policy.value);
+ this.setSetting(settingName, policy.value, true);
}
if (policy.managed) {
this.set(`settings.${settingName}.setByPolicy`, true);
@@ -1085,7 +1128,9 @@ Polymer({
STICKY_SETTING_NAMES.forEach(settingName => {
const setting = this.get(settingName, this.settings);
- serialization[assert(setting.key)] = setting.value;
+ if (setting.setFromUi) {
+ serialization[assert(setting.key)] = setting.value;
+ }
});
return JSON.stringify(serialization);
@@ -1145,7 +1190,7 @@ Polymer({
headerFooterEnabled: false, // only used in print preview
marginsType: this.getSettingValue('margins'),
duplex: this.getDuplexMode_(),
- copies: parseInt(this.getSettingValue('copies'), 10),
+ copies: this.getSettingValue('copies'),
collate: this.getSettingValue('collate'),
shouldPrintBackgrounds: this.getSettingValue('cssBackground'),
shouldPrintSelectionOnly: false, // only used in print preview
@@ -1247,7 +1292,7 @@ Polymer({
}
}
if (this.settings.copies.available) {
- cjt.print.copies = {copies: parseInt(this.getSettingValue('copies'), 10)};
+ cjt.print.copies = {copies: this.getSettingValue('copies')};
}
if (this.settings.duplex.available) {
cjt.print.duplex = {
diff --git a/chromium/chrome/browser/resources/print_preview/data/user_manager.js b/chromium/chrome/browser/resources/print_preview/data/user_manager.js
index ac2814d715e..8124cad7c1a 100644
--- a/chromium/chrome/browser/resources/print_preview/data/user_manager.js
+++ b/chromium/chrome/browser/resources/print_preview/data/user_manager.js
@@ -32,6 +32,12 @@ Polymer({
notify: true,
},
+ /** @type {?cloudprint.CloudPrintInterface} */
+ cloudPrintInterface: {
+ type: Object,
+ observer: 'onCloudPrintInterfaceSet_',
+ },
+
/** @type {?print_preview.DestinationStore} */
destinationStore: Object,
@@ -93,19 +99,22 @@ Polymer({
}
},
- /** @param {!cloudprint.CloudPrintInterface} cloudPrintInterface */
- setCloudPrintInterface: function(cloudPrintInterface) {
+ /** @private */
+ onCloudPrintInterfaceSet_: function() {
this.tracker_.add(
- cloudPrintInterface.getEventTarget(),
+ this.cloudPrintInterface.getEventTarget(),
cloudprint.CloudPrintInterfaceEventType.UPDATE_USERS,
this.onCloudPrintUpdateUsers_.bind(this));
[cloudprint.CloudPrintInterfaceEventType.SEARCH_FAILED,
cloudprint.CloudPrintInterfaceEventType.PRINTER_FAILED,
].forEach(eventType => {
this.tracker_.add(
- cloudPrintInterface.getEventTarget(), eventType,
+ this.cloudPrintInterface.getEventTarget(), eventType,
this.checkCloudPrintStatus_.bind(this));
});
+ if (this.users.length > 0) {
+ this.cloudPrintInterface.setUsers(this.users);
+ }
assert(this.cloudPrintDisabled);
this.cloudPrintDisabled = false;
},
@@ -149,6 +158,9 @@ Polymer({
const updateActiveUser = (users.length > 0 && this.users.length === 0) ||
!users.includes(this.activeUser);
this.users = users;
+ if (this.cloudPrintInterface) {
+ this.cloudPrintInterface.setUsers(users);
+ }
if (updateActiveUser) {
this.updateActiveUser(this.users[0] || '');
}
diff --git a/chromium/chrome/browser/resources/print_preview/native_layer.js b/chromium/chrome/browser/resources/print_preview/native_layer.js
index 7b3f097389c..fe78ee05149 100644
--- a/chromium/chrome/browser/resources/print_preview/native_layer.js
+++ b/chromium/chrome/browser/resources/print_preview/native_layer.js
@@ -2,113 +2,113 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.exportPath('print_preview');
-
-/**
- * @typedef {{selectSaveAsPdfDestination: boolean,
- * layoutSettings.portrait: boolean,
- * pageRange: string,
- * headersAndFooters: boolean,
- * backgroundColorsAndImages: boolean,
- * margins: number}}
- * @see chrome/browser/printing/print_preview_pdf_generated_browsertest.cc
- */
-print_preview.PreviewSettings;
+cr.define('print_preview', function() {
+ 'use strict';
-/**
- * @typedef {{
- * deviceName: string,
- * printerName: string,
- * printerDescription: (string | undefined),
- * cupsEnterprisePrinter: (boolean | undefined),
- * printerOptions: (Object | undefined),
- * policies: (print_preview.Policies | undefined),
- * }}
- */
-print_preview.LocalDestinationInfo;
+ /**
+ * @typedef {{selectSaveAsPdfDestination: boolean,
+ * layoutSettings.portrait: boolean,
+ * pageRange: string,
+ * headersAndFooters: boolean,
+ * backgroundColorsAndImages: boolean,
+ * margins: number}}
+ * @see chrome/browser/printing/print_preview_pdf_generated_browsertest.cc
+ */
+ let PreviewSettings;
-/**
- * @typedef {{
- * isInKioskAutoPrintMode: boolean,
- * isInAppKioskMode: boolean,
- * thousandsDelimeter: string,
- * decimalDelimeter: string,
- * unitType: !print_preview.MeasurementSystemUnitType,
- * previewModifiable: boolean,
- * documentTitle: string,
- * documentHasSelection: boolean,
- * shouldPrintSelectionOnly: boolean,
- * printerName: string,
- * headerFooter: (boolean | undefined),
- * isHeaderFooterManaged: boolean,
- * serializedAppStateStr: ?string,
- * serializedDefaultDestinationSelectionRulesStr: ?string,
- * cloudPrintURL: (string | undefined),
- * userAccounts: (Array<string> | undefined),
- * syncAvailable: boolean
- * }}
- * @see corresponding field name definitions in print_preview_handler.cc
- */
-print_preview.NativeInitialSettings;
+ /**
+ * @typedef {{
+ * deviceName: string,
+ * printerName: string,
+ * printerDescription: (string | undefined),
+ * cupsEnterprisePrinter: (boolean | undefined),
+ * printerOptions: (Object | undefined),
+ * policies: (print_preview.Policies | undefined),
+ * }}
+ */
+ let LocalDestinationInfo;
-/**
- * @typedef {{
- * serviceName: string,
- * name: string,
- * hasLocalPrinting: boolean,
- * isUnregistered: boolean,
- * cloudID: string,
- * }}
- * @see PrintPreviewHandler::FillPrinterDescription in print_preview_handler.cc
- */
-print_preview.PrivetPrinterDescription;
+ /**
+ * @typedef {{
+ * isInKioskAutoPrintMode: boolean,
+ * isInAppKioskMode: boolean,
+ * uiLocale: string,
+ * thousandsDelimeter: string,
+ * decimalDelimeter: string,
+ * unitType: !print_preview.MeasurementSystemUnitType,
+ * previewModifiable: boolean,
+ * documentTitle: string,
+ * documentHasSelection: boolean,
+ * shouldPrintSelectionOnly: boolean,
+ * printerName: string,
+ * headerFooter: (boolean | undefined),
+ * isHeaderFooterManaged: boolean,
+ * serializedAppStateStr: ?string,
+ * serializedDefaultDestinationSelectionRulesStr: ?string,
+ * cloudPrintURL: (string | undefined),
+ * userAccounts: (Array<string> | undefined),
+ * syncAvailable: boolean
+ * }}
+ * @see corresponding field name definitions in print_preview_handler.cc
+ */
+ let NativeInitialSettings;
-/**
- * @typedef {{
- * printer:(print_preview.PrivetPrinterDescription |
- * print_preview.LocalDestinationInfo |
- * undefined),
- * capabilities: !print_preview.Cdd,
- * }}
- */
-print_preview.CapabilitiesResponse;
+ /**
+ * @typedef {{
+ * serviceName: string,
+ * name: string,
+ * hasLocalPrinting: boolean,
+ * isUnregistered: boolean,
+ * cloudID: string,
+ * }}
+ * @see PrintPreviewHandler::FillPrinterDescription in
+ * print_preview_handler.cc
+ */
+ let PrivetPrinterDescription;
-/**
- * @typedef {{
- * printerId: string,
- * success: boolean,
- * capabilities: !print_preview.Cdd,
- * policies: (print_preview.Policies | undefined),
- * }}
- */
-print_preview.PrinterSetupResponse;
+ /**
+ * @typedef {{
+ * printer:(print_preview.PrivetPrinterDescription |
+ * print_preview.LocalDestinationInfo |
+ * undefined),
+ * capabilities: !print_preview.Cdd,
+ * }}
+ */
+ let CapabilitiesResponse;
-/**
- * @typedef {{
- * extensionId: string,
- * extensionName: string,
- * id: string,
- * name: string,
- * description: (string|undefined),
- * }}
- */
-print_preview.ProvisionalDestinationInfo;
+ /**
+ * @typedef {{
+ * printerId: string,
+ * success: boolean,
+ * capabilities: !print_preview.Cdd,
+ * policies: (print_preview.Policies | undefined),
+ * }}
+ */
+ let PrinterSetupResponse;
-/**
- * Printer types for capabilities and printer list requests.
- * Should match PrinterType in print_preview_handler.h
- * @enum {number}
- */
-print_preview.PrinterType = {
- PRIVET_PRINTER: 0,
- EXTENSION_PRINTER: 1,
- PDF_PRINTER: 2,
- LOCAL_PRINTER: 3,
- CLOUD_PRINTER: 4
-};
+ /**
+ * @typedef {{
+ * extensionId: string,
+ * extensionName: string,
+ * id: string,
+ * name: string,
+ * description: (string|undefined),
+ * }}
+ */
+ let ProvisionalDestinationInfo;
-cr.define('print_preview', function() {
- 'use strict';
+ /**
+ * Printer types for capabilities and printer list requests.
+ * Should match PrinterType in print_preview_handler.h
+ * @enum {number}
+ */
+ const PrinterType = {
+ PRIVET_PRINTER: 0,
+ EXTENSION_PRINTER: 1,
+ PDF_PRINTER: 2,
+ LOCAL_PRINTER: 3,
+ CLOUD_PRINTER: 4
+ };
/**
* An interface to the native Chromium printing system layer.
@@ -323,6 +323,14 @@ cr.define('print_preview', function() {
// Export
return {
- NativeLayer: NativeLayer
+ CapabilitiesResponse: CapabilitiesResponse,
+ LocalDestinationInfo: LocalDestinationInfo,
+ NativeInitialSettings: NativeInitialSettings,
+ NativeLayer: NativeLayer,
+ PreviewSettings: PreviewSettings,
+ PrinterSetupResponse: PrinterSetupResponse,
+ PrinterType: PrinterType,
+ PrivetPrinterDescription: PrivetPrinterDescription,
+ ProvisionalDestinationInfo: ProvisionalDestinationInfo,
};
});
diff --git a/chromium/chrome/browser/resources/print_preview/polymer3/demo.js b/chromium/chrome/browser/resources/print_preview/polymer3/demo.js
index 2e1415cc4d4..6a59ffd92d1 100644
--- a/chromium/chrome/browser/resources/print_preview/polymer3/demo.js
+++ b/chromium/chrome/browser/resources/print_preview/polymer3/demo.js
@@ -4,7 +4,7 @@
import 'chrome://resources/polymer/v3_0/paper-button/paper-button.js';
-import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer-element.js';
+import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
class HelloPolymer3Element extends PolymerElement {
static get template() {
diff --git a/chromium/chrome/browser/resources/print_preview/print_preview.html b/chromium/chrome/browser/resources/print_preview/print_preview.html
index f4e95893d95..d0e4cf1f3c7 100644
--- a/chromium/chrome/browser/resources/print_preview/print_preview.html
+++ b/chromium/chrome/browser/resources/print_preview/print_preview.html
@@ -1,6 +1,6 @@
<!doctype html>
<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading"
- $i18n{dark} $i18n{newprintpreviewlayout}>
+ $i18n{newprintpreviewlayout}>
<head>
<meta charset="utf-8">
<if expr="not optimize_webui">
@@ -13,16 +13,20 @@
touch-action: manipulation;
}
- html[dark] {
- background: rgb(189, 193, 198); /* --google-grey-400 */
+ @media (prefers-color-scheme: dark) {
+ html {
+ background: rgb(189, 193, 198); /* --google-grey-400 */
+ }
}
html[new-print-preview-layout] {
background: rgb(218, 220, 224); /* --google-grey-refresh-300 */
}
- html[new-print-preview-layout][dark] {
- background: rgb(95, 99, 104); /* --google-grey-refresh-700 */
+ @media (prefers-color-scheme: dark) {
+ html[new-print-preview-layout] {
+ background: rgb(95, 99, 104); /* --google-grey-refresh-700 */
+ }
}
html,
@@ -60,9 +64,11 @@
border-inline-start-width: 1px;
}
- [dark].loading body::before {
- background: rgb(40, 41, 44);
- border-color: rgba(255, 255, 255, .04);
+ @media (prefers-color-scheme: dark) {
+ .loading body::before {
+ background: rgb(40, 41, 44);
+ border-color: rgba(255, 255, 255, .04);
+ }
}
</style>
</head>
@@ -73,6 +79,5 @@
<link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
<link rel="stylesheet" href="chrome://resources/css/md_colors.css">
<link rel="import" href="ui/app.html">
- <link rel="import" href="chrome://resources/html/dark_mode.html">
</body>
</html>
diff --git a/chromium/chrome/browser/resources/print_preview/print_preview_resources.grd b/chromium/chrome/browser/resources/print_preview/print_preview_resources.grd
index 680483f0d16..41d460f7452 100644
--- a/chromium/chrome/browser/resources/print_preview/print_preview_resources.grd
+++ b/chromium/chrome/browser/resources/print_preview/print_preview_resources.grd
@@ -133,6 +133,12 @@
<structure name="IDR_PRINT_PREVIEW_PRINT_PREVIEW_UTILS_JS"
file="print_preview_utils.js"
type="chrome_html" />
+ <structure name="IDR_PRINT_PREVIEW_PRINT_DARK_MODE_BEHAVIOR_HTML"
+ file="dark_mode_behavior.html"
+ type="chrome_html" />
+ <structure name="IDR_PRINT_PREVIEW_PRINT_DARK_MODE_BEHAVIOR_JS"
+ file="dark_mode_behavior.js"
+ type="chrome_html" />
<structure name="IDR_PRINT_PREVIEW_DATA_DOCUMENT_INFO_HTML"
file="data/document_info.html"
type="chrome_html" />
diff --git a/chromium/chrome/browser/resources/print_preview/print_preview_utils.html b/chromium/chrome/browser/resources/print_preview/print_preview_utils.html
index bca9791024a..59e5c9657e4 100644
--- a/chromium/chrome/browser/resources/print_preview/print_preview_utils.html
+++ b/chromium/chrome/browser/resources/print_preview/print_preview_utils.html
@@ -1,5 +1,5 @@
-<link rel="import" href="chrome://resources/html/dark_mode.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-iconset-svg/iron-iconset-svg.html">
+<link rel="import" href="dark_mode_behavior.html">
<script src="print_preview_utils.js"></script>
diff --git a/chromium/chrome/browser/resources/print_preview/print_preview_utils.js b/chromium/chrome/browser/resources/print_preview/print_preview_utils.js
index 9d84d07311e..009f602c06e 100644
--- a/chromium/chrome/browser/resources/print_preview/print_preview_utils.js
+++ b/chromium/chrome/browser/resources/print_preview/print_preview_utils.js
@@ -68,12 +68,13 @@ function observerDepsDefined(args) {
function getSelectDropdownBackground(iconset, iconName, el) {
const serializer = new XMLSerializer();
const iconElement = iconset.createIcon(iconName, isRTL());
+ const inDarkMode = print_preview.DarkModeBehavior.inDarkMode();
const fillColor = getComputedStyle(el).getPropertyValue(
- inDarkMode() ? '--google-grey-refresh-500' : '--google-grey-600');
+ inDarkMode ? '--google-grey-refresh-500' : '--google-grey-600');
iconElement.style.fill = fillColor;
const serializedIcon = serializer.serializeToString(iconElement);
const uri = encodeURIComponent(serializedIcon);
- const arrowDownPath = inDarkMode() ?
+ const arrowDownPath = inDarkMode ?
'chrome://resources/images/dark/arrow_down.svg' :
'chrome://resources/images/arrow_down.svg';
return `url("data:image/svg+xml;charset=utf-8,${uri}"),` +
diff --git a/chromium/chrome/browser/resources/print_preview/ui/BUILD.gn b/chromium/chrome/browser/resources/print_preview/ui/BUILD.gn
index cefdf0cce22..488bf4143ba 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/BUILD.gn
+++ b/chromium/chrome/browser/resources/print_preview/ui/BUILD.gn
@@ -89,6 +89,7 @@ js_library("sidebar") {
":pages_settings",
":scaling_settings",
"..:cloud_print_interface",
+ "..:dark_mode_behavior",
"..:metrics",
"../data:destination",
"../data:state",
@@ -311,6 +312,7 @@ js_library("preview_area") {
":margin_control_container",
":plugin_proxy",
":settings_behavior",
+ "..:dark_mode_behavior",
"..:native_layer",
"../../pdf:pdf_scripting_api",
"../data:coordinate2d",
@@ -321,7 +323,6 @@ js_library("preview_area") {
"../data:size",
"../data:state",
"//ui/webui/resources/js:cr",
- "//ui/webui/resources/js:dark_mode",
"//ui/webui/resources/js:i18n_behavior",
"//ui/webui/resources/js:util",
"//ui/webui/resources/js:web_ui_listener_behavior",
@@ -347,6 +348,7 @@ js_library("margin_control") {
":input_behavior",
"../data:coordinate2d",
"../data:margins",
+ "../data:measurement_system",
"../data:size",
"//ui/webui/resources/js:i18n_behavior",
]
diff --git a/chromium/chrome/browser/resources/print_preview/ui/advanced_options_settings.html b/chromium/chrome/browser/resources/print_preview/ui/advanced_options_settings.html
index 180b59820cb..4cffcd9b8e9 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/advanced_options_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/advanced_options_settings.html
@@ -1,7 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="../data/destination.html">
<link rel="import" href="advanced_settings_dialog.html">
<link rel="import" href="print_preview_shared_css.html">
@@ -9,8 +8,8 @@
<dom-module id="print-preview-advanced-options-settings">
<template>
- <style include="print-preview-shared paper-button-style">
- paper-button {
+ <style include="print-preview-shared">
+ cr-button {
min-height: 32px;
text-align: center;
width: calc(100% - 2 * var(--print-preview-sidebar-margin));
@@ -19,10 +18,10 @@
<print-preview-settings-section>
<span slot="title"></span>
<div slot="controls">
- <paper-button id="button" disabled$="[[disabled]]"
+ <cr-button id="button" disabled$="[[disabled]]"
on-click="onButtonClick_">
$i18n{newShowAdvancedOptions}
- </paper-button>
+ </cr-button>
</div>
</print-preview-settings-section>
<template is="dom-if" if="[[showAdvancedDialog_]]" restamp>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.html b/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.html
index 36b3dbdb037..a81ba439ea2 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.html
@@ -1,10 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../metrics.html">
<link rel="import" href="../data/destination.html">
<link rel="import" href="advanced_settings_item.html">
@@ -16,13 +15,11 @@
<dom-module id="print-preview-advanced-settings-dialog">
<template>
- <style include="print-preview-shared paper-button-style cr-hidden-style">
- #dialog {
- --cr-dialog-native: {
- height: -webkit-fit-content;
- max-height: calc(100vh - 2 * var(--print-preview-dialog-margin));
- max-width: calc(100vw - 2 * var(--print-preview-dialog-margin));
- };
+ <style include="print-preview-shared cr-hidden-style">
+ #dialog::part(dialog) {
+ height: -webkit-fit-content;
+ max-height: calc(100vh - 2 * var(--print-preview-dialog-margin));
+ max-width: calc(100vw - 2 * var(--print-preview-dialog-margin));
}
print-preview-search-box {
@@ -54,12 +51,12 @@
</div>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelButtonClick_">
+ <cr-button class="cancel-button" on-click="onCancelButtonClick_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onApplyButtonClick_">
+ </cr-button>
+ <cr-button class="action-button" on-click="onApplyButtonClick_">
$i18n{advancedSettingsDialogConfirm}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.js b/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.js
index 4fadd89be5d..00abe9b1869 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_dialog.js
@@ -52,10 +52,21 @@ Polymer({
onKeydown_: function(e) {
e.stopPropagation();
const searchInput = this.$.searchBox.getSearchInput();
- if (e.key == 'Escape' &&
- (e.composedPath()[0] !== searchInput || !searchInput.value.trim())) {
+ const eventInSearchBox = e.composedPath().includes(searchInput);
+ if (e.key == 'Escape' && (!eventInSearchBox || !searchInput.value.trim())) {
this.$.dialog.cancel();
e.preventDefault();
+ return;
+ }
+
+ if (e.key == 'Enter' && !eventInSearchBox) {
+ const activeElementTag = e.composedPath()[0].tagName;
+ if (['CR-BUTTON', 'SELECT'].includes(activeElementTag)) {
+ return;
+ }
+ this.onApplyButtonClick_();
+ e.preventDefault();
+ return;
}
},
diff --git a/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_item.html b/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_item.html
index ee686cd27fb..2dd7432984d 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_item.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/advanced_settings_item.html
@@ -4,7 +4,7 @@
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/cr_elements/search_highlight_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="../print_preview_utils.html">
<link rel="import" href="../data/destination.html">
<link rel="import" href="highlight_utils.html">
@@ -13,7 +13,8 @@
<dom-module id="print-preview-advanced-settings-item">
<template>
- <style include="print-preview-shared md-select search-highlight-style cr-hidden-style">
+ <style include="print-preview-shared md-select search-highlight-style
+ cr-hidden-style">
:host {
display: flex;
min-height: 54px;
@@ -35,7 +36,6 @@
.label {
flex: 1;
- margin-inline-end: 10px;
min-width: 96px;
opacity: 0.87;
}
@@ -47,6 +47,11 @@
white-space: nowrap;
}
+ .value > * {
+ display: flex;
+ margin-inline-start: 10px;
+ }
+
cr-input {
width: 239px;
--cr-input-error-display: none;
diff --git a/chromium/chrome/browser/resources/print_preview/ui/app.html b/chromium/chrome/browser/resources/print_preview/ui/app.html
index 7ac6414b1bb..2e5816ecc93 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/app.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/app.html
@@ -29,8 +29,10 @@
user-select: none;
}
- :host-context([dark]) {
- background: var(--google-grey-900);
+ @media (prefers-color-scheme: dark) {
+ :host {
+ background: var(--google-grey-900);
+ }
}
:host([new-print-preview-layout_]) {
diff --git a/chromium/chrome/browser/resources/print_preview/ui/app.js b/chromium/chrome/browser/resources/print_preview/ui/app.js
index 3b6c9e675e0..afdf54feb0f 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/app.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/app.js
@@ -209,7 +209,7 @@ Polymer({
this.state === print_preview.State.READY &&
this.openDialogs_.length === 0) {
const activeElementTag = e.path[0].tagName;
- if (['PAPER-BUTTON', 'BUTTON', 'SELECT', 'A', 'CR-CHECKBOX'].includes(
+ if (['CR-BUTTON', 'BUTTON', 'SELECT', 'A', 'CR-CHECKBOX'].includes(
activeElementTag)) {
return;
}
@@ -262,7 +262,8 @@ Polymer({
// sidebar, so that cloud printers can be selected automatically.
if (settings.cloudPrintURL) {
this.initializeCloudPrint_(
- settings.cloudPrintURL, settings.isInAppKioskMode);
+ settings.cloudPrintURL, settings.isInAppKioskMode,
+ settings.uiLocale);
}
this.$.documentInfo.init(
settings.previewModifiable, settings.documentTitle,
@@ -294,12 +295,13 @@ Polymer({
* Called when Google Cloud Print integration is enabled.
* @param {string} cloudPrintUrl The URL to use for cloud print servers.
* @param {boolean} appKioskMode Whether the browser is in app kiosk mode.
+ * @param {string} uiLocale The UI locale.
* @private
*/
- initializeCloudPrint_: function(cloudPrintUrl, appKioskMode) {
+ initializeCloudPrint_: function(cloudPrintUrl, appKioskMode, uiLocale) {
assert(!this.cloudPrintInterface_);
this.cloudPrintInterface_ = cloudprint.getCloudPrintInterface(
- cloudPrintUrl, assert(this.nativeLayer_), appKioskMode);
+ cloudPrintUrl, assert(this.nativeLayer_), appKioskMode, uiLocale);
this.tracker_.add(
assert(this.cloudPrintInterface_).getEventTarget(),
cloudprint.CloudPrintInterfaceEventType.SUBMIT_DONE,
@@ -556,21 +558,26 @@ Polymer({
}
if (copies > 0 && this.getSetting('copies').available) {
- this.setSetting('copies', copies);
+ this.setSetting('copies', copies, true);
}
- if (duplex !== print_preview.DuplexMode.UNKNOWN_DUPLEX_MODE &&
- this.getSetting('duplex').available) {
+ if (duplex === print_preview.DuplexMode.UNKNOWN_DUPLEX_MODE) {
+ return;
+ }
+
+ if (this.getSetting('duplex').available) {
this.setSetting(
'duplex',
duplex === print_preview.DuplexMode.LONG_EDGE ||
- duplex === print_preview.DuplexMode.SHORT_EDGE);
+ duplex === print_preview.DuplexMode.SHORT_EDGE,
+ true);
}
- if (duplex !== print_preview.DuplexMode.UNKNOWN_DUPLEX_MODE &&
- duplex !== print_preview.DuplexMode.SIMPLEX &&
+
+ if (duplex !== print_preview.DuplexMode.SIMPLEX &&
this.getSetting('duplexShortEdge').available) {
this.setSetting(
- 'duplexShortEdge', duplex === print_preview.DuplexMode.SHORT_EDGE);
+ 'duplexShortEdge', duplex === print_preview.DuplexMode.SHORT_EDGE,
+ true);
}
},
diff --git a/chromium/chrome/browser/resources/print_preview/ui/button_strip.html b/chromium/chrome/browser/resources/print_preview/ui/button_strip.html
index c0dda930cfd..e6d16e5e913 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/button_strip.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/button_strip.html
@@ -1,17 +1,16 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../data/destination.html">
<link rel="import" href="../data/state.html">
<link rel="import" href="strings.html">
<dom-module id="print-preview-button-strip">
<template>
- <style include="paper-button-style">
+ <style>
:host {
display: flex;
flex-direction: row;
@@ -21,31 +20,33 @@
padding-top: 16px;
}
- :host-context(html:not([dark])) {
- background-color: white;
+ @media (prefers-color-scheme: light) {
+ :host {
+ background-color: white;
+ }
}
- :host paper-button:not(:last-child) {
+ :host cr-button:not(:last-child) {
margin-inline-end: 8px;
}
- :host paper-button:last-child {
+ :host cr-button:last-child {
margin-inline-end: 0;
}
</style>
<if expr="not is_win">
- <paper-button class="cancel-button" on-click="onCancelClick_">
+ <cr-button class="cancel-button" on-click="onCancelClick_">
$i18n{cancel}
- </paper-button>
+ </cr-button>
</if>
- <paper-button class="action-button" on-click="onPrintClick_"
+ <cr-button class="action-button" on-click="onPrintClick_"
disabled$="[[!printButtonEnabled_]]">
[[printButtonLabel_]]
- </paper-button>
+ </cr-button>
<if expr="is_win">
- <paper-button class="cancel-button" on-click="onCancelClick_">
+ <cr-button class="cancel-button" on-click="onCancelClick_">
$i18n{cancel}
- </paper-button>
+ </cr-button>
</if>
</template>
<script src="button_strip.js"></script>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/button_strip.js b/chromium/chrome/browser/resources/print_preview/ui/button_strip.js
index ffcfb2e4e93..971a6c3e751 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/button_strip.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/button_strip.js
@@ -9,6 +9,8 @@ Polymer({
/** @type {!print_preview.Destination} */
destination: Object,
+ firstLoad: Boolean,
+
/** @type {!print_preview.State} */
state: {
type: Number,
@@ -71,10 +73,9 @@ Polymer({
break;
case (print_preview.State.READY):
this.printButtonEnabled_ = true;
- if (this.lastState_ != this.state &&
- (document.activeElement == null ||
- document.activeElement == document.body)) {
- this.$$('paper-button.action-button').focus();
+ if (this.firstLoad) {
+ this.$$('cr-button.action-button').focus();
+ this.fire('print-button-focused');
}
break;
default:
diff --git a/chromium/chrome/browser/resources/print_preview/ui/color_settings.html b/chromium/chrome/browser/resources/print_preview/ui/color_settings.html
index 9d3b121ff25..030305abcd7 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/color_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/color_settings.html
@@ -1,6 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="print_preview_shared_css.html">
<link rel="import" href="select_behavior.html">
<link rel="import" href="settings_behavior.html">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/copies_settings.js b/chromium/chrome/browser/resources/print_preview/ui/copies_settings.js
index 3dfc1aa2a71..fad6d80050a 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/copies_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/copies_settings.js
@@ -42,7 +42,8 @@ Polymer({
* @private
*/
onInputChanged_: function() {
- if (this.currentValue_ !== '') {
+ if (this.currentValue_ !== '' &&
+ this.currentValue_ !== this.getSettingValue('copies').toString()) {
this.setSetting(
'copies', this.inputValid_ ? parseInt(this.currentValue_, 10) : 1);
}
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_dialog.html b/chromium/chrome/browser/resources/print_preview/ui/destination_dialog.html
index 624b32bd370..a941dae7276 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_dialog.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_dialog.html
@@ -1,22 +1,21 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<!-- The imports below are needed as an action-link is added to the promo-text
div to create the cloud print "Sign in" link when this element is
attached. -->
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/event_tracker.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/list_property_update_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../icons.html">
<link rel="import" href="../metrics.html">
<link rel="import" href="../native_layer.html">
@@ -35,19 +34,20 @@
<dom-module id="print-preview-destination-dialog">
<template>
- <style include="print-preview-shared action-link md-select cr-hidden-style throbber paper-button-style">
- #dialog {
- --cr-dialog-native: {
- height: calc(100vh - 2 * var(--print-preview-dialog-margin));
- max-width: 640px;
- width: calc(100vw - 2 * var(--print-preview-dialog-margin));
- };
- --cr-dialog-wrapper: {
- height: calc(100vh - 2 * var(--print-preview-dialog-margin));
- };
- --cr-dialog-body-container: {
- flex: 1;
- };
+ <style include="print-preview-shared action-link md-select cr-hidden-style
+ throbber">
+ #dialog::part(dialog) {
+ height: calc(100vh - 2 * var(--print-preview-dialog-margin));
+ max-width: 640px;
+ width: calc(100vw - 2 * var(--print-preview-dialog-margin));
+ }
+
+ #dialog::part(wrapper) {
+ height: calc(100vh - 2 * var(--print-preview-dialog-margin));
+ }
+
+ #dialog::part(body-container) {
+ flex: 1;
}
print-preview-search-box {
@@ -57,7 +57,7 @@
.user-info {
font-size: calc(13 / 15 * 1em);
- line-height: normal;
+ line-height: calc(20 / 15 * 1em);
margin-bottom: 14px;
margin-top: 8px;
}
@@ -78,7 +78,7 @@
justify-content: space-between;
}
- paper-button {
+ cr-button {
font-size: calc(12 / 13 * 1em);
}
@@ -91,8 +91,10 @@
padding: 0;
}
- :host-context([dark]) #dialog #promos {
- background: rgb(50, 54, 57);
+ @media (prefers-color-scheme: dark) {
+ #dialog #promos {
+ background: rgb(50, 54, 57);
+ }
}
#dialog .promo {
@@ -130,12 +132,14 @@
padding: 12px 0;
}
- #invitationPromo paper-button {
+ #invitationPromo cr-button {
margin: 0 4px;
}
- :host-context(html:not([dark])) #invitationPromo paper-button {
- background-color: white;
+ @media (prefers-color-scheme: light) {
+ #invitationPromo cr-button {
+ background-color: white;
+ }
}
#invitationPromo invitation-details {
@@ -154,8 +158,7 @@
<select class="md-select account-select"
aria-labelledby="accountSelectLabel" on-change="onUserChange_">
<template is="dom-repeat" items="[[users]]">
- <option selected="[[isSelected_(item, activeUser)]]"
- value="[[item]]">
+ <option value="[[item]]">
[[item]]
</option>
</template>
@@ -163,8 +166,7 @@
</select>
</div>
<print-preview-search-box id="searchBox"
- label="$i18n{searchBoxPlaceholder}" search-query="{{searchQuery_}}"
- autofocus>
+ label="$i18n{searchBoxPlaceholder}" search-query="{{searchQuery_}}">
</print-preview-search-box>
</div>
<div slot="body">
@@ -180,12 +182,12 @@
</print-preview-provisional-destination-resolver>
</div>
<div slot="button-container">
- <paper-button on-click="onOpenSettingsPrintPage_">
+ <cr-button on-click="onOpenSettingsPrintPage_">
$i18n{manage}
- </paper-button>
- <paper-button class="cancel-button" on-click="onCancelButtonClick_">
+ </cr-button>
+ <cr-button class="cancel-button" on-click="onCancelButtonClick_">
$i18n{cancel}
- </paper-button>
+ </cr-button>
</div>
<div id="promos" slot="footer" hidden="[[!shouldShowFooter_(
shouldShowCloudPrintPromo_, invitation_)]]">
@@ -199,12 +201,12 @@
<div class="promo" id="invitationPromo" hidden="[[!invitation_]]">
<div inner-h-t-m-l="[[getInvitationText_(invitation_)]]"></div>
<div class="invitation-buttons">
- <paper-button on-click="onInvitationAcceptClick_">
+ <cr-button on-click="onInvitationAcceptClick_">
[[getAcceptButtonText_(invitation_)]]
- </paper-button>
- <paper-button on-click="onInvitationRejectClick_">
+ </cr-button>
+ <cr-button on-click="onInvitationRejectClick_">
$i18n{reject}
- </paper-button>
+ </cr-button>
<div id="invitation-process-throbber" class="throbber" hidden></div>
</div>
<div class="invitation-details">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_dialog.js b/chromium/chrome/browser/resources/print_preview/ui/destination_dialog.js
index bf05c1a4445..5c30560c050 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_dialog.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_dialog.js
@@ -22,7 +22,7 @@ Polymer({
activeUser: {
type: String,
- observer: 'updateDestinationsAndInvitations_',
+ observer: 'onActiveUserChange_',
},
currentDestinationAccount: String,
@@ -138,10 +138,6 @@ Polymer({
this.updateDestinations_.bind(this));
this.tracker_.add(
destinationStore,
- print_preview.DestinationStore.EventType.DESTINATIONS_RESET,
- () => this.destinations_ = []);
- this.tracker_.add(
- destinationStore,
print_preview.DestinationStore.EventType.DESTINATION_SEARCH_DONE,
this.updateDestinationsAndInvitations_.bind(this));
this.initialized_ = true;
@@ -161,6 +157,15 @@ Polymer({
},
/** @private */
+ onActiveUserChange_: function() {
+ if (this.activeUser) {
+ this.$$('select').value = this.activeUser;
+ }
+
+ this.updateDestinationsAndInvitations_();
+ },
+
+ /** @private */
updateDestinationsAndInvitations_: function() {
if (!this.initialized_) {
return;
@@ -282,10 +287,21 @@ Polymer({
show: function() {
this.$.dialog.showModal();
+ // Note: Manually focusing here instead of using autofocus, as it is
+ // currently not possible to validate refocusing of the search input if
+ // autofocus is used. See https://crbug.com/985637 and
+ // https://crbug.com/985636. Autofocus can be restored when one or both of
+ // these issues are resolved.
+ this.$.searchBox.focus();
this.loadingDestinations_ = this.destinationStore === undefined ||
this.destinationStore.isPrintDestinationSearchInProgress;
this.metrics_.record(
print_preview.Metrics.DestinationSearchBucket.DESTINATION_SHOWN);
+ if (this.activeUser) {
+ Polymer.RenderStatus.beforeNextRender(assert(this.$$('select')), () => {
+ this.$$('select').value = this.activeUser;
+ });
+ }
this.$.printList.forceIronResize();
},
@@ -295,11 +311,6 @@ Polymer({
},
/** @private */
- isSelected_: function(account) {
- return account == this.activeUser;
- },
-
- /** @private */
onSignInClick_: function() {
this.metrics_.record(
print_preview.Metrics.DestinationSearchBucket.SIGNIN_TRIGGERED);
@@ -387,19 +398,12 @@ Polymer({
const account = select.value;
if (account) {
this.loadingDestinations_ = true;
- this.destinations_ = [];
this.fire('account-change', account);
this.metrics_.record(
print_preview.Metrics.DestinationSearchBucket.ACCOUNT_CHANGED);
} else {
+ select.value = this.activeUser;
print_preview.NativeLayer.getInstance().signIn(true);
- const options = select.querySelectorAll('option');
- for (let i = 0; i < options.length; i++) {
- if (options[i].value == this.activeUser) {
- select.selectedIndex = i;
- break;
- }
- }
this.metrics_.record(
print_preview.Metrics.DestinationSearchBucket.ADD_ACCOUNT_SELECTED);
}
@@ -419,6 +423,10 @@ Polymer({
if (this.shouldShowCloudPrintPromo_) {
this.metrics_.record(
print_preview.Metrics.DestinationSearchBucket.SIGNIN_PROMPT);
+ } else {
+ // Since the sign in link/dismiss promo button is disappearing, focus the
+ // search box.
+ this.$.searchBox.focus();
}
},
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_list.html b/chromium/chrome/browser/resources/print_preview/ui/destination_list.html
index 85956ce117b..9191f1caec1 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_list.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_list.html
@@ -53,8 +53,10 @@
background-color: rgb(228, 236, 247);
}
- :host-context([dark]) .list-item:-webkit-any(:hover, :focus) {
- background-color: var(--cr-menu-background-focus-color);
+ @media (prefers-color-scheme: dark) {
+ .list-item:-webkit-any(:hover, :focus) {
+ background-color: var(--cr-menu-background-focus-color);
+ }
}
.list-item:focus {
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_list.js b/chromium/chrome/browser/resources/print_preview/ui/destination_list.js
index 59ee859021c..c513269a193 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_list.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_list.js
@@ -68,9 +68,7 @@ Polymer({
}
this.updateList(
- 'matchingDestinations_',
- destination => destination.origin + '/' + destination.id + '/' +
- destination.connectionStatusText,
+ 'matchingDestinations_', destination => destination.key,
this.searchQuery ?
this.destinations.filter(
d => d.matches(/** @type {!RegExp} */ (this.searchQuery))) :
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_list_item.html b/chromium/chrome/browser/resources/print_preview/ui/destination_list_item.html
index 8a1900fc25d..5e6056eb752 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_list_item.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_list_item.html
@@ -49,8 +49,10 @@
transition: opacity 150ms;
}
- :host-context([dark]) iron-icon {
- fill: var(--google-grey-refresh-500);
+ @media (prefers-color-scheme: dark) {
+ iron-icon {
+ fill: var(--google-grey-refresh-500);
+ }
}
.name {
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_select.html b/chromium/chrome/browser/resources/print_preview/ui/destination_select.html
index d8369b50966..2b7cb3cec17 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_select.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_select.html
@@ -2,7 +2,7 @@
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-iconset-svg/iron-iconset-svg.html">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_settings.html b/chromium/chrome/browser/resources/print_preview/ui/destination_settings.html
index a24b038553d..96c34177251 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_settings.html
@@ -61,6 +61,7 @@
<print-preview-user-manager id="userManager" active-user="{{activeUser_}}"
app-kiosk-mode="[[appKioskMode]]"
cloud-print-disabled="{{cloudPrintDisabled_}}"
+ cloud-print-interface="[[cloudPrintInterface]]"
users="{{users_}}" destination-store="[[destinationStore_]]"
invitation-store="[[invitationStore_]]"
should-reload-cookies="[[isDialogOpen_]]">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_settings.js b/chromium/chrome/browser/resources/print_preview/ui/destination_settings.js
index 0701852c2eb..7e5266744e8 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_settings.js
@@ -63,6 +63,8 @@ Polymer({
observer: 'onErrorChanged_',
},
+ firstLoad: Boolean,
+
/** @type {!print_preview.State} */
state: Number,
@@ -126,6 +128,9 @@ Polymer({
users_: Array,
},
+ /** @private {string} */
+ lastUser_: '',
+
/** @private {!EventTracker} */
tracker_: new EventTracker(),
@@ -167,11 +172,61 @@ Polymer({
/** @private */
onCloudPrintInterfaceSet_: function() {
const cloudPrintInterface = assert(this.cloudPrintInterface);
- this.$.userManager.setCloudPrintInterface(cloudPrintInterface);
this.destinationStore_.setCloudPrintInterface(cloudPrintInterface);
this.invitationStore_.setCloudPrintInterface(cloudPrintInterface);
},
+ /** @private */
+ onActiveUserChanged_: function() {
+ // Re-filter the dropdown destinations for the new account.
+ if (!this.isDialogOpen_) {
+ // Don't update the destination settings UI while the dialog is open in
+ // front of it.
+ this.updateDropdownDestinations_();
+ }
+
+ if (!this.destination ||
+ this.destination.origin !== print_preview.DestinationOrigin.COOKIES) {
+ // Active user changing doesn't impact non-cookie based destinations.
+ return;
+ }
+
+ if (this.destination.account === this.activeUser_) {
+ // If the current destination belongs to the new account and the dialog
+ // was waiting for sign in, update the state.
+ if (this.destinationState === print_preview.DestinationState.SELECTED) {
+ this.destinationState = this.destination.capabilities ?
+ print_preview.DestinationState.UPDATED :
+ print_preview.DestinationState.SET;
+ }
+ return;
+ }
+
+ if (this.isDialogOpen_) {
+ // Do not update the selected destination if the dialog is open, as this
+ // will change the destination settings UI behind the dialog, and the user
+ // may be selecting a new destination in the dialog anyway. Wait for the
+ // user to select a destination or cancel.
+ return;
+ }
+
+ // Destination belongs to a different account. Reset the destination to the
+ // most recent destination associated with the new account, or the default.
+ const recent = this.displayedDestinations_.find(d => {
+ return d.origin !== print_preview.DestinationOrigin.COOKIES ||
+ d.account === this.activeUser_;
+ });
+ if (recent) {
+ const success = this.destinationStore_.selectRecentDestinationByKey(
+ print_preview.createRecentDestinationKey(recent),
+ this.displayedDestinations_);
+ if (success) {
+ return;
+ }
+ }
+ this.destinationStore_.selectDefaultDestination();
+ },
+
/**
* @param {string} defaultPrinter The system default printer ID.
* @param {string} serializedDefaultDestinationRulesStr String with rules for
@@ -192,27 +247,18 @@ Polymer({
},
/** @private */
- onActiveUserChanged_: function() {
- if (!this.activeUser_ || !this.destination) {
- return;
- }
-
- if (this.destinationState === print_preview.DestinationState.SELECTED &&
- this.destination.origin === print_preview.DestinationOrigin.COOKIES) {
- // Adjust states if the destination is now ready to be printed to.
- this.destinationState = this.destination.capabilities ?
- print_preview.DestinationState.UPDATED :
- print_preview.DestinationState.SET;
+ onDestinationSelect_: function() {
+ // If the user selected a destination in the dialog after changing the
+ // active user, do the UI updates that were previously deferred.
+ if (this.isDialogOpen_ && this.lastUser_ !== this.activeUser_) {
+ this.updateDropdownDestinations_();
}
- this.updateDropdownDestinations_();
- },
- /** @private */
- onDestinationSelect_: function() {
if (this.state === print_preview.State.FATAL_ERROR) {
// Don't let anything reset if there is a fatal error.
return;
}
+
const destination = this.destinationStore_.selectedDestination;
if (!!this.activeUser_ ||
destination.origin !== print_preview.DestinationOrigin.COOKIES) {
@@ -392,6 +438,7 @@ Polymer({
this.invitationStore_.startLoadingInvitations(this.activeUser_);
}
this.$.destinationDialog.get().show();
+ this.lastUser_ = this.activeUser_;
this.isDialogOpen_ = true;
} else {
const success = this.destinationStore_.selectRecentDestinationByKey(
@@ -415,8 +462,10 @@ Polymer({
onDialogClose_: function() {
// Reset the select value if the user dismissed the dialog without
// selecting a new destination.
+ if (this.lastUser_ != this.activeUser_) {
+ this.updateDropdownDestinations_();
+ }
this.updateDestinationSelect_();
- this.$.destinationSelect.focus();
this.isDialogOpen_ = false;
},
@@ -434,8 +483,14 @@ Polymer({
return;
}
+ const shouldFocus =
+ this.destinationState !== print_preview.DestinationState.SET &&
+ !this.firstLoad;
Polymer.RenderStatus.beforeNextRender(this.$.destinationSelect, () => {
this.$.destinationSelect.updateDestination();
+ if (shouldFocus) {
+ this.$.destinationSelect.focus();
+ }
});
},
});
diff --git a/chromium/chrome/browser/resources/print_preview/ui/duplex_settings.html b/chromium/chrome/browser/resources/print_preview/ui/duplex_settings.html
index 834247c015d..a1382d8bc8d 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/duplex_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/duplex_settings.html
@@ -2,7 +2,7 @@
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-iconset-svg/iron-iconset-svg.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-meta/iron-meta.html">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/header.html b/chromium/chrome/browser/resources/print_preview/ui/header.html
index 4a88f67ecc4..8e92fdd887f 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/header.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/header.html
@@ -1,10 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../data/destination.html">
<link rel="import" href="../data/state.html">
<link rel="import" href="../icons.html">
@@ -14,15 +13,17 @@
<dom-module id="print-preview-header">
<template>
- <style include="paper-button-style">
+ <style>
:host {
border-bottom: var(--print-preview-settings-border);
display: block;
padding: 20px var(--print-preview-sidebar-margin) 8px;
}
- :host-context(html:not([dark])) {
- background-color: white;
+ @media (prefers-color-scheme: light) {
+ :host {
+ background-color: white;
+ }
}
.title-container {
@@ -56,11 +57,11 @@
padding-top: 16px;
}
- #button-strip paper-button:first-child {
+ #button-strip cr-button:first-child {
margin-inline-end: 8px;
}
- #button-strip paper-button:last-child {
+ #button-strip cr-button:last-child {
margin-inline-end: 0;
}
@@ -83,18 +84,18 @@
</span>
<div id="button-strip">
<if expr="not is_win">
- <paper-button class="cancel-button" on-click="onCancelClick_">
+ <cr-button class="cancel-button" on-click="onCancelClick_">
$i18n{cancel}
- </paper-button>
+ </cr-button>
</if>
- <paper-button class="action-button" on-click="onPrintClick_"
+ <cr-button class="action-button" on-click="onPrintClick_"
disabled$="[[!printButtonEnabled_]]">
[[printButtonLabel_]]
- </paper-button>
+ </cr-button>
<if expr="is_win">
- <paper-button class="cancel-button" on-click="onCancelClick_">
+ <cr-button class="cancel-button" on-click="onCancelClick_">
$i18n{cancel}
- </paper-button>
+ </cr-button>
</if>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/header.js b/chromium/chrome/browser/resources/print_preview/ui/header.js
index 2731225c3a4..21dc46bc04a 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/header.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/header.js
@@ -26,6 +26,8 @@ Polymer({
/** @type {!print_preview.Error} */
error: Number,
+ firstLoad: Boolean,
+
/** @type {!print_preview.State} */
state: Number,
@@ -64,9 +66,6 @@ Polymer({
'updatePrintButtonLabel_(destination.id)'
],
- /** @private {!print_preview.State} */
- lastState_: print_preview.State.NOT_READY,
-
/** @private */
onPrintClick_: function() {
this.fire('print-requested');
@@ -144,10 +143,9 @@ Polymer({
const labelInfo = this.computeLabelInfo_();
this.summary_ = this.getSummary_(labelInfo);
this.summaryLabel_ = this.getSummaryLabel_(labelInfo);
- if (this.lastState_ != this.state &&
- (document.activeElement == null ||
- document.activeElement == document.body)) {
- this.$$('paper-button.action-button').focus();
+ if (this.firstLoad) {
+ this.$$('cr-button.action-button').focus();
+ this.fire('print-button-focused');
}
break;
case (print_preview.State.FATAL_ERROR):
@@ -161,7 +159,6 @@ Polymer({
this.printButtonEnabled_ = false;
break;
}
- this.lastState_ = this.state;
},
/**
@@ -185,6 +182,10 @@ Polymer({
* @private
*/
getSummary_: function(labelInfo) {
+ if (labelInfo.numSheets === 0) {
+ return '';
+ }
+
let html = loadTimeData.getStringF(
'printPreviewSummaryFormatShort',
'<b>' + labelInfo.numSheets.toLocaleString() + '</b>',
diff --git a/chromium/chrome/browser/resources/print_preview/ui/header_new.html b/chromium/chrome/browser/resources/print_preview/ui/header_new.html
index 88746dd198d..9983f9f2b24 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/header_new.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/header_new.html
@@ -20,8 +20,10 @@
padding: 20px var(--print-preview-sidebar-margin) 12px;
}
- :host-context(html:not([dark])) {
- background-color: white;
+ @media (prefers-color-scheme: light) {
+ :host {
+ background-color: white;
+ }
}
#headerContainer {
@@ -59,7 +61,7 @@
alt="" title="$i18n{managedSettings}">
</iron-icon>
</div>
- <span class="summary" aria-label$="[[summaryLabel_]]">[[summary_]]</span>
+ <span class="summary">[[summary_]]</span>
</template>
<script src="header_new.js"></script>
</dom-module>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/header_new.js b/chromium/chrome/browser/resources/print_preview/ui/header_new.js
index d9b344a8421..9d639b1f9d0 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/header_new.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/header_new.js
@@ -36,12 +36,6 @@ Polymer({
type: String,
value: null,
},
-
- /** @private {?string} */
- summaryLabel_: {
- type: String,
- value: null,
- },
},
observers: [
@@ -102,20 +96,16 @@ Polymer({
case (print_preview.State.PRINTING):
this.summary_ = loadTimeData.getString(
this.isPdfOrDrive_() ? 'saving' : 'printing');
- this.summaryLabel_ = this.summary_;
break;
case (print_preview.State.READY):
const labelInfo = this.computeLabelInfo_();
this.summary_ = this.getSummary_(labelInfo);
- this.summaryLabel_ = this.getSummaryLabel_(labelInfo);
break;
case (print_preview.State.FATAL_ERROR):
this.summary_ = this.getErrorMessage_();
- this.summaryLabel_ = this.getErrorMessage_();
break;
default:
this.summary_ = null;
- this.summaryLabel_ = null;
break;
}
},
@@ -141,19 +131,10 @@ Polymer({
* @private
*/
getSummary_: function(labelInfo) {
- return loadTimeData.getStringF(
- 'printPreviewNewSummaryFormatShort',
- labelInfo.numSheets.toLocaleString(), labelInfo.summaryLabel);
- },
-
- /**
- * @param {!print_preview.HeaderNew.LabelInfo} labelInfo
- * @return {string}
- * @private
- */
- getSummaryLabel_: function(labelInfo) {
- return loadTimeData.getStringF(
- 'printPreviewNewSummaryFormatShort',
- labelInfo.numSheets.toLocaleString(), labelInfo.summaryLabel);
+ return labelInfo.numSheets === 0 ?
+ '' :
+ loadTimeData.getStringF(
+ 'printPreviewNewSummaryFormatShort',
+ labelInfo.numSheets.toLocaleString(), labelInfo.summaryLabel);
},
});
diff --git a/chromium/chrome/browser/resources/print_preview/ui/input_behavior.js b/chromium/chrome/browser/resources/print_preview/ui/input_behavior.js
index 79aa7cc3b9f..016e4f2bfc8 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/input_behavior.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/input_behavior.js
@@ -29,8 +29,9 @@ cr.define('print_preview', function() {
},
/**
- * @return {!CrInputElement} The cr-input element the behavior should use.
- * Should be overridden by elements using this behavior.
+ * @return {(!CrInputElement|!HTMLInputElement)} The cr-input or input
+ * element the behavior should use. Should be overridden by elements
+ * using this behavior.
*/
getInput: function() {},
@@ -52,7 +53,7 @@ cr.define('print_preview', function() {
* @private
*/
onKeyDown_: function(event) {
- if (event.code != 'Enter') {
+ if (event.code != 'Enter' && event.code != 'Tab') {
return;
}
diff --git a/chromium/chrome/browser/resources/print_preview/ui/layout_settings.html b/chromium/chrome/browser/resources/print_preview/ui/layout_settings.html
index 8ec91736c59..b3c22b26c7c 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/layout_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/layout_settings.html
@@ -1,6 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="print_preview_shared_css.html">
<link rel="import" href="select_behavior.html">
<link rel="import" href="settings_behavior.html">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/margin_control.html b/chromium/chrome/browser/resources/print_preview/ui/margin_control.html
index 904ea128f1a..4aa2d7e9dc9 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/margin_control.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/margin_control.html
@@ -1,18 +1,19 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input_style_css.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="../print_preview_utils.html">
<link rel="import" href="../data/coordinate2d.html">
<link rel="import" href="../data/margins.html">
+<link rel="import" href="../data/measurement_system.html">
<link rel="import" href="../data/size.html">
<link rel="import" href="input_behavior.html">
<link rel="import" href="strings.html">
<dom-module id="print-preview-margin-control">
<template>
- <style>
+ <style include="cr-input-style">
:host {
display: block;
position: absolute;
@@ -28,15 +29,15 @@
pointer-events: none;
}
- :host([side=top]),
- :host([side=bottom]) {
+ :host([side=top]) #lineContainer,
+ :host([side=bottom]) #lineContainer {
cursor: ns-resize;
padding: 8px 0;
width: 100%;
}
- :host([side=left]),
- :host([side=right]) {
+ :host([side=left]) #lineContainer,
+ :host([side=right]) #lineContainer {
cursor: ew-resize;
height: 100%;
padding: 0 8px;
@@ -46,8 +47,10 @@
border: 1px dashed var(--google-blue-500);
}
- :host-context([dark]) #line {
- border-color: var(--google-blue-refresh-300);
+ @media (prefers-color-scheme: dark) {
+ #line {
+ border-color: var(--google-blue-refresh-300);
+ }
}
:host([side=top]) #line,
@@ -60,56 +63,99 @@
height: 100%;
}
- #textbox {
- --cr-input-error-display: none;
- --cr-input-row-container: {
- min-height: 25px;
- }
- box-sizing: border-box;
+ #row-container {
+ border-radius: 4px;
font-size: 0.8rem;
+ min-height: 25px;
+ overflow: hidden;
padding: 1px;
position: absolute;
- text-align: center;
width: 60px;
}
- :host-context(html:not([dark])) #textbox {
- --cr-input-background-color: var(--cr-primary-text-color);
- --cr-input-color: white;
- color: white;
+ @media (prefers-color-scheme: light) {
+ #row-container {
+ --cr-input-background-color: var(--cr-primary-text-color);
+ --cr-input-color: white;
+ background-color: var(--cr-primary-text-color);
+ color: white;
+ }
}
- :host-context([dark]) #textbox {
- --cr-input-background-color: #1b1c1e; /* GG900 + 30% black */
- --cr-input-color: var(--cr-primary-text-color);
+ @media (prefers-color-scheme: dark) {
+ #row-container {
+ --cr-input-background-color: rgb(27, 28, 30); /* GG900 + 30% black */
+ --cr-input-color: var(--cr-primary-text-color);
+ background-color: rgb(27, 28, 30); /* GG900 + 30% black */
+ color: var(--cr-primary-text-color);
+ }
}
- :host([side=top]) #textbox {
+ :host([side=top]) #row-container {
left: 50%;
- top: 8px;
+ top: 9px;
}
- :host([side=right]) #textbox {
- right: 8px;
+ :host([side=right]) #row-container {
+ right: 9px;
top: 50%;
}
- :host([side=bottom]) #textbox {
- bottom: 8px;
+ :host([side=bottom]) #row-container {
+ bottom: 9px;
right: 50%;
}
- :host([side=left]) #textbox {
+ :host([side=left]) #row-container {
bottom: 50%;
- left: 8px;
+ left: 9px;
+ }
+
+ :host([disabled]) #row-container {
+ opacity: var(--cr-disabled-opacity);
+ }
+
+ :host([invalid]) #input {
+ caret-color: var(--cr-input-error-color);
+ }
+
+ :host([invalid]) #underline {
+ border-color: var(--cr-input-error-color);
+ }
+
+ #row-container,
+ #input-container {
+ align-items: center;
+ display: flex;
+ }
+
+ #input-container {
+ position: relative;
+ }
+
+ #input {
+ padding-inline-end: 0;
+ text-align: end;
+ }
+
+ #unit {
+ padding-inline-end: 8px;
}
</style>
- <div id="line"></div>
- <cr-input id="textbox" aria-hidden$="[[getAriaHidden_(invisible)]]"
- aria-label$="[[i18n(side)]]" type="text" disabled="[[disabled]]"
- invalid="[[invalid]]" on-blur="onBlur_" on-focus="onFocus_"
- data-timeout-delay="1000">
- </cr-input>
+ <div id="lineContainer">
+ <div id="line"></div>
+ </div>
+ <div id="row-container">
+ <div id="input-container">
+ <input id="input" disabled="[[disabled]]" aria-label$="[[i18n(side)]]"
+ aria-hidden$="[[getAriaHidden_(invisible)]]"
+ on-focus="onFocus_" on-blur="onBlur_" on-change="onInputChange_"
+ data-timeout-delay="1000">
+ <span id="unit">[[measurementSystem.unitSymbol]]</span>
+ </div>
+ <div id="underline"></div>
+ </div>
+ </div>
</template>
<script src="margin_control.js"></script>
</dom-module>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/margin_control.js b/chromium/chrome/browser/resources/print_preview/ui/margin_control.js
index b4588fab068..d3ccb88904f 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/margin_control.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/margin_control.js
@@ -20,6 +20,7 @@ Polymer({
disabled: {
type: Boolean,
reflectToAttribute: true,
+ observer: 'onDisabledChange_',
},
side: {
@@ -27,7 +28,10 @@ Polymer({
reflectToAttribute: true,
},
- invalid: Boolean,
+ invalid: {
+ type: Boolean,
+ reflectToAttribute: true,
+ },
invisible: {
type: Boolean,
@@ -35,6 +39,16 @@ Polymer({
observer: 'onClipSizeChange_',
},
+ /** @type {?print_preview.MeasurementSystem} */
+ measurementSystem: Object,
+
+ /** @private {boolean} */
+ focused_: {
+ type: Boolean,
+ reflectToAttribute: true,
+ value: false,
+ },
+
/** @private {number} */
positionInPts_: {
type: Number,
@@ -76,17 +90,26 @@ Polymer({
'input-change': 'onInputChange_',
},
- /** @return {!CrInputElement} The cr-input element for InputBehavior. */
+ /** @return {!HTMLInputElement} The input element for InputBehavior. */
getInput: function() {
- return this.$.textbox;
+ return this.$.input;
},
- /** @param {string} value New value of the margin control's textbox. */
- setTextboxValue: function(value) {
- const textbox = this.$.textbox;
- if (textbox.value != value) {
- textbox.value = value;
+ /**
+ * @param {number} valueInPts New value of the margin control's textbox in
+ * pts.
+ */
+ setTextboxValue: function(valueInPts) {
+ const textbox = this.$.input;
+ const pts = textbox.value ? this.parseValueToPts_(textbox.value) : null;
+ if (!!pts && valueInPts === Math.round(pts)) {
+ // If the textbox's value represents the same value in pts as the new one,
+ // don't reset. This allows the "undo" command to work as expected, see
+ // https://crbug.com/452844.
+ return;
}
+
+ textbox.value = this.serializeValueFromPts_(valueInPts);
},
/** @return {number} The current position of the margin control. */
@@ -115,20 +138,20 @@ Polymer({
*/
convertPixelsToPts: function(pixels) {
let pts;
- const orientationEnum = print_preview.ticket_items.CustomMarginsOrientation;
- if (this.side == orientationEnum.TOP) {
+ const Orientation = print_preview.ticket_items.CustomMarginsOrientation;
+ if (this.side == Orientation.TOP) {
pts = pixels - this.translateTransform.y + RADIUS_PX;
pts /= this.scaleTransform;
- } else if (this.side == orientationEnum.RIGHT) {
+ } else if (this.side == Orientation.RIGHT) {
pts = pixels - this.translateTransform.x + RADIUS_PX;
pts /= this.scaleTransform;
pts = this.pageSize.width - pts;
- } else if (this.side == orientationEnum.BOTTOM) {
+ } else if (this.side == Orientation.BOTTOM) {
pts = pixels - this.translateTransform.y + RADIUS_PX;
pts /= this.scaleTransform;
pts = this.pageSize.height - pts;
} else {
- assert(this.side == orientationEnum.LEFT);
+ assert(this.side == Orientation.LEFT);
pts = pixels - this.translateTransform.x + RADIUS_PX;
pts /= this.scaleTransform;
}
@@ -140,8 +163,55 @@ Polymer({
* @return {boolean} Whether the margin should start being dragged.
*/
shouldDrag: function(event) {
- return !this.$.textbox.disabled && event.button == 0 &&
- (event.path[0] == this || event.path[0] == this.$.line);
+ return !this.disabled && event.button == 0 &&
+ (event.path[0] == this.$.lineContainer || event.path[0] == this.$.line);
+ },
+
+ /** @private */
+ onDisabledChange_: function() {
+ if (this.disabled) {
+ this.focused_ = false;
+ }
+ },
+
+ /**
+ * @param {string} value Value to parse to points. E.g. '3.40' or '200'.
+ * @return {?number} Value in points represented by the input value.
+ * @private
+ */
+ parseValueToPts_: function(value) {
+ // Removing whitespace anywhere in the string.
+ value = value.replace(/\s*/g, '');
+ if (value.length == 0) {
+ return null;
+ }
+ assert(this.measurementSystem);
+ const decimal = this.measurementSystem.decimalDelimeter;
+ const thousands = this.measurementSystem.thousandsDelimeter;
+ const validationRegex = new RegExp(
+ `^(^-?)(((\\d)(\\${thousands}\\d{3})*)(\\${decimal}\\d*)?|` +
+ `((\\d)?(\\${thousands}\\d{3})*)(\\${decimal}\\d*))`);
+ if (validationRegex.test(value)) {
+ // Replacing decimal point with the dot symbol in order to use
+ // parseFloat() properly.
+ value = value.replace(new RegExp(`\\${decimal}{1}`), '.');
+ value = value.replace(new RegExp(`\\${thousands}`, 'g'), '');
+ return this.measurementSystem.convertToPoints(parseFloat(value));
+ }
+ return null;
+ },
+
+ /**
+ * @param {number} value Value in points to serialize.
+ * @return {string} String representation of the value in the system's local
+ * units.
+ * @private
+ */
+ serializeValueFromPts_: function(value) {
+ assert(this.measurementSystem);
+ value = this.measurementSystem.convertFromPoints(value);
+ value = this.measurementSystem.roundValue(value);
+ return value.toString();
},
/**
@@ -149,17 +219,29 @@ Polymer({
* @private
*/
onInputChange_: function(e) {
- this.fire('text-change', e.detail);
+ if (!e.detail) {
+ return;
+ }
+
+ const value = this.parseValueToPts_(e.detail);
+ if (value === null) {
+ this.invalid = true;
+ return;
+ }
+
+ this.fire('text-change', value);
},
/** @private */
onBlur_: function() {
+ this.focused_ = false;
this.resetAndUpdate();
- this.fire('text-blur', this.invalid);
+ this.fire('text-blur', this.invalid || !this.$.input.value);
},
/** @private */
onFocus_: function() {
+ this.focused_ = true;
this.fire('text-focus');
},
@@ -169,20 +251,20 @@ Polymer({
return;
}
- const orientationEnum = print_preview.ticket_items.CustomMarginsOrientation;
+ const Orientation = print_preview.ticket_items.CustomMarginsOrientation;
let x = this.translateTransform.x;
let y = this.translateTransform.y;
let width = null;
let height = null;
- if (this.side == orientationEnum.TOP) {
+ if (this.side == Orientation.TOP) {
y = this.scaleTransform * this.positionInPts_ +
this.translateTransform.y - RADIUS_PX;
width = this.scaleTransform * this.pageSize.width;
- } else if (this.side == orientationEnum.RIGHT) {
+ } else if (this.side == Orientation.RIGHT) {
x = this.scaleTransform * (this.pageSize.width - this.positionInPts_) +
this.translateTransform.x - RADIUS_PX;
height = this.scaleTransform * this.pageSize.height;
- } else if (this.side == orientationEnum.BOTTOM) {
+ } else if (this.side == Orientation.BOTTOM) {
y = this.scaleTransform * (this.pageSize.height - this.positionInPts_) +
this.translateTransform.y - RADIUS_PX;
width = this.scaleTransform * this.pageSize.width;
diff --git a/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.html b/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.html
index f9e56ae61c6..fa7375baf19 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.html
@@ -28,8 +28,11 @@
<print-preview-margin-control side="[[item]]" invisible="[[invisible_]]"
disabled="[[controlsDisabled_(state, invisible_)]]"
translate-transform="[[translateTransform_]]"
- clip-size="[[clipSize_]]" scale-transform="[[scaleTransform_]]"
- page-size="[[pageSize]]" on-pointerdown="onPointerDown_"
+ clip-size="[[clipSize_]]"
+ measurement-system="[[measurementSystem]]"
+ scale-transform="[[scaleTransform_]]"
+ page-size="[[pageSize]]"
+ on-pointerdown="onPointerDown_"
on-text-change="onTextChange_" on-text-blur="onTextBlur_"
on-text-focus="onTextFocus_" on-transition-end="onTransitionEnd_">
</print-preview-margin-control>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.js b/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.js
index 149383308dc..eb6adf25058 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/margin_control_container.js
@@ -172,7 +172,7 @@ Polymer({
const key = print_preview.MARGIN_KEY_MAP.get(control.side);
const newValue = margins[key] || 0;
control.setPositionInPts(newValue);
- control.setTextboxValue(this.serializeValueFromPts_(newValue));
+ control.setTextboxValue(newValue);
});
},
@@ -259,20 +259,7 @@ Polymer({
*/
moveControlWithConstraints_: function(control, posInPts) {
control.setPositionInPts(posInPts);
- control.setTextboxValue(this.serializeValueFromPts_(posInPts));
- },
-
- /**
- * @param {number} value Value in points to serialize.
- * @return {string} String representation of the value in the system's local
- * units.
- * @private
- */
- serializeValueFromPts_: function(value) {
- assert(this.measurementSystem);
- value = this.measurementSystem.convertFromPoints(value);
- value = this.measurementSystem.roundValue(value);
- return value + this.measurementSystem.unitSymbol;
+ control.setTextboxValue(posInPts);
},
/**
@@ -448,19 +435,14 @@ Polymer({
},
/**
- * @param {!CustomEvent<string>} e Event containing the new textbox value.
+ * @param {!CustomEvent<number>} e Event containing the new textbox value.
* @private
*/
onTextChange_: function(e) {
- const marginValue = this.parseValueToPts_(e.detail);
const control =
/** @type {!PrintPreviewMarginControlElement} */ (e.target);
- if (marginValue == null) {
- control.invalid = true;
- return;
- }
control.invalid = false;
- const clippedValue = this.clipAndRoundValue_(control.side, marginValue);
+ const clippedValue = this.clipAndRoundValue_(control.side, e.detail);
control.setPositionInPts(clippedValue);
this.setMargin_(control.side, clippedValue);
},
@@ -475,8 +457,7 @@ Polymer({
if (e.detail /* detail is true if the control is in an invalid state */) {
const control =
/** @type {!PrintPreviewMarginControlElement} */ (e.target);
- control.setTextboxValue(
- this.serializeValueFromPts_(control.getPositionInPts()));
+ control.setTextboxValue(control.getPositionInPts());
control.invalid = false;
}
this.textboxFocused_ = false;
@@ -522,33 +503,6 @@ Polymer({
},
/**
- * @param {string} value Value to parse to points. E.g. '3.40"' or '200mm'.
- * @return {?number} Value in points represented by the input value.
- * @private
- */
- parseValueToPts_: function(value) {
- // Removing whitespace anywhere in the string.
- value = value.replace(/\s*/g, '');
- if (value.length == 0) {
- return null;
- }
- assert(this.measurementSystem);
- const validationRegex = new RegExp(
- '^(^-?)(\\d)+(\\' + this.measurementSystem.thousandsDelimeter +
- '\\d{3})*(\\' + this.measurementSystem.decimalDelimeter + '\\d*)?' +
- '(' + this.measurementSystem.unitSymbol + ')?$');
- if (validationRegex.test(value)) {
- // Replacing decimal point with the dot symbol in order to use
- // parseFloat() properly.
- const replacementRegex =
- new RegExp('\\' + this.measurementSystem.decimalDelimeter + '{1}');
- value = value.replace(replacementRegex, '.');
- return this.measurementSystem.convertToPoints(parseFloat(value));
- }
- return null;
- },
-
- /**
* Updates the translation transformation that translates pixel values in
* the space of the HTML DOM.
* @param {print_preview.Coordinate2d} translateTransform Updated value of
diff --git a/chromium/chrome/browser/resources/print_preview/ui/margins_settings.html b/chromium/chrome/browser/resources/print_preview/ui/margins_settings.html
index 49f34fe5b86..f02aa28e304 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/margins_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/margins_settings.html
@@ -1,6 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="../data/margins.html">
<link rel="import" href="print_preview_shared_css.html">
<link rel="import" href="select_behavior.html">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/pages_per_sheet_settings.html b/chromium/chrome/browser/resources/print_preview/ui/pages_per_sheet_settings.html
index de31288d84e..13a454cd909 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/pages_per_sheet_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/pages_per_sheet_settings.html
@@ -1,6 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="../data/margins.html">
<link rel="import" href="print_preview_shared_css.html">
<link rel="import" href="select_behavior.html">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/pages_settings.html b/chromium/chrome/browser/resources/print_preview/ui/pages_settings.html
index cddc0ba643d..4d6c107374a 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/pages_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/pages_settings.html
@@ -1,7 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
<link rel="import" href="../data/document_info.html">
<link rel="import" href="../print_preview_utils.html">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/pages_settings.js b/chromium/chrome/browser/resources/print_preview/ui/pages_settings.js
index f46015b8a5e..176161fa688 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/pages_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/pages_settings.js
@@ -374,10 +374,8 @@ Polymer({
'pageRangeSyntaxInstruction',
loadTimeData.getString('examplePageRangeText'));
} else {
- formattedMessage = (this.pageCount === 0) ?
- '' :
- loadTimeData.getStringF(
- 'pageRangeLimitInstructionWithValue', this.pageCount);
+ formattedMessage = loadTimeData.getStringF(
+ 'pageRangeLimitInstructionWithValue', this.pageCount);
}
return formattedMessage.replace(/<\/b>|<b>/g, '');
},
@@ -404,6 +402,10 @@ Polymer({
* @private
*/
getAllPagesString_: function() {
+ if (this.pageCount === 0) {
+ return '';
+ }
+
return this.pageCount === 1 ? '1' : `1-${this.pageCount}`;
},
diff --git a/chromium/chrome/browser/resources/print_preview/ui/pin_settings.js b/chromium/chrome/browser/resources/print_preview/ui/pin_settings.js
index 656c932fd23..e6c1c40346b 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/pin_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/pin_settings.js
@@ -145,7 +145,8 @@ Polymer({
// We allow to save the empty string as sticky setting value to give users
// the opportunity to unset their PIN in sticky settings.
- if (this.inputValid_ || this.inputString_ == '') {
+ if ((this.inputValid_ || this.inputString_ == '') &&
+ this.inputString_ !== this.getSettingValue('pinValue')) {
this.setSetting('pinValue', this.inputString_);
}
},
diff --git a/chromium/chrome/browser/resources/print_preview/ui/plugin_proxy.js b/chromium/chrome/browser/resources/print_preview/ui/plugin_proxy.js
index fb393a7df29..d4e1c49cfc0 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/plugin_proxy.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/plugin_proxy.js
@@ -160,6 +160,21 @@ cr.define('print_preview', function() {
this.getPreviewUrl_(previewUid, pageIndex), index);
}
+ /** @param {?Function} keyEventCallback */
+ setKeyEventCallback(keyEventCallback) {
+ this.plugin_.setKeyEventCallback(keyEventCallback);
+ }
+
+ /** @param {?Function} loadCallback */
+ setLoadCallback(loadCallback) {
+ this.plugin_.setLoadCallback(loadCallback);
+ }
+
+ /** @param {?Function} viewportChangedCallback */
+ setViewportChangedCallback(viewportChangedCallback) {
+ this.plugin_.setViewportChangedCallback(viewportChangedCallback);
+ }
+
/** @param {boolean} darkMode Whether the page is in dark mode. */
darkModeChanged(darkMode) {
this.plugin_.darkModeChanged(darkMode);
diff --git a/chromium/chrome/browser/resources/print_preview/ui/preview_area.html b/chromium/chrome/browser/resources/print_preview/ui/preview_area.html
index b67043fab53..ac0d828314d 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/preview_area.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/preview_area.html
@@ -1,14 +1,13 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/html/dark_mode.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="../native_layer.html">
+<link rel="import" href="../dark_mode_behavior.html">
<link rel="import" href="../data/coordinate2d.html">
<link rel="import" href="../data/destination.html">
<link rel="import" href="../data/margins.html">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/preview_area.js b/chromium/chrome/browser/resources/print_preview/ui/preview_area.js
index 29796265200..71f038f3955 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/preview_area.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/preview_area.js
@@ -25,7 +25,12 @@ print_preview.PreviewAreaState = {
Polymer({
is: 'print-preview-preview-area',
- behaviors: [WebUIListenerBehavior, SettingsBehavior, I18nBehavior],
+ behaviors: [
+ WebUIListenerBehavior,
+ SettingsBehavior,
+ I18nBehavior,
+ print_preview.DarkModeBehavior,
+ ],
properties: {
/** @type {print_preview.Destination} */
@@ -89,6 +94,7 @@ Polymer({
},
observers: [
+ 'onDarkModeChanged_(inDarkMode)',
'pluginOrDocumentStatusChanged_(pluginLoaded_, documentReady_)',
'onStateOrErrorChange_(state, error)',
],
@@ -113,12 +119,7 @@ Polymer({
this.nativeLayer_ = print_preview.NativeLayer.getInstance();
this.addWebUIListener(
'page-preview-ready', this.onPagePreviewReady_.bind(this));
- if (this.newPrintPreviewLayout) {
- this.addWebUIListener(
- 'dark-mode-changed', this.onDarkModeChanged_.bind(this));
- }
- this.pluginProxy_ = print_preview.PluginProxy.getInstance();
if (!this.pluginProxy_.checkPluginCompatibility(assert(
this.$$('.preview-area-compatibility-object-out-of-process')))) {
this.error = print_preview.Error.NO_PLUGIN;
@@ -126,6 +127,11 @@ Polymer({
}
},
+ /** @override */
+ created: function() {
+ this.pluginProxy_ = print_preview.PluginProxy.getInstance();
+ },
+
/**
* @return {boolean} Whether the preview is loaded.
* @private
@@ -311,17 +317,17 @@ Polymer({
onPreviewStart_: function(previewUid, index) {
if (!this.pluginProxy_.pluginReady()) {
const plugin = this.pluginProxy_.createPlugin(previewUid, index);
- plugin.setKeyEventCallback(this.keyEventCallback_);
+ this.pluginProxy_.setKeyEventCallback(this.keyEventCallback_);
this.$$('.preview-area-plugin-wrapper')
.appendChild(
/** @type {Node} */ (plugin));
- plugin.setLoadCallback(this.onPluginLoad_.bind(this));
- plugin.setViewportChangedCallback(
+ this.pluginProxy_.setLoadCallback(this.onPluginLoad_.bind(this));
+ this.pluginProxy_.setViewportChangedCallback(
this.onPreviewVisualStateChange_.bind(this));
}
this.pluginLoaded_ = false;
- if (inDarkMode() && this.newPrintPreviewLayout) {
+ if (this.inDarkMode && this.newPrintPreviewLayout) {
this.pluginProxy_.darkModeChanged(true);
}
this.pluginProxy_.resetPrintPreviewMode(
@@ -359,6 +365,10 @@ Polymer({
*/
onPreviewVisualStateChange_: function(
pageX, pageY, pageWidth, viewportWidth, viewportHeight) {
+ // Ensure the PDF viewer isn't tabbable if the window is small enough that
+ // the zoom toolbar isn't displayed.
+ const tabindex = viewportWidth < 300 || viewportHeight < 200 ? '-1' : '0';
+ this.$$('.preview-area-plugin').setAttribute('tabindex', tabindex);
this.$.marginControlContainer.updateTranslationTransform(
new print_preview.Coordinate2d(pageX, pageY));
this.$.marginControlContainer.updateScaleTransform(
@@ -396,13 +406,14 @@ Polymer({
}
},
- /**
- * @param {boolean} darkMode Whether the page is now in dark mode.
- * @private
- */
- onDarkModeChanged_: function(darkMode) {
+ /** @private */
+ onDarkModeChanged_: function() {
+ if (!this.newPrintPreviewLayout) {
+ return;
+ }
+
if (this.pluginProxy_.pluginReady()) {
- this.pluginProxy_.darkModeChanged(darkMode);
+ this.pluginProxy_.darkModeChanged(this.inDarkMode);
}
if (this.previewState === print_preview.PreviewAreaState.DISPLAY_PREVIEW) {
diff --git a/chromium/chrome/browser/resources/print_preview/ui/print_preview_search_box.html b/chromium/chrome/browser/resources/print_preview/ui/print_preview_search_box.html
index f9d62440612..12f71762264 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/print_preview_search_box.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/print_preview_search_box.html
@@ -13,12 +13,13 @@
:host {
display: flex;
font-size: calc(13/15 * 1em);
- --cr-input-row-container: {
- min-height: 32px;
- }
--cr-input-error-display: none;
}
+ cr-input::part(row-container) {
+ min-height: 32px;
+ }
+
#icon,
#clearSearch {
margin-inline-end: 0;
@@ -45,6 +46,10 @@
right: auto;
}
+ :host([has-search-text]) cr-input {
+ --cr-input-padding-end: 24px;
+ }
+
.search-box-input {
width: 100%;
}
diff --git a/chromium/chrome/browser/resources/print_preview/ui/print_preview_search_box.js b/chromium/chrome/browser/resources/print_preview/ui/print_preview_search_box.js
index c1f40fbaa40..c9282280385 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/print_preview_search_box.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/print_preview_search_box.js
@@ -38,6 +38,10 @@ Polymer({
return this.$.searchInput;
},
+ focus: function() {
+ this.$.searchInput.focus();
+ },
+
/**
* @param {!CustomEvent<string>} e Event containing the new search.
* @private
diff --git a/chromium/chrome/browser/resources/print_preview/ui/print_preview_shared_css.html b/chromium/chrome/browser/resources/print_preview/ui/print_preview_shared_css.html
index d92a5ee8f38..1d85437404f 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/print_preview_shared_css.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/print_preview_shared_css.html
@@ -28,24 +28,31 @@
.checkbox cr-checkbox {
min-height: var(--print-preview-row-height);
--cr-checkbox-ripple-size: var(--print-preview-row-height);
- --cr-checkbox-label-container: {
- overflow: hidden;
- padding-inline-start: 16px;
- };
+ }
+
+ .checkbox cr-checkbox::part(label-container) {
+ overflow: hidden;
+ padding-inline-start: 16px;
}
cr-input {
line-height: 20px;
}
+ cr-input::part(row-container) {
+ min-height: var(--print-preview-row-height);
+ }
+
a[href],
a[is='action-link'] {
color: var(--google-blue-600); /* Same in light and dark mode. */
text-decoration: none;
}
- :host-context([dark]) :-webkit-any(a[href], a[is='action-link']) {
- color: var(--cr-link-color);
+ @media (prefers-color-scheme: dark) {
+ :-webkit-any(a[href], a[is='action-link']) {
+ color: var(--cr-link-color);
+ }
}
print-preview-settings-section [slot=controls] > * {
@@ -53,19 +60,14 @@
}
/* Default print preview dialog styles. */
- cr-dialog {
- --cr-dialog-wrapper: {
- max-height: calc(100vh - 68px);
- width: calc(100vw - 68px);
- max-width: 100%;
- };
- --cr-dialog-body: {
- box-sizing: border-box;
- padding-inline-end: 20px;
- padding-inline-start: 20px;
- padding-bottom: 0;
- padding-top: 0;
- };
+ cr-dialog::part(wrapper) {
+ max-height: calc(100vh - 68px);
+ max-width: 100%;
+ width: calc(100vw - 68px);
+ }
+
+ cr-dialog [slot=body] {
+ box-sizing: border-box;
}
#dialog div[slot='title'] {
diff --git a/chromium/chrome/browser/resources/print_preview/ui/print_preview_vars_css.html b/chromium/chrome/browser/resources/print_preview/ui/print_preview_vars_css.html
index 3ded67f68ea..fd217edc4cc 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/print_preview_vars_css.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/print_preview_vars_css.html
@@ -11,9 +11,6 @@
--print-preview-title-width: 120px;
--print-preview-sidebar-margin: 24px;
- --cr-input-row-container: {
- min-height: var(--print-preview-row-height);
- };
--print-preview-settings-border: 1px solid var(--google-grey-200);
--print-preview-dialog-margin: 34px;
--print-preview-disabled-label: {
@@ -27,13 +24,15 @@
--preview-area-background-color-new: var(--google-grey-refresh-300);
}
- html[dark] {
- --preview-area-background-color: var(--google-grey-400);
- --preview-area-background-color-new: var(--google-grey-refresh-700);
- --print-preview-disabled-label: {
- opacity: var(--cr-disabled-opacity);
+ @media (prefers-color-scheme: dark) {
+ html {
+ --preview-area-background-color: var(--google-grey-400);
+ --preview-area-background-color-new: var(--google-grey-refresh-700);
+ --print-preview-disabled-label: {
+ opacity: var(--cr-disabled-opacity);
+ }
+ --print-preview-settings-border: var(--cr-separator-line);
}
- --print-preview-settings-border: var(--cr-separator-line);
}
</style>
</custom-style>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/provisional_destination_resolver.html b/chromium/chrome/browser/resources/print_preview/ui/provisional_destination_resolver.html
index 9705521ee4f..f77b393a6b2 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/provisional_destination_resolver.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/provisional_destination_resolver.html
@@ -1,12 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../data/destination.html">
<link rel="import" href="../data/destination_store.html">
<link rel="import" href="print_preview_shared_css.html">
@@ -16,13 +15,11 @@
<dom-module id="print-preview-provisional-destination-resolver">
<template>
- <style include="print-preview-shared paper-button-style cr-hidden-style throbber">
- #dialog {
- --cr-dialog-native: {
- height: -webkit-fit-content;
- max-height: calc(100vh - 4 * var(--print-preview-dialog-margin));
- max-width: calc(100vw - 4 * var(--print-preview-dialog-margin));
- };
+ <style include="print-preview-shared cr-hidden-style throbber">
+ #dialog::part(dialog) {
+ height: -webkit-fit-content;
+ max-height: calc(100vh - 4 * var(--print-preview-dialog-margin));
+ max-width: calc(100vw - 4 * var(--print-preview-dialog-margin));
}
.throbber-placeholder {
@@ -81,15 +78,15 @@
</div>
</div>
<div slot="button-container" id="buttons">
- <paper-button class="cancel-button" on-click="onCancelClick_">
+ <cr-button class="cancel-button" on-click="onCancelClick_">
$i18n{goBackButton}
- </paper-button>
- <paper-button class="action-button"
+ </cr-button>
+ <cr-button class="action-button"
hidden="[[isInErrorState_(state_)]]"
disabled="[[!isInActiveState_(state_)]]"
on-click="startResolveDestination_">
$i18n{selectButton}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/scaling_settings.html b/chromium/chrome/browser/resources/print_preview/ui/scaling_settings.html
index 58b147ee4bb..d4cd7a36b99 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/scaling_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/scaling_settings.html
@@ -1,6 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
<link rel="import" href="number_settings_section.html">
<link rel="import" href="print_preview_shared_css.html">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/scaling_settings.js b/chromium/chrome/browser/resources/print_preview/ui/scaling_settings.js
index f9da00e5886..909562b33d3 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/scaling_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/scaling_settings.js
@@ -164,7 +164,8 @@ Polymer({
onInputChanged_: function() {
this.setSettingValid('scaling', this.inputValid_);
- if (this.currentValue_ !== '' && this.inputValid_) {
+ if (this.currentValue_ !== '' && this.inputValid_ &&
+ this.currentValue_ !== this.getSettingValue('scaling')) {
this.setSetting('scaling', this.currentValue_);
}
},
diff --git a/chromium/chrome/browser/resources/print_preview/ui/settings_behavior.js b/chromium/chrome/browser/resources/print_preview/ui/settings_behavior.js
index b6b37abb6e4..89dba47e66d 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/settings_behavior.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/settings_behavior.js
@@ -32,9 +32,11 @@ const SettingsBehavior = {
* an update to sticky settings.
* @param {string} settingName Name of the setting to set
* @param {*} value The value to set the setting to.
+ * @param {boolean=} noSticky Whether to avoid stickying the setting. Defaults
+ * to false.
*/
- setSetting: function(settingName, value) {
- print_preview.Model.getInstance().setSetting(settingName, value);
+ setSetting: function(settingName, value, noSticky) {
+ print_preview.Model.getInstance().setSetting(settingName, value, noSticky);
},
/**
@@ -42,10 +44,12 @@ const SettingsBehavior = {
* @param {number} start
* @param {number} end
* @param {*} newValue The value to add (if any).
+ * @param {boolean=} noSticky Whether to avoid stickying the setting. Defaults
+ * to false.
*/
- setSettingSplice: function(settingName, start, end, newValue) {
+ setSettingSplice: function(settingName, start, end, newValue, noSticky) {
print_preview.Model.getInstance().setSettingSplice(
- settingName, start, end, newValue);
+ settingName, start, end, newValue, noSticky);
},
/**
diff --git a/chromium/chrome/browser/resources/print_preview/ui/settings_select.html b/chromium/chrome/browser/resources/print_preview/ui/settings_select.html
index b5d8e6168a4..dd4a716db2e 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/settings_select.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/settings_select.html
@@ -1,6 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="../print_preview_utils.html">
<link rel="import" href="print_preview_shared_css.html">
<link rel="import" href="select_behavior.html">
diff --git a/chromium/chrome/browser/resources/print_preview/ui/sidebar.html b/chromium/chrome/browser/resources/print_preview/ui/sidebar.html
index ea0b75e4a5d..7e5739246aa 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/sidebar.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/sidebar.html
@@ -4,11 +4,11 @@
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/html/dark_mode.html">
<link rel="import" href="chrome://resources/html/load_time_data.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
<link rel="import" href="../metrics.html">
+<link rel="import" href="../dark_mode_behavior.html">
<link rel="import" href="../data/destination.html">
<link rel="import" href="../data/state.html">
<link rel="import" href="advanced_options_settings.html">
@@ -48,8 +48,10 @@
flex-direction: column;
}
- :host-context([dark]) {
- background-color: rgba(255, 255, 255, .04);
+ @media (prefers-color-scheme: dark) {
+ :host {
+ background-color: rgba(255, 255, 255, .04);
+ }
}
#container {
@@ -95,15 +97,16 @@
<template is="dom-if" if="[[!newPrintPreviewLayout]]">
<print-preview-header id="header" destination="[[destination]]"
cloud-print-error-message="[[cloudPrintErrorMessage]]"
- error="[[error]]" state="[[state]]"
- settings="[[settings]]" managed="[[controlsManaged]]">
+ error="[[error]]" first-load="[[firstLoad_]]" state="[[state]]"
+ settings="[[settings]]" managed="[[controlsManaged]]"
+ on-print-button-focused="onPrintButtonFocused_">
</print-preview-header>
</template>
<div id="container" show-bottom-shadow$="[[newPrintPreviewLayout]]">
<print-preview-destination-settings id="destinationSettings"
- cloud-print-interface="[[cloudPrintInterface]]" dark="[[dark_]]"
+ cloud-print-interface="[[cloudPrintInterface]]" dark="[[inDarkMode]]"
destination="{{destination}}" destination-state="{{destinationState}}"
- error="{{error}}" settings="[[settings]]"
+ error="{{error}}" first-load="[[firstLoad_]]" settings="[[settings]]"
state="[[state]]" app-kiosk-mode="[[isInAppKioskMode_]]"
disabled="[[controlsDisabled_]]"
available class="settings-section">
@@ -165,7 +168,7 @@
class="settings-section">
</print-preview-scaling-settings>
<print-preview-duplex-settings settings="[[settings]]"
- disabled="[[controlsDisabled_]]" dark="[[dark_]]"
+ disabled="[[controlsDisabled_]]" dark="[[inDarkMode]]"
hidden$="[[!settings.duplex.available]]"
class="settings-section">
</print-preview-duplex-settings>
@@ -200,7 +203,8 @@
</div>
<template is="dom-if" if="[[newPrintPreviewLayout]]">
<print-preview-button-strip destination="[[destination]]"
- state="[[state]]">
+ state="[[state]]" first-load="[[firstLoad_]]"
+ on-print-button-focused="onPrintButtonFocused_">
</print-preview-button-strip>
</template>
</template>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/sidebar.js b/chromium/chrome/browser/resources/print_preview/ui/sidebar.js
index 90f5915325f..687539f8323 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/sidebar.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/sidebar.js
@@ -18,6 +18,7 @@ Polymer({
SettingsBehavior,
CrContainerShadowBehavior,
WebUIListenerBehavior,
+ print_preview.DarkModeBehavior,
],
properties: {
@@ -66,11 +67,9 @@ Polymer({
},
/** @private {boolean} */
- dark_: {
+ firstLoad_: {
type: Boolean,
- value: function() {
- return inDarkMode();
- },
+ value: true,
},
/** @private {boolean} */
@@ -98,13 +97,6 @@ Polymer({
},
},
- /** @override */
- attached: function() {
- this.addWebUIListener('dark-mode-changed', darkMode => {
- this.dark_ = darkMode;
- });
- },
-
/**
* @param {boolean} appKioskMode
* @param {string} defaultPrinter The system default printer ID.
@@ -160,6 +152,11 @@ Polymer({
return this.settingsExpandedByUser_ || !this.shouldShowMoreSettings_;
},
+ /** @private */
+ onPrintButtonFocused_: function() {
+ this.firstLoad_ = false;
+ },
+
onStateChanged_: function() {
if (this.state !== print_preview.State.PRINTING) {
return;
diff --git a/chromium/chrome/browser/resources/quota_internals/main.css b/chromium/chrome/browser/resources/quota_internals/main.css
index ef8dc11a092..ab3de652bdc 100644
--- a/chromium/chrome/browser/resources/quota_internals/main.css
+++ b/chromium/chrome/browser/resources/quota_internals/main.css
@@ -4,8 +4,8 @@
th,
td {
- padding-left: 0.5em;
- padding-right: 0.5em;
+ padding-inline-end: 0.5em;
+ padding-inline-start: 0.5em;
text-align: center;
}
@@ -19,6 +19,6 @@ tr:nth-child(odd) {
background: rgb(238, 238, 255);
}
-.tree-item:not([may-have-children]) > .tree-row > .tree-label {
+.tree-item:not([may-have-children]) > .tree-row > .tree-label-icon {
background-image: url(../../../../ui/webui/resources/images/icon_file.png);
}
diff --git a/chromium/chrome/browser/resources/quota_internals/main.html b/chromium/chrome/browser/resources/quota_internals/main.html
index a1a1b11a5dc..51eb50ca2d1 100644
--- a/chromium/chrome/browser/resources/quota_internals/main.html
+++ b/chromium/chrome/browser/resources/quota_internals/main.html
@@ -4,7 +4,7 @@ Copyright (c) 2011 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
-<html dir="$i18n{textdirection}" lang="$i18n{language}">
+<html dir="ltr" lang="en">
<title>Quota Internals</title>
<meta charset="utf-8">
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
diff --git a/chromium/chrome/browser/resources/safety_tips/BUILD.gn b/chromium/chrome/browser/resources/safety_tips/BUILD.gn
new file mode 100644
index 00000000000..d28e9c1cf15
--- /dev/null
+++ b/chromium/chrome/browser/resources/safety_tips/BUILD.gn
@@ -0,0 +1,50 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+# Generate the binary proto form of "safety_tips" from the ascii proto.
+#
+# TODO(meacer): Remove this from the build once we have the script to push the
+# generated protobuf ready. This will most likely be a manual process and won't
+# be part of the build.
+#
+action("make_safety_tips_protobuf") {
+ script = "gen_safety_tips_proto.py"
+
+ # The output goes in $target_gen_dir since that's where
+ # chrome/browser/browser_resources.grd will look for it.
+
+ input_filename = "safety_tips.asciipb"
+ output_dir = target_gen_dir
+ output_basename = "safety_tips.pb"
+ python_path_root = "$root_out_dir/pyproto"
+ python_path_safety_tips =
+ "$python_path_root/chrome/browser/lookalikes/safety_tips/"
+
+ inputs = [
+ input_filename,
+ ]
+
+ deps = [
+ "//chrome/browser/lookalikes/safety_tips:proto",
+ "//third_party/protobuf:py_proto",
+ ]
+
+ outputs = [
+ "$output_dir/$output_basename",
+ ]
+
+ args = [
+ "-w",
+ "-i",
+ rebase_path(input_filename, root_build_dir),
+ "-d",
+ rebase_path(output_dir, root_build_dir),
+ "-o",
+ output_basename,
+ "-p",
+ rebase_path(python_path_root, root_build_dir),
+ "-p",
+ rebase_path(python_path_safety_tips, root_build_dir),
+ ]
+}
diff --git a/chromium/chrome/browser/resources/safety_tips/OWNERS b/chromium/chrome/browser/resources/safety_tips/OWNERS
new file mode 100644
index 00000000000..f050018fa29
--- /dev/null
+++ b/chromium/chrome/browser/resources/safety_tips/OWNERS
@@ -0,0 +1 @@
+file://chrome/browser/lookalikes/OWNERS
diff --git a/chromium/chrome/browser/resources/safety_tips/gen_safety_tips_proto.py b/chromium/chrome/browser/resources/safety_tips/gen_safety_tips_proto.py
new file mode 100755
index 00000000000..a12e8e78eb0
--- /dev/null
+++ b/chromium/chrome/browser/resources/safety_tips/gen_safety_tips_proto.py
@@ -0,0 +1,72 @@
+#!/usr/bin/python
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""
+ Convert the ASCII safety_tips.asciipb proto into a binary resource.
+"""
+
+import os
+import sys
+
+# Disable warnings for "safety_tips_pb2" which is dynamically imported.
+# pylint: disable=undefined-variable
+
+# Subdirectory to be copied to Google Cloud Storage. Contains a copy of the
+# generated proto under a versioned directory.
+GS_COPY_DIR = "gs_copy"
+
+# Import the binary proto generator. Walks up to the root of the source tree
+# which is five directories above, and finds the protobufs directory from there.
+proto_generator_path = os.path.normpath(os.path.join(os.path.abspath(__file__),
+ *[os.path.pardir] * 5 + ['chrome/browser/resources/protobufs']))
+sys.path.insert(0, proto_generator_path)
+from binary_proto_generator import BinaryProtoGenerator
+
+def MakeSubDirs(outfile):
+ """ Make the subdirectories needed to create file |outfile| """
+ dirname = os.path.dirname(outfile)
+ if not os.path.exists(dirname):
+ os.makedirs(dirname)
+
+class SafetyTipsProtoGenerator(BinaryProtoGenerator):
+ def ImportProtoModule(self):
+ import safety_tips_pb2
+ globals()['safety_tips_pb2'] = safety_tips_pb2
+
+ def EmptyProtoInstance(self):
+ return safety_tips_pb2.SafetyTipsConfig()
+
+ def ValidatePb(self, opts, pb):
+ assert pb.version_id > 0
+ assert len(pb.flagged_page) > 0
+ for flagged_page in pb.flagged_page:
+ assert flagged_page.url
+ assert flagged_page.type != safety_tips_pb2.FlaggedPage.UNKNOWN
+
+ def ProcessPb(self, opts, pb):
+ binary_pb_str = pb.SerializeToString()
+ outfile = os.path.join(opts.outdir, opts.outbasename)
+
+ # Write two copies of the proto:
+ # 1. Under the root of the gen directory for .grd files to refer to
+ # (./safety_tips/safety_tips.pb)
+ # 2. Under a versioned directory for the proto pusher to refer to
+ # (./safety_tips/gs_copy/<version>/all/safety_tips.pb)
+ outfile = os.path.join(opts.outdir, opts.outbasename)
+ with open(outfile, 'wb') as f:
+ f.write(binary_pb_str)
+
+ outfile_copy = os.path.join(opts.outdir, GS_COPY_DIR, str(pb.version_id),
+ "all", opts.outbasename)
+ MakeSubDirs(outfile_copy)
+ with open(outfile_copy, 'wb') as f:
+ f.write(binary_pb_str)
+
+
+def main():
+ return SafetyTipsProtoGenerator().Run()
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/chromium/chrome/browser/resources/safety_tips/safety_tips.asciipb b/chromium/chrome/browser/resources/safety_tips/safety_tips.asciipb
new file mode 100644
index 00000000000..9306e6c7a27
--- /dev/null
+++ b/chromium/chrome/browser/resources/safety_tips/safety_tips.asciipb
@@ -0,0 +1,17 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+# Placeholder for list of known bad URLs.
+# This file must be kept as-is and the full list must not be checked in to
+# Chromium source. When you want to update it, overwrite it locally, generate
+# and push the protobuffer to the storage bucket but do not check in the
+# changes.
+
+version_id: 1
+
+# See chrome/browser/lookalikes/safety_tips.proto for the full format.
+flagged_page {
+ url: "http://example.test/test-path-for-safety-tips/test.html"
+ type: BAD_REP
+}
diff --git a/chromium/chrome/browser/resources/settings/BUILD.gn b/chromium/chrome/browser/resources/settings/BUILD.gn
index 39d59932f30..90c81d10457 100644
--- a/chromium/chrome/browser/resources/settings/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/BUILD.gn
@@ -113,8 +113,8 @@ group("closure_compile") {
"date_time_page:closure_compile",
"device_page:closure_compile",
"internet_page:closure_compile",
- "kiosk_next_shell_page:closure_compile",
"multidevice_page:closure_compile",
+ "parental_controls_page:closure_compile",
"plugin_vm_page:closure_compile",
]
}
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/BUILD.gn b/chromium/chrome/browser/resources/settings/a11y_page/BUILD.gn
index 26dc31667fc..cb0f25da20a 100644
--- a/chromium/chrome/browser/resources/settings/a11y_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/a11y_page/BUILD.gn
@@ -7,17 +7,30 @@ import("//third_party/closure_compiler/compile_js.gni")
js_type_check("closure_compile") {
deps = [
":a11y_page",
+ ":captions_browser_proxy",
+ ":captions_subpage",
]
if (is_chromeos) {
deps += [
":externs",
":manage_a11y_page",
+ ":switch_access_subpage",
":tts_subpage",
]
}
}
+js_library("captions_subpage") {
+ deps = [
+ "../appearance_page:fonts_browser_proxy",
+ "../controls:settings_dropdown_menu",
+ "//ui/webui/resources/cr_elements/cr_slider:cr_slider",
+ "//ui/webui/resources/js:i18n_behavior",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
+ ]
+}
+
js_library("a11y_page") {
deps = [
"..:route",
@@ -36,6 +49,15 @@ js_library("manage_a11y_page") {
externs_list = [ "$externs_path/settings_private.js" ]
}
+js_library("switch_access_subpage") {
+ deps = [
+ "..:route",
+ "//ui/webui/resources/js:i18n_behavior",
+ "//ui/webui/resources/js:load_time_data",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
+ ]
+}
+
js_library("tts_subpage") {
deps = [
":externs",
@@ -51,3 +73,9 @@ js_library("tts_subpage") {
js_library("externs") {
}
+
+js_library("captions_browser_proxy") {
+ deps = [
+ "//ui/webui/resources/js:cr",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html b/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html
index d31b232766a..74d602e6f8e 100644
--- a/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html
+++ b/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.html
@@ -1,5 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="captions_browser_proxy.html">
+<link rel="import" href="captions_subpage.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="../i18n_setup.html">
@@ -10,16 +12,49 @@
<link rel="import" href="../controls/settings_toggle_button.html">
<link rel="import" href="../settings_page/settings_animated_pages.html">
<link rel="import" href="../settings_page/settings_subpage.html">
+<link rel="import" href="switch_access_subpage.html">
<link rel="import" href="tts_subpage.html">
</if>
<dom-module id="settings-a11y-page">
<template>
<style include="settings-shared"></style>
+ <template is="dom-if" if="[[showCaptionSettings_]]">
+ <cr-link-row class="hr" id="captions" label="$i18n{captionsTitle}"
+ on-click="onCaptionsClick_">
+ </cr-link-row>
+ </template>
+ <settings-animated-pages id="pages" current-route="{{currentRoute}}"
+ section="a11y" focus-config="[[focusConfig_]]">
+<if expr="not chromeos">
+ <div route-path="default">
+ <settings-toggle-button
+ id="a11yImageLabels"
+ hidden$="[[!showAccessibilityLabelsSetting_]]"
+ pref="{{prefs.settings.a11y.enable_accessibility_image_labels}}"
+ on-change="onToggleAccessibilityImageLabels_"
+ label="$i18n{accessibleImageLabelsTitle}"
+ sub-label="$i18n{accessibleImageLabelsSubtitle}">
+ </settings-toggle-button>
+ <cr-link-row class="hr" label="$i18n{moreFeaturesLink}"
+ on-click="onMoreFeaturesLinkClick_" sub-label="$i18n{a11yWebStore}"
+ external>
+ </cr-link-row>
+ </div>
+</if>
+<if expr="chromeos or is_linux or is_win">
+ <template is="dom-if" if="[[showCaptionSettings_]]">
+ <template is="dom-if" route-path="/captions">
+ <settings-subpage
+ associated-control="[[$$('#captions')]]"
+ page-title="$i18n{captionsTitle}">
+ <settings-captions prefs="{{prefs}}"></settings-captions>
+ </settings-subpage>
+ </template>
+ </template>
+</if>
<if expr="chromeos">
- <template is="dom-if" if="[[pageVisibility.webstoreLink]]">
- <settings-animated-pages id="pages" current-route="{{currentRoute}}"
- section="a11y" focus-config="[[focusConfig_]]">
+ <template is="dom-if" if="[[pageVisibility.webstoreLink]]">
<div route-path="default">
<settings-toggle-button
id="a11yImageLabels"
@@ -39,7 +74,6 @@
sub-label="$i18n{moreFeaturesLinkDescription}">
</cr-link-row>
</div>
-
<template is="dom-if" route-path="/manageAccessibility">
<settings-subpage
associated-control="[[$$('#subpage-trigger')]]"
@@ -56,28 +90,22 @@
</settings-tts-subpage>
</settings-subpage>
</template>
- </settings-animated-pages>
- </template>
- <cr-link-row class="hr" label="$i18n{moreFeaturesLink}"
- on-click="onMoreFeaturesLinkClick_" sub-label="$i18n{a11yWebStore}"
- hidden="[[pageVisibility.webstoreLink]]"
- external></cr-link-row>
+ <template is="dom-if" route-path="/manageAccessibility/switchAccess">
+ <settings-subpage associated-control="[[$$('#subpage-trigger')]]"
+ page-title="$i18n{manageSwitchAccessSettings}">
+ <settings-switch-access-subpage prefs="{{prefs.settings.a11y}}">
+ </settings-switch-access-subpage>
+ </settings-subpage>
+ </template>
+ </template>
</if>
-
-<if expr="not chromeos">
- <settings-toggle-button
- id="a11yImageLabels"
- hidden$="[[!showAccessibilityLabelsSetting_]]"
- pref="{{prefs.settings.a11y.enable_accessibility_image_labels}}"
- on-change="onToggleAccessibilityImageLabels_"
- label="$i18n{accessibleImageLabelsTitle}"
- sub-label="$i18n{accessibleImageLabelsSubtitle}">
- </settings-toggle-button>
+ </settings-animated-pages>
+<if expr="chromeos">
<cr-link-row class="hr" label="$i18n{moreFeaturesLink}"
on-click="onMoreFeaturesLinkClick_" sub-label="$i18n{a11yWebStore}"
- external></cr-link-row>
+ hidden="[[pageVisibility.webstoreLink]]" external>
+ </cr-link-row>
</if>
-
</template>
<script src="a11y_page.js"></script>
</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.js b/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.js
index 22a29747230..6629ff75429 100644
--- a/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.js
+++ b/chromium/chrome/browser/resources/settings/a11y_page/a11y_page.js
@@ -43,6 +43,9 @@ Polymer({
type: Object,
value: function() {
const map = new Map();
+ if (settings.routes.CAPTIONS) {
+ map.set(settings.routes.CAPTIONS.path, '#captions');
+ }
// <if expr="chromeos">
if (settings.routes.MANAGE_ACCESSIBILITY) {
map.set(
@@ -53,6 +56,17 @@ Polymer({
},
},
+ /**
+ * Whether to show the link to caption settings.
+ * @private {boolean}
+ */
+ showCaptionSettings_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('enableCaptionSettings');
+ },
+ },
+
// <if expr="chromeos">
/**
* Whether to show experimental accessibility features.
@@ -109,4 +123,29 @@ Polymer({
window.open(
'https://chrome.google.com/webstore/category/collection/accessibility');
},
+
+ /** @private */
+ onCaptionsClick_: function() {
+ // Open the system captions dialog for Mac.
+ // <if expr="is_macosx">
+ settings.CaptionsBrowserProxyImpl.getInstance().openSystemCaptionsDialog();
+ // </if>
+
+ // Open the system captions dialog for Windows 10+ or navigate to the
+ // caption settings page for older versions of Windows
+ // <if expr="is_win">
+ if (loadTimeData.getBoolean('isWindows10OrNewer')) {
+ settings.CaptionsBrowserProxyImpl.getInstance()
+ .openSystemCaptionsDialog();
+ } else {
+ settings.navigateTo(settings.routes.CAPTIONS);
+ }
+ // </if>
+
+ // Navigate to the caption settings page for ChromeOS and Linux as they
+ // do not have system caption settings.
+ // <if expr="chromeos or is_linux">
+ settings.navigateTo(settings.routes.CAPTIONS);
+ // </if>
+ },
});
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/captions_browser_proxy.html b/chromium/chrome/browser/resources/settings/a11y_page/captions_browser_proxy.html
new file mode 100644
index 00000000000..92b4cd16176
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/a11y_page/captions_browser_proxy.html
@@ -0,0 +1,2 @@
+<link rel="import" href="chrome://resources/html/cr.html">
+<script src="captions_browser_proxy.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/captions_browser_proxy.js b/chromium/chrome/browser/resources/settings/a11y_page/captions_browser_proxy.js
new file mode 100644
index 00000000000..bf86a7e8665
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/a11y_page/captions_browser_proxy.js
@@ -0,0 +1,35 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview A helper object used from the Chrome captions section to
+ * interact with the browser. Used on operating system that is not Chrome OS.
+ */
+
+cr.define('settings', function() {
+ /** @interface */
+ class CaptionsBrowserProxy {
+ /**
+ * Open the native captions system dialog.
+ */
+ openSystemCaptionsDialog() {}
+ }
+
+ /**
+ * @implements {settings.CaptionsBrowserProxy}
+ */
+ class CaptionsBrowserProxyImpl {
+ /** @override */
+ openSystemCaptionsDialog() {
+ chrome.send('openSystemCaptionsDialog');
+ }
+ }
+
+ cr.addSingletonGetter(CaptionsBrowserProxyImpl);
+
+ return {
+ CaptionsBrowserProxy: CaptionsBrowserProxy,
+ CaptionsBrowserProxyImpl: CaptionsBrowserProxyImpl,
+ };
+});
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.html b/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.html
new file mode 100644
index 00000000000..d3d305b9c42
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.html
@@ -0,0 +1,91 @@
+<link rel="import" href="chrome://resources/html/i18n_behavior.html">
+<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="../appearance_page/fonts_browser_proxy.html">
+<link rel="import" href="../controls/settings_dropdown_menu.html">
+<link rel="import" href="../controls/settings_slider.html">
+<link rel="import" href="../settings_shared_css.html">
+
+<dom-module id="settings-captions">
+ <template>
+ <style include="settings-shared"></style>
+ <div class="settings-box">
+ <div class="start settings-box-text">$i18n{captionsTextSize}</div>
+ <settings-dropdown-menu id="captionsTextSize"
+ label="$i18n{captionsTextSize}"
+ pref="{{prefs.accessibility.captions.text_size}}"
+ menu-options="[[textSizeOptions_]]">
+ </settings-dropdown-menu>
+ </div>
+ <div class="settings-box">
+ <div class="start settings-box-text">$i18n{captionsTextFont}</div>
+ <settings-dropdown-menu id="captionsTextFont"
+ label="$i18n{captionsTextFont}"
+ pref="{{prefs.accessibility.captions.text_font}}"
+ menu-options="[[textFontOptions_]]">
+ </settings-dropdown-menu>
+ </div>
+ <div class="settings-box">
+ <div class="start settings-box-text">$i18n{captionsTextColor}</div>
+ <settings-dropdown-menu id="captionsTextColor"
+ label="$i18n{captionsTextColor}"
+ pref="{{prefs.accessibility.captions.text_color}}"
+ menu-options="[[colorOptions_]]">
+ </settings-dropdown-menu>
+ </div>
+ <div class="settings-box">
+ <div class="start settings-box-text">$i18n{captionsTextOpacity}</div>
+ <settings-slider id="captionsTextOpacity"
+ ticks="[[textOpacityRange_]]"
+ label-min="$i18n{captionsOpacityMin}"
+ label-max="$i18n{captionsOpacityMax}"
+ pref="{{prefs.accessibility.captions.text_opacity}}">
+ </settings-slider>
+ </div>
+ <div class="settings-box">
+ <div class="start settings-box-text">$i18n{captionsTextShadow}</div>
+ <settings-dropdown-menu id="captionsTextShadow"
+ label="$i18n{captionsTextShadow}"
+ pref="{{prefs.accessibility.captions.text_shadow}}"
+ menu-options="[[textShadowOptions_]]">
+ </settings-dropdown-menu>
+ </div>
+ <div class="settings-box">
+ <div class="start settings-box-text">$i18n{captionsBackgroundColor}</div>
+ <settings-dropdown-menu id="captionsBackgroundColor"
+ label="$i18n{captionsBackgroundColor}"
+ pref="{{prefs.accessibility.captions.background_color}}"
+ menu-options="[[colorOptions_]]">
+ </settings-dropdown-menu>
+ </div>
+ <div class="settings-box">
+ <div class="start settings-box-text">
+ $i18n{captionsBackgroundOpacity}
+ </div>
+ <settings-slider id="captionsBackgroundOpacity"
+ ticks="[[textOpacityRange_]]"
+ label-min="$i18n{captionsOpacityMin}"
+ label-max="$i18n{captionsOpacityMax}"
+ pref="{{prefs.accessibility.captions.background_opacity}}">
+ </settings-slider>
+ </div>
+ <div class="list-frame">
+ <div class="list-item">
+ <span style="
+ font-size:[[prefs.accessibility.captions.text_size.value]];
+ font-family:[[prefs.accessibility.captions.text_font.value]];
+ background-color: [[computeBackgroundColor_(
+ prefs.accessibility.captions.background_opacity.value,
+ prefs.accessibility.captions.background_color.value)]];
+ color: [[computeTextColor_(
+ prefs.accessibility.captions.text_opacity.value,
+ prefs.accessibility.captions.text_color.value)]];
+ text-shadow: [[prefs.accessibility.captions.text_shadow.value]];
+ padding: [[computePadding_(
+ prefs.accessibility.captions.text_size.value)]]">
+ $i18n{quickBrownFox}
+ </span>
+ </div>
+ </div>
+ </template>
+ <script src="captions_subpage.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.js b/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.js
new file mode 100644
index 00000000000..df973af40cd
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/a11y_page/captions_subpage.js
@@ -0,0 +1,217 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview 'settings-captions' is a component for showing captions
+ * settings subpage (chrome://settings/captions).
+ */
+(function() {
+'use strict';
+
+
+/** @type {!Array<number>} */
+const TEXT_OPACITY_RANGE = [
+ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50,
+ 55, 60, 65, 70, 75, 80, 85, 90, 95, 100
+];
+
+/**
+ * @param {!Array<number>} ticks
+ * @return {!Array<!cr_slider.SliderTick>}
+ */
+function ticksWithLabels(ticks) {
+ return ticks.map(x => ({label: `${x}`, value: x}));
+}
+
+Polymer({
+ is: 'settings-captions',
+
+ behaviors: [I18nBehavior, WebUIListenerBehavior],
+
+ properties: {
+ prefs: {
+ type: Object,
+ notify: true,
+ },
+
+ /**
+ * List of fonts populated by the fonts browser proxy.
+ * @private {!DropdownMenuOptionList} */
+ textFontOptions_: Object,
+
+ /**
+ * Reasonable, text opacity range.
+ * @private {!Array<!cr_slider.SliderTick>}
+ */
+ textOpacityRange_: {
+ readOnly: true,
+ type: Array,
+ value: ticksWithLabels(TEXT_OPACITY_RANGE),
+ },
+
+ /**
+ * List of options for the text size drop-down menu.
+ * @type {!DropdownMenuOptionList}
+ */
+ textSizeOptions_: {
+ readOnly: true,
+ type: Array,
+ value: function() {
+ return [
+ {value: '50%', name: loadTimeData.getString('verySmall')},
+ {value: '75%', name: loadTimeData.getString('small')},
+ {value: '', name: loadTimeData.getString('medium')}, // Default = 100%
+ {value: '150%', name: loadTimeData.getString('large')},
+ {value: '200%', name: loadTimeData.getString('veryLarge')},
+ ];
+ },
+ },
+
+ /**
+ * List of options for the color drop-down menu.
+ * @type {!DropdownMenuOptionList}
+ */
+ colorOptions_: {
+ readOnly: true,
+ type: Array,
+ value: function() {
+ return [
+ {value: '', name: loadTimeData.getString('captionsDefaultSetting')},
+ {value: '0,0,0', name: loadTimeData.getString('captionsColorBlack')},
+ {
+ value: '255,255,255',
+ name: loadTimeData.getString('captionsColorWhite')
+ },
+ {value: '255,0,0', name: loadTimeData.getString('captionsColorRed')},
+ {
+ value: '0,255,0',
+ name: loadTimeData.getString('captionsColorGreen')
+ },
+ {value: '0,0,255', name: loadTimeData.getString('captionsColorBlue')},
+ {
+ value: '255,255,0',
+ name: loadTimeData.getString('captionsColorYellow')
+ },
+ {
+ value: '0,255,255',
+ name: loadTimeData.getString('captionsColorCyan')
+ },
+ {
+ value: '255,0,255',
+ name: loadTimeData.getString('captionsColorMagenta')
+ },
+ ];
+ },
+ },
+
+ /**
+ * List of options for the text shadow drop-down menu.
+ * @type {!DropdownMenuOptionList}
+ */
+ textShadowOptions_: {
+ readOnly: true,
+ type: Array,
+ value: function() {
+ return [
+ {value: '', name: loadTimeData.getString('captionsTextShadowNone')},
+ {
+ value: '-2px -2px 4px rgba(0, 0, 0, 0.5)',
+ name: loadTimeData.getString('captionsTextShadowRaised')
+ },
+ {
+ value: '2px 2px 4px rgba(0, 0, 0, 0.5)',
+ name: loadTimeData.getString('captionsTextShadowDepressed')
+ },
+ {
+ value: '-1px 0px 0px black, ' +
+ '0px -1px 0px black, 1px 0px 0px black, 0px 1px 0px black',
+ name: loadTimeData.getString('captionsTextShadowUniform')
+ },
+ {
+ value: '0px 0px 2px rgba(0, 0, 0, 0.5), 2px 2px 2px black',
+ name: loadTimeData.getString('captionsTextShadowDropShadow')
+ },
+ ];
+ },
+ },
+ },
+
+ /** @private {?settings.FontsBrowserProxy} */
+ browserProxy_: null,
+
+ /** @override */
+ created: function() {
+ this.browserProxy_ = settings.FontsBrowserProxyImpl.getInstance();
+ },
+
+ /** @override */
+ ready: function() {
+ this.browserProxy_.observeAdvancedFontExtensionAvailable();
+
+ this.browserProxy_.fetchFontsData().then(this.setFontsData_.bind(this));
+ },
+
+ /**
+ * @param {!FontsData} response A list of fonts.
+ * @private
+ */
+ setFontsData_: function(response) {
+ const fontMenuOptions =
+ [{value: '', name: loadTimeData.getString('captionsDefaultSetting')}];
+ for (const fontData of response.fontList) {
+ fontMenuOptions.push({value: fontData[0], name: fontData[1]});
+ }
+ this.textFontOptions_ = fontMenuOptions;
+ },
+
+ /**
+ * Get the background color as a RGBA string.
+ * @return {string}
+ * @private
+ */
+ computeBackgroundColor_: function() {
+ return this.formatRGAString_(
+ 'prefs.accessibility.captions.background_color.value',
+ 'prefs.accessibility.captions.background_opacity.value');
+ },
+
+ /**
+ * Get the text color as a RGBA string.
+ * @return {string}
+ * @private
+ */
+ computeTextColor_: function() {
+ return this.formatRGAString_(
+ 'prefs.accessibility.captions.text_color.value',
+ 'prefs.accessibility.captions.text_opacity.value');
+ },
+
+ /**
+ * Formats the color as an RGBA string.
+ * @param {string} colorPreference The name of the preference containing the
+ * RGB values as a comma-separated string.
+ * @param {string} opacityPreference The name of the preference containing
+ * the opacity value as a percentage.
+ * @return {string} The formatted RGBA string.
+ * @private
+ */
+ formatRGAString_: function(colorPreference, opacityPreference) {
+ return 'rgba(' + this.get(colorPreference) + ',' +
+ parseInt(this.get(opacityPreference), 10) / 100.0 + ')';
+ },
+
+ /**
+ * @param {string} size The font size of the captions text as a percentage.
+ * @return {string} The padding around the captions text as a percentage.
+ * @private
+ */
+ computePadding_: function(size) {
+ if (size == '') {
+ return '1%';
+ }
+
+ return `${+size.slice(0, -1) / 100}%`;
+ }
+});
+})();
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html b/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html
index 524500927f6..c7f4721a974 100644
--- a/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html
+++ b/chromium/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html
@@ -81,7 +81,9 @@
disabled="[[prefs.ash.docked_magnifier.enabled.value]]">
</settings-toggle-button>
<div class="settings-box continuation">
- <div class="start sub-item">$i18n{screenMagnifierZoomLabel}</div>
+ <div class="start sub-item settings-box-text">
+ $i18n{screenMagnifierZoomLabel}
+ </div>
<settings-dropdown-menu label="$i18n{screenMagnifierZoomLabel}"
pref="{{prefs.settings.a11y.screen_magnifier_scale}}"
menu-options="[[screenMagnifierZoomOptions_]]"
@@ -94,7 +96,9 @@
disabled="[[prefs.settings.a11y.screen_magnifier.value]]">
</settings-toggle-button>
<div class="settings-box continuation">
- <div class="start sub-item">$i18n{dockedMagnifierZoomLabel}</div>
+ <div class="start sub-item settings-box-text">
+ $i18n{dockedMagnifierZoomLabel}
+ </div>
<settings-dropdown-menu label="$i18n{dockedMagnifierZoomLabel}"
pref="{{prefs.ash.docked_magnifier.scale}}"
menu-options="[[screenMagnifierZoomOptions_]]"
@@ -115,8 +119,7 @@
</settings-toggle-button>
<settings-toggle-button
pref="{{prefs.settings.a11y.virtual_keyboard}}"
- label="$i18n{onScreenKeyboardLabel}"
- hidden$="[[prefs.ash.kiosk_next_shell.enabled.value]]">
+ label="$i18n{onScreenKeyboardLabel}">
</settings-toggle-button>
<settings-toggle-button
pref="{{prefs.settings.a11y.dictation}}"
@@ -133,10 +136,11 @@
</settings-toggle-button>
<template is="dom-if" if="[[showExperimentalSwitchAccess_]]">
<settings-toggle-button
- pref="{{prefs.settings.a11y.switch_access}}"
+ pref="{{prefs.settings.a11y.switch_access.enabled}}"
label="$i18n{switchAccessLabel}">
</settings-toggle-button>
- <iron-collapse opened="[[prefs.settings.a11y.switch_access.value]]">
+ <iron-collapse
+ opened="[[prefs.settings.a11y.switch_access.enabled.value]]">
<cr-link-row label="$i18n{switchAccessOptionsLabel}"
on-click="onSwitchAccessSettingsTap_" embedded external>
</cr-link-row>
@@ -153,7 +157,9 @@
</settings-toggle-button>
<div class="settings-box continuation"
hidden$="[[!prefs.settings.a11y.autoclick.value]]">
- <div class="start sub-item">$i18n{delayBeforeClickLabel}</div>
+ <div class="start sub-item settings-box-text">
+ $i18n{delayBeforeClickLabel}
+ </div>
<settings-dropdown-menu label="$i18n{delayBeforeClickLabel}"
pref="{{prefs.settings.a11y.autoclick_delay_ms}}"
menu-options="[[autoClickDelayOptions_]]"
@@ -176,7 +182,8 @@
</div>
<div class="settings-box continuation"
hidden$="[[!prefs.settings.a11y.autoclick.value]]">
- <div class="start sub-item" id="autoclickMovementThresholdLabel">
+ <div class="start sub-item settings-box-text"
+ id="autoclickMovementThresholdLabel">
$i18n{autoclickMovementThresholdLabel}
</div>
<settings-dropdown-menu
@@ -192,7 +199,9 @@
</settings-toggle-button>
<div class="settings-box continuation"
hidden$="[[!prefs.settings.a11y.large_cursor_enabled.value]]">
- <div class="start sub-item">$i18n{largeMouseCursorSizeLabel}</div>
+ <div class="start sub-item settings-box-text">
+ $i18n{largeMouseCursorSizeLabel}
+ </div>
<settings-slider
pref="{{prefs.settings.a11y.large_cursor_dip_size}}"
min="25" max="64"
@@ -220,10 +229,10 @@
</settings-toggle-button>
<template is="dom-if" if="[[!isGuest_]]">
- <a class="settings-box two-line inherit-color no-outline" tabindex="-1"
+ <a class="settings-box inherit-color no-outline" tabindex="-1"
target="_blank"
href="https://chrome.google.com/webstore/category/collection/accessibility">
- <div class="start">
+ <div class="start settings-box-text">
$i18n{additionalFeaturesTitle}
<div class="secondary" id="moreFeaturesSecondary">
$i18n{a11yWebStore}
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.html b/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.html
new file mode 100644
index 00000000000..d8c101b1563
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.html
@@ -0,0 +1,74 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/html/i18n_behavior.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
+<link rel="import" href="../controls/settings_dropdown_menu.html">
+<link rel="import" href="../controls/settings_slider.html">
+<link rel="import" href="../controls/settings_toggle_button.html">
+<link rel="import" href="../i18n_setup.html">
+<link rel="import" href="../settings_shared_css.html">
+
+<dom-module id="settings-switch-access-subpage">
+ <template>
+ <style include="settings-shared md-select">
+ h2 {
+ padding-inline-start: var(--cr-section-padding);
+ }
+ </style>
+ <h2>$i18n{switchAssignmentHeading}</h2>
+ <div class="list-frame">
+ <div class="settings-box continuation list-item">
+ <div class="start sub-item settings-box-text">
+ $i18n{assignSelectSwitchLabel}
+ </div>
+ <settings-dropdown-menu label="$i18n{assignSelectSwitchLabel}"
+ pref="{{prefs.switch_access.select.setting}}"
+ menu-options="[[switchAssignOptions_]]"
+ on-settings-control-change="onSelectAssigned_">
+ </settings-dropdown-menu>
+ </div>
+ <div class="settings-box continuation list-item">
+ <div class="start sub-item settings-box-text">
+ $i18n{assignNextSwitchLabel}
+ </div>
+ <settings-dropdown-menu label="$i18n{assignNextSwitchLabel}"
+ pref="{{prefs.switch_access.next.setting}}"
+ menu-options="[[switchAssignOptions_]]"
+ on-settings-control-change="onNextAssigned_">
+ </settings-dropdown-menu>
+ </div>
+ <div class="settings-box continuation list-item">
+ <div class="start sub-item settings-box-text">
+ $i18n{assignPreviousSwitchLabel}
+ </div>
+ <settings-dropdown-menu label="$i18n{assignPreviousSwitchLabel}"
+ pref="{{prefs.switch_access.previous.setting}}"
+ menu-options="[[switchAssignOptions_]]"
+ on-settings-control-change="onPreviousAssigned_">
+ </settings-dropdown-menu>
+ </div>
+ </div>
+ <h2>$i18n{switchAccessAutoScanHeading}</h2>
+ <div class="list-frame">
+ <settings-toggle-button class="continuation list-item"
+ pref="{{prefs.switch_access.auto_scan.enabled}}"
+ label="$i18n{switchAccessAutoScanLabel}">
+ </settings-toggle-button>
+ <div class="settings-box continuation list-item"
+ hidden$="[[!prefs.switch_access.auto_scan.enabled.value]]">
+ <div class="start sub-item settings-box-text" id="scanSpeed">
+ [[getLabelForSpeedSlider_(prefs.switch_access.auto_scan.speed_ms.*)]]
+ </div>
+ <settings-slider id="scanSpeedSlider" aria-describedby="scanSpeed"
+ pref="{{prefs.switch_access.auto_scan.speed_ms}}"
+ ticks="[[autoScanSpeedValuesMs_]]"
+ min="[[minScanSpeedMs_]]"
+ max="[[maxScanSpeedMs_]]"
+ label-min="[[minScanSpeedLabelSec_]]"
+ label-max="[[maxScanSpeedLabelSec_]]">
+ </settings-dropdown-menu>
+ </div>
+ </div>
+ </template>
+ <script src="switch_access_subpage.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.js b/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.js
new file mode 100644
index 00000000000..328e60ca3d0
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/a11y_page/switch_access_subpage.js
@@ -0,0 +1,168 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * Available switch assignment values.
+ * @enum {number}
+ * @const
+ */
+const SwitchAccessAssignmentValue = {
+ NONE: 0,
+ SPACE: 1,
+ ENTER: 2,
+};
+
+/**
+ * @fileoverview 'switch-access-subpage' is the collapsible section containing
+ * Switch Access settings.
+ */
+Polymer({
+ is: 'settings-switch-access-subpage',
+
+ behaviors: [I18nBehavior],
+
+ properties: {
+ /**
+ * Preferences state.
+ */
+ prefs: {
+ type: Object,
+ notify: true,
+ },
+
+ /** @private {Array<number>} */
+ autoScanSpeedValuesMs_: {
+ readOnly: true,
+ type: Array,
+ value: [
+ 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300,
+ 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100, 2200,
+ 2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000, 3100,
+ 3200, 3300, 3400, 3500, 3600, 3700, 3800, 3900, 4000
+ ]
+ },
+
+ /** @private {Object} */
+ formatter_: {
+ type: Object,
+ value: function() {
+ // navigator.language actually returns a locale, not just a language.
+ const locale = window.navigator.language;
+ const options = {minimumFractionDigits: 1, maximumFractionDigits: 1};
+ return new Intl.NumberFormat(locale, options);
+ },
+ },
+
+ /** @private {number} */
+ maxScanSpeedMs_: {readOnly: true, type: Number, value: 4000},
+
+ /** @private {string} */
+ maxScanSpeedLabelSec_: {
+ readOnly: true,
+ type: String,
+ value: function() {
+ return this.scanSpeedStringInSec_(this.maxScanSpeedMs_);
+ },
+ },
+
+ /** @private {number} */
+ minScanSpeedMs_: {readOnly: true, type: Number, value: 500},
+
+ /** @private {string} */
+ minScanSpeedLabelSec_: {
+ readOnly: true,
+ type: String,
+ value: function() {
+ return this.scanSpeedStringInSec_(this.minScanSpeedMs_);
+ },
+ },
+
+ /** @private {Array<Object>} */
+ switchAssignOptions_: {
+ readOnly: true,
+ type: Array,
+ value: function() {
+ return [
+ {
+ value: SwitchAccessAssignmentValue.NONE,
+ name: this.i18n('switchAssignOptionNone')
+ },
+ {
+ value: SwitchAccessAssignmentValue.SPACE,
+ name: this.i18n('switchAssignOptionSpace')
+ },
+ {
+ value: SwitchAccessAssignmentValue.ENTER,
+ name: this.i18n('switchAssignOptionEnter')
+ },
+ ];
+ },
+ },
+ },
+
+ /**
+ * @return {string}
+ * @private
+ */
+ currentSpeed_: function() {
+ const speed = this.get('prefs.switch_access.auto_scan.speed_ms.value');
+ if (typeof speed != 'number') {
+ return '';
+ }
+ return this.scanSpeedStringInSec_(speed);
+ },
+
+ /**
+ * @return {string} label for the speed slider.
+ * @private
+ */
+ getLabelForSpeedSlider_: function() {
+ const speedString = this.currentSpeed_();
+ return this.i18n('switchAccessAutoScanSpeedLabel', speedString);
+ },
+
+ /**
+ * @param {string} command
+ */
+ onSwitchAssigned_: function(command) {
+ const pref = 'prefs.switch_access.' + command;
+ const keyCodeSuffix = '.key_codes.value';
+ const settingSuffix = '.setting.value';
+
+ switch (this.get(pref + settingSuffix)) {
+ case SwitchAccessAssignmentValue.NONE:
+ this.set(pref + keyCodeSuffix, []);
+ break;
+ case SwitchAccessAssignmentValue.SPACE:
+ this.set(pref + keyCodeSuffix, [32]);
+ break;
+ case SwitchAccessAssignmentValue.ENTER:
+ this.set(pref + keyCodeSuffix, [13]);
+ break;
+ }
+ },
+
+ onNextAssigned_: function() {
+ this.onSwitchAssigned_('next');
+ },
+
+ onPreviousAssigned_: function() {
+ this.onSwitchAssigned_('previous');
+ },
+
+ onSelectAssigned_: function() {
+ this.onSwitchAssigned_('select');
+ },
+
+ /**
+ * @param {number} scanSpeedValueMs
+ * @return {string} a string representing the scan speed in seconds.
+ * @private
+ */
+ scanSpeedStringInSec_: function(scanSpeedValueMs) {
+ const scanSpeedValueSec = scanSpeedValueMs / 1000;
+ return this.i18n(
+ 'durationInSeconds', this.formatter_.format(scanSpeedValueSec));
+ },
+});
diff --git a/chromium/chrome/browser/resources/settings/a11y_page/tts_subpage.html b/chromium/chrome/browser/resources/settings/a11y_page/tts_subpage.html
index 5866fcc1539..6d66dfe0934 100644
--- a/chromium/chrome/browser/resources/settings/a11y_page/tts_subpage.html
+++ b/chromium/chrome/browser/resources/settings/a11y_page/tts_subpage.html
@@ -1,12 +1,12 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html"
+<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../controls/settings_slider.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../languages_page/languages_browser_proxy.html">
@@ -31,14 +31,16 @@
--cr-input-error-display: none;
}
- #previewInput paper-button {
+ #previewInput cr-button {
margin-inline-start: 8px;
}
</style>
<h2>$i18n{textToSpeechProperties}</h2>
<div class="settings-box first">
- <div class="start" id="rate">$i18n{textToSpeechRate}</div>
+ <div class="start settings-box-text" id="rate">
+ $i18n{textToSpeechRate}
+ </div>
<settings-slider show-markers
pref="{{prefs.settings.tts.speech_rate}}"
ticks="[[speechRateTicks_()]]"
@@ -48,7 +50,9 @@
</settings-slider>
</div>
<div class="settings-box continuation">
- <div class="start" id="pitch">$i18n{textToSpeechPitch}</div>
+ <div class="start settings-box-text" id="pitch">
+ $i18n{textToSpeechPitch}
+ </div>
<settings-slider show-markers
pref="{{prefs.settings.tts.speech_pitch}}"
ticks="[[speechPitchTicks_()]]"
@@ -58,7 +62,9 @@
</settings-slider>
</div>
<div class="settings-box continuation">
- <div class="start" id="volume">$i18n{textToSpeechVolume}</div>
+ <div class="start settings-box-text" id="volume">
+ $i18n{textToSpeechVolume}
+ </div>
<settings-slider show-markers
pref="{{prefs.settings.tts.speech_volume}}"
ticks="[[speechVolumeTicks_()]]"
@@ -70,7 +76,7 @@
<h2>$i18n{textToSpeechPreviewHeading}</h2>
<div class="settings-box first">
- <div class="start">
+ <div class="start settings-box-text">
$i18n{textToSpeechPreviewVoice}
</div>
<select id="previewVoice" class="md-select"
@@ -90,12 +96,12 @@
<cr-input id="previewInput" label="$i18n{textToSpeechPreviewInputLabel}"
value="{{previewText_}}"
disabled="[[isPreviewing_]]">
- <paper-button on-click="onPreviewTtsClick_"
+ <cr-button on-click="onPreviewTtsClick_"
disabled$="[[!enablePreviewButton_(allVoices, isPreviewing_,
previewText_)]]"
slot="suffix">
$i18n{textToSpeechPreviewPlay}
- </paper-button>
+ </cr-button>
</cr-input>
</div>
@@ -104,7 +110,7 @@
filter="isPrimaryLanguage_"
sort="alphabeticalSort_">
<div class="settings-box first">
- <div class="start">
+ <div class="start settings-box-text">
[[lang.language]]
</div>
<settings-dropdown-menu label="[[lang.language]]"
@@ -127,7 +133,7 @@
<template is="dom-repeat" items="[[languagesToVoices]]"
as="lang" sort="alphabeticalSort_" filter="isSecondaryLanguage_">
<div class="settings-box continuation">
- <div class="start">
+ <div class="start settings-box-text">
[[lang.language]]
</div>
<settings-dropdown-menu label="[[lang.language]]"
@@ -140,21 +146,21 @@
</div>
</template>
</iron-collapse>
- <div class="settings-box first" hidden$="[[hasVoices]]">
+ <div class="settings-box first settings-box-text" hidden$="[[hasVoices]]">
$i18n{textToSpeechNoVoicesMessage}
</div>
<h2>$i18n{textToSpeechEngines}</h2>
<template is="dom-repeat" items="[[extensions]]" as="extension">
<div class="settings-box continuation">
- <div id="extension_name_[[index]]" class="start">
+ <div id="extension_name_[[index]]" class="start settings-box-text">
[[extension.name]]
</div>
- <paper-button on-click="onEngineSettingsTap_"
+ <cr-button on-click="onEngineSettingsTap_"
aria-describedby$="extension_name_[[index]]"
hidden$="[[!extension.optionsPage]]">
$i18n{settings}
- </paper-button>
+ </cr-button>
</div>
</template>
</template>
diff --git a/chromium/chrome/browser/resources/settings/about_page/about_page.html b/chromium/chrome/browser/resources/settings/about_page/about_page.html
index 9c777d16b48..18c371cdbbe 100644
--- a/chromium/chrome/browser/resources/settings/about_page/about_page.html
+++ b/chromium/chrome/browser/resources/settings/about_page/about_page.html
@@ -11,6 +11,7 @@
<link rel="import" href="../settings_page/settings_section.html">
<link rel="import" href="../settings_page_css.html">
<link rel="import" href="../settings_shared_css.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
@@ -18,7 +19,6 @@
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<if expr="chromeos">
<link rel="import" href="detailed_build_info.html">
@@ -72,7 +72,7 @@
overflow-x: auto;
}
- paper-button {
+ cr-button {
white-space: nowrap;
}
@@ -103,15 +103,19 @@
src URL -->
<!-- Set the icon from the iconset (when it's obsolete/EOL and
when update is done) or set the src (when it's updating). -->
+<if expr="not chromeos">
<div class="icon-container"
hidden="[[!shouldShowIcons_(showUpdateStatus_)]]">
<iron-icon
-<if expr="not chromeos">
icon$="[[getUpdateStatusIcon_(
obsoleteSystemInfo_, currentUpdateStatusEvent_)]]"
src="[[getThrobberSrcIfUpdating_(obsoleteSystemInfo_, currentUpdateStatusEvent_)]]">
</if>
<if expr="chromeos">
+ <div class="icon-container"
+ hidden="[[!shouldShowIcons_(showUpdateStatus_,
+ showOsSettings_)]]">
+ <iron-icon
icon$="[[getUpdateStatusIcon_(
hasEndOfLife_, currentUpdateStatusEvent_)]]"
src="[[getThrobberSrcIfUpdating_(hasEndOfLife_, currentUpdateStatusEvent_)]]">
@@ -157,41 +161,38 @@
</div>
<div class="separator" hidden="[[!showButtonContainer_]]"></div>
<span id="buttonContainer" hidden="[[!showButtonContainer_]]">
- <paper-button id="relaunch" class="secondary-button"
- hidden="[[!showRelaunch_]]" on-click="onRelaunchTap_">
+ <cr-button id="relaunch" hidden="[[!showRelaunch_]]"
+ on-click="onRelaunchTap_">
$i18n{aboutRelaunch}
- </paper-button>
+ </cr-button>
<if expr="chromeos">
- <paper-button id="relaunchAndPowerwash" class="secondary-button"
+ <cr-button id="relaunchAndPowerwash"
hidden="[[!showRelaunchAndPowerwash_]]"
on-click="onRelaunchAndPowerwashTap_">
$i18n{aboutRelaunchAndPowerwash}
- </paper-button>
- <paper-button id="checkForUpdates" class="secondary-button"
- hidden="[[!showCheckUpdates_]]"
+ </cr-button>
+ <cr-button id="checkForUpdates" hidden="[[!showCheckUpdates_]]"
on-click="onCheckUpdatesTap_">
$i18n{aboutCheckForUpdates}
- </paper-button>
+ </cr-button>
</if>
</span>
</div>
<if expr="chromeos">
- <div id="aboutTPMFirmwareUpdate" class="settings-box two-line"
+ <cr-link-row
+ id="aboutTPMFirmwareUpdate"
+ class="hr"
hidden$="[[!showTPMFirmwareUpdateLineItem_]]"
- on-click="onTPMFirmwareUpdateTap_" actionable>
- <div class="start">
- <div>$i18n{aboutTPMFirmwareUpdateTitle}</div>
- <div class="secondary">
- $i18n{aboutTPMFirmwareUpdateDescription}
- <a href="$i18n{aboutTPMFirmwareUpdateLearnMoreURL}"
- target="_blank" on-click="onLearnMoreTap_">
- $i18n{learnMore}
- </a>
- </div>
+ label="$i18n{aboutTPMFirmwareUpdateTitle}"
+ on-click="onTPMFirmwareUpdateTap_">
+ <div slot="sub-label">
+ $i18n{aboutTPMFirmwareUpdateDescription}
+ <a href="$i18n{aboutTPMFirmwareUpdateLearnMoreURL}"
+ target="_blank" on-click="onLearnMoreTap_">
+ $i18n{learnMore}
+ </a>
</div>
- <cr-icon-button class="subpage-arrow"
- aria-labelledby="aboutTPMFirmwareUpdate"></cr-icon-button>
- </div>
+ </cr-link-row>
</if>
<if expr="_google_chrome and is_macosx">
<template is="dom-if" if="[[!promoteUpdaterStatus_.hidden]]">
@@ -214,16 +215,32 @@
</div>
</template>
</if>
+<if expr="chromeos">
+ <template is="dom-if" if="[[hasReleaseNotes_]]">
+ <cr-link-row class="hr" id="releaseNotesOnline"
+ hidden="[[!hasInternetConnection_]]"
+ on-click="onReleaseNotesTap_"
+ label="$i18n{aboutShowReleaseNotes}" external></cr-link-row>
+ <cr-link-row class="hr" id="releaseNotesOffline"
+ hidden="[[hasInternetConnection_]]"
+ on-click="onReleaseNotesTap_"
+ label="$i18n{aboutShowReleaseNotes}"
+ title="$i18n{aboutReleaseNotesOffline}" external></cr-link-row>
+ </template>
+</if>
<cr-link-row class="hr" id="help" on-click="onHelpTap_"
label="$i18n{aboutGetHelpUsingChrome}" external></cr-link-row>
<if expr="_google_chrome">
<cr-link-row class="hr" id="reportIssue" on-click="onReportIssueTap_"
+ hidden="[[!prefs.feedback_allowed.value]]"
label="$i18n{aboutReportAnIssue}"></cr-link-row>
</if>
<if expr="chromeos">
<cr-link-row class="hr" id="detailed-build-info-trigger"
on-click="onDetailedBuildInfoTap_"
- label="$i18n{aboutDetailedBuildInfo}"></cr-link-row>
+ label="$i18n{aboutDetailedBuildInfo}"
+ hidden$="[[!showOsSettings_]]">
+ </cr-link-row>
</if>
<cr-link-row class="hr" on-click="onManagementPageTap_"
start-icon="cr:domain" label="$i18n{managementPage}"
@@ -249,10 +266,9 @@
<div class="info-section">
<div class="secondary">$i18nRaw{aboutProductLicense}</div>
<if expr="chromeos">
- <div class="secondary"
+ <div id="crostiniLicense" class="secondary"
inner-h-t-m-l="[[getAboutProductOsLicense_(
- showCrostiniLicense_)]]">
- </div>
+ showCrostiniLicense_)]]" hidden$="[[!showOsSettings_]]"></div>
</if>
</div>
<if expr="_google_chrome">
@@ -261,7 +277,8 @@
</div>
<if expr="chromeos">
<div class="settings-box padded block" id="regulatoryInfo"
- hidden$="[[!shouldShowRegulatoryOrSafetyInfo_(regulatoryInfo_)]]">
+ hidden$="[[!shouldShowRegulatoryOrSafetyInfo_(regulatoryInfo_,
+ showOsSettings_)]]">
<if expr="_google_chrome">
<div class="secondary" hidden$="[[!shouldShowSafetyInfo_()]]">
<a target="_blank" href="$i18n{aboutProductSafetyURL}">
@@ -270,8 +287,7 @@
</div>
</if>
<img src="[[regulatoryInfo_.url]]" alt="[[regulatoryInfo_.text]]"
- hidden$="[[!shouldShowRegulatoryInfo_(regulatoryInfo_)]]"
- role="presentation">
+ hidden$="[[!shouldShowRegulatoryInfo_(regulatoryInfo_)]]">
</div>
</if>
</settings-section>
diff --git a/chromium/chrome/browser/resources/settings/about_page/about_page.js b/chromium/chrome/browser/resources/settings/about_page/about_page.js
index 7f9047f7226..4899236f7b7 100644
--- a/chromium/chrome/browser/resources/settings/about_page/about_page.js
+++ b/chromium/chrome/browser/resources/settings/about_page/about_page.js
@@ -64,8 +64,26 @@ Polymer({
},
/** @private */
+ hasReleaseNotes_: {
+ type: Boolean,
+ value: false,
+ },
+
+ /** @private */
showCrostini: Boolean,
+ /**
+ * When the SplitSettings feature is disabled, the about page shows the OS-
+ * specific parts. When SplitSettings is enabled, the OS-specific parts
+ * will only show up in chrome://os-settings/help.
+ * TODO(aee): remove after SplitSettings feature flag is removed.
+ * @private
+ */
+ showOsSettings_: {
+ type: Boolean,
+ value: () => loadTimeData.getBoolean('showOSSettings'),
+ },
+
/** @private */
showCrostiniLicense_: {
type: Boolean,
@@ -73,6 +91,12 @@ Polymer({
},
// </if>
+ /** @private */
+ hasInternetConnection_: {
+ type: Boolean,
+ value: false,
+ },
+
// <if expr="_google_chrome and is_macosx">
/** @private {!PromoteUpdaterStatus} */
promoteUpdaterStatus_: Object,
@@ -143,7 +167,10 @@ Polymer({
},
/** @private */
- showTPMFirmwareUpdateLineItem_: Boolean,
+ showTPMFirmwareUpdateLineItem_: {
+ type: Boolean,
+ value: false,
+ },
/** @private */
showTPMFirmwareUpdateDialog_: Boolean,
@@ -188,6 +215,10 @@ Polymer({
settings.LifetimeBrowserProxyImpl.getInstance();
// <if expr="chromeos">
+ if (!this.showOsSettings_) {
+ return;
+ }
+
this.addEventListener('target-channel-changed', e => {
this.targetChannel_ = e.detail;
});
@@ -206,6 +237,14 @@ Polymer({
this.hasEndOfLife_ = result;
});
+ this.aboutBrowserProxy_.getEnabledReleaseNotes().then(result => {
+ this.hasReleaseNotes_ = result;
+ });
+
+ this.aboutBrowserProxy_.checkInternetConnection().then(result => {
+ this.hasInternetConnection_ = result;
+ });
+
// </if>
// <if expr="not chromeos">
this.startListening_();
@@ -297,6 +336,11 @@ Polymer({
},
/** @private */
+ onReleaseNotesTap_: function() {
+ this.aboutBrowserProxy_.launchReleaseNotes();
+ },
+
+ /** @private */
onHelpTap_: function() {
this.aboutBrowserProxy_.openHelpPage();
},
@@ -617,7 +661,8 @@ Polymer({
* @private
*/
shouldShowRegulatoryOrSafetyInfo_: function() {
- return this.shouldShowSafetyInfo_() || this.shouldShowRegulatoryInfo_();
+ return this.showOsSettings_ &&
+ (this.shouldShowSafetyInfo_() || this.shouldShowRegulatoryInfo_());
},
/** @private */
diff --git a/chromium/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js b/chromium/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js
index c074d7e2c16..d1f1373396e 100644
--- a/chromium/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js
@@ -153,6 +153,12 @@ cr.define('settings', function() {
*/
refreshUpdateStatus() {}
+ // <if expr="chromeos">
+ /** Opens the release notes app. */
+ launchReleaseNotes() {}
+ // </if>
+
+
/** Opens the help page. */
openHelpPage() {}
@@ -165,6 +171,9 @@ cr.define('settings', function() {
// </if>
// <if expr="chromeos">
+ /** Opens the OS help page. */
+ openOsHelpPage() {}
+
/**
* Checks for available update and applies if it exists.
*/
@@ -217,6 +226,20 @@ cr.define('settings', function() {
*/
promoteUpdater() {}
// </if>
+
+ // <if expr="chromeos">
+ /**
+ * Checks if the device has release notes enabled.
+ * @return {!Promise<boolean>}
+ */
+ getEnabledReleaseNotes() {}
+
+ /**
+ * Checks if the device is connected to the internet.
+ * @return {!Promise<boolean>}
+ */
+ checkInternetConnection() {}
+ // </if>
}
/**
@@ -242,6 +265,11 @@ cr.define('settings', function() {
// </if>
/** @override */
+ launchReleaseNotes() {
+ chrome.send('launchReleaseNotes');
+ }
+
+ /** @override */
openHelpPage() {
chrome.send('openHelpPage');
}
@@ -256,6 +284,11 @@ cr.define('settings', function() {
// <if expr="chromeos">
/** @override */
+ openOsHelpPage() {
+ chrome.send('openOsHelpPage');
+ }
+
+ /** @override */
requestUpdate() {
chrome.send('requestUpdate');
}
@@ -291,6 +324,16 @@ cr.define('settings', function() {
}
/** @override */
+ getEnabledReleaseNotes() {
+ return cr.sendWithPromise('getEnabledReleaseNotes');
+ }
+
+ /** @override */
+ checkInternetConnection() {
+ return cr.sendWithPromise('checkInternetConnection');
+ }
+
+ /** @override */
refreshTPMFirmwareUpdateStatus() {
chrome.send('refreshTPMFirmwareUpdateStatus');
}
diff --git a/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.html b/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.html
index 8dcad3fd879..a974334455c 100644
--- a/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.html
+++ b/chromium/chrome/browser/resources/settings/about_page/channel_switcher_dialog.html
@@ -1,10 +1,10 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_radio_button/cr_radio_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_radio_group/cr_radio_group.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-selector/iron-selector.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="about_page_browser_proxy.html">
<link rel="import" href="../settings_shared_css.html">
@@ -37,7 +37,7 @@
<h2>$i18n{aboutDelayedWarningTitle}</h2>
<div>[[substituteString_(
'$i18nPolymer{aboutDelayedWarningMessage}',
- '$i18nPolymer{aboutProductTitle}')]]</div>
+ '$i18nPolymer{aboutOsProductTitle}')]]</div>
</div>
<div>
<h2>$i18n{aboutPowerwashWarningTitle}</h2>
@@ -47,23 +47,23 @@
<h2>$i18n{aboutUnstableWarningTitle}</h2>
<div>[[substituteString_(
'$i18nPolymer{aboutUnstableWarningMessage}',
- '$i18nPolymer{aboutProductTitle}')]]</div>
+ '$i18nPolymer{aboutOsProductTitle}')]]</div>
</div>
</iron-selector>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelTap_"
- id="cancel">$i18n{cancel}</paper-button>
- <paper-button id="changeChannel" class="action-button"
+ <cr-button class="cancel-button" on-click="onCancelTap_"
+ id="cancel">$i18n{cancel}</cr-button>
+ <cr-button id="changeChannel" class="action-button"
on-click="onChangeChannelTap_"
hidden="[[!shouldShowButtons_.changeChannel]]">
$i18n{aboutChangeChannel}
- </paper-button>
- <paper-button id="changeChannelAndPowerwash" class="action-button"
+ </cr-button>
+ <cr-button id="changeChannelAndPowerwash" class="action-button"
on-click="onChangeChannelAndPowerwashTap_"
hidden="[[!shouldShowButtons_.changeChannelAndPowerwash]]">
$i18n{aboutChangeChannelAndPowerwash}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.html b/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.html
index dd300b5449e..2369486bc71 100644
--- a/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.html
+++ b/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.html
@@ -6,9 +6,9 @@
<link rel="import" href="channel_switcher_dialog.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../settings_shared_css.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_indicator.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<dom-module id="settings-detailed-build-info">
<template>
@@ -39,10 +39,10 @@
<div class="secondary">[[currentlyOnChannelText_]]</div>
</div>
<div class="separator"></div>
- <paper-button on-click="onChangeChannelTap_"
+ <cr-button on-click="onChangeChannelTap_"
disabled="[[!canChangeChannel_]]">
$i18n{aboutChangeChannel}
- </paper-button>
+ </cr-button>
<template is="dom-if" if="[[!canChangeChannel_]]">
<cr-policy-indicator
indicator-source-name="[[getChangeChannelIndicatorSourceName_(
diff --git a/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.js b/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.js
index e63021ebe7e..18ad3b217ed 100644
--- a/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.js
+++ b/chromium/chrome/browser/resources/settings/about_page/detailed_build_info.js
@@ -96,7 +96,7 @@ Polymer({
/** @private */
onChannelSwitcherDialogClosed_: function() {
this.showChannelSwitcherDialog_ = false;
- cr.ui.focusWithoutInk(assert(this.$$('paper-button')));
+ cr.ui.focusWithoutInk(assert(this.$$('cr-button')));
this.updateChannelInfo_();
},
});
diff --git a/chromium/chrome/browser/resources/settings/about_page/update_warning_dialog.html b/chromium/chrome/browser/resources/settings/about_page/update_warning_dialog.html
index 73621cfe225..b6fe9f3a612 100644
--- a/chromium/chrome/browser/resources/settings/about_page/update_warning_dialog.html
+++ b/chromium/chrome/browser/resources/settings/about_page/update_warning_dialog.html
@@ -1,8 +1,8 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="about_page_browser_proxy.html">
<link rel="import" href="../settings_shared_css.html">
@@ -15,12 +15,12 @@
<div id="update-warning-message"></div>
</div>
<div slot="button-container">
- <paper-button id="cancel" class="cancel-button"
- on-click="onCancelTap_">$i18n{cancel}</paper-button>
- <paper-button id="continue" class="action-button"
+ <cr-button id="cancel" class="cancel-button"
+ on-click="onCancelTap_">$i18n{cancel}</cr-button>
+ <cr-button id="continue" class="action-button"
on-click="onContinueTap_">
- $i18n{aboutUpdateWarningContinue}
- </paper-button>
+ $i18n{continue}
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_page.html b/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_page.html
index bccb0f2a902..39116e40833 100644
--- a/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_page.html
+++ b/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_page.html
@@ -1,10 +1,10 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../prefs/prefs_behavior.html">
<link rel="import" href="../settings_page/settings_animated_pages.html">
@@ -21,10 +21,10 @@
focus-config="[[focusConfig_]]">
<div route-path="default">
<template is="dom-if" if="[[havePlayStoreApp]]" restamp>
- <div id="android-apps" class="settings-box two-line first"
+ <div id="android-apps" class="settings-box first"
actionable$="[[androidAppsInfo.playStoreEnabled]]"
on-click="onSubpageTap_">
- <div class="start">
+ <div class="start settings-box-text">
$i18n{androidAppsPageLabel}
<div class="secondary" id="secondaryText"
inner-h-t-m-l="[[i18nAdvanced('androidAppsSubtext')]]">
@@ -40,13 +40,13 @@
</template>
<template is="dom-if" if="[[!androidAppsInfo.playStoreEnabled]]">
<div class="separator"></div>
- <paper-button id="enable" class="secondary-button"
+ <cr-button id="enable"
disabled="[[isEnforced_(prefs.arc.enabled)]]"
on-click="onEnableTap_"
aria-label="$i18n{androidAppsPageTitle}"
aria-describedby="secondaryText">
$i18n{androidAppsEnable}
- </paper-button>
+ </cr-button>
</template>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_subpage.html b/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_subpage.html
index f27ac898cdd..b0d86e21b93 100644
--- a/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_subpage.html
+++ b/chromium/chrome/browser/resources/settings/android_apps_page/android_apps_subpage.html
@@ -1,11 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="android_apps_browser_proxy.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../prefs/prefs_behavior.html">
@@ -34,14 +34,14 @@
<div slot="title">$i18n{androidAppsDisableDialogTitle}</div>
<div slot="body" inner-h-t-m-l="[[dialogBody_]]"></div>
<div slot="button-container">
- <paper-button class="cancel-button"
+ <cr-button class="cancel-button"
on-click="onConfirmDisableDialogCancel_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button"
+ </cr-button>
+ <cr-button class="action-button"
on-click="onConfirmDisableDialogConfirm_">
$i18n{androidAppsDisableDialogRemove}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
diff --git a/chromium/chrome/browser/resources/settings/app_management_page/BUILD.gn b/chromium/chrome/browser/resources/settings/app_management_page/BUILD.gn
index 8bc0597c70c..d404c63c107 100644
--- a/chromium/chrome/browser/resources/settings/app_management_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/app_management_page/BUILD.gn
@@ -12,8 +12,7 @@ js_type_check("closure_compile") {
js_library("app_management_page") {
deps = [
- "../prefs:prefs_behavior",
- "//ui/webui/resources/js:i18n_behavior",
+ "..:open_window_proxy",
]
- externs_list = [ "$externs_path/settings_private.js" ]
+ externs_list = [ "$externs_path/metrics_private.js" ]
}
diff --git a/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.html b/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.html
index bdd793d8fbd..cab1b4a924f 100644
--- a/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.html
+++ b/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.html
@@ -1,12 +1,13 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="../open_window_proxy.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
-<link rel="import" href="../settings_shared_css.html">
<dom-module id="settings-app-management-page">
<template>
- <cr-link-row class="hr" id="app-management-trigger"
- label="$i18n{manageYourApps}" on-click="onManageAppsClick_">
+ <cr-link-row id="appManagementButton"
+ label="$i18n{manageYourApps}" sub-label="$i18n{manageYourAppsSublabel}"
+ on-click="openAppManagement_" external>
</cr-link-row>
</template>
<script src="app_management_page.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.js b/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.js
index 57a46ecca57..da525757d79 100644
--- a/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.js
+++ b/chromium/chrome/browser/resources/settings/app_management_page/app_management_page.js
@@ -11,7 +11,9 @@ Polymer({
is: 'settings-app-management-page',
/** @private */
- onManageAppsClick_: function() {
- window.location.href = 'chrome://app-management';
+ openAppManagement_: function() {
+ chrome.metricsPrivate.recordUserAction('SettingsPage.OpenAppManagement');
+ settings.OpenWindowProxyImpl.getInstance().openURL(
+ 'chrome://app-management');
},
});
diff --git a/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.html b/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.html
index e531e1a0d22..c79e375102d 100644
--- a/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.html
+++ b/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.html
@@ -23,7 +23,7 @@
}
</style>
<div class="settings-box first">
- <div class="start">$i18n{fontSize}</div>
+ <div class="start settings-box-text">$i18n{fontSize}</div>
<settings-slider id="sizeSlider"
pref="{{prefs.webkit.webprefs.default_font_size}}"
ticks="[[fontSizeRange_]]"
@@ -31,16 +31,18 @@
</settings-slider>
</div>
<div class="settings-box">
- <div class="start">$i18n{minimumFont}</div>
+ <div class="start settings-box-text">$i18n{minimumFont}</div>
<div id="minimumSize">
<settings-slider pref="{{prefs.webkit.webprefs.minimum_font_size}}"
ticks="[[minimumFontSizeRange_]]" label-min="$i18n{tiny}"
label-max="$i18n{huge}"></settings-slider>
- <div id="minimumSizeSample" style="
- font-size:[[computeMinimumFontSize_(
- prefs.webkit.webprefs.minimum_font_size.value)]]px;
- font-family:
- '[[prefs.webkit.webprefs.fonts.standard.Zyyy.value]]';">
+ <div id="minimumSizeSample"
+ style="
+ font-size:[[computeMinimumFontSize_(
+ prefs.webkit.webprefs.minimum_font_size.value)]]px;
+ font-family:
+ '[[prefs.webkit.webprefs.fonts.standard.Zyyy.value]]';"
+ hidden>
[[computeMinimumFontSize_(
prefs.webkit.webprefs.minimum_font_size.value)]]:
$i18n{quickBrownFox}
@@ -57,7 +59,7 @@
menu-options="[[fontOptions_]]">
</settings-dropdown-menu>
</div>
- <div class="list-item"
+ <div class="list-item settings-box-text"
style="
font-size:[[prefs.webkit.webprefs.default_font_size.value]]px;
font-family:
@@ -78,7 +80,7 @@
menu-options="[[fontOptions_]]">
</settings-dropdown-menu>
</div>
- <div class="list-item"
+ <div class="list-item settings-box-text"
style="
font-size:[[prefs.webkit.webprefs.default_font_size.value]]px;
font-family:
@@ -99,7 +101,7 @@
menu-options="[[fontOptions_]]">
</settings-dropdown-menu>
</div>
- <div class="list-item"
+ <div class="list-item settings-box-text"
style="
font-size:[[prefs.webkit.webprefs.default_font_size.value]]px;
font-family:
@@ -120,7 +122,7 @@
menu-options="[[fontOptions_]]">
</settings-dropdown-menu>
</div>
- <div class="list-item"
+ <div class="list-item settings-box-text"
style="
font-size:
[[prefs.webkit.webprefs.default_fixed_font_size.value]]px;
diff --git a/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js b/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js
index e3877f978a3..7852e2ec734 100644
--- a/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js
+++ b/chromium/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js
@@ -76,6 +76,10 @@ Polymer({
},
},
+ observers: [
+ 'onMinimumSizeChange_(prefs.webkit.webprefs.minimum_font_size.value)',
+ ],
+
/** @private {?settings.FontsBrowserProxy} */
browserProxy_: null,
@@ -136,12 +140,18 @@ Polymer({
/**
* Get the minimum font size, accounting for unset prefs.
- * @return {?}
+ * @return {number}
* @private
*/
computeMinimumFontSize_: function() {
- return this.get('prefs.webkit.webprefs.minimum_font_size.value') ||
- MINIMUM_FONT_SIZE_RANGE[0];
+ const prefValue = this.get('prefs.webkit.webprefs.minimum_font_size.value');
+ return /** @type {number} */ (prefValue) || MINIMUM_FONT_SIZE_RANGE[0];
+ },
+
+
+ /** @private */
+ onMinimumSizeChange_: function() {
+ this.$.minimumSizeSample.hidden = this.computeMinimumFontSize_() <= 0;
},
});
})();
diff --git a/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html b/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html
index e9797c97d52..df9863a3a64 100644
--- a/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html
+++ b/chromium/chrome/browser/resources/settings/appearance_page/appearance_page.html
@@ -1,9 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="appearance_browser_proxy.html">
<link rel="import" href="../controls/controlled_radio_button.html">
<link rel="import" href="../controls/extension_controlled_indicator.html">
@@ -23,18 +23,17 @@
<style include="settings-shared md-select iron-flex">
/* Lines up with cr-input. */
#custom-input {
- --cr-radio-button-disc: {
- /* (cr-input line-height + cr-input top/bottom padding) / 2 -
- cr-radio disc-wrapper height / 2 */
- margin-top: calc((1.54em + 12px) / 2 - 8px);
- }
+ /* (cr-input line-height + cr-input top/bottom padding) / 2 -
+ cr-radio disc-wrapper height / 2 */
+ --cr-radio-button-disc-margin-block-start: calc(
+ (1.54em + 12px) / 2 - 8px);
align-items: start;
}
- /* The theme mixes a link and a paper-button divided by a separator with
+ /* The theme mixes a link and a cr-button divided by a separator with
* grit expressions and dom-if templates. That leads to a tricky thing
* to style correctly, these are a workaround. */
- #themeRow paper-button {
+ #themeRow cr-button {
margin-inline-end: 20px;
}
@@ -67,31 +66,28 @@
<if expr="not is_linux or chromeos">
<template is="dom-if" if="[[prefs.extensions.theme.id.value]]">
<div class="separator"></div>
- <paper-button id="useDefault" on-click="onUseDefaultTap_"
- class="secondary-button">
+ <cr-button id="useDefault" on-click="onUseDefaultTap_">
$i18n{resetToDefaultTheme}
- </paper-button>
+ </cr-button>
</template>
</if>
<if expr="is_linux and not chromeos">
<div class="settings-row continuation"
hidden="[[!showThemesSecondary_(
- prefs.extensions.theme.id.value, useSystemTheme_)]]"
+ prefs.extensions.theme.id.value, useSystemTheme_)]]"
id="themesSecondaryActions">
<div class="separator"></div>
<template is="dom-if" if="[[showUseClassic_(
prefs.extensions.theme.id.value, useSystemTheme_)]]" restamp>
- <paper-button id="useDefault" on-click="onUseDefaultTap_"
- class="secondary-button">
+ <cr-button id="useDefault" on-click="onUseDefaultTap_">
$i18n{useClassicTheme}
- </paper-button>
+ </cr-button>
</template>
<template is="dom-if" if="[[showUseSystem_(
prefs.extensions.theme.id.value, useSystemTheme_)]]" restamp>
- <paper-button id="useSystem" on-click="onUseSystemTap_"
- class="secondary-button">
+ <cr-button id="useSystem" on-click="onUseSystemTap_">
$i18n{useSystemTheme}
- </paper-button>
+ </cr-button>
</template>
</div>
</if>
@@ -147,7 +143,7 @@
</settings-toggle-button>
</if>
<div class="settings-box">
- <div class="start">$i18n{fontSize}</div>
+ <div class="start settings-box-text">$i18n{fontSize}</div>
<settings-dropdown-menu id="defaultFontSize" label="$i18n{fontSize}"
pref="{{prefs.webkit.webprefs.default_font_size}}"
menu-options="[[fontSizeOptions_]]">
@@ -157,7 +153,9 @@
label="$i18n{customizeFonts}" on-click="onCustomizeFontsTap_">
</cr-link-row>
<div class="settings-box" hidden="[[!pageVisibility.pageZoom]]">
- <div id="pageZoom" class="start">$i18n{pageZoom}</div>
+ <div id="pageZoom" class="start settings-box-text">
+ $i18n{pageZoom}
+ </div>
<select id="zoomLevel" class="md-select" aria-labelledby="pageZoom"
on-change="onZoomLevelChange_">
<template is="dom-repeat" items="[[pageZoomLevels_]]">
diff --git a/chromium/chrome/browser/resources/settings/appearance_page/home_url_input.html b/chromium/chrome/browser/resources/settings/appearance_page/home_url_input.html
index d2db2dc0d01..6d293ea3061 100644
--- a/chromium/chrome/browser/resources/settings/appearance_page/home_url_input.html
+++ b/chromium/chrome/browser/resources/settings/appearance_page/home_url_input.html
@@ -20,6 +20,10 @@
width: 100%;
--cr-input-width: 50%;
}
+
+ cr-input::part(row-container) {
+ justify-content: normal;
+ }
</style>
<!-- Max length of 100 KB to prevent browser from freezing. -->
<cr-input id="input" value="{{value}}" error-message="$i18n{notValid}"
diff --git a/chromium/chrome/browser/resources/settings/autofill_page/address_edit_dialog.html b/chromium/chrome/browser/resources/settings/autofill_page/address_edit_dialog.html
index fb0eafae545..b2eb9d48433 100644
--- a/chromium/chrome/browser/resources/settings/autofill_page/address_edit_dialog.html
+++ b/chromium/chrome/browser/resources/settings/autofill_page/address_edit_dialog.html
@@ -1,18 +1,20 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="../settings_vars_css.html">
<link rel="import" href="../controls/settings_textarea.html">
<dom-module id="settings-address-edit-dialog">
<template>
- <style include="settings-shared md-select">
+ <style include="cr-shared-style settings-shared md-select">
:host {
white-space: nowrap;
}
@@ -36,14 +38,6 @@
--md-select-width: var(--settings-input-max-width);
}
- #select-label {
- @apply --cr-form-field-label;
- }
-
- :host-context([dir=rtl]) #select-label {
- transform-origin: right;
- }
-
.long {
width: var(--settings-input-max-width);
}
@@ -58,17 +52,13 @@
margin-bottom: var(--cr-form-field-bottom-spacing);
}
- #dialog {
- --cr-dialog-body-container: {
- max-height: 450px;
- };
+ #dialog::part(body-container) {
+ max-height: 450px;
}
@media all and (max-height: 714px) {
- #dialog {
- --cr-dialog-body-container: {
- max-height: 270px;
- };
+ #dialog::part(body-container) {
+ max-height: 270px;
}
}
</style>
@@ -96,7 +86,9 @@
</div>
</template>
<div id="select-row" class="address-row">
- <div id="select-label">$i18n{addressCountry}</div>
+ <label id="select-label" class="cr-form-field-label">
+ $i18n{addressCountry}
+ </label>
<select class="md-select" aria-labelledby="select-label"
value="[[countryCode_]]" on-change="onCountryChange_">
<option value=""></option>
@@ -120,14 +112,14 @@
</div>
</div>
<div slot="button-container">
- <paper-button id="cancelButton" class="cancel-button"
+ <cr-button id="cancelButton" class="cancel-button"
on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button id="saveButton" class="action-button"
+ </cr-button>
+ <cr-button id="saveButton" class="action-button"
disabled="[[!canSave_]]" on-click="onSaveButtonTap_">
$i18n{save}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/autofill_page/autofill_section.html b/chromium/chrome/browser/resources/settings/autofill_page/autofill_section.html
index 8853eaa4133..d7814621568 100644
--- a/chromium/chrome/browser/resources/settings/autofill_page/autofill_section.html
+++ b/chromium/chrome/browser/resources/settings/autofill_page/autofill_section.html
@@ -1,6 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
@@ -46,12 +47,11 @@
</template>
<div class="settings-box continuation">
<h2 class="start">$i18n{addresses}</h2>
- <paper-button id="addAddress"
- class="secondary-button header-aligned-button"
+ <cr-button id="addAddress" class="header-aligned-button"
on-click="onAddAddressTap_"
hidden$="[[!prefs.autofill.profile_enabled.value]]">
$i18n{add}
- </paper-button>
+ </cr-button>
</div>
<div class="list-frame">
<div id="addressList" class="vertical-list">
diff --git a/chromium/chrome/browser/resources/settings/autofill_page/blocking_request_manager.js b/chromium/chrome/browser/resources/settings/autofill_page/blocking_request_manager.js
index 69d4eb60818..b82aa59e60b 100644
--- a/chromium/chrome/browser/resources/settings/autofill_page/blocking_request_manager.js
+++ b/chromium/chrome/browser/resources/settings/autofill_page/blocking_request_manager.js
@@ -8,9 +8,13 @@
*/
cr.define('settings', function() {
class BlockingRequestManager {
- /** @param {Function} makeRequest Function to initiate flow for request. */
+ /**
+ * @param {Function=} makeRequest Function to initiate flow for request. If
+ * no function is provided, it defaults to this.resolve, i.e. it
+ * immediately resolves all requests.
+ */
constructor(makeRequest) {
- this.makeRequest_ = makeRequest;
+ this.makeRequest_ = makeRequest || this.resolve;
/**
* @private {Function} callback Provided in requests and called when the
* request is resolved.
diff --git a/chromium/chrome/browser/resources/settings/autofill_page/credit_card_edit_dialog.html b/chromium/chrome/browser/resources/settings/autofill_page/credit_card_edit_dialog.html
index 304471f26a2..30f32f21490 100644
--- a/chromium/chrome/browser/resources/settings/autofill_page/credit_card_edit_dialog.html
+++ b/chromium/chrome/browser/resources/settings/autofill_page/credit_card_edit_dialog.html
@@ -1,17 +1,18 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="../settings_vars_css.html">
<dom-module id="settings-credit-card-edit-dialog">
<template>
- <style include="settings-shared md-select">
+ <style include="cr-shared-style settings-shared md-select">
cr-input {
--cr-input-error-display: none;
margin-bottom: var(--cr-form-field-bottom-spacing);
@@ -37,10 +38,12 @@
padding: 0 0 0 8px;
}
- :host-context([dark]) #expired {
- background-color: unset;
- font-weight: bold;
- padding: 0;
+ @media (prefers-color-scheme: dark) {
+ #expired {
+ background-color: unset;
+ font-weight: bold;
+ padding: 0;
+ }
}
#month {
@@ -54,10 +57,6 @@
#year {
width: 100px;
}
-
- label {
- @apply --cr-form-field-label;
- }
</style>
<cr-dialog id="dialog" close-text="$i18n{close}">
<div slot="title">[[title_]]</div>
@@ -70,10 +69,12 @@
value="{{creditCard.cardNumber}}"
on-input="onCreditCardNameOrNumberChanged_">
</cr-input>
- <label>$i18n{creditCardExpiration}</label>
+ <label id="creditCardExpiration" class="cr-form-field-label">
+ $i18n{creditCardExpiration}
+ </label>
<select class="md-select" id="month" value="[[expirationMonth_]]"
on-change="onMonthChange_"
- aria-label="$i18n{creditCardExpirationMonth}">
+ aria-labelledby="creditCardExpiration">
<template is="dom-repeat" items="[[monthList_]]">
<option>[[item]]</option>
</template>
@@ -95,10 +96,10 @@
</div>
</div>
<div slot="button-container">
- <paper-button id="cancelButton" class="cancel-button"
- on-click="onCancelButtonTap_">$i18n{cancel}</paper-button>
- <paper-button id="saveButton" class="action-button"
- on-click="onSaveButtonTap_" disabled>$i18n{save}</paper-button>
+ <cr-button id="cancelButton" class="cancel-button"
+ on-click="onCancelButtonTap_">$i18n{cancel}</cr-button>
+ <cr-button id="saveButton" class="action-button"
+ on-click="onSaveButtonTap_" disabled>$i18n{save}</cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/autofill_page/password_edit_dialog.html b/chromium/chrome/browser/resources/settings/autofill_page/password_edit_dialog.html
index b10ede531f7..6cb9d2b64fd 100644
--- a/chromium/chrome/browser/resources/settings/autofill_page/password_edit_dialog.html
+++ b/chromium/chrome/browser/resources/settings/autofill_page/password_edit_dialog.html
@@ -1,11 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../icons.html">
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="../settings_vars_css.html">
@@ -29,23 +29,22 @@
#passwordInput {
--cr-input-width: var(--settings-input-max-width);
- --cr-input-row-container: {
- justify-content: initial;
- }
}
- #passwordInput {
- --cr-input-input: {
+ #passwordInput::part(row-container) {
+ justify-content: initial;
+ }
+
+ #passwordInput::part(input) {
<if expr="chromeos or is_linux">
- font-family: 'DejaVu Sans Mono', monospace;
+ font-family: 'DejaVu Sans Mono', monospace;
</if>
<if expr="is_win">
- font-family: 'Consolas', monospace;
+ font-family: 'Consolas', monospace;
</if>
<if expr="is_macosx">
- font-family: 'Menlo', monospace;
+ font-family: 'Menlo', monospace;
</if>
- }
}
cr-icon-button {
@@ -77,9 +76,9 @@
</cr-input>
</div>
<div slot="button-container">
- <paper-button class="action-button" on-click="onActionButtonTap_">
+ <cr-button class="action-button" on-click="onActionButtonTap_">
$i18n{done}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/autofill_page/passwords_export_dialog.html b/chromium/chrome/browser/resources/settings/autofill_page/passwords_export_dialog.html
index ab305896fc3..ae962e2577f 100644
--- a/chromium/chrome/browser/resources/settings/autofill_page/passwords_export_dialog.html
+++ b/chromium/chrome/browser/resources/settings/autofill_page/passwords_export_dialog.html
@@ -1,9 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-progress/paper-progress.html">
<link rel="import" href="../settings_shared_css.html">
<if expr="chromeos">
@@ -18,11 +18,13 @@
width: 100%;
}
- :host-context([dark]) paper-progress {
- /* TODO(dbeam): this is the same as downloads (and probably anywhere
- * else that uses paper-progress). Should we make something like a
- * paper_progress_style_css.html? */
- --paper-progress-active-color: var(--google-blue-refresh-300);
+ @media (prefers-color-scheme: dark) {
+ paper-progress {
+ /* TODO(dbeam): this is the same as downloads (and probably anywhere
+ * else that uses paper-progress). Should we make something like a
+ * paper_progress_style_css.html? */
+ --paper-progress-active-color: var(--google-blue-refresh-300);
+ }
}
.action-button {
@@ -38,14 +40,14 @@
</div>
</div>
<div slot="button-container">
- <paper-button class="secondary-button header-aligned-button"
+ <cr-button class="secondary-button header-aligned-button"
on-click="onCancelButtonTap_" id="cancelButton">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button header-aligned-button"
+ </cr-button>
+ <cr-button class="action-button header-aligned-button"
on-click="onExportTap_" id="exportPasswordsButton">
$i18n{exportPasswords}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
@@ -57,11 +59,10 @@
<paper-progress indeterminate class="blue"></paper-progress>
</div>
<div slot="button-container">
- <paper-button id="cancel_progress_button"
- class="secondary-button header-aligned-button"
+ <cr-button id="cancel_progress_button" class="header-aligned-button"
on-click="onCancelProgressButtonTap_">
$i18n{cancel}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
@@ -77,14 +78,14 @@
</ul>
</div>
<div slot="button-container">
- <paper-button class="secondary-button header-aligned-button"
- on-click="onCancelButtonTap_" id="cancelErrorButton">
+ <cr-button class="header-aligned-button" on-click="onCancelButtonTap_"
+ id="cancelErrorButton">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button header-aligned-button"
+ </cr-button>
+ <cr-button class="action-button header-aligned-button"
on-click="onExportTap_" id="tryAgainButton">
$i18n{exportPasswordsTryAgain}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.html b/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.html
index 2f65256cce8..1e7b7923b1a 100644
--- a/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.html
+++ b/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.html
@@ -1,6 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
@@ -164,9 +165,9 @@
</if>
<cr-toast id="undoToast" duration="[[toastDuration_]]">
<div id="undoLabel">$i18n{passwordDeleted}</div>
- <paper-button on-click="onUndoButtonTap_">
+ <cr-button on-click="onUndoButtonTap_">
$i18n{undoRemovePassword}
- </paper-button>
+ </cr-button>
</cr-toast>
<div class="settings-box block first">
<h2>$i18n{passwordExceptionsHeading}</h2>
diff --git a/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.js b/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.js
index 1603dc8b370..1f552fdf4ec 100644
--- a/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.js
+++ b/chromium/chrome/browser/resources/settings/autofill_page/passwords_section.js
@@ -202,8 +202,16 @@ Polymer({
this.passwordManager_ = PasswordManagerImpl.getInstance();
// <if expr="chromeos">
- this.tokenRequestManager_ = new settings.BlockingRequestManager(
- () => this.showPasswordPromptDialog_ = true);
+ // If the user's account supports the password check, an auth token will be
+ // required in order for them to view or export passwords. Otherwise there
+ // is no additional security so |tokenRequestManager_| will immediately
+ // resolve requests.
+ if (loadTimeData.getBoolean('userCannotManuallyEnterPassword')) {
+ this.tokenRequestManager_ = new settings.BlockingRequestManager();
+ } else {
+ this.tokenRequestManager_ = new settings.BlockingRequestManager(
+ () => this.showPasswordPromptDialog_ = true);
+ }
// </if>
// Request initial data.
diff --git a/chromium/chrome/browser/resources/settings/autofill_page/payments_section.html b/chromium/chrome/browser/resources/settings/autofill_page/payments_section.html
index 8fcf01900f6..5836b23e617 100644
--- a/chromium/chrome/browser/resources/settings/autofill_page/payments_section.html
+++ b/chromium/chrome/browser/resources/settings/autofill_page/payments_section.html
@@ -1,6 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
@@ -61,12 +62,11 @@
<div class="settings-box continuation">
<h2 class="start">$i18n{creditCards}</h2>
- <paper-button id="addCreditCard"
- class="secondary-button header-aligned-button"
+ <cr-button id="addCreditCard" class="header-aligned-button"
on-click="onAddCreditCardTap_"
hidden$="[[!prefs.autofill.credit_card_enabled.value]]">
$i18n{add}
- </paper-button>
+ </cr-button>
</div>
<cr-link-row id="migrateCreditCards"
hidden$="[[!checkIfMigratable_(creditCards,
diff --git a/chromium/chrome/browser/resources/settings/basic_page/basic_page.html b/chromium/chrome/browser/resources/settings/basic_page/basic_page.html
index 8e63bace4df..80d61cd92c3 100644
--- a/chromium/chrome/browser/resources/settings/basic_page/basic_page.html
+++ b/chromium/chrome/browser/resources/settings/basic_page/basic_page.html
@@ -1,5 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
@@ -22,7 +23,6 @@
<link rel="import" href="../bluetooth_page/bluetooth_page.html">
<link rel="import" href="../crostini_page/crostini_page.html">
<link rel="import" href="../plugin_vm_page/plugin_vm_page.html">
-<link rel="import" href="../kiosk_next_shell_page/kiosk_next_shell_page.html">
<link rel="import" href="../device_page/device_page.html">
<link rel="import" href="../internet_page/internet_page.html">
<link rel="import" href="../multidevice_page/multidevice_page.html">
@@ -44,14 +44,22 @@
}
#advancedToggle {
- @apply --cr-actionable;
+ --ink-color: currentColor;
align-items: center;
+ background: transparent;
+ border: none;
+ box-shadow: none;
+ color: currentColor;
display: flex;
+ font-weight: 400;
margin-bottom: 3px;
margin-top: 12px; /* Part of a 48px spacer (33px + 12px + 3px). */
min-height: 32px;
padding: 0 12px;
- text-transform: none;
+ }
+
+ :host-context(.focus-outline-visible) #advancedToggle:focus {
+ font-weight: 600;
}
#secondaryUserBanner {
@@ -196,14 +204,6 @@
</settings-android-apps-page>
</settings-section>
</template>
- <template is="dom-if" if="[[showKioskNextShell]]" restamp>
- <settings-section
- page-title="$i18n{kioskNextShellPageTitle}"
- section="kiosk-next-shell">
- <settings-kiosk-next-shell-page prefs="{{prefs}}">
- </settings-kiosk-next-shell-page>
- </settings-section>
- </template>
<template is="dom-if" if="[[showCrostini]]" restamp>
<settings-section page-title="$i18n{crostiniPageTitle}"
section="crostini">
@@ -244,12 +244,12 @@
inSearchMode, hasExpandedSection_)]]">
<div id="toggleSpacer"></div>
<h2 id="toggleContainer">
- <paper-button id="advancedToggle" on-click="advancedToggleClicked_"
+ <cr-button id="advancedToggle" on-click="advancedToggleClicked_"
aria-expanded$="[[boolToString_(advancedToggleExpanded)]]">
<span>$i18n{advancedPageTitle}</span>
<iron-icon icon="[[getArrowIcon_(advancedToggleExpanded)]]">
</iron-icon>
- </paper-button>
+ </cr-button>
</h2>
</template>
@@ -282,7 +282,8 @@
restamp>
<settings-section page-title="$i18n{languagesPageTitle}"
section="languages">
- <settings-languages-page prefs="{{prefs}}">
+ <settings-languages-page prefs="{{prefs}}"
+ page-visibility="[[pageVisibility.languages]]">
</settings-languages-page>
</settings-section>
</template>
diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js
index a3328e0331b..ead6fe1075e 100644
--- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js
+++ b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js
@@ -91,8 +91,12 @@ Polymer({
if (device.connecting) {
return this.i18n('bluetoothConnecting');
}
- return this.i18n(
- device.connected ? 'bluetoothConnected' : 'bluetoothNotConnected');
+ if (!device.connected) {
+ return this.i18n('bluetoothNotConnected');
+ }
+ return device.batteryPercentage !== undefined ?
+ this.i18n('bluetoothConnectedWithBattery', device.batteryPercentage) :
+ this.i18n('bluetoothConnected');
},
/**
diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.html b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.html
index 3929df27e54..81f28b1245d 100644
--- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.html
+++ b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_page.html
@@ -17,32 +17,38 @@
<dom-module id="settings-bluetooth-page">
<template>
<style include="settings-shared">
+ .link-wrapper {
+ align-items: center;
+ display: flex;
+ flex-grow: 1;
+ }
</style>
<settings-animated-pages id="pages" section="bluetooth"
focus-config="[[focusConfig_]]">
<div route-path="default">
<template is="dom-if" if="[[!isSecondaryUser_]]">
- <div id="bluetoothDevices"
- class="settings-box two-line" actionable on-click="onTap_">
- <iron-icon icon="[[getIcon_(bluetoothToggleState_)]]"></iron-icon>
- <div class="middle settings-box-text">
- $i18n{bluetoothPageTitle}
- <div class="secondary" id="bluetoothSecondary">
- [[getOnOffString_(bluetoothToggleState_,
- '$i18nPolymer{deviceOn}', '$i18nPolymer{deviceOff}')]]
+ <div id="bluetoothDevices" class="settings-box two-line">
+ <div class="link-wrapper" actionable on-click="onTap_">
+ <iron-icon icon="[[getIcon_(bluetoothToggleState_)]]"></iron-icon>
+ <div class="middle settings-box-text">
+ $i18n{bluetoothPageTitle}
+ <div class="secondary" id="bluetoothSecondary">
+ [[getOnOffString_(bluetoothToggleState_,
+ '$i18nPolymer{deviceOn}', '$i18nPolymer{deviceOff}')]]
+ </div>
</div>
+ <cr-policy-pref-indicator
+ icon-aria-label="$i18n{bluetoothPageTitle}"
+ pref="[[prefs.cros.device.allow_bluetooth]]"
+ hidden="[[prefs.cros.device.allow_bluetooth.value]]">
+ </cr-policy-pref-indicator>
+ <template is="dom-if" if="[[bluetoothToggleState_]]">
+ <cr-icon-button class="subpage-arrow"
+ on-click="onSubpageArrowTap_"
+ aria-label="$i18n{bluetoothPageTitle}"
+ aria-describedby="bluetoothSecondary"></cr-icon-button>
+ </template>
</div>
- <cr-policy-pref-indicator
- icon-aria-label="$i18n{bluetoothPageTitle}"
- pref="[[prefs.cros.device.allow_bluetooth]]"
- hidden="[[prefs.cros.device.allow_bluetooth.value]]">
- </cr-policy-pref-indicator>
- <template is="dom-if" if="[[bluetoothToggleState_]]">
- <cr-icon-button class="subpage-arrow"
- on-click="onSubpageArrowTap_"
- aria-label="$i18n{bluetoothPageTitle}"
- aria-describedby="bluetoothSecondary"></cr-icon-button>
- </template>
<div class="separator"></div>
<cr-toggle id="enableBluetooth"
checked="{{bluetoothToggleState_}}"
diff --git a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.js b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.js
index f22bdd000d0..7e2c35f331d 100644
--- a/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.js
+++ b/chromium/chrome/browser/resources/settings/bluetooth_page/bluetooth_subpage.js
@@ -143,6 +143,18 @@ Polymer({
type: Number,
value: 1000,
},
+
+ /**
+ * The time in milliseconds at which discovery was started attempt (when the
+ * page was opened with Bluetooth on, or when Bluetooth turned on while the
+ * page was active).
+ * @private {?number}
+ */
+ discoveryStartTimestampMs_: {
+ type: Number,
+ value: null,
+ },
+
},
observers: [
@@ -392,6 +404,10 @@ Polymer({
this.openDialog_();
}
+ if (isPaired !== undefined && device.transport !== undefined) {
+ this.recordDeviceSelectionDuration_(isPaired, device.transport);
+ }
+
const address = device.address;
this.bluetoothPrivate.connect(address, result => {
if (isPaired) {
@@ -492,10 +508,12 @@ Polymer({
this.updateTimerId_ =
window.setInterval(this.refreshBluetoothList_.bind(this),
this.listUpdateFrequencyMs);
+ this.discoveryStartTimestampMs_ = Date.now();
return;
}
window.clearInterval(this.updateTimerId_);
this.updateTimerId_ = undefined;
+ this.discoveryStartTimestampMs_ = null;
this.deviceList_ = [];
},
@@ -542,5 +560,31 @@ Polymer({
}
chrome.bluetoothPrivate.recordReconnection(success);
- }
+ },
+
+ /**
+ * Record metrics for how long it took between when discovery started on the
+ * Settings page, and the user selected the device they wanted to connect to.
+ * @param {!boolean} wasPaired If the selected device was already
+ * paired.
+ * @param {!chrome.bluetooth.Transport} transport The transport type
+ * of the device.
+ * @private
+ */
+ recordDeviceSelectionDuration_: function(wasPaired, transport) {
+ if (!this.discoveryStartTimestampMs_) {
+ // It's not necessarily an error that |discoveryStartTimestampMs_| isn't
+ // present; it's intentionally cleared after the first device selection
+ // (see further on in this method). Recording subsequent device selections
+ // after the first would provide inflated durations that don't truly
+ // reflect how long it took for the user to find the device they're
+ // looking for.
+ return;
+ }
+
+ chrome.bluetoothPrivate.recordDeviceSelection(
+ Date.now() - this.discoveryStartTimestampMs_, wasPaired, transport);
+
+ this.discoveryStartTimestampMs_ = null;
+ },
});
diff --git a/chromium/chrome/browser/resources/settings/change_password_page/change_password_page.html b/chromium/chrome/browser/resources/settings/change_password_page/change_password_page.html
index 50554b25513..f2833f096f2 100644
--- a/chromium/chrome/browser/resources/settings/change_password_page/change_password_page.html
+++ b/chromium/chrome/browser/resources/settings/change_password_page/change_password_page.html
@@ -2,10 +2,10 @@
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="change_password_browser_proxy.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<dom-module id="settings-change-password-page">
<template>
@@ -25,7 +25,7 @@
.top-aligned-settings-box {
align-items: start;
min-height: 0;
- padding: 12px var(--cr-section-padding);
+ padding: var(--cr-section-vertical-padding) var(--cr-section-padding);
}
</style>
<div class="settings-box first top-aligned-settings-box">
@@ -40,10 +40,10 @@
</div>
</div>
<div class="separator"></div>
- <paper-button class="action-button" id="changePassword"
+ <cr-button class="action-button" id="changePassword"
on-click="changePassword_">
$i18n{changePasswordPageButton}
- </paper-button>
+ </cr-button>
</div>
</template>
<script src="change_password_page.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html b/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html
index ceae8b274f8..8f991df6e48 100644
--- a/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html
+++ b/chromium/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.html
@@ -1,10 +1,10 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
@@ -60,10 +60,10 @@
<cr-policy-pref-indicator pref="[[prefs.software_reporter.enabled]]">
</cr-policy-pref-indicator>
<div class="separator"></div>
- <paper-button id="action-button" class="action-button"
+ <cr-button id="action-button" class="action-button"
disabled$="[[!cleanupEnabled_]]" on-click="proceed_">
[[actionButtonLabel_]]
- </paper-button>
+ </cr-button>
</template>
</div>
<div class="settings-box continuation">
diff --git a/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn
index 4991d67b221..e2642b28c73 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn
@@ -63,7 +63,10 @@ if (optimize_webui) {
group("closure_compile") {
deps = [
"os_a11y_page:closure_compile",
+ "os_files_page:closure_compile",
+ "os_languages_page:closure_compile",
"os_people_page:closure_compile",
+ "os_printing_page:closure_compile",
"os_privacy_page:closure_compile",
"os_reset_page:closure_compile",
"os_search_page:closure_compile",
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_a11y_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_a11y_page/BUILD.gn
index a87a220e0ad..b883f4e20f1 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/os_a11y_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_a11y_page/BUILD.gn
@@ -9,6 +9,7 @@ js_type_check("closure_compile") {
":os_a11y_page",
"../../a11y_page:externs",
"../../a11y_page:manage_a11y_page",
+ "../../a11y_page:switch_access_subpage",
"../../a11y_page:tts_subpage",
]
}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_about_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_about_page/BUILD.gn
new file mode 100644
index 00000000000..efbf96b029c
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_about_page/BUILD.gn
@@ -0,0 +1,26 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/closure_compiler/compile_js.gni")
+
+js_type_check("closure_compile") {
+ deps = [
+ ":os_about_page",
+ ]
+}
+
+js_library("os_about_page") {
+ deps = [
+ "../..:lifetime_browser_proxy",
+ "../..:route",
+ "../../about_page:about_page_browser_proxy",
+ "../../settings_page:main_page_behavior",
+ "../../settings_page:settings_animated_pages",
+ "//ui/webui/resources/js:assert",
+ "//ui/webui/resources/js:i18n_behavior",
+ "//ui/webui/resources/js:parse_html_subset",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
+ ]
+ externs_list = [ "$externs_path/web_animations.js" ]
+}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_downloads_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_files_page/BUILD.gn
index 3879949381d..a1b5d3d633d 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/os_downloads_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_files_page/BUILD.gn
@@ -6,7 +6,7 @@ import("//third_party/closure_compiler/compile_js.gni")
js_type_check("closure_compile") {
deps = [
- ":os_downloads_page",
+ ":os_files_page",
":smb_shares_page",
]
}
@@ -18,7 +18,7 @@ js_library("smb_shares_page") {
]
}
-js_library("os_downloads_page") {
+js_library("os_files_page") {
deps = [
"../..:page_visibility",
"../..:route",
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_languages_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_languages_page/BUILD.gn
new file mode 100644
index 00000000000..38b28886429
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_languages_page/BUILD.gn
@@ -0,0 +1,58 @@
+# 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("//third_party/closure_compiler/compile_js.gni")
+
+js_type_check("closure_compile") {
+ deps = [
+ ":os_add_languages_dialog",
+ ":os_languages_page",
+ ":os_languages_section",
+ "../../languages_page:languages",
+ "../../languages_page:languages_browser_proxy",
+ "../../languages_page:languages_types",
+ "../../languages_page:manage_input_methods_page",
+ ]
+}
+
+js_library("os_languages_section") {
+ deps = [
+ ":os_languages_page",
+ "../..:route",
+ "../../languages_page:languages",
+ "../../languages_page:languages_types",
+ "../../languages_page:manage_input_methods_page",
+ "../../settings_page:settings_animated_pages",
+ "../../settings_page:settings_subpage",
+ "//ui/webui/resources/js:assert",
+ "//ui/webui/resources/js:cr",
+ "//ui/webui/resources/js:load_time_data",
+ "//ui/webui/resources/js/cr/ui:focus_without_ink",
+ ]
+}
+
+js_library("os_languages_page") {
+ deps = [
+ "../..:lifetime_browser_proxy",
+ "../..:route",
+ "../../languages_page:languages_types",
+ "../../settings_page:settings_animated_pages",
+ "//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu",
+ "//ui/webui/resources/cr_elements/cr_expand_button:cr_expand_button",
+ "//ui/webui/resources/cr_elements/cr_lazy_render:cr_lazy_render",
+ "//ui/webui/resources/js:assert",
+ "//ui/webui/resources/js:cr",
+ "//ui/webui/resources/js:load_time_data",
+ "//ui/webui/resources/js/cr/ui:focus_without_ink",
+ ]
+}
+
+js_library("os_add_languages_dialog") {
+ deps = [
+ "../../languages_page:languages",
+ "//ui/webui/resources/cr_elements:cr_scrollable_behavior",
+ "//ui/webui/resources/cr_elements/cr_search_field:cr_search_field",
+ "//ui/webui/resources/js:find_shortcut_behavior",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_printing_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_printing_page/BUILD.gn
new file mode 100644
index 00000000000..eecae87d275
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_printing_page/BUILD.gn
@@ -0,0 +1,27 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/closure_compiler/compile_js.gni")
+
+js_type_check("closure_compile") {
+ deps = [
+ ":os_printing_page",
+ "../../printing_page:cups_add_printer_dialog",
+ "../../printing_page:cups_add_printer_dialog_elements",
+ "../../printing_page:cups_edit_printer_dialog",
+ "../../printing_page:cups_printer_dialog_util",
+ "../../printing_page:cups_printers",
+ "../../printing_page:cups_printers_browser_proxy",
+ "../../printing_page:cups_printers_list",
+ ]
+}
+
+js_library("os_printing_page") {
+ deps = [
+ "../..:route",
+ "../../settings_page:settings_animated_pages",
+ "//ui/webui/resources/js:assert",
+ "//ui/webui/resources/js:load_time_data",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_settings_menu/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_settings_menu/BUILD.gn
index 3f1eae6ed31..397f4d3e434 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/os_settings_menu/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_settings_menu/BUILD.gn
@@ -14,6 +14,7 @@ js_library("os_settings_menu") {
deps = [
"../..:page_visibility",
"../..:route",
+ "//third_party/polymer/v1_0/components-chromium/iron-collapse:iron-collapse-extracted",
"//third_party/polymer/v1_0/components-chromium/paper-ripple:paper-ripple-extracted",
]
}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_settings_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_settings_page/BUILD.gn
index e2f8ef47446..e34d80d6362 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/os_settings_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_settings_page/BUILD.gn
@@ -16,7 +16,6 @@ js_library("os_settings_page") {
"../..:route",
"../..:search_settings",
"../../android_apps_page:android_apps_browser_proxy",
- "../../change_password_page:change_password_browser_proxy",
"../../chrome_cleanup_page:chrome_cleanup_proxy",
"../../settings_page:main_page_behavior",
"//ui/webui/resources/js:load_time_data",
diff --git a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html
index a1acb226189..52e133a23ab 100644
--- a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html
+++ b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html
@@ -1,11 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_tabs/cr_tabs.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-pages/iron-pages.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="clear_browsing_data_browser_proxy.html">
@@ -29,23 +29,27 @@
#clearBrowsingDataDialog {
--border-top-color: var(--paper-grey-300);
--cr-dialog-top-container-min-height: 42px;
- --cr-dialog-title: {
- padding-bottom: 8px;
- };
- --cr-dialog-body-container: {
- height: var(--body-container-height);
- };
--cr-dialog-body-border-top: 1px solid var(--border-top-color);
}
- :host-context([dark]) #clearBrowsingDataDialog {
- --border-top-color: var(--cr-separator-color);
+ @media (prefers-color-scheme: dark) {
+ #clearBrowsingDataDialog {
+ --border-top-color: var(--cr-separator-color);
+ }
}
#clearBrowsingDataDialog:not(.fully-rendered) {
visibility: hidden;
}
+ #clearBrowsingDataDialog [slot=title] {
+ padding-bottom: 8px;
+ }
+
+ #clearBrowsingDataDialog::part(body-container) {
+ height: var(--body-container-height);
+ }
+
#clearBrowsingDataDialog [slot=body] {
padding-top: 8px;
}
@@ -56,8 +60,10 @@
padding: 0;
}
- :host-context([dark]) #clearBrowsingDataDialog [slot=footer] {
- background: rgb(50, 54, 57); /* Custom color from Namrata. */
+ @media (prefers-color-scheme: dark) {
+ #clearBrowsingDataDialog [slot=footer] {
+ background: rgb(50, 54, 57); /* Custom color from Namrata. */
+ }
}
.row {
@@ -74,9 +80,6 @@
settings-checkbox {
--settings-row-two-line-min-height: 48px;
- --settings-checkbox-label: {
- line-height: 1.25rem;
- }
}
#basic-tab settings-checkbox + settings-checkbox {
@@ -226,9 +229,7 @@
</settings-checkbox>
<settings-checkbox
pref="{{prefs.browser.clear_data.site_settings}}"
- label="[[siteSettingsLabel_(
- '$i18nPolymer{siteSettings}',
- '$i18nPolymer{contentSettings}')]]"
+ label="$i18nPolymer{siteSettings}"
sub-label="[[counters_.site_settings]]"
disabled="[[clearingInProgress_]]">
</settings-checkbox>
@@ -244,14 +245,14 @@
<div slot="button-container">
<paper-spinner-lite active="[[clearingInProgress_]]">
</paper-spinner-lite>
- <paper-button class="cancel-button" disabled="[[clearingInProgress_]]"
- on-click="onCancelTap_">$i18n{cancel}</paper-button>
- <paper-button id="clearBrowsingDataConfirm"
+ <cr-button class="cancel-button" disabled="[[clearingInProgress_]]"
+ on-click="onCancelTap_">$i18n{cancel}</cr-button>
+ <cr-button id="clearBrowsingDataConfirm"
class="action-button" on-click="clearBrowsingData_"
disabled="[[isClearButtonDisabled_(clearingInProgress_,
clearButtonDisabled_)]]">
$i18n{clearData}
- </paper-button>
+ </cr-button>
</div>
<div slot="footer"
hidden="[[!shouldShowFooter_(syncStatus.signedIn, diceEnabled_)]]">
diff --git a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js
index fc53faa388d..d64aa86e82e 100644
--- a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js
+++ b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js
@@ -294,19 +294,6 @@ Polymer({
return cookiesSummary;
},
-
- /**
- * Choose a content/site settings label.
- * @param {string} siteSettings
- * @param {string} contentSettings
- * @return {string}
- * @private
- */
- siteSettingsLabel_: function(siteSettings, contentSettings) {
- return loadTimeData.getBoolean('enableSiteSettings') ? siteSettings :
- contentSettings;
- },
-
/**
* Updates the text of a browsing data counter corresponding to the given
* preference.
diff --git a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.html b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.html
index 5ca17611b90..7dad80083a6 100644
--- a/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.html
+++ b/chromium/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.html
@@ -1,5 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="../settings_shared_css.html">
@@ -11,9 +12,9 @@
<div slot="title">$i18n{historyDeletionDialogTitle}</div>
<div slot="body">$i18nRaw{historyDeletionDialogBody}</div>
<div slot="button-container">
- <paper-button class="action-button" on-click="onOkTap_">
+ <cr-button class="action-button" on-click="onOkTap_">
$i18n{historyDeletionDialogOK}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/controls/controlled_button.html b/chromium/chrome/browser/resources/settings/controls/controlled_button.html
index 062e4c2072f..af328098f62 100644
--- a/chromium/chrome/browser/resources/settings/controls/controlled_button.html
+++ b/chromium/chrome/browser/resources/settings/controls/controlled_button.html
@@ -1,7 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/assert.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
@@ -42,10 +42,10 @@
}
</style>
- <paper-button class$="[[getClass_(actionButton)]]"
+ <cr-button class$="[[getClass_(actionButton)]]"
disabled="[[!buttonEnabled_(enforced_, disabled)]]">
[[label]]
- </paper-button>
+ </cr-button>
<template is="dom-if" if="[[hasPrefPolicyIndicator(pref.*)]]" restamp>
<cr-policy-pref-indicator pref="[[pref]]" on-click="onIndicatorTap_"
diff --git a/chromium/chrome/browser/resources/settings/controls/controlled_button.js b/chromium/chrome/browser/resources/settings/controls/controlled_button.js
index eef0645228c..43f07fd36c0 100644
--- a/chromium/chrome/browser/resources/settings/controls/controlled_button.js
+++ b/chromium/chrome/browser/resources/settings/controls/controlled_button.js
@@ -50,11 +50,11 @@ Polymer({
/**
* @param {!boolean} actionButton
- * @return {string} Class of the paper-button.
+ * @return {string} Class of the cr-button.
* @private
*/
getClass_: function(actionButton) {
- return actionButton ? "action-button" : "";
+ return actionButton ? 'action-button' : '';
},
/**
diff --git a/chromium/chrome/browser/resources/settings/controls/extension_controlled_indicator.html b/chromium/chrome/browser/resources/settings/controls/extension_controlled_indicator.html
index 15be87a78f0..e09561aa0ef 100644
--- a/chromium/chrome/browser/resources/settings/controls/extension_controlled_indicator.html
+++ b/chromium/chrome/browser/resources/settings/controls/extension_controlled_indicator.html
@@ -1,7 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../extension_control_browser_proxy.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../settings_shared_css.html">
@@ -32,9 +32,7 @@
<img role="presentation" src="chrome://extension-icon/[[extensionId]]/40/1">
<span inner-h-t-m-l="[[getLabel_(extensionId, extensionName)]]"></span>
<template is="dom-if" if="[[extensionCanBeDisabled]]" restamp>
- <paper-button class="secondary-button" on-click="onDisableTap_">
- $i18n{disable}
- </paper-button>
+ <cr-button on-click="onDisableTap_">$i18n{disable}</cr-button>
</template>
</template>
</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/controls/password_prompt_dialog.html b/chromium/chrome/browser/resources/settings/controls/password_prompt_dialog.html
index b8afbd0e4a8..d58fdddf3d8 100644
--- a/chromium/chrome/browser/resources/settings/controls/password_prompt_dialog.html
+++ b/chromium/chrome/browser/resources/settings/controls/password_prompt_dialog.html
@@ -1,8 +1,8 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../settings_shared_css.html">
<dom-module id="settings-password-prompt-dialog">
@@ -32,15 +32,15 @@
</cr-input>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelTap_">
+ <cr-button class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
+ </cr-button>
- <paper-button id="confirmButton" class="action-button"
+ <cr-button id="confirmButton" class="action-button"
disabled$="[[!isConfirmEnabled_(inputValue_, passwordInvalid_)]]"
on-click="submitPassword_">
$i18n{confirm}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_dropdown_menu.html b/chromium/chrome/browser/resources/settings/controls/settings_dropdown_menu.html
index f842fca23ba..39d0615a9eb 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_dropdown_menu.html
+++ b/chromium/chrome/browser/resources/settings/controls/settings_dropdown_menu.html
@@ -1,6 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
<link rel="import" href="pref_control_behavior.html">
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_radio_group.html b/chromium/chrome/browser/resources/settings/controls/settings_radio_group.html
index 1e37711850a..ff6a6759926 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_radio_group.html
+++ b/chromium/chrome/browser/resources/settings/controls/settings_radio_group.html
@@ -9,9 +9,9 @@
<dom-module id="settings-radio-group">
<template>
<style include="settings-shared"></style>
- <div>[[label]]</div>
<cr-radio-group selected="[[selected]]"
- on-selected-changed="onSelectedChanged_">
+ on-selected-changed="onSelectedChanged_"
+ aria-label$="[[groupAriaLabel]]">
<slot></slot>
</cr-radio-group>
</template>
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_radio_group.js b/chromium/chrome/browser/resources/settings/controls/settings_radio_group.js
index 622ae66bb10..542e6df91c7 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_radio_group.js
+++ b/chromium/chrome/browser/resources/settings/controls/settings_radio_group.js
@@ -18,6 +18,8 @@ Polymer({
behaviors: [PrefControlBehavior],
properties: {
+ groupAriaLabel: String,
+
selected: String,
},
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_slider.html b/chromium/chrome/browser/resources/settings/controls/settings_slider.html
index d60229a596e..5c2e7028a8a 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_slider.html
+++ b/chromium/chrome/browser/resources/settings/controls/settings_slider.html
@@ -21,8 +21,10 @@
color: var(--paper-grey-400);
}
- :host-context([dark]) #labels[disabled] {
- color: var(--google-grey-refresh-500);
+ @media (prefers-color-scheme: dark) {
+ #labels[disabled] {
+ color: var(--google-grey-refresh-500);
+ }
}
div.outer {
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_textarea.html b/chromium/chrome/browser/resources/settings/controls/settings_textarea.html
index 04e44c93d9e..0d6cf960e5d 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_textarea.html
+++ b/chromium/chrome/browser/resources/settings/controls/settings_textarea.html
@@ -1,11 +1,12 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input_style_css.html">
<dom-module id="settings-textarea">
<template>
- <style include="cr-hidden-style cr-input-style">
+ <style include="cr-hidden-style cr-input-style cr-shared-style">
textarea {
display: block;
resize: none;
@@ -19,15 +20,17 @@
position: static;
}
</style>
- <div id="label" hidden="[[!label]]">[[label]]</div>
+ <div id="label" class="cr-form-field-label" hidden="[[!label]]">
+ [[label]]
+ </div>
<div id="input-container">
- <!-- The textarea will default to 3-row height, and if the content
- exceeds the bounds, it will scroll by default. No space or comments
- allowed before closing tag. -->
- <textarea id="input" autofocus="[[autofocus]]" rows="3"
+ <!-- The textarea is limited to |rows| height. If the content exceeds the
+ bounds, it scrolls by default. No space or comments are allowed
+ before the closing tag. -->
+ <textarea id="input" autofocus="[[autofocus]]" rows="[[rows]]"
value="{{value::input}}" aria-label$="[[label]]"
on-focus="onInputFocusChange_" on-blur="onInputFocusChange_"
- on-change="onInputChange_"></textarea>
+ on-change="onInputChange_" disabled="[[disabled]]"></textarea>
<div id="underline"></div>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/settings/controls/settings_textarea.js b/chromium/chrome/browser/resources/settings/controls/settings_textarea.js
index a7faab3d570..a66898fccb3 100644
--- a/chromium/chrome/browser/resources/settings/controls/settings_textarea.js
+++ b/chromium/chrome/browser/resources/settings/controls/settings_textarea.js
@@ -10,17 +10,45 @@ Polymer({
is: 'settings-textarea',
properties: {
+ /**
+ * Whether the text area should automatically get focus when the page
+ * loads.
+ */
autofocus: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
+ /**
+ * Whether the text area is disabled. When disabled, the text area loses
+ * focus and is not reachable by tabbing.
+ */
+ disabled: {
+ type: Boolean,
+ value: false,
+ reflectToAttribute: true,
+ observer: 'onDisabledChanged_'
+ },
+
+ /** Number of rows (lines) of the text area. */
+ rows: {
+ type: Number,
+ value: 3,
+ reflectToAttribute: true,
+ },
+
+ /** Caption of the text area. */
label: {
type: String,
value: '',
},
+ /**
+ * Text inside the text area. If the text exceeds the bounds of the text
+ * area, i.e. if it has more than |rows| lines, a scrollbar is shown by
+ * default.
+ */
value: {
type: String,
value: '',
@@ -28,10 +56,6 @@ Polymer({
},
},
- hostAttributes: {
- 'aria-disabled': 'false',
- },
-
/**
* 'change' event fires when <input> value changes and user presses 'Enter'.
* This function helps propagate it to host since change events don't
@@ -43,13 +67,19 @@ Polymer({
this.fire('change', {sourceEvent: e});
},
- // focused_ is used instead of :focus-within, so focus on elements within the
- // suffix slot does not trigger a change in input styles.
+ /**@private */
onInputFocusChange_: function() {
+ // focused_ is used instead of :focus-within, so focus on elements within
+ // the suffix slot does not trigger a change in input styles.
if (this.shadowRoot.activeElement == this.$.input) {
this.setAttribute('focused_', '');
} else {
this.removeAttribute('focused_');
}
},
+
+ /**@private */
+ onDisabledChanged_: function() {
+ this.setAttribute('aria-disabled', this.disabled ? 'true' : 'false');
+ },
});
diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.html b/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.html
index 930c0d8d329..88989b88f9c 100644
--- a/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.html
+++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.html
@@ -1,8 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="crostini_browser_proxy.html">
+<link rel="import" href="crostini_import_confirmation_dialog.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../settings_shared_css.html">
@@ -14,21 +15,26 @@
<div id="exportCrostiniLabel" class="start secondary">
$i18n{crostiniExportLabel}
</div>
- <paper-button on-click="onExportClick_"
+ <cr-button on-click="onExportClick_"
aria-labelledby="exportCrostiniLabel">
$i18n{crostiniExport}
- </paper-button>
+ </cr-button>
</div>
<div id="import" class="list-item">
<div id="importCrostiniLabel" class="start secondary">
$i18n{crostiniImportLabel}
</div>
- <paper-button on-click="onImportClick_"
+ <cr-button on-click="onImportClick_"
aria-labelledby="importCrostiniLabel">
$i18n{crostiniImport}
- </paper-button>
+ </cr-button>
</div>
</div>
+ <template is="dom-if" if="[[showImportConfirmationDialog_]]" restamp>
+ <settings-crostini-import-confirmation-dialog
+ on-close="onImportConfirmationDialogClose_">
+ </settings-crostini-import-confirmation-dialog>
+ </template>
</template>
<script src="crostini_export_import.js"></script>
</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.js b/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.js
index d1a513bb6e8..fa1be63a919 100644
--- a/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.js
+++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_export_import.js
@@ -11,6 +11,14 @@
Polymer({
is: 'settings-crostini-export-import',
+ properties: {
+ /** @private */
+ showImportConfirmationDialog_: {
+ type: Boolean,
+ value: false,
+ },
+ },
+
/** @private */
onExportClick_: function() {
settings.CrostiniBrowserProxyImpl.getInstance().exportCrostiniContainer();
@@ -18,6 +26,11 @@ Polymer({
/** @private */
onImportClick_: function() {
- settings.CrostiniBrowserProxyImpl.getInstance().importCrostiniContainer();
+ this.showImportConfirmationDialog_ = true;
+ },
+
+ /** @private */
+ onImportConfirmationDialogClose_: function() {
+ this.showImportConfirmationDialog_ = false;
},
});
diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.html b/chromium/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.html
new file mode 100644
index 00000000000..4351e857f57
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.html
@@ -0,0 +1,26 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
+<link rel="import" href="chrome://resources/html/i18n_behavior.html">
+<link rel="import" href="crostini_browser_proxy.html">
+<link rel="import" href="../settings_shared_css.html">
+
+<dom-module id="settings-crostini-import-confirmation-dialog">
+ <template>
+ <style include="settings-shared"></style>
+ <cr-dialog id="dialog" close-text="$i18n{close}">
+ <div slot="title">$i18n{crostiniImportConfirmationDialogTitle}</div>
+ <div slot="body">$i18n{crostiniImportConfirmationDialogMessage}</div>
+ <div slot="button-container">
+ <cr-button id="cancel" class="cancel-button"
+ on-click="onCancelTap_">$i18n{cancel}</cr-button>
+ <cr-button id="continue" class="action-button"
+ on-click="onContinueTap_">
+ $i18n{crostiniImportConfirmationDialogConfirmationButton}
+ </cr-button>
+ </div>
+ </cr-dialog>
+ </template>
+ <script src="crostini_import_confirmation_dialog.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.js b/chromium/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.js
new file mode 100644
index 00000000000..acfbdc9ac9a
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_import_confirmation_dialog.js
@@ -0,0 +1,28 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview 'settings-crostini-import-confirmation-dialog' is a component
+ * warning the user that importing a container overrides the existing container.
+ * By clicking 'Continue', the user agrees to start the import.
+ */
+Polymer({
+ is: 'settings-crostini-import-confirmation-dialog',
+
+ /** @override */
+ attached: function() {
+ this.$.dialog.showModal();
+ },
+
+ /** @private */
+ onCancelTap_: function() {
+ this.$.dialog.close();
+ },
+
+ /** @private */
+ onContinueTap_: function() {
+ settings.CrostiniBrowserProxyImpl.getInstance().importCrostiniContainer();
+ this.$.dialog.close();
+ },
+});
diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.html b/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.html
index 0b910eae1c5..1949eb2f98f 100644
--- a/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.html
+++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_page.html
@@ -1,9 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_indicator.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../prefs/prefs_behavior.html">
<link rel="import" href="../settings_page/settings_animated_pages.html">
@@ -42,13 +42,13 @@
</template>
<template is="dom-if" if="[[!prefs.crostini.enabled.value]]">
<div class="separator"></div>
- <paper-button id="enable"
+ <cr-button id="enable"
disabled="[[!allowCrostini]]"
on-click="onEnableTap_"
aria-label="$i18n{crostiniPageTitle}"
aria-describedby="secondaryText">
$i18n{crostiniEnable}
- </paper-button>
+ </cr-button>
</template>
</div>
</div>
diff --git a/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.html b/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.html
index 5cc34585f23..125be381c77 100644
--- a/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.html
+++ b/chromium/chrome/browser/resources/settings/crostini_page/crostini_subpage.html
@@ -1,8 +1,8 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="crostini_browser_proxy.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../prefs/prefs_behavior.html">
@@ -36,10 +36,10 @@
<template is="dom-if" if="[[!hideCrostiniUninstall_]]">
<div id="remove" class="settings-box">
<div id="removeCrostiniLabel" class="start">$i18n{crostiniRemove}</div>
- <paper-button on-click="onRemoveClick_"
+ <cr-button on-click="onRemoveClick_"
aria-labelledby="removeCrostiniLabel">
$i18n{crostiniRemoveButton}
- </paper-button>
+ </cr-button>
</div>
</template>
</template>
diff --git a/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.js b/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.js
index ec588874de5..186c536e121 100644
--- a/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.js
+++ b/chromium/chrome/browser/resources/settings/date_time_page/date_time_page.js
@@ -54,13 +54,19 @@ Polymer({
activeTimeZoneDisplayName,
prefs.generated.resolve_timezone_by_geolocation_on_off.value,
prefs.generated.resolve_timezone_by_geolocation_method_short.value)`
- }
+ },
+
+ /** @private */
+ isChild_: {type: Boolean, value: loadTimeData.getBoolean('isChild')},
},
/** @override */
attached: function() {
this.addWebUIListener(
'can-set-date-time-changed', this.onCanSetDateTimeChanged_.bind(this));
+ this.addWebUIListener(
+ 'access-code-validation-complete',
+ this.openTimeZoneSubpage_.bind(this));
chrome.send('dateTimePageReady');
},
@@ -99,7 +105,24 @@ Polymer({
return id ? this.i18n(id) : '';
},
+ /**
+ * Called when the timezone row is clicked. Child accounts need parental
+ * approval to modify their timezone, this method starts this process on the
+ * C++ side, and once it is complete the 'access-code-validation-complete'
+ * event is triggered which invokes openTimeZoneSubpage_. For non-child
+ * accounts the method is invoked immediately.
+ * @private
+ */
onTimeZoneSettings_: function() {
+ if (this.isChild_) {
+ chrome.send('handleShowParentAccessForTimeZone');
+ return;
+ }
+ this.openTimeZoneSubpage_();
+ },
+
+ /** @private */
+ openTimeZoneSubpage_: function() {
settings.navigateTo(settings.routes.DATETIME_TIMEZONE_SUBPAGE);
},
});
diff --git a/chromium/chrome/browser/resources/settings/default_browser_page/default_browser_page.html b/chromium/chrome/browser/resources/settings/default_browser_page/default_browser_page.html
index c24783b0bd2..8be48c881e0 100644
--- a/chromium/chrome/browser/resources/settings/default_browser_page/default_browser_page.html
+++ b/chromium/chrome/browser/resources/settings/default_browser_page/default_browser_page.html
@@ -1,5 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="default_browser_browser_proxy.html">
<link rel="import" href="../icons.html">
@@ -10,28 +11,29 @@
<style include="settings-shared">
</style>
<template is="dom-if" if="[[maySetDefaultBrowser_]]">
- <div class="settings-box first two-line">
- <div class="start">
+ <div class="settings-box first">
+ <div class="start settings-box-text">
<div id="canBeDefaultBrowser">$i18n{defaultBrowser}</div>
<div class="secondary">$i18n{defaultBrowserMakeDefault}</div>
</div>
<div class="separator"></div>
- <paper-button class="secondary-button"
- on-click="onSetDefaultBrowserTap_">
+ <cr-button on-click="onSetDefaultBrowserTap_">
$i18n{defaultBrowserMakeDefaultButton}
- </paper-button>
+ </cr-button>
</div>
</template>
<template is="dom-if" if="[[!maySetDefaultBrowser_]]">
<div class="settings-box first">
- <div class="start" hidden$="[[!isDefault_]]" id="isDefault">
+ <div class="start settings-box-text" hidden$="[[!isDefault_]]"
+ id="isDefault">
$i18n{defaultBrowserDefault}
</div>
- <div class="start" hidden$="[[!isSecondaryInstall_]]"
+ <div class="start settings-box-text" hidden$="[[!isSecondaryInstall_]]"
id="isSecondaryInstall">
$i18n{defaultBrowserSecondary}
</div>
- <div class="start" hidden$="[[!isUnknownError_]]" id="isUnknownError">
+ <div class="start settings-box-text" hidden$="[[!isUnknownError_]]"
+ id="isUnknownError">
$i18n{defaultBrowserError}
</div>
</div>
diff --git a/chromium/chrome/browser/resources/settings/device_page/display.html b/chromium/chrome/browser/resources/settings/device_page/display.html
index 9d3fbdf0cb9..5b906f084eb 100644
--- a/chromium/chrome/browser/resources/settings/device_page/display.html
+++ b/chromium/chrome/browser/resources/settings/device_page/display.html
@@ -8,9 +8,8 @@
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="display_layout.html">
<link rel="import" href="display_overscan_dialog.html">
<link rel="import" href="night_light_slider.html">
@@ -49,7 +48,7 @@
margin: 10px 0;
}
- .settings-box > paper-button:first-child {
+ .settings-box > cr-button:first-child {
padding-inline-start: 0
}
@@ -65,6 +64,10 @@
flex-grow: 1;
margin-top: 20px;
}
+
+ iron-collapse {
+ width: 100%;
+ }
</style>
<div class="settings-box first layout vertical self-stretch">
<h2 class="layout self-start">
@@ -274,16 +277,17 @@
</settings-dropdown-menu>
</div>
<!-- Custom schedule slider -->
- <div class="settings-box indented continuation">
- <iron-collapse id="nightLightCustomScheduleCollapse"
- class="start text-area layout vertical"
- opened="[[shouldOpenCustomScheduleCollapse_]]">
- <div class="settings-box continuation self-stretch">
- <night-light-slider id="nightLightSlider" prefs="{{prefs}}">
- </night-light-slider>
+ <iron-collapse id="nightLightCustomScheduleCollapse"
+ opened="[[shouldOpenCustomScheduleCollapse_]]">
+ <div class="settings-box indented continuation">
+ <div class="start text-area layout vertical">
+ <div class="settings-box continuation self-stretch">
+ <night-light-slider id="nightLightSlider" prefs="{{prefs}}">
+ </night-light-slider>
+ </div>
</div>
- </iron-collapse>
- </div>
+ </div>
+ </iron-collapse>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/settings/device_page/display.js b/chromium/chrome/browser/resources/settings/device_page/display.js
index 371dd501c8f..630be8d593a 100644
--- a/chromium/chrome/browser/resources/settings/device_page/display.js
+++ b/chromium/chrome/browser/resources/settings/device_page/display.js
@@ -570,6 +570,10 @@ Polymer({
*/
showUnifiedDesktop_: function(
unifiedDesktopAvailable, unifiedDesktopMode, displays) {
+ if (displays === undefined) {
+ return false;
+ }
+
return unifiedDesktopMode ||
(unifiedDesktopAvailable && displays.length > 1 &&
!this.isMirrored_(displays));
diff --git a/chromium/chrome/browser/resources/settings/device_page/display_overscan_dialog.html b/chromium/chrome/browser/resources/settings/device_page/display_overscan_dialog.html
index c5b2d745652..514f8d719b6 100644
--- a/chromium/chrome/browser/resources/settings/device_page/display_overscan_dialog.html
+++ b/chromium/chrome/browser/resources/settings/device_page/display_overscan_dialog.html
@@ -1,10 +1,10 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../icons.html">
<link rel="import" href="../settings_shared_css.html">
@@ -74,12 +74,12 @@
</div>
</div>
<div slot="button-container">
- <paper-button id="reset" class="cancel-button" on-click="onResetTap_">
+ <cr-button id="reset" class="cancel-button" on-click="onResetTap_">
$i18n{displayOverscanReset}
- </paper-button>
- <paper-button class="action-button" on-click="onSaveTap_">
+ </cr-button>
+ <cr-button class="action-button" on-click="onSaveTap_">
$i18n{ok}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/device_page/drive_cache_dialog.html b/chromium/chrome/browser/resources/settings/device_page/drive_cache_dialog.html
index c493176b1d7..00e43a44464 100644
--- a/chromium/chrome/browser/resources/settings/device_page/drive_cache_dialog.html
+++ b/chromium/chrome/browser/resources/settings/device_page/drive_cache_dialog.html
@@ -1,8 +1,8 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../settings_shared_css.html">
<dom-module id="settings-drive-cache-dialog">
@@ -16,14 +16,14 @@
<span>$i18n{storageClearDriveCacheDialogDescription}</span>
</div>
<div slot="button-container">
- <paper-button id="cancelButton" class="cancel-button"
+ <cr-button id="cancelButton" class="cancel-button"
on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button id="deleteButton" class="action-button"
+ </cr-button>
+ <cr-button id="deleteButton" class="action-button"
on-click="onDeleteTap_">
$i18n{storageDeleteAllButtonTitle}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/device_page/keyboard.js b/chromium/chrome/browser/resources/settings/device_page/keyboard.js
index 9d829cee65c..4c189aa6727 100644
--- a/chromium/chrome/browser/resources/settings/device_page/keyboard.js
+++ b/chromium/chrome/browser/resources/settings/device_page/keyboard.js
@@ -154,7 +154,9 @@ Polymer({
},
onShowLanguageInputTap_: function() {
- settings.navigateTo(settings.routes.LANGUAGES);
+ settings.navigateTo(
+ settings.routes.LANGUAGES,
+ /* dynamicParams */ null, /* removeSearch */ true);
},
getExternalMetaKeyLabel_: function(hasInternalKeyboard) {
diff --git a/chromium/chrome/browser/resources/settings/device_page/power.html b/chromium/chrome/browser/resources/settings/device_page/power.html
index 1bc1d4b816b..8df6cf9fd7b 100644
--- a/chromium/chrome/browser/resources/settings/device_page/power.html
+++ b/chromium/chrome/browser/resources/settings/device_page/power.html
@@ -3,7 +3,7 @@
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_indicator.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="../controls/settings_toggle_button.html">
<link rel="import" href="../route.html">
diff --git a/chromium/chrome/browser/resources/settings/device_page/storage.js b/chromium/chrome/browser/resources/settings/device_page/storage.js
index a6a8704cca4..211c28c7726 100644
--- a/chromium/chrome/browser/resources/settings/device_page/storage.js
+++ b/chromium/chrome/browser/resources/settings/device_page/storage.js
@@ -162,7 +162,9 @@ Polymer({
* @private
*/
onBrowsingDataTap_: function() {
- settings.navigateTo(settings.routes.CLEAR_BROWSER_DATA);
+ settings.navigateTo(
+ settings.routes.CLEAR_BROWSER_DATA,
+ /* dynamicParams */ null, /* removeSearch */ true);
},
/**
@@ -178,7 +180,9 @@ Polymer({
* @private
*/
onCrostiniTap_: function() {
- settings.navigateTo(settings.routes.CROSTINI_DETAILS);
+ settings.navigateTo(
+ settings.routes.CROSTINI_DETAILS, /* dynamicParams */ null,
+ /* removeSearch */ true);
},
/**
@@ -186,7 +190,9 @@ Polymer({
* @private
*/
onOtherUsersTap_: function() {
- settings.navigateTo(settings.routes.ACCOUNTS);
+ settings.navigateTo(
+ settings.routes.ACCOUNTS,
+ /* dynamicParams */ null, /* removeSearch */ true);
},
/**
diff --git a/chromium/chrome/browser/resources/settings/device_page/stylus.html b/chromium/chrome/browser/resources/settings/device_page/stylus.html
index 6ec8eeef379..7dad79f1c65 100644
--- a/chromium/chrome/browser/resources/settings/device_page/stylus.html
+++ b/chromium/chrome/browser/resources/settings/device_page/stylus.html
@@ -35,8 +35,7 @@
<settings-toggle-button id="enableStylusToolsToggle"
class="continuation"
pref="{{prefs.settings.enable_stylus_tools}}"
- label="$i18n{stylusEnableStylusTools}"
- hidden$="[[prefs.ash.kiosk_next_shell.enabled.value]]">
+ label="$i18n{stylusEnableStylusTools}">
</settings-toggle-button>
<template is="dom-if" if="[[hasInternalStylus_]]">
@@ -44,8 +43,7 @@
id ="launchPaletteOnEjectEventToggle"
pref="{{prefs.settings.launch_palette_on_eject_event}}"
label="$i18n{stylusAutoOpenStylusTools}"
- disabled="[[!prefs.settings.enable_stylus_tools.value]]"
- hidden$="[[prefs.ash.kiosk_next_shell.enabled.value]]">
+ disabled="[[!prefs.settings.enable_stylus_tools.value]]">
</settings-toggle-button>
</template>
diff --git a/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.html b/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.html
index 3e3dac9ec4a..966a88d2381 100644
--- a/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.html
+++ b/chromium/chrome/browser/resources/settings/downloads_page/downloads_page.html
@@ -1,5 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
@@ -24,7 +25,7 @@
focus-config="[[focusConfig_]]">
<div route-path="default">
<div class="settings-box first two-line">
- <div class="start">
+ <div class="start settings-box-text">
<div>$i18n{downloadLocation}</div>
<div class="secondary" id="defaultDownloadPath">
<if expr="not chromeos">
@@ -36,7 +37,7 @@
</div>
</div>
<div class="separator"></div>
- <controlled-button class="secondary-button" id="changeDownloadsPath"
+ <controlled-button id="changeDownloadsPath"
label="$i18n{changeDownloadLocation}"
on-click="selectDownloadLocation_"
pref="[[prefs.download.default_directory]]"
@@ -63,10 +64,10 @@
$i18n{openFileTypesAutomatically}
</div>
<div class="separator"></div>
- <paper-button id="resetAutoOpenFileTypes" class="secondary-button"
+ <cr-button id="resetAutoOpenFileTypes"
on-click="onClearAutoOpenFileTypesTap_">
$i18n{clear}
- </paper-button>
+ </cr-button>
</div>
</template>
</div>
diff --git a/chromium/chrome/browser/resources/settings/downloads_page/smb_shares_page.html b/chromium/chrome/browser/resources/settings/downloads_page/smb_shares_page.html
index 5b702b3ee7e..a5dfd95d3be 100644
--- a/chromium/chrome/browser/resources/settings/downloads_page/smb_shares_page.html
+++ b/chromium/chrome/browser/resources/settings/downloads_page/smb_shares_page.html
@@ -1,11 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_components/chromeos/smb_shares/add_smb_share_dialog.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../route.html">
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="../settings_vars_css.html">
@@ -27,11 +27,11 @@
icon-aria-label="$i18n{smbSharesTitle}">
</cr-policy-pref-indicator>
</template>
- <paper-button class="action-button" id="addShare"
+ <cr-button class="action-button" id="addShare"
on-click="onAddShareTap_"
disabled="[[!prefs.network_file_shares.allowed.value]]">
$i18n{addSmbShare}
- </paper-button>
+ </cr-button>
</div>
<template is="dom-if" if="[[showAddSmbDialog_]]" restamp>
<add-smb-share-dialog on-close="onAddSmbDialogClosed_"
diff --git a/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.html b/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.html
index 8f5a39a982d..131565b3c41 100644
--- a/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.html
+++ b/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.html
@@ -4,7 +4,8 @@
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="google_assistant_browser_proxy.html">
<link rel="import" href="../controls/controlled_button.html">
<link rel="import" href="../controls/settings_toggle_button.html">
@@ -33,7 +34,8 @@
class="first primary-toggle"
pref="{{prefs.settings.voice_interaction.enabled}}"
label="[[getAssistantOnOffLabel_(
- prefs.settings.voice_interaction.enabled.value)]]">
+ prefs.settings.voice_interaction.enabled.value)]]"
+ disabled="{{prefs.settings.assistant.disabled_by_policy.value}}">
</settings-toggle-button>
<template is="dom-if"
if="[[prefs.settings.voice_interaction.enabled.value]]">
@@ -50,9 +52,9 @@
on-settings-boolean-control-change="onEnableHotwordChange_"
hidden="[[!hotwordDspAvailable_]]">
</settings-toggle-button>
- <div class="settings-box three-line" id="dsp-hotword-container"
+ <div class="settings-box" id="dsp-hotword-container"
hidden="[[hotwordDspAvailable_]]">
- <div class="start text-area">
+ <div class="start text-area settings-box-text">
<div class="label">
$i18n{googleAssistantEnableHotword}
</div>
@@ -85,8 +87,8 @@
</select>
</div>
<template is="dom-if" if="[[shouldShowVoiceMatchSettings_]]">
- <div class="settings-box two-line">
- <div class="start text-area">
+ <div class="settings-box">
+ <div class="start text-area settings-box-text">
<div class="label">
$i18n{googleAssistantVoiceSettings}
</div>
@@ -94,7 +96,7 @@
$i18n{googleAssistantVoiceSettingsDescription}
</div>
</div>
- <controlled-button id="retrain-voice-model" class="secondary-button"
+ <controlled-button id="retrain-voice-model"
on-click="onRetrainVoiceModelTapped_"
label="$i18n{googleAssistantVoiceSettingsRetrainButton}"
pref="{{prefs.settings.voice_interaction.hotword.enabled}}">
diff --git a/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.js b/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.js
index b68ac1421f5..a901f4e32bd 100644
--- a/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.js
+++ b/chromium/chrome/browser/resources/settings/google_assistant_page/google_assistant_page.js
@@ -41,7 +41,7 @@ const ConsentStatus = {
Polymer({
is: 'settings-google-assistant-page',
- behaviors: [I18nBehavior, PrefsBehavior],
+ behaviors: [I18nBehavior, PrefsBehavior, WebUIListenerBehavior],
properties: {
/** @private */
@@ -113,6 +113,7 @@ Polymer({
'onPrefsChanged_(prefs.settings.voice_interaction.hotword.always_on.value)',
`onPrefsChanged_(
prefs.settings.voice_interaction.activity_control.consent_status.value)`,
+ 'onPrefsChanged_(prefs.settings.assistant.disabled_by_policy.value)',
],
/** @private {?settings.GoogleAssistantBrowserProxy} */
@@ -123,6 +124,15 @@ Polymer({
this.browserProxy_ = settings.GoogleAssistantBrowserProxyImpl.getInstance();
},
+ /** @override */
+ ready: function() {
+ this.addWebUIListener('hotwordDeviceUpdated', (hasHotword) => {
+ this.hotwordDspAvailable_ = hasHotword;
+ });
+
+ chrome.send('initializeGoogleAssistantPage');
+ },
+
/**
* @param {boolean} toggleValue
* @return {string}
@@ -187,10 +197,14 @@ Polymer({
/** @private */
onPrefsChanged_: function() {
+ if (this.getPref('settings.assistant.disabled_by_policy.value')) {
+ this.setPrefValue('settings.voice_interaction.enabled', false);
+ return;
+ }
+
this.refreshDspHotwordState_();
this.shouldShowVoiceMatchSettings_ =
- loadTimeData.getBoolean('voiceMatchEnabled') &&
this.getPref('settings.voice_interaction.hotword.enabled.value') &&
(this.getPref(
'settings.voice_interaction.activity_control.consent_status.value') ==
diff --git a/chromium/chrome/browser/resources/settings/icons.html b/chromium/chrome/browser/resources/settings/icons.html
index 01400a09a5f..816bb70c3a1 100644
--- a/chromium/chrome/browser/resources/settings/icons.html
+++ b/chromium/chrome/browser/resources/settings/icons.html
@@ -40,7 +40,7 @@ List icons here rather than importing large sets of (e.g. Polymer) icons.
<if expr="chromeos">
<!-- Icons from http://icons/ -->
- <g id="play-prism"><path fill="#5A5A5A" d="M20.18 10.88l-3.06-1.74L14.26 12l2.86 2.86 3.06-1.74c.55-.31.82-.71.82-1.12 0-.41-.27-.81-.82-1.12zM4.71 2.45l8.42 8.42 2.55-2.55-10.7-6.06c-.07-.04-.14-.07-.21-.1-.17-.07-.3.05-.15.21.03.02.06.05.09.08zm0 19.1l-.08.08c-.15.15-.02.28.15.21.07-.03.14-.06.21-.1l10.69-6.06-2.55-2.55s-7.2 7.21-8.42 8.42zM12 12L3.38 3.38c-.19-.19-.38-.07-.38.19v16.86c0 .26.19.38.38.19L12 12z"></path></g>
+ <g id="play-prism"><path d="M20.18 10.88l-3.06-1.74L14.26 12l2.86 2.86 3.06-1.74c.55-.31.82-.71.82-1.12 0-.41-.27-.81-.82-1.12zM4.71 2.45l8.42 8.42 2.55-2.55-10.7-6.06c-.07-.04-.14-.07-.21-.1-.17-.07-.3.05-.15.21.03.02.06.05.09.08zm0 19.1l-.08.08c-.15.15-.02.28.15.21.07-.03.14-.06.21-.1l10.69-6.06-2.55-2.55s-7.2 7.21-8.42 8.42zM12 12L3.38 3.38c-.19-.19-.38-.07-.38.19v16.86c0 .26.19.38.38.19L12 12z"></path></g>
<!-- Apps icon for Settings drawer -->
<g id="apps">
@@ -55,12 +55,12 @@ List icons here rather than importing large sets of (e.g. Polymer) icons.
</g>
<!-- Plugin VM icon for Settings drawer -->
- <g id="plugin-vm" fill="#5F6368" fill-rule="evenodd"><path transform="scale(1.2)" d="M7 12v4H4V4a1 1 0 0 1 1-1h8a3 3 0 0 1 3 3v3a3 3 0 0 1-3 3H7zm0-6v3h5a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1H7z"></path></g>
+ <g id="plugin-vm"><path transform="scale(1.2)" d="M7 12v4H4V4a1 1 0 0 1 1-1h8a3 3 0 0 1 3 3v3a3 3 0 0 1-3 3H7zm0-6v3h5a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1H7z"></path></g>
<!-- Icons for MultiDevice Settings UI -->
- <g id="multidevice-better-together-suite" fill="#5F6368" fill-rule="nonzero"><path d="M17,1.01 L7,1 C5.9,1 5,1.9 5,3 L5,21 C5,22.1 5.9,23 7,23 L17,23 C18.1,23 19,22.1 19,21 L19,3 C19,1.9 18.1,1.01 17,1.01 Z M17,21 L7,21 L7,20 L17,20 L17,21 Z M17,18 L7,18 L7,6 L17,6 L17,18 Z M7,4 L7,3 L17,3 L17,4 L7,4 Z"></path></g>
- <g id="multidevice-smart-lock" fill="#9AA0A6" fill-rule="nonzero"><path d="M18,9 L17,9 L17,7 C17,4.24 14.76,2 12,2 C9.24,2 7,4.24 7,7 L7,9 L6,9 C4.9,9 4,9.9 4,11 L4,21 C4,22.1 4.9,23 6,23 L18,23 C19.1,23 20,22.1 20,21 L20,11 C20,9.9 19.1,9 18,9 Z M9,7 C9,5.34 10.34,4 12,4 C13.66,4 15,5.34 15,7 L15,9 L9,9 L9,7 Z M18,21 L6,21 L6,11 L18,11 L18,21 Z M12,18 C13.1,18 14,17.1 14,16 C14,14.9 13.1,14 12,14 C10.9,14 10,14.9 10,16 C10,17.1 10.9,18 12,18 Z"></path></g>
- <g id="multidevice-messages" fill="#9AA0A6" fill-rule="nonzero"><path d="M19.9593506,2 C21.0593506,2 22,2.89658203 22,3.99658203 L22,16.0036621 C22,17.1036621 21.0593506,18.0036621 19.9593506,18.0036621 L6.00878906,18.0036621 L2.00878906,22.4 L2.01878906,3.99658203 C2.01878906,2.89658203 2.90878906,2 4.00878906,2 L19.9593506,2 Z M8,8.56896973 L4.5,12 L8,15.6103516 L8,13 L14,13 L14,11 L8,11 L8,8.56896973 Z M20.5688477,7 L17,3.57207031 L17,6 L11,6 L11,8 L17,8 L17,10.5720703 L20.5688477,7 Z"></path></g>
+ <g id="multidevice-better-together-suite"><path d="M17,1.01 L7,1 C5.9,1 5,1.9 5,3 L5,21 C5,22.1 5.9,23 7,23 L17,23 C18.1,23 19,22.1 19,21 L19,3 C19,1.9 18.1,1.01 17,1.01 Z M17,21 L7,21 L7,20 L17,20 L17,21 Z M17,18 L7,18 L7,6 L17,6 L17,18 Z M7,4 L7,3 L17,3 L17,4 L7,4 Z"></path></g>
+ <g id="multidevice-smart-lock"><path d="M18,9 L17,9 L17,7 C17,4.24 14.76,2 12,2 C9.24,2 7,4.24 7,7 L7,9 L6,9 C4.9,9 4,9.9 4,11 L4,21 C4,22.1 4.9,23 6,23 L18,23 C19.1,23 20,22.1 20,21 L20,11 C20,9.9 19.1,9 18,9 Z M9,7 C9,5.34 10.34,4 12,4 C13.66,4 15,5.34 15,7 L15,9 L9,9 L9,7 Z M18,21 L6,21 L6,11 L18,11 L18,21 Z M12,18 C13.1,18 14,17.1 14,16 C14,14.9 13.1,14 12,14 C10.9,14 10,14.9 10,16 C10,17.1 10.9,18 12,18 Z"></path></g>
+ <g id="multidevice-messages"><path d="M19.9593506,2 C21.0593506,2 22,2.89658203 22,3.99658203 L22,16.0036621 C22,17.1036621 21.0593506,18.0036621 19.9593506,18.0036621 L6.00878906,18.0036621 L2.00878906,22.4 L2.01878906,3.99658203 C2.01878906,2.89658203 2.90878906,2 4.00878906,2 L19.9593506,2 Z M8,8.56896973 L4.5,12 L8,15.6103516 L8,13 L14,13 L14,11 L8,11 L8,8.56896973 Z M20.5688477,7 L17,3.57207031 L17,6 L11,6 L11,8 L17,8 L17,10.5720703 L20.5688477,7 Z"></path></g>
</if>
<!-- Protected Content SVG -->
@@ -126,7 +126,7 @@ List icons here rather than importing large sets of (e.g. Polymer) icons.
<g id="restore"><path d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"></path></g>
<g id="rotate-right"><path d="M15.55 5.55L11 1v3.07C7.06 4.56 4 7.92 4 12s3.05 7.44 7 7.93v-2.02c-2.84-.48-5-2.94-5-5.91s2.16-5.43 5-5.91V10l4.55-4.45zM19.93 11c-.17-1.39-.72-2.73-1.62-3.89l-1.42 1.42c.54.75.88 1.6 1.02 2.47h2.02zM13 17.9v2.02c1.39-.17 2.74-.71 3.9-1.61l-1.44-1.44c-.75.54-1.59.89-2.46 1.03zm3.89-2.42l1.42 1.41c.9-1.16 1.45-2.5 1.62-3.89h-2.02c-.14.87-.48 1.72-1.02 2.48z"></path></g>
<g id="sensors"><path d="M10 8.5c-0.8 0-1.5 0.7-1.5 1.5s0.7 1.5 1.5 1.5s1.5-0.7 1.5-1.5S10.8 8.5 10 8.5z M7.6 5.8 C6.2 6.7 5.2 8.2 5.2 10c0 1.8 1 3.4 2.4 4.2l0.8-1.4c-1-0.6-1.6-1.6-1.6-2.8c0-1.2 0.6-2.2 1.6-2.8L7.6 5.8z M14.8 10 c0-1.8-1-3.4-2.4-4.2l-0.8 1.4c0.9 0.6 1.6 1.6 1.6 2.8c0 1.2-0.6 2.2-1.6 2.8l0.8 1.4C13.8 13.4 14.8 11.8 14.8 10z M6 3 c-2.4 1.4-4 4-4 7c0 3 1.6 5.6 4 7l0.8-1.4c-1.9-1.1-3.2-3.2-3.2-5.6c0-2.4 1.3-4.5 3.2-5.6L6 3z M13.2 4.4 c1.9 1.1 3.2 3.2 3.2 5.6c0 2.4-1.3 4.5-3.2 5.6L14 17c2.4-1.4 4-4 4-7c0-3-1.6-5.6-4-7L13.2 4.4z"></path></g>
- <g id="serial-port"><path stroke="#000" fill="none" stroke-width=".529" d="M1.963 7.039h20.074c.632 0 1.176.836 1 1.443l-2.14 7.339c-.177.606-.51 1.14-1.141 1.14H4.244c-.631 0-.962-.534-1.14-1.14l-2.14-7.3c-.178-.605.367-1.482 1-1.482z"></path><circle r="1.154" cx="4.279" cy="9.882"></circle><circle r="1.154" cx="5.772" cy="14.134"></circle><circle r="1.154" cx="19.892" cy="9.882"></circle><circle r="1.154" cx="15.989" cy="9.882"></circle><circle r="1.154" cx="12.086" cy="9.882"></circle><circle r="1.154" cx="8.183" cy="9.882"></circle><circle r="1.154" cx="9.849" cy="14.134"></circle><circle r="1.154" cx="13.925" cy="14.134"></circle><circle r="1.154" cx="18.002" cy="14.134"></circle></g>
+ <g id="serial-port"><path d="M22 9V7h-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2v-2h-2V9h2zm-4 10H4V5h14v14zM6 13h5v4H6zm6-6h4v3h-4zM6 7h5v5H6zm6 4h4v6h-4z"></path></g>
<if expr="chromeos">
<g id="alert-device-out-of-range" fill="none" fill-rule="evenodd"><path d="M-1-1h20v20H-1z"></path><path fill="#C53929" fill-rule="nonzero" d="M8.167 11.5h1.666v1.667H8.167V11.5zm0-6.667h1.666v5H8.167v-5zM8.992.667C4.392.667.667 4.4.667 9s3.725 8.333 8.325 8.333c4.608 0 8.341-3.733 8.341-8.333S13.6.667 8.992.667zm.008 15A6.665 6.665 0 0 1 2.333 9 6.665 6.665 0 0 1 9 2.333 6.665 6.665 0 0 1 15.667 9 6.665 6.665 0 0 1 9 15.667z"></path></g>
<g id="signal-cellular-0-bar"><path fill-opacity=".3" d="M2 22h20V2z"></path></g>
diff --git a/chromium/chrome/browser/resources/settings/incompatible_applications_page/incompatible_application_item.html b/chromium/chrome/browser/resources/settings/incompatible_applications_page/incompatible_application_item.html
index 98ab469bde5..ad5b501f448 100644
--- a/chromium/chrome/browser/resources/settings/incompatible_applications_page/incompatible_application_item.html
+++ b/chromium/chrome/browser/resources/settings/incompatible_applications_page/incompatible_application_item.html
@@ -1,8 +1,8 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="incompatible_applications_browser_proxy.html">
@@ -16,9 +16,9 @@
<div class="list-item">
<div class="start">[[applicationName]]</div>
<div class="separator"></div>
- <paper-button class="action-button" on-click="onActionTap_">
+ <cr-button class="action-button" on-click="onActionTap_">
[[getActionName_(actionType)]]
- </paper-button>
+ </cr-button>
</div>
</template>
<script src="incompatible_application_item.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/BUILD.gn b/chromium/chrome/browser/resources/settings/internet_page/BUILD.gn
index 02cd35af1eb..936eea443b4 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/internet_page/BUILD.gn
@@ -25,11 +25,13 @@ js_library("internet_page") {
":internet_page_browser_proxy",
"..:route",
"../settings_page:settings_animated_pages",
- "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior",
+ "//chromeos/services/network_config/public/mojom:mojom_js_library_for_compile",
+ "//ui/webui/resources/cr_components/chromeos/network:mojo_interface_provider",
"//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types",
"//ui/webui/resources/js:assert",
"//ui/webui/resources/js:i18n_behavior",
"//ui/webui/resources/js:web_ui_listener_behavior",
+ "//ui/webui/resources/js/chromeos:onc_mojo",
]
externs_list = [
"$externs_path/chrome_send.js",
@@ -64,6 +66,7 @@ js_library("internet_detail_page") {
":internet_page_browser_proxy",
":tether_connection_dialog",
"..:route",
+ "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior",
"//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types",
"//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior",
"//ui/webui/resources/js:assert",
@@ -78,6 +81,7 @@ js_library("internet_detail_page") {
js_library("internet_known_networks_page") {
deps = [
+ "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior",
"//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types",
"//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu",
"//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior",
@@ -91,10 +95,11 @@ js_library("internet_subpage") {
deps = [
":internet_page_browser_proxy",
"..:route",
- "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types",
+ "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior",
"//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior",
"//ui/webui/resources/js:assert",
"//ui/webui/resources/js:i18n_behavior",
+ "//ui/webui/resources/js/chromeos:onc_mojo",
]
externs_list = [ "$externs_path/networking_private.js" ]
extra_sources = [ "$interfaces_path/networking_private_interface.js" ]
@@ -115,9 +120,11 @@ js_library("network_proxy_section") {
js_library("network_summary") {
deps = [
+ "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior",
"//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types",
"//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior",
"//ui/webui/resources/js:assert",
+ "//ui/webui/resources/js/chromeos:onc_mojo",
]
extra_sources = [ "$interfaces_path/networking_private_interface.js" ]
}
@@ -128,6 +135,7 @@ js_library("network_summary_item") {
"//ui/webui/resources/cr_elements/policy:cr_policy_network_behavior",
"//ui/webui/resources/js:assert",
"//ui/webui/resources/js:i18n_behavior",
+ "//ui/webui/resources/js/chromeos:onc_mojo",
]
extra_sources = [ "$interfaces_path/networking_private_interface.js" ]
}
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_config.html b/chromium/chrome/browser/resources/settings/internet_page/internet_config.html
index cb45f2c8fe8..df873613ea5 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_config.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_config.html
@@ -2,19 +2,17 @@
<link rel="import" href="chrome://resources/cr_components/chromeos/network/network_config.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="internet_shared_css.html">
<dom-module id="internet-config">
<template>
<style include="internet-shared iron-flex">
- cr-dialog {
- --cr-dialog-native: {
- width: 460px;
- };
+ cr-dialog::part(dialog) {
+ width: 460px;
}
.error {
@@ -45,20 +43,20 @@
<template is="dom-if" if="[[error_]]" restamp>
<div class="flex error">[[getError_(error_)]]</div>
</template>
- <paper-button class="cancel-button" on-click="onCancelTap_">
+ <cr-button class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
+ </cr-button>
<template is="dom-if" if="[[!showConnect]]">
- <paper-button class="action-button" on-click="onSaveTap_"
+ <cr-button class="action-button" on-click="onSaveTap_"
disabled="[[!enableSave_]]">
$i18n{save}
- </paper-button>
+ </cr-button>
</template>
<template is="dom-if" if="[[showConnect]]">
- <paper-button class="action-button" on-click="onConnectTap_"
+ <cr-button class="action-button" on-click="onConnectTap_"
disabled="[[!enableConnect_]]">
$i18n{networkButtonConnect}
- </paper-button>
+ </cr-button>
</template>
</div>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_config.js b/chromium/chrome/browser/resources/settings/internet_page/internet_config.js
index 97cca745eda..0b3760d0477 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_config.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_config.js
@@ -113,7 +113,6 @@ Polymer({
*/
onClose_: function(event) {
this.close();
- this.fire('networks-changed');
event.stopPropagation();
},
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.html b/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.html
index 480ec02a983..a49a1d32fe9 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.html
@@ -7,7 +7,9 @@
<link rel="import" href="chrome://resources/cr_components/chromeos/network/network_property_list.html">
<link rel="import" href="chrome://resources/cr_components/chromeos/network/network_siminfo.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_icon.html">
+<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
@@ -18,7 +20,6 @@
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
<link rel="import" href="../controls/controlled_button.html">
<link rel="import" href="../controls/settings_toggle_button.html">
@@ -31,7 +32,7 @@
<dom-module id="settings-internet-detail-page">
<template>
- <style include="internet-shared iron-flex">
+ <style include="internet-shared settings-shared iron-flex">
:host {
padding-bottom: 40px;
}
@@ -65,13 +66,17 @@
paper-spinner-lite {
@apply --cr-icon-height-width;
}
+ .warning {
+ color: var(--cr-secondary-text-color);
+ margin-inline-start: var(--settings-controlled-by-spacing);
+ }
</style>
<!-- Title section: Icon + name + connection state. -->
<div id="titleDiv" class="settings-box first">
<div class="start layout horizontal center">
<cr-network-icon
show-technology-badge="[[showTechnologyBadge_]]"
- network-state="[[networkProperties_]]">
+ network-state="[[getNetworkState_(networkProperties_)]]">
</cr-network-icon>
<div id="networkState" class="title settings-box-text"
connected$="[[isConnectedState_(networkProperties_)]]"
@@ -86,27 +91,27 @@
</cr-policy-indicator>
</template>
</div>
- <paper-button on-click="onForgetTap_"
+ <cr-button on-click="onForgetTap_"
hidden$="[[!showForget_(networkProperties_)]]"
disabled="[[disableForget_(networkProperties_,
prefs.vpn_config_allowed)]]">
$i18n{networkButtonForget}
- </paper-button>
- <paper-button on-click="onViewAccountTap_"
+ </cr-button>
+ <cr-button on-click="onViewAccountTap_"
hidden$="[[!showViewAccount_(networkProperties_)]]">
$i18n{networkButtonViewAccount}
- </paper-button>
- <paper-button on-click="onActivateTap_"
+ </cr-button>
+ <cr-button on-click="onActivateTap_"
hidden$="[[!showActivate_(networkProperties_)]]">
$i18n{networkButtonActivate}
- </paper-button>
- <paper-button on-click="onConfigureTap_"
+ </cr-button>
+ <cr-button on-click="onConfigureTap_"
hidden$="[[!showConfigure_(networkProperties_, globalPolicy,
managedNetworkAvailable)]]"
disabled="[[disableConfigure_(networkProperties_,
prefs.vpn_config_allowed)]]">
$i18n{networkButtonConfigure}
- </paper-button>
+ </cr-button>
<!-- Use policy properties from vpn_config_allowed to indicate when that
pref disables buttons in this row. -->
<controlled-button id="connect" action-button on-click="onConnectTap_"
@@ -183,6 +188,16 @@
pref="{{autoConnect_}}"
label="[[getAutoConnectToggleLabel_(networkProperties_)]]">
</settings-toggle-button>
+ <!-- Hidden Network Warning -->
+ <template is="dom-if"
+ if="[[showHiddenNetworkWarning_(autoConnect_.*,
+ networkProperties_)]]"
+ restamp>
+ <div class="warning">
+ <iron-icon icon="cr:warning"></iron-icon>
+ [[i18n('hiddenNetworkWarning')]]
+ </div>
+ </template>
</template>
<!-- Always-on VPN. -->
<template is="dom-if"
@@ -196,16 +211,15 @@
<template is="dom-if" if="[[isCellular_(networkProperties_)]]">
<settings-toggle-button id="allowDataRoaming"
pref="{{prefs.cros.signed.data_roaming_enabled}}"
- label="$i18n{networkAllowDataRoaming}">
+ label="$i18n{networkAllowDataRoaming}"
+ sub-label="[[getRoamingDetails_(networkProperties_)]]">
</settings-toggle-button>
</template>
<!-- SIM Info (Cellular only). -->
<template is="dom-if" if="[[showCellularSim_(networkProperties_)]]"
restamp>
<div class="settings-box single-column stretch">
- <network-siminfo on-siminfo-change="onNetworkPropertyChange_"
- network-properties="[[networkProperties_]]"
- networking-private="[[networkingPrivate]]">
+ <network-siminfo on-siminfo-change="onNetworkPropertyChange_">
</network-siminfo>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.js b/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.js
index 7404a12fa06..bf2d66f205c 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_detail_page.js
@@ -10,11 +10,17 @@
(function() {
'use strict';
+const mojom = chromeos.networkConfig.mojom;
+
Polymer({
is: 'settings-internet-detail-page',
- behaviors:
- [CrPolicyNetworkBehavior, settings.RouteObserverBehavior, I18nBehavior],
+ behaviors: [
+ CrNetworkListenerBehavior,
+ CrPolicyNetworkBehavior,
+ settings.RouteObserverBehavior,
+ I18nBehavior,
+ ],
properties: {
/** The network GUID to display details for. */
@@ -65,9 +71,9 @@ Polymer({
/**
* Whether the network has been lost (e.g., has gone out of range). A
- * network is considered to be lost when a 'network-list-changed' event
- * occurs, and the new network list does not contain the GUID of the current
- * network.
+ * network is considered to be lost when a OnNetworkStateListChanged
+ * is signaled and the new network list does not contain the GUID of the
+ * current network.
* @private
*/
outOfRange_: {
@@ -77,7 +83,7 @@ Polymer({
/**
* Highest priority connected network or null.
- * @type {?CrOnc.NetworkStateProperties}
+ * @type {?OncMojo.NetworkStateProperties}
*/
defaultNetwork: {
type: Object,
@@ -178,11 +184,6 @@ Polymer({
'autoConnectChanged_(autoConnect_.*)', 'alwaysOnVpnChanged_(alwaysOnVpn_.*)'
],
- listeners: {
- 'network-list-changed': 'checkNetworkExists_',
- 'networks-changed': 'updateNetworkDetails_'
- },
-
/** @private {boolean} */
didSetFocus_: false,
@@ -204,9 +205,20 @@ Polymer({
/** @private {settings.InternetPageBrowserProxy} */
browserProxy_: null,
+ /**
+ * This UI will use both the networkingPrivate extension API and the
+ * networkConfig mojo API until we provide all of the required functionality
+ * in networkConfig. TODO(stevenjb): Remove use of networkingPrivate api.
+ * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy}
+ */
+ networkConfigProxy_: null,
+
/** @override */
created: function() {
this.browserProxy_ = settings.InternetPageBrowserProxyImpl.getInstance();
+ this.networkConfigProxy_ =
+ network_config.MojoInterfaceProviderImpl.getInstance()
+ .getMojoServiceProxy();
},
/**
@@ -276,7 +288,38 @@ Polymer({
});
},
- /** @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy */
+ /**
+ * CrosNetworkConfigObserver impl
+ * @param {!Array<OncMojo.NetworkStateProperties>} networks
+ */
+ onActiveNetworksChanged: function(networks) {
+ if (!this.guid || !this.networkProperties_) {
+ return;
+ }
+ // If the network was or is active, request an update.
+ if (this.networkProperties_.ConnectionState !=
+ CrOnc.ConnectionState.NOT_CONNECTED ||
+ networks.find(network => network.guid == this.guid)) {
+ this.getNetworkDetails_();
+ }
+ },
+
+ /** CrosNetworkConfigObserver impl */
+ onNetworkStateListChanged: function() {
+ this.checkNetworkExists_();
+ },
+
+ /** CrosNetworkConfigObserver impl */
+ onDeviceStateListChanged: function() {
+ if (this.guid) {
+ this.getNetworkDetails_();
+ }
+ },
+
+ /**
+ * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy
+ * @private
+ */
globalPolicyChanged_: function(globalPolicy) {
this.updateAutoConnectPref_(
!!(this.autoConnect_ && this.autoConnect_.value), globalPolicy);
@@ -314,7 +357,7 @@ Polymer({
// Focus a button once the initial state is set.
this.didSetFocus_ = true;
const button = this.$$('#titleDiv .action-button:not([hidden])') ||
- this.$$('#titleDiv paper-button:not([hidden])');
+ this.$$('#titleDiv cr-button:not([hidden])');
if (button) {
setTimeout(() => button.focus());
}
@@ -384,24 +427,25 @@ Polymer({
this.setNetworkProperties_(onc);
},
- /**
- * @param {!CustomEvent<!Array<string>>} event
- * @private
- */
- checkNetworkExists_: function(event) {
- const networkIds = event.detail;
- this.outOfRange_ = networkIds.indexOf(this.guid) == -1;
- },
-
- /**
- * @param {!CustomEvent<!Array<string>>} event
- * @private
- */
- updateNetworkDetails_: function(event) {
- const networkIds = event.detail;
- if (networkIds.indexOf(this.guid) != -1) {
- this.getNetworkDetails_();
- }
+ /** @private */
+ checkNetworkExists_: function() {
+ const filter = {
+ networkType: CrOnc.Type.ALL,
+ visible: true,
+ configured: false
+ };
+ this.networkingPrivate.getNetworks(filter, networks => {
+ if (networks.find(network => network.GUID == this.guid)) {
+ return;
+ }
+ this.outOfRange_ = true;
+ if (this.networkProperties_) {
+ // Set the connection state since we won't receive an update for a non
+ // existent network.
+ this.networkProperties_.ConnectionState =
+ CrOnc.ConnectionState.NOT_CONNECTED;
+ }
+ });
},
/**
@@ -411,8 +455,9 @@ Polymer({
getNetworkDetails_: function() {
assert(this.guid);
if (this.isSecondaryUser_) {
- this.networkingPrivate.getState(
- this.guid, this.getStateCallback_.bind(this));
+ this.networkConfigProxy_.getNetworkState(this.guid).then(response => {
+ this.getStateCallback_(response.result);
+ });
} else {
this.networkingPrivate.getManagedProperties(
this.guid, this.getPropertiesCallback_.bind(this));
@@ -444,7 +489,7 @@ Polymer({
}
if (!properties) {
- console.error('No properties for: ' + this.guid);
+ // Edge case, may occur when disabling. Close this.
this.close();
return;
}
@@ -461,29 +506,54 @@ Polymer({
},
/**
- * networkingPrivate.getState callback.
- * @param {CrOnc.NetworkStateProperties} state The network state properties.
+ * @param {?OncMojo.NetworkStateProperties} networkState
* @private
*/
- getStateCallback_: function(state) {
- if (!state) {
- // If |state| is null, the network is no longer visible, close this.
- console.error('Network no longer exists: ' + this.guid);
- this.networkProperties_ = undefined;
+ getStateCallback_: function(networkState) {
+ if (!networkState) {
+ // Edge case, may occur when disabling. Close this.
this.close();
return;
}
+ const type = /** @type {CrOnc.Type} */ (
+ OncMojo.getNetworkTypeString(networkState.type));
+
+ let connectionState;
+ switch (networkState.connectionState) {
+ case mojom.ConnectionStateType.kOnline:
+ case mojom.ConnectionStateType.kConnected:
+ case mojom.ConnectionStateType.kPortal:
+ connectionState = CrOnc.ConnectionState.CONNECTED;
+ break;
+ case mojom.ConnectionStateType.kConnecting:
+ connectionState = CrOnc.ConnectionState.CONNECTING;
+ break;
+ case mojom.ConnectionStateType.kNotConnected:
+ connectionState = CrOnc.ConnectionState.NOT_CONNECTED;
+ break;
+ }
+
this.networkProperties_ = {
- GUID: state.GUID,
- Type: state.Type,
- Connectable: state.Connectable,
- ConnectionState: state.ConnectionState,
+ GUID: networkState.guid,
+ Name: {Active: networkState.name},
+ Type: type,
+ Connectable: networkState.connectable,
+ ConnectionState: connectionState,
};
this.networkPropertiesReceived_ = true;
this.outOfRange_ = false;
},
/**
+ * @param {!CrOnc.NetworkProperties} properties
+ * @return {!OncMojo.NetworkStateProperties|undefined}
+ */
+ getNetworkState_: function(properties) {
+ return properties ? OncMojo.oncPropertiesToNetworkState(properties) :
+ undefined;
+ },
+
+ /**
* @param {!chrome.networkingPrivate.NetworkConfigProperties} onc The ONC
* network properties.
* @private
@@ -548,6 +618,22 @@ Polymer({
/**
* @param {!CrOnc.NetworkProperties} networkProperties
+ * @return {string} The text to display with roaming details.
+ * @private
+ */
+ getRoamingDetails_: function(networkProperties) {
+ if (!networkProperties.Cellular.AllowRoaming) {
+ return this.i18n('networkAllowDataRoamingDisabled');
+ }
+
+ return networkProperties.Cellular.RoamingState ===
+ CrOnc.RoamingState.ROAMING ?
+ this.i18n('networkAllowDataRoamingEnabledRoaming') :
+ this.i18n('networkAllowDataRoamingEnabledHome');
+ },
+
+ /**
+ * @param {!CrOnc.NetworkProperties} networkProperties
* @return {boolean} True if the network is connected.
* @private
*/
@@ -805,7 +891,7 @@ Polymer({
/**
* @param {!CrOnc.NetworkProperties} networkProperties
- * @param {?CrOnc.NetworkStateProperties} defaultNetwork
+ * @param {?OncMojo.NetworkStateProperties} defaultNetwork
* @param {boolean} networkPropertiesReceived
* @param {boolean} outOfRange
* @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy
@@ -850,8 +936,7 @@ Polymer({
/** @private */
updateAlwaysOnVpnPrefValue_: function() {
this.alwaysOnVpn_.value = this.prefs.arc && this.prefs.arc.vpn &&
- this.prefs.arc.vpn.always_on &&
- this.prefs.arc.vpn.always_on.lockdown &&
+ this.prefs.arc.vpn.always_on && this.prefs.arc.vpn.always_on.lockdown &&
this.prefs.arc.vpn.always_on.lockdown.value;
},
@@ -868,9 +953,8 @@ Polymer({
// Only mark VPN networks as enforced. This fake pref also controls the
// policy indicator on the connect/disconnect buttons, so it shouldn't be
// shown on non-VPN networks.
- if (this.isVpn_(this.networkProperties_) &&
- this.prefs.vpn_config_allowed &&
- !this.prefs.vpn_config_allowed.value) {
+ if (this.isVpn_(this.networkProperties_) && this.prefs &&
+ this.prefs.vpn_config_allowed && !this.prefs.vpn_config_allowed.value) {
fakeAlwaysOnVpnEnforcementPref.enforcement =
chrome.settingsPrivate.Enforcement.ENFORCED;
fakeAlwaysOnVpnEnforcementPref.controlledBy =
@@ -897,20 +981,33 @@ Polymer({
/** @private */
onConnectTap_: function() {
- if (CrOnc.shouldShowTetherDialogBeforeConnection(this.networkProperties_)) {
+ // For Tether networks that have not connected to a host, show a dialog.
+ if (this.networkProperties_.Type == CrOnc.Type.TETHER &&
+ (!this.networkProperties_.Tether ||
+ !this.networkProperties_.Tether.HasConnectedToHost)) {
this.showTetherDialog_();
return;
}
- this.fire('network-connect', {networkProperties: this.networkProperties_});
+ this.fireNetworkConnect_(/*bypassDialog=*/ false);
},
/** @private */
onTetherConnect_: function() {
this.getTetherDialog_().close();
- this.fire('network-connect', {
- networkProperties: this.networkProperties_,
- bypassConnectionDialog: true
- });
+ this.fireNetworkConnect_(/*bypassDialog=*/ true);
+ },
+
+ /**
+ * @param {boolean} bypassDialog
+ * @private
+ */
+ fireNetworkConnect_: function(bypassDialog) {
+ assert(this.networkProperties_);
+ const networkState =
+ OncMojo.oncPropertiesToNetworkState(this.networkProperties_);
+ this.fire(
+ 'network-connect',
+ {networkState: networkState, bypassConnectionDialog: bypassDialog});
},
/** @private */
@@ -939,7 +1036,11 @@ Polymer({
return;
}
- this.fire('show-config', this.networkProperties_);
+ this.fire('show-config', {
+ guid: this.networkProperties_.GUID,
+ type: this.networkProperties_.Type,
+ name: CrOnc.getNetworkName(this.networkProperties_)
+ });
},
/** @private */
@@ -957,6 +1058,17 @@ Polymer({
},
/**
+ * @return {boolean}
+ * @private
+ */
+ showHiddenNetworkWarning_: function() {
+ return loadTimeData.getBoolean('showHiddenNetworkWarning') &&
+ !!this.autoConnect_ && !!this.autoConnect_.value &&
+ !!this.networkProperties_ && !!this.networkProperties_.WiFi &&
+ !!CrOnc.getActiveValue(this.networkProperties_.WiFi.HiddenSSID);
+ },
+
+ /**
* Event triggered for elements associated with network properties.
* @param {!CustomEvent<!{
* field: string,
@@ -1254,8 +1366,8 @@ Polymer({
const type = this.networkProperties_.Type;
if (type == CrOnc.Type.CELLULAR && !!this.networkProperties_.Cellular) {
fields.push(
- 'Cellular.ActivationState', 'Cellular.RoamingState',
- 'RestrictedConnectivity', 'Cellular.ServingOperator.Name');
+ 'Cellular.ActivationState', 'RestrictedConnectivity',
+ 'Cellular.ServingOperator.Name');
} else if (type == CrOnc.Type.TETHER && !!this.networkProperties_.Tether) {
fields.push(
'Tether.BatteryPercentage', 'Tether.SignalStrength',
@@ -1512,6 +1624,11 @@ Polymer({
return false;
}
+ // Cellular IP addresses are shown under the network details section.
+ if (this.isCellular_(networkProperties)) {
+ return false;
+ }
+
return !!ipAddress && this.isConnectedState_(networkProperties);
},
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.html b/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.html
index 3685d4ca8f0..42dcf86aa71 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.html
@@ -1,5 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
@@ -33,13 +34,12 @@
<template is="dom-repeat" items="[[networkStateList_]]"
filter="networkIsPreferred_">
<div class="list-item">
- <cr-link-row
- embedded
- label="[[item.Name]]"
+ <cr-link-row embedded label="[[getNetworkDisplayName_(item)]]"
on-click="fireShowDetails_">
- <template is="dom-if" if="[[isPolicySource(item.Source))]]">
+ <template is="dom-if" if="[[isPolicySourceMojo(item.source))]]">
<cr-policy-indicator on-click="doNothing_"
- indicator-type="[[getIndicatorTypeForSource(item.Source)]]">
+ indicator-type="[[getIndicatorTypeForSourceMojo(
+ item.source)]]">
</cr-policy-indicator>
</template>
</cr-link-row>
@@ -59,13 +59,12 @@
<template is="dom-repeat" items="[[networkStateList_]]"
filter="networkIsNotPreferred_">
<div class="list-item">
- <cr-link-row
- embedded
- label="[[item.Name]]"
+ <cr-link-row embedded label="[[getNetworkDisplayName_(item)]]"
on-click="fireShowDetails_">
- <template is="dom-if" if="[[isPolicySource(item.Source))]]">
+ <template is="dom-if" if="[[isPolicySourceMojo(item.source))]]">
<cr-policy-indicator on-click="doNothing_"
- indicator-type="[[getIndicatorTypeForSource(item.Source)]]">
+ indicator-type="[[getIndicatorTypeForSourceMojo(
+ item.source)]]">
</cr-policy-indicator>
</template>
</cr-link-row>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js b/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js
index f5196b08250..6d613efeda5 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_known_networks_page.js
@@ -10,7 +10,10 @@
Polymer({
is: 'settings-internet-known-networks-page',
- behaviors: [CrPolicyNetworkBehavior],
+ behaviors: [
+ CrNetworkListenerBehavior,
+ CrPolicyNetworkBehavior,
+ ],
properties: {
/**
@@ -30,7 +33,7 @@ Polymer({
/**
* List of all network state data for the network type.
- * @private {!Array<!CrOnc.NetworkStateProperties>}
+ * @private {!Array<!OncMojo.NetworkStateProperties>}
*/
networkStateList_: {
type: Array,
@@ -54,11 +57,29 @@ Polymer({
enableForget_: Boolean,
},
- listeners: {'network-list-changed': 'refreshNetworks_'},
-
/** @private {string} */
selectedGuid_: '',
+ /**
+ * This UI will use both the networkingPrivate extension API and the
+ * networkConfig mojo API until we provide all of the required functionality
+ * in networkConfig. TODO(stevenjb): Remove use of networkingPrivate api.
+ * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy}
+ */
+ networkConfigProxy_: null,
+
+ /** @override */
+ created: function() {
+ this.networkConfigProxy_ =
+ network_config.MojoInterfaceProviderImpl.getInstance()
+ .getMojoServiceProxy();
+ },
+
+ /** CrosNetworkConfigObserver impl */
+ onNetworkStateListChanged: function() {
+ this.refreshNetworks_();
+ },
+
/** @private */
networkTypeChanged_: function() {
this.refreshNetworks_();
@@ -74,32 +95,32 @@ Polymer({
return;
}
const filter = {
- networkType: this.networkType,
- visible: false,
- configured: true
+ filter: chromeos.networkConfig.mojom.FilterType.kConfigured,
+ limit: chromeos.networkConfig.mojom.kNoLimit,
+ networkType: OncMojo.getNetworkTypeFromString(this.networkType),
};
- this.networkingPrivate.getNetworks(filter, states => {
- this.networkStateList_ = states;
+ this.networkConfigProxy_.getNetworkStateList(filter).then(response => {
+ this.networkStateList_ = response.result;
});
},
/**
- * @param {!CrOnc.NetworkStateProperties} state
+ * @param {!OncMojo.NetworkStateProperties} networkState
* @return {boolean}
* @private
*/
- networkIsPreferred_: function(state) {
+ networkIsPreferred_: function(networkState) {
// Currently we treat NetworkStateProperties.Priority as a boolean.
- return state.Priority > 0;
+ return networkState.priority > 0;
},
/**
- * @param {!CrOnc.NetworkStateProperties} networkState
+ * @param {!OncMojo.NetworkStateProperties} networkState
* @return {boolean}
* @private
*/
networkIsNotPreferred_: function(networkState) {
- return networkState.Priority == 0;
+ return networkState.priority == 0;
},
/**
@@ -121,14 +142,23 @@ Polymer({
},
/**
+ * @param {!OncMojo.NetworkStateProperties} networkState
+ * @return {string}
+ * @private
+ */
+ getNetworkDisplayName_: function(networkState) {
+ return OncMojo.getNetworkDisplayName(networkState);
+ },
+
+ /**
* @param {!Event} event
* @private
*/
onMenuButtonTap_: function(event) {
const button = event.target;
const networkState =
- /** @type {!CrOnc.NetworkStateProperties} */ (event.model.item);
- this.selectedGuid_ = networkState.GUID;
+ /** @type {!OncMojo.NetworkStateProperties} */ (event.model.item);
+ this.selectedGuid_ = networkState.guid;
// We need to make a round trip to Chrome in order to retrieve the managed
// properties for the network. The delay is not noticeable (~5ms) and is
// preferable to initiating a query for every known network at load time.
@@ -173,16 +203,15 @@ Polymer({
},
/**
- * Fires a 'show-details' event with an item containing a |networkStateList_|
+ * Fires a 'show-detail' event with an item containing a |networkStateList_|
* entry in the event model.
* @param {!Event} event
* @private
*/
fireShowDetails_: function(event) {
- const state =
- /** @type {!{model: !{item: !CrOnc.NetworkStateProperties}}} */ (event)
- .model.item;
- this.fire('show-detail', state);
+ const networkState =
+ /** @type {!OncMojo.NetworkStateProperties} */ (event.model.item);
+ this.fire('show-detail', networkState);
event.stopPropagation();
},
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_page.html b/chromium/chrome/browser/resources/settings/internet_page/internet_page.html
index 14ba902ebc1..3727b4dad9a 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_page.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_page.html
@@ -1,10 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html">
+<link rel="import" href="chrome://resources/cr_components/chromeos/network/mojo_interface_provider.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
<link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
+<link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
@@ -34,8 +35,7 @@
focus-config="[[focusConfig_]]">
<div route-path="default">
<network-summary default-network="{{defaultNetwork}}"
- device-states="{{deviceStates}}"
- networking-private="[[networkingPrivate]]">
+ device-states="{{deviceStates}}">
</network-summary>
<template is="dom-if" if="[[allowAddConnection_(globalPolicy_,
managedNetworkAvailable)]]">
@@ -49,7 +49,7 @@
<template is="dom-if" if="[[addConnectionExpanded_]]">
<div class="list-frame vertical-list">
<template is="dom-if"
- if="[[deviceIsEnabled_(deviceStates.WiFi)]]">
+ if="[[deviceIsEnabled_(deviceStates, 'WiFi')]]">
<div actionable class="list-item" on-click="onAddWiFiTap_">
<div class="start settings-box-text">
$i18n{internetAddWiFi}
@@ -122,15 +122,15 @@
<template is="dom-if" route-path="/networks" no-search restamp>
<settings-subpage page-title="[[getNetworksPageTitle_(subpageType_)]]"
- show-spinner="[[showSpinner_]]">
+ show-spinner="[[showSpinner_]]"
+ spinner-title="$i18n{networkScanningLabel}">
<settings-internet-subpage
default-network="[[defaultNetwork]]"
device-state="[[getDeviceState_(subpageType_, deviceStates)]]"
- tether-device-state="[[get('Tether', deviceStates)]]"
+ tether-device-state="[[getTetherDeviceState_(deviceStates)]]"
global-policy="[[globalPolicy_]]"
third-party-vpn-providers="[[thirdPartyVpnProviders_]]"
arc-vpn-providers="[[arcVpnProviders_]]"
- networking-private="[[networkingPrivate]]"
show-spinner="{{showSpinner_}}">
</settings-internet-subpage>
</settings-subpage>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_page.js b/chromium/chrome/browser/resources/settings/internet_page/internet_page.js
index dd4a459b6d7..bb18ded6ab7 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_page.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_page.js
@@ -2,6 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+(function() {
+
+const mojom = chromeos.networkConfig.mojom;
+
/**
* @fileoverview
* 'settings-internet-page' is the settings page containing internet
@@ -11,8 +15,9 @@ Polymer({
is: 'settings-internet-page',
behaviors: [
- I18nBehavior, settings.RouteObserverBehavior, WebUIListenerBehavior,
- CrNetworkListenerBehavior
+ I18nBehavior,
+ settings.RouteObserverBehavior,
+ WebUIListenerBehavior,
],
properties: {
@@ -32,8 +37,9 @@ Polymer({
},
/**
- * The device state for each network device type. Set by network-summary.
- * @type {!Object<!CrOnc.DeviceStateProperties>|undefined}
+ * The device state for each network device type, keyed by NetworkType. Set
+ * by network-summary.
+ * @type {!Object<!OncMojo.DeviceStateProperties>|undefined}
* @private
*/
deviceStates: {
@@ -44,7 +50,7 @@ Polymer({
/**
* Highest priority connected network or null. Set by network-summary.
- * @type {?CrOnc.NetworkStateProperties|undefined}
+ * @type {?OncMojo.NetworkStateProperties|undefined}
*/
defaultNetwork: {
type: Object,
@@ -93,31 +99,6 @@ Polymer({
value: false,
},
- /** Overridden from NetworkListenerBehavior. */
- networkListChangeSubscriberSelectors_: {
- type: Array,
- value: function() {
- return [
- 'network-summary',
- 'settings-internet-detail-page',
- 'settings-internet-known-networks-page',
- 'settings-internet-subpage',
- ];
- }
- },
-
- /** Overridden from NetworkListenerBehavior. */
- networksChangeSubscriberSelectors_: {
- type: Array,
- value: function() {
- return [
- 'network-summary',
- 'settings-internet-detail-page',
- 'settings-internet-subpage',
- ];
- }
- },
-
/**
* List of third party VPN providers.
* @type {!Array<!chrome.networkingPrivate.ThirdPartyVPNProperties>}
@@ -174,12 +155,23 @@ Polymer({
/** @private {Function} */
onExtensionDisabledListener_: null,
- /** @private {settings.InternetPageBrowserProxy} */
+ /** @private {?settings.InternetPageBrowserProxy} */
browserProxy_: null,
+ /**
+ * This UI will use both the networkingPrivate extension API and the
+ * networkConfig mojo API until we provide all of the required functionality
+ * in networkConfig. TODO(stevenjb): Remove use of networkingPrivate api.
+ * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy}
+ */
+ networkConfigProxy_: null,
+
/** @override */
created: function() {
this.browserProxy_ = settings.InternetPageBrowserProxyImpl.getInstance();
+ this.networkConfigProxy_ =
+ network_config.MojoInterfaceProviderImpl.getInstance()
+ .getMojoServiceProxy();
},
/** @override */
@@ -290,74 +282,70 @@ Polymer({
* Event triggered by a device state enabled toggle.
* @param {!CustomEvent<!{
* enabled: boolean,
- * type: chrome.networkingPrivate.NetworkType
+ * type: chromeos.networkConfig.mojom.NetworkType
* }>} event
* @private
*/
onDeviceEnabledToggled_: function(event) {
- if (event.detail.enabled) {
- this.networkingPrivate.enableNetworkType(event.detail.type);
- } else {
- this.networkingPrivate.disableNetworkType(event.detail.type);
- }
+ this.networkConfigProxy_.setNetworkTypeEnabledState(
+ event.detail.type, event.detail.enabled);
},
/**
- * @param {!CustomEvent<!CrOnc.NetworkProperties>} event
+ * @param {!CustomEvent<!{type: string, guid: ?string, name: ?string}>} event
* @private
*/
onShowConfig_: function(event) {
- const properties = event.detail;
- if (!properties.GUID) {
+ if (!event.detail.guid) {
// New configuration
- this.showConfig_(true /* configAndConnect */, properties.Type);
+ this.showConfig_(true /* configAndConnect */, event.detail.type);
} else {
this.showConfig_(
- false /* configAndConnect */, properties.Type, properties.GUID,
- CrOnc.getNetworkName(properties));
+ false /* configAndConnect */, event.detail.type, event.detail.guid,
+ event.detail.name);
}
},
/**
* @param {boolean} configAndConnect
* @param {string} type
- * @param {string=} guid
- * @param {string=} name
+ * @param {?string=} opt_guid
+ * @param {?string=} opt_name
* @private
*/
- showConfig_: function(configAndConnect, type, guid, name) {
+ showConfig_: function(configAndConnect, type, opt_guid, opt_name) {
assert(type != CrOnc.Type.CELLULAR && type != CrOnc.Type.TETHER);
const configDialog =
/** @type {!InternetConfigElement} */ (this.$.configDialog);
configDialog.type =
/** @type {chrome.networkingPrivate.NetworkType} */ (type);
- configDialog.guid = guid || '';
- configDialog.name = name || '';
+ configDialog.guid = opt_guid || '';
+ configDialog.name = opt_name || '';
configDialog.showConnect = configAndConnect;
configDialog.open();
},
/**
- * @param {!CustomEvent<!CrOnc.NetworkStateProperties>} event
+ * @param {!CustomEvent<!OncMojo.NetworkStateProperties>} event
* @private
*/
onShowDetail_: function(event) {
- this.detailType_ = event.detail.Type;
+ const networkState = event.detail;
+ const oncType = OncMojo.getNetworkTypeString(networkState.type);
+ this.detailType_ = oncType;
const params = new URLSearchParams;
- params.append('guid', event.detail.GUID);
- params.append('type', event.detail.Type);
- if (event.detail.Name) {
- params.append('name', event.detail.Name);
- }
+ params.append('guid', networkState.guid);
+ params.append('type', oncType);
+ params.append('name', OncMojo.getNetworkDisplayName(networkState));
settings.navigateTo(settings.routes.NETWORK_DETAIL, params);
},
/**
- * @param {!CustomEvent<!{type: string}>} event
+ * @param {!CustomEvent<chromeos.networkConfig.mojom.NetworkType>} event
* @private
*/
onShowNetworks_: function(event) {
- this.showNetworksSubpage_(event.detail.type);
+ this.showNetworksSubpage_(event.detail);
},
/**
@@ -365,6 +353,13 @@ Polymer({
* @private
*/
getNetworksPageTitle_: function() {
+ // The shared Cellular/Tether subpage is referred to as "Mobile".
+ // TODO(khorimoto): Remove once Cellular/Tether are split into their own
+ // sections.
+ if (this.subpageType_ == CrOnc.Type.CELLULAR ||
+ this.subpageType_ == CrOnc.Type.TETHER) {
+ return this.i18n('OncTypeMobile');
+ }
return this.i18n('OncType' + this.subpageType_);
},
@@ -379,37 +374,51 @@ Polymer({
/**
* @param {string} subpageType
- * @param {!Object<!CrOnc.DeviceStateProperties>|undefined} deviceStates
- * @return {!CrOnc.DeviceStateProperties|undefined}
+ * @param {!Object<!OncMojo.DeviceStateProperties>|undefined} deviceStates
+ * @return {!OncMojo.DeviceStateProperties|undefined}
* @private
*/
getDeviceState_: function(subpageType, deviceStates) {
+ if (!subpageType) {
+ return undefined;
+ }
// If both Tether and Cellular are enabled, use the Cellular device state
// when directly navigating to the Tether page.
if (subpageType == CrOnc.Type.TETHER &&
- this.deviceStates[CrOnc.Type.CELLULAR]) {
+ this.deviceStates[mojom.NetworkType.kCellular]) {
subpageType = CrOnc.Type.CELLULAR;
}
- return deviceStates[subpageType];
+ return deviceStates[OncMojo.getNetworkTypeFromString(subpageType)];
+ },
+
+ /**
+ * @param {!Object<!OncMojo.DeviceStateProperties>|undefined} deviceStates
+ * @return {!OncMojo.DeviceStateProperties|undefined}
+ * @private
+ */
+ getTetherDeviceState_: function(deviceStates) {
+ return deviceStates[mojom.NetworkType.kTether];
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} newValue
- * @param {!CrOnc.DeviceStateProperties|undefined} oldValue
+ * @param {!OncMojo.DeviceStateProperties|undefined} newValue
+ * @param {!OncMojo.DeviceStateProperties|undefined} oldValue
* @private
*/
onDeviceStatesChanged_: function(newValue, oldValue) {
const wifiDeviceState = this.getDeviceState_(CrOnc.Type.WI_FI, newValue);
let managedNetworkAvailable = false;
if (wifiDeviceState) {
- managedNetworkAvailable = !!wifiDeviceState.ManagedNetworkAvailable;
+ managedNetworkAvailable = !!wifiDeviceState.managedNetworkAvailable;
}
if (this.managedNetworkAvailable != managedNetworkAvailable) {
this.managedNetworkAvailable = managedNetworkAvailable;
}
- if (this.detailType_ && !this.deviceStates[this.detailType_]) {
+ if (this.detailType_ &&
+ !this.deviceStates[OncMojo.getNetworkTypeFromString(
+ this.detailType_)]) {
// If the device type associated with the current network has been
// removed (e.g., due to unplugging a Cellular dongle), the details page,
// if visible, displays controls which are no longer functional. If this
@@ -422,14 +431,15 @@ Polymer({
},
/**
- * @param {!CustomEvent<!{type: string}>} event
+ * @param {!CustomEvent<chromeos.networkConfig.mojom.NetworkType>} event
* @private
*/
onShowKnownNetworks_: function(event) {
- this.detailType_ = event.detail.type;
+ const oncType = OncMojo.getNetworkTypeString(event.detail);
+ this.detailType_ = oncType;
+ this.knownNetworksType_ = oncType;
const params = new URLSearchParams;
- params.append('type', event.detail.type);
- this.knownNetworksType_ = event.detail.type;
+ params.append('type', oncType);
settings.navigateTo(settings.routes.KNOWN_NETWORKS, params);
},
@@ -456,18 +466,19 @@ Polymer({
/** @private */
onAddArcVpnTap_: function() {
- this.showNetworksSubpage_(CrOnc.Type.VPN);
+ this.showNetworksSubpage_(mojom.NetworkType.kVPN);
},
/**
- * @param {string} type
+ * @param {chromeos.networkConfig.mojom.NetworkType} type
* @private
*/
showNetworksSubpage_: function(type) {
- this.detailType_ = type;
+ const oncType = OncMojo.getNetworkTypeString(type);
+ this.detailType_ = oncType;
const params = new URLSearchParams;
- params.append('type', type);
- this.subpageType_ = type;
+ params.append('type', oncType);
+ this.subpageType_ = oncType;
settings.navigateTo(settings.routes.INTERNET_NETWORKS, params);
},
@@ -567,12 +578,16 @@ Polymer({
},
/**
- * @param {!CrOnc.DeviceStateProperties} deviceState
+ * @param {!Array<!OncMojo.DeviceStateProperties>} deviceStates
+ * @param {string} type
* @return {boolean}
* @private
*/
- deviceIsEnabled_: function(deviceState) {
- return !!deviceState && deviceState.State == CrOnc.DeviceState.ENABLED;
+ deviceIsEnabled_: function(deviceStates, type) {
+ const device = deviceStates[OncMojo.getNetworkTypeFromString(type)];
+ return !!device &&
+ device.deviceState ==
+ chromeos.networkConfig.mojom.DeviceStateType.kEnabled;
},
/**
@@ -595,44 +610,44 @@ Polymer({
* @return {string}
*/
getAddThirdPartyVpnLabel_: function(provider) {
- return this.i18n(
- 'internetAddThirdPartyVPN', provider.ProviderName || '');
+ return this.i18n('internetAddThirdPartyVPN', provider.ProviderName || '');
},
/**
* Handles UI requests to connect to a network.
* TODO(stevenjb): Handle Cellular activation, etc.
* @param {!CustomEvent<!{
- * networkProperties: (!CrOnc.NetworkProperties|
- * !CrOnc.NetworkStateProperties),
+ * networkState: !OncMojo.NetworkStateProperties,
* bypassConnectionDialog: (boolean|undefined)
* }>} event
* @private
*/
onNetworkConnect_: function(event) {
- const properties = event.detail.networkProperties;
- const name = CrOnc.getNetworkName(properties);
- const networkType = properties.Type;
+ const networkState = event.detail.networkState;
+ const oncType = OncMojo.getNetworkTypeString(networkState.type);
+ const displayName = OncMojo.getNetworkDisplayName(networkState);
+
if (!event.detail.bypassConnectionDialog &&
- CrOnc.shouldShowTetherDialogBeforeConnection(properties)) {
+ networkState.type == mojom.NetworkType.kTether &&
+ !networkState.tether.hasConnectedToHost) {
const params = new URLSearchParams;
- params.append('guid', properties.GUID);
- params.append('type', networkType);
- params.append('name', name);
+ params.append('guid', networkState.guid);
+ params.append('type', oncType);
+ params.append('name', displayName);
params.append('showConfigure', true.toString());
settings.navigateTo(settings.routes.NETWORK_DETAIL, params);
return;
}
- if (!CrOnc.isMobileNetwork(properties) &&
- (properties.Connectable === false || !!properties.ErrorState)) {
+ const isMobile = OncMojo.networkTypeIsMobile(networkState.type);
+ if (!isMobile && (!networkState.connectable || !!networkState.errorState)) {
this.showConfig_(
- true /* configAndConnect */, networkType, properties.GUID, name);
+ true /* configAndConnect */, oncType, networkState.guid, displayName);
return;
}
- this.networkingPrivate.startConnect(properties.GUID, () => {
+ this.networkingPrivate.startConnect(networkState.guid, () => {
if (chrome.runtime.lastError) {
const message = chrome.runtime.lastError.message;
if (message == 'connecting' || message == 'connect-canceled' ||
@@ -641,14 +656,16 @@ Polymer({
}
console.error(
'networkingPrivate.startConnect error: ' + message +
- ' For: ' + properties.GUID);
+ ' For: ' + networkState.guid);
// There is no configuration flow for Mobile Networks.
- if (!CrOnc.isMobileNetwork(properties)) {
+ if (!isMobile) {
this.showConfig_(
- true /* configAndConnect */, networkType, properties.GUID, name);
+ true /* configAndConnect */, oncType, networkState.guid,
+ displayName);
}
}
});
},
});
+})();
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html b/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html
index 6378a878a5f..3516ce9f4de 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.html
@@ -1,10 +1,12 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_list.html">
+<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
+<link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
@@ -110,7 +112,7 @@
<template is="dom-if" if="[[deviceIsEnabled_(deviceState)]]">
<div id="networkListDiv" class="layout vertical flex">
<!-- VPN only header for built-in VPNs. -->
- <template is="dom-if" if="[[isEqual_('VPN', deviceState.Type)]]">
+ <template is="dom-if" if="[[matchesType_('VPN', deviceState)]]">
<div class="vpn-header layout horizontal center">
<div class="flex settings-box-text">$i18n{networkVpnBuiltin}</div>
<cr-icon-button class="icon-add-circle"
@@ -156,7 +158,7 @@
class="no-networks">
</div>
- <template is="dom-if" if="[[isEqual_('VPN', deviceState.Type)]]">
+ <template is="dom-if" if="[[matchesType_('VPN', deviceState)]]">
<!-- Third party VPNs. -->
<template is="dom-repeat" items="[[thirdPartyVpnProviders]]">
<div id="[[item.ProviderName]]"
diff --git a/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js b/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js
index a7e399ef0d0..0b5b7863c2f 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/internet_subpage.js
@@ -7,10 +7,15 @@
* WiMAX, or virtual networks.
*/
+(function() {
+
+const mojom = chromeos.networkConfig.mojom;
+
Polymer({
is: 'settings-internet-subpage',
behaviors: [
+ CrNetworkListenerBehavior,
CrPolicyNetworkBehavior,
settings.RouteObserverBehavior,
I18nBehavior,
@@ -20,7 +25,7 @@ Polymer({
/**
* Highest priority connected network or null. Provided by
* settings-internet-page (but set in network-summary).
- * @type {?CrOnc.NetworkStateProperties|undefined}
+ * @type {?OncMojo.NetworkStateProperties|undefined}
*/
defaultNetwork: Object,
@@ -28,14 +33,14 @@ Polymer({
* Device state for the network type. Note: when both Cellular and Tether
* are available this will always be set to the Cellular device state and
* |tetherDeviceState| will be set to the Tether device state.
- * @type {!CrOnc.DeviceStateProperties|undefined}
+ * @type {!OncMojo.DeviceStateProperties|undefined}
*/
deviceState: Object,
/**
* If both Cellular and Tether technologies exist, we combine the subpages
* and set this to the device state for Tether.
- * @type {!CrOnc.DeviceStateProperties|undefined}
+ * @type {!OncMojo.DeviceStateProperties|undefined}
*/
tetherDeviceState: Object,
@@ -55,12 +60,6 @@ Polymer({
*/
arcVpnProviders: Array,
- /**
- * Interface for networkingPrivate calls, passed from internet_page.
- * @type {!NetworkingPrivate}
- */
- networkingPrivate: Object,
-
showSpinner: {
type: Boolean,
notify: true,
@@ -69,7 +68,7 @@ Polymer({
/**
* List of all network state data for the network type.
- * @private {!Array<!CrOnc.NetworkStateProperties>}
+ * @private {!Array<!OncMojo.NetworkStateProperties>}
*/
networkStateList_: {
type: Array,
@@ -80,7 +79,7 @@ Polymer({
/**
* Dictionary of lists of network states for third party VPNs.
- * @private {!Object<!Array<!CrOnc.NetworkStateProperties>>}
+ * @private {!Object<!Array<!OncMojo.NetworkStateProperties>>}
*/
thirdPartyVpns_: {
type: Object,
@@ -91,7 +90,7 @@ Polymer({
/**
* Dictionary of lists of network states for Arc VPNs.
- * @private {!Object<!Array<!CrOnc.NetworkStateProperties>>}
+ * @private {!Object<!Array<!OncMojo.NetworkStateProperties>>}
*/
arcVpns_: {
type: Object,
@@ -125,12 +124,7 @@ Polymer({
},
},
- listeners: {
- 'network-list-changed': 'getNetworkStateList_',
- 'networks-changed': 'getNetworkStateList_',
- },
-
- observers: ['deviceStateChanged_(networkingPrivate, deviceState)'],
+ observers: ['deviceStateChanged_(deviceState)'],
/** @private {number|null} */
scanIntervalId_: null,
@@ -138,9 +132,20 @@ Polymer({
/** @private {settings.InternetPageBrowserProxy} */
browserProxy_: null,
+ /**
+ * This UI will use both the networkingPrivate extension API and the
+ * networkConfig mojo API until we provide all of the required functionality
+ * in networkConfig. TODO(stevenjb): Remove use of networkingPrivate api.
+ * @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy}
+ */
+ networkConfigProxy_: null,
+
/** @override */
created: function() {
this.browserProxy_ = settings.InternetPageBrowserProxyImpl.getInstance();
+ this.networkConfigProxy_ =
+ network_config.MojoInterfaceProviderImpl.getInstance()
+ .getMojoServiceProxy();
},
/** @override */
@@ -174,10 +179,23 @@ Polymer({
this.updateScanning_();
},
+ /**
+ * CrosNetworkConfigObserver impl
+ * @param {!Array<OncMojo.NetworkStateProperties>} networks
+ */
+ onActiveNetworksChanged: function(networks) {
+ this.getNetworkStateList_();
+ },
+
+ /** CrosNetworkConfigObserver impl */
+ onNetworkStateListChanged: function() {
+ this.getNetworkStateList_();
+ },
+
/** @private */
deviceStateChanged_: function() {
this.showSpinner =
- this.deviceState !== undefined && !!this.deviceState.Scanning;
+ this.deviceState !== undefined && !!this.deviceState.scanning;
// Scans should only be triggered by the "networks" subpage.
if (settings.getCurrentRoute() != settings.routes.INTERNET_NETWORKS) {
@@ -185,6 +203,7 @@ Polymer({
return;
}
+ this.getNetworkStateList_();
this.updateScanning_();
},
@@ -198,9 +217,6 @@ Polymer({
this.startScanning_();
return;
}
-
- // deviceState probably changed, re-request networks.
- this.getNetworkStateList_();
},
/**
@@ -209,14 +225,14 @@ Polymer({
*/
shouldStartScan_: function() {
// Scans should be kicked off from the Wi-Fi networks subpage.
- if (this.deviceState.Type == CrOnc.Type.WI_FI) {
+ if (this.deviceState.type == mojom.NetworkType.kWiFi) {
return true;
}
// Scans should be kicked off from the Mobile data subpage, as long as it
// includes Tether networks.
- if (this.deviceState.Type == CrOnc.Type.TETHER ||
- (this.deviceState.Type == CrOnc.Type.CELLULAR &&
+ if (this.deviceState.type == mojom.NetworkType.kTether ||
+ (this.deviceState.type == mojom.NetworkType.kCellular &&
this.tetherDeviceState)) {
return true;
}
@@ -230,9 +246,9 @@ Polymer({
return;
}
const INTERVAL_MS = 10 * 1000;
- this.networkingPrivate.requestNetworkScan(this.deviceState.Type);
+ this.networkConfigProxy_.requestNetworkScan(this.deviceState.type);
this.scanIntervalId_ = window.setInterval(() => {
- this.networkingPrivate.requestNetworkScan(this.deviceState.Type);
+ this.networkConfigProxy_.requestNetworkScan(this.deviceState.type);
}, INTERVAL_MS);
},
@@ -251,58 +267,66 @@ Polymer({
return;
}
const filter = {
- networkType: this.deviceState.Type,
- visible: true,
- configured: false
+ filter: chromeos.networkConfig.mojom.FilterType.kVisible,
+ limit: chromeos.networkConfig.mojom.kNoLimit,
+ networkType: this.deviceState.type,
};
- this.networkingPrivate.getNetworks(filter, this.onGetNetworks_.bind(this));
+ this.networkConfigProxy_.getNetworkStateList(filter).then(response => {
+ this.onGetNetworks_(response.result);
+ });
},
/**
- * @param {!Array<!CrOnc.NetworkStateProperties>} networkStates
+ * @param {!Array<!OncMojo.NetworkStateProperties>} networkStates
* @private
*/
onGetNetworks_: function(networkStates) {
if (!this.deviceState) {
+ // Edge case when device states change before this callback.
return;
- } // Edge case when device states change before this callback.
+ }
- // For the Cellular/Mobile subpage, request Tether networks if available.
- if (this.deviceState.Type == CrOnc.Type.CELLULAR &&
+ // For the Cellular/Mobile subpage, also request Tether networks.
+ if (this.deviceState.type == mojom.NetworkType.kCellular &&
this.tetherDeviceState) {
const filter = {
- networkType: CrOnc.Type.TETHER,
- visible: true,
- configured: false
+ filter: chromeos.networkConfig.mojom.FilterType.kVisible,
+ limit: chromeos.networkConfig.mojom.kNoLimit,
+ networkType: mojom.NetworkType.kTether,
};
- this.networkingPrivate.getNetworks(filter, tetherNetworkStates => {
+ this.networkConfigProxy_.getNetworkStateList(filter).then(response => {
+ const tetherNetworkStates = response.result;
this.networkStateList_ = networkStates.concat(tetherNetworkStates);
});
return;
}
// For VPNs, separate out third party VPNs and Arc VPNs.
- if (this.deviceState.Type == CrOnc.Type.VPN) {
+ if (this.deviceState.type == mojom.NetworkType.kVPN) {
const builtinNetworkStates = [];
const thirdPartyVpns = {};
const arcVpns = {};
- for (let i = 0; i < networkStates.length; ++i) {
- const state = networkStates[i];
- const providerType = this.get('VPN.ThirdPartyVPN.ProviderName', state);
- if (providerType) {
- thirdPartyVpns[providerType] = thirdPartyVpns[providerType] || [];
- thirdPartyVpns[providerType].push(state);
- } else if (this.get('VPN.Type', state) == 'ARCVPN') {
- const arcProviderName = this.get('VPN.Host', state);
- if (state.ConnectionState != CrOnc.ConnectionState.CONNECTED) {
- continue;
- }
- arcVpns[arcProviderName] = arcVpns[arcProviderName] || [];
- arcVpns[arcProviderName].push(state);
- } else {
- builtinNetworkStates.push(state);
+ networkStates.forEach(state => {
+ assert(state.type == mojom.NetworkType.kVPN);
+ switch (state.vpn.type) {
+ case mojom.VPNType.kL2TPIPsec:
+ case mojom.VPNType.kOpenVPN:
+ builtinNetworkStates.push(state);
+ break;
+ case mojom.VPNType.kThirdPartyVPN:
+ const providerName = state.vpn.providerName;
+ thirdPartyVpns[providerName] = thirdPartyVpns[providerName] || [];
+ thirdPartyVpns[providerName].push(state);
+ break;
+ case mojom.VPNType.kArcVPN:
+ const arcProviderName = this.get('VPN.Host', state);
+ if (OncMojo.connectionStateIsConnected(state.connectionState)) {
+ arcVpns[arcProviderName] = arcVpns[arcProviderName] || [];
+ arcVpns[arcProviderName].push(state);
+ }
+ break;
}
- }
+ });
networkStates = builtinNetworkStates;
this.thirdPartyVpns_ = thirdPartyVpns;
this.arcVpns_ = arcVpns;
@@ -321,16 +345,18 @@ Polymer({
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {boolean} Whether or not the device state is enabled.
* @private
*/
deviceIsEnabled_: function(deviceState) {
- return !!deviceState && deviceState.State == CrOnc.DeviceState.ENABLED;
+ return !!deviceState &&
+ deviceState.deviceState ==
+ chromeos.networkConfig.mojom.DeviceStateType.kEnabled;
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @param {string} onstr
* @param {string} offstr
* @return {string}
@@ -341,26 +367,28 @@ Polymer({
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {boolean}
* @private
*/
enableToggleIsVisible_: function(deviceState) {
- return !!deviceState && deviceState.Type != CrOnc.Type.ETHERNET &&
- deviceState.Type != CrOnc.Type.VPN;
+ return !!deviceState && deviceState.type != mojom.NetworkType.kEthernet &&
+ deviceState.type != mojom.NetworkType.kVPN;
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {boolean}
* @private
*/
enableToggleIsEnabled_: function(deviceState) {
- return !!deviceState && deviceState.State != CrOnc.DeviceState.PROHIBITED;
+ return !!deviceState &&
+ deviceState.deviceState !=
+ chromeos.networkConfig.mojom.DeviceStateType.kProhibited;
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {string}
* @private
*/
@@ -368,13 +396,13 @@ Polymer({
if (!this.enableToggleIsVisible_(deviceState)) {
return '';
}
- switch (deviceState.Type) {
- case CrOnc.Type.TETHER:
- case CrOnc.Type.CELLULAR:
+ switch (deviceState.type) {
+ case mojom.NetworkType.kTether:
+ case mojom.NetworkType.kCellular:
return this.i18n('internetToggleMobileA11yLabel');
- case CrOnc.Type.WI_FI:
+ case mojom.NetworkType.kWiFi:
return this.i18n('internetToggleWiFiA11yLabel');
- case CrOnc.Type.WI_MAX:
+ case mojom.NetworkType.kWiMAX:
return this.i18n('internetToggleWiMAXA11yLabel');
}
assertNotReached();
@@ -387,8 +415,7 @@ Polymer({
* @private
*/
getAddThirdPartyVpnA11yString_: function(vpnState) {
- return this.i18n(
- 'internetAddThirdPartyVPN', vpnState.ProviderName || '');
+ return this.i18n('internetAddThirdPartyVPN', vpnState.ProviderName || '');
},
/**
@@ -410,13 +437,13 @@ Polymer({
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy
* @return {boolean}
* @private
*/
showAddButton_: function(deviceState, globalPolicy) {
- if (!deviceState || deviceState.Type != CrOnc.Type.WI_FI) {
+ if (!deviceState || deviceState.type != mojom.NetworkType.kWiFi) {
return false;
}
if (!this.deviceIsEnabled_(deviceState)) {
@@ -428,15 +455,14 @@ Polymer({
/** @private */
onAddButtonTap_: function() {
assert(this.deviceState);
- const type = this.deviceState.Type;
- assert(type != CrOnc.Type.CELLULAR);
- this.fire('show-config', {GUID: '', Type: type});
+ const type = this.deviceState.type;
+ assert(type != mojom.NetworkType.kCellular);
+ this.fire('show-config', {type: OncMojo.getNetworkTypeString(type)});
},
/**
- * @param {!{model:
- * !{item: !chrome.networkingPrivate.ThirdPartyVPNProperties},
- * }} event
+ * @param {!{model: !{item:
+ * !chrome.networkingPrivate.ThirdPartyVPNProperties}}} event
* @private
*/
onAddThirdPartyVpnTap_: function(event) {
@@ -454,12 +480,12 @@ Polymer({
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {boolean}
* @private
*/
knownNetworksIsVisible_: function(deviceState) {
- return !!deviceState && deviceState.Type == CrOnc.Type.WI_FI;
+ return !!deviceState && deviceState.type == mojom.NetworkType.kWiFi;
},
/**
@@ -467,8 +493,8 @@ Polymer({
* @private
*/
onKnownNetworksTap_: function() {
- assert(this.deviceState.Type == CrOnc.Type.WI_FI);
- this.fire('show-known-networks', {type: this.deviceState.Type});
+ assert(this.deviceState.type == mojom.NetworkType.kWiFi);
+ this.fire('show-known-networks', this.deviceState.type);
},
/**
@@ -480,14 +506,14 @@ Polymer({
assert(this.deviceState);
this.fire('device-enabled-toggled', {
enabled: !this.deviceIsEnabled_(this.deviceState),
- type: this.deviceState.Type
+ type: this.deviceState.type
});
},
/**
- * @param {!Object<!Array<!CrOnc.NetworkStateProperties>>} thirdPartyVpns
+ * @param {!Object<!Array<!OncMojo.NetworkStateProperties>>} thirdPartyVpns
* @param {!chrome.networkingPrivate.ThirdPartyVPNProperties} vpnState
- * @return {!Array<!CrOnc.NetworkStateProperties>}
+ * @return {!Array<!OncMojo.NetworkStateProperties>}
* @private
*/
getThirdPartyVpnNetworks_: function(thirdPartyVpns, vpnState) {
@@ -495,7 +521,7 @@ Polymer({
},
/**
- * @param {!Object<!Array<!CrOnc.NetworkStateProperties>>} thirdPartyVpns
+ * @param {!Object<!Array<!OncMojo.NetworkStateProperties>>} thirdPartyVpns
* @param {!chrome.networkingPrivate.ThirdPartyVPNProperties} vpnState
* @return {boolean}
* @private
@@ -506,9 +532,9 @@ Polymer({
},
/**
- * @param {!Object<!Array<!CrOnc.NetworkStateProperties>>} arcVpns
+ * @param {!Object<!Array<!OncMojo.NetworkStateProperties>>} arcVpns
* @param {!settings.ArcVpnProvider} arcVpnProvider
- * @return {!Array<!CrOnc.NetworkStateProperties>}
+ * @return {!Array<!OncMojo.NetworkStateProperties>}
* @private
*/
getArcVpnNetworks_: function(arcVpns, arcVpnProvider) {
@@ -516,7 +542,7 @@ Polymer({
},
/**
- * @param {!Object<!Array<!CrOnc.NetworkStateProperties>>} arcVpns
+ * @param {!Object<!Array<!OncMojo.NetworkStateProperties>>} arcVpns
* @param {!settings.ArcVpnProvider} arcVpnProvider
* @return {boolean}
* @private
@@ -528,81 +554,81 @@ Polymer({
/**
* Event triggered when a network list item is selected.
- * @param {!{target: HTMLElement, detail: !CrOnc.NetworkStateProperties}} e
+ * @param {!{target: HTMLElement, detail: !OncMojo.NetworkStateProperties}} e
* @private
*/
onNetworkSelected_: function(e) {
assert(this.globalPolicy);
assert(this.defaultNetwork !== undefined);
- const state = e.detail;
+ const networkState = e.detail;
e.target.blur();
- if (this.canConnect_(state)) {
- this.fire('network-connect', {networkProperties: state});
+ if (this.canConnect_(networkState)) {
+ this.fire('network-connect', {networkState: networkState});
return;
}
- this.fire('show-detail', state);
+ this.fire('show-detail', networkState);
},
/**
- * @param {!CrOnc.NetworkStateProperties} state The network state.
+ * @param {!OncMojo.NetworkStateProperties} state The network state.
* @return {boolean}
* @private
*/
isBlockedByPolicy_: function(state) {
- if (state.Type != CrOnc.Type.WI_FI || this.isPolicySource(state.Source) ||
- !this.globalPolicy) {
+ if (state.type != mojom.NetworkType.kWiFi ||
+ this.isPolicySourceMojo(state.source) || !this.globalPolicy) {
return false;
}
return !!this.globalPolicy.AllowOnlyPolicyNetworksToConnect ||
(!!this.globalPolicy.AllowOnlyPolicyNetworksToConnectIfAvailable &&
- !!this.deviceState && !!this.deviceState.ManagedNetworkAvailable) ||
- (!!state.WiFi && !!state.WiFi.HexSSID &&
- !!this.globalPolicy.BlacklistedHexSSIDs &&
- this.globalPolicy.BlacklistedHexSSIDs.includes(state.WiFi.HexSSID));
+ !!this.deviceState && !!this.deviceState.managedNetworkAvailable) ||
+ (!!this.globalPolicy.BlacklistedHexSSIDs &&
+ this.globalPolicy.BlacklistedHexSSIDs.includes(state.wifi.hexSsid));
},
/**
* Determines whether or not a network state can be connected to.
- * @param {!CrOnc.NetworkStateProperties} state The network state.
+ * @param {!OncMojo.NetworkStateProperties} state The network state.
* @private
*/
canConnect_: function(state) {
- if (state.ConnectionState != CrOnc.ConnectionState.NOT_CONNECTED) {
+ if (state.connectionState != mojom.ConnectionStateType.kNotConnected) {
return false;
}
if (this.isBlockedByPolicy_(state)) {
return false;
}
- if (state.Type == CrOnc.Type.VPN &&
+ if (state.type == mojom.NetworkType.kVPN &&
(!this.defaultNetwork ||
- this.defaultNetwork.ConnectionState !=
- CrOnc.ConnectionState.CONNECTED)) {
+ !OncMojo.connectionStateIsConnected(
+ this.defaultNetwork.connectionState))) {
return false;
}
return true;
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
- * @param {!CrOnc.DeviceStateProperties|undefined} tetherDeviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} tetherDeviceState
* @return {boolean}
* @private
*/
tetherToggleIsVisible_: function(deviceState, tetherDeviceState) {
- return !!deviceState && deviceState.Type == CrOnc.Type.CELLULAR &&
+ return !!deviceState && deviceState.type == mojom.NetworkType.kCellular &&
!!tetherDeviceState;
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
- * @param {!CrOnc.DeviceStateProperties|undefined} tetherDeviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} tetherDeviceState
* @return {boolean}
* @private
*/
tetherToggleIsEnabled_: function(deviceState, tetherDeviceState) {
return this.tetherToggleIsVisible_(deviceState, tetherDeviceState) &&
this.enableToggleIsEnabled_(tetherDeviceState) &&
- tetherDeviceState.State != CrOnc.DeviceState.UNINITIALIZED;
+ tetherDeviceState.deviceState !=
+ chromeos.networkConfig.mojom.DeviceStateType.kUninitialized;
},
/**
@@ -612,23 +638,24 @@ Polymer({
onTetherEnabledChange_: function(event) {
this.fire('device-enabled-toggled', {
enabled: !this.deviceIsEnabled_(this.tetherDeviceState),
- type: CrOnc.Type.TETHER,
+ type: mojom.NetworkType.kTether,
});
event.stopPropagation();
},
/**
- * @param {*} lhs
- * @param {*} rhs
+ * @param {string} typeString
+ * @param {OncMojo.DeviceStateProperties} device
* @return {boolean}
* @private
*/
- isEqual_: function(lhs, rhs) {
- return lhs === rhs;
+ matchesType_: function(typeString, device) {
+ return device &&
+ device.type == OncMojo.getNetworkTypeFromString(typeString);
},
/**
- * @param {!Array<!CrOnc.NetworkStateProperties>} networkStateList
+ * @param {!Array<!OncMojo.NetworkStateProperties>} networkStateList
* @return {boolean}
* @private
*/
@@ -637,15 +664,15 @@ Polymer({
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
- * @param {!CrOnc.DeviceStateProperties|undefined} tetherDeviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} tetherDeviceState
* @return {string}
* @private
*/
getNoNetworksString_: function(deviceState, tetherDeviceState) {
- const type = deviceState.Type;
- if (type == CrOnc.Type.TETHER ||
- (type == CrOnc.Type.CELLULAR && this.tetherDeviceState)) {
+ const type = deviceState.type;
+ if (type == mojom.NetworkType.kTether ||
+ (type == mojom.NetworkType.kCellular && this.tetherDeviceState)) {
return this.i18nAdvanced('internetNoNetworksMobileData');
}
@@ -684,3 +711,4 @@ Polymer({
return this.i18n('gmscoreNotificationsManyDevicesSubtitle');
},
});
+})();
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html
index 9d718a9df80..c1e7309b691 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/network_proxy_section.html
@@ -2,6 +2,7 @@
<link rel="import" href="chrome://resources/cr_components/chromeos/network/network_proxy.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior.html">
@@ -10,7 +11,6 @@
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../controls/extension_controlled_indicator.html">
<link rel="import" href="../controls/settings_toggle_button.html">
<link rel="import" href="../i18n_setup.html">
@@ -20,7 +20,8 @@
<dom-module id="network-proxy-section">
<template>
- <style include="internet-shared cr-hidden-style iron-flex iron-flex-alignment">
+ <style include="internet-shared cr-hidden-style iron-flex
+ iron-flex-alignment">
cr-policy-network-indicator {
margin-inline-end: 10px;
}
@@ -89,14 +90,14 @@
$i18n{networkProxyAllowSharedWarningMessage}
</div>
<div slot="button-container">
- <paper-button class="cancel-button"
+ <cr-button class="cancel-button"
on-click="onAllowSharedDialogCancel_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button"
+ </cr-button>
+ <cr-button class="action-button"
on-click="onAllowSharedDialogConfirm_">
$i18n{confirm}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_summary.html b/chromium/chrome/browser/resources/settings/internet_page/network_summary.html
index f31a25cd7aa..1dfcd0bccaf 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/network_summary.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/network_summary.html
@@ -1,18 +1,18 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
+<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_network_behavior.html">
+<link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html">
<link rel="import" href="network_summary_item.html">
<dom-module id="network-summary">
<template>
<div id="summary">
<template is="dom-repeat" items="[[activeNetworkStates_]]">
- <network-summary-item id="[[item.Type]]"
+ <network-summary-item id="[[getTypeString_(item)]]"
active-network-state="[[item]]"
- device-state="[[get(item.Type, deviceStates)]]"
- network-state-list="[[get(item.Type, networkStateLists_)]]"
- networking-private="[[networkingPrivate]]"
+ device-state="[[get(item.type, deviceStates)]]"
+ network-state-list="[[get(item.type, networkStateLists_)]]"
tether-device-state="[[get('Tether', deviceStates)]]">
</network-summary-item>
</template>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_summary.js b/chromium/chrome/browser/resources/settings/internet_page/network_summary.js
index 4bdfa6b5cb4..70b08bde47c 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/network_summary.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/network_summary.js
@@ -7,37 +7,23 @@
* by type: Ethernet, WiFi, Cellular, WiMAX, and VPN.
*/
-/**
- * @typedef {{
- * Ethernet: (!CrOnc.DeviceStateProperties|undefined),
- * WiFi: (!CrOnc.DeviceStateProperties|undefined),
- * Cellular: (!CrOnc.DeviceStateProperties|undefined),
- * WiMAX: (!CrOnc.DeviceStateProperties|undefined),
- * VPN: (!CrOnc.DeviceStateProperties|undefined)
- * }}
- */
-let DeviceStateObject;
+(function() {
-/**
- * @typedef {{
- * Ethernet: (Array<!CrOnc.NetworkStateProperties>|undefined),
- * WiFi: (Array<!CrOnc.NetworkStateProperties>|undefined),
- * Cellular: (Array<!CrOnc.NetworkStateProperties>|undefined),
- * WiMAX: (Array<!CrOnc.NetworkStateProperties>|undefined),
- * VPN: (Array<!CrOnc.NetworkStateProperties>|undefined)
- * }}
- */
-let NetworkStateListObject;
+const mojom = chromeos.networkConfig.mojom;
Polymer({
is: 'network-summary',
- behaviors: [CrPolicyNetworkBehavior],
+ behaviors: [
+ CrNetworkListenerBehavior,
+ CrPolicyNetworkBehavior,
+ ],
properties: {
/**
- * Highest priority connected network or null.
- * @type {?CrOnc.NetworkStateProperties}
+ * Highest priority connected network or null. Set here to update
+ * internet-page which updates internet-subpage and internet-detail-page.
+ * @type {?OncMojo.NetworkStateProperties}
*/
defaultNetwork: {
type: Object,
@@ -46,23 +32,20 @@ Polymer({
},
/**
- * Interface for networkingPrivate calls, passed from internet_page.
- * @type {!NetworkingPrivate}
- */
- networkingPrivate: Object,
-
- /**
* The device state for each network device type. We initialize this to
* include a disabled WiFi type since WiFi is always present. This reduces
* the amount of visual change on first load.
- * @private {!DeviceStateObject}
+ * @private {!Object<!OncMojo.DeviceStateProperties>}
*/
deviceStates: {
type: Object,
value: function() {
- return {
- WiFi: {Type: CrOnc.Type.WI_FI, State: CrOnc.DeviceState.DISABLED},
+ const result = {};
+ result[chromeos.networkConfig.mojom.NetworkType.kWiFi] = {
+ deviceState: chromeos.networkConfig.mojom.DeviceStateType.kDisabled,
+ type: chromeos.networkConfig.mojom.NetworkType.kWiFi,
};
+ return result;
},
notify: true,
},
@@ -70,38 +53,31 @@ Polymer({
/**
* Array of active network states, one per device type. Initialized to
* include a default WiFi state (see deviceStates comment).
- * @private {!Array<!CrOnc.NetworkStateProperties>}
+ * @private {!Array<!OncMojo.NetworkStateProperties>}
*/
activeNetworkStates_: {
type: Array,
value: function() {
- return [{GUID: '', Type: CrOnc.Type.WI_FI}];
+ return [OncMojo.getDefaultNetworkState(mojom.NetworkType.kWiFi)];
},
},
/**
* List of network state data for each network type.
- * @private {!NetworkStateListObject}
+ * @private {!Object<!Array<!OncMojo.NetworkStateProperties>>}
*/
networkStateLists_: {
type: Object,
value: function() {
- return {WiFi: []};
+ const result = {};
+ result[mojom.NetworkType.kWiFi] = [];
+ return result;
},
},
},
- listeners: {
- 'network-list-changed': 'getNetworkLists_',
- 'networks-changed': 'updateActiveNetworks_',
- },
-
- /**
- * Listener function for chrome.networkingPrivate.onDeviceStateListChanged
- * event.
- * @private {?function(!Array<string>)}
- */
- deviceStateListChangedListener_: null,
+ /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} */
+ networkConfigProxy_: null,
/**
* Set of GUIDs identifying active networks, one for each type.
@@ -110,80 +86,45 @@ Polymer({
activeNetworkIds_: null,
/** @override */
- attached: function() {
- this.getNetworkLists_();
-
- this.deviceStateListChangedListener_ =
- this.deviceStateListChangedListener_ ||
- this.onDeviceStateListChangedEvent_.bind(this);
- this.networkingPrivate.onDeviceStateListChanged.addListener(
- this.deviceStateListChangedListener_);
+ created: function() {
+ this.networkConfigProxy_ =
+ network_config.MojoInterfaceProviderImpl.getInstance()
+ .getMojoServiceProxy();
},
/** @override */
- detached: function() {
- this.networkingPrivate.onDeviceStateListChanged.removeListener(
- assert(this.deviceStateListChangedListener_));
- },
-
- /**
- * networkingPrivate.onDeviceStateListChanged event callback.
- * @private
- */
- onDeviceStateListChangedEvent_: function() {
+ attached: function() {
this.getNetworkLists_();
},
/**
- * @param {!CustomEvent<!Array<string>>} event
- * @private
+ * CrosNetworkConfigObserver impl
+ * Updates any matching existing active networks. Note: newly active networks
+ * will trigger onNetworkStateListChanged which triggers getNetworkLists_.
+ * @param {!Array<OncMojo.NetworkStateProperties>} networks
*/
- updateActiveNetworks_: function(event) {
+ onActiveNetworksChanged: function(networks) {
if (!this.activeNetworkIds_) {
+ // Initial list of networks not received yet.
return;
- } // Initial list of networks not received yet.
- const networkIds = event.detail;
- networkIds.forEach(function(id) {
- if (this.activeNetworkIds_.has(id)) {
- this.networkingPrivate.getState(
- id, this.getActiveStateCallback_.bind(this, id));
+ }
+ networks.forEach(network => {
+ const index = this.activeNetworkStates_.findIndex(
+ state => state.guid == network.guid);
+ if (index != -1) {
+ this.set(['activeNetworkStates_', index], network);
}
- }, this);
+ });
},
- /**
- * networkingPrivate.getState event callback for an active state.
- * @param {string} id The id of the requested state.
- * @param {!CrOnc.NetworkStateProperties} state
- * @private
- */
- getActiveStateCallback_: function(id, state) {
- if (chrome.runtime.lastError) {
- const message = chrome.runtime.lastError.message;
- if (message != 'Error.NetworkUnavailable' &&
- message != 'Error.InvalidNetworkGuid') {
- console.error(
- 'Unexpected networkingPrivate.getState error: ' + message +
- ' For: ' + id);
- return;
- }
- }
- // Async call, ensure id still exists.
- if (!this.activeNetworkIds_.has(id)) {
- return;
- }
- if (!state) {
- this.activeNetworkIds_.delete(id);
- return;
- }
- // Find the active state for the type and update it.
- const idx =
- this.activeNetworkStates_.findIndex((s) => s.Type == state.Type);
- if (idx == -1) {
- console.error('Active state not found: ' + state.Name);
- return;
- }
- this.set(['activeNetworkStates_', idx], state);
+ /** CrosNetworkConfigObserver impl */
+ onNetworkStateListChanged: function() {
+ this.getNetworkLists_();
+ },
+
+ /** CrosNetworkConfigObserver impl */
+ onDeviceStateListChanged: function() {
+ this.getNetworkLists_();
},
/**
@@ -194,9 +135,9 @@ Polymer({
*/
getNetworkLists_: function() {
// First get the device states.
- this.networkingPrivate.getDeviceStates(deviceStates => {
+ this.networkConfigProxy_.getDeviceStateList().then(response => {
// Second get the network states.
- this.getNetworkStates_(deviceStates);
+ this.getNetworkStates_(response.result);
});
},
@@ -204,54 +145,61 @@ Polymer({
* Requests the list of network states from Chrome. Updates
* activeNetworkStates and networkStateLists once the results are returned
* from Chrome.
- * @param {!Array<!CrOnc.DeviceStateProperties>} deviceStates
+ * @param {!Array<!OncMojo.DeviceStateProperties>} deviceStateList
* @private
*/
- getNetworkStates_: function(deviceStates) {
+ getNetworkStates_: function(deviceStateList) {
const filter = {
- networkType: CrOnc.Type.ALL,
- visible: true,
- configured: false
+ filter: chromeos.networkConfig.mojom.FilterType.kVisible,
+ limit: chromeos.networkConfig.mojom.kNoLimit,
+ networkType: mojom.NetworkType.kAll,
};
- this.networkingPrivate.getNetworks(filter, networkStates => {
- this.updateNetworkStates_(networkStates, deviceStates);
+ this.networkConfigProxy_.getNetworkStateList(filter).then(response => {
+ this.updateNetworkStates_(response.result, deviceStateList);
});
},
/**
* Called after network states are received from getNetworks.
- * @param {!Array<!CrOnc.NetworkStateProperties>} networkStates The state
+ * @param {!Array<!OncMojo.NetworkStateProperties>} networkStates The state
* properties for all visible networks.
- * @param {!Array<!CrOnc.DeviceStateProperties>} deviceStates
+ * @param {!Array<!OncMojo.DeviceStateProperties>} deviceStateList
* @private
*/
- updateNetworkStates_: function(networkStates, deviceStates) {
- const newDeviceStates = /** @type {!DeviceStateObject} */ ({});
- for (const state of deviceStates) {
- newDeviceStates[state.Type] = state;
+ updateNetworkStates_: function(networkStates, deviceStateList) {
+ const newDeviceStates = {};
+ for (const device of deviceStateList) {
+ newDeviceStates[device.type] = device;
}
+ const orderedNetworkTypes = [
+ mojom.NetworkType.kEthernet,
+ mojom.NetworkType.kWiFi,
+ mojom.NetworkType.kCellular,
+ mojom.NetworkType.kTether,
+ mojom.NetworkType.kWiMAX,
+ mojom.NetworkType.kVPN,
+ ];
+
// Clear any current networks.
const activeNetworkStatesByType =
- /** @type {!Map<string, !CrOnc.NetworkStateProperties>} */ (new Map);
+ /** @type {!Map<mojom.NetworkType, !OncMojo.NetworkStateProperties>} */
+ (new Map);
// Complete list of states by type.
- /** @type {!NetworkStateListObject} */ const newNetworkStateLists = {
- Ethernet: [],
- Tether: [],
- WiFi: [],
- Cellular: [],
- WiMAX: [],
- VPN: [],
- };
+ const newNetworkStateLists = {};
+ for (const type of orderedNetworkTypes) {
+ newNetworkStateLists[type] = [];
+ }
let firstConnectedNetwork = null;
networkStates.forEach(function(networkState) {
- const type = networkState.Type;
+ const type = networkState.type;
if (!activeNetworkStatesByType.has(type)) {
activeNetworkStatesByType.set(type, networkState);
- if (!firstConnectedNetwork && networkState.Type != CrOnc.Type.VPN &&
- networkState.ConnectionState == CrOnc.ConnectionState.CONNECTED) {
+ if (!firstConnectedNetwork &&
+ networkState.type != mojom.NetworkType.kVPN &&
+ OncMojo.connectionStateIsConnected(networkState.connectionState)) {
firstConnectedNetwork = networkState;
}
}
@@ -261,10 +209,10 @@ Polymer({
this.defaultNetwork = firstConnectedNetwork;
// Create a VPN entry in deviceStates if there are any VPN networks.
- if (newNetworkStateLists.VPN && newNetworkStateLists.VPN.length > 0) {
- newDeviceStates.VPN = {
- Type: CrOnc.Type.VPN,
- State: CrOnc.DeviceState.ENABLED
+ if (newNetworkStateLists[mojom.NetworkType.kVPN].length > 0) {
+ newDeviceStates[mojom.NetworkType.kVPN] = {
+ type: mojom.NetworkType.kVPN,
+ deviceState: chromeos.networkConfig.mojom.DeviceStateType.kEnabled,
};
}
@@ -272,11 +220,7 @@ Polymer({
// device priority, creating an empty state for devices with no networks.
const newActiveNetworkStates = [];
this.activeNetworkIds_ = new Set;
- const orderedDeviceTypes = [
- CrOnc.Type.ETHERNET, CrOnc.Type.WI_FI, CrOnc.Type.CELLULAR,
- CrOnc.Type.TETHER, CrOnc.Type.WI_MAX, CrOnc.Type.VPN
- ];
- for (const type of orderedDeviceTypes) {
+ for (const type of orderedNetworkTypes) {
const device = newDeviceStates[type];
if (!device) {
continue;
@@ -285,24 +229,26 @@ Polymer({
// If both 'Tether' and 'Cellular' technologies exist, merge the network
// lists and do not add an active network for 'Tether' so that there is
// only one 'Mobile data' section / subpage.
- if (type == CrOnc.Type.TETHER && newDeviceStates[CrOnc.Type.CELLULAR]) {
- newNetworkStateLists[CrOnc.Type.CELLULAR] =
- newNetworkStateLists[CrOnc.Type.CELLULAR].concat(
- newNetworkStateLists[CrOnc.Type.TETHER]);
+ if (type == mojom.NetworkType.kTether &&
+ newDeviceStates[mojom.NetworkType.kCellular]) {
+ newNetworkStateLists[mojom.NetworkType.kCellular] =
+ newNetworkStateLists[mojom.NetworkType.kCellular].concat(
+ newNetworkStateLists[mojom.NetworkType.kTether]);
continue;
}
// Note: The active state for 'Cellular' may be a Tether network if both
// types are enabled but no Cellular network exists (edge case).
- const state =
+ const networkState =
this.getActiveStateForType_(activeNetworkStatesByType, type);
- if (state.Source === undefined &&
- device.State == CrOnc.DeviceState.PROHIBITED) {
+ if (networkState.source === undefined &&
+ device.deviceState == mojom.DeviceStateType.kProhibited) {
// Prohibited technologies are enforced by the device policy.
- state.Source = CrOnc.Source.DEVICE_POLICY;
+ networkState.source =
+ chromeos.networkConfig.mojom.OncSource.kDevicePolicy;
}
- newActiveNetworkStates.push(state);
- this.activeNetworkIds_.add(state.GUID);
+ newActiveNetworkStates.push(networkState);
+ this.activeNetworkIds_.add(networkState.guid);
}
this.deviceStates = newDeviceStates;
@@ -315,15 +261,37 @@ Polymer({
* Returns the active network state for |type| or a default network state.
* If there is no 'Cellular' network, return the active 'Tether' network if
* any since the two types are represented by the same section / subpage.
- * @param {!Map<string, !CrOnc.NetworkStateProperties>} activeStatesByType
- * @param {string} type
- * @return {!CrOnc.NetworkStateProperties|undefined}
+ * @param {!Map<mojom.NetworkType, !OncMojo.NetworkStateProperties>}
+ * activeStatesByType
+ * @param {!mojom.NetworkType} type
+ * @return {!OncMojo.NetworkStateProperties|undefined}
+ * @private
*/
getActiveStateForType_: function(activeStatesByType, type) {
let activeState = activeStatesByType.get(type);
- if (!activeState && type == CrOnc.Type.CELLULAR) {
- activeState = activeStatesByType.get(CrOnc.Type.TETHER);
+ if (!activeState && type == mojom.NetworkType.kCellular) {
+ activeState = activeStatesByType.get(mojom.NetworkType.kTether);
}
- return activeState || {GUID: '', Type: type};
+ return activeState || OncMojo.getDefaultNetworkState(type);
+ },
+
+ /**
+ * Provides an id string for summary items. Used in tests.
+ * @param {!OncMojo.NetworkStateProperties} network
+ * @return {string}
+ * @private
+ */
+ getTypeString_: function(network) {
+ return OncMojo.getNetworkTypeString(network.type);
+ },
+
+ /**
+ * @param {!Object<!OncMojo.DeviceStateProperties>} deviceStates
+ * @return {!OncMojo.DeviceStateProperties|undefined}
+ * @private
+ */
+ getTetherDeviceState_: function(deviceStates) {
+ return this.deviceStates[mojom.NetworkType.kTether];
},
});
+})();
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.html b/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.html
index e5326a65acb..7e6f3f9fbce 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.html
@@ -2,10 +2,12 @@
<link rel="import" href="chrome://resources/cr_components/chromeos/network/network_siminfo.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_icon.html">
+<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_indicator.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
+<link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
<link rel="import" href="../settings_page/settings_subpage.html">
@@ -19,7 +21,6 @@
#outerBox {
padding: 0 var(--cr-section-padding);
- @apply(--network-summary-item-outer-box);
}
#details {
@@ -31,7 +32,6 @@
#networkTitleText {
color: #333;
font-weight: 500;
- @apply(--network-summary-item-title);
}
#networkState {
@@ -60,15 +60,13 @@
</div>
<template is="dom-if" if="[[showSimInfo_(deviceState)]]" restamp>
- <network-siminfo editable on-click="doNothing_"
- network-properties="[[getCellularState_(deviceState)]]"
- networking-private="[[networkingPrivate]]">
+ <network-siminfo on-click="doNothing_">
</network-siminfo>
</template>
<template is="dom-if" if="[[showPolicyIndicator_(activeNetworkState)]]">
- <cr-policy-indicator indicator-type="[[getIndicatorTypeForSource(
- activeNetworkState.Source)]]" on-click="doNothing_">
+ <cr-policy-indicator indicator-type="[[getIndicatorTypeForSourceMojo(
+ activeNetworkState.source)]]" on-click="doNothing_">
</cr-policy-indicator>
</template>
diff --git a/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js b/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js
index 48217998b3b..326cf06dfa1 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js
+++ b/chromium/chrome/browser/resources/settings/internet_page/network_summary_item.js
@@ -9,6 +9,10 @@
* section. See crbug.com/726380.
*/
+(function() {
+
+const mojom = chromeos.networkConfig.mojom;
+
Polymer({
is: 'network-summary-item',
@@ -16,28 +20,28 @@ Polymer({
properties: {
/**
- * Device state for the network type. This might briefly be undefined if a
- * device becomes unavailable.
- * @type {!CrOnc.DeviceStateProperties|undefined}
+ * Device state for the network type. This might briefly be undefined if
+ * a device becomes unavailable.
+ * @type {!OncMojo.DeviceStateProperties|undefined}
*/
deviceState: Object,
/**
- * If both Cellular and Tether technologies exist, we combine the sections
- * and set this to the device state for Tether.
- * @type {!CrOnc.DeviceStateProperties|undefined}
+ * If both Cellular and Tether technologies exist, we combine the
+ * sections and set this to the device state for Tether.
+ * @type {!OncMojo.DeviceStateProperties|undefined}
*/
tetherDeviceState: Object,
/**
* Network state for the active network.
- * @type {!CrOnc.NetworkStateProperties|undefined}
+ * @type {!OncMojo.NetworkStateProperties|undefined}
*/
activeNetworkState: Object,
/**
* List of all network state data for the network type.
- * @type {!Array<!CrOnc.NetworkStateProperties>}
+ * @type {!Array<!OncMojo.NetworkStateProperties>}
*/
networkStateList: {
type: Array,
@@ -47,15 +51,9 @@ Polymer({
},
/**
- * Interface for networkingPrivate calls, passed from internet_page.
- * @type {!NetworkingPrivate}
- */
- networkingPrivate: Object,
-
- /**
- * Title line describing the network type to appear in the row's top line.
- * If it is undefined, the title text is a default from CrOncStrings (see
- * this.getTitleText_() below).
+ * Title line describing the network type to appear in the row's top
+ * line. If it is undefined, the title text is a default from
+ * CrOncStrings (see this.getTitleText_() below).
* @type {string|undefined}
*/
networkTitleText: String,
@@ -74,39 +72,40 @@ Polymer({
},
/**
- * @param {!CrOnc.NetworkStateProperties} activeNetworkState
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.NetworkStateProperties} activeNetworkState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {string}
* @private
*/
getNetworkStateText_: function(activeNetworkState, deviceState) {
- const stateText = this.getConnectionStateText_(activeNetworkState);
+ const stateText =
+ this.getConnectionStateText_(activeNetworkState, deviceState);
if (stateText) {
return stateText;
}
// No network state, use device state.
if (deviceState) {
// Type specific scanning or initialization states.
- if (deviceState.Type == CrOnc.Type.CELLULAR) {
- if (deviceState.Scanning) {
+ if (deviceState.type == mojom.NetworkType.kCellular) {
+ if (deviceState.scanning) {
return this.i18n('internetMobileSearching');
}
- if (deviceState.State == CrOnc.DeviceState.UNINITIALIZED) {
+ if (deviceState.deviceState == mojom.DeviceStateType.kUninitialized) {
return this.i18n('internetDeviceInitializing');
}
- } else if (deviceState.Type == CrOnc.Type.TETHER) {
- if (deviceState.State == CrOnc.DeviceState.UNINITIALIZED) {
+ } else if (deviceState.type == mojom.NetworkType.kTether) {
+ if (deviceState.deviceState == mojom.DeviceStateType.kUninitialized) {
return this.i18n('tetherEnableBluetooth');
}
}
// Enabled or enabling states.
- if (deviceState.State == CrOnc.DeviceState.ENABLED) {
+ if (deviceState.deviceState == mojom.DeviceStateType.kEnabled) {
if (this.networkStateList.length > 0) {
return CrOncStrings.networkListItemNotConnected;
}
return CrOncStrings.networkListItemNoNetwork;
}
- if (deviceState.State == CrOnc.DeviceState.ENABLING) {
+ if (deviceState.deviceState == mojom.DeviceStateType.kEnabling) {
return this.i18n('internetDeviceEnabling');
}
}
@@ -115,61 +114,59 @@ Polymer({
},
/**
- * @param {!CrOnc.NetworkStateProperties} networkState
+ * @param {!OncMojo.NetworkStateProperties} networkState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {string}
* @private
*/
- getConnectionStateText_: function(networkState) {
- const state = networkState ? networkState.ConnectionState : null;
- if (!state) {
+ getConnectionStateText_: function(networkState, deviceState) {
+ if (!networkState) {
return '';
}
- const name = CrOnc.getNetworkName(networkState);
- switch (state) {
- case CrOnc.ConnectionState.CONNECTED:
- return name;
- case CrOnc.ConnectionState.CONNECTING:
- if (name) {
- return CrOncStrings.networkListItemConnectingTo.replace('$1', name);
- }
- return CrOncStrings.networkListItemConnecting;
- case CrOnc.ConnectionState.NOT_CONNECTED:
- if (networkState.Type == CrOnc.Type.CELLULAR && networkState.Cellular &&
- networkState.Cellular.Scanning) {
- return this.i18n('internetMobileSearching');
- }
- return CrOncStrings.networkListItemNotConnected;
+ const connectionState = networkState.connectionState;
+ const name =
+ networkState ? OncMojo.getNetworkDisplayName(networkState) : '';
+ if (OncMojo.connectionStateIsConnected(connectionState)) {
+ return name;
}
- assertNotReached();
- return state;
+ if (connectionState == mojom.ConnectionStateType.kConnecting) {
+ return name ?
+ CrOncStrings.networkListItemConnectingTo.replace('$1', name) :
+ CrOncStrings.networkListItemConnecting;
+ }
+ if (networkState.type == mojom.NetworkType.kCellular && deviceState &&
+ deviceState.scanning) {
+ return this.i18n('internetMobileSearching');
+ }
+ return CrOncStrings.networkListItemNotConnected;
},
/**
- * @param {!CrOnc.NetworkStateProperties} activeNetworkState
+ * @param {!OncMojo.NetworkStateProperties} activeNetworkState
* @return {boolean}
* @private
*/
showPolicyIndicator_: function(activeNetworkState) {
return (activeNetworkState !== undefined &&
- activeNetworkState.ConnectionState ==
- CrOnc.ConnectionState.CONNECTED) ||
- this.isPolicySource(activeNetworkState.Source);
+ OncMojo.connectionStateIsConnected(
+ activeNetworkState.connectionState)) ||
+ this.isPolicySourceMojo(activeNetworkState.source);
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {boolean}
* @private
*/
showSimInfo_: function(deviceState) {
- if (!deviceState || deviceState.Type != CrOnc.Type.CELLULAR) {
+ if (!deviceState || deviceState.type != mojom.NetworkType.kCellular) {
return false;
}
return this.simLockedOrAbsent_(deviceState);
},
/**
- * @param {!CrOnc.DeviceStateProperties} deviceState
+ * @param {!OncMojo.DeviceStateProperties} deviceState
* @return {boolean}
* @private
*/
@@ -177,47 +174,29 @@ Polymer({
if (this.deviceIsEnabled_(deviceState)) {
return false;
}
- if (deviceState.SIMPresent === false) {
+ if (!deviceState.simLockStatus) {
+ return false;
+ }
+ if (deviceState.simLockStatus.simAbsent) {
return true;
}
- const simLockType =
- deviceState.SIMLockStatus ? deviceState.SIMLockStatus.LockType : '';
+ const simLockType = deviceState.simLockStatus.lockType;
return simLockType == CrOnc.LockType.PIN ||
simLockType == CrOnc.LockType.PUK;
},
/**
- * Returns a NetworkProperties object for <network-siminfo> built from
- * the device properties (since there will be no active network).
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
- * @return {!CrOnc.NetworkProperties|undefined}
- * @private
- */
- getCellularState_: function(deviceState) {
- if (!deviceState) {
- return undefined;
- }
- return {
- GUID: '',
- Type: CrOnc.Type.CELLULAR,
- Cellular: {
- SIMLockStatus: deviceState.SIMLockStatus,
- SIMPresent: deviceState.SIMPresent,
- },
- };
- },
-
- /**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {boolean} Whether or not the device state is enabled.
* @private
*/
deviceIsEnabled_: function(deviceState) {
- return !!deviceState && deviceState.State == CrOnc.DeviceState.ENABLED;
+ return !!deviceState &&
+ deviceState.deviceState == mojom.DeviceStateType.kEnabled;
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {boolean}
* @private
*/
@@ -225,17 +204,18 @@ Polymer({
if (!deviceState) {
return false;
}
- switch (deviceState.Type) {
- case CrOnc.Type.ETHERNET:
- case CrOnc.Type.VPN:
+ switch (deviceState.type) {
+ case mojom.NetworkType.kEthernet:
+ case mojom.NetworkType.kVPN:
return false;
- case CrOnc.Type.TETHER:
+ case mojom.NetworkType.kTether:
return true;
- case CrOnc.Type.WI_FI:
- case CrOnc.Type.WI_MAX:
- return deviceState.State != CrOnc.DeviceState.UNINITIALIZED;
- case CrOnc.Type.CELLULAR:
- return deviceState.State != CrOnc.DeviceState.UNINITIALIZED &&
+ case mojom.NetworkType.kWiFi:
+ case mojom.NetworkType.kWiMAX:
+ return deviceState.deviceState != mojom.DeviceStateType.kUninitialized;
+ case mojom.NetworkType.kCellular:
+ return deviceState.deviceState !=
+ mojom.DeviceStateType.kUninitialized &&
!this.simLockedOrAbsent_(deviceState);
}
assertNotReached();
@@ -243,18 +223,18 @@ Polymer({
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {boolean}
* @private
*/
enableToggleIsEnabled_: function(deviceState) {
return this.enableToggleIsVisible_(deviceState) &&
- deviceState.State != CrOnc.DeviceState.PROHIBITED &&
- deviceState.State != CrOnc.DeviceState.UNINITIALIZED;
+ deviceState.deviceState != mojom.DeviceStateType.kProhibited &&
+ deviceState.deviceState != mojom.DeviceStateType.kUninitialized;
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
* @return {string}
* @private
*/
@@ -262,13 +242,13 @@ Polymer({
if (!this.enableToggleIsVisible_(deviceState)) {
return '';
}
- switch (deviceState.Type) {
- case CrOnc.Type.TETHER:
- case CrOnc.Type.CELLULAR:
+ switch (deviceState.type) {
+ case mojom.NetworkType.kTether:
+ case mojom.NetworkType.kCellular:
return this.i18n('internetToggleMobileA11yLabel');
- case CrOnc.Type.WI_FI:
+ case mojom.NetworkType.kWiFi:
return this.i18n('internetToggleWiFiA11yLabel');
- case CrOnc.Type.WI_MAX:
+ case mojom.NetworkType.kWiMAX:
return this.i18n('internetToggleWiMAXA11yLabel');
}
assertNotReached();
@@ -276,21 +256,21 @@ Polymer({
},
/**
- * @param {!CrOnc.NetworkStateProperties} activeNetworkState
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
- * @param {!Array<!CrOnc.NetworkStateProperties>} networkStateList
+ * @param {!OncMojo.NetworkStateProperties} activeNetworkState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
+ * @param {!Array<!OncMojo.NetworkStateProperties>} networkStateList
* @return {boolean}
* @private
*/
showDetailsIsVisible_: function(
activeNetworkState, deviceState, networkStateList) {
return this.deviceIsEnabled_(deviceState) &&
- (!!activeNetworkState.GUID || networkStateList.length > 0);
+ (!!activeNetworkState.guid || networkStateList.length > 0);
},
/**
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
- * @param {!Array<!CrOnc.NetworkStateProperties>} networkStateList
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
+ * @param {!Array<!OncMojo.NetworkStateProperties>} networkStateList
* @return {boolean}
* @private
*/
@@ -298,14 +278,17 @@ Polymer({
if (!deviceState) {
return false;
}
- const type = deviceState.Type;
- if (type == CrOnc.Type.TETHER ||
- (type == CrOnc.Type.CELLULAR && this.tetherDeviceState)) {
+ const type = deviceState.type;
+ if (type == mojom.NetworkType.kTether ||
+ (type == mojom.NetworkType.kCellular && this.tetherDeviceState)) {
// The "Mobile data" subpage should always be shown if Tether networks are
// available, even if there are currently no associated networks.
return true;
}
- const minlen = (type == CrOnc.Type.WI_FI || type == CrOnc.Type.VPN) ? 1 : 2;
+ const minlen =
+ (type == mojom.NetworkType.kWiFi || type == mojom.NetworkType.kVPN) ?
+ 1 :
+ 2;
return networkStateList.length >= minlen;
},
@@ -316,14 +299,13 @@ Polymer({
onShowDetailsTap_: function(event) {
if (!this.deviceIsEnabled_(this.deviceState)) {
if (this.enableToggleIsEnabled_(this.deviceState)) {
- this.fire(
- 'device-enabled-toggled',
- {enabled: true, type: this.deviceState.Type});
+ const type = this.deviceState.type;
+ this.fire('device-enabled-toggled', {enabled: true, type: type});
}
} else if (this.shouldShowSubpage_(
this.deviceState, this.networkStateList)) {
- this.fire('show-networks', {type: this.deviceState.Type});
- } else if (this.activeNetworkState.GUID) {
+ this.fire('show-networks', this.deviceState.type);
+ } else if (this.activeNetworkState.guid) {
this.fire('show-detail', this.activeNetworkState);
} else if (this.networkStateList.length > 0) {
this.fire('show-detail', this.networkStateList[0]);
@@ -332,22 +314,22 @@ Polymer({
},
/**
- * @param {!CrOnc.NetworkStateProperties} activeNetworkState
- * @param {!CrOnc.DeviceStateProperties|undefined} deviceState
- * @param {!Array<!CrOnc.NetworkStateProperties>} networkStateList
+ * @param {!OncMojo.NetworkStateProperties} activeNetworkState
+ * @param {!OncMojo.DeviceStateProperties|undefined} deviceState
+ * @param {!Array<!OncMojo.NetworkStateProperties>} networkStateList
* @return {string}
* @private
*/
getDetailsA11yString_: function(
activeNetworkState, deviceState, networkStateList) {
if (!this.shouldShowSubpage_(deviceState, networkStateList)) {
- if (activeNetworkState.GUID) {
- return CrOnc.getNetworkName(activeNetworkState);
+ if (activeNetworkState.guid) {
+ return OncMojo.getNetworkDisplayName(activeNetworkState);
} else if (networkStateList.length > 0) {
- return CrOnc.getNetworkName(networkStateList[0]);
+ return OncMojo.getNetworkDisplayName(networkStateList[0]);
}
}
- return this.i18n('OncType' + deviceState.Type);
+ return this.getNetworkTypeString_(deviceState.type);
},
/**
@@ -356,10 +338,11 @@ Polymer({
* @private
*/
onDeviceEnabledChange_: function(event) {
+ assert(this.deviceState);
const deviceIsEnabled = this.deviceIsEnabled_(this.deviceState);
- const type = this.deviceState ? this.deviceState.Type : '';
this.fire(
- 'device-enabled-toggled', {enabled: !deviceIsEnabled, type: type});
+ 'device-enabled-toggled',
+ {enabled: !deviceIsEnabled, type: this.deviceState.type});
},
/**
@@ -367,8 +350,9 @@ Polymer({
* @private
*/
getTitleText_: function() {
+ assert(CrOncStrings);
return this.networkTitleText ||
- CrOncStrings['OncType' + this.activeNetworkState.Type];
+ this.getNetworkTypeString_(this.activeNetworkState.type);
},
/**
@@ -379,4 +363,21 @@ Polymer({
doNothing_: function(event) {
event.stopPropagation();
},
+
+ /**
+ * @param {!mojom.NetworkType} type
+ * @return {string}
+ * @private
+ */
+ getNetworkTypeString_: function(type) {
+ // The shared Cellular/Tether subpage is referred to as "Mobile".
+ // TODO(khorimoto): Remove once Cellular/Tether are split into their own
+ // sections.
+ if (type == mojom.NetworkType.kCellular ||
+ type == mojom.NetworkType.kTether) {
+ type = mojom.NetworkType.kMobile;
+ }
+ return this.i18n('OncType' + OncMojo.getNetworkTypeString(type));
+ },
});
+})();
diff --git a/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html b/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html
index 2d9a2c92619..8e8b914c2e6 100644
--- a/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html
+++ b/chromium/chrome/browser/resources/settings/internet_page/tether_connection_dialog.html
@@ -1,11 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_icon.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../icons.html">
<link rel="import" href="../route.html">
<link rel="import" href="../settings_shared_css.html">
@@ -109,13 +109,13 @@
</ul>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onNotNowTap_">
+ <cr-button class="cancel-button" on-click="onNotNowTap_">
$i18n{tetherConnectionNotNowButton}
- </paper-button>
- <paper-button id="connectButton" class="action-button"
+ </cr-button>
+ <cr-button id="connectButton" class="action-button"
on-click="onConnectTap_" disabled="[[outOfRange]]">
$i18n{tetherConnectionConnectButton}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/BUILD.gn b/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/BUILD.gn
deleted file mode 100644
index bde7e39d052..00000000000
--- a/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/BUILD.gn
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copyright 2019 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import("//third_party/closure_compiler/compile_js.gni")
-
-js_type_check("closure_compile") {
- deps = [
- ":kiosk_next_shell_confirmation_dialog",
- ":kiosk_next_shell_page",
- ]
-}
-
-js_library("kiosk_next_shell_page") {
- deps = [
- "../prefs:prefs_behavior",
- "//ui/webui/resources/js:load_time_data",
- ]
-}
-
-js_library("kiosk_next_shell_confirmation_dialog") {
- deps = [
- "..:lifetime_browser_proxy",
- "../prefs:prefs_behavior",
- "//ui/webui/resources/js:load_time_data",
- ]
-}
diff --git a/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.html b/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.html
deleted file mode 100644
index 1d1d0624e38..00000000000
--- a/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.html
+++ /dev/null
@@ -1,34 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="../lifetime_browser_proxy.html">
-<link rel="import" href="../prefs/prefs_behavior.html">
-<link rel="import" href="../settings_shared_css.html">
-
-<dom-module id="settings-kiosk-next-shell-confirmation-dialog">
- <template>
- <style include="settings-shared"></style>
- <cr-dialog id="dialog" close-text="$i18n{close}" ignore-enter-key>
- <div slot="title">
- [[getTitleText_(prefs.ash.kiosk_next_shell.enabled.value)]]
- </div>
- <div slot="body">
- [[getBodyText_(prefs.ash.kiosk_next_shell.enabled.value)]]
- </div>
- <div slot="button-container">
- <paper-button class="cancel-button"
- on-click="onCancelClick_"
- id="cancel">
- $i18n{cancel}
- </paper-button>
- <paper-button class="action-button"
- id="confirm"
- on-click="onConfirmClick_">
- [[getConfirmationText_(prefs.ash.kiosk_next_shell.enabled.value)]]
- </paper-button>
- </div>
- </cr-dialog>
- </template>
- <script src="kiosk_next_shell_confirmation_dialog.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.js b/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.js
deleted file mode 100644
index c4dd7f154a9..00000000000
--- a/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.js
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-/**
- * @fileoverview
- * 'settings-kiosk-next-shell-confirmation-dialog' is a dialog shown to confirm
- * if a Kiosk Next Shell change is really wanted. Since enabling/disabling the
- * shell requires a sign out, we need to provide this dialog to avoid surprising
- * users.
- */
-
-/**
- * Histogram name for KioskNextShell enabled state.
- * @type {string}
- */
-const KIOSK_NEXT_SHELL_ENABLED_STATE_UMA_NAME = 'KioskNextShell.EnabledState';
-
-Polymer({
- is: 'settings-kiosk-next-shell-confirmation-dialog',
-
- behaviors: [PrefsBehavior],
-
- properties: {
- /** Preferences state. */
- prefs: {
- type: Object,
- notify: true,
- },
- },
-
- /** @override */
- attached: function() {
- this.$.dialog.showModal();
- },
-
- /**
- * @param {!Event} event
- * @private
- */
- onCancelClick_: function(event) {
- this.$.dialog.cancel();
- event.stopPropagation();
- },
-
- /**
- * @param {!Event} event
- * @private
- */
- onConfirmClick_: function(event) {
- const prefPath = 'ash.kiosk_next_shell.enabled';
- // Toggle previous enabled state.
- const isEnabled = !this.getPref(prefPath).value;
- chrome.send(
- 'metricsHandler:recordBooleanHistogram',
- [KIOSK_NEXT_SHELL_ENABLED_STATE_UMA_NAME, isEnabled]);
- this.setPrefValue(prefPath, isEnabled);
- settings.LifetimeBrowserProxyImpl.getInstance().signOutAndRestart();
- this.$.dialog.close();
- event.stopPropagation();
- },
-
- /**
- * @param {boolean} kioskNextShellEnabled
- * @return {string}
- * @private
- */
- getTitleText_: function(kioskNextShellEnabled) {
- return loadTimeData.getString(
- kioskNextShellEnabled ? 'kioskNextShellEnabledDialogTitle' :
- 'kioskNextShellDisabledDialogTitle');
- },
-
- /**
- * @param {boolean} kioskNextShellEnabled
- * @return {string}
- * @private
- */
- getBodyText_: function(kioskNextShellEnabled) {
- return loadTimeData.getString(
- kioskNextShellEnabled ? 'kioskNextShellEnabledDialogBody' :
- 'kioskNextShellDisabledDialogBody');
- },
-
- /**
- * @param {boolean} kioskNextShellEnabled
- * @return {string}
- * @private
- */
- getConfirmationText_: function(kioskNextShellEnabled) {
- return loadTimeData.getString(
- kioskNextShellEnabled ? 'kioskNextShellTurnOff' :
- 'kioskNextShellTurnOn');
- },
-});
diff --git a/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_page.html b/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_page.html
deleted file mode 100644
index db08f3a4b26..00000000000
--- a/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_page.html
+++ /dev/null
@@ -1,36 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="../i18n_setup.html">
-<link rel="import" href="../prefs/prefs_behavior.html">
-<link rel="import" href="../settings_shared_css.html">
-<link rel="import" href="kiosk_next_shell_confirmation_dialog.html">
-
-<dom-module id="settings-kiosk-next-shell-page">
- <template>
- <style include="settings-shared"></style>
- <template is="dom-if" if="[[showConfirmationDialog_]]" restamp>
- <settings-kiosk-next-shell-confirmation-dialog
- id="dialog"
- on-close="onConfirmationDialogClose_"
- prefs="{{prefs}}">
- </settings-kiosk-next-shell-confirmation-dialog>
- </template>
- <div id="kiosk-next-shell" class="settings-box two-line first">
- <div class="start">
- $i18n{kioskNextShellPageLabel}
- <div class="secondary" id="secondaryText">
- [[getSubtextLabel_(prefs.ash.kiosk_next_shell.enabled.value)]]
- </div>
- </div>
- <div class="separator"></div>
- <paper-button
- on-click="onToggleButtonClick_"
- aria-label="$i18n{kioskNextShellPageTitle}"
- aria-describedby="secondaryText">
- [[getButtonLabel_(prefs.ash.kiosk_next_shell.enabled.value)]]
- </paper-button>
- </div>
- </template>
- <script src="kiosk_next_shell_page.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_page.js b/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_page.js
deleted file mode 100644
index 4485674dcef..00000000000
--- a/chromium/chrome/browser/resources/settings/kiosk_next_shell_page/kiosk_next_shell_page.js
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-/**
- * @fileoverview
- * 'settings-kiosk-next-shell-page' is the settings page for enabling the
- * Kiosk Next Shell.
- */
-Polymer({
- is: 'settings-kiosk-next-shell-page',
-
- behaviors: [PrefsBehavior],
-
- properties: {
- /** Preferences state. */
- prefs: {
- type: Object,
- notify: true,
- },
-
- /** @private */
- showConfirmationDialog_: Boolean,
- },
-
- /**
- * @private
- * @param {!Event} event
- */
- onToggleButtonClick_: function(event) {
- this.showConfirmationDialog_ = true;
- event.stopPropagation();
- },
-
- /**
- * @private
- * @param {!Event} event
- */
- onConfirmationDialogClose_: function(event) {
- this.showConfirmationDialog_ = false;
- event.stopPropagation();
- },
-
- /**
- * @private
- * @param {boolean} kioskNextShellEnabled
- * @return {string}
- */
- getSubtextLabel_: function(kioskNextShellEnabled) {
- return loadTimeData.getString(
- kioskNextShellEnabled ? 'kioskNextShellPageSubtextDisable' :
- 'kioskNextShellPageSubtextEnable');
- },
-
- /**
- * @private
- * @param {boolean} kioskNextShellEnabled
- * @return {string}
- */
- getButtonLabel_: function(kioskNextShellEnabled) {
- return loadTimeData.getString(
- kioskNextShellEnabled ? 'kioskNextShellTurnOff' :
- 'kioskNextShellTurnOn');
- }
-});
diff --git a/chromium/chrome/browser/resources/settings/languages_page/BUILD.gn b/chromium/chrome/browser/resources/settings/languages_page/BUILD.gn
index 99a4c371aee..b0041ec678c 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/languages_page/BUILD.gn
@@ -78,7 +78,6 @@ js_library("languages_types") {
js_library("manage_input_methods_page") {
deps = [
- ":languages",
":languages_types",
"../prefs",
]
diff --git a/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.html b/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.html
index b8fb95c4c48..9611202ce04 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.html
+++ b/chromium/chrome/browser/resources/settings/languages_page/add_languages_dialog.html
@@ -1,27 +1,25 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_scrollable_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/cr_search_field/cr_search_field.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/find_shortcut_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="languages.html">
<link rel="import" href="../settings_shared_css.html">
<dom-module id="settings-add-languages-dialog">
<template>
<style include="settings-shared">
- cr-dialog {
- --cr-dialog-body: {
- padding-inline-end: 0;
- display: flex;
- flex-direction: column;
- height: 350px;
- overflow: auto;
- };
+ #dialog-body {
+ display: flex;
+ flex-direction: column;
+ height: 350px;
+ overflow: auto;
+ padding-inline-end: 0;
}
cr-search-field {
@@ -37,15 +35,13 @@
padding-inline-start: 20px;
}
- cr-checkbox {
- --cr-checkbox-label-container: {
- white-space: nowrap;
- };
+ cr-checkbox::part(label-container) {
+ white-space: nowrap;
}
</style>
<cr-dialog id="dialog" close-text="$i18n{close}">
<div slot="title">$i18n{addLanguagesDialogTitle}</div>
- <div slot="body" scrollable>
+ <div id="dialog-body" slot="body" scrollable>
<cr-search-field label="$i18n{searchLanguages}" id="search"
on-search-changed="onSearchChanged_"
on-keydown="onKeydown_" autofocus>
@@ -64,13 +60,13 @@
</iron-list>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelButtonTap_">
+ <cr-button class="cancel-button" on-click="onCancelButtonTap_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onActionButtonTap_"
+ </cr-button>
+ <cr-button class="action-button" on-click="onActionButtonTap_"
disabled="[[disableActionButton_]]">
$i18n{add}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.html b/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.html
index 9d01835b882..c3732a62e48 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.html
+++ b/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.html
@@ -1,11 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-a11y-keys/iron-a11y-keys.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../global_scroll_target_behavior.html">
<link rel="import" href="../prefs/prefs.html">
<link rel="import" href="../prefs/prefs_behavior.html">
@@ -25,6 +25,10 @@
--cr-input-width: var(--settings-input-max-width);
}
+ #newWord::part(row-container) {
+ justify-content: normal;
+ }
+
iron-list .word {
flex: 1;
}
@@ -34,16 +38,13 @@
on-keys-pressed="onKeysPress_"></iron-a11y-keys>
<cr-input id="newWord" value="{{newWordValue_}}"
placeholder="$i18n{addDictionaryWordLabel}"
- invalid="[[isWordInvalid_(newWordValue_)]]"
- error-message="[[isWordInvalid_(newWordValue_,
- '$i18nPolymer{addDictionaryWordDuplicateError}',
- '$i18nPolymer{addDictionaryWordLengthError}')]]"
+ invalid="[[isWordInvalid_(newWordValue_, words_.*)]]"
+ error-message="[[getErrorMessage_(newWordValue_, words_.*)]]"
spellcheck="false">
- <paper-button class="secondary-button" on-click="onAddWordTap_"
- disabled="[[disableAddButton_(newWordValue_)]]" id="addWord"
- slot="suffix">
+ <cr-button on-click="onAddWordTap_" id="addWord" slot="suffix"
+ disabled$="[[disableAddButton_(newWordValue_, words_.*)]]">
$i18n{addDictionaryWordButton}
- </paper-button>
+ </cr-button>
</cr-input>
</div>
<div class="settings-box continuation block">
diff --git a/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js b/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js
index 64176619be4..cb66b2e7b95 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js
+++ b/chromium/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js
@@ -18,7 +18,10 @@ Polymer({
properties: {
/** @private {string} */
- newWordValue_: String,
+ newWordValue_: {
+ type: String,
+ value: '',
+ },
/**
* Needed by GlobalScrollTargetBehavior.
@@ -66,33 +69,81 @@ Polymer({
},
/**
+ * Adds the word in the new-word input to the dictionary.
+ * @private
+ */
+ addWordFromInput_: function() {
+ // Spaces are allowed, but removing leading and trailing whitespace.
+ const word = this.getTrimmedNewWord_();
+ this.newWordValue_ = '';
+ if (word) {
+ this.languageSettingsPrivate.addSpellcheckWord(word);
+ }
+ },
+
+ /**
* Check if the field is empty or invalid.
- * @param {string} word
* @return {boolean}
* @private
*/
- disableAddButton_: function(word) {
- return word.trim().length == 0 || this.isWordInvalid_(word);
+ disableAddButton_: function() {
+ return this.getTrimmedNewWord_().length == 0 || this.isWordInvalid_();
+ },
+
+ /**
+ * @return {string}
+ * @private
+ */
+ getErrorMessage_: function() {
+ if (this.newWordIsTooLong_()) {
+ return loadTimeData.getString('addDictionaryWordLengthError');
+ }
+ if (this.newWordAlreadyAdded_()) {
+ return loadTimeData.getString('addDictionaryWordDuplicateError');
+ }
+ return '';
+ },
+
+ /**
+ * @return {string}
+ * @private
+ */
+ getTrimmedNewWord_: function() {
+ return this.newWordValue_.trim();
},
/**
* If the word is invalid, returns true (or a message if one is provided).
* Otherwise returns false.
- * @param {string} word
- * @param {string} duplicateError
- * @param {string} lengthError
- * @return {string|boolean}
+ * @return {boolean}
* @private
*/
- isWordInvalid_: function(word, duplicateError, lengthError) {
- const trimmedWord = word.trim();
- if (this.words_.indexOf(trimmedWord) != -1) {
- return duplicateError || true;
- } else if (trimmedWord.length > MAX_CUSTOM_DICTIONARY_WORD_BYTES) {
- return lengthError || true;
- }
+ isWordInvalid_: function() {
+ return this.newWordAlreadyAdded_() || this.newWordIsTooLong_();
+ },
- return false;
+ /**
+ * @return {boolean}
+ * @private
+ */
+ newWordAlreadyAdded_: function() {
+ return this.words_.includes(this.getTrimmedNewWord_());
+ },
+
+ /**
+ * @return {boolean}
+ * @private
+ */
+ newWordIsTooLong_: function() {
+ return this.getTrimmedNewWord_().length > MAX_CUSTOM_DICTIONARY_WORD_BYTES;
+ },
+
+ /**
+ * Handles tapping on the Add Word button.
+ */
+ onAddWordTap_: function(e) {
+ this.addWordFromInput_();
+ this.$.newWord.focus();
},
/**
@@ -120,7 +171,7 @@ Polymer({
}
for (const word of added) {
- if (this.words_.indexOf(word) == -1) {
+ if (!this.words_.includes(word)) {
this.unshift('words_', word);
}
}
@@ -134,12 +185,6 @@ Polymer({
Polymer.dom.flush();
this.$$('#list').notifyResize();
}
-
- // Update input enable to reflect new additions/removals.
- // TODO(hsuregan): Remove hack when notifyPath() or notifySplices()
- // is successful at creating DOM changes when applied to words_ (when
- // attached to input newWord), OR when array changes are registered.
- this.$.addWord.disabled = !this.$.newWord.validate();
},
/**
@@ -147,8 +192,7 @@ Polymer({
* @param {!CustomEvent<!{key: string}>} e
*/
onKeysPress_: function(e) {
- if (e.detail.key == 'enter' &&
- !this.disableAddButton_(this.newWordValue_)) {
+ if (e.detail.key == 'enter' && !this.disableAddButton_()) {
this.addWordFromInput_();
} else if (e.detail.key == 'esc') {
e.detail.keyboardEvent.target.value = '';
@@ -156,32 +200,10 @@ Polymer({
},
/**
- * Handles tapping on the Add Word button.
- */
- onAddWordTap_: function(e) {
- this.addWordFromInput_();
- this.$.newWord.focus();
- },
-
- /**
* Handles tapping on a "Remove word" icon button.
* @param {!{model: !{item: string}}} e
*/
onRemoveWordTap_: function(e) {
this.languageSettingsPrivate.removeSpellcheckWord(e.model.item);
},
-
- /**
- * Adds the word in the new-word input to the dictionary.
- */
- addWordFromInput_: function() {
- // Spaces are allowed, but removing leading and trailing whitespace.
- const word = this.newWordValue_.trim();
- this.newWordValue_ = '';
- if (!word) {
- return;
- }
-
- this.languageSettingsPrivate.addSpellcheckWord(word);
- },
});
diff --git a/chromium/chrome/browser/resources/settings/languages_page/languages_page.html b/chromium/chrome/browser/resources/settings/languages_page/languages_page.html
index 0cd54256af2..2cc7d7d74b3 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/languages_page.html
+++ b/chromium/chrome/browser/resources/settings/languages_page/languages_page.html
@@ -1,23 +1,24 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
+<link rel="import" href="chrome://resources/cr_elements/icons.html">
+<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
-<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
-<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="add_languages_dialog.html">
<link rel="import" href="languages.html">
<link rel="import" href="../controls/controlled_radio_button.html">
@@ -53,8 +54,10 @@
margin-top: 4px;
}
- :host-context([dark]) .explain-selected {
- color: var(--google-green-refresh-300);
+ @media (prefers-color-scheme: dark) {
+ .explain-selected {
+ color: var(--google-green-refresh-300);
+ }
}
cr-action-menu.complex .dropdown-item {
@@ -109,8 +112,10 @@
margin-top: 8px;
}
- :host-context([dark]) .name-with-error-list div {
- color: var(--settings-error-color);
+ @media (prefers-color-scheme: dark) {
+ .name-with-error-list div {
+ color: var(--settings-error-color);
+ }
}
iron-icon[icon='cr:error'] {
@@ -142,10 +147,9 @@
.spell-check-radio-button.enhanced {
align-items: start;
- --cr-radio-button-disc: {
- /* Align with just the first line of text */
- margin-top: calc((1.5em - var(--cr-radio-button-size)) / 2);
- }
+ /* Align with just the first line of text */
+ --cr-radio-button-disc-margin-block-start: calc(
+ (1.5em - var(--cr-radio-button-size)) / 2);
}
.enhanced-spellcheck-description {
@@ -167,10 +171,13 @@
display: none;
}
- .restart-button {
+ #restartButton {
margin-inline-start: var(--settings-controlled-by-spacing);
}
+ .external-wrapper {
+ display: flex;
+ }
</style>
<settings-languages languages="{{languages}}" prefs="{{prefs}}"
language-helper="{{languageHelper}}">
@@ -219,16 +226,17 @@
languages.prospectiveUILanguage)]]">
$i18n{isDisplayedInThisLanguage}
</div>
-</if>
+</if> <!-- chromeos or is_win -->
</div>
<if expr="chromeos or is_win">
<template is="dom-if" if="[[isRestartRequired_(
- item.language.code, languages.prospectiveUILanguage)]]">
- <paper-button class="restart-button" on-click="onRestartTap_">
+ item.language.code, languages.prospectiveUILanguage)]]"
+ restamp>
+ <cr-button id="restartButton" on-click="onRestartTap_">
$i18n{restart}
- </paper-button>
+ </cr-button>
</template>
-</if>
+</if> <!-- chromeos or is_win -->
<cr-icon-button class="icon-more-vert"
title="$i18n{moreActions}" id="more-[[item.language.code]]"
on-click="onDotsTap_"></cr-icon-button>
@@ -249,6 +257,7 @@
</iron-collapse>
<if expr="chromeos">
<cr-expand-button
+ hidden="[[!pageVisibility.inputMethodsList]]"
alt="$i18n{inputMethodsExpandA11yLabel}"
class="settings-box two-line"
expanded="{{inputMethodsOpened_}}"
@@ -259,6 +268,7 @@
</div>
</cr-expand-button>
<iron-collapse id="inputMethodsCollapse"
+ hidden="[[!pageVisibility.inputMethodsList]]"
opened="[[inputMethodsOpened_]]">
<div class="list-frame vertical-list">
<template is="dom-repeat"
@@ -275,9 +285,11 @@
$i18n{inputMethodEnabled}
</div>
</div>
- <cr-icon-button class="icon-external"
- hidden="[[!item.hasOptionsPage]]"
- on-click="onInputMethodOptionsTap_"></cr-icon-button>
+ <div class="external-wrapper" hidden="[[!item.hasOptionsPage]]">
+ <div class="separator"></div>
+ <cr-icon-button class="icon-external"
+ on-click="onInputMethodOptionsTap_"></cr-icon-button>
+ </div>
</div>
</template>
<cr-link-row class="hr list-item" id="manageInputMethods"
@@ -286,8 +298,7 @@
</div>
<settings-toggle-button
pref="{{prefs.settings.language.ime_menu_activated}}"
- label="$i18n{showImeMenu}"
- hidden$="[[prefs.ash.kiosk_next_shell.enabled.value]]">
+ label="$i18n{showImeMenu}">
</settings-toggle-button>
</iron-collapse>
</if>
@@ -350,11 +361,11 @@
$i18n{languagesDictionaryDownloadErrorHelp}
</div>
</div>
- <paper-button on-click="onRetryDictionaryDownloadClick_"
+ <cr-button on-click="onRetryDictionaryDownloadClick_"
hidden="[[!errorsGreaterThan_(
item.downloadDictionaryFailureCount, 0)]]">
$i18n{retry}
- </paper-button>
+ </cr-button>
<template is="dom-if" if="[[!item.isManaged]]">
<cr-toggle on-change="onSpellCheckLanguageChange_"
disabled="[[!item.language.supportsSpellcheck]]"
@@ -383,7 +394,8 @@
</div>
</div>
<cr-link-row on-click="onEditDictionaryTap_"
- id="spellCheckSubpageTrigger" label="$i18n{manageSpellCheck}">
+ id="spellCheckSubpageTrigger"
+ label="$i18n{manageSpellCheck}">
</cr-link-row>
</if> <!-- not is_macosx -->
</iron-collapse>
@@ -391,6 +403,9 @@
<cr-lazy-render id="menu">
<template>
<cr-action-menu
+<if expr="chromeos or is_win">
+ on-close="onCloseMenu_"
+</if>
class$="[[getMenuClass_(prefs.translate.enabled.value)]]">
<if expr="chromeos or is_win">
<cr-checkbox id="uiLanguageItem"
@@ -406,7 +421,7 @@
!detailLanguage_.language.isProhibitedLanguage]]">
</iron-icon>
</cr-checkbox>
-</if>
+</if> <!-- chromeos or is_win -->
<cr-checkbox id="offerTranslations"
class="dropdown-item"
checked="[[detailLanguage_.translateEnabled]]"
@@ -447,6 +462,7 @@
<if expr="chromeos">
<template is="dom-if" route-path="/inputMethods">
<settings-subpage
+ hidden="[[!pageVisibility.manageInputMethods]]"
associated-control="[[$$('#manageInputMethodsSubpageTrigger')]]"
page-title="$i18n{manageInputMethodsPageTitle}">
<settings-manage-input-methods-page languages="{{languages}}"
diff --git a/chromium/chrome/browser/resources/settings/languages_page/languages_page.js b/chromium/chrome/browser/resources/settings/languages_page/languages_page.js
index 19fd2d995a5..a69c59b8e0c 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/languages_page.js
+++ b/chromium/chrome/browser/resources/settings/languages_page/languages_page.js
@@ -111,6 +111,12 @@ Polymer({
return map;
},
},
+
+ /**
+ * Dictionary defining page visibility.
+ * @type {!LanguagesPageVisibility}
+ */
+ pageVisibility: Object,
},
// <if expr="not is_macosx">
@@ -119,7 +125,14 @@ Polymer({
'languages.forcedSpellCheckLanguages.*)',
'updateSpellcheckEnabled_(prefs.browser.enable_spellchecking.*)',
],
+ // </if>
+
+ // <if expr="chromeos or is_win">
+ /** @private {boolean} */
+ isChangeInProgress_: false,
+ // </if>
+ // <if expr="not is_macosx">
/**
* Checks if there are any errors downloading the spell check dictionary. This
* is used for showing/hiding error messages, spell check toggle and retry.
@@ -302,6 +315,37 @@ Polymer({
onInputMethodOptionsTap_: function(e) {
this.languageHelper.openInputMethodOptions(e.model.item.id);
},
+
+ /**
+ * @param {string} id The input method ID.
+ * @param {string} currentId The ID of the currently enabled input method.
+ * @return {boolean} True if the IDs match.
+ * @private
+ */
+ isCurrentInputMethod_: function(id, currentId) {
+ assert(cr.isChromeOS);
+ return id == currentId;
+ },
+
+ /**
+ * @param {string} id The input method ID.
+ * @param {string} currentId The ID of the currently enabled input method.
+ * @return {string} The class for the input method item.
+ * @private
+ */
+ getInputMethodItemClass_: function(id, currentId) {
+ assert(cr.isChromeOS);
+ return this.isCurrentInputMethod_(id, currentId) ? 'selected' : '';
+ },
+
+ getInputMethodName_: function(id) {
+ assert(cr.isChromeOS);
+ const inputMethod =
+ this.languages.inputMethods.enabled.find(function(inputMethod) {
+ return inputMethod.id == id;
+ });
+ return inputMethod ? inputMethod.displayName : '';
+ },
// </if>
// <if expr="chromeos or is_win">
@@ -325,6 +369,20 @@ Polymer({
this.languageHelper.requiresRestart();
},
+ /** @private */
+ onCloseMenu_() {
+ if (!this.isChangeInProgress_) {
+ return;
+ }
+ Polymer.dom.flush();
+ this.isChangeInProgress_ = false;
+ const restartButton = this.$$('#restartButton');
+ if (!restartButton) {
+ return;
+ }
+ cr.ui.focusWithoutInk(restartButton);
+ },
+
/**
* @param {!LanguageState} languageState
* @param {string} prospectiveUILanguage The chosen UI language.
@@ -372,11 +430,49 @@ Polymer({
// We don't support unchecking this checkbox. TODO(michaelpg): Ask for a
// simpler widget.
assert(e.target.checked);
+ this.isChangeInProgress_ = true;
this.languageHelper.setProspectiveUILanguage(
this.detailLanguage_.language.code);
+ this.languageHelper.moveLanguageToFront(this.detailLanguage_.language.code);
this.closeMenuSoon_();
},
+
+ /**
+ * Checks whether the prospective UI language (the pref that indicates what
+ * language to use in Chrome) matches the current language. This pref is used
+ * only on Chrome OS and Windows; we don't control the UI language elsewhere.
+ * @param {string} languageCode The language code identifying a language.
+ * @param {string} prospectiveUILanguage The prospective UI language.
+ * @return {boolean} True if the given language matches the prospective UI
+ * pref (which may be different from the actual UI language).
+ * @private
+ */
+ isProspectiveUILanguage_: function(languageCode, prospectiveUILanguage) {
+ return languageCode == prospectiveUILanguage;
+ },
+
+ /**
+ * @param {string} prospectiveUILanguage
+ * @return {string}
+ * @private
+ */
+ getProspectiveUILanguageName_: function(prospectiveUILanguage) {
+ return this.languageHelper.getLanguage(prospectiveUILanguage).displayName;
+ },
+
+ /**
+ * Handler for the restart button.
+ * @private
+ */
+ onRestartTap_: function() {
+ // <if expr="chromeos">
+ settings.LifetimeBrowserProxyImpl.getInstance().signOutAndRestart();
+ // </if>
+ // <if expr="is_win">
+ settings.LifetimeBrowserProxyImpl.getInstance().restart();
+ // </if>
+ },
// </if>
/**
@@ -466,31 +562,6 @@ Polymer({
this.languageHelper.disableLanguage(this.detailLanguage_.language.code);
},
- // <if expr="chromeos or is_win">
- /**
- * Checks whether the prospective UI language (the pref that indicates what
- * language to use in Chrome) matches the current language. This pref is used
- * only on Chrome OS and Windows; we don't control the UI language elsewhere.
- * @param {string} languageCode The language code identifying a language.
- * @param {string} prospectiveUILanguage The prospective UI language.
- * @return {boolean} True if the given language matches the prospective UI
- * pref (which may be different from the actual UI language).
- * @private
- */
- isProspectiveUILanguage_: function(languageCode, prospectiveUILanguage) {
- return languageCode == prospectiveUILanguage;
- },
-
- /**
- * @param {string} prospectiveUILanguage
- * @return {string}
- * @private
- */
- getProspectiveUILanguageName_: function(prospectiveUILanguage) {
- return this.languageHelper.getLanguage(prospectiveUILanguage).displayName;
- },
- // </if>
-
/**
* @return {string}
* @private
@@ -707,39 +778,6 @@ Polymer({
return undefined;
},
- // <if expr="chromeos">
- /**
- * @param {string} id The input method ID.
- * @param {string} currentId The ID of the currently enabled input method.
- * @return {boolean} True if the IDs match.
- * @private
- */
- isCurrentInputMethod_: function(id, currentId) {
- assert(cr.isChromeOS);
- return id == currentId;
- },
-
- /**
- * @param {string} id The input method ID.
- * @param {string} currentId The ID of the currently enabled input method.
- * @return {string} The class for the input method item.
- * @private
- */
- getInputMethodItemClass_: function(id, currentId) {
- assert(cr.isChromeOS);
- return this.isCurrentInputMethod_(id, currentId) ? 'selected' : '';
- },
-
- getInputMethodName_: function(id) {
- assert(cr.isChromeOS);
- const inputMethod =
- this.languages.inputMethods.enabled.find(function(inputMethod) {
- return inputMethod.id == id;
- });
- return inputMethod ? inputMethod.displayName : '';
- },
- // </if>
-
/**
* @param {!Event} e
* @private
@@ -790,21 +828,6 @@ Polymer({
}, settings.kMenuCloseDelay);
},
- // <if expr="chromeos or is_win">
- /**
- * Handler for the restart button.
- * @private
- */
- onRestartTap_: function() {
- // <if expr="chromeos">
- settings.LifetimeBrowserProxyImpl.getInstance().signOutAndRestart();
- // </if>
- // <if expr="is_win">
- settings.LifetimeBrowserProxyImpl.getInstance().restart();
- // </if>
- },
- // </if>
-
/**
* Toggles the expand button within the element being listened to.
* @param {!Event} e
diff --git a/chromium/chrome/browser/resources/settings/languages_page/manage_input_methods_page.html b/chromium/chrome/browser/resources/settings/languages_page/manage_input_methods_page.html
index 151858ba08d..96a23def8a8 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/manage_input_methods_page.html
+++ b/chromium/chrome/browser/resources/settings/languages_page/manage_input_methods_page.html
@@ -4,7 +4,6 @@
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="../settings_shared_css.html">
-<link rel="import" href="languages.html">
<dom-module id="settings-manage-input-methods-page">
<template>
diff --git a/chromium/chrome/browser/resources/settings/languages_page/manage_input_methods_page.js b/chromium/chrome/browser/resources/settings/languages_page/manage_input_methods_page.js
index 2cd14eff530..b2b717581f7 100644
--- a/chromium/chrome/browser/resources/settings/languages_page/manage_input_methods_page.js
+++ b/chromium/chrome/browser/resources/settings/languages_page/manage_input_methods_page.js
@@ -7,8 +7,7 @@
* and disabling input methods. Input methods are grouped by base languages to
* avoid showing duplicate or ambiguous input methods.
*
- * @group Chrome Settings Elements
- * @element settings-manage-input-methods-page
+ * TODO(hsuregan): Move to OS settings.
*/
Polymer({
is: 'settings-manage-input-methods-page',
diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/BUILD.gn b/chromium/chrome/browser/resources/settings/multidevice_page/BUILD.gn
index fb0695025d9..7818234969e 100644
--- a/chromium/chrome/browser/resources/settings/multidevice_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/multidevice_page/BUILD.gn
@@ -4,18 +4,25 @@
import("//third_party/closure_compiler/compile_js.gni")
+# Note: This file is not chromeos only because multidevice_browser_proxy is
+# required by site_settings:site_list.
+
js_type_check("closure_compile") {
deps = [
":multidevice_browser_proxy",
":multidevice_constants",
- ":multidevice_feature_behavior",
- ":multidevice_feature_item",
- ":multidevice_feature_toggle",
- ":multidevice_page",
- ":multidevice_smartlock_subpage",
- ":multidevice_subpage",
- ":multidevice_tether_item",
]
+ if (is_chromeos) {
+ deps += [
+ ":multidevice_feature_behavior",
+ ":multidevice_feature_item",
+ ":multidevice_feature_toggle",
+ ":multidevice_page",
+ ":multidevice_smartlock_subpage",
+ ":multidevice_subpage",
+ ":multidevice_tether_item",
+ ]
+ }
}
js_library("multidevice_browser_proxy") {
@@ -31,77 +38,81 @@ js_library("multidevice_constants") {
]
}
-js_library("multidevice_feature_behavior") {
- deps = [
- ":multidevice_constants",
- "//ui/webui/resources/js:cr",
- "//ui/webui/resources/js:i18n_behavior",
- ]
-}
+if (is_chromeos) {
+ js_library("multidevice_feature_behavior") {
+ deps = [
+ ":multidevice_constants",
+ "//ui/webui/resources/js:cr",
+ "//ui/webui/resources/js:i18n_behavior",
+ ]
+ }
-js_library("multidevice_feature_item") {
- deps = [
- ":multidevice_constants",
- ":multidevice_feature_behavior",
- "..:route",
- "//ui/webui/resources/js:cr",
- ]
-}
+ js_library("multidevice_feature_item") {
+ deps = [
+ ":multidevice_constants",
+ ":multidevice_feature_behavior",
+ "..:route",
+ "//ui/webui/resources/js:cr",
+ ]
+ }
-js_library("multidevice_feature_toggle") {
- deps = [
- ":multidevice_constants",
- ":multidevice_feature_behavior",
- ]
-}
+ js_library("multidevice_feature_toggle") {
+ deps = [
+ ":multidevice_constants",
+ ":multidevice_feature_behavior",
+ ]
+ }
-js_library("multidevice_page") {
- deps = [
- ":multidevice_browser_proxy",
- ":multidevice_constants",
- ":multidevice_feature_behavior",
- "..:route",
- "../controls:password_prompt_dialog",
- "//ui/webui/resources/js:cr",
- "//ui/webui/resources/js:web_ui_listener_behavior",
- ]
-}
+ js_library("multidevice_page") {
+ deps = [
+ ":multidevice_browser_proxy",
+ ":multidevice_constants",
+ ":multidevice_feature_behavior",
+ "..:route",
+ "../controls:password_prompt_dialog",
+ "//ui/webui/resources/js:cr",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
+ ]
+ }
-js_library("multidevice_radio_button") {
- deps = [
- "//third_party/polymer/v1_0/components-chromium/iron-a11y-keys-behavior:iron-a11y-keys-behavior-extracted",
- "//ui/webui/resources/cr_elements/cr_radio_button:cr_radio_button_behavior",
- "//ui/webui/resources/cr_elements/policy:cr_policy_indicator",
- ]
-}
+ js_library("multidevice_radio_button") {
+ deps = [
+ "//third_party/polymer/v1_0/components-chromium/iron-a11y-keys-behavior:iron-a11y-keys-behavior-extracted",
+ "//ui/webui/resources/cr_elements/cr_radio_button:cr_radio_button_behavior",
+ "//ui/webui/resources/cr_elements/policy:cr_policy_indicator",
+ ]
+ }
-js_library("multidevice_smartlock_subpage") {
- deps = [
- ":multidevice_constants",
- ":multidevice_feature_behavior",
- "../prefs:prefs_behavior",
- "//ui/webui/resources/cr_elements/cr_radio_button:cr_radio_button",
- "//ui/webui/resources/js:cr",
- ]
-}
+ js_library("multidevice_smartlock_subpage") {
+ deps = [
+ ":multidevice_constants",
+ ":multidevice_feature_behavior",
+ "../prefs:prefs_behavior",
+ "//ui/webui/resources/cr_elements/cr_radio_button:cr_radio_button",
+ "//ui/webui/resources/js:cr",
+ ]
+ }
-js_library("multidevice_subpage") {
- deps = [
- ":multidevice_constants",
- ":multidevice_feature_behavior",
- "..:route",
- "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior",
- ]
- externs_list = [ "$externs_path/networking_private.js" ]
- extra_sources = [ "$interfaces_path/networking_private_interface.js" ]
-}
+ js_library("multidevice_subpage") {
+ deps = [
+ ":multidevice_constants",
+ ":multidevice_feature_behavior",
+ "..:route",
+ "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior",
+ ]
+ externs_list = [ "$externs_path/networking_private.js" ]
+ extra_sources = [ "$interfaces_path/networking_private_interface.js" ]
+ }
-js_library("multidevice_tether_item") {
- deps = [
- ":multidevice_feature_behavior",
- "..:route",
- "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types",
- ]
- externs_list = [ "$externs_path/networking_private.js" ]
- extra_sources = [ "$interfaces_path/networking_private_interface.js" ]
+ js_library("multidevice_tether_item") {
+ deps = [
+ ":multidevice_feature_behavior",
+ "..:route",
+ "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior",
+ "//ui/webui/resources/cr_elements/chromeos/network:cr_onc_types",
+ "//ui/webui/resources/js/chromeos:onc_mojo",
+ ]
+ externs_list = [ "$externs_path/networking_private.js" ]
+ extra_sources = [ "$interfaces_path/networking_private_interface.js" ]
+ }
}
diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_item.html b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_item.html
index a31ccceba62..b4d69033c1e 100644
--- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_item.html
+++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_feature_item.html
@@ -27,30 +27,43 @@
cr-policy-indicator {
padding: 0 var(--cr-controlled-by-spacing);
}
+
+ .link-wrapper {
+ align-items: center;
+ display: flex;
+ flex-grow: 1;
+ }
</style>
- <div id="card"
- class="settings-box two-line"
- on-click="handleItemClick_"
- actionable$="[[hasSubpageClickHandler_(
- feature, pageContentData, subpageRoute)]]">
- <slot name="icon">
- <iron-icon icon="[[getIconName(feature)]]"></iron-icon>
- </slot>
- <div id="item-text-container" class="middle">
- <div id="featureName">[[getFeatureName(feature)]]</div>
- <div class="secondary"
- id="featureSecondary"
- inner-h-t-m-l="[[getFeatureSummaryHtml(feature)]]">
+ <div id="card" class="settings-box two-line">
+ <div class="link-wrapper" actionable
+ actionable$="[[hasSubpageClickHandler_(
+ feature, pageContentData, subpageRoute)]]"
+ on-click="handleItemClick_">
+ <slot name="icon">
+ <iron-icon icon="[[getIconName(feature)]]"></iron-icon>
+ </slot>
+ <div id="item-text-container" class="middle">
+ <div id="featureName">[[getFeatureName(feature)]]</div>
+ <div class="secondary"
+ id="featureSecondary"
+ inner-h-t-m-l="[[getFeatureSummaryHtml(feature)]]">
+ </div>
</div>
+ <template is="dom-if"
+ if="[[hasSubpageClickHandler_(
+ feature, pageContentData, subpageRoute)]]"
+ restamp>
+ <cr-icon-button class="subpage-arrow" aria-labelledby="featureName"
+ aria-describedby="featureSecondary"></cr-icon-button>
+ </template>
</div>
<template is="dom-if"
- if="[[hasSubpageClickHandler_(
+ if="[[hasSubpageClickHandler_(
feature, pageContentData, subpageRoute)]]"
- restamp>
- <cr-icon-button class="subpage-arrow" aria-labelledby="featureName"
- aria-describedby="featureSecondary"></cr-icon-button>
+ restamp>
<div class="separator"></div>
</template>
+
<template is="dom-if"
if="[[!isFeatureAllowedByPolicy(feature, pageContentData)]]"
restamp>
diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_page.html b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_page.html
index 5e59df3da66..f318ff45b63 100644
--- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_page.html
+++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_page.html
@@ -1,12 +1,12 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../icons.html">
<link rel="import" href="../route.html">
@@ -27,30 +27,46 @@
cr-policy-indicator {
padding: 0 var(--cr-controlled-by-spacing);
}
+
+ .link-wrapper {
+ align-items: center;
+ display: flex;
+ flex-grow: 1;
+ }
</style>
<settings-animated-pages id="pages" section="multidevice"
focus-config="[[focusConfig_]]">
<div route-path="default">
- <div id="multidevice-item"
- class="settings-box two-line"
- on-click="handleItemClick_"
- actionable$="[[doesClickOpenSubpage_(pageContentData)]]">
- <template is="dom-if" if="[[isHostSet(pageContentData)]]" restamp>
- <iron-icon icon=
- "[[getIconName(MultiDeviceFeature.BETTER_TOGETHER_SUITE)]]">
- </iron-icon>
- </template>
- <div class$=
- "[[getMultiDeviceItemLabelBlockCssClass_(pageContentData)]]
- settings-box-text">
- <div id="multidevice-label">[[getLabelText_(pageContentData)]]</div>
- <div id="multideviceSubLabel" class="secondary"
- inner-h-t-m-l="[[getSubLabelInnerHtml_(pageContentData)]]">
+ <div id="multidevice-item" class="settings-box two-line">
+ <div class="link-wrapper" actionable
+ actionable$="[[doesClickOpenSubpage_(pageContentData)]]"
+ on-click="handleItemClick_">
+ <template is="dom-if" if="[[isHostSet(pageContentData)]]" restamp>
+ <iron-icon icon=
+ "[[getIconName(MultiDeviceFeature.BETTER_TOGETHER_SUITE)]]">
+ </iron-icon>
+ </template>
+ <div class$=
+ "[[getMultiDeviceItemLabelBlockCssClass_(pageContentData)]]
+ settings-box-text">
+ <div id="multidevice-label">
+ [[getLabelText_(pageContentData)]]
+ </div>
+ <div id="multideviceSubLabel" class="secondary"
+ inner-h-t-m-l="[[getSubLabelInnerHtml_(pageContentData)]]">
+ </div>
</div>
+ <template is="dom-if"
+ if="[[doesClickOpenSubpage_(pageContentData)]]"
+ restamp>
+ <cr-icon-button class="subpage-arrow"
+ aria-labelledby="multidevice-label"
+ aria-describedby="multideviceSubLabel"></cr-icon-button>
+ </template>
</div>
<template is="dom-if"
- if="[[!isSuiteAllowedByPolicy(pageContentData)]]"
- restamp>
+ if="[[!isSuiteAllowedByPolicy(pageContentData)]]"
+ restamp>
<cr-policy-indicator indicator-type="userPolicy">
</cr-policy-indicator>
<settings-multidevice-feature-toggle
@@ -61,22 +77,14 @@
<template is="dom-if"
if="[[shouldShowSeparatorAndSubpageArrow_(pageContentData)]]"
restamp>
- <template is="dom-if"
- if="[[doesClickOpenSubpage_(pageContentData)]]"
- restamp>
- <cr-icon-button class="subpage-arrow"
- aria-labelledby="multidevice-label"
- aria-describedby="multideviceSubLabel"></cr-icon-button>
- </template>
<div class="separator"></div>
</template>
<template is="dom-if"
if="[[shouldShowButton_(pageContentData)]]"
restamp>
- <paper-button class="secondary-button"
- on-click="handleButtonClick_">
+ <cr-button on-click="handleButtonClick_">
[[getButtonText_(pageContentData)]]
- </paper-button>
+ </cr-button>
</template>
<template is="dom-if"
if="[[shouldShowToggle_(pageContentData)]]"
diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_radio_button.html b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_radio_button.html
index 44a0ea66727..c1f52cdc294 100644
--- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_radio_button.html
+++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_radio_button.html
@@ -30,7 +30,15 @@
}
</style>
- <div class="disc-wrapper">
+ <div
+ aria-checked$="[[getAriaChecked_(checked)]]"
+ aria-disabled$="[[getAriaDisabled_(disabled)]]"
+ aria-labelledby="labelWrapper"
+ class="disc-wrapper"
+ id="button"
+ role="radio"
+ tabindex="0"
+ on-keydown="onInputKeydown_">
<div class="disc-border"></div>
<div class="disc"></div>
</div>
diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_smartlock_subpage.html b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_smartlock_subpage.html
index 382c8b11075..8a150439064 100644
--- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_smartlock_subpage.html
+++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_smartlock_subpage.html
@@ -30,16 +30,16 @@
page-content-data="[[pageContentData]]">
</settings-multidevice-feature-toggle>
</div>
- <div class="settings-box first line-only">
- <h2 class="start first">
- $i18n{multideviceSmartLockOptions}
- </h2>
- </div>
<iron-collapse opened="[[smartLockEnabled_]]">
+ <div class="settings-box first line-only">
+ <h2 class="start first">
+ $i18n{multideviceSmartLockOptions}
+ </h2>
+ </div>
<div class="list-frame">
<cr-radio-group
selected="[[smartLockSignInEnabled_]]"
- selectable="multidevice-radio-button"
+ selectable-elements="multidevice-radio-button"
disabled="[[!smartLockSignInAllowed_]]"
on-selected-changed="onSmartLockSignInEnabledChanged_">
<multidevice-radio-button
diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_subpage.html b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_subpage.html
index e621471c502..2e75dd98bd0 100644
--- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_subpage.html
+++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_subpage.html
@@ -1,11 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../route.html">
<link rel="import" href="../settings_shared_css.html">
@@ -44,9 +44,9 @@
</div>
<template is="dom-if" if="[[shouldShowVerifyButton_(pageContentData)]]"
restamp>
- <paper-button on-click="handleVerifyButtonClick_">
+ <cr-button on-click="handleVerifyButtonClick_">
$i18n{multideviceVerifyButton}
- </paper-button>
+ </cr-button>
</template>
<template is="dom-if" if="[[shouldShowSuiteToggle_(pageContentData)]]"
restamp>
@@ -88,12 +88,12 @@
<template is="dom-if"
if="[[doesAndroidMessagesRequireSetUp_(pageContentData)]]"
restamp>
- <paper-button disabled$="[[isAndroidMessagesSetupButtonDisabled_(
+ <cr-button disabled$="[[isAndroidMessagesSetupButtonDisabled_(
pageContentData)]]"
on-click="handleAndroidMessagesButtonClick_"
slot="feature-controller">
$i18n{multideviceSetupButton}
- </paper-button>
+ </cr-button>
</template>
</settings-multidevice-feature-item>
</template>
@@ -113,15 +113,15 @@
</div>
</div>
<div slot="button-container">
- <paper-button class="cancel-button"
+ <cr-button class="cancel-button"
on-click="onForgetDeviceDialogCancelClick_">
$i18n{cancel}
- </paper-button>
- <paper-button id="confirmButton"
+ </cr-button>
+ <cr-button id="confirmButton"
class="action-button"
on-click="onForgetDeviceDialogConfirmClick_">
$i18n{confirm}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_subpage.js b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_subpage.js
index 08bc3dfbf10..cb8f1dc6368 100644
--- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_subpage.js
+++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_subpage.js
@@ -12,10 +12,7 @@ cr.exportPath('settings');
Polymer({
is: 'settings-multidevice-subpage',
- behaviors: [
- MultiDeviceFeatureBehavior,
- CrNetworkListenerBehavior,
- ],
+ behaviors: [MultiDeviceFeatureBehavior],
properties: {
/**
@@ -26,24 +23,6 @@ Polymer({
type: Object,
value: settings.routes,
},
-
- /** Overridden from NetworkListenerBehavior. */
- networkingPrivate: {
- type: Object,
- value: chrome.networkingPrivate,
- },
-
- /** Overridden from NetworkListenerBehavior. */
- networkListChangeSubscriberSelectors_: {
- type: Array,
- value: () => ['settings-multidevice-tether-item'],
- },
-
- /** Overridden from NetworkListenerBehavior. */
- networksChangeSubscriberSelectors_: {
- type: Array,
- value: () => ['settings-multidevice-tether-item'],
- },
},
/** @private {?settings.MultiDeviceBrowserProxy} */
@@ -129,10 +108,8 @@ Polymer({
* @private
*/
doesAndroidMessagesRequireSetUp_: function() {
- // The pairing state is preferred over the FeatureState here since
- // FeatureState.UNAVAILABLE_SUITE_DISABLED is returned when the suite is
- // disabled, regardless if Messages requires further setup.
- return !this.pageContentData.isAndroidSmsPairingComplete;
+ return this.getFeatureState(settings.MultiDeviceFeature.MESSAGES) ===
+ settings.MultiDeviceFeatureState.FURTHER_SETUP_REQUIRED;
},
/**
@@ -140,9 +117,10 @@ Polymer({
* @private
*/
isAndroidMessagesSetupButtonDisabled_: function() {
- const messagesFeatureState = this.getFeatureState(
- settings.MultiDeviceFeature.MESSAGES);
- return !this.isSuiteOn() || messagesFeatureState ===
+ const messagesFeatureState =
+ this.getFeatureState(settings.MultiDeviceFeature.MESSAGES);
+ return !this.isSuiteOn() ||
+ messagesFeatureState ===
settings.MultiDeviceFeatureState.PROHIBITED_BY_POLICY;
}
});
diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.html b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.html
index 42431eb5826..326a4c50e00 100644
--- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.html
+++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.html
@@ -2,6 +2,8 @@
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_onc_types.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_icon.html">
+<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html">
+<link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../route.html">
<link rel="import" href="../settings_shared_css.html">
diff --git a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.js b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.js
index a5c84407384..8dc4cf217eb 100644
--- a/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.js
+++ b/chromium/chrome/browser/resources/settings/multidevice_page/multidevice_tether_item.js
@@ -7,28 +7,22 @@
* This element provides a layer between the settings-multidevice-subpage
* element and the internet_page folder's network-summary-item. It is
* responsible for loading initial tethering network data from the
- * chrome.networkingPrivate API as well as updating the data in real time. It
+ * networkConfig mojo API as well as updating the data in real time. It
* serves a role comparable to the internet_page's network-summary element.
*/
Polymer({
is: 'settings-multidevice-tether-item',
- behaviors: [MultiDeviceFeatureBehavior],
+ behaviors: [
+ CrNetworkListenerBehavior,
+ MultiDeviceFeatureBehavior,
+ ],
properties: {
/**
- * Interface for networkingPrivate calls.
- * @private {!NetworkingPrivate}
- */
- networkingPrivate_: {
- type: Object,
- value: chrome.networkingPrivate,
- },
-
- /**
* The device state for tethering.
- * @private {?CrOnc.DeviceStateProperties|undefined}
+ * @private {?OncMojo.DeviceStateProperties|undefined}
*/
deviceState_: Object,
@@ -36,7 +30,7 @@ Polymer({
* The network state for a potential tethering host phone. Note that there
* is at most one because only one MultiDevice host phone is allowed on an
* account at a given time.
- * @private {?CrOnc.NetworkStateProperties|undefined}
+ * @private {?OncMojo.NetworkStateProperties|undefined}
*/
activeNetworkState_: Object,
@@ -62,114 +56,109 @@ Polymer({
},
},
- listeners: {
- 'network-list-changed': 'updateTetherNetworkState_',
- // network-changed is fired by the settings-multidevice-subpage element's
- // CrNetworkListenerBehavior.
- // TODO (jordynass): Refactor to allow this element to listen to network
- // changes without requiring the settings-multidevice-subpage to communicate
- // with the networkingPrivate API.
- 'networks-changed': 'onNetworksChanged_',
- },
+ /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} */
+ networkConfigProxy_: null,
- /**
- * Listener function for chrome.networkingPrivate.onDeviceStateListChanged
- * event.
- * @private {?function(!Array<string>)}
- */
- deviceStateListChangedListener_: null,
+ /** @override */
+ created: function() {
+ this.networkConfigProxy_ =
+ network_config.MojoInterfaceProviderImpl.getInstance()
+ .getMojoServiceProxy();
+ },
/** @override */
attached: function() {
this.updateTetherDeviceState_();
this.updateTetherNetworkState_();
-
- this.deviceStateListChangedListener_ =
- this.deviceStateListChangedListener_ ||
- this.updateTetherDeviceState_.bind(this);
- this.networkingPrivate_.onDeviceStateListChanged.addListener(
- this.deviceStateListChangedListener_);
- },
-
- /** @override */
- detached: function() {
- this.networkingPrivate_.onDeviceStateListChanged.removeListener(
- assert(this.deviceStateListChangedListener_));
},
/**
- * Callback for the a network changing state. Note that any change to leading
- * to a new active network would fire the 'network-list-changed' event,
- * triggering updateTetherNetworkState_ and rendering this callback
- * redundant. As a result, we return early if the active network is not
- * changed.
- * @param {!CustomEvent<!Array<string>>} event stores an array of the GUIDs of
- * all networks that changed in its detail property.
+ * CrosNetworkConfigObserver impl
+ * Note that any change to leading to a new active network will also trigger
+ * onNetworkStateListChanged, triggering updateTetherNetworkState_ and
+ * rendering this callback redundant. As a result, we return early if the
+ * active network is not changed.
+ * @param {!Array<chromeos.networkConfig.mojom.NetworkStateProperties>}
+ * networks
* @private
*/
- onNetworksChanged_: function(event) {
- const id = this.activeNetworkState_.GUID;
- if (!event.detail.includes(id)) {
+ onActiveNetworksChanged: function(networks) {
+ const guid = this.activeNetworkState_.guid;
+ if (!networks.find(network => network.guid == guid)) {
return;
}
- this.networkingPrivate_.getState(id, newNetworkState => {
- if (chrome.runtime.lastError) {
- const message = chrome.runtime.lastError.message;
- if (message != 'Error.NetworkUnavailable' &&
- message != 'Error.InvalidNetworkGuid') {
- console.error(
- 'Unexpected networkingPrivate.getState error: ' + message +
- ' For: ' + id);
- return;
- }
+ this.networkConfigProxy_.getNetworkState(guid).then(response => {
+ if (response.result) {
+ this.activeNetworkState_ = response.result;
}
- this.activeNetworkState_ = newNetworkState;
});
},
+ /** CrosNetworkConfigObserver impl */
+ onNetworkStateListChanged: function() {
+ this.updateTetherNetworkState_();
+ },
+
+ /** CrosNetworkConfigObserver impl */
+ onDeviceStateListChanged: function() {
+ this.updateTetherDeviceState_();
+ },
+
/**
- * Retrieves device states (CrOnc.DeviceStateProperties) and sets
- * this.deviceState_ to the retrieved Instant Tethering state (or undefined if
- * there is none) in its callback. Note that the function
- * chrome.networkingPrivate.getDevicePolicy() retrieves at most one object per
- * network type (CrOnc.Type) so, in particular there will be at most one state
- * for Instant Tethering.
+ * Retrieves device states (OncMojo.DeviceStateProperties) and sets
+ * this.deviceState_ to the retrieved Tether device state (or undefined if
+ * there is none). Note that crosNetworkConfig.getDeviceStateList retrieves at
+ * most one device per NetworkType so there will be at most one Tether device
+ * state.
* @private
*/
updateTetherDeviceState_: function() {
- this.networkingPrivate_.getDeviceStates(deviceStates => {
- this.deviceState_ =
- deviceStates.find(
- deviceState => deviceState.Type == CrOnc.Type.TETHER) ||
- {Type: CrOnc.Type.TETHER, State: CrOnc.DeviceState.DISABLED};
+ this.networkConfigProxy_.getDeviceStateList().then(response => {
+ const kTether = chromeos.networkConfig.mojom.NetworkType.kTether;
+ const deviceStates = response.result;
+ const deviceState =
+ deviceStates.find(deviceState => deviceState.type == kTether);
+ this.deviceState_ = deviceState || {
+ deviceState: chromeos.networkConfig.mojom.DeviceStateType.kDisabled,
+ managedNetworkAvailable: false,
+ scanning: false,
+ simAbsent: false,
+ type: kTether,
+ };
});
},
/**
* Retrieves all Instant Tethering network states
- * (CrOnc.NetworkStateProperties). Note that there is at most one because
+ * (OncMojo.NetworkStateProperties). Note that there is at most one because
* only one host is allowed on an account at a given time. Then it sets
* this.activeNetworkState_ to that network if there is one or a dummy object
* with an empty string for a GUID otherwise.
* @private
*/
updateTetherNetworkState_: function() {
- this.networkingPrivate_.getNetworks(
- {networkType: CrOnc.Type.TETHER}, networkStates => {
- this.activeNetworkState_ =
- networkStates[0] || {GUID: '', Type: CrOnc.Type.TETHER};
- });
+ const kTether = chromeos.networkConfig.mojom.NetworkType.kTether;
+ const filter = {
+ filter: chromeos.networkConfig.mojom.FilterType.kVisible,
+ limit: 1,
+ networkType: kTether,
+ };
+ this.networkConfigProxy_.getNetworkStateList(filter).then(response => {
+ const networks = response.result;
+ this.activeNetworkState_ =
+ networks[0] || OncMojo.getDefaultNetworkState(kTether);
+ });
},
/**
* Returns an array containing the active network state if there is one
* (note that if there is not GUID will be falsy). Returns an empty array
* otherwise.
- * @return {!Array<CrOnc.NetworkStateProperties>}
+ * @return {!Array<chromeos.networkConfig.mojom.NetworkStateProperties>}
* @private
*/
getNetworkStateList_: function() {
- return this.activeNetworkState_.GUID ? [this.activeNetworkState_] : [];
+ return this.activeNetworkState_.guid ? [this.activeNetworkState_] : [];
},
/**
diff --git a/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.html b/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.html
index f4bdec1ade6..1d7e8883129 100644
--- a/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.html
+++ b/chromium/chrome/browser/resources/settings/on_startup_page/on_startup_page.html
@@ -17,7 +17,8 @@
</style>
<div class="settings-box block first">
<settings-radio-group id="onStartupRadioGroup"
- pref="{{prefs.session.restore_on_startup}}">
+ pref="{{prefs.session.restore_on_startup}}"
+ group-aria-label="$i18n{onStartup}">
<controlled-radio-button name="[[prefValues_.OPEN_NEW_TAB]]"
pref="[[prefs.session.restore_on_startup]]"
label="$i18n{onStartupOpenNewTab}"
diff --git a/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.html b/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.html
index 206a93fff34..e6583006957 100644
--- a/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.html
+++ b/chromium/chrome/browser/resources/settings/on_startup_page/startup_url_dialog.html
@@ -1,8 +1,8 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="startup_urls_page_browser_proxy.html">
@@ -21,10 +21,10 @@
</cr-input>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelTap_"
- id="cancel">$i18n{cancel}</paper-button>
- <paper-button id="actionButton" class="action-button"
- on-click="onActionButtonTap_">[[actionButtonText_]]</paper-button>
+ <cr-button class="cancel-button" on-click="onCancelTap_"
+ id="cancel">$i18n{cancel}</cr-button>
+ <cr-button id="actionButton" class="action-button"
+ on-click="onActionButtonTap_">[[actionButtonText_]]</cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html b/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html
index 040d1e8bb74..cb74a00ae97 100644
--- a/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html
+++ b/chromium/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html
@@ -1,7 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
diff --git a/chromium/chrome/browser/resources/settings/os_settings_manifest.json b/chromium/chrome/browser/resources/settings/os_settings_manifest.json
new file mode 100644
index 00000000000..b5aa51b98e5
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/os_settings_manifest.json
@@ -0,0 +1,13 @@
+{
+ "name": "Settings",
+ "display": "standalone",
+ "icons": [
+ {
+ "src": "icon-192.png",
+ "sizes": "192x192",
+ "type": "image/png"
+ }
+ ],
+ "start_url": "/",
+ "theme_color": "#fff"
+}
diff --git a/chromium/chrome/browser/resources/settings/os_settings_resources.grd b/chromium/chrome/browser/resources/settings/os_settings_resources.grd
index 052920bce32..8ad9dd094f8 100644
--- a/chromium/chrome/browser/resources/settings/os_settings_resources.grd
+++ b/chromium/chrome/browser/resources/settings/os_settings_resources.grd
@@ -14,12 +14,10 @@
<structures>
<structure name="IDR_OS_SETTINGS_A11Y_PAGE_JS"
file="chromeos/os_a11y_page/os_a11y_page.js"
- preprocess="true"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_A11Y_PAGE_HTML"
file="chromeos/os_a11y_page/os_a11y_page.html"
type="chrome_html"
- preprocess="true"
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_MANAGE_A11Y_PAGE_JS"
file="a11y_page/manage_a11y_page.js"
@@ -27,6 +25,12 @@
<structure name="IDR_OS_SETTINGS_MANAGE_A11Y_PAGE_HTML"
file="a11y_page/manage_a11y_page.html"
type="chrome_html" />
+ <structure name="IDS_OS_SETTINGS_SWITCH_ACCESS_SUBPAGE_JS"
+ file="a11y_page/switch_access_subpage.js"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_SWITCH_ACCESS_SUBPAGE_HTML"
+ file="a11y_page/switch_access_subpage.html"
+ type="chrome_html" />
<structure name="IDR_OS_SETTINGS_TTS_SUBPAGE_JS"
file="a11y_page/tts_subpage.js"
type="chrome_html" />
@@ -34,7 +38,41 @@
file="a11y_page/tts_subpage.html"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_MANIFEST"
- file="manifest.json"
+ file="os_settings_manifest.json"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_ABOUT_PAGE_BROWSER_PROXY_HTML"
+ file="about_page/about_page_browser_proxy.html"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_ABOUT_PAGE_BROWSER_PROXY_JS"
+ file="about_page/about_page_browser_proxy.js"
+ type="chrome_html"
+ preprocess="true" />
+ <structure name="IDR_OS_SETTINGS_ABOUT_PAGE_JS"
+ file="chromeos/os_about_page/os_about_page.js"
+ type="chrome_html"
+ preprocess="true" />
+ <structure name="IDR_OS_SETTINGS_ABOUT_PAGE_HTML"
+ file="chromeos/os_about_page/os_about_page.html"
+ type="chrome_html"
+ preprocess="true"
+ allowexternalscript="true" />
+ <structure name="IDR_OS_SETTINGS_CHANNEL_SWITCHER_DIALOG_HTML"
+ file="about_page/channel_switcher_dialog.html"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_CHANNEL_SWITCHER_DIALOG_JS"
+ file="about_page/channel_switcher_dialog.js"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_DETAILED_BUILD_INFO_JS"
+ file="about_page/detailed_build_info.js"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_DETAILED_BUILD_INFO_HTML"
+ file="about_page/detailed_build_info.html"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_UPDATE_WARNING_DIALOG_HTML"
+ file="about_page/update_warning_dialog.html"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_UPDATE_WARNING_DIALOG_JS"
+ file="about_page/update_warning_dialog.js"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_ADD_SITE_DIALOG_HTML"
file="site_settings/add_site_dialog.html"
@@ -92,25 +130,20 @@
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_PERSONALIZATION_BROWSER_PROXY_JS"
file="chromeos/personalization_page/personalization_browser_proxy.js"
- type="chrome_html"
- preprocess="true" />
+ type="chrome_html" />
<structure name="IDR_OS_SETTINGS_PERSONALIZATION_PAGE_HTML"
file="chromeos/personalization_page/personalization_page.html"
type="chrome_html"
- preprocess="true"
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_PERSONALIZATION_PAGE_JS"
file="chromeos/personalization_page/personalization_page.js"
- type="chrome_html"
- preprocess="true" />
+ type="chrome_html" />
<structure name="IDR_OS_SETTINGS_OS_SETTINGS_PAGE_JS"
file="chromeos/os_settings_page/os_settings_page.js"
- preprocess="true"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_OS_SETTINGS_PAGE_HTML"
file="chromeos/os_settings_page/os_settings_page.html"
type="chrome_html"
- preprocess="true"
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_EDIT_EXCEPTION_DIALOG_HTML"
file="site_settings/edit_exception_dialog.html"
@@ -137,7 +170,6 @@
<structure name="IDR_OS_SETTINGS_CR_OS_SETTINGS_MAIN_HTML"
file="chromeos/os_settings_main/os_settings_main.html"
type="chrome_html"
- preprocess="true"
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_CR_OS_SETTINGS_MAIN_JS"
file="chromeos/os_settings_main/os_settings_main.js"
@@ -145,7 +177,6 @@
<structure name="IDR_OS_SETTINGS_CR_OS_SETTINGS_MENU_HTML"
file="chromeos/os_settings_menu/os_settings_menu.html"
type="chrome_html"
- preprocess="true"
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_CR_OS_SETTINGS_MENU_JS"
file="chromeos/os_settings_menu/os_settings_menu.js"
@@ -174,7 +205,8 @@
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_MAIN_PAGE_BEHAVIOR_JS"
file="settings_page/main_page_behavior.js"
- type="chrome_html" />
+ type="chrome_html"
+ preprocess="true" />
<structure name="IDR_OS_SETTINGS_SETTINGS_VARS_CSS_HTML"
file="settings_vars_css.html"
type="chrome_html" />
@@ -185,12 +217,10 @@
<structure name="IDR_OS_SETTINGS_CR_OS_SETTINGS_UI_HTML"
file="chromeos/os_settings_ui/os_settings_ui.html"
type="chrome_html"
- preprocess="true"
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_CR_OS_SETTINGS_UI_JS"
file="chromeos/os_settings_ui/os_settings_ui.js"
- type="chrome_html"
- preprocess="true" />
+ type="chrome_html" />
<structure name="IDR_OS_SETTINGS_GLOBAL_SCROLL_TARGET_BEHAVIOR_HTML"
file="global_scroll_target_behavior.html"
type="chrome_html" />
@@ -406,20 +436,18 @@
<structure name="IDR_OS_SETTINGS_DEVICE_NIGHT_LIGHT_SLIDER_JS"
file="device_page/night_light_slider.js"
type="chrome_html" />
- <structure name="IDR_OS_SETTINGS_DOWNLOADS_PAGE_HTML"
- file="chromeos/os_downloads_page/os_downloads_page.html"
+ <structure name="IDR_OS_SETTINGS_FILES_PAGE_HTML"
+ file="chromeos/os_files_page/os_files_page.html"
type="chrome_html"
- preprocess="true"
allowexternalscript="true" />
- <structure name="IDR_OS_SETTINGS_DOWNLOADS_PAGE_JS"
- file="chromeos/os_downloads_page/os_downloads_page.js"
- type="chrome_html"
- preprocess="true" />
+ <structure name="IDR_OS_SETTINGS_FILES_PAGE_JS"
+ file="chromeos/os_files_page/os_files_page.js"
+ type="chrome_html" />
<structure name="IDR_OS_SETTINGS_SMB_SHARES_PAGE_HTML"
- file="chromeos/os_downloads_page/smb_shares_page.html"
+ file="chromeos/os_files_page/smb_shares_page.html"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_SMB_SHARES_PAGE_JS"
- file="chromeos/os_downloads_page/smb_shares_page.js"
+ file="chromeos/os_files_page/smb_shares_page.js"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_I18n_SETUP_HTML"
file="i18n_setup.html"
@@ -436,8 +464,7 @@
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_RESET_PAGE_HTML"
file="chromeos/os_reset_page/os_reset_page.html"
- type="chrome_html"
- preprocess="true" />
+ type="chrome_html" />
<structure name="IDR_OS_SETTINGS_RESET_PAGE_JS"
file="chromeos/os_reset_page/os_reset_page.js"
type="chrome_html" />
@@ -463,20 +490,26 @@
preprocess="true"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_LANGUAGES_ADD_LANGUAGES_DIALOG_HTML"
- file="languages_page/add_languages_dialog.html"
+ file="chromeos/os_languages_page/os_add_languages_dialog.html"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_LANGUAGES_ADD_LANGUAGES_DIALOG_JS"
- file="languages_page/add_languages_dialog.js"
+ file="chromeos/os_languages_page/os_add_languages_dialog.js"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_LANGUAGES_PAGE_HTML"
- file="languages_page/languages_page.html"
+ file="chromeos/os_languages_page/os_languages_page.html"
type="chrome_html"
- preprocess="true"
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_LANGUAGES_PAGE_JS"
- file="languages_page/languages_page.js"
+ file="chromeos/os_languages_page/os_languages_page.js"
+ type="chrome_html"
+ allowexternalscript="true" />
+ <structure name="IDR_OS_SETTINGS_LANGUAGES_SECTION_HTML"
+ file="chromeos/os_languages_page/os_languages_section.html"
+ type="chrome_html"
+ allowexternalscript="true" />
+ <structure name="IDR_OS_SETTINGS_LANGUAGES_SECTION_JS"
+ file="chromeos/os_languages_page/os_languages_section.js"
type="chrome_html"
- preprocess="true"
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_LANGUAGES_MANAGE_INPUT_METHODS_PAGE_HTML"
file="languages_page/manage_input_methods_page.html"
@@ -484,12 +517,6 @@
<structure name="IDR_OS_SETTINGS_LANGUAGES_MANAGE_INPUT_METHODS_PAGE_JS"
file="languages_page/manage_input_methods_page.js"
type="chrome_html" />
- <structure name="IDR_OS_SETTINGS_LANGUAGES_EDIT_DICTIONARY_PAGE_HTML"
- file="languages_page/edit_dictionary_page.html"
- type="chrome_html" />
- <structure name="IDR_OS_SETTINGS_LANGUAGES_EDIT_DICTIONARY_PAGE_JS"
- file="languages_page/edit_dictionary_page.js"
- type="chrome_html" />
<structure name="IDR_OS_SETTINGS_MEDIA_PICKER_HTML"
file="site_settings/media_picker.html"
type="chrome_html" />
@@ -504,7 +531,6 @@
<structure name="IDR_OS_SETTINGS_PEOPLE_PAGE_JS"
file="chromeos/os_people_page/os_people_page.js"
type="chrome_html"
- preprocess="true"
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_PEOPLE_PAGE_SIGNOUT_DIALOG_HTML"
file="people_page/signout_dialog.html"
@@ -553,13 +579,17 @@
file="prefs/prefs_types.js"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_PRINTING_PAGE_HTML"
- file="printing_page/printing_page.html"
- preprocess="true"
+ file="chromeos/os_printing_page/os_printing_page.html"
allowexternalscript="true"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_PRINTING_PAGE_JS"
- file="printing_page/printing_page.js"
- preprocess="true"
+ file="chromeos/os_printing_page/os_printing_page.js"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_CUPS_PRINTER_TYPES_HTML"
+ file="printing_page/cups_printer_types.html"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_CUPS_PRINTER_TYPES_JS"
+ file="printing_page/cups_printer_types.js"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_CUPS_PRINTER_SHARED_CSS_HTML"
file="printing_page/cups_printer_shared_css.html"
@@ -576,6 +606,18 @@
<structure name="IDR_OS_SETTINGS_CUPS_PRINTERS_BROWSER_PROXY_JS"
file="printing_page/cups_printers_browser_proxy.js"
type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_CUPS_PRINTERS_ENTRY_HTML"
+ file="printing_page/cups_printers_entry.html"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_CUPS_PRINTERS_ENTRY_JS"
+ file="printing_page/cups_printers_entry.js"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_CUPS_PRINTERS_ENTRY_LIST_HTML"
+ file="printing_page/cups_printers_entry_list.html"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_CUPS_PRINTERS_ENTRY_LIST_JS"
+ file="printing_page/cups_printers_entry_list.js"
+ type="chrome_html" />
<structure name="IDR_OS_SETTINGS_CUPS_PRINTERS_LIST_HTML"
file="printing_page/cups_printers_list.html"
type="chrome_html" />
@@ -606,6 +648,18 @@
<structure name="IDR_OS_SETTINGS_CUPS_PRINTER_DIALOG_UTIL_JS"
file="printing_page/cups_printer_dialog_util.js"
type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_CUPS_SAVED_PRINTERS_HTML"
+ file="printing_page/cups_saved_printers.html"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_CUPS_SAVED_PRINTERS_JS"
+ file="printing_page/cups_saved_printers.js"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_CUPS_NEARBY_PRINTERS_HTML"
+ file="printing_page/cups_nearby_printers.html"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_CUPS_NEARBY_PRINTERS_JS"
+ file="printing_page/cups_nearby_printers.js"
+ type="chrome_html" />
<structure name="IDR_OS_SETTINGS_CLOUD_PRINTING_PAGE_HTML"
file="printing_page/cloud_printers.html"
type="chrome_html" />
@@ -669,10 +723,10 @@
file="chromeos/os_privacy_page/os_privacy_page.html"
type="chrome_html"
flattenhtml="true"
+ preprocess="true"
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_OS_PRIVACY_PAGE_JS"
file="chromeos/os_privacy_page/os_privacy_page.js"
- preprocess="true"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_PROTOCOL_HANDLERS_HTML"
file="site_settings/protocol_handlers.html"
@@ -841,12 +895,10 @@
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_SEARCH_PAGE_JS"
file="chromeos/os_search_page/os_search_page.js"
- type="chrome_html"
- preprocess="true" />
+ type="chrome_html" />
<structure name="IDR_OS_SETTINGS_SEARCH_PAGE_HTML"
file="chromeos/os_search_page/os_search_page.html"
type="chrome_html"
- preprocess="true"
allowexternalscript="true" />
<structure name="IDR_OS_SETTINGS_SYNC_CONTROLS_JS"
file="people_page/sync_controls.js"
@@ -857,7 +909,7 @@
type="chrome_html"
preprocess="true"
allowexternalscript="true" />
- <structure name="IDR_OS_SETTINGS_SYNC_PAGE_JS"
+ <structure name="IDR_OS_SETTINGS_SYNC_PAGE_JS"
file="people_page/sync_page.js"
type="chrome_html"
preprocess="true" />
@@ -880,11 +932,10 @@
file="system_page/system_page.js"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_SETTINGS_HTML"
- preprocess="true"
file="chromeos/os_settings.html"
+ preprocess="true"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_LAZY_LOAD_HTML"
- preprocess="true"
file="chromeos/lazy_load.html"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_WEBSITE_USAGE_PRIVATE_API_HTML"
@@ -967,17 +1018,11 @@
type="chrome_html"
preprocess="true"
allowexternalscript="true" />
- <structure name="IDR_OS_SETTINGS_KIOSK_NEXT_SHELL_PAGE_HTML"
- file="kiosk_next_shell_page/kiosk_next_shell_page.html"
- type="chrome_html" />
- <structure name="IDR_OS_SETTINGS_KIOSK_NEXT_SHELL_PAGE_JS"
- file="kiosk_next_shell_page/kiosk_next_shell_page.js"
- type="chrome_html" />
- <structure name="IDR_OS_SETTINGS_KIOSK_NEXT_SHELL_CONFIRMATION_DIALOG_HTML"
- file="kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.html"
+ <structure name="IDR_SETTINGS_CROSTINI_IMPORT_CONFIRMATION_DIALOG_HTML"
+ file="crostini_page/crostini_import_confirmation_dialog.html"
type="chrome_html" />
- <structure name="IDR_OS_SETTINGS_KIOSK_NEXT_SHELL_CONFIRMATION_DIALOG_JS"
- file="kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.js"
+ <structure name="IDR_SETTINGS_CROSTINI_IMPORT_CONFIRMATION_DIALOG_JS"
+ file="crostini_page/crostini_import_confirmation_dialog.js"
type="chrome_html" />
<structure name="IDR_OS_SETTINGS_BLUETOOTH_DEVICE_LIST_ITEM_HTML"
file="bluetooth_page/bluetooth_device_list_item.html"
@@ -1144,6 +1189,18 @@
<structure name="IDR_OS_SETTINGS_TETHER_CONNECTION_DIALOG_JS"
file="internet_page/tether_connection_dialog.js"
type="chrome_html" />
+ <structure name="IDR_SETTINGS_PARENTAL_CONTROLS_BROWSER_PROXY_HTML"
+ file="parental_controls_page/parental_controls_browser_proxy.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_PARENTAL_CONTROLS_BROWSER_PROXY_JS"
+ file="parental_controls_page/parental_controls_browser_proxy.js"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_PARENTAL_CONTROLS_PAGE_HTML"
+ file="parental_controls_page/parental_controls_page.html"
+ type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_PARENTAL_CONTROLS_PAGE_JS"
+ file="parental_controls_page/parental_controls_page.js"
+ type="chrome_html" />
<structure name="IDR_OS_SETTINGS_PEOPLE_PAGE_ACCOUNT_MANAGER_HTML"
file="people_page/account_manager.html"
type="chrome_html"/>
diff --git a/chromium/chrome/browser/resources/settings/os_settings_resources_vulcanized.grd b/chromium/chrome/browser/resources/settings/os_settings_resources_vulcanized.grd
index 04aae4acda2..24bcdcc3e4e 100644
--- a/chromium/chrome/browser/resources/settings/os_settings_resources_vulcanized.grd
+++ b/chromium/chrome/browser/resources/settings/os_settings_resources_vulcanized.grd
@@ -38,7 +38,10 @@
flattenhtml="true"
type="BINDATA"
compress="gzip" />
- <include name="IDR_OS_SETTINGS_MANIFEST" file="manifest.json" type="BINDATA" compress="gzip" />
+ <include name="IDR_OS_SETTINGS_MANIFEST"
+ file="os_settings_manifest.json"
+ type="BINDATA"
+ compress="gzip" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/settings/page_visibility.js b/chromium/chrome/browser/resources/settings/page_visibility.js
index bcf816bde64..fc8d51f2e10 100644
--- a/chromium/chrome/browser/resources/settings/page_visibility.js
+++ b/chromium/chrome/browser/resources/settings/page_visibility.js
@@ -18,6 +18,7 @@
* device: (boolean|undefined),
* downloads: (boolean|undefined|DownloadsPageVisibility),
* internet: (boolean|undefined),
+ * languages: (boolean|undefined|LanguagesPageVisibility),
* multidevice: (boolean|undefined),
* onStartup: (boolean|undefined),
* people: (boolean|undefined|PeoplePageVisibility),
@@ -81,6 +82,14 @@ let PrivacyPageVisibility;
*/
let ResetPageVisibility;
+/**
+ * @typedef {{
+ * manageInputMethods: boolean,
+ * inputMethodsList: boolean,
+ * }}
+ */
+let LanguagesPageVisibility;
+
cr.define('settings', function() {
/**
* Dictionary defining page visibility.
@@ -104,6 +113,7 @@ cr.define('settings', function() {
advancedSettings: false,
extensions: false,
printing: false,
+ languages: false,
};
// </if>
// <if expr="chromeos">
@@ -114,9 +124,7 @@ cr.define('settings', function() {
autofill: false,
people: false,
onStartup: false,
- reset: {
- powerwash: false,
- },
+ reset: false,
appearance: {
setWallpaper: false,
setTheme: false,
@@ -141,7 +149,11 @@ cr.define('settings', function() {
webstoreLink: showOSSettings,
},
extensions: false,
- printing: showOSSettings,
+ printing: true,
+ languages: {
+ manageInputMethods: showOSSettings,
+ inputMethodsList: showOSSettings,
+ },
};
// </if>
} else {
@@ -187,7 +199,11 @@ cr.define('settings', function() {
webstoreLink: showOSSettings,
},
extensions: true,
- printing: showOSSettings,
+ printing: true,
+ languages: {
+ manageInputMethods: showOSSettings,
+ inputMethodsList: showOSSettings,
+ },
};
// </if>
}
diff --git a/chromium/chrome/browser/resources/settings/parental_controls_page/BUILD.gn b/chromium/chrome/browser/resources/settings/parental_controls_page/BUILD.gn
new file mode 100644
index 00000000000..bf02be96291
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/parental_controls_page/BUILD.gn
@@ -0,0 +1,27 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/closure_compiler/compile_js.gni")
+
+js_type_check("closure_compile") {
+ deps = [
+ ":parental_controls_page",
+ ]
+}
+
+js_library("parental_controls_browser_proxy") {
+ deps = [
+ "//ui/webui/resources/js:cr",
+ ]
+}
+
+js_library("parental_controls_page") {
+ deps = [
+ ":parental_controls_browser_proxy",
+ "..:route",
+ "//ui/webui/resources/js:cr",
+ "//ui/webui/resources/js:i18n_behavior",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_browser_proxy.html b/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_browser_proxy.html
new file mode 100644
index 00000000000..9e5cdfc8400
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_browser_proxy.html
@@ -0,0 +1,2 @@
+<link rel="import" href="chrome://resources/html/cr.html">
+<script src="parental_controls_browser_proxy.js"></script>
diff --git a/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_browser_proxy.js b/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_browser_proxy.js
new file mode 100644
index 00000000000..45c48b39a07
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_browser_proxy.js
@@ -0,0 +1,45 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview
+ * Browser Proxy for Parental Controls functions.
+ */
+
+cr.define('parental_controls', function() {
+ /** @interface */
+ class BrowserProxy {
+ /**
+ * Shows the Add Supervsion dialog.
+ */
+ showAddSupervisionDialog() {}
+
+ /**
+ * Launches an app that shows the Family Link Settings. Depending
+ * on whether the Family Link Helper app is available, this might
+ * launch the app, or take some kind of backup/default action.
+ */
+ launchFamilyLinkSettings() {}
+ }
+
+ /** @implements {parental_controls.BrowserProxy} */
+ class BrowserProxyImpl {
+ /** @override */
+ showAddSupervisionDialog() {
+ chrome.send('showAddSupervisionDialog');
+ }
+
+ /** @override */
+ launchFamilyLinkSettings() {
+ chrome.send('launchFamilyLinkSettings');
+ }
+ }
+
+ cr.addSingletonGetter(BrowserProxyImpl);
+
+ return {
+ BrowserProxy: BrowserProxy,
+ BrowserProxyImpl: BrowserProxyImpl,
+ };
+});
diff --git a/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.html b/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.html
new file mode 100644
index 00000000000..960c4f9f0db
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.html
@@ -0,0 +1,56 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
+<link rel="import" href="chrome://resources/cr_elements/icons.html">
+<link rel="import" href="chrome://resources/html/cr.html">
+<link rel="import" href="chrome://resources/html/i18n_behavior.html">
+<link rel="import" href="parental_controls_browser_proxy.html">
+<link rel="import" href="../i18n_setup.html">
+<link rel="import" href="../icons.html">
+<link rel="import" href="../route.html">
+<link rel="import" href="../settings_page/settings_animated_pages.html">
+<link rel="import" href="../settings_page/settings_subpage.html">
+<link rel="import" href="../settings_shared_css.html">
+
+<dom-module id="settings-parental-controls-page">
+ <template>
+ <style include="settings-shared">
+ #parental-controls-setup-section {
+ padding-inline-start: 20px;
+ }
+
+ cr-link-row {
+ --cr-section-padding: 0;
+ }
+ </style>
+ <div id="parental-controls-item" class="settings-box two-line">
+ <template is="dom-if" if="[[isChild_]]">
+ <cr-link-row on-click="handleFamilyLinkButtonClick_"
+ label="$i18n{parentalControlsPageTitle}"
+ sub-label="$i18n{parentalControlsPageViewSettingsLabel}"
+ start-icon="cr20:kite"
+ external>
+ </cr-link-row>
+ </template>
+ <template is="dom-if" if="[[!isChild_]]">
+ <div>
+ <iron-icon icon="cr20:kite"></iron-icon>
+ </div>
+ <div id="parental-controls-setup-section"
+ class="start settings-box-text">
+ <div>
+ $i18n{parentalControlsPageTitle}
+ </div>
+ <div class="secondary">
+ [[getSetupLabelText_(online_)]]
+ </div>
+ </div>
+ <div class="separator"></div>
+ <cr-button on-click="handleSetupButtonClick_" disabled$="[[!online_]]">
+ $i18n{parentalControlsSetUpButtonLabel}
+ </cr-button>
+ </template>
+ </div>
+ </template>
+ <script src="parental_controls_page.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.js b/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.js
new file mode 100644
index 00000000000..85c58b62dff
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/parental_controls_page/parental_controls_page.js
@@ -0,0 +1,87 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview
+ * Settings page for managing Parental Controls features.
+ */
+
+Polymer({
+ is: 'settings-parental-controls-page',
+
+ behaviors: [
+ I18nBehavior,
+ ],
+
+ properties: {
+ /** @private */
+ isChild_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('isChild');
+ }
+ },
+
+ /** @private */
+ online_: {
+ type: Boolean,
+ value: function() {
+ return navigator.onLine;
+ }
+ },
+ },
+
+ /** @override */
+ created: function() {
+ this.browserProxy_ = parental_controls.BrowserProxyImpl.getInstance();
+ },
+
+ /** @override */
+ ready: function() {
+ // Set up online/offline listeners.
+ window.addEventListener('offline', this.onOffline_.bind(this));
+ window.addEventListener('online', this.onOnline_.bind(this));
+ },
+
+ /**
+ * Updates the UI when the device goes offline.
+ * @private
+ */
+ onOffline_: function() {
+ this.online_ = false;
+ },
+
+ /**
+ * Updates the UI when the device comes online.
+ * @private
+ */
+ onOnline_: function() {
+ this.online_ = true;
+ },
+
+ /**
+ * @return {string} Returns the string to display in the main
+ * description area for non-child users.
+ * @private
+ */
+ getSetupLabelText_: function(online) {
+ if (online) {
+ return this.i18n('parentalControlsPageSetUpLabel');
+ } else {
+ return this.i18n('parentalControlsPageConnectToInternetLabel');
+ }
+ },
+
+ /** @private */
+ handleSetupButtonClick_: function(event) {
+ event.stopPropagation();
+ this.browserProxy_.showAddSupervisionDialog();
+ },
+
+ /** @private */
+ handleFamilyLinkButtonClick_: function(event) {
+ event.stopPropagation();
+ this.browserProxy_.launchFamilyLinkSettings();
+ },
+});
diff --git a/chromium/chrome/browser/resources/settings/people_page/BUILD.gn b/chromium/chrome/browser/resources/settings/people_page/BUILD.gn
index 68f69699ff4..799bbfa9a5d 100644
--- a/chromium/chrome/browser/resources/settings/people_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/people_page/BUILD.gn
@@ -129,12 +129,14 @@ js_library("kerberos_accounts_browser_proxy") {
js_library("kerberos_add_account_dialog") {
deps = [
":kerberos_accounts_browser_proxy",
+ "//chrome/browser/resources/settings/controls:settings_textarea",
"//ui/webui/resources/cr_elements/cr_input:cr_input",
"//ui/webui/resources/js:cr",
"//ui/webui/resources/js:i18n_behavior",
"//ui/webui/resources/js:web_ui_listener_behavior",
]
}
+
js_library("lock_screen") {
deps = [
":fingerprint_browser_proxy",
diff --git a/chromium/chrome/browser/resources/settings/people_page/account_manager.html b/chromium/chrome/browser/resources/settings/people_page/account_manager.html
index e3ded337694..b4687fedb68 100644
--- a/chromium/chrome/browser/resources/settings/people_page/account_manager.html
+++ b/chromium/chrome/browser/resources/settings/people_page/account_manager.html
@@ -1,6 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_indicator.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
@@ -101,11 +102,11 @@
hidden="[[isSecondaryGoogleAccountSigninAllowed_()]]"
indicator-type="userPolicy">
</cr-policy-indicator>
- <paper-button disabled="[[!isSecondaryGoogleAccountSigninAllowed_()]]"
+ <cr-button disabled="[[!isSecondaryGoogleAccountSigninAllowed_()]]"
id="add-account-button" on-tap="addAccount_">
<div id="add-account-icon"></div>
$i18n{addAccountLabel}
- </paper-button>
+ </cr-button>
</div>
<div id="outer" class="layout vertical nowrap">
@@ -138,10 +139,10 @@
<template is="dom-if"
if="[[shouldShowReauthenticationButton_(item)]]">
- <paper-button class="reauth-button"
- on-click="onReauthenticationTap_">
+ <cr-button title="[[getAccountManagerSignedOutTitle_(item)]]"
+ class="reauth-button" on-click="onReauthenticationTap_">
[[getAccountManagerSignedOutLabel_(item.unmigrated)]]
- </paper-button>
+ </cr-button>
</template>
<!-- If this is the Device Account, display the management status -->
@@ -152,8 +153,10 @@
</template>
<!-- Else, display a hamburger menu for removing the account -->
<template is="dom-if" if="[[!item.isDeviceAccount]]">
- <cr-icon-button class="icon-more-vert" title="$i18n{moreActions}"
- on-click="onAccountActionsMenuButtonTap_"></cr-icon-button>
+ <cr-icon-button class="icon-more-vert"
+ title="[[getMoreActionsTitle_(item)]]"
+ on-click="onAccountActionsMenuButtonTap_">
+ </cr-icon-button>
</template>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/settings/people_page/account_manager.js b/chromium/chrome/browser/resources/settings/people_page/account_manager.js
index 00248e2ca02..c4364f4ea11 100644
--- a/chromium/chrome/browser/resources/settings/people_page/account_manager.js
+++ b/chromium/chrome/browser/resources/settings/people_page/account_manager.js
@@ -133,6 +133,26 @@ Polymer({
: 'accountManagerReauthenticationLabel');
},
+
+ /**
+ * @param {!settings.Account} account
+ * @private
+ */
+ getAccountManagerSignedOutTitle_: function(account) {
+ const label = account.unmigrated ? 'accountManagerMigrationTooltip'
+ : 'accountManagerReauthenticationTooltip';
+ return loadTimeData.getStringF(label, account.email);
+ },
+
+ /**
+ * @param {!settings.Account} account
+ * @private
+ */
+ getMoreActionsTitle_: function(account) {
+ return loadTimeData.getStringF('accountManagerMoreActionsTooltip',
+ account.email);
+ },
+
/**
* @param {!CustomEvent<!{model: !{item: !settings.Account}}>} event
* @private
@@ -149,7 +169,8 @@ Polymer({
* @private
*/
refreshAccounts_: function() {
- this.browserProxy_.getAccounts().then(accounts => {
+ const includeImages = true;
+ this.browserProxy_.getAccounts(includeImages).then(accounts => {
this.set('accounts_', accounts);
});
},
diff --git a/chromium/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js b/chromium/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js
index b08b02268b5..87826f732a5 100644
--- a/chromium/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/people_page/account_manager_browser_proxy.js
@@ -19,7 +19,7 @@ cr.exportPath('settings');
* unmigrated: boolean,
* fullName: string,
* email: string,
- * pic: string,
+ * pic: (string|undefined),
* organization: (string|undefined),
* }}
*/
@@ -30,9 +30,11 @@ cr.define('settings', function() {
class AccountManagerBrowserProxy {
/**
* Returns a Promise for the list of GAIA accounts held in AccountManager.
+ * @param {boolean} includeImages Include the profile icon images in
+ * settings.Account.pic field, which increases IPC data from the browser.
* @return {!Promise<!Array<settings.Account>>}
*/
- getAccounts() {}
+ getAccounts(includeImages) {}
/**
* Triggers the 'Add account' flow.
@@ -70,8 +72,8 @@ cr.define('settings', function() {
*/
class AccountManagerBrowserProxyImpl {
/** @override */
- getAccounts() {
- return cr.sendWithPromise('getAccounts');
+ getAccounts(includeImages) {
+ return cr.sendWithPromise('getAccounts', includeImages);
}
/** @override */
diff --git a/chromium/chrome/browser/resources/settings/people_page/change_picture.html b/chromium/chrome/browser/resources/settings/people_page/change_picture.html
index 002b1f13299..1dc7a5d0d42 100644
--- a/chromium/chrome/browser/resources/settings/people_page/change_picture.html
+++ b/chromium/chrome/browser/resources/settings/people_page/change_picture.html
@@ -88,7 +88,8 @@
capture-video-label="$i18n{captureVideo}"
switch-mode-to-camera-label="$i18n{switchModeToCamera}"
switch-mode-to-video-label="$i18n{switchModeToVideo}"
- camera-video-mode-enabled="[[cameraVideoModeEnabled_]]">
+ camera-video-mode-enabled="[[cameraVideoModeEnabled_]]"
+ on-keys-pressed="onCameraPaneKeysPressed_">
</cr-picture-pane>
<div id="authorCredit"
hidden="[[!isAuthorCreditShown_(selectedItem_)]]">
@@ -100,6 +101,7 @@
</div>
</div>
<cr-picture-list id="pictureList"
+ hidden="[[!defaultImages_]]"
camera-present="[[cameraPresent_]]"
default-images="[[getDefaultImages_(defaultImages_,
firstDefaultImageIndex_)]]"
diff --git a/chromium/chrome/browser/resources/settings/people_page/change_picture.js b/chromium/chrome/browser/resources/settings/people_page/change_picture.js
index 9c9183b438d..8dd70529250 100644
--- a/chromium/chrome/browser/resources/settings/people_page/change_picture.js
+++ b/chromium/chrome/browser/resources/settings/people_page/change_picture.js
@@ -39,13 +39,11 @@ Polymer({
/**
* The active set of default user images.
- * @private {!Array<!settings.DefaultImage>}
+ * @private {?Array<!settings.DefaultImage>}
*/
defaultImages_: {
- type: Array,
- value: function() {
- return [];
- },
+ type: Object,
+ value: null,
},
/**
@@ -239,6 +237,17 @@ Polymer({
videomode ? 'videoModeAccessibleText' : 'photoModeAccessibleText'));
},
+ /**
+ * Callback the iron-a11y-keys "keys-pressed" event bubbles up from the
+ * cr-camera-pane.
+ * @param {!CustomEvent<!{key: string, keyboardEvent: Object}>} event
+ * @private
+ */
+ onCameraPaneKeysPressed_(event) {
+ this.$.pictureList.focus();
+ this.$.pictureList.onKeysPressed(event);
+ },
+
/** @private */
onDiscardImage_: function() {
// Prevent image from being discarded if old image is pending.
@@ -277,7 +286,7 @@ Polymer({
* @private
*/
getDefaultImages_(defaultImages, firstDefaultImageIndex) {
- return defaultImages.slice(firstDefaultImageIndex);
+ return defaultImages ? defaultImages.slice(firstDefaultImageIndex) : [];
},
/**
diff --git a/chromium/chrome/browser/resources/settings/people_page/fingerprint_list.html b/chromium/chrome/browser/resources/settings/people_page/fingerprint_list.html
index 998a9714d96..37db70a1b32 100644
--- a/chromium/chrome/browser/resources/settings/people_page/fingerprint_list.html
+++ b/chromium/chrome/browser/resources/settings/people_page/fingerprint_list.html
@@ -1,5 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
@@ -9,7 +10,6 @@
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-ripple/paper-ripple.html">
<link rel="import" href="fingerprint_browser_proxy.html">
<link rel="import" href="setup_fingerprint_dialog.html">
@@ -61,10 +61,10 @@
</template>
</iron-list>
<div class="continuation">
- <paper-button id="addFingerprint" class="add-link action-button"
+ <cr-button id="addFingerprint" class="add-link action-button"
on-click="openAddFingerprintDialog_">
$i18n{lockScreenAddFingerprint}
- </paper-button>
+ </cr-button>
</div>
</div>
<i class="settings-box continuation">$i18n{lockScreenFingerprintWarning}</i>
diff --git a/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.html b/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.html
index 8ba8062f92c..9eb241a1aba 100644
--- a/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/import_data_dialog.html
@@ -1,11 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
<link rel="import" href="../controls/settings_checkbox.html">
<link rel="import" href="../controls/settings_toggle_button.html">
@@ -102,27 +102,27 @@
hidden="[[hasImportStatus_(
importStatusEnum_.SUCCEEDED, importStatus_)]]">
</paper-spinner-lite>
- <paper-button id="cancel" class="cancel-button"
+ <cr-button id="cancel" class="cancel-button"
hidden="[[hasImportStatus_(
importStatusEnum_.SUCCEEDED, importStatus_)]]"
disabled="[[hasImportStatus_(
importStatusEnum_.IN_PROGRESS, importStatus_)]]"
on-click="closeDialog_">
$i18n{cancel}
- </paper-button>
- <paper-button id="import" class="action-button"
+ </cr-button>
+ <cr-button id="import" class="action-button"
hidden="[[hasImportStatus_(
importStatusEnum_.SUCCEEDED, importStatus_)]]"
disabled="[[shouldDisableImport_(
importStatus_, noImportDataTypeSelected_)]]"
on-click="onActionButtonTap_">
[[getActionButtonText_(selected_)]]
- </paper-button>
+ </cr-button>
- <paper-button id="done" class="action-button"
+ <cr-button id="done" class="action-button"
hidden$="[[!hasImportStatus_(
importStatusEnum_.SUCCEEDED, importStatus_)]]"
- on-click="closeDialog_">$i18n{done}</paper-button>
+ on-click="closeDialog_">$i18n{done}</cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.html b/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.html
index f20559bf3c0..da29870c4e8 100644
--- a/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.html
+++ b/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.html
@@ -1,13 +1,14 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast.html">
+<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_indicator.html">
<link rel="import" href="chrome://resources/html/icon.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../route.html">
<link rel="import" href="../settings_shared_css.html">
@@ -16,10 +17,9 @@
<dom-module id="settings-kerberos-accounts">
<template>
- <style include="settings-shared iron-flex iron-flex-alignment
- paper-button-style">
- .profile-icon {
- background: center / cover no-repeat;
+ <style include="settings-shared iron-flex iron-flex-alignment">
+ .account-icon {
+ background: center no-repeat;
border-radius: 20px;
flex-shrink: 0;
height: 40px;
@@ -35,6 +35,15 @@
padding-bottom: 1em;
}
+ .account-toolbar,
+ #remove-account-policy-indicator {
+ margin-inline-start: 1em;
+ }
+
+ #add-account-policy-indicator {
+ margin-inline-end: 1em;
+ }
+
#add-account-icon {
-webkit-mask-image: url(chrome://resources/images/add.svg);
background-color: currentColor;
@@ -43,6 +52,11 @@
width: 24px;
}
+ #remove-account-container {
+ align-items: center;
+ display: flex;
+ }
+
.error-badge {
left: 60%;
position: relative;
@@ -59,23 +73,35 @@
}
</style>
- <div class="settings-box first">$i18n{kerberosAccountsDescription}</div>
+ <div class="settings-box first">
+ <h2 class="first">
+ <!-- Inner div needed to get spacing right in front of 'Learn more'. -->
+ <div inner-h-t-m-l="[[i18nAdvanced('kerberosAccountsDescription')]]">
+ </div>
+ </h2>
+ </div>
<div class="settings-box first">
<div id="account-list-header" class="flex">
<h2>$i18n{kerberosAccountsListHeader}</h2>
</div>
- <paper-button id="add-account-button" on-click="onAddAccountClick_">
+ <template is="dom-if" if="[[!addAccountsAllowed_]]">
+ <cr-policy-indicator id="add-account-policy-indicator"
+ indicator-type="userPolicy">
+ </cr-policy-indicator>
+ </template>
+ <cr-button id="add-account-button" on-click="onAddAccountClick_"
+ disabled="[[!addAccountsAllowed_]]">
<div id="add-account-icon"></div>
$i18n{kerberosAccountsAddAccountLabel}
- </paper-button>
+ </cr-button>
</div>
<div id="outer" class="layout vertical nowrap">
<template is="dom-repeat" id="account-list" items="[[accounts_]]">
- <div class="settings-box">
+ <div class="settings-box account-list-item">
- <div class="profile-icon"
+ <div class="account-icon"
style="background-image: [[getIconImageSet_(item.pic)]]">
<img class="error-badge" hidden$="[[item.isSignedIn]]"
src="chrome://resources/images/error_badge.svg">
@@ -85,22 +111,36 @@
<div class="flex text-elide">
<span>[[item.principalName]]</span>
- <div class="secondary" hidden$="[[!item.isSignedIn]]">
- $i18n{kerberosAccountsSignedIn}
+ <div class="secondary signed-in" hidden$="[[!item.isSignedIn]]">
+ [[i18n('kerberosAccountsSignedIn', item.validForDuration)]]
</div>
- <div class="secondary warning" hidden$="[[item.isSignedIn]]">
+ <div class="secondary warning signed-out"
+ hidden$="[[item.isSignedIn]]">
$i18n{kerberosAccountsSignedOut}
</div>
</div>
</div>
- <paper-button class="reauth-button" hidden$="[[item.isSignedIn]]"
+ <div class="secondary account-toolbar active-indicator"
+ hidden$="[[!item.isActive]]">
+ $i18n{kerberosAccountsTicketActive}
+ </div>
+
+ <cr-button class="account-toolbar reauth-button"
+ hidden$="[[item.isSignedIn]]"
on-click="onReauthenticationClick_">
$i18n{kerberosAccountsReauthenticationLabel}
- </paper-button>
+ </cr-button>
+
+ <template is="dom-if" if="[[item.isManaged]]">
+ <cr-policy-indicator indicator-type="userPolicy"
+ class="account-toolbar account-policy-indicator">
+ </cr-policy-indicator>
+ </template>
<!-- Hamburger menu -->
- <cr-icon-button class="icon-more-vert" title="$i18n{moreActions}"
+ <cr-icon-button class="icon-more-vert more-actions"
+ title="$i18n{moreActions}"
on-click="onAccountActionsMenuButtonClick_">
</cr-icon-button>
</div>
@@ -109,14 +149,35 @@
<div class="clear settings-box"></div>
<cr-action-menu>
- <button class="dropdown-item" on-click="onRemoveAccountClick_">
- $i18n{kerberosAccountsRemoveAccountLabel}
+ <button class="dropdown-item" on-click="onRefreshNowClick_">
+ $i18n{kerberosAccountsRefreshNowLabel}
+ </button>
+ <button class="dropdown-item" on-click="onSetAsActiveAccountClick_">
+ $i18n{kerberosAccountsSetAsActiveAccountLabel}
+ </button>
+ <button class="dropdown-item" on-click="onRemoveAccountClick_"
+ disabled="[[selectedAccount_.isManaged]]">
+ <div id="remove-account-container">
+ $i18n{kerberosAccountsRemoveAccountLabel}
+ <template is="dom-if" if="[[selectedAccount_.isManaged]]">
+ <cr-policy-indicator id="remove-account-policy-indicator"
+ indicator-type="userPolicy">
+ </cr-policy-indicator>
+ </template>
+ </div>
</button>
</cr-action-menu>
</div>
+ <cr-toast id="account-removed-toast" duration="3000">
+ <!-- Gets displayed with black font without div and id :-/ -->
+ <div id="account-removed-toast-label">
+ $i18n{kerberosAccountsAccountRemovedTip}
+ </div>
+ </cr-toast>
+
<template is="dom-if" if="[[showAddAccountDialog_]]" restamp>
- <kerberos-add-account-dialog username="[[addAccountPresetUsername_]]"
+ <kerberos-add-account-dialog preset-account="[[selectedAccount_]]"
on-close="onAddAccountDialogClosed_">
</kerberos-add-account-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.js b/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.js
index 219fe4f427b..aec55ed61e7 100644
--- a/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.js
+++ b/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts.js
@@ -8,10 +8,13 @@
* list, add and delete Kerberos Accounts.
*/
+'use strict';
+
Polymer({
is: 'settings-kerberos-accounts',
behaviors: [
+ I18nBehavior,
WebUIListenerBehavior,
],
@@ -28,19 +31,21 @@ Polymer({
},
/**
- * The targeted account for menu operations.
+ * The targeted account for menu and other operations.
* @private {?settings.KerberosAccount}
*/
- actionMenuAccount_: Object,
+ selectedAccount_: Object,
/** @private */
- addAccountPresetUsername_: {
- type: String,
- value: '',
- },
+ showAddAccountDialog_: Boolean,
/** @private */
- showAddAccountDialog_: Boolean,
+ addAccountsAllowed_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('kerberosAddAccountsAllowed');
+ },
+ },
},
/** @private {?settings.KerberosAccountsBrowserProxy} */
@@ -56,7 +61,20 @@ Polymer({
ready: function() {
this.browserProxy_ =
settings.KerberosAccountsBrowserProxyImpl.getInstance();
- this.refreshAccounts_();
+
+ // Grab account list and - when done - pop up the reauthentication dialog if
+ // there is a kerberos_reauth param.
+ this.refreshAccounts_().then(() => {
+ const queryParams = settings.getQueryParameters();
+ const reauthPrincipal = queryParams.get('kerberos_reauth');
+ const reauthAccount = this.accounts_.find(account => {
+ return account.principalName == reauthPrincipal;
+ });
+ if (reauthAccount) {
+ this.selectedAccount_ = reauthAccount;
+ this.showAddAccountDialog_ = true;
+ }
+ });
},
/**
@@ -73,7 +91,7 @@ Polymer({
* @private
*/
onAddAccountClick_: function(event) {
- this.addAccountPresetUsername_ = '';
+ this.selectedAccount_ = null;
this.showAddAccountDialog_ = true;
},
@@ -82,20 +100,23 @@ Polymer({
* @private
*/
onReauthenticationClick_: function(event) {
- this.addAccountPresetUsername_ = event.model.item.principalName;
+ this.selectedAccount_ = event.model.item;
this.showAddAccountDialog_ = true;
},
/** @private */
onAddAccountDialogClosed_: function() {
this.showAddAccountDialog_ = false;
+ // In case it was opened by the 'Refresh now' action menu.
+ this.closeActionMenu_();
},
/**
+ * @return {!Promise}
* @private
*/
refreshAccounts_: function() {
- this.browserProxy_.getAccounts().then(accounts => {
+ return this.browserProxy_.getAccounts().then(accounts => {
this.accounts_ = accounts;
});
},
@@ -107,7 +128,7 @@ Polymer({
* @private
*/
onAccountActionsMenuButtonClick_: function(event) {
- this.actionMenuAccount_ = event.model.item;
+ this.selectedAccount_ = event.model.item;
/** @type {!CrActionMenuElement} */ (this.$$('cr-action-menu'))
.showAt(event.target);
},
@@ -118,16 +139,42 @@ Polymer({
*/
closeActionMenu_: function() {
this.$$('cr-action-menu').close();
- this.actionMenuAccount_ = null;
+ this.selectedAccount_ = null;
},
/**
- * Removes the account being pointed to by |this.actionMenuAccount_|.
+ * Removes |this.selectedAccount_|.
* @private
*/
onRemoveAccountClick_: function() {
- this.browserProxy_.removeAccount(
- /** @type {!settings.KerberosAccount} */ (this.actionMenuAccount_));
+ this.browserProxy_
+ .removeAccount(
+ /** @type {!settings.KerberosAccount} */ (this.selectedAccount_))
+ .then(error => {
+ if (error == settings.KerberosErrorType.kNone) {
+ this.$$('#account-removed-toast').show();
+ } else {
+ console.error('Unexpected error removing account: ' + error);
+ }
+ });
+ this.closeActionMenu_();
+ },
+
+ /**
+ * Sets |this.selectedAccount_| as active Kerberos account.
+ * @private
+ */
+ onSetAsActiveAccountClick_: function() {
+ this.browserProxy_.setAsActiveAccount(
+ /** @type {!settings.KerberosAccount} */ (this.selectedAccount_));
this.closeActionMenu_();
+ },
+
+ /**
+ * Opens the reauth dialog for |this.selectedAccount_|.
+ * @private
+ */
+ onRefreshNowClick_: function() {
+ this.showAddAccountDialog_ = true;
}
});
diff --git a/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts_browser_proxy.js b/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts_browser_proxy.js
index 25ec4f1d482..89d27cd38aa 100644
--- a/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/people_page/kerberos_accounts_browser_proxy.js
@@ -13,12 +13,28 @@ cr.exportPath('settings');
* Information for a Chrome OS Kerberos account.
* @typedef {{
* principalName: string,
+ * config: string,
* isSignedIn: boolean,
+ * isActive: boolean,
+ * isManaged: boolean,
+ * passwordWasRemembered: boolean,
* pic: string,
+ * validForDuration: string
* }}
*/
settings.KerberosAccount;
+/**
+ * @typedef {{
+ * error: !settings.KerberosErrorType,
+ * errorInfo: !{
+ * code: !settings.KerberosConfigErrorCode,
+ * lineIndex: (number|undefined)
+ * }
+ * }}
+ */
+settings.ValidateKerberosConfigResult;
+
cr.define('settings', function() {
/**
* @enum {number}
@@ -45,6 +61,26 @@ cr.define('settings', function() {
kDuplicatePrincipalName: 16,
kInProgress: 17,
kParsePrincipalFailed: 18,
+ kBadConfig: 19,
+ kJailFailure: 20,
+ };
+
+ /**
+ * @enum {number}
+ * Error codes for config validation.
+ * These values must be kept in sync with the KerberosConfigErrorCode enum in
+ * third_party/cros_system_api/dbus/kerberos/kerberos_service.proto.
+ */
+ const KerberosConfigErrorCode = {
+ kNone: 0,
+ kSectionNestedInGroup: 1,
+ kSectionSyntax: 2,
+ kExpectedOpeningCurlyBrace: 3,
+ kExtraCurlyBrace: 4,
+ kRelationSyntax: 5,
+ kKeyNotSupported: 6,
+ kSectionNotSupported: 7,
+ kKrb5FailedToParse: 8,
};
/** @interface */
@@ -60,15 +96,35 @@ cr.define('settings', function() {
* Attempts to add a new (or update an existing) Kerberos account.
* @param {string} principalName Kerberos principal (user@realm.com).
* @param {string} password Account password.
+ * @param {boolean} rememberPassword Whether to store the password.
+ * @param {string} config Kerberos configuration.
+ * @param {boolean} allowExisting Whether existing accounts may be updated.
* @return {!Promise<!settings.KerberosErrorType>}
*/
- addAccount(principalName, password) {}
+ addAccount(
+ principalName, password, rememberPassword, config, allowExisting) {}
/**
* Removes |account| from the set of Kerberos accounts.
* @param {!settings.KerberosAccount} account
+ * @return {!Promise<!settings.KerberosErrorType>}
*/
removeAccount(account) {}
+
+ /**
+ * Validates |krb5conf| by making sure that it does not contain syntax
+ * errors or disallowed configuration options.
+ * @param {string} krb5Conf Kerberos configuration data (krb5.conf)
+ * @return {!Promise<!settings.ValidateKerberosConfigResult>}
+ */
+ validateConfig(krb5Conf) {}
+
+ /**
+ * Sets |account| as currently active account. Kerberos credentials are
+ * consumed from this account.
+ * @param {!settings.KerberosAccount} account
+ */
+ setAsActiveAccount(account) {}
}
/**
@@ -81,13 +137,26 @@ cr.define('settings', function() {
}
/** @override */
- addAccount(principalName, password) {
- return cr.sendWithPromise('addKerberosAccount', principalName, password);
+ addAccount(
+ principalName, password, rememberPassword, config, allowExisting) {
+ return cr.sendWithPromise(
+ 'addKerberosAccount', principalName, password, rememberPassword,
+ config, allowExisting);
}
/** @override */
removeAccount(account) {
- chrome.send('removeKerberosAccount', [account.principalName]);
+ return cr.sendWithPromise('removeKerberosAccount', account.principalName);
+ }
+
+ /** @override */
+ validateConfig(krb5conf) {
+ return cr.sendWithPromise('validateKerberosConfig', krb5conf);
+ }
+
+ /** @override */
+ setAsActiveAccount(account) {
+ chrome.send('setAsActiveKerberosAccount', [account.principalName]);
}
}
@@ -95,6 +164,7 @@ cr.define('settings', function() {
return {
KerberosErrorType: KerberosErrorType,
+ KerberosConfigErrorCode: KerberosConfigErrorCode,
KerberosAccountsBrowserProxy: KerberosAccountsBrowserProxy,
KerberosAccountsBrowserProxyImpl: KerberosAccountsBrowserProxyImpl,
};
diff --git a/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.html b/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.html
index c6a15532381..b6f3fd769cd 100644
--- a/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.html
@@ -1,63 +1,169 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_indicator.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
+<link rel="import" href="chrome://resources/html/action_link.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/load_time_data.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="../controls/settings_textarea.html">
+<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="kerberos_accounts_browser_proxy.html">
<dom-module id="kerberos-add-account-dialog">
<template>
- <style include="paper-button-style">
- .label {
- @apply --cr-form-field-label;
+ <style include="settings-shared action-link">
+ #advancedConfigDesc {
+ align-items: center;
+ display: flex;
}
- #credentials > cr-input:not(:last-child) {
+ #advancedConfigPolicyIndicator {
+ margin-inline-start: 1em;
+ }
+
+ #credentials > *:not(:last-child) {
margin-bottom: var(--cr-form-field-bottom-spacing);
}
#general-error-container {
- height: 48px;
+ height: 56px;
+ }
+
+ #config-error-container {
+ height: 40px;
+ margin-top: 16px;
+ }
+
+ #general-error-message,
+ #config-error-message {
+ color: var(--settings-error-color);
+ }
+
+ .inner-error-container {
+ display: flex;
+ }
+
+ iron-icon[icon='cr:error'] {
+ fill: var(--settings-error-color);
+ margin-inline-end: 8px;
+ }
+
+ #rememberPasswordContainer {
+ align-items: center;
+ display: flex;
+ margin-bottom: 32px;
+ }
+
+ #rememberPassword {
+ margin-inline-end: 1em;
}
</style>
- <cr-dialog id="dialog">
- <div slot="title">$i18n{addKerberosAccount}</div>
+
+ <cr-dialog id="addDialog" hidden="[[showAdvancedConfig_]]">
+ <div slot="title">[[title_]]</div>
+
<div slot="body" spellcheck="false">
+ <h2 class="start first">
+ $i18n{addKerberosAccountDescription}
+ </h2>
+
<div id="general-error-container">
- <div hidden="[[!showError_(generalErrorText_)]]">
- <iron-icon id="general-error-icon" icon="cr:warning"></iron-icon>
+ <div class="inner-error-container"
+ hidden="[[!showError_(generalErrorText_)]]">
+ <iron-icon id="error-icon" icon="cr:error"></iron-icon>
<div id="general-error-message">[[generalErrorText_]]</div>
</div>
</div>
<div id="credentials">
<cr-input id="username" label="$i18n{kerberosUsername}"
- value="{{username}}" invalid="[[showError_(usernameErrorText_)]]"
+ value="{{username_}}" invalid="[[showError_(usernameErrorText_)]]"
+ placeholder="user@example.com"
error-message="[[usernameErrorText_]]">
</cr-input>
+
<cr-input id="password" type="password"
label="$i18n{kerberosPassword}" value="{{password_}}"
invalid="[[showError_(passwordErrorText_)]]"
- error-message="[[passwordErrorText_]]">
+ error-message="[[passwordErrorText_]]"
+ on-input="onPasswordInput_">
</cr-input>
+
+ <div id="rememberPasswordContainer">
+ <cr-checkbox id="rememberPassword" checked="{{rememberPassword_}}"
+ disabled="[[!rememberPasswordEnabled_]]">
+ $i18n{addKerberosAccountRememberPassword}
+ </cr-checkbox>
+ <template is="dom-if" if="[[!rememberPasswordEnabled_]]">
+ <cr-policy-indicator id="rememberPasswordPolicyIndicator"
+ indicator-type="userPolicy">
+ </cr-policy-indicator>
+ </template>
+ </div>
+
+ <a is="action-link" id="advancedConfigButton"
+ on-click="onAdvancedConfigClick_">
+ $i18n{kerberosAccountsAdvancedConfigLabel}
+ </a>
</div>
</div>
+
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancel_" id="cancel">
+ <cr-button class="cancel-button" on-click="onCancel_" id="cancel">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onAdd_"
+ </cr-button>
+ <cr-button class="action-button" on-click="onAdd_"
disabled="[[inProgress_]]">
- $i18n{add}
- </paper-button>
+ [[actionButtonLabel_]]
+ </cr-button>
</div>
</cr-dialog>
+
+ <template is="dom-if" if="[[showAdvancedConfig_]]" restamp>
+ <cr-dialog id="advancedConfigDialog" on-close="onAdvancedConfigClose_">
+ <div slot="title">$i18n{kerberosAdvancedConfigTitle}</div>
+
+ <div slot="body">
+ <h2 class="first" id="advancedConfigDesc">
+ $i18n{kerberosAdvancedConfigDesc}
+ <template is="dom-if" if="[[isManaged_]]">
+ <cr-policy-indicator id="advancedConfigPolicyIndicator"
+ indicator-type="userPolicy">
+ </cr-policy-indicator>
+ </template>
+ </h2>
+
+ <settings-textarea id="config" value="{{editableConfig_}}" rows=12
+ spellcheck="false" disabled="[[isManaged_]]">
+ </settings-textarea>
+
+ <div id="config-error-container">
+ <div class="inner-error-container"
+ hidden="[[!showError_(configErrorText_)]]">
+ <iron-icon id="error-icon" icon="cr:error"></iron-icon>
+ <div id="config-error-message">[[configErrorText_]]</div>
+ </div>
+ </div>
+ </div>
+
+ <div slot="button-container">
+ <cr-button class="cancel-button"
+ on-click="onAdvancedConfigCancel_">
+ $i18n{cancel}
+ </cr-button>
+ <cr-button class="action-button" on-click="onAdvancedConfigSave_"
+ disabled="[[inProgress_]]">
+ $i18n{save}
+ </cr-button>
+ </div>
+ </cr-dialog>
+ </template>
</template>
<script src="kerberos_add_account_dialog.js"></script>
-</dom-module> \ No newline at end of file
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.js b/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.js
index df260a36ac4..295a14d087a 100644
--- a/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.js
+++ b/chromium/chrome/browser/resources/settings/people_page/kerberos_add_account_dialog.js
@@ -13,7 +13,15 @@ Polymer({
behaviors: [I18nBehavior],
properties: {
- username: {
+ /**
+ * If set, some fields are preset from this account (like username or
+ * whether to remember the password).
+ * @type {?settings.KerberosAccount}
+ */
+ presetAccount: Object,
+
+ /** @private */
+ username_: {
type: String,
value: '',
},
@@ -24,6 +32,22 @@ Polymer({
value: '',
},
+ /**
+ * Current configuration in the Advanced Config dialog. Propagates to
+ * |config| only if 'Save' button is pressed.
+ * @private {string}
+ */
+ editableConfig_: {
+ type: String,
+ value: '',
+ },
+
+ /** @private */
+ rememberPassword_: {
+ type: Boolean,
+ value: false,
+ },
+
/** @private */
generalErrorText_: {
type: String,
@@ -43,48 +67,127 @@ Polymer({
},
/** @private */
+ configErrorText_: {
+ type: String,
+ value: '',
+ },
+
+ /** @private */
inProgress_: {
type: Boolean,
value: false,
},
+
+ /** @private */
+ isManaged_: {
+ type: Boolean,
+ value: false,
+ },
+
+ /** @private */
+ showAdvancedConfig_: {
+ type: Boolean,
+ value: false,
+ },
+
+ /** @private */
+ rememberPasswordEnabled_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('kerberosRememberPasswordEnabled');
+ },
+ },
},
+ /** @private {boolean} */
+ useRememberedPassword_: false,
+
+ /** @private {string} */
+ config_: '',
+
+ /** @private {string} */
+ title_: '',
+
+ /** @private {string} */
+ actionButtonLabel_: '',
+
/** @private {?settings.KerberosAccountsBrowserProxy} */
browserProxy_: null,
- /** @private {!settings.KerberosErrorType} */
- lastError_: settings.KerberosErrorType.kNone,
+ /** @override */
+ created: function() {
+ this.browserProxy_ =
+ settings.KerberosAccountsBrowserProxyImpl.getInstance();
+ },
/** @override */
attached: function() {
- this.$.dialog.showModal();
+ this.$.addDialog.showModal();
+
+ if (this.presetAccount) {
+ // Refresh an existing account.
+ this.title_ = this.i18n('refreshKerberosAccount');
+ this.actionButtonLabel_ =
+ this.i18n('addKerberosAccountRefreshButtonLabel');
- // If a non-empty username is preset, make the UI read-only.
- // Note: At least the focus() part needs to be after showModal.
- if (this.username) {
- this.$.username.disabled = true;
+ // Preset username and make UI read-only.
+ // Note: At least the focus() part needs to be after showModal.
+ this.username_ = this.presetAccount.principalName;
+ this.isManaged_ = this.presetAccount.isManaged;
+ this.$.username.readonly = true;
this.$.password.focus();
+
+ if (this.presetAccount.passwordWasRemembered &&
+ this.rememberPasswordEnabled_) {
+ // The daemon knows the user's password, so prefill the password field
+ // with some string (Chrome does not know the actual password for
+ // security reasons). If the user does not change it, an empty password
+ // is sent to the daemon, which is interpreted as "use remembered
+ // password". Also, keep remembering the password by default.
+ const FAKE_PASSWORD = 'xxxxxxxx';
+ this.password_ = FAKE_PASSWORD;
+ this.rememberPassword_ = true;
+ this.useRememberedPassword_ = true;
+ }
+
+ this.config_ = this.presetAccount.config;
+ } else {
+ // Add a new Kerberos account.
+ this.title_ = this.i18n('addKerberosAccount');
+ this.actionButtonLabel_ = this.i18n('add');
+
+ // Set a default configuration.
+ this.config_ = loadTimeData.getString('defaultKerberosConfig');
}
},
/** @private */
onCancel_: function() {
- this.$.dialog.cancel();
+ this.$.addDialog.cancel();
},
/** @private */
onAdd_: function() {
+ assert(!this.inProgress_);
this.inProgress_ = true;
this.updateErrorMessages_(settings.KerberosErrorType.kNone);
- settings.KerberosAccountsBrowserProxyImpl.getInstance()
- .addAccount(this.username, this.password_)
+ // An empty password triggers the Kerberos daemon to use the remembered one.
+ const passwordToSubmit = this.useRememberedPassword_ ? '' : this.password_;
+
+ // For new accounts (no preset), bail if the account already exists.
+ const allowExisting = !!this.presetAccount;
+
+ this.browserProxy_
+ .addAccount(
+ this.username_, passwordToSubmit, this.rememberPassword_,
+ this.config_, allowExisting)
.then(error => {
this.inProgress_ = false;
// Success case. Close dialog.
if (error == settings.KerberosErrorType.kNone) {
- this.$.dialog.close();
+ this.$.addDialog.close();
return;
}
@@ -93,13 +196,67 @@ Polymer({
});
},
+ /** @private */
+ onPasswordInput_: function() {
+ // On first input, don't reuse the remembered password, but submit the
+ // changed one.
+ this.useRememberedPassword_ = false;
+ },
+
+ /** @private */
+ onAdvancedConfigClick_: function() {
+ // Keep a copy of the config in case the user cancels.
+ this.editableConfig_ = this.config_;
+ this.showAdvancedConfig_ = true;
+ Polymer.dom.flush();
+ this.$$('#advancedConfigDialog').showModal();
+ },
+
+ /** @private */
+ onAdvancedConfigCancel_: function() {
+ this.configErrorText_ = '';
+ this.showAdvancedConfig_ = false;
+ this.$$('#advancedConfigDialog').cancel();
+ },
+
+ /** @private */
+ onAdvancedConfigSave_: function() {
+ assert(!this.inProgress_);
+ this.inProgress_ = true;
+
+ this.browserProxy_.validateConfig(this.editableConfig_).then(result => {
+ this.inProgress_ = false;
+
+ // Success case. Close dialog.
+ if (result.error == settings.KerberosErrorType.kNone) {
+ this.showAdvancedConfig_ = false;
+ this.config_ = this.editableConfig_;
+ this.configErrorText_ = '';
+ this.$$('#advancedConfigDialog').close();
+ return;
+ }
+
+ // Triggers the UI to update error messages.
+ this.updateConfigErrorMessage_(result);
+ });
+ },
+
+ onAdvancedConfigClose_: function(event) {
+ // Note: 'Esc' doesn't trigger onAdvancedConfigCancel_() and some tests
+ // that trigger onAdvancedConfigCancel_() don't trigger this for some
+ // reason, hence this is needed here and above.
+ this.showAdvancedConfig_ = false;
+
+ // Since this is a sub-dialog, prevent event from bubbling up. Otherwise,
+ // it might cause the add-dialog to be closed.
+ event.stopPropagation();
+ },
+
/**
* @param {!settings.KerberosErrorType} error Current error enum
* @private
*/
updateErrorMessages_: function(error) {
- this.lastError_ = error;
-
this.generalErrorText_ = '';
this.usernameErrorText_ = '';
this.passwordErrorText_ = '';
@@ -117,6 +274,10 @@ Polymer({
case settings.KerberosErrorType.kBadPrincipal:
this.usernameErrorText_ = this.i18n('kerberosErrorUsernameUnknown');
break;
+ case settings.KerberosErrorType.kDuplicatePrincipalName:
+ this.usernameErrorText_ =
+ this.i18n('kerberosErrorDuplicatePrincipalName');
+ break;
case settings.KerberosErrorType.kContactingKdcFailed:
this.usernameErrorText_ = this.i18n('kerberosErrorContactingServer');
break;
@@ -133,11 +294,107 @@ Polymer({
break;
default:
this.generalErrorText_ =
- this.i18n('kerberosErrorGeneral', String(error));
+ this.i18n('kerberosErrorGeneral', error.toString());
+ }
+ },
+
+ /**
+ * @param {!settings.ValidateKerberosConfigResult} result Result from a
+ * validateKerberosConfig() call.
+ * @private
+ */
+ updateConfigErrorMessage_: function(result) {
+ // There should be an error at this point.
+ assert(result.error != settings.KerberosErrorType.kNone);
+
+ // Only handle kBadConfig here. Display generic error otherwise. Should only
+ // occur if something is wrong with D-Bus, but nothing user-induced.
+ if (result.error != settings.KerberosErrorType.kBadConfig) {
+ this.configErrorText_ =
+ this.i18n('kerberosErrorGeneral', result.error.toString());
+ return;
+ }
+
+ let errorLine = '';
+
+ // Don't fall for the classical blunder 0 == false.
+ if (result.errorInfo.lineIndex != undefined) {
+ const textArea = this.$$('#config').shadowRoot.querySelector('#input');
+ errorLine = this.selectAndScrollTo_(textArea, result.errorInfo.lineIndex);
+ }
+
+ // If kBadConfig, the error code should be set.
+ assert(result.errorInfo.code != settings.KerberosConfigErrorCode.kNone);
+ this.configErrorText_ =
+ this.getConfigErrorString_(result.errorInfo.code, errorLine);
+ },
+
+ /**
+ * @param {!settings.KerberosConfigErrorCode} code Error code
+ * @param {!string} errorLine Line where the error occurred
+ * @return {!string} Localized error string that corresponds to code
+ * @private
+ */
+ getConfigErrorString_: function(code, errorLine) {
+ switch (code) {
+ case settings.KerberosConfigErrorCode.kSectionNestedInGroup:
+ return this.i18n('kerberosConfigErrorSectionNestedInGroup', errorLine);
+ case settings.KerberosConfigErrorCode.kSectionSyntax:
+ return this.i18n('kerberosConfigErrorSectionSyntax', errorLine);
+ case settings.KerberosConfigErrorCode.kExpectedOpeningCurlyBrace:
+ return this.i18n(
+ 'kerberosConfigErrorExpectedOpeningCurlyBrace', errorLine);
+ case settings.KerberosConfigErrorCode.kExtraCurlyBrace:
+ return this.i18n('kerberosConfigErrorExtraCurlyBrace', errorLine);
+ case settings.KerberosConfigErrorCode.kRelationSyntax:
+ return this.i18n('kerberosConfigErrorRelationSyntax', errorLine);
+ case settings.KerberosConfigErrorCode.kKeyNotSupported:
+ return this.i18n('kerberosConfigErrorKeyNotSupported', errorLine);
+ case settings.KerberosConfigErrorCode.kSectionNotSupported:
+ return this.i18n('kerberosConfigErrorSectionNotSupported', errorLine);
+ case settings.KerberosConfigErrorCode.kKrb5FailedToParse:
+ // Note: This error doesn't have an error line.
+ return this.i18n('kerberosConfigErrorKrb5FailedToParse');
+ default:
+ assertNotReached();
}
},
/**
+ * Selects a line in a text area and scrolls to it.
+ * @param {!Element} textArea A textarea element
+ * @param {!number} lineIndex 0-based index of the line to select
+ * @return {!string} The line at lineIndex.
+ * @private
+ */
+ selectAndScrollTo_: function(textArea, lineIndex) {
+ const lines = textArea.value.split('\n');
+ assert(lineIndex >= 0 && lineIndex < lines.length);
+
+ // Compute selection position in characters.
+ let startPos = 0;
+ for (let i = 0; i < lineIndex; i++) {
+ startPos += lines[i].length + 1;
+ }
+
+ // Ignore starting and trailing whitespace for the selection.
+ const trimmedLine = lines[lineIndex].trim();
+ startPos += lines[lineIndex].indexOf(trimmedLine);
+ const endPos = startPos + trimmedLine.length;
+
+ // Set selection.
+ textArea.focus();
+ textArea.setSelectionRange(startPos, endPos);
+
+ // Scroll to center the selected line.
+ const lineHeight = textArea.clientHeight / textArea.rows;
+ const firstLine = Math.max(0, lineIndex - textArea.rows / 2);
+ textArea.scrollTop = lineHeight * firstLine;
+
+ return lines[lineIndex];
+ },
+
+ /**
* Whether an error element should be shown.
* Note that !! is not supported in Polymer bindings.
* @param {?string} errorText Error text to be displayed. Empty if no error.
diff --git a/chromium/chrome/browser/resources/settings/people_page/lock_screen.html b/chromium/chrome/browser/resources/settings/people_page/lock_screen.html
index 5947726a16d..a2ce568a87d 100644
--- a/chromium/chrome/browser/resources/settings/people_page/lock_screen.html
+++ b/chromium/chrome/browser/resources/settings/people_page/lock_screen.html
@@ -1,6 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_components/chromeos/quick_unlock/lock_screen_constants.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_radio_button/cr_radio_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_radio_group/cr_radio_group.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
@@ -35,16 +36,15 @@
display: block;
}
- cr-radio-button {
- --cr-radio-button-slot: {
- display: flex;
- line-height: 154%; /* Apply 20px line-height to paper radio button
- text to match rest of settings line-heights. */
- width: 100%;
- };
+ #pinPasswordDiv {
+ display: flex;
}
- #pinPasswordDiv,
+ #pinPasswordLabel {
+ flex: 1;
+ }
+
+ #pinPasswordLabel,
#pinPasswordSecondaryActionDiv {
margin: auto;
}
@@ -66,6 +66,12 @@
label="$i18n{enableScreenlock}">
</settings-toggle-button>
+ <settings-toggle-button id="enableLockScreenMediaKeys"
+ hidden="[[!lockScreenMediaKeysPreferenceEnabled_]]"
+ pref="{{prefs.ash.lock_screen_media_keys_enabled}}"
+ label="$i18n{lockScreenMediaKeys}">
+ </settings-toggle-button>
+
<template is="dom-if" if="[[quickUnlockEnabled_]]">
<div id="lockOptionsDiv">
<div class="settings-box">
@@ -85,24 +91,25 @@
</div>
</cr-radio-button>
<cr-radio-button name="pin+password" class="list-item">
- <div id="pinPasswordDiv" class="start">
- $i18n{lockScreenPinOrPassword}
- </div>
- <template is="dom-if"
- if="[[showConfigurePinButton_(selectedUnlockType)]]">
- <div class="separator"></div>
- <div id="pinPasswordSecondaryActionDiv"
- class="secondary-action">
- <!-- Use stop-keyboard-event-propagation to prevent
- triggering this when focused after closing the
- dialog. -->
- <paper-button id="setupPinButton" class="secondary-button"
- on-click="onConfigurePin_"
- stop-keyboard-event-propagation>
- [[getSetupPinText_(hasPin)]]
- </paper-button>
+ <div id="pinPasswordDiv">
+ <div id="pinPasswordLabel">
+ $i18n{lockScreenPinOrPassword}
</div>
- </template>
+ <template is="dom-if"
+ if="[[showConfigurePinButton_(selectedUnlockType)]]">
+ <div class="separator"></div>
+ <div id="pinPasswordSecondaryActionDiv"
+ class="secondary-action">
+ <!-- Use stop-keyboard-event-propagation to prevent
+ triggering this when focused after closing the
+ dialog. -->
+ <cr-button id="setupPinButton" on-click="onConfigurePin_"
+ stop-keyboard-event-propagation>
+ [[getSetupPinText_(hasPin)]]
+ </cr-button>
+ </div>
+ </template>
+ </div>
</cr-radio-button>
</cr-radio-group>
</div>
@@ -145,12 +152,11 @@
</div>
<div class="separator"></div>
<div class="secondary-action">
- <paper-button class="secondary-button"
- on-click="onEditFingerprints_"
+ <cr-button on-click="onEditFingerprints_"
aria-label="$i18n{lockScreenEditFingerprints}"
aria-descibedby="lockScreenEditFingerprintsSecondary">
$i18n{lockScreenSetupFingerprintButton}
- </paper-button>
+ </cr-button>
</div>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/settings/people_page/lock_screen.js b/chromium/chrome/browser/resources/settings/people_page/lock_screen.js
index f0584fee7e4..6780493980f 100644
--- a/chromium/chrome/browser/resources/settings/people_page/lock_screen.js
+++ b/chromium/chrome/browser/resources/settings/people_page/lock_screen.js
@@ -130,6 +130,19 @@ Polymer({
readOnly: true,
},
+ /**
+ * Whether the lock screen media keys preference is enabled by the
+ * feature flag.
+ * @private
+ */
+ lockScreenMediaKeysPreferenceEnabled_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('lockScreenMediaKeysEnabled');
+ },
+ readOnly: true,
+ },
+
/** @private */
showPasswordPromptDialog_: Boolean,
diff --git a/chromium/chrome/browser/resources/settings/people_page/people_page.html b/chromium/chrome/browser/resources/settings/people_page/people_page.html
index 95a0b616ef8..f2a605bb946 100644
--- a/chromium/chrome/browser/resources/settings/people_page/people_page.html
+++ b/chromium/chrome/browser/resources/settings/people_page/people_page.html
@@ -1,8 +1,10 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
+<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_indicator.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
@@ -11,7 +13,6 @@
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../controls/settings_toggle_button.html">
<link rel="import" href="profile_info_browser_proxy.html">
<link rel="import" href="sync_browser_proxy.html">
@@ -34,6 +35,7 @@
<link rel="import" href="lock_screen.html">
<link rel="import" href="lock_state_behavior.html">
<link rel="import" href="users_page.html">
+<link rel="import" href="../parental_controls_page/parental_controls_page.html">
</if>
<if expr="not chromeos">
<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast.html">
@@ -62,8 +64,10 @@
--iron-icon-fill-color: var(--google-green-refresh-700);
}
- :host-context([dark]) iron-icon[icon='cr:sync'] {
- --iron-icon-fill-color: var(--google-green-refresh-300);
+ @media (prefers-color-scheme: dark) {
+ iron-icon[icon='cr:sync'] {
+ --iron-icon-fill-color: var(--google-green-refresh-300);
+ }
}
#sync-status[actionable] iron-icon[icon='settings:sync-problem'] {
@@ -75,9 +79,11 @@
--iron-icon-fill-color: var(--google-blue-500);
}
- :host-context([dark]) #sync-status[actionable].auth-error
- iron-icon[icon='settings:sync-disabled'] {
- --iron-icon-fill-color: var(--google-blue-refresh-300);
+ @media (prefers-color-scheme: dark) {
+ #sync-status[actionable].auth-error
+ iron-icon[icon='settings:sync-disabled'] {
+ --iron-icon-fill-color: var(--google-blue-refresh-300);
+ }
}
#sync-status:not([actionable]) .subpage-arrow {
@@ -111,22 +117,16 @@
right: 0;
}
- settings-sync-account-control[showing-promo] {
- --promo-banner: {
- /* Make the banner image stay within setting-section's card border
- radius. */
- border-top-left-radius: var(--cr-card-border-radius);
- border-top-right-radius: var(--cr-card-border-radius);
- }
- /* When showing promo in this page, text should be larger. */
- --promo-description: {
- font-size: 0.9rem;
- line-height: 1.625rem;
- }
- --promo-title: {
- font-size: 1.1rem;
- line-height: 1.625rem;
- }
+ settings-sync-account-control[showing-promo]::part(banner) {
+ /* Make the banner image stay within setting-section's card border
+ radius. */
+ border-top-left-radius: var(--cr-card-border-radius);
+ border-top-right-radius: var(--cr-card-border-radius);
+ }
+
+ settings-sync-account-control[showing-promo]::part(title) {
+ font-size: 1.1rem;
+ line-height: 1.625rem;
}
</if>
</style>
@@ -177,18 +177,17 @@
<if expr="not chromeos">
<template is="dom-if" if="[[showSignin_(syncStatus)]]">
<div class="separator"></div>
- <paper-button class="action-button" on-click="onSigninTap_"
+ <cr-button class="action-button" on-click="onSigninTap_"
disabled="[[syncStatus.firstSetupInProgress]]">
$i18n{syncSignin}
- </paper-button>
+ </cr-button>
</template>
<template is="dom-if" if="[[syncStatus.signedIn]]">
<div class="separator"></div>
- <paper-button id="disconnectButton" class="secondary-button"
- on-click="onDisconnectTap_"
+ <cr-button id="disconnectButton" on-click="onDisconnectTap_"
disabled="[[syncStatus.firstSetupInProgress]]">
$i18n{syncDisconnect}
- </paper-button>
+ </cr-button>
</template>
</if>
</template>
@@ -275,18 +274,24 @@
on-click="onAccountManagerTap_"
label="$i18n{accountManagerSubMenuLabel}"></cr-link-row>
</template>
+ <template is="dom-if" if="[[showParentalControls_]]">
+ <settings-parental-controls-page>
+ </settings-parental-controls-page>
+ </template>
+ <cr-link-row id="manage-other-people-subpage-trigger"
+ label="$i18n{manageOtherPeople}" on-click="onManageOtherPeople_"
+ hidden="[[!pageVisibility.people.manageUsers]]">
+ </cr-link-row>
<template is="dom-if" if="[[shouldShowKerberos_(
isKerberosEnabled_, pageVisibility.people.kerberosAccounts)]]">
<cr-link-row id="kerberos-accounts-subpage-trigger" class="hr"
on-click="onKerberosAccountsTap_"
- label="$i18n{kerberosAccountsSubMenuLabel}"></cr-link-row>
+ label="$i18n{kerberosAccountsSubMenuLabel}">
+ <cr-policy-indicator indicator-type="userPolicy">
+ </cr-policy-indicator>
+ </cr-link-row>
</template>
-
- <cr-link-row id="manage-other-people-subpage-trigger"
- label="$i18n{manageOtherPeople}" on-click="onManageOtherPeople_"
- hidden="[[!pageVisibility.people.manageUsers]]">
- </cr-link-row>
</if>
<if expr="not chromeos">
@@ -329,26 +334,26 @@
</template>
<if expr="chromeos">
- <template is="dom-if" if="[[!pageVisibility.people.lockScreen]]"
- route-path="/lockScreen">
- <settings-subpage
- page-title="[[selectLockScreenTitleString(hasPinLogin)]]"
- associated-control="[[$$('#lock-screen-subpage-trigger')]]">
- <settings-lock-screen
- prefs="{{prefs}}" auth-token="{{authToken_}}">
- </settings-lock-screen>
- </settings-subpage>
- </template>
- <template is="dom-if" if="[[fingerprintUnlockEnabled_
- && !pageVisibility.people.lockScreen]]">
- <template is="dom-if" route-path="/lockScreen/fingerprint" no-search>
- <settings-subpage page-title="$i18n{lockScreenFingerprintTitle}">
- <settings-fingerprint-list auth-token="[[authToken_]]">
- </settings-fingerprint-list>
+ <template is="dom-if" if="[[pageVisibility.people.lockScreen]]">
+ <template is="dom-if" route-path="/lockScreen">
+ <settings-subpage
+ page-title="[[selectLockScreenTitleString(hasPinLogin)]]"
+ associated-control="[[$$('#lock-screen-subpage-trigger')]]">
+ <settings-lock-screen
+ prefs="{{prefs}}" auth-token="{{authToken_}}">
+ </settings-lock-screen>
</settings-subpage>
</template>
+ <template is="dom-if" if="[[fingerprintUnlockEnabled_]]">
+ <template is="dom-if" route-path="/lockScreen/fingerprint" no-search>
+ <settings-subpage page-title="$i18n{lockScreenFingerprintTitle}">
+ <settings-fingerprint-list auth-token="[[authToken_]]">
+ </settings-fingerprint-list>
+ </settings-subpage>
+ </template>
+ </template>
</template>
- <template is="dom-if" if="[!pageVisibility.people.manageUsers]]">
+ <template is="dom-if" if="[[pageVisibility.people.manageUsers]]">
<template is="dom-if" route-path="/accounts">
<settings-subpage
associated-control=
diff --git a/chromium/chrome/browser/resources/settings/people_page/people_page.js b/chromium/chrome/browser/resources/settings/people_page/people_page.js
index f1ac47c8b17..cce39871d20 100644
--- a/chromium/chrome/browser/resources/settings/people_page/people_page.js
+++ b/chromium/chrome/browser/resources/settings/people_page/people_page.js
@@ -151,6 +151,15 @@ Polymer({
},
readOnly: true,
},
+
+ /** @private */
+ showParentalControls_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.valueExists('showParentalControls') &&
+ loadTimeData.getBoolean('showParentalControls');
+ },
+ },
// </if>
/** @private {!Map<string, string>} */
diff --git a/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html b/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html
index 4274c2b31d8..6636a96d3eb 100644
--- a/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.html
@@ -1,11 +1,12 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/chromeos/fingerprint/cr_fingerprint_progress_arc.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
+<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-iconset-svg/iron-iconset-svg.html">
<link rel="import" href="../icons.html">
@@ -15,21 +16,24 @@
<dom-module id="settings-setup-fingerprint-dialog">
<template>
<style include="settings-shared">
- #dialog {
- --cr-dialog-native: {
- min-width: 500px;
- width: 500px;
- };
+ #dialog::part(dialog) {
+ min-width: 500px;
+ width: 500px;
}
- .fingerprint-scanner-tablet {
+ .fingerprint-scanner-tablet-power-button {
background:
- url(chrome://theme/IDR_LOGIN_FINGERPRINT_SCANNER_TABLET_ANIMATION);
+ url(chrome://theme/IDR_LOGIN_FINGERPRINT_SCANNER_TABLET_POWER_BUTTON_ANIMATION);
}
- .fingerprint-scanner-laptop {
+ .fingerprint-scanner-laptop-bottom-right {
background:
- url(chrome://theme/IDR_LOGIN_FINGERPRINT_SCANNER_LAPTOP_ANIMATION);
+ url(chrome://theme/IDR_LOGIN_FINGERPRINT_SCANNER_LAPTOP_BOTTOM_RIGHT_ANIMATION);
+ }
+
+ .fingerprint-scanner-laptop-top-right {
+ background:
+ url(chrome://theme/IDR_LOGIN_FINGERPRINT_SCANNER_LAPTOP_TOP_RIGHT_ANIMATION);
}
#scannerLocation {
@@ -64,7 +68,7 @@
<span>[[getInstructionMessage_(step_, problemMessage_)]]</span>
</div>
<div id="scannerLocation" hidden="[[!showScannerLocation_(step_)]]"
- class$="[[getFingerprintScannerAnimationClass_()]]"
+ class$="[[fingerprintScannerAnimationClass_]]"
aria-label="$i18n{configureFingerprintScannerStepAriaLabel}"
aria-live="polite" >
</div>
@@ -73,15 +77,15 @@
</cr-fingerprint-progress-arc>
</div>
<div slot="button-container">
- <paper-button id="addAnotherButton" on-click="onAddAnotherFingerprint_"
+ <cr-button id="addAnotherButton" on-click="onAddAnotherFingerprint_"
hidden$="[[hideAddAnother_(step_, allowAddAnotherFinger)]]">
$i18n{configureFingerprintAddAnotherButton}
- </paper-button>
+ </cr-button>
- <paper-button id="closeButton"
+ <cr-button id="closeButton"
class$="[[getCloseButtonClass_(step_)]]" on-click="onClose_">
[[getCloseButtonText_(step_)]]
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js b/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js
index 2f770c9f4e5..57168253b54 100644
--- a/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js
+++ b/chromium/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js
@@ -14,6 +14,18 @@ settings.FingerprintSetupStep = {
READY: 3 // The scanner has read the fingerprint successfully.
};
+/**
+ * Fingerprint sensor locations corresponding to the FingerprintLocation
+ * enumerators in
+ * /chrome/browser/chromeos/login/quick_unlock/quick_unlock_utils.h
+ * @enum {number}
+ */
+settings.FingerprintLocation = {
+ TABLET_POWER_BUTTON: 0,
+ KEYBOARD_TOP_RIGHT: 1,
+ KEYBOARD_BOTTOM_RIGHT: 2,
+};
+
(function() {
/**
@@ -74,6 +86,31 @@ Polymer({
value: 0,
observer: 'onProgressChanged_',
},
+
+ /**
+ * This is used to display right animation for fingerprint sensor.
+ * @private {string}
+ */
+ fingerprintScannerAnimationClass_: {
+ type: String,
+ value: function() {
+ if (!loadTimeData.getBoolean('fingerprintUnlockEnabled')) {
+ return '';
+ }
+ const fingerprintLocation =
+ loadTimeData.getInteger('fingerprintReaderLocation');
+ switch (fingerprintLocation) {
+ case settings.FingerprintLocation.TABLET_POWER_BUTTON:
+ return 'fingerprint-scanner-tablet-power-button';
+ case settings.FingerprintLocation.KEYBOARD_TOP_RIGHT:
+ return 'fingerprint-scanner-laptop-top-right';
+ case settings.FingerprintLocation.KEYBOARD_BOTTOM_RIGHT:
+ return 'fingerprint-scanner-laptop-bottom-right';
+ }
+ assertNotReached();
+ },
+ readOnly: true,
+ },
},
/**
@@ -308,16 +345,5 @@ Polymer({
this.$.arc.setProgress(oldValue, newValue, newValue === 100);
},
- /**
- * Returns the class name for fingerprint scanner animation.
- * @private
- */
- getFingerprintScannerAnimationClass_: function() {
- if (loadTimeData.getBoolean('fingerprintUnlockEnabled') &&
- loadTimeData.getBoolean('isFingerprintReaderOnKeyboard')) {
- return 'fingerprint-scanner-laptop';
- }
- return 'fingerprint-scanner-tablet';
- },
});
})();
diff --git a/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.html b/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.html
index 9cfa9f130e5..ec1fb7827e3 100644
--- a/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.html
@@ -1,10 +1,10 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_components/chromeos/quick_unlock/setup_pin_keyboard.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../settings_shared_css.html">
@@ -33,13 +33,13 @@
</div>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelTap_">
+ <cr-button class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onPinSubmit_"
+ </cr-button>
+ <cr-button class="action-button" on-click="onPinSubmit_"
disabled$="[[!enableSubmit_]]">
<span>[[getContinueMessage_(isConfirmStep_)]]</span>
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.js b/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.js
index 7790181ab89..83e44e8ed17 100644
--- a/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.js
+++ b/chromium/chrome/browser/resources/settings/people_page/setup_pin_dialog.js
@@ -114,7 +114,7 @@ Polymer({
* @return {string}
*/
getContinueMessage_: function(isConfirmStep) {
- return this.i18n(isConfirmStep ? 'confirm' : 'configurePinContinueButton');
+ return this.i18n(isConfirmStep ? 'confirm' : 'continue');
},
});
diff --git a/chromium/chrome/browser/resources/settings/people_page/signout_dialog.html b/chromium/chrome/browser/resources/settings/people_page/signout_dialog.html
index 4a938428b72..74a1ee48418 100644
--- a/chromium/chrome/browser/resources/settings/people_page/signout_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/signout_dialog.html
@@ -1,11 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="profile_info_browser_proxy.html">
<link rel="import" href="sync_browser_proxy.html">
<link rel="import" href="../settings_shared_css.html">
@@ -30,35 +30,33 @@
padding: 16px 0;
}
- cr-dialog {
- --cr-dialog-body: {
- /* Add space for the link focus ring. See https://crbug.com/916939. */
- padding-bottom: 2px;
- };
+ #dialog-body {
+ /* Add space for the link focus ring. See https://crbug.com/916939. */
+ padding-bottom: 2px;
}
</style>
<cr-dialog id="dialog" ignore-enter-key close-text="$i18n{close}">
<div slot="title">$i18n{syncDisconnectTitle}</div>
- <div slot="body">
+ <div id="dialog-body" slot="body">
<div inner-h-t-m-l="[[
getDisconnectExplanationHtml_(syncStatus.domain)]]">
</div>
</div>
<div slot="button-container">
- <paper-button id="disconnectCancel" class="cancel-button"
+ <cr-button id="disconnectCancel" class="cancel-button"
on-click="onDisconnectCancel_" >
$i18n{cancel}
- </paper-button>
- <paper-button id="disconnectConfirm" class="action-button"
+ </cr-button>
+ <cr-button id="disconnectConfirm" class="action-button"
hidden="[[syncStatus.domain]]" on-click="onDisconnectConfirm_">
$i18n{syncDisconnect}
- </paper-button>
- <paper-button id="disconnectManagedProfileConfirm"
+ </cr-button>
+ <cr-button id="disconnectManagedProfileConfirm"
class="action-button" hidden="[[!syncStatus.domain]]"
on-click="onDisconnectConfirm_">
$i18n{syncDisconnectConfirm}
- </paper-button>
+ </cr-button>
</div>
<if expr="(not chromeos and is_posix) or is_win or is_macosx">
<template is="dom-if" if="[[!syncStatus.domain]]">
diff --git a/chromium/chrome/browser/resources/settings/people_page/sync_account_control.html b/chromium/chrome/browser/resources/settings/people_page/sync_account_control.html
index 1bc6162d81a..e299214c6b6 100644
--- a/chromium/chrome/browser/resources/settings/people_page/sync_account_control.html
+++ b/chromium/chrome/browser/resources/settings/people_page/sync_account_control.html
@@ -1,12 +1,12 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="profile_info_browser_proxy.html">
<link rel="import" href="sync_browser_proxy.html">
<link rel="import" href="../i18n_setup.html">
@@ -78,13 +78,14 @@
right: initial;
}
- :host-context([dark]) #sync-icon-container {
- background: var(--google-green-refresh-300);
- border-color: var(--google-grey-900);
+ @media (prefers-color-scheme: dark) {
+ #sync-icon-container {
+ background: var(--google-green-refresh-300);
+ border-color: var(--google-grey-900);
+ }
}
- #sync-icon-container.sync-problem,
- :host-context([dark]) #sync-icon-container.sync-problem {
+ #sync-icon-container.sync-problem {
background: var(--settings-error-color);
}
@@ -92,16 +93,20 @@
background: var(--google-blue-500);
}
- :host-context([dark]) #sync-icon-container.sync-paused {
- background: var(--google-blue-refresh-300);
+ @media (prefers-color-scheme: dark) {
+ #sync-icon-container.sync-paused {
+ background: var(--google-blue-refresh-300);
+ }
}
#sync-icon-container.sync-disabled {
background: var(--google-grey-400);
}
- :host-context([dark]) #sync-icon-container.sync-disabled {
- background: var(--google-grey-refresh-500);
+ @media (prefers-color-scheme: dark) {
+ #sync-icon-container.sync-disabled {
+ background: var(--google-grey-refresh-500);
+ }
}
#sync-icon-container iron-icon {
@@ -121,42 +126,34 @@
background-size: 100% auto;
display: none;
padding-top: calc(120 / 680 * 100%); /* Keep background ratio. */
-
- @apply --promo-banner;
}
- :host-context([dark]) #banner {
- background-image: url(../images/sync_banner_dark.svg);
+ @media (prefers-color-scheme: dark) {
+ #banner {
+ background-image: url(../images/sync_banner_dark.svg);
+ }
}
:host([showing-promo]) #banner {
display: block;
}
-
- :host([showing-promo]) #promo-title {
- @apply --promo-title;
- }
-
- :host([showing-promo]) #promo-description {
- @apply --promo-description;
- }
</style>
- <div id="banner" hidden="[[syncStatus.signedIn]]"></div>
+ <div id="banner" hidden="[[syncStatus.signedIn]]" part="banner"></div>
<div class$="settings-box first
[[getPromoHeaderClass_(subLabel_)]]"
id="promo-header" hidden="[[syncStatus.signedIn]]">
<div class="start settings-box-text">
- <div id="promo-title">
+ <div id="promo-title" part="title">
[[getLabel_(promoLabelWithAccount,
promoLabelWithNoAccount, shownAccount_)]]
</div>
<div class="secondary">[[subLabel_]]</div>
</div>
- <paper-button class="action-button" on-click="onSigninTap_"
+ <cr-button class="action-button" on-click="onSigninTap_"
disabled="[[syncStatus.firstSetupInProgress]]" id="sign-in"
hidden="[[shouldShowAvatarRow_]]">
$i18n{peopleSignIn}
- </paper-button>
+ </cr-button>
</div>
<template is="dom-if" if="[[shouldShowAvatarRow_]]">
<div class="settings-box first two-line" id="avatar-row">
@@ -194,32 +191,30 @@
id="dropdown-arrow" aria-label="$i18n{useAnotherAccount}">
</cr-icon-button>
<div class="separator" hidden="[[syncStatus.signedIn]]"></div>
- <paper-button id="sync-button" class="action-button"
+ <cr-button id="sync-button" class="action-button"
hidden="[[syncStatus.signedIn]]" on-click="onSyncButtonTap_"
disabled="[[syncStatus.firstSetupInProgress]]">
$i18n{peopleSignIn}
- </paper-button>
- <paper-button id="turn-off" class="secondary-button"
+ </cr-button>
+ <cr-button id="turn-off"
hidden="[[!shouldShowTurnOffButton_(syncStatus.signedIn,
showSetupButtons_)]]"
on-click="onTurnOffButtonTap_"
disabled="[[syncStatus.firstSetupInProgress]]">
$i18n{turnOffSync}
- </paper-button>
- <paper-button id="sync-error-button" class="action-button"
+ </cr-button>
+ <cr-button id="sync-error-button" class="action-button"
hidden="[[!shouldShowErrorActionButton_(syncStatus,
showSetupButtons_)]]"
on-click="onErrorButtonTap_"
disabled="[[syncStatus.firstSetupInProgress]]">
[[syncStatus.statusActionText]]
- </paper-button>
+ </cr-button>
<div id="setup-buttons" hidden="[[!showSetupButtons_]]">
- <paper-button class="secondary-button" on-click="onSetupCancel_">
- $i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onSetupConfirm_">
+ <cr-button on-click="onSetupCancel_">$i18n{cancel}</cr-button>
+ <cr-button class="action-button" on-click="onSetupConfirm_">
$i18n{confirm}
- </paper-button>
+ </cr-button>
</div>
</div>
<template is="dom-if" if="[[!syncStatus.signedIn]]" restamp>
diff --git a/chromium/chrome/browser/resources/settings/people_page/sync_page.html b/chromium/chrome/browser/resources/settings/people_page/sync_page.html
index 7bf0489fbeb..51b1cf194c8 100644
--- a/chromium/chrome/browser/resources/settings/people_page/sync_page.html
+++ b/chromium/chrome/browser/resources/settings/people_page/sync_page.html
@@ -4,14 +4,15 @@
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/cr_elements/cr_radio_button/cr_radio_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_radio_group/cr_radio_group.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="sync_browser_proxy.html">
<link rel="import" href="sync_controls.html">
<link rel="import" href="../privacy_page/personalization_options.html">
@@ -26,11 +27,7 @@
<dom-module id="settings-sync-page">
<template>
- <style include="settings-shared iron-flex">
- h2 {
- @apply --cr-title-text;
- }
-
+ <style include="cr-shared-style settings-shared iron-flex">
#sync-separator {
border-bottom: var(--cr-separator-line);
}
@@ -137,11 +134,11 @@
placeholder="$i18n{passphrasePlaceholder}"
error-message="$i18n{incorrectPassphraseError}"
on-keypress="onSubmitExistingPassphraseTap_">
- <paper-button id="submitExistingPassphrase" slot="suffix"
+ <cr-button id="submitExistingPassphrase" slot="suffix"
on-click="onSubmitExistingPassphraseTap_"
class="action-button" disabled="[[!existingPassphrase_]]">
$i18n{submitPassphraseButton}
- </paper-button>
+ </cr-button>
</cr-input>
</div>
<div id="passphraseRecoverHint" class="list-item">
@@ -154,7 +151,7 @@
<div id="sync-section" hidden="[[syncSectionDisabled_]]">
<div class="settings-box first" hidden="[[!unifiedConsentEnabled]]">
- <h2 class="start">$i18n{sync}</h2>
+ <h2 class="cr-title-text start">$i18n{sync}</h2>
</div>
<div id="[[pages_.SPINNER]]" class="settings-box first settings-box-text"
@@ -184,11 +181,11 @@
placeholder="$i18n{passphrasePlaceholder}"
error-message="$i18n{incorrectPassphraseError}"
on-keypress="onSubmitExistingPassphraseTap_">
- <paper-button id="submitExistingPassphrase" slot="suffix"
+ <cr-button id="submitExistingPassphrase" slot="suffix"
on-click="onSubmitExistingPassphraseTap_"
class="action-button" disabled="[[!existingPassphrase_]]">
$i18n{submitPassphraseButton}
- </paper-button>
+ </cr-button>
</cr-input>
</div>
<div id="passphraseRecoverHint" class="list-item">
@@ -306,12 +303,12 @@
placeholder="$i18n{passphraseConfirmationPlaceholder}"
error-message="$i18n{mismatchedPassphraseError}">
</cr-input>
- <paper-button id="saveNewPassphrase"
+ <cr-button id="saveNewPassphrase"
on-click="onSaveNewPassphraseTap_" class="action-button"
disabled="[[!isSaveNewPassphraseEnabled_(passphrase_,
confirmation_)]]">
$i18n{save}
- </paper-button>
+ </cr-button>
</div>
</div>
</template>
@@ -322,7 +319,9 @@
<template is="dom-if" if="[[unifiedConsentEnabled]]">
<div class="settings-box first">
- <h2>$i18n{nonPersonalizedServicesSectionLabel}</h2>
+ <h2 class="cr-title-text">
+ $i18n{nonPersonalizedServicesSectionLabel}
+ </h2>
</div>
<settings-personalization-options class="list-frame" prefs="{{prefs}}"
page-visibility="[[pageVisibility]]" sync-status="[[syncStatus]]"
@@ -337,14 +336,14 @@
<div slot="title">$i18n{syncSetupCancelDialogTitle}</div>
<div slot="body">$i18n{syncSetupCancelDialogBody}</div>
<div slot="button-container">
- <paper-button class="cancel-button"
+ <cr-button class="cancel-button"
on-click="onSetupCancelDialogBack_">
$i18n{back}
- </paper-button>
- <paper-button class="action-button"
+ </cr-button>
+ <cr-button class="action-button"
on-click="onSetupCancelDialogConfirm_">
$i18n{cancelSync}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
@@ -352,9 +351,9 @@
<template is="dom-if" if="[[!unifiedConsentEnabled]]">
<cr-toast id="toast" open="[[syncStatus.firstSetupInProgress]]">
<div>$i18n{syncWillStart}</div>
- <paper-button on-click="onSyncSetupCancel_">
+ <cr-button on-click="onSyncSetupCancel_">
$i18n{cancelSync}
- </paper-button>
+ </cr-button>
</cr-toast>
</template>
</if>
diff --git a/chromium/chrome/browser/resources/settings/people_page/sync_page.js b/chromium/chrome/browser/resources/settings/people_page/sync_page.js
index f1f13ade17c..fd28dad676a 100644
--- a/chromium/chrome/browser/resources/settings/people_page/sync_page.js
+++ b/chromium/chrome/browser/resources/settings/people_page/sync_page.js
@@ -444,7 +444,7 @@ Polymer({
assert(this.creatingNewPassphrase_);
// Ignore events on irrelevant elements or with irrelevant keys.
- if (e.target.tagName != 'PAPER-BUTTON' && e.target.tagName != 'CR-INPUT') {
+ if (e.target.tagName != 'CR-BUTTON' && e.target.tagName != 'CR-INPUT') {
return;
}
if (e.type == 'keypress' && e.key != 'Enter') {
diff --git a/chromium/chrome/browser/resources/settings/people_page/user_list.html b/chromium/chrome/browser/resources/settings/people_page/user_list.html
index 34231952976..f6ba5eba5bd 100644
--- a/chromium/chrome/browser/resources/settings/people_page/user_list.html
+++ b/chromium/chrome/browser/resources/settings/people_page/user_list.html
@@ -36,6 +36,11 @@
.user-info {
padding-inline-start: 20px;
}
+
+ :host([disabled]) .user-list {
+ opacity: var(--cr-disabled-opacity);
+ overflow: auto;
+ }
</style>
<div class="user-list" scrollable>
<template is="dom-repeat" items="[[users_]]">
diff --git a/chromium/chrome/browser/resources/settings/people_page/user_list.js b/chromium/chrome/browser/resources/settings/people_page/user_list.js
index 8da449a46d0..66786887296 100644
--- a/chromium/chrome/browser/resources/settings/people_page/user_list.js
+++ b/chromium/chrome/browser/resources/settings/people_page/user_list.js
@@ -42,6 +42,7 @@ Polymer({
disabled: {
type: Boolean,
value: false,
+ reflectToAttribute: true,
}
},
diff --git a/chromium/chrome/browser/resources/settings/people_page/users_add_user_dialog.html b/chromium/chrome/browser/resources/settings/people_page/users_add_user_dialog.html
index 7915b03403e..e1caa97fc46 100644
--- a/chromium/chrome/browser/resources/settings/people_page/users_add_user_dialog.html
+++ b/chromium/chrome/browser/resources/settings/people_page/users_add_user_dialog.html
@@ -1,9 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/html/assert.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="../settings_vars_css.html">
@@ -24,13 +24,13 @@
</cr-input>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelTap_">
+ <cr-button class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button on-click="addUser_" class="action-button"
+ </cr-button>
+ <cr-button on-click="addUser_" class="action-button"
disabled$="[[!canAddUser_(isEmail_, isEmpty_)]]">
$i18n{add}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/people_page/users_page.html b/chromium/chrome/browser/resources/settings/people_page/users_page.html
index afdbbe7dfbc..47c03a09a34 100644
--- a/chromium/chrome/browser/resources/settings/people_page/users_page.html
+++ b/chromium/chrome/browser/resources/settings/people_page/users_page.html
@@ -1,11 +1,10 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/action_link.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../controls/settings_toggle_button.html">
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="user_list.html">
@@ -23,13 +22,13 @@
margin-inline-start: var(--cr-section-indent-padding);
}
- #add-user-button a {
- outline: none;
- }
-
.block {
display: block;
}
+
+ #header {
+ padding-inline-start: 20px;
+ }
</style>
<div class="settings-box" hidden$="[[!isWhitelistManaged_]]">
$i18n{settingsManagedLabel}
diff --git a/chromium/chrome/browser/resources/settings/printing_page/BUILD.gn b/chromium/chrome/browser/resources/settings/printing_page/BUILD.gn
index 889e4b1ce6a..0f0acd7af8e 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/printing_page/BUILD.gn
@@ -15,10 +15,15 @@ js_type_check("closure_compile") {
":cups_add_printer_dialog",
":cups_add_printer_dialog_elements",
":cups_edit_printer_dialog",
+ ":cups_nearby_printers",
":cups_printer_dialog_util",
+ ":cups_printer_types",
":cups_printers",
":cups_printers_browser_proxy",
+ ":cups_printers_entry",
+ ":cups_printers_entry_list",
":cups_printers_list",
+ ":cups_saved_printers",
":printing_browser_proxy",
]
}
@@ -30,59 +35,6 @@ js_library("cloud_printers") {
]
}
-js_library("cups_add_printer_dialog") {
- deps = [
- ":cups_printers_browser_proxy",
- "//ui/webui/resources/js:load_time_data",
- "//ui/webui/resources/js:web_ui_listener_behavior",
- ]
-}
-
-js_library("cups_add_printer_dialog_elements") {
- deps = [
- ":cups_printers_browser_proxy",
- ]
-}
-
-js_library("cups_printer_dialog_util") {
- deps = [
- "//ui/webui/resources/js:cr",
- ]
-}
-
-js_library("cups_edit_printer_dialog") {
- deps = [
- "//ui/webui/resources/cr_elements:cr_scrollable_behavior",
- ]
-}
-
-js_library("cups_printers") {
- deps = [
- ":cups_printers_browser_proxy",
- "//ui/webui/resources/cr_elements/cr_toast:cr_toast",
- "//ui/webui/resources/js:assert",
- "//ui/webui/resources/js:load_time_data",
- "//ui/webui/resources/js:web_ui_listener_behavior",
- "//ui/webui/resources/js/cr/ui:focus_without_ink",
- ]
- externs_list = [ "$externs_path/networking_private.js" ]
-}
-
-js_library("cups_printers_browser_proxy") {
- deps = [
- "//ui/webui/resources/js:cr",
- ]
-}
-
-js_library("cups_printers_list") {
- deps = [
- ":cups_printers_browser_proxy",
- "//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu",
- "//ui/webui/resources/js:cr",
- "//ui/webui/resources/js:icon",
- ]
-}
-
js_library("printing_browser_proxy") {
deps = [
"//ui/webui/resources/js:cr",
@@ -91,11 +43,113 @@ js_library("printing_browser_proxy") {
js_library("printing_page") {
deps = [
- ":cups_printers_browser_proxy",
":printing_browser_proxy",
"..:route",
"../settings_page:settings_animated_pages",
"//ui/webui/resources/js:assert",
"//ui/webui/resources/js:load_time_data",
]
+ if (is_chromeos) {
+ deps += [ ":cups_printers_browser_proxy" ]
+ }
+}
+
+if (is_chromeos) {
+ js_library("cups_add_printer_dialog") {
+ deps = [
+ ":cups_printers_browser_proxy",
+ "//ui/webui/resources/js:load_time_data",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
+ ]
+ }
+
+ js_library("cups_add_printer_dialog_elements") {
+ deps = [
+ ":cups_printers_browser_proxy",
+ ]
+ }
+
+ js_library("cups_edit_printer_dialog") {
+ deps = [
+ "//ui/webui/resources/cr_components/chromeos/network:mojo_interface_provider",
+ "//ui/webui/resources/cr_elements:cr_scrollable_behavior",
+ "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior",
+ "//ui/webui/resources/js/chromeos:onc_mojo",
+ ]
+ }
+
+ js_library("cups_nearby_printers") {
+ deps = [
+ ":cups_printer_types",
+ ":cups_printers_browser_proxy",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
+ ]
+ }
+
+ js_library("cups_printer_types") {
+ deps = [
+ ":cups_printers_browser_proxy",
+ ]
+ }
+
+ js_library("cups_printer_dialog_util") {
+ deps = [
+ "//ui/webui/resources/js:cr",
+ ]
+ }
+
+ js_library("cups_printers") {
+ deps = [
+ ":cups_nearby_printers",
+ ":cups_printers_browser_proxy",
+ ":cups_saved_printers",
+ "//ui/webui/resources/cr_components/chromeos/network:mojo_interface_provider",
+ "//ui/webui/resources/cr_elements/chromeos/network:cr_network_listener_behavior",
+ "//ui/webui/resources/cr_elements/cr_toast:cr_toast",
+ "//ui/webui/resources/js:assert",
+ "//ui/webui/resources/js:load_time_data",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
+ "//ui/webui/resources/js/chromeos:onc_mojo",
+ "//ui/webui/resources/js/cr/ui:focus_without_ink",
+ ]
+ }
+
+ js_library("cups_printers_browser_proxy") {
+ deps = [
+ "//ui/webui/resources/js:cr",
+ ]
+ }
+
+ js_library("cups_printers_entry") {
+ deps = [
+ ":cups_printer_types",
+ ":cups_printers_browser_proxy",
+ ]
+ }
+
+ js_library("cups_printers_entry_list") {
+ deps = [
+ ":cups_printer_types",
+ ":cups_printers_browser_proxy",
+ "//ui/webui/resources/js:list_property_update_behavior",
+ ]
+ }
+
+ js_library("cups_printers_list") {
+ deps = [
+ ":cups_printers_browser_proxy",
+ "//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu",
+ "//ui/webui/resources/js:cr",
+ "//ui/webui/resources/js:icon",
+ ]
+ }
+
+ js_library("cups_saved_printers") {
+ deps = [
+ ":cups_printer_types",
+ ":cups_printers_browser_proxy",
+ "//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
+ ]
+ }
}
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.html b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.html
index 8da4a0c0547..55b32a67b00 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.html
@@ -1,10 +1,12 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/cr_elements/cr_searchable_drop_down/cr_searchable_drop_down.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="cups_add_printer_dialog_elements.html">
@@ -14,7 +16,7 @@
<dom-module id="add-printer-discovery-dialog">
<template>
- <style include="cups-printer-shared">
+ <style include="cr-shared-style cups-printer-shared">
add-printer-list {
max-height: 310px;
overflow-y: auto;
@@ -52,21 +54,20 @@
</div>
<div slot="dialog-buttons">
<div> <!-- Left group -->
- <paper-button id="manuallyAddPrinterButton" class="secondary-button"
+ <cr-button id="manuallyAddPrinterButton"
on-click="switchToManualAddDialog_">
$i18n{manuallyAddPrinterButtonText}
- </paper-button>
+ </cr-button>
</div>
<div> <!-- Right group -->
- <paper-button class="cancel-button secondary-button"
- on-click="onCancelTap_">
+ <cr-button class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" id="addPrinterButton"
+ </cr-button>
+ <cr-button class="action-button" id="addPrinterButton"
disabled="[[!canAddPrinter_(selectedPrinter)]]"
on-click="switchToConfiguringDialog_">
$i18n{addPrinterButtonText}
- </paper-button>
+ </cr-button>
</div>
</div>
</add-printer-dialog>
@@ -75,39 +76,17 @@
<dom-module id="add-printer-manually-dialog">
<template>
- <style include="cups-printer-shared">
- #discoverPrintersButton {
- margin-inline-end: 153px;
- }
-
- .search-printer-box {
- margin-top: 18px;
- }
-
- .search-printer-box paper-spinner-lite {
- --paper-spinner-stroke-width: 2px;
- height: 15px;
- margin-inline-end: 3px;
- margin-inline-start: 20px;
- width: 15px;
- }
-
- .search-printer-box .spinner-comment {
- color: var(--google-grey-700);
- }
-
- .printer-not-found {
- background-color: var(--paper-yellow-100);
- padding: 10px 20px;
- }
-
- .printer-found {
- background-color: var(--paper-green-100);
- padding: 10px 20px;
- }
- </style>
+ <style include="cups-printer-shared"></style>
<add-printer-dialog>
<div slot="dialog-title">$i18n{addPrintersManuallyTitle}</div>
+ <div id="general-error-container" hidden="[[!errorText_]]">
+ <div id="general-error">
+ <iron-icon id="general-error-icon" icon="cr:warning"></iron-icon>
+ <div id="general-error-message">
+ [[errorText_]]
+ </div>
+ </div>
+ </div>
<div slot="dialog-body">
<div class="settings-box first two-line">
<cr-input class="printer-name-input" autofocus
@@ -117,12 +96,15 @@
</div>
<div class="settings-box two-line">
<cr-input id="printerAddressInput" label="$i18n{printerAddress}"
- value="{{newPrinter.printerAddress}}" maxlength=63>
+ value="{{newPrinter.printerAddress}}" maxlength=63
+ error-message="$i18n{ippPrinterUnreachable}">
</cr-input>
</div>
<div class="settings-box two-line">
<div class="start">
- <div id="printerProtocol" class="label">$i18n{printerProtocol}</div>
+ <div id="printerProtocol" class="cr-form-field-label">
+ $i18n{printerProtocol}
+ </div>
<div class="secondary">
<select class="md-select" aria-labelledby="printerProtocol"
value="[[newPrinter.printerProtocol]]"
@@ -139,28 +121,27 @@
</div>
</div>
<div class="settings-box two-line">
- <cr-input placeholder="ipp/print" label="$i18n{printerQueue}"
+ <cr-input label="$i18n{printerQueue}"
value="{{newPrinter.printerQueue}}" maxlength=64>
</cr-input>
</div>
</div>
<div slot="dialog-buttons">
<div> <!-- Left group -->
- <paper-button class="secondary-button"
- on-click="switchToDiscoveryDialog_">
+ <cr-button on-click="switchToDiscoveryDialog_"
+ hidden="[[enableUpdatedUi]]">
$i18n{discoverPrintersButtonText}
- </paper-button>
+ </cr-button>
</div>
<div> <!-- Right group -->
- <paper-button class="cancel-button secondary-button"
- on-click="onCancelTap_">
+ <cr-button class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button id="addPrinterButton" class="action-button"
+ </cr-button>
+ <cr-button id="addPrinterButton" class="action-button"
on-click="addPressed_"
- disabled="[[!canAddPrinter_(newPrinter.*)]]">
+ disabled="[[!canAddPrinter_(newPrinter.*, inProgress_)]]">
$i18n{addPrinterButtonText}
- </paper-button>
+ </cr-button>
</div>
</div>
</add-printer-dialog>
@@ -177,7 +158,16 @@
}
</style>
<add-printer-dialog>
- <div slot="dialog-title">$i18n{manufacturerAndModelDialogTitle}</div>
+ <div slot="dialog-title">$i18n{manufacturerAndModelDialogTitle}
+ <div id="general-error-container" hidden="[[!errorText_]]">
+ <div id="general-error">
+ <iron-icon id="general-error-icon" icon="cr:warning"></iron-icon>
+ <div id="general-error-message">
+ [[errorText_]]
+ </div>
+ </div>
+ </div>
+ </div>
<div slot="dialog-body">
<div class="subtext" id="makeModelTextInfo">
<span>[[getManufacturerAndModelSubtext_(activePrinter.*)]]
@@ -200,7 +190,7 @@
value="{{activePrinter.ppdModel}}">
</cr-searchable-drop-down>
</div>
- <div id="ppdLabel" class="field-label">
+ <div id="ppdLabel" class="cr-form-field-label">
<span>$i18n{selectDriver}</span>
<a href="$i18n{printingCUPSPrintPpdLearnMoreUrl}" target="_blank">
$i18n{learnMore}
@@ -211,26 +201,25 @@
aria-labelledby="ppdLabel" invalid="[[invalidPPD_]]"
error-message="$i18n{selectDriverErrorMessage}" tabindex="-1">
</cr-input>
- <paper-button class="browse-button" on-click="onBrowseFile_">
+ <cr-button class="browse-button" on-click="onBrowseFile_">
$i18n{selectDriverButtonText}
- </paper-button>
+ </cr-button>
</div>
<div class="eula" id="eulaUrl" hidden="[[!eulaUrl_]]">
<a href="[[eulaUrl_]]" target="_blank">$i18n{printerEulaNotice}</a>
</div>
</div>
<div slot="dialog-buttons">
- <paper-button class="cancel-button secondary-button"
- on-click="onCancelTap_">
+ <cr-button class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" id="addPrinterButton"
+ </cr-button>
+ <cr-button class="action-button" id="addPrinterButton"
disabled="[[!canAddPrinter_(activePrinter.ppdManufacturer,
activePrinter.ppdModel,
activePrinter.printerPPDPath)]]"
- on-click="switchToConfiguringDialog_">
+ on-click="addPrinter_">
$i18n{addPrinterButtonText}
- </paper-button>
+ </cr-button>
</div>
</add-printer-dialog>
</template>
@@ -251,10 +240,9 @@
<div id="configuringMessage">$i18n{printerConfiguringMessage}</div>
</div>
<div slot="dialog-buttons">
- <paper-button class="cancel-button secondary-button"
- on-click="onCloseConfiguringTap_">
+ <cr-button class="cancel-button" on-click="onCloseConfiguringTap_">
$i18n{close}
- </paper-button>
+ </cr-button>
</div>
</add-printer-dialog>
</template>
@@ -272,7 +260,8 @@
<!-- Manually Add Printer Dialog -->
<template is="dom-if" if="[[showManuallyAddDialog_]]" restamp>
- <add-printer-manually-dialog new-printer="{{newPrinter}}">
+ <add-printer-manually-dialog new-printer="{{newPrinter}}"
+ enable-updated-ui="[[enableUpdatedUi]]">
</add-printer-manually-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js
index 8bf6fb7a183..c63057baedb 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js
@@ -56,7 +56,7 @@ function getEmptyPrinter_() {
},
printerPpdReferenceResolved: false,
printerProtocol: 'ipp',
- printerQueue: '',
+ printerQueue: 'ipp/print',
printerStatus: '',
};
}
@@ -70,6 +70,7 @@ Polymer({
/** @type {!Array<!CupsPrinterInfo>|undefined} */
discoveredPrinters: {
type: Array,
+ value: () => [],
},
/** @type {!CupsPrinterInfo} */
@@ -82,14 +83,25 @@ Polymer({
type: Boolean,
value: true,
},
+
+ /**
+ * TODO(jimmyxgong): Remove this feature flag conditional once feature
+ * is launched.
+ * @private
+ */
+ enableUpdatedUi: Boolean,
},
/** @override */
ready: function() {
+ if (this.enableUpdatedUi) {
+ return;
+ }
+
settings.CupsPrintersBrowserProxyImpl.getInstance()
.startDiscoveringPrinters();
this.addWebUIListener(
- 'on-printer-discovered', this.onPrinterDiscovered_.bind(this));
+ 'on-nearby-printers-changed', this.onNearbyPrintersChanged_.bind(this));
this.addWebUIListener(
'on-printer-discovery-done', this.onPrinterDiscoveryDone_.bind(this));
},
@@ -99,12 +111,14 @@ Polymer({
},
/**
- * @param {!Array<!CupsPrinterInfo>} printers
+ * @param {!Array<!CupsPrinterInfo>} automaticPrinters
+ * @param {!Array<!CupsPrinterInfo>} discoveredPrinters
* @private
*/
- onPrinterDiscovered_: function(printers) {
+ onNearbyPrintersChanged_: function(automaticPrinters, discoveredPrinters) {
this.discovering_ = true;
- this.discoveredPrinters = printers;
+ this.set(
+ 'discoveredPrinters', automaticPrinters.concat(discoveredPrinters));
},
/** @private */
@@ -127,25 +141,40 @@ Polymer({
/** @private */
switchToManualAddDialog_: function() {
- this.stopDiscoveringPrinters_();
// We're abandoning discovery in favor of manual specification, so
// drop the selection if one exists.
this.selectedPrinter = getEmptyPrinter_();
this.close();
this.fire('open-manually-add-printer-dialog');
+
+ if (this.enableUpdatedUi) {
+ return;
+ }
+
+ this.stopDiscoveringPrinters_();
},
/** @private */
onCancelTap_: function() {
- this.stopDiscoveringPrinters_();
this.close();
+
+ if (this.enableUpdatedUi) {
+ return;
+ }
+
+ this.stopDiscoveringPrinters_();
},
/** @private */
switchToConfiguringDialog_: function() {
- this.stopDiscoveringPrinters_();
this.close();
this.fire('open-configuring-printer-dialog');
+
+ if (this.enableUpdatedUi) {
+ return;
+ }
+
+ this.stopDiscoveringPrinters_();
},
/**
@@ -164,8 +193,34 @@ Polymer({
properties: {
/** @type {!CupsPrinterInfo} */
newPrinter: {type: Object, notify: true, value: getEmptyPrinter_},
+
+ /** @private */
+ addPrinterInProgress_: {
+ type: Boolean,
+ value: false,
+ },
+
+ /**
+ * The error text to be displayed on the dialog.
+ * @private
+ */
+ errorText_: {
+ type: String,
+ value: '',
+ },
+
+ /**
+ * TODO(jimmyxgong): Remove this feature flag conditional once feature
+ * is launched.
+ * @private
+ */
+ enableUpdatedUi: Boolean,
},
+ observers: [
+ 'printerInfoChanged_(newPrinter.*)',
+ ],
+
/** @private */
switchToDiscoveryDialog_: function() {
this.newPrinter = getEmptyPrinter_();
@@ -178,14 +233,93 @@ Polymer({
this.$$('add-printer-dialog').close();
},
+ /**
+ * Handler for addCupsPrinter success.
+ * @param {!PrinterSetupResult} result
+ * @private
+ * */
+ onAddPrinterSucceeded_: function(result) {
+ this.fire(
+ 'show-cups-printer-toast',
+ {resultCode: result, printerName: this.newPrinter.printerName});
+ this.$$('add-printer-dialog').close();
+ },
+
+ /**
+ * Handler for addCupsPrinter failure.
+ * @param {*} result
+ * @private
+ * */
+ onAddPrinterFailed_: function(result) {
+ this.errorText_ = settings.printing.getErrorText(
+ /** @type {PrinterSetupResult} */ (result));
+ },
+
+ /**
+ * Handler for getPrinterInfo success.
+ * @param {!PrinterMakeModel} info
+ * @private
+ * */
+ onPrinterFound_: function(info) {
+ const newPrinter =
+ /** @type {CupsPrinterInfo} */ (Object.assign({}, this.newPrinter));
+
+ newPrinter.printerManufacturer = info.manufacturer;
+ newPrinter.printerModel = info.model;
+ newPrinter.printerMakeAndModel = info.makeAndModel;
+ newPrinter.printerPpdReference.userSuppliedPpdUrl =
+ info.ppdRefUserSuppliedPpdUrl;
+ newPrinter.printerPpdReference.effectiveMakeAndModel =
+ info.ppdRefEffectiveMakeAndModel;
+ newPrinter.printerPpdReference.autoconf = info.autoconf;
+ newPrinter.printerPpdReferenceResolved = info.ppdReferenceResolved;
+
+ this.newPrinter = newPrinter;
+
+
+ // Add the printer if it's configurable. Otherwise, forward to the
+ // manufacturer dialog.
+ if (this.newPrinter.printerPpdReferenceResolved) {
+ settings.CupsPrintersBrowserProxyImpl.getInstance()
+ .addCupsPrinter(this.newPrinter)
+ .then(
+ this.onAddPrinterSucceeded_.bind(this),
+ this.onAddPrinterFailed_.bind(this));
+ } else {
+ this.$$('add-printer-dialog').close();
+ this.fire('open-manufacturer-model-dialog');
+ }
+ },
+
+ /**
+ * Handler for getPrinterInfo failure.
+ * @param {*} result a PrinterSetupResult with an error code indicating why
+ * getPrinterInfo failed.
+ * @private
+ */
+ infoFailed_: function(result) {
+ this.addPrinterInProgress_ = false;
+ if (result == PrinterSetupResult.PRINTER_UNREACHABLE) {
+ this.$.printerAddressInput.invalid = true;
+ return;
+ }
+ this.errorText_ = settings.printing.getErrorText(
+ /** @type {PrinterSetupResult} */ (result));
+ },
+
/** @private */
addPressed_: function() {
- // Set the default printer queue to be "ipp/print".
- if (!this.newPrinter.printerQueue) {
- this.set('newPrinter.printerQueue', 'ipp/print');
+ this.addPrinterInProgress_ = true;
+
+ if (this.newPrinter.printerProtocol == 'ipp' ||
+ this.newPrinter.printerProtocol == 'ipps') {
+ settings.CupsPrintersBrowserProxyImpl.getInstance()
+ .getPrinterInfo(this.newPrinter)
+ .then(this.onPrinterFound_.bind(this), this.infoFailed_.bind(this));
+ } else {
+ this.$$('add-printer-dialog').close();
+ this.fire('open-manufacturer-model-dialog');
}
- this.$$('add-printer-dialog').close();
- this.fire('open-configuring-printer-dialog');
},
/**
@@ -201,8 +335,16 @@ Polymer({
* @private
*/
canAddPrinter_: function() {
- return settings.printing.isNameAndAddressValid(this.newPrinter);
+ return !this.addPrinterInProgress_ &&
+ settings.printing.isNameAndAddressValid(this.newPrinter);
+ },
+
+ /** @private */
+ printerInfoChanged_: function() {
+ this.$.printerAddressInput.invalid = false;
+ this.errorText_ = '';
},
+
});
Polymer({
@@ -244,6 +386,15 @@ Polymer({
type: String,
value: '',
},
+
+ /**
+ * The error text to be displayed on the dialog.
+ * @private
+ */
+ errorText_: {
+ type: String,
+ value: '',
+ },
},
observers: [
@@ -263,6 +414,28 @@ Polymer({
},
/**
+ * Handler for addCupsPrinter success.
+ * @param {!PrinterSetupResult} result
+ * @private
+ * */
+ onPrinterAddedSucceeded_: function(result) {
+ this.fire(
+ 'show-cups-printer-toast',
+ {resultCode: result, printerName: this.activePrinter.printerName});
+ this.close();
+ },
+
+ /**
+ * Handler for addCupsPrinter failure.
+ * @param {*} result
+ * @private
+ * */
+ onPrinterAddedFailed_: function(result) {
+ this.errorText_ = settings.printing.getErrorText(
+ /** @type {PrinterSetupResult} */ (result));
+ },
+
+ /**
* If the printer is a nearby printer, return make + model with the subtext.
* Otherwise, return printer name.
* @return {string} The additional information subtext of the manufacturer and
@@ -301,6 +474,7 @@ Polymer({
* @private
*/
selectedModelChanged_: function() {
+ this.errorText_ = '';
if (!this.activePrinter.ppdManufacturer || !this.activePrinter.ppdModel) {
// Do not check for an EULA unless both |ppdManufacturer| and |ppdModel|
// are set. Set |eulaUrl_| to be empty in this case.
@@ -373,9 +547,12 @@ Polymer({
},
/** @private */
- switchToConfiguringDialog_: function() {
- this.close();
- this.fire('open-configuring-printer-dialog');
+ addPrinter_: function() {
+ settings.CupsPrintersBrowserProxyImpl.getInstance()
+ .addCupsPrinter(this.activePrinter)
+ .then(
+ this.onPrinterAddedSucceeded_.bind(this),
+ this.onPrinterAddedFailed_.bind(this));
},
/**
@@ -418,8 +595,6 @@ Polymer({
Polymer({
is: 'settings-cups-add-printer-dialog',
- behaviors: [WebUIListenerBehavior],
-
properties: {
/** @type {!CupsPrinterInfo} */
newPrinter: {
@@ -457,29 +632,36 @@ Polymer({
type: Boolean,
value: false,
},
+
+ /**
+ * TODO(jimmyxgong): Remove this feature flag conditional once feature
+ * is launched.
+ * @private
+ */
+ enableUpdatedUi: Boolean,
},
listeners: {
'open-manually-add-printer-dialog': 'openManuallyAddPrinterDialog_',
'open-configuring-printer-dialog': 'openConfiguringPrinterDialog_',
'open-discovery-printers-dialog': 'openDiscoveryPrintersDialog_',
- 'open-manufacturer-model-dialog': 'openManufacturerModelDialog_',
+ 'open-manufacturer-model-dialog':
+ 'openManufacturerModelDialogForCurrentPrinter_',
'no-detected-printer': 'onNoDetectedPrinter_',
},
- /** @override */
- ready: function() {
- this.addWebUIListener(
- 'on-add-or-edit-cups-printer', this.onAddPrinter_.bind(this));
- this.addWebUIListener(
- 'on-manually-add-discovered-printer',
- this.onManuallyAddDiscoveredPrinter_.bind(this));
- },
-
/** Opens the Add printer discovery dialog. */
open: function() {
this.resetData_();
- this.switchDialog_('', AddPrinterDialogs.DISCOVERY, 'showDiscoveryDialog_');
+ if (this.enableUpdatedUi) {
+ // The updated UI will remove the discovery dialog. Open the manual
+ // dialog by default.
+ this.switchDialog_(
+ '', AddPrinterDialogs.MANUALLY, 'showManuallyAddDialog_');
+ } else {
+ this.switchDialog_(
+ '', AddPrinterDialogs.DISCOVERY, 'showDiscoveryDialog_');
+ }
},
/**
@@ -507,49 +689,9 @@ Polymer({
},
/** @private */
- addPrinter_: function() {
- settings.CupsPrintersBrowserProxyImpl.getInstance().addCupsPrinter(
- this.newPrinter);
- },
-
- /** @private */
switchToManufacturerDialog_: function() {
this.$$('add-printer-configuring-dialog').close();
- this.fire('open-manufacturer-model-dialog');
- },
-
- /**
- * Handler for getPrinterInfo success.
- * @param {!PrinterMakeModel} info
- * @private
- * */
- onPrinterFound_: function(info) {
- this.newPrinter.printerManufacturer = info.manufacturer;
- this.newPrinter.printerModel = info.model;
- this.newPrinter.printerMakeAndModel = info.makeAndModel;
- this.newPrinter.printerPpdReference.userSuppliedPpdUrl =
- info.ppdRefUserSuppliedPpdUrl;
- this.newPrinter.printerPpdReference.effectiveMakeAndModel =
- info.ppdRefEffectiveMakeAndModel;
- this.newPrinter.printerPpdReference.autoconf = info.autoconf;
- this.newPrinter.printerPpdReferenceResolved = info.ppdReferenceResolved;
-
- // Add the printer if it's configurable. Otherwise, forward to the
- // manufacturer dialog.
- if (this.newPrinter.printerPpdReferenceResolved) {
- this.addPrinter_();
- } else {
- this.switchToManufacturerDialog_();
- }
- },
-
- /**
- * Handler for getPrinterInfo failure.
- * @param {*} rejected
- * @private
- */
- infoFailed_: function(rejected) {
- this.switchToManufacturerDialog_();
+ this.openManufacturerModelDialogForCurrentPrinter_();
},
/** @private */
@@ -560,34 +702,30 @@ Polymer({
if (this.previousDialog_ == AddPrinterDialogs.DISCOVERY) {
this.configuringDialogTitle =
loadTimeData.getString('addPrintersNearbyTitle');
- settings.CupsPrintersBrowserProxyImpl.getInstance().addDiscoveredPrinter(
- this.newPrinter.printerId);
- } else if (this.previousDialog_ == AddPrinterDialogs.MANUFACTURER) {
- this.configuringDialogTitle =
- loadTimeData.getString('manufacturerAndModelDialogTitle');
- this.addPrinter_();
- } else if (this.previousDialog_ == AddPrinterDialogs.MANUALLY) {
- this.configuringDialogTitle =
- loadTimeData.getString('addPrintersManuallyTitle');
- if (this.newPrinter.printerProtocol == 'ipp' ||
- this.newPrinter.printerProtocol == 'ipps') {
- settings.CupsPrintersBrowserProxyImpl.getInstance()
- .getPrinterInfo(this.newPrinter)
- .then(this.onPrinterFound_.bind(this), this.infoFailed_.bind(this));
- } else {
- // Defer the switch until all the elements are drawn.
- this.async(this.switchToManufacturerDialog_.bind(this));
- }
+ settings.CupsPrintersBrowserProxyImpl.getInstance()
+ .addDiscoveredPrinter(this.newPrinter.printerId)
+ .then(
+ this.onAddingDiscoveredPrinterSucceeded_.bind(this),
+ this.manuallyAddDiscoveredPrinter_.bind(this));
+ } else {
+ assertNotReached('Opening configuring dialog from invalid place');
}
},
/** @private */
- openManufacturerModelDialog_: function() {
+ openManufacturerModelDialogForCurrentPrinter_: function() {
this.switchDialog_(
this.currentDialog_, AddPrinterDialogs.MANUFACTURER,
'showManufacturerDialog_');
},
+ /** @param {!CupsPrinterInfo} printer */
+ openManufacturerModelDialogForSpecifiedPrinter: function(printer) {
+ this.newPrinter = printer;
+ this.switchDialog_(
+ '', AddPrinterDialogs.MANUFACTURER, 'showManufacturerDialog_');
+ },
+
/** @private */
onNoDetectedPrinter_: function() {
// If there is no detected printer, automatically open manually-add-printer
@@ -622,15 +760,27 @@ Polymer({
},
/**
+ * Handler for addDiscoveredPrinter.
+ * @param {!PrinterSetupResult} result
+ * @private
+ * */
+ onAddingDiscoveredPrinterSucceeded_: function(result) {
+ this.$$('add-printer-configuring-dialog').close();
+ this.fire(
+ 'show-cups-printer-toast',
+ {resultCode: result, printerName: this.newPrinter.printerName});
+ },
+
+ /**
* Use the given printer as the starting point for a user-driven
* add of a printer. This is called if we can't automatically configure
* the printer, and need more information from the user.
*
- * @param {!CupsPrinterInfo} printer
+ * @param {*} printer
* @private
*/
- onManuallyAddDiscoveredPrinter_: function(printer) {
- this.newPrinter = printer;
+ manuallyAddDiscoveredPrinter_: function(printer) {
+ this.newPrinter = /** @type {CupsPrinterInfo} */ (printer);
this.switchToManufacturerDialog_();
},
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_elements.html b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_elements.html
index 83e2e9000bd..f7ed42a8229 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_elements.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_elements.html
@@ -2,7 +2,7 @@
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="cups_printer_dialog_util.html">
<link rel="import" href="cups_printer_shared_css.html">
<link rel="import" href="cups_printers_browser_proxy.html">
@@ -17,7 +17,7 @@
<array-selector id="arraySelector" items="[[printers]]"
selected="{{selectedPrinter}}">
</array-selector>
- <template is="dom-repeat" items="[[printers]]">
+ <template is="dom-repeat" items="[[printers]]" sort="sort_">
<button class="list-item" on-click="onSelect_">
[[item.printerName]]
</button>
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_elements.js b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_elements.js
index d27c65f58a8..724c9cc9f46 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_elements.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog_elements.js
@@ -27,6 +27,16 @@ Polymer({
onSelect_: function(event) {
this.selectedPrinter = event.model.item;
},
+
+ /**
+ * @param {!CupsPrinterInfo} first
+ * @param {!CupsPrinterInfo} second
+ * @return {number} The result of the comparison.
+ * @private
+ */
+ sort_: function(first, second) {
+ return settings.printing.alphabeticalSort(first, second);
+ },
});
/** 'add-printer-dialog' is the template of the Add Printer dialog. */
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.html b/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.html
index 8947b67a8bf..793770fd6dc 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.html
@@ -1,9 +1,13 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_components/chromeos/network/mojo_interface_provider.html">
+<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/cr_elements/cr_scrollable_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/cr_searchable_drop_down/cr_searchable_drop_down.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
+<link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="cups_add_printer_dialog_elements.html">
<link rel="import" href="cups_printer_dialog_util.html">
@@ -12,9 +16,18 @@
<dom-module id="settings-cups-edit-printer-dialog">
<template>
- <style include="cups-printer-shared"> </style>
+ <style include="cr-shared-style cups-printer-shared"></style>
<add-printer-dialog>
- <div slot="dialog-title">$i18n{editPrinterDialogTitle}</div>
+ <div slot="dialog-title">$i18n{editPrinterDialogTitle}
+ <div id="general-error-container" hidden="[[!errorText_]]">
+ <div id="general-error">
+ <iron-icon id="general-error-icon" icon="cr:warning"></iron-icon>
+ <div id="general-error-message">
+ [[errorText_]]
+ </div>
+ </div>
+ </div>
+ </div>
<div slot="dialog-body" scrollable>
<div class="settings-box first two-line">
<cr-input class="printer-name-input" autofocus
@@ -31,17 +44,21 @@
on-input="onPrinterInfoChange_"
value="{{pendingPrinter_.printerAddress}}"
disabled="[[!networkProtocolActive_]]"
- maxlength=63>
+ maxlength=63
+ readonly="[[!isOnline_]]">
</cr-input>
</div>
<div class="settings-box two-line">
<div class="start">
- <div id="printerProtocol" class="label">$i18n{printerProtocol}</div>
+ <div id="printerProtocol" class="cr-form-field-label">
+ $i18n{printerProtocol}
+ </div>
<div class="secondary">
<select class="md-select" aria-labelledby="printerProtocol"
value="[[pendingPrinter_.printerProtocol]]"
on-change="onProtocolChange_"
- disabled="[[!networkProtocolActive_]]">
+ disabled="[[!protocolSelectEnabled(isOnline_,
+ networkProtocolActive_)]]">
<option value="ipp" disabled="[[!networkProtocolActive_]]">
$i18n{printerProtocolIpp}
</option>
@@ -74,8 +91,9 @@
<cr-input id="printerQueue" label="$i18n{printerQueue}"
value="{{pendingPrinter_.printerQueue}}"
on-input="onPrinterInfoChange_"
+ maxlength=64
disabled="[[!networkProtocolActive_]]"
- maxlength=64>
+ readonly="[[!isOnline_]]">
</cr-input>
</div>
<div class="settings-box two-line">
@@ -87,17 +105,19 @@
<cr-searchable-drop-down items="[[manufacturerList]]"
id="printerPPDManufacturer"
label="$i18n{printerManufacturer}"
- value="{{pendingPrinter_.ppdManufacturer}}">
+ value="{{pendingPrinter_.ppdManufacturer}}"
+ readonly="[[!isOnline_]]">
</cr-searchable-drop-down>
</div>
<div class="settings-box two-line">
<cr-searchable-drop-down items="[[modelList]]"
id="printerPPDModel"
label="$i18n{printerModel}"
- value="{{pendingPrinter_.ppdModel}}">
+ value="{{pendingPrinter_.ppdModel}}"
+ readonly="[[!isOnline_]]">
</cr-searchable-drop-down>
</div>
- <div id="ppdLabel" class="field-label">
+ <div id="ppdLabel" class="cr-form-field-label">
<span>$i18n{selectDriver}</span>
<a href="$i18n{printingCUPSPrintPpdLearnMoreUrl}" target="_blank">
$i18n{learnMore}
@@ -109,24 +129,24 @@
error-message="$i18n{selectDriverErrorMessage}"
invalid="[[invalidPPD_]]">
</cr-input>
- <paper-button class="browse-button" on-click="onBrowseFile_">
+ <cr-button class="browse-button" on-click="onBrowseFile_"
+ disabled="[[!isOnline_]]">
$i18n{selectDriverButtonText}
- </paper-button>
+ </cr-button>
</div>
<div class="eula" id="eulaUrl" hidden="[[!eulaUrl_]]">
<a href="[[eulaUrl_]]" target="_blank">$i18n{printerEulaNotice}</a>
</div>
</div>
<div slot="dialog-buttons">
- <paper-button class="cancel-button secondary-button"
- on-click="onCancelTap_">
+ <cr-button class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onSaveTap_"
+ </cr-button>
+ <cr-button class="action-button" on-click="onSaveTap_"
disabled="[[!canSavePrinter_(pendingPrinter_.*,
- printerInfoChanged_)]]">
+ printerInfoChanged_, isOnline_)]]">
$i18n{editPrinterButtonText}
- </paper-button>
+ </cr-button>
</div>
</add-printer-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.js b/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.js
index 2e5404f4cfd..2832048cf28 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_edit_printer_dialog.js
@@ -12,6 +12,7 @@ Polymer({
behaviors: [
CrScrollableBehavior,
+ CrNetworkListenerBehavior,
],
properties: {
@@ -101,6 +102,21 @@ Polymer({
type: String,
value: '',
},
+
+ /** @private */
+ isOnline_: {
+ type: Boolean,
+ value: true,
+ },
+
+ /**
+ * The error text to be displayed on the dialog.
+ * @private
+ */
+ errorText_: {
+ type: String,
+ value: '',
+ },
},
observers: [
@@ -109,11 +125,24 @@ Polymer({
'onModelChanged_(pendingPrinter_.ppdModel)',
],
+ /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} */
+ networkConfigProxy_: null,
+
+ /** @override */
+ created: function() {
+ this.networkConfigProxy_ =
+ network_config.MojoInterfaceProviderImpl.getInstance()
+ .getMojoServiceProxy();
+ },
+
/** @override */
attached: function() {
// Create a copy of activePrinter so that we can modify its fields.
this.pendingPrinter_ = /** @type{CupsPrinterInfo} */
(Object.assign({}, this.activePrinter));
+
+ this.refreshNetworks_();
+
settings.CupsPrintersBrowserProxyImpl.getInstance()
.getPrinterPpdManufacturerAndModel(this.pendingPrinter_.printerId)
.then(
@@ -127,6 +156,18 @@ Polymer({
},
/**
+ * CrosNetworkConfigObserver impl
+ * @param {!Array<chromeos.networkConfig.mojom.NetworkStateProperties>}
+ * networks
+ * @private
+ */
+ onActiveNetworksChanged: function(networks) {
+ this.isOnline_ = networks.some(function(network) {
+ return OncMojo.connectionStateIsConnected(network.connectionState);
+ });
+ },
+
+ /**
* @param {!{path: string, value: string}} change
* @private
*/
@@ -155,17 +196,47 @@ Polymer({
this.$$('add-printer-dialog').close();
},
+ /**
+ * Handler for update|reconfigureCupsPrinter success.
+ * @param {!PrinterSetupResult} result
+ * @private
+ */
+ onPrinterEditSucceeded_: function(result) {
+ this.fire(
+ 'show-cups-printer-toast',
+ {resultCode: result, printerName: this.activePrinter.printerName});
+ this.$$('add-printer-dialog').close();
+ },
+
+ /**
+ * Handler for update|reconfigureCupsPrinter failure.
+ * @param {*} result
+ * @private
+ */
+ onPrinterEditFailed_: function(result) {
+ this.errorText_ = settings.printing.getErrorText(
+ /** @type {PrinterSetupResult} */ (result));
+ },
+
/** @private */
onSaveTap_: function() {
this.updateActivePrinter_();
- if (this.needsReconfigured_) {
+ if (!this.needsReconfigured_ || !this.isOnline_) {
+ // If we don't need to reconfigure or we are offline, just update the
+ // printer name.
settings.CupsPrintersBrowserProxyImpl.getInstance()
- .reconfigureCupsPrinter(this.activePrinter);
+ .updateCupsPrinter(
+ this.activePrinter.printerId, this.activePrinter.printerName)
+ .then(
+ this.onPrinterEditSucceeded_.bind(this),
+ this.onPrinterEditFailed_.bind(this));
} else {
- settings.CupsPrintersBrowserProxyImpl.getInstance().updateCupsPrinter(
- this.activePrinter.printerId, this.activePrinter.printerName);
+ settings.CupsPrintersBrowserProxyImpl.getInstance()
+ .reconfigureCupsPrinter(this.activePrinter)
+ .then(
+ this.onPrinterEditSucceeded_.bind(this),
+ this.onPrinterEditFailed_.bind(this));
}
- this.$$('add-printer-dialog').close();
},
/**
@@ -224,7 +295,8 @@ Polymer({
* @private
*/
canSavePrinter_: function() {
- return this.printerInfoChanged_ && this.isPrinterValid();
+ return this.printerInfoChanged_ &&
+ (this.isPrinterValid() || !this.isOnline_);
},
/**
@@ -324,7 +396,7 @@ Polymer({
this.userPPD_ = settings.printing.getBaseName(path);
},
- /*
+ /**
* Returns true if the printer has valid name, address, and PPD.
* @return {boolean}
*/
@@ -335,15 +407,48 @@ Polymer({
this.pendingPrinter_.printerPPDPath);
},
- /*
+
+ /**
* Helper function to copy over modified fields to activePrinter.
* @private
*/
updateActivePrinter_: function() {
+ if (!this.isOnline_) {
+ // If we are not online, only copy over the printerName.
+ this.activePrinter.printerName = this.pendingPrinter_.printerName;
+ return;
+ }
+
this.activePrinter =
/** @type{CupsPrinterInfo} */ (Object.assign({}, this.pendingPrinter_));
// Set ppdModel since there is an observer that clears ppdmodel's value when
// ppdManufacturer changes.
this.activePrinter.ppdModel = this.pendingPrinter_.ppdModel;
},
+
+ /**
+ * Callback function when networks change.
+ * @private
+ */
+ refreshNetworks_: function() {
+ this.networkConfigProxy_
+ .getNetworkStateList({
+ filter: chromeos.networkConfig.mojom.FilterType.kActive,
+ networkType: chromeos.networkConfig.mojom.NetworkType.kAll,
+ limit: chromeos.networkConfig.mojom.kNoLimit,
+ })
+ .then((responseParams) => {
+ this.onActiveNetworksChanged(responseParams.result);
+ });
+ },
+
+ /**
+ * Returns true if the printer protocol select field should be enabled.
+ * @return {boolean}
+ * @private
+ */
+ protocolSelectEnabled: function() {
+ return this.isOnline_ && this.networkProtocolActive_;
+ },
+
});
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.html b/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.html
new file mode 100644
index 00000000000..428055b1b0f
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.html
@@ -0,0 +1,17 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
+<link rel="import" href="cups_printer_types.html">
+<link rel="import" href="cups_printers_browser_proxy.html">
+<link rel="import" href="cups_printers_entry_list.html">
+<link rel="import" href="../settings_shared_css.html">
+
+<dom-module id="settings-cups-nearby-printers">
+ <template>
+ <style include="settings-shared"></style>
+ <settings-cups-printers-entry-list printers="[[nearbyPrinters_]]"
+ search-term="[[searchTerm]]">
+ </settings-cups-printers-entry-list>
+ </template>
+ <script src="cups_nearby_printers.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.js b/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.js
new file mode 100644
index 00000000000..76652d815cd
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_nearby_printers.js
@@ -0,0 +1,127 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview 'settings-cups-nearby-printers' is a list container for
+ * Nearby Printers.
+ */
+Polymer({
+ is: 'settings-cups-nearby-printers',
+
+ behaviors: [WebUIListenerBehavior],
+
+ properties: {
+ /**
+ * @type {!Array<!PrinterListEntry>}
+ * @private
+ */
+ nearbyPrinters_: {
+ type: Array,
+ value: () => [],
+ },
+
+ /**
+ * Search term for filtering |nearbyPrinters_|.
+ * @type {string}
+ */
+ searchTerm: {
+ type: String,
+ value: '',
+ },
+
+ /**
+ * @type {number}
+ * @private
+ */
+ activePrinterListEntryIndex_: {
+ type: Number,
+ value: -1,
+ },
+
+ /** @type {?CupsPrinterInfo} */
+ activePrinter: {
+ type: Object,
+ notify: true,
+ },
+ },
+
+ listeners: {
+ 'add-automatic-printer': 'onAddAutomaticPrinter_',
+ },
+
+ /** @override */
+ attached: function() {
+ settings.CupsPrintersBrowserProxyImpl.getInstance()
+ .startDiscoveringPrinters();
+ this.addWebUIListener(
+ 'on-nearby-printers-changed', this.onNearbyPrintersChanged_.bind(this));
+ },
+
+ /**
+ * @param {!Array<!CupsPrinterInfo>} automaticPrinters
+ * @param {!Array<!CupsPrinterInfo>} discoveredPrinters
+ * @private
+ */
+ onNearbyPrintersChanged_: function(automaticPrinters, discoveredPrinters) {
+ if (!automaticPrinters && !discoveredPrinters) {
+ return;
+ }
+
+ const printers = /** @type{!Array<!PrinterListEntry>} */ ([]);
+
+ for (const printer of automaticPrinters) {
+ printers.push({printerInfo: printer,
+ printerType: PrinterType.AUTOMATIC});
+ }
+
+ for (const printer of discoveredPrinters) {
+ printers.push({printerInfo: printer,
+ printerType: PrinterType.DISCOVERED});
+ }
+
+ this.nearbyPrinters_ = printers;
+ },
+
+ /**
+ * @param {!CustomEvent<{item: !PrinterListEntry}>} e
+ * @private
+ */
+ onAddAutomaticPrinter_: function(e) {
+ const item = e.detail.item;
+ this.setActivePrinter_(item);
+
+ settings.CupsPrintersBrowserProxyImpl.getInstance()
+ .addDiscoveredPrinter(item.printerInfo.printerId)
+ .then(this.onAddNearbyPrintersSucceeded_.bind(this,
+ item.printerInfo.printerName));
+ },
+
+ /**
+ * Retrieves the index of |item| in |nearbyPrinters_| and sets that printer as
+ * the active printer.
+ * @param {!PrinterListEntry} item
+ * @private
+ */
+ setActivePrinter_: function(item) {
+ this.activePrinterListEntryIndex_ =
+ this.nearbyPrinters_.findIndex(
+ printer => printer.printerInfo == item.printerInfo);
+
+ this.activePrinter =
+ this.get(['nearbyPrinters_', this.activePrinterListEntryIndex_])
+ .printerInfo;
+ },
+
+ /**
+ * Handler for addDiscoveredPrinter.
+ * @param {string} printerName
+ * @param {!PrinterSetupResult} result
+ * @private
+ */
+ onAddNearbyPrintersSucceeded_: function(printerName, result) {
+ this.fire(
+ 'show-cups-printer-toast',
+ {resultCode: result, printerName: printerName});
+ }
+}); \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printer_dialog_util.js b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_dialog_util.js
index d448aa64f05..15542cb8d1c 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_printer_dialog_util.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_dialog_util.js
@@ -96,10 +96,57 @@ cr.define('settings.printing', function() {
return '';
}
+ /**
+ * A function used for sorting printer names based on the current locale's
+ * collation order.
+ * @param {!CupsPrinterInfo} first
+ * @param {!CupsPrinterInfo} second
+ * @return {number} The result of the comparison.
+ */
+ function alphabeticalSort(first, second) {
+ return first.printerName.toLocaleLowerCase().localeCompare(
+ second.printerName.toLocaleLowerCase());
+ }
+
+ /**
+ * Return the error string corresponding to the result code.
+ * @param {!PrinterSetupResult} result
+ * @return {string}
+ */
+ function getErrorText(result) {
+ switch (result) {
+ case PrinterSetupResult.FATAL_ERROR:
+ return loadTimeData.getString('printerAddedFatalErrorMessage');
+ case PrinterSetupResult.PRINTER_UNREACHABLE:
+ return loadTimeData.getString('printerAddedUnreachableMessage');
+ case PrinterSetupResult.DBUS_ERROR:
+ // Simply return a generic error message as this error should only
+ // occur when a call to Dbus fails which isn't meaningful to the user.
+ return loadTimeData.getString('printerAddedFailedMessage');
+ case PrinterSetupResult.NATIVE_PRINTERS_NOT_ALLOWED:
+ return loadTimeData.getString(
+ 'printerAddedNativePrintersNotAllowedMessage');
+ case PrinterSetupResult.INVALID_PRINTER_UPDATE:
+ return loadTimeData.getString('editPrinterInvalidPrinterUpdate');
+ case PrinterSetupResult.PPD_TOO_LARGE:
+ return loadTimeData.getString('printerAddedPpdTooLargeMessage');
+ case PrinterSetupResult.INVALID_PPD:
+ return loadTimeData.getString('printerAddedInvalidPpdMessage');
+ case PrinterSetupResult.PPD_NOT_FOUND:
+ return loadTimeData.getString('printerAddedPpdNotFoundMessage');
+ case PrinterSetupResult.PPD_UNRETRIEVABLE:
+ return loadTimeData.getString('printerAddedPpdUnretrievableMessage');
+ default:
+ assertNotReached();
+ }
+ }
+
return {
isNetworkProtocol: isNetworkProtocol,
isNameAndAddressValid: isNameAndAddressValid,
isPPDInfoValid: isPPDInfoValid,
getBaseName: getBaseName,
+ alphabeticalSort: alphabeticalSort,
+ getErrorText: getErrorText,
};
});
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html
index bee8541920b..cda0410aaa6 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_shared_css.html
@@ -1,7 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="../settings_shared_css.html">
<!-- Common styles for CUPS printer settings. -->
@@ -17,10 +17,6 @@
align-items: flex-start;
}
- [slot='dialog-body'] .settings-box .start .label {
- @apply --cr-form-field-label;
- }
-
[slot='dialog-body'] .settings-box cr-input {
width: 100%;
}
@@ -77,12 +73,12 @@
border: none;
box-sizing: border-box;
color: var(--paper-grey-800);
+ cursor: pointer;
font: inherit;
min-height: 32px;
padding: 0 24px;
text-align: start;
width: 100%;
- @apply --cr-actionable;
}
.list-item:focus {
@@ -94,9 +90,24 @@
font: inherit;
}
- .field-label {
+ #ppdLabel {
padding-inline-start: 20px;
- @apply --cr-form-field-label;
+ }
+
+ #general-error-container {
+ height: 20px;
+ margin-top: 10px;
+ }
+
+ #general-error-icon {
+ --iron-icon-fill-color: var(--google-red-600);
+ }
+
+ #general-error-message {
+ color: var(--google-red-600);
+ display: inline-block;
+ font-size: 10px;
+ margin-inline-start: 5px;
}
</style>
</template>
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.html b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.html
new file mode 100644
index 00000000000..59964ef38b5
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.html
@@ -0,0 +1,2 @@
+<link rel="import" href="cups_printers_browser_proxy.html">
+<script src="cups_printer_types.js"></script> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.js b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.js
new file mode 100644
index 00000000000..1d8487bf254
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printer_types.js
@@ -0,0 +1,23 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @typedef {{
+ * printerInfo: !CupsPrinterInfo,
+ * printerType: number,
+ * }}
+ */
+let PrinterListEntry;
+
+/**
+ * @enum {number}
+ * These values correspond to the different types of printers available. Refer
+ * to cups_printer_management.md for more information about the different
+ * categories of printers.
+ */
+const PrinterType = {
+ SAVED: 0,
+ AUTOMATIC: 1,
+ DISCOVERED: 2,
+}; \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers.html b/chromium/chrome/browser/resources/settings/printing_page/cups_printers.html
index 1e36dfa6a2d..7f23152c39a 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers.html
@@ -1,20 +1,47 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
+<link rel="import" href="chrome://resources/cr_components/chromeos/network/mojo_interface_provider.html">
+<link rel="import" href="chrome://resources/cr_elements/chromeos/network/cr_network_listener_behavior.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast.html">
+<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
+<link rel="import" href="chrome://resources/html/chromeos/onc_mojo.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="cups_add_printer_dialog.html">
<link rel="import" href="cups_edit_printer_dialog.html">
<link rel="import" href="cups_printer_shared_css.html">
<link rel="import" href="cups_printers_list.html">
+<link rel="import" href="cups_saved_printers.html">
+<link rel="import" href="cups_nearby_printers.html">
<dom-module id="settings-cups-printers">
<template>
<style include="cups-printer-shared action-link">
+ .custom-list-item {
+ align-items: center;
+ border-bottom: var(--cr-separator-line);
+ display: flex;
+ min-height: var(--settings-row-min-height);
+ }
+
+ .padded {
+ padding: 20px;
+ }
+
+ #addPrinterSection {
+ padding-inline-start:
+ var(--settings-list-frame-padding_-_padding-inline-start);
+ padding-inline-end:
+ var(--settings-list-frame-padding_-_padding-inline-end);
+ }
+
+ #addPrinterText {
+ flex: 1;
+ }
+
#noSearchResultsMessage {
color: var(--md-loading-message-color);
font-size: 16px;
@@ -24,33 +51,89 @@
}
</style>
- <div class="settings-box first">
- <div class="start">
- <span>$i18n{cupsPrintersLearnMoreLabel}</span>
+ <template is="dom-if" if="[[!enableUpdatedUi_]]">
+ <div class="settings-box first">
+ <div class="start">
+ <span>$i18n{cupsPrintersLearnMoreLabel}</span>
+ <a href="$i18n{printingCUPSPrintLearnMoreUrl}" target="_blank">
+ $i18n{learnMore}
+ </a>
+ <div class="secondary" hidden="[[canAddPrinter_]]">
+ $i18n{requireNetworkMessage}
+ </div>
+ </div>
+ <template is="dom-if" if="[[!addPrinterButtonActive_(canAddPrinter_,
+ prefs.native_printing.user_native_printers_allowed.value)]]">
+ <cr-policy-pref-indicator
+ pref="[[prefs.native_printing.user_native_printers_allowed]]"
+ icon-aria-label="$i18n{printingPageTitle}">
+ </cr-policy-pref-indicator>
+ </template>
+ <cr-button class="action-button" id="addPrinter"
+ on-click="onAddPrinterTap_"
+ disabled="[[!addPrinterButtonActive_(canAddPrinter_,
+ prefs.native_printing.user_native_printers_allowed.value)]]">
+ $i18n{addCupsPrinter}
+ </cr-button>
+ </div>
+ <settings-cups-printers-list printers="{{printers}}"
+ active-printer="{{activePrinter}}"
+ search-term="[[searchTerm]]">
+ </settings-cups-printers-list>
+ </template>
+
+ <template is="dom-if" if="[[enableUpdatedUi_]]">
+ <div class="settings-box first">
+ <div class="start">
+ <span>$i18n{savedPrintersTitle}</span>
+ </div>
+ </div>
+
+ <settings-cups-saved-printers id="savedPrinters"
+ active-printer="{{activePrinter}}"
+ search-term="[[searchTerm]]">
+ </settings-cups-saved-printers>
+
+ <div class="padded first" id="nearbyPrinters">
+ <div>$i18n{nearbyPrintersListTitle}</div>
+ <span class="secondary">
+ $i18n{nearbyPrintersListDescription}
+ </span>
<a href="$i18n{printingCUPSPrintLearnMoreUrl}" target="_blank">
$i18n{learnMore}
</a>
<div class="secondary" hidden="[[canAddPrinter_]]">
$i18n{requireNetworkMessage}
</div>
+ <template is="dom-if" if="[[!addPrinterButtonActive_(canAddPrinter_,
+ prefs.native_printing.user_native_printers_allowed.value)]]">
+ <cr-policy-pref-indicator
+ pref="[[prefs.native_printing.user_native_printers_allowed]]"
+ icon-aria-label="$i18n{printingPageTitle}">
+ </cr-policy-pref-indicator>
+ </template>
</div>
- <template is="dom-if" if="[[!addPrinterButtonActive_(canAddPrinter_,
- prefs.native_printing.user_native_printers_allowed.value)]]">
- <cr-policy-pref-indicator
- pref="[[prefs.native_printing.user_native_printers_allowed]]"
- icon-aria-label="$i18n{printingPageTitle}">
- </cr-policy-pref-indicator>
- </template>
- <paper-button class="action-button" id="addPrinter"
- on-click="onAddPrinterTap_"
- disabled="[[!addPrinterButtonActive_(canAddPrinter_,
- prefs.native_printing.user_native_printers_allowed.value)]]">
- $i18n{addCupsPrinter}
- </paper-button>
- </div>
+
+ <div id="addPrinterSection">
+ <div class="custom-list-item">
+ <div id="addPrinterText">$i18n{addCupsPrinter}</div>
+ <cr-button class="action-button" id="addPrinter"
+ on-click="onAddPrinterTap_"
+ disabled="[[!addPrinterButtonActive_(canAddPrinter_,
+ prefs.native_printing.user_native_printers_allowed.value)]]">
+ $i18n{addCupsPrinter}
+ </cr-button>
+ </div>
+ </div>
+
+ <settings-cups-nearby-printers search-term="[[searchTerm]]"
+ active-printer="{{activePrinter}}">
+ </settings-cups-nearby-printers>
+ </template>
<settings-cups-add-printer-dialog id="addPrinterDialog"
- on-close="onAddPrinterDialogClose_">
+ on-close="onAddPrinterDialogClose_"
+ enable-updated-ui="[[enableUpdatedUi_]]">
</settings-cups-add-printer-dialog>
<template is="dom-if" if="[[showCupsEditPrinterDialog_]]" restamp>
@@ -60,11 +143,6 @@
</settings-cups-edit-printer-dialog>
</template>
- <settings-cups-printers-list printers="{{printers}}"
- active-printer="{{activePrinter}}"
- search-term="[[searchTerm]]">
- </settings-cups-printers-list>
-
<div id="noSearchResultsMessage"
hidden="[[!showNoSearchResultsMessage_(searchTerm)]]">
$i18n{noSearchResults}
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers.js b/chromium/chrome/browser/resources/settings/printing_page/cups_printers.js
index 19a7fe7fe32..7e41ed47507 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers.js
@@ -12,7 +12,10 @@
Polymer({
is: 'settings-cups-printers',
- behaviors: [WebUIListenerBehavior],
+ behaviors: [
+ CrNetworkListenerBehavior,
+ WebUIListenerBehavior,
+ ],
properties: {
/** @type {!Array<!CupsPrinterInfo>} */
@@ -41,129 +44,121 @@ Polymer({
/**@private */
addPrinterResultText_: String,
+
+ /**
+ * TODO(jimmyxgong): Remove this feature flag conditional once feature
+ * is launched.
+ * @private
+ */
+ enableUpdatedUi_: {
+ type: Boolean,
+ value: function() {
+ return loadTimeData.getBoolean('updatedCupsPrintersUiEnabled');
+ },
+ },
},
listeners: {
'edit-cups-printer-details': 'onShowCupsEditPrinterDialog_',
+ 'show-cups-printer-toast': 'openResultToast_',
+ 'open-manufacturer-model-dialog-for-specified-printer':
+ 'openManufacturerModelDialogForSpecifiedPrinter_',
},
- /**
- * @type {function()}
- * @private
- */
- networksChangedListener_: function() {},
+ /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigProxy} */
+ networkConfigProxy_: null,
/** @override */
- ready: function() {
- this.updateCupsPrintersList_();
- this.refreshNetworks_();
+ created: function() {
+ this.networkConfigProxy_ =
+ network_config.MojoInterfaceProviderImpl.getInstance()
+ .getMojoServiceProxy();
},
/** @override */
attached: function() {
- this.addWebUIListener('on-add-or-edit-cups-printer',
- this.onAddOrEditPrinter_.bind(this));
+ this.networkConfigProxy_
+ .getNetworkStateList({
+ filter: chromeos.networkConfig.mojom.FilterType.kActive,
+ networkType: chromeos.networkConfig.mojom.NetworkType.kAll,
+ limit: chromeos.networkConfig.mojom.kNoLimit,
+ })
+ .then((responseParams) => {
+ this.onActiveNetworksChanged(responseParams.result);
+ });
+
+ if (this.enableUpdatedUi_) {
+ return;
+ }
+
this.addWebUIListener(
'on-printers-changed', this.printersChanged_.bind(this));
- this.networksChangedListener_ = this.refreshNetworks_.bind(this);
- chrome.networkingPrivate.onNetworksChanged.addListener(
- this.networksChangedListener_);
},
/** @override */
- detached: function() {
- chrome.networkingPrivate.onNetworksChanged.removeListener(
- this.networksChangedListener_);
- },
-
- /**
- * Callback function when networks change.
- * @private
- */
- refreshNetworks_: function() {
- chrome.networkingPrivate.getNetworks(
- {
- 'networkType': chrome.networkingPrivate.NetworkType.ALL,
- 'configured': true
- },
- this.onNetworksReceived_.bind(this));
+ ready: function() {
+ this.updateCupsPrintersList_();
},
/**
- * Callback function when configured networks are received.
- * @param {!Array<!chrome.networkingPrivate.NetworkStateProperties>} states
- * A list of network state information for each network.
+ * CrosNetworkConfigObserver impl
+ * @param {!Array<chromeos.networkConfig.mojom.NetworkStateProperties>}
+ * networks
* @private
*/
- onNetworksReceived_: function(states) {
- this.canAddPrinter_ = states.some(function(entry) {
- return entry.hasOwnProperty('ConnectionState') &&
- entry.ConnectionState == 'Connected';
+ onActiveNetworksChanged: function(networks) {
+ this.canAddPrinter_ = networks.some(function(network) {
+ return OncMojo.connectionStateIsConnected(network.connectionState);
});
},
/**
- * @param {PrinterSetupResult} result_code
- * @param {string} printerName
+ * @param {!CustomEvent<!{
+ * resultCode: PrinterSetupResult,
+ * printerName: string
+ * }>} event
* @private
*/
- onAddOrEditPrinter_: function(result_code, printerName) {
- switch (result_code) {
+ openResultToast_: function(event) {
+ const printerName = event.detail.printerName;
+ switch (event.detail.resultCode) {
case PrinterSetupResult.SUCCESS:
- this.updateCupsPrintersList_();
+ if (this.enableUpdatedUi_) {
+ this.$$('#savedPrinters').updateSavedPrintersList();
+ } else {
+ this.updateCupsPrintersList_();
+ }
this.addPrinterResultText_ =
loadTimeData.getStringF('printerAddedSuccessfulMessage',
printerName);
break;
case PrinterSetupResult.EDIT_SUCCESS:
- this.updateCupsPrintersList_();
+ if (this.enableUpdatedUi_) {
+ this.$$('#savedPrinters').updateSavedPrintersList();
+ } else {
+ this.updateCupsPrintersList_();
+ }
this.addPrinterResultText_ =
loadTimeData.getStringF('printerEditedSuccessfulMessage',
printerName);
break;
- case PrinterSetupResult.FATAL_ERROR:
- this.addPrinterResultText_ =
- loadTimeData.getString('printerAddedFatalErrorMessage');
- break;
- case PrinterSetupResult.PRINTER_UNREACHABLE:
- this.addPrinterResultText_ =
- loadTimeData.getString('printerAddedUnreachableMessage');
- break;
- case PrinterSetupResult.DBUS_ERROR:
- // Simply display a generic error message as this error should only
- // occur when a call to Dbus fails which isn't meaningful to the user.
- this.addPrinterResultText_ =
- loadTimeData.getString('printerAddedFailedMessage');
- break;
- case PrinterSetupResult.NATIVE_PRINTERS_NOT_ALLOWED:
- this.addPrinterResultText_ = loadTimeData.getString(
- 'printerAddedNativePrintersNotAllowedMessage');
- break;
- case PrinterSetupResult.INVALID_PRINTER_UPDATE:
- this.addPrinterResultText_ =
- loadTimeData.getString('editPrinterInvalidPrinterUpdate');
- break;
- case PrinterSetupResult.PPD_TOO_LARGE:
- this.addPrinterResultText_ =
- loadTimeData.getString('printerAddedPpdTooLargeMessage');
- break;
- case PrinterSetupResult.INVALID_PPD:
- this.addPrinterResultText_ =
- loadTimeData.getString('printerAddedInvalidPpdMessage');
- break;
- case PrinterSetupResult.PPD_NOT_FOUND:
- this.addPrinterResultText_ =
- loadTimeData.getString('printerAddedPpdNotFoundMessage');
- break;
- case PrinterSetupResult.PPD_UNRETRIEVABLE:
- this.addPrinterResultText_ =
- loadTimeData.getString('printerAddedPpdUnretrievableMessage');
- break;
+ default:
+ assertNotReached();
}
this.$.errorToast.show();
},
+ /**
+ * @param {!CustomEvent<{item: !CupsPrinterInfo}>} e
+ * @private
+ */
+ openManufacturerModelDialogForSpecifiedPrinter_: function(e) {
+ const item = e.detail.item;
+ this.$.addPrinterDialog
+ .openManufacturerModelDialogForSpecifiedPrinter(item);
+ },
+
/** @private */
updateCupsPrintersList_: function() {
settings.CupsPrintersBrowserProxyImpl.getInstance()
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_browser_proxy.js b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_browser_proxy.js
index b3096663827..9f35ce694f5 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_browser_proxy.js
@@ -120,6 +120,7 @@ cr.define('settings', function() {
/**
* @param {string} printerId
* @param {string} printerName
+ * @return {!Promise<!PrinterSetupResult>}
*/
updateCupsPrinter(printerId, printerName) {}
@@ -136,11 +137,13 @@ cr.define('settings', function() {
/**
* @param {!CupsPrinterInfo} newPrinter
+ * @return {!Promise<!PrinterSetupResult>}
*/
addCupsPrinter(newPrinter) {}
/**
* @param {!CupsPrinterInfo} printer
+ * @return {!Promise<!PrinterSetupResult>}
*/
reconfigureCupsPrinter(printer) {}
@@ -172,6 +175,7 @@ cr.define('settings', function() {
/**
* @param{string} printerId
+ * @return {!Promise<!PrinterSetupResult>}
*/
addDiscoveredPrinter(printerId) {}
@@ -201,7 +205,7 @@ cr.define('settings', function() {
/** @override */
updateCupsPrinter(printerId, printerName) {
- chrome.send('updateCupsPrinter', [printerId, printerName]);
+ return cr.sendWithPromise('updateCupsPrinter', printerId, printerName);
}
/** @override */
@@ -211,12 +215,12 @@ cr.define('settings', function() {
/** @override */
addCupsPrinter(newPrinter) {
- chrome.send('addCupsPrinter', [newPrinter]);
+ return cr.sendWithPromise('addCupsPrinter', newPrinter);
}
/** @override */
reconfigureCupsPrinter(printer) {
- chrome.send('reconfigureCupsPrinter', [printer]);
+ return cr.sendWithPromise('reconfigureCupsPrinter', printer);
}
/** @override */
@@ -256,7 +260,7 @@ cr.define('settings', function() {
/** @override */
addDiscoveredPrinter(printerId) {
- chrome.send('addDiscoveredPrinter', [printerId]);
+ return cr.sendWithPromise('addDiscoveredPrinter', printerId);
}
/** @override */
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.html b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.html
new file mode 100644
index 00000000000..164a8c5e637
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.html
@@ -0,0 +1,47 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
+<link rel="import" href="cups_printer_types.html">
+<link rel="import" href="cups_printers_browser_proxy.html">
+<link rel="import" href="../settings_shared_css.html">
+
+<dom-module id="settings-cups-printers-entry">
+ <template>
+ <style include="settings-shared">
+ .printer-name {
+ flex: 1;
+ }
+ </style>
+ <div id="entry" class="list-item" focus-row-container>
+ <div class="printer-name text-elide">
+ <span id="printerName">
+ [[printerEntry.printerInfo.printerName]]
+ </span>
+ <div id="printerSubtext" hidden="[[!subtext]]" class="secondary">
+ [[subtext]]
+ </div>
+ </div>
+ <template is="dom-if" if="[[isSavedPrinter_(printerEntry.printerType)]]">
+ <cr-icon-button class="icon-more-vert" on-click="onOpenActionMenuTap_"
+ title="$i18n{moreActions}">
+ </cr-icon-button>
+ </template>
+ <template is="dom-if"
+ if="[[isDiscoveredPrinter_(printerEntry.printerType)]]">
+ <cr-button class="action-button"
+ on-click="onOpenManufacturerModelDialogTap_">
+ $i18n{configurePrinter}
+ </cr-button>
+ </template>
+ <template is="dom-if"
+ if="[[isAutomaticPrinter_(printerEntry.printerType)]]">
+ <cr-icon-button class="icon-add-circle"
+ on-click="onAddAutomaticPrinterTap_"
+ title="$i18n{moreActions}">
+ </cr-icon-button>
+ </template>
+ </div>
+ </template>
+ <script src="cups_printers_entry.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.js b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.js
new file mode 100644
index 00000000000..fe225dcf9fa
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry.js
@@ -0,0 +1,68 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview 'settings-cups-printers-entry' is a component that holds a
+ * printer.
+ */
+Polymer({
+ is: 'settings-cups-printers-entry',
+
+ properties: {
+ /** @type {!PrinterListEntry} */
+ printerEntry: Object,
+
+ /**
+ * TODO(jimmyxgong): Determine how subtext should be set and what
+ * information it should have.
+ * The additional information subtext for a printer.
+ * @type {string}
+ */
+ subtext: {type: String, value: ''},
+ },
+
+ /**
+ * Fires a custom event when the menu button is clicked. Sends the details of
+ * the printer and where the menu should appear.
+ */
+ onOpenActionMenuTap_: function(e) {
+ this.fire('open-action-menu', {
+ target: e.target,
+ item: this.printerEntry,
+ });
+ },
+
+ onOpenManufacturerModelDialogTap_: function(e) {
+ this.fire('open-manufacturer-model-dialog-for-specified-printer',
+ {item: this.printerEntry.printerInfo});
+ },
+
+ onAddAutomaticPrinterTap_: function() {
+ this.fire('add-automatic-printer', {item: this.printerEntry});
+ },
+
+ /**
+ * @return {boolean}
+ * @private
+ */
+ isSavedPrinter_: function() {
+ return this.printerEntry.printerType == PrinterType.SAVED;
+ },
+
+ /**
+ * @return {boolean}
+ * @private
+ */
+ isDiscoveredPrinter_: function() {
+ return this.printerEntry.printerType == PrinterType.DISCOVERED;
+ },
+
+ /**
+ * @return {boolean}
+ * @private
+ */
+ isAutomaticPrinter_: function() {
+ return this.printerEntry.printerType == PrinterType.AUTOMATIC;
+ }
+});
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.html b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.html
new file mode 100644
index 00000000000..fdb85be62b1
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.html
@@ -0,0 +1,32 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/html/list_property_update_behavior.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
+<link rel="import" href="cups_printer_dialog_util.html">
+<link rel="import" href="cups_printer_types.html">
+<link rel="import" href="cups_printers_browser_proxy.html">
+<link rel="import" href="cups_printers_entry.html">
+<link rel="import" href="../settings_shared_css.html">
+
+<dom-module id="settings-cups-printers-entry-list">
+ <template>
+ <style include="settings-shared">
+ :host {
+ display: flex;
+ flex-direction: column;
+ }
+
+ iron-list {
+ flex: 1 1 auto;
+ }
+ </style>
+ <iron-list class="list-frame vertical-list" id="printerEntryList"
+ items="[[filteredPrinters_]]">
+ <template>
+ <settings-cups-printers-entry printer-entry="[[item]]">
+ </settings-cups-printers-entry>
+ </template>
+ </iron-list>
+ </template>
+ <script src="cups_printers_entry_list.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.js b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.js
new file mode 100644
index 00000000000..6037c31aecc
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_entry_list.js
@@ -0,0 +1,80 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview 'settings-cups-printers-entry-list' is a component for a list
+ * of PrinterListEntry's.
+ */
+Polymer({
+ is: 'settings-cups-printers-entry-list',
+
+ behaviors: [
+ ListPropertyUpdateBehavior,
+ ],
+
+ properties: {
+ /**
+ * List of printers.
+ * @type {!Array<!PrinterListEntry>}
+ */
+ printers: {
+ type: Array,
+ value: () => [],
+ },
+
+ /**
+ * List of printers filtered through a search term.
+ * @type {!Array<!PrinterListEntry>}
+ * @private
+ */
+ filteredPrinters_: {
+ type: Array,
+ value: () => [],
+ },
+
+ /**
+ * Search term for filtering |printers|.
+ * @type {string}
+ */
+ searchTerm: String,
+ },
+
+ observers: [
+ 'onSearchChanged_(printers.*, searchTerm)'
+ ],
+
+ /**
+ * Redoes the search whenever |searchTerm| or |printers| changes.
+ * @private
+ */
+ onSearchChanged_: function() {
+ if (!this.printers) {
+ return;
+ }
+ // Filter printers through |searchTerm|. If |searchTerm| is empty,
+ // |filteredPrinters_| is just |printers|.
+ const updatedPrinters = this.searchTerm ?
+ this.printers.filter(
+ item =>this.matchesSearchTerm_(item.printerInfo,this.searchTerm)) :
+ this.printers.slice();
+
+ updatedPrinters.sort((first, second) => {
+ return settings.printing.alphabeticalSort(
+ first.printerInfo, second.printerInfo);
+ });
+
+ this.updateList('filteredPrinters_', printer => printer.printerInfo,
+ updatedPrinters);
+ },
+
+ /**
+ * @param {!CupsPrinterInfo} printer
+ * @param {string} searchTerm
+ * @return {boolean} True if the printer has |searchTerm| in its name.
+ * @private
+ */
+ matchesSearchTerm_: function(printer, searchTerm) {
+ return printer.printerName.toLowerCase().includes(searchTerm.toLowerCase());
+ }
+});
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.html b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.html
index c6f1c093516..c0e8208c60d 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.html
@@ -3,6 +3,7 @@
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
+<link rel="import" href="cups_printer_dialog_util.html">
<link rel="import" href="cups_printers_browser_proxy.html">
<link rel="import" href="../settings_shared_css.html">
@@ -24,7 +25,8 @@
</cr-action-menu>
<div class="list-frame vertical-list">
<template is="dom-repeat" items="[[printers]]"
- filter="[[filterPrinter_(searchTerm)]]">
+ filter="[[filterPrinter_(searchTerm)]]"
+ sort="sort_">
<div class="list-item">
<div class="printer-name text-elide">[[item.printerName]]</div>
<!--TODO(xdai): Add icon for enterprise CUPS printer. -->
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.js b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.js
index 0e266c7f653..df422ff4ca1 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_printers_list.js
@@ -93,4 +93,14 @@ Polymer({
searchTerm.toLowerCase());
};
},
+
+ /**
+ * @param {!CupsPrinterInfo} first
+ * @param {!CupsPrinterInfo} second
+ * @return {number} The result of the comparison.
+ * @private
+ */
+ sort_: function(first, second) {
+ return settings.printing.alphabeticalSort(first, second);
+ },
});
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.html b/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.html
new file mode 100644
index 00000000000..b343992525d
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.html
@@ -0,0 +1,27 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
+<link rel="import" href="cups_printer_types.html">
+<link rel="import" href="cups_printers_browser_proxy.html">
+<link rel="import" href="cups_printers_entry_list.html">
+<link rel="import" href="../settings_shared_css.html">
+
+<dom-module id="settings-cups-saved-printers">
+ <template>
+ <cr-action-menu>
+ <button id="editButton" class="dropdown-item" on-click="onEditTap_">
+ $i18n{editPrinter}
+ </button>
+ <button id="removeButton" class="dropdown-item" on-click="onRemoveTap_">
+ $i18n{removePrinter}
+ </button>
+ </cr-action-menu>
+
+ <style include="settings-shared"></style>
+ <settings-cups-printers-entry-list printers="[[savedPrinters_]]"
+ search-term="[[searchTerm]]">
+ </settings-cups-printers-entry-list>
+ </template>
+ <script src="cups_saved_printers.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.js b/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.js
new file mode 100644
index 00000000000..a44b197232f
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/printing_page/cups_saved_printers.js
@@ -0,0 +1,130 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview 'settings-cups-saved-printers' is a list container for Saved
+ * Printers.
+ */
+Polymer({
+ is: 'settings-cups-saved-printers',
+
+ behaviors: [
+ WebUIListenerBehavior,
+ ],
+
+ properties: {
+ /**
+ * @type {!Array<!PrinterListEntry>}
+ * @private
+ */
+ savedPrinters_: {
+ type: Array,
+ value: () => [],
+ },
+
+ /**
+ * Search term for filtering |savedPrinters_|.
+ * @type {string}
+ */
+ searchTerm: {
+ type: String,
+ value: '',
+ },
+
+ /**
+ * @type {number}
+ * @private
+ */
+ activePrinterListEntryIndex_: {
+ type: Number,
+ value: -1,
+ },
+
+ /** @type {?CupsPrinterInfo} */
+ activePrinter: {
+ type: Object,
+ notify: true,
+ },
+ },
+
+ listeners: {
+ 'open-action-menu': 'onOpenActionMenu_',
+ },
+
+ /** @private {settings.CupsPrintersBrowserProxy} */
+ browserProxy_: null,
+
+ /** @override */
+ created: function() {
+ this.browserProxy_ = settings.CupsPrintersBrowserProxyImpl.getInstance();
+ },
+
+ /** @override */
+ ready: function() {
+ this.addWebUIListener(
+ 'on-printers-changed', this.printersChanged_.bind(this));
+ this.updateSavedPrintersList();
+ },
+
+ /** Public function to update the printer list. */
+ updateSavedPrintersList: function() {
+ settings.CupsPrintersBrowserProxyImpl.getInstance()
+ .getCupsPrintersList()
+ .then(this.printersChanged_.bind(this));
+ },
+
+ /**
+ * @param {!CupsPrintersList} cupsPrintersList
+ * @private
+ */
+ printersChanged_: function(cupsPrintersList) {
+ if (!cupsPrintersList) {
+ return;
+ }
+
+ this.savedPrinters_ = cupsPrintersList.printerList.map(
+ printer => /** @type {!PrinterListEntry} */({
+ printerInfo: printer,
+ printerType: PrinterType.SAVED}));
+ },
+
+ /**
+ * @param {!CustomEvent<{target: !HTMLElement, item: !PrinterListEntry}>} e
+ * @private
+ */
+ onOpenActionMenu_: function(e) {
+ const item = /** @type {!PrinterListEntry} */(e.detail.item);
+ this.activePrinterListEntryIndex_ =
+ this.savedPrinters_.findIndex(
+ printer => printer.printerInfo == item.printerInfo);
+ this.activePrinter =
+ this.get(['savedPrinters_', this.activePrinterListEntryIndex_])
+ .printerInfo;
+
+ const target = /** @type {!HTMLElement} */ (e.detail.target);
+ this.$$('cr-action-menu').showAt(target);
+ },
+
+ /** @private */
+ onEditTap_: function() {
+ // Event is caught by 'settings-cups-printers'.
+ this.fire('edit-cups-printer-details');
+ this.closeActionMenu_();
+ },
+
+ /** @private */
+ onRemoveTap_: function() {
+ this.splice('savedPrinters_', this.activePrinterListEntryIndex_, 1);
+ this.browserProxy_.removeCupsPrinter(
+ this.activePrinter.printerId, this.activePrinter.printerName);
+ this.activePrinter = null;
+ this.activeListEntryIndex_ = -1;
+ this.closeActionMenu_();
+ },
+
+ /** @private */
+ closeActionMenu_: function() {
+ this.$$('cr-action-menu').close();
+ }
+});
diff --git a/chromium/chrome/browser/resources/settings/printing_page/printing_page.html b/chromium/chrome/browser/resources/settings/printing_page/printing_page.html
index 3d892798674..ca572d61d8d 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/printing_page.html
+++ b/chromium/chrome/browser/resources/settings/printing_page/printing_page.html
@@ -19,12 +19,13 @@
focus-config="[[focusConfig_]]">
<div route-path="default">
<if expr="chromeos">
- <cr-link-row id="cupsPrinters" label="$i18n{cupsPrintersTitle}"
+ <cr-link-row hidden$="[[!showCupsPrinters_]]"
+ id="cupsPrinters" label="$i18n{cupsPrintersTitle}"
on-click="onTapCupsPrinters_"></cr-link-row>
</if>
<if expr="not chromeos">
<cr-link-row label="$i18n{localPrintersTitle}"
- on-click="onTapLocalPrinters_"></cr-link-row>
+ on-click="onTapLocalPrinters_" external></cr-link-row>
</if>
<cr-link-row class="hr" id="cloudPrinters"
label="$i18n{cloudPrintersTitle}" on-click="onTapCloudPrinters_">
diff --git a/chromium/chrome/browser/resources/settings/printing_page/printing_page.js b/chromium/chrome/browser/resources/settings/printing_page/printing_page.js
index 8bdd69e3287..678364bd05a 100644
--- a/chromium/chrome/browser/resources/settings/printing_page/printing_page.js
+++ b/chromium/chrome/browser/resources/settings/printing_page/printing_page.js
@@ -32,6 +32,18 @@ Polymer({
return map;
},
},
+
+ // <if expr="chromeos">
+ /**
+ * TODO(crbug.com/950007): Remove when SplitSettings is the default because
+ * CUPS printers will exist only in the OS settings page.
+ * @private
+ */
+ showCupsPrinters_: {
+ type: Boolean,
+ value: () => loadTimeData.getBoolean('showOSSettings'),
+ }
+ // </if>
},
// <if expr="chromeos">
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/BUILD.gn b/chromium/chrome/browser/resources/settings/privacy_page/BUILD.gn
index 3077a5790ae..a77c34ad919 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/privacy_page/BUILD.gn
@@ -9,6 +9,7 @@ js_type_check("closure_compile") {
":personalization_options",
":privacy_page",
":privacy_page_browser_proxy",
+ ":security_keys_credential_management_dialog",
":security_keys_reset_dialog",
":security_keys_set_pin_dialog",
":security_keys_subpage",
@@ -80,6 +81,21 @@ js_library("security_keys_set_pin_dialog") {
externs_list = [ "$externs_path/settings_private.js" ]
}
+js_library("security_keys_pin_field") {
+ deps = [
+ "//ui/webui/resources/js:i18n_behavior",
+ ]
+}
+
+js_library("security_keys_credential_management_dialog") {
+ deps = [
+ ":security_keys_browser_proxy",
+ ":security_keys_pin_field",
+ "//ui/webui/resources/js:i18n_behavior",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
+ ]
+}
+
js_library("security_keys_reset_dialog") {
deps = [
":security_keys_browser_proxy",
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/personalization_options.html b/chromium/chrome/browser/resources/settings/privacy_page/personalization_options.html
index 7efe994e239..491eff1b6aa 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/personalization_options.html
+++ b/chromium/chrome/browser/resources/settings/privacy_page/personalization_options.html
@@ -1,8 +1,8 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../controls/settings_toggle_button.html">
<link rel="import" href="../lifetime_browser_proxy.html">
<link rel="import" href="../people_page/sync_browser_proxy.html">
@@ -61,10 +61,10 @@
sub-label="$i18n{enableLoggingDesc}" no-set-pref
on-settings-boolean-control-change="onMetricsReportingChange_">
<template is="dom-if" if="[[showRestart_]]" restamp>
- <paper-button on-click="onRestartTap_" id="restart"
+ <cr-button on-click="onRestartTap_" id="restart"
slot="more-actions">
$i18n{restart}
- </paper-button>
+ </cr-button>
</template>
</settings-toggle-button>
</if><!-- not chromeos -->
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html b/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html
index 41fce3a2fcf..283cfb4c790 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html
+++ b/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.html
@@ -1,13 +1,13 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="security_keys_subpage.html">
<link rel="import" href="../clear_browsing_data_dialog/clear_browsing_data_dialog.html">
<link rel="import" href="../controls/settings_toggle_button.html">
@@ -69,14 +69,14 @@
<div slot="title">$i18n{doNotTrackDialogTitle}</div>
<div slot="body">$i18nRaw{doNotTrackDialogMessage}</div>
<div slot="button-container">
- <paper-button class="cancel-button"
+ <cr-button class="cancel-button"
on-click="onDoNotTrackDialogCancel_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button"
+ </cr-button>
+ <cr-button class="action-button"
on-click="onDoNotTrackDialogConfirm_">
$i18n{confirm}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
@@ -156,7 +156,7 @@
</template>
<cr-link-row id="site-settings-subpage-trigger"
class="hr"
- label="[[siteSettingsPageTitle_()]]"
+ label="$i18n{siteSettings}"
sub-label="$i18n{siteSettingsDescription}"
on-click="onSiteSettingsTap_"></cr-link-row>
<cr-link-row id="clearBrowsingData"
@@ -190,7 +190,7 @@
<settings-subpage
associated-control="[[$$('#site-settings-subpage-trigger')]]"
id="site-settings"
- page-title="[[siteSettingsPageTitle_()]]"
+ page-title="$i18n{siteSettings}"
learn-more-url="$i18n{exceptionsLearnMoreURL}">
<settings-site-settings-page focus-config="[[focusConfig_]]">
</settings-site-settings-page>
@@ -567,10 +567,10 @@
</template>
<template is="dom-if" route-path="/cookies/detail" no-search>
<settings-subpage page-title="[[pageTitle]]">
- <paper-button slot="subpage-title-extra" class="secondary-button"
+ <cr-button slot="subpage-title-extra"
on-click="onRemoveAllCookiesFromSite_">
$i18n{siteSettingsCookieRemoveAll}
- </paper-button>
+ </cr-button>
<site-data-details-subpage page-title="{{pageTitle}}">
</site-data-details-subpage>
</settings-subpage>
@@ -678,9 +678,9 @@
<if expr="not chromeos">
<cr-toast id="toast" open="[[showRestart_]]">
<div>$i18n{restartToApplyChanges}</div>
- <paper-button on-click="onRestartTap_">
+ <cr-button on-click="onRestartTap_">
$i18n{restart}
- </paper-button>
+ </cr-button>
</cr-toast>
</if>
</template>
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js b/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js
index 14bf47251ee..49ea7f9dae2 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js
+++ b/chromium/chrome/browser/resources/settings/privacy_page/privacy_page.js
@@ -389,17 +389,6 @@ Polymer({
settings.navigateTo(settings.routes.SECURITY_KEYS);
},
- /**
- * The sub-page title for the site or content settings.
- * @return {string}
- * @private
- */
- siteSettingsPageTitle_: function() {
- return loadTimeData.getBoolean('enableSiteSettings') ?
- loadTimeData.getString('siteSettings') :
- loadTimeData.getString('contentSettings');
- },
-
/** @private */
getProtectedContentLabel_: function(value) {
return value ? this.i18n('siteSettingsProtectedContentEnable') :
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_browser_proxy.js b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_browser_proxy.js
index 1be440a7f7c..0d6f5fb4ce3 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_browser_proxy.js
+++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_browser_proxy.js
@@ -4,9 +4,31 @@
cr.exportPath('settings');
+/**
+ * Credential represents a CTAP2 resident credential enumerated from a security
+ * key.
+ *
+ * id: (required) The hex encoding of the CBOR-serialized
+ * PublicKeyCredentialDescriptor of the credential.
+ *
+ * relyingPartyId: (required) The RP ID (i.e. the site that created the
+ * credential; eTLD+n)
+ *
+ * userName: (required) The PublicKeyCredentialUserEntity.name
+ *
+ * userDisplayName: (required) The PublicKeyCredentialUserEntity.display_name
+ *
+ * @typedef {{id: string,
+ * relyingPartyId: string,
+ * userName: string,
+ * userDisplayName: string}}
+ * @see chrome/browser/ui/webui/settings/settings_security_key_handler.cc
+ */
+let Credential;
+
cr.define('settings', function() {
/** @interface */
- class SecurityKeysBrowserProxy {
+ class SecurityKeysPINBrowserProxy {
/**
* Starts a PIN set/change operation by flashing all security keys. Resolves
* with a pair of numbers. The first is one if the process has immediately
@@ -15,7 +37,7 @@ cr.define('settings', function() {
* |setPIN|. In this case the second number is either the number of tries
* remaining to correctly specify the current PIN, or else null to indicate
* that no PIN is currently set.
- * @return {!Promise<Array<number>>}
+ * @return {!Promise<!Array<number>>}
*/
startSetPIN() {}
@@ -24,10 +46,60 @@ cr.define('settings', function() {
* whose meaning is the same as with |startSetPIN|. The first number will
* always be 1 to indicate that the process has completed and thus the
* second will be the CTAP error code.
- * @return {!Promise<Array<number>>}
+ * @return {!Promise<!Array<number>>}
*/
setPIN(oldPIN, newPIN) {}
+ /** Cancels all outstanding operations. */
+ close() {}
+ }
+
+ /** @interface */
+ class SecurityKeysCredentialBrowserProxy {
+ /**
+ * Starts a credential management operation.
+ *
+ * Callers must listen to errors that can occur during the operation via a
+ * 'security-keys-credential-management-error' WebListener. Values received
+ * via this listener are localized error strings. When the
+ * WebListener fires, the operation must be considered terminated.
+ *
+ * @return {!Promise} a promise that resolves when the handler is ready for
+ * the authenticator PIN to be provided.
+ */
+ startCredentialManagement() {}
+
+ /**
+ * Provides a PIN for a credential management operation. The
+ * startCredentialManagement() promise must have resolved before this method
+ * may be called.
+ * @return {!Promise<?number>} a promise that resolves with null if the PIN
+ * was correct or the number of retries remaining otherwise.
+ */
+ providePIN(pin) {}
+
+ /**
+ * Enumerates credentials on the authenticator. A correct PIN must have
+ * previously been supplied via providePIN() before this
+ * method may be called.
+ * @return {!Promise<!Array<!Credential>>}
+ */
+ enumerateCredentials() {}
+
+ /**
+ * Deletes the credentials with the given IDs from the security key.
+ * @param {!Array<string>} ids
+ * @return {!Promise<string>} a localized response message to display to
+ * the user (on either success or error)
+ */
+ deleteCredentials(ids) {}
+
+ /** Cancels all outstanding operations. */
+ close() {}
+ }
+
+ /** @interface */
+ class SecurityKeysResetBrowserProxy {
/**
* Starts a reset operation by flashing all security keys and sending a
* reset command to the one that the user activates. Resolves with a CTAP
@@ -42,16 +114,12 @@ cr.define('settings', function() {
*/
completeReset() {}
- /**
- * Cancel all outstanding operations.
- */
+ /** Cancels all outstanding operations. */
close() {}
}
- /**
- * @implements {settings.SecurityKeysBrowserProxy}
- */
- class SecurityKeysBrowserProxyImpl {
+ /** @implements {settings.SecurityKeysPINBrowserProxy} */
+ class SecurityKeysPINBrowserProxyImpl {
/** @override */
startSetPIN() {
return cr.sendWithPromise('securityKeyStartSetPIN');
@@ -63,6 +131,42 @@ cr.define('settings', function() {
}
/** @override */
+ close() {
+ return chrome.send('securityKeyPINClose');
+ }
+ }
+
+ /** @implements {settings.SecurityKeysCredentialBrowserProxy} */
+ class SecurityKeysCredentialBrowserProxyImpl {
+ /** @override */
+ startCredentialManagement() {
+ return cr.sendWithPromise('securityKeyCredentialManagementStart');
+ }
+
+ /** @override */
+ providePIN(pin) {
+ return cr.sendWithPromise('securityKeyCredentialManagementPIN', pin);
+ }
+
+ /** @override */
+ enumerateCredentials() {
+ return cr.sendWithPromise('securityKeyCredentialManagementEnumerate');
+ }
+
+ /** @override */
+ deleteCredentials(ids) {
+ return cr.sendWithPromise('securityKeyCredentialManagementDelete', ids);
+ }
+
+ /** @override */
+ close() {
+ return chrome.send('securityKeyCredentialManagementClose');
+ }
+ }
+
+ /** @implements {settings.SecurityKeysResetBrowserProxy} */
+ class SecurityKeysResetBrowserProxyImpl {
+ /** @override */
reset() {
return cr.sendWithPromise('securityKeyReset');
}
@@ -74,16 +178,23 @@ cr.define('settings', function() {
/** @override */
close() {
- return chrome.send('securityKeyClose');
+ return chrome.send('securityKeyResetClose');
}
}
// The singleton instance_ is replaced with a test version of this wrapper
// during testing.
- cr.addSingletonGetter(SecurityKeysBrowserProxyImpl);
+ cr.addSingletonGetter(SecurityKeysPINBrowserProxyImpl);
+ cr.addSingletonGetter(SecurityKeysCredentialBrowserProxyImpl);
+ cr.addSingletonGetter(SecurityKeysResetBrowserProxyImpl);
return {
- SecurityKeysBrowserProxy: SecurityKeysBrowserProxy,
- SecurityKeysBrowserProxyImpl: SecurityKeysBrowserProxyImpl,
+ SecurityKeysPINBrowserProxy: SecurityKeysPINBrowserProxy,
+ SecurityKeysPINBrowserProxyImpl: SecurityKeysPINBrowserProxyImpl,
+ SecurityKeysCredentialBrowserProxy: SecurityKeysCredentialBrowserProxy,
+ SecurityKeysCredentialBrowserProxyImpl:
+ SecurityKeysCredentialBrowserProxyImpl,
+ SecurityKeysResetBrowserProxy: SecurityKeysResetBrowserProxy,
+ SecurityKeysResetBrowserProxyImpl: SecurityKeysResetBrowserProxyImpl,
};
});
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.html b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.html
new file mode 100644
index 00000000000..a67ac0a89bc
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.html
@@ -0,0 +1,128 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
+<link rel="import" href="chrome://resources/html/i18n_behavior.html">
+<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/iron-pages/iron-pages.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
+
+<link rel="import" href="../i18n_setup.html">
+<link rel="import" href="../settings_shared_css.html">
+<link rel="import" href="../site_favicon.html">
+<link rel="import" href="security_keys_browser_proxy.html">
+<link rel="import" href="security_keys_pin_field.html">
+
+<dom-module id="settings-security-keys-credential-management-dialog">
+ <template>
+ <style include="settings-shared">
+ paper-spinner-lite {
+ padding-bottom: 12px;
+ }
+
+ #header {
+ display: flex;
+ }
+
+ .site {
+ flex: 3;
+ }
+
+ .user {
+ flex: 2;
+ }
+
+ .list-item .site {
+ align-items: center;
+ display: flex;
+ }
+
+ .list-item .site,
+ .list-item .user {
+ word-break: break-word;
+ }
+
+ site-favicon {
+ margin-inline-end: 8px;
+ min-width: 16px;
+ }
+
+ .checkbox-placeholder {
+ width: var(--cr-icon-ripple-size);
+ }
+ </style>
+
+ <cr-dialog id="dialog" close-text="$i18n{cancel}" ignore-popstate
+ on-close="onDialogClosed_">
+ <div slot="title">$i18n{securityKeysCredentialManagementDialogTitle}</div>
+
+ <div slot="body">
+ <iron-pages attr-for-selected="id" selected="[[dialogPage_]]"
+ on-iron-select="onIronSelect_">
+ <div id="initial">
+ <p>$i18n{securityKeysCredentialManagementTouch}</p>
+ <paper-spinner-lite active></paper-spinner-lite>
+ </div>
+
+ <div id="pinPrompt">
+ <p>$i18nRaw{securityKeysCredentialManagementPinPrompt}</p>
+ <settings-security-keys-pin-field id="pin">
+ </settings-security-keys-pin-field>
+ </div>
+
+ <div id="credentials">
+ <div id="header" class="list-item column-header">
+ <div class="site">$i18n{securityKeysCredentialWebsite}</div>
+ <div class="user">$i18n{securityKeysCredentialUsername}</div>
+ <div class="checkbox-placeholder"></div>
+ </div>
+
+ <div id="container">
+ <iron-list id="credentialList" items="[[credentials_]]"
+ class="cr-separators list-with-header">
+ <template>
+ <div class="list-item">
+ <div class="site" aria-label="[[item.relyingPartyId]]">
+ <site-favicon url="[[item.relyingPartyId]]">
+ </site-favicon>
+ <div>[[item.relyingPartyId]]</div>
+ </div>
+ <div class="user">[[formatUser_(item)]]</div>
+ <cr-checkbox on-change="checkedCredentialsChanged_"
+ data-id$="[[item.id]]"
+ checked="[[credentialIsChecked_(item.id)]]"
+ disabled="[[deleteInProgress_]]"></cr-checkbox>
+ </div>
+ </template>
+ </iron-list>
+ </div>
+ </div>
+
+ <div id="error">[[errorMsg_]]</div>
+ </iron-pages>
+ </div>
+
+ <div slot="button-container">
+ <cr-button id="cancelButton" class="cancel-button"
+ on-click="close_" hidden="[[!cancelButtonVisible_]]">
+ $i18n{cancel}
+ </cr-button>
+ <cr-button id="confirmButton" class="action-button"
+ on-click="confirmButtonClick_"
+ disabled="[[confirmButtonDisabled_]]"
+ hidden="[[!confirmButtonVisible_]]">
+ [[confirmButtonLabel_]]
+ </cr-button>
+ <cr-button id="closeButton" class="action-button"
+ on-click="close_"
+ hidden="[[!closeButtonVisible_]]">
+ $i18n{close}
+ </cr-button>
+ </div>
+ </cr-dialog>
+
+ </template>
+ <script src="security_keys_credential_management_dialog.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.js b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.js
new file mode 100644
index 00000000000..ce300e509eb
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_credential_management_dialog.js
@@ -0,0 +1,268 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+(function() {
+'use strict';
+
+/**
+ * @fileoverview 'settings-security-keys-credential-management-dialog' is a
+ * dialog for viewing and erasing credentials stored on a security key.
+ */
+Polymer({
+ is: 'settings-security-keys-credential-management-dialog',
+
+ behaviors: [
+ I18nBehavior,
+ WebUIListenerBehavior,
+ ],
+
+ properties: {
+ /**
+ * The ID of the element currently shown in the dialog.
+ * @private
+ */
+ dialogPage_: {
+ type: String,
+ value: 'initial',
+ observer: 'dialogPageChanged_',
+ },
+
+ /**
+ * The list of credentials displayed in the dialog.
+ * @private {!Array<!Credential>}
+ */
+ credentials_: Array,
+
+ /**
+ * The message displayed on the "error" dialog page.
+ * @private
+ */
+ errorMsg_: String,
+
+ /** @private */
+ cancelButtonVisible_: Boolean,
+
+ /** @private */
+ confirmButtonVisible_: Boolean,
+
+ /** @private */
+ confirmButtonDisabled_: Boolean,
+
+ /** @private */
+ confirmButtonLabel_: String,
+
+ /** @private */
+ closeButtonVisible_: Boolean,
+
+ /** @private */
+ deleteInProgress_: Boolean,
+ },
+
+ /** @private {?settings.SecurityKeysCredentialBrowserProxy} */
+ browserProxy_: null,
+
+ /** @private {?Set<string>} */
+ checkedCredentialIds_: null,
+
+ /** @override */
+ attached: function() {
+ this.$.dialog.showModal();
+ this.addWebUIListener(
+ 'security-keys-credential-management-finished',
+ this.onError_.bind(this));
+ this.checkedCredentialIds_ = new Set();
+ this.browserProxy_ =
+ settings.SecurityKeysCredentialBrowserProxyImpl.getInstance();
+ this.browserProxy_.startCredentialManagement().then(
+ this.collectPin_.bind(this));
+ },
+
+ /** @private */
+ collectPin_: function() {
+ this.dialogPage_ = 'pinPrompt';
+ this.$.pin.focus();
+ },
+
+ /**
+ * @private
+ * @param {string} error
+ */
+ onError_: function(error) {
+ this.errorMsg_ = error;
+ this.dialogPage_ = 'error';
+ },
+
+ /** @private */
+ submitPIN_: function() {
+ if (!this.$.pin.validate()) {
+ return;
+ }
+ this.browserProxy_.providePIN(this.$.pin.value).then((retries) => {
+ if (retries != null) {
+ this.$.pin.showIncorrectPINError(retries);
+ this.collectPin_();
+ return;
+ }
+ this.browserProxy_.enumerateCredentials().then(
+ this.onCredentials_.bind(this));
+ });
+ },
+
+ /**
+ * @param {number} retries
+ * @return {string} localized error string for an invalid PIN attempt and a
+ * given number of remaining retries.
+ */
+ pinRetriesError_: function(retries) {
+ // Warn the user if the number of retries is getting low.
+ if (1 < retries && retries <= 3) {
+ return this.i18n('securityKeysPINIncorrectRetriesPl', retries.toString());
+ }
+ return this.i18n(
+ retries == 1 ? 'securityKeysPINIncorrectRetriesSin' :
+ 'securityKeysPINIncorrect');
+ },
+
+ /**
+ * @private
+ * @param {!Array<!Credential>} credentials
+ */
+ onCredentials_: function(credentials) {
+ if (!credentials.length) {
+ this.onError_(this.i18n('securityKeysCredentialManagementNoCredentials'));
+ return;
+ }
+ this.credentials_ = credentials;
+ this.$.credentialList.fire('iron-resize');
+ this.dialogPage_ = 'credentials';
+ },
+
+ /** @private */
+ dialogPageChanged_: function() {
+ switch (this.dialogPage_) {
+ case 'initial':
+ this.cancelButtonVisible_ = true;
+ this.confirmButtonVisible_ = false;
+ this.closeButtonVisible_ = false;
+ break;
+ case 'pinPrompt':
+ this.cancelButtonVisible_ = true;
+ this.confirmButtonLabel_ = this.i18n('continue');
+ this.confirmButtonDisabled_ = false;
+ this.confirmButtonVisible_ = true;
+ this.closeButtonVisible_ = false;
+ break;
+ case 'credentials':
+ this.cancelButtonVisible_ = true;
+ this.confirmButtonLabel_ =
+ this.i18n('securityKeysCredentialManagementErase');
+ this.confirmButtonDisabled_ = true;
+ this.confirmButtonVisible_ = true;
+ this.closeButtonVisible_ = false;
+ break;
+ case 'error':
+ this.cancelButtonVisible_ = false;
+ this.confirmButtonVisible_ = false;
+ this.closeButtonVisible_ = true;
+ break;
+ }
+ this.fire('credential-management-dialog-ready-for-testing');
+ },
+
+ /** @private */
+ confirmButtonClick_: function() {
+ switch (this.dialogPage_) {
+ case 'pinPrompt':
+ this.submitPIN_();
+ break;
+ case 'credentials':
+ this.deleteSelectedCredentials_();
+ break;
+ default:
+ assertNotReached();
+ }
+ },
+
+ /** @private */
+ close_: function() {
+ this.$.dialog.close();
+ },
+
+ /**
+ * Stringifies the user entity of a Credential for display in the dialog.
+ * @private
+ * @param {!Credential} credential
+ * @return {string}
+ */
+ formatUser_: function(credential) {
+ if (this.isEmpty_(credential.userDisplayName)) {
+ return credential.userName;
+ }
+ return `${credential.userDisplayName} (${credential.userName})`;
+ },
+
+ /** @private */
+ onDialogClosed_: function() {
+ this.browserProxy_.close();
+ },
+
+ /**
+ * @private
+ * @param {?string} str
+ * @return {boolean} Whether this credential has been selected for removal.
+ */
+ isEmpty_: function(str) {
+ return !str || str.length == 0;
+ },
+
+ /**
+ * @param {!Event} e
+ * @private
+ */
+ onIronSelect_: function(e) {
+ // Prevent this event from bubbling since it is unnecessarily triggering the
+ // listener within settings-animated-pages.
+ e.stopPropagation();
+ },
+
+ /**
+ * Handler for checking or unchecking a credential.
+ * @param {!Event} e
+ * @private
+ */
+ checkedCredentialsChanged_: function(e) {
+ const credentialId = e.target.dataset.id;
+ if (e.target.checked) {
+ this.checkedCredentialIds_.add(credentialId);
+ } else {
+ this.checkedCredentialIds_.delete(credentialId);
+ }
+ this.confirmButtonDisabled_ = this.checkedCredentialIds_.size == 0;
+ },
+
+ /**
+ * @private
+ * @param {string} credentialId
+ * @return {boolean} true if the checkbox for |credentialId| is checked
+ */
+ credentialIsChecked_: function(credentialId) {
+ return this.checkedCredentialIds_.has(credentialId);
+ },
+
+ /** @private */
+ deleteSelectedCredentials_: function() {
+ assert(this.dialogPage_ == 'credentials');
+ assert(this.credentials_ && this.credentials_.length > 0);
+ assert(this.checkedCredentialIds_.size > 0);
+
+ this.deleteInProgress_ = true;
+ this.browserProxy_.deleteCredentials(Array.from(this.checkedCredentialIds_))
+ .then((err) => {
+ this.deleteInProgress_ = false;
+ this.onError_(err);
+ });
+ },
+
+});
+})();
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_pin_field.html b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_pin_field.html
new file mode 100644
index 00000000000..bd62a4001c0
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_pin_field.html
@@ -0,0 +1,34 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/html/i18n_behavior.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
+<link rel="import" href="../i18n_setup.html">
+<link rel="import" href="../settings_shared_css.html">
+
+<dom-module id="settings-security-keys-pin-field">
+ <template>
+ <style include="settings-shared">
+ cr-input {
+ display: inline-block;
+ padding-inline-end: 2em;
+ --cr-input-width: 8em;
+ }
+ </style>
+
+ <cr-input id="pin" value="{{value}}" minLength="4"
+ maxLength="255" spellcheck="false"
+ on-input="onPINInput_"
+ invalid="[[isNonEmpty_(error)]]"
+ label="[[label]]" tabindex="0"
+ type$="[[inputType_(inputVisible_)]]"
+ error-message="[[error]]">
+ <cr-icon-button slot="suffix" id="showButton"
+ class$="[[showButtonClass_(inputVisible_)]]"
+ title="[[showButtonTitle_(inputVisible_)]]"
+ focus-row-control focus-type="showPassword"
+ on-click="showButtonClick_"></cr-icon-button>
+ </cr-input>
+ </template>
+ <script src="security_keys_pin_field.js"></script>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_pin_field.js b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_pin_field.js
new file mode 100644
index 00000000000..abace08a7e0
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_pin_field.js
@@ -0,0 +1,161 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview 'settings-security-keys-pin-field' is a component for entering
+ * a security key PIN.
+ */
+Polymer({
+ is: 'settings-security-keys-pin-field',
+
+ behaviors: [
+ I18nBehavior,
+ ],
+
+ properties: {
+ /** The label of the input field. */
+ label: String,
+
+ /** The validation error label of the input field. */
+ error: String,
+
+ /** The value of the input field. */
+ value: String,
+
+ /**
+ * Whether the contents of the input field are visible.
+ * @private
+ */
+ inputVisible_: Boolean,
+ },
+
+ /** @override */
+ attached: function() {
+ this.inputVisible_ = false;
+ },
+
+ /** Focuses the PIN input field. */
+ focus: function() {
+ this.$.pin.focus();
+ },
+
+ /**
+ * Validates the PIN and sets the validation error if it is not valid.
+ * @return {boolean} True iff the PIN is valid.
+ */
+ validate: function() {
+ const error = this.isValidPIN_(this.value);
+ if (error != '') {
+ this.error = error;
+ return false;
+ }
+ return true;
+ },
+
+ /**
+ * Sets the validation error to indicate the PIN was incorrect.
+ * @param {number} retries The number of retries remaining.
+ */
+ showIncorrectPINError: function(retries) {
+ // Warn the user if the number of retries is getting low.
+ let error;
+ if (1 < retries && retries <= 3) {
+ error =
+ this.i18n('securityKeysPINIncorrectRetriesPl', retries.toString());
+ } else if (retries == 1) {
+ error = this.i18n('securityKeysPINIncorrectRetriesSin');
+ } else {
+ error = this.i18n('securityKeysPINIncorrect');
+ }
+ this.error = error;
+ },
+
+ /** @private */
+ onPINInput_: function() {
+ // Typing in the PIN box after an error makes the error message
+ // disappear.
+ this.error = '';
+ },
+
+ /**
+ * Polymer helper function to detect when an error string is empty.
+ * @param {string} s Arbitrary string
+ * @return {boolean} True iff |s| is non-empty.
+ * @private
+ */
+ isNonEmpty_: function(s) {
+ return s != '';
+ },
+
+ /**
+ * @return {string} The PIN-input element type.
+ * @private
+ */
+ inputType_: function() {
+ return this.inputVisible_ ? 'text' : 'password';
+ },
+
+ /**
+ * @return {string} The class (and thus icon) to be displayed.
+ * @private
+ */
+ showButtonClass_: function() {
+ return 'icon-visibility' + (this.inputVisible_ ? '-off' : '');
+ },
+
+ /**
+ * @return {string} The tooltip for the icon.
+ * @private
+ */
+ showButtonTitle_: function() {
+ return this.i18n(
+ this.inputVisible_ ? 'securityKeysHidePINs' : 'securityKeysShowPINs');
+ },
+
+ /**
+ * onClick handler for the show/hide icon.
+ * @private
+ */
+ showButtonClick_: function() {
+ this.inputVisible_ = !this.inputVisible_;
+ },
+
+ /**
+ * @param {string} pin A candidate PIN.
+ * @return {string} An error string or else '' to indicate validity.
+ * @private
+ */
+ isValidPIN_: function(pin) {
+ // The UTF-8 encoding of the PIN must be between 4
+ // and 63 bytes, and the final byte cannot be zero.
+ const utf8Encoded = new TextEncoder().encode(pin);
+ if (utf8Encoded.length < 4) {
+ return this.i18n('securityKeysPINTooShort');
+ }
+ if (utf8Encoded.length > 63 ||
+ // If the PIN somehow has a NUL at the end then it's invalid, but this
+ // is so obscure that we don't try to message it. Rather we just say
+ // that it's too long because trimming the final character is the best
+ // response by the user.
+ utf8Encoded[utf8Encoded.length - 1] == 0) {
+ return this.i18n('securityKeysPINTooLong');
+ }
+
+ // A PIN must contain at least four code-points. Javascript strings are
+ // UCS-2 and the |length| property counts UCS-2 elements, not code-points.
+ // (For example, '\u{1f6b4}'.length == 2, but it's a single code-point.)
+ // Therefore, iterate over the string (which does yield codepoints) and
+ // check that four or more were seen.
+ let length = 0;
+ for (const codepoint of pin) {
+ length++;
+ }
+
+ if (length < 4) {
+ return this.i18n('securityKeysPINTooShort');
+ }
+
+ return '';
+ },
+});
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_reset_dialog.html b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_reset_dialog.html
index fdec7c89f13..9313a82657b 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_reset_dialog.html
+++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_reset_dialog.html
@@ -1,9 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-pages/iron-pages.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../settings_shared_css.html">
@@ -20,7 +20,8 @@
on-close="closeDialog_">
<div slot="title">[[title_]]</div>
<div slot="body">
- <iron-pages attr-for-selected="id" selected="[[shown_]]">
+ <iron-pages attr-for-selected="id" selected="[[shown_]]"
+ on-iron-select="onIronSelect_">
<div id="initial">
<p>$i18n{securityKeysResetStep1}</p>
<paper-spinner-lite active></paper-spinner-lite>
@@ -48,10 +49,10 @@
</iron-pages>
</div>
<div slot="button-container">
- <paper-button id="button" class$="[[maybeActionButton_(complete_)]]"
+ <cr-button id="button" class$="[[maybeActionButton_(complete_)]]"
on-click="closeDialog_">
[[closeText_(complete_)]]
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_reset_dialog.js b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_reset_dialog.js
index 8d433ba840e..ce37c7e591c 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_reset_dialog.js
+++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_reset_dialog.js
@@ -42,13 +42,14 @@ Polymer({
title_: String,
},
- /** @private {?settings.SecurityKeysBrowserProxy} */
+ /** @private {?settings.SecurityKeysResetBrowserProxy} */
browserProxy_: null,
/** @override */
attached: function() {
this.title_ = this.i18n('securityKeysResetTitle');
- this.browserProxy_ = settings.SecurityKeysBrowserProxyImpl.getInstance();
+ this.browserProxy_ =
+ settings.SecurityKeysResetBrowserProxyImpl.getInstance();
this.$.dialog.showModal();
this.browserProxy_.reset().then(code => {
@@ -96,6 +97,16 @@ Polymer({
},
/**
+ * @param {!Event} e
+ * @private
+ */
+ onIronSelect_: function(e) {
+ // Prevent this event from bubbling since it is unnecessarily triggering the
+ // listener within settings-animated-pages.
+ e.stopPropagation();
+ },
+
+ /**
@param {number} code CTAP error code.
@return {string} Contents of the error string that may be displayed
to the user. Used automatically by Polymer.
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.html b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.html
index 96abaa0724b..2e6c0a4942f 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.html
+++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.html
@@ -1,10 +1,12 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-pages/iron-pages.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../settings_shared_css.html">
@@ -15,10 +17,13 @@
<style include="settings-shared">
cr-input {
display: inline-block;
- padding-inline-end: 2em;
--cr-input-width: 8em;
}
+ #newPIN {
+ padding-inline-end: 2em;
+ }
+
#newPINRow {
display: flex;
flex-direction: row;
@@ -33,7 +38,8 @@
on-close="closeDialog_">
<div slot="title">[[title_]]</div>
<div slot="body">
- <iron-pages attr-for-selected="id" selected="[[shown_]]">
+ <iron-pages attr-for-selected="id" selected="[[shown_]]"
+ on-iron-select="onIronSelect_">
<div id="initial">
<p>$i18n{securityKeysPINTouch}</p>
<paper-spinner-lite active></paper-spinner-lite>
@@ -44,30 +50,57 @@
</div>
<div id="pinPrompt">
- <div id="currentPINEntry">
+ <div id="currentPINEntry" hidden="[[!showCurrentEntry_]]">
<p>$i18nRaw{securityKeysCurrentPINIntro}</p>
- <cr-input id="currentPIN" value="{{currentPIN_}}" minLength="4"
- maxLength="255" spellcheck="false"
- on-input="validateCurrentPIN_" invalid="[[!currentPINValid_]]"
- label="$i18n{securityKeysCurrentPIN}" tabindex="0"
- type="password"
- error-message="[[mismatchErrorText_(mismatchErrorVisible_, retries_)]]">
- </cr-input>
+ <div id="currentPINRow">
+ <cr-input id="currentPIN" value="{{currentPIN_}}" minLength="4"
+ maxLength="255" spellcheck="false"
+ on-input="onCurrentPINInput_"
+ invalid="[[isNonEmpty_(currentPINError_)]]"
+ label="$i18n{securityKeysCurrentPIN}" tabindex="0"
+ type$="[[inputType_(pinsVisible_)]]"
+ error-message="[[currentPINError_]]">
+ <cr-icon-button slot="suffix" id="showPINsButton"
+ class$="[[showPINsClass_(pinsVisible_)]]"
+ title="[[showPINsTitle_(pinsVisible_)]]"
+ focus-row-control focus-type="showPassword"
+ on-click="showPINsClick_"></cr-icon-button>
+ </cr-input>
+
+ </div>
</div>
<p>$i18n{securityKeysNewPIN}</p>
<div id="newPINRow">
<cr-input id="newPIN" value="{{newPIN_}}" minLength="4"
- maxLength="255" spellcheck="false" on-input="validateNewPIN_"
- invalid="[[!newPINValid_]]" label="$i18n{securityKeysPIN}"
- tabindex="0" type="password"></cr-input>
+ maxLength="255" spellcheck="false" on-input="onNewPINInput_"
+ label="$i18n{securityKeysPIN}"
+ tabindex="0" type$="[[inputType_(pinsVisible_)]]"
+ invalid="[[isNonEmpty_(newPINError_)]]"
+ error-message="[[newPINError_]]">
+ <!-- If a show/hide icon is included in this row, this div is
+ needed to ensure that the cr-input is the same height
+ as the one to the right. Otherwise they don't vertically
+ align -->
+ <div style="height: 36px" slot="suffix"
+ hidden="[[showCurrentEntry_]]"></div>
+ </cr-input>
<cr-input id="confirmPIN" value="{{confirmPIN_}}" minLength="4"
maxLength="255" spellcheck="false"
- on-input="validateConfirmPIN_" invalid="[[!confirmPINValid_]]"
+ on-input="onConfirmPINInput_"
label="$i18n{securityKeysConfirmPIN}" tabindex="0"
- type="password"></cr-input>
+ invalid="[[isNonEmpty_(confirmPINError_)]]"
+ type$="[[inputType_(pinsVisible_)]]"
+ error-message="[[confirmPINError_]]">
+ <cr-icon-button slot="suffix"
+ class$="[[showPINsClass_(pinsVisible_)]]"
+ title="[[showPINsTitle_(pinsVisible_)]]"
+ hidden="[[showCurrentEntry_]]"
+ focus-row-control focus-type="showPassword"
+ on-click="showPINsClick_"></cr-icon-button>
+ </cr-input>
</div>
</div>
@@ -90,16 +123,16 @@
</div>
<div slot="button-container">
- <paper-button id="closeButton"
+ <cr-button id="closeButton"
class$="[[maybeActionButton_(complete_)]]"
on-click="closeDialog_">
[[closeText_(complete_)]]
- </paper-button>
- <paper-button id="pinSubmit" class="action-button"
+ </cr-button>
+ <cr-button id="pinSubmit" class="action-button"
on-click="pinSubmitNew_" disabled="[[!setPINButtonValid_]]"
hidden="[[complete_]]">
$i18n{securityKeysSetPINConfirm}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.js b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.js
index 1ed18cea22b..4cadbca4e28 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.js
+++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_set_pin_dialog.js
@@ -6,33 +6,6 @@
'use strict';
/**
- @param {string} pin A candidate PIN.
- @return {boolean} Whether the parameter was a valid PIN.
- @private
- */
-function isValidPIN(pin) {
- // The UTF-8 encoding of the PIN must be between 4 and 63 bytes, and the
- // final byte cannot be zero.
- const utf8Encoded = new TextEncoder().encode(pin);
- if (utf8Encoded.length < 4 || utf8Encoded.length > 63 ||
- utf8Encoded[utf8Encoded.length - 1] == 0) {
- return false;
- }
-
- // A PIN must contain at least four code-points. Javascript strings are UCS-2
- // and the |length| property counts UCS-2 elements, not code-points. (For
- // example, '\u{1f6b4}'.length == 2, but it's a single code-point.) Therefore,
- // iterate over the string (which does yield codepoints) and check that four
- // or more were seen.
- let length = 0;
- for (const codepoint of pin) {
- length++;
- }
-
- return length >= 4;
-}
-
-/**
* @fileoverview 'settings-security-keys-set-pin-dialog' is a dialog for
* setting and changing security key PINs.
*/
@@ -99,15 +72,43 @@ Polymer({
errorCode_: Number,
/**
- * Whether the error message indicating an incorrect PIN should be visible.
+ * Whether an entry for the current PIN should be displayed. (If no PIN
+ * has been set then it won't be shown.)
* @private
*/
- mismatchErrorVisible_: {
+ showCurrentEntry_: {
type: Boolean,
value: false,
},
/**
+ * Error string to display under the current PIN entry, or empty.
+ * @private
+ */
+ currentPINError_: {
+ type: String,
+ value: '',
+ },
+
+ /**
+ * Error string to display under the new PIN entry, or empty.
+ * @private
+ */
+ newPINError_: {
+ type: String,
+ value: '',
+ },
+
+ /**
+ * Error string to display under the confirmation PIN entry, or empty.
+ * @private
+ */
+ confirmPINError_: {
+ type: String,
+ value: '',
+ },
+
+ /**
* Whether the dialog process has completed, successfully or otherwise.
* @private
*/
@@ -125,38 +126,48 @@ Polymer({
value: 'initial',
},
+ /**
+ * Whether the contents of the PIN entries are visible, or are displayed
+ * like passwords.
+ * @private
+ */
+ pinsVisible_: {
+ type: Boolean,
+ value: false,
+ },
+
/** @private */
title_: String,
},
- /** @private {?settings.SecurityKeysBrowserProxy} */
+ /** @private {?settings.SecurityKeysPINBrowserProxy} */
browserProxy_: null,
/** @override */
attached: function() {
this.title_ = this.i18n('securityKeysSetPINInitialTitle');
- this.browserProxy_ = settings.SecurityKeysBrowserProxyImpl.getInstance();
+ this.browserProxy_ = settings.SecurityKeysPINBrowserProxyImpl.getInstance();
this.$.dialog.showModal();
- this.browserProxy_.startSetPIN().then(result => {
- if (result[0]) {
- // Operation is complete. result[1] is a CTAP error code. See
+ this.browserProxy_.startSetPIN().then(([success, errorCode]) => {
+ if (success) {
+ // Operation is complete. errorCode is a CTAP error code. See
// https://fidoalliance.org/specs/fido-v2.0-rd-20180702/fido-client-to-authenticator-protocol-v2.0-rd-20180702.html#error-responses
- if (result[1] == 1 /* INVALID_COMMAND */) {
+ if (errorCode == 1 /* INVALID_COMMAND */) {
this.shown_ = 'noPINSupport';
this.finish_();
- } else if (result[1] == 52 /* temporarily locked */) {
+ } else if (errorCode == 52 /* temporarily locked */) {
this.shown_ = 'reinsert';
this.finish_();
- } else if (result[1] == 50 /* locked */) {
+ } else if (errorCode == 50 /* locked */) {
this.shown_ = 'locked';
this.finish_();
} else {
- this.errorCode_ = result[1];
+ this.errorCode_ = errorCode;
this.shown_ = 'error';
this.finish_();
}
- } else if (result[1] == 0) {
+ } else if (errorCode == 0) {
// A device can also signal that it is locked by returning zero retries.
this.shown_ = 'locked';
this.finish_();
@@ -166,16 +177,17 @@ Polymer({
this.currentPINValid_ = true;
this.newPINValid_ = true;
this.confirmPINValid_ = true;
+ this.setPINButtonValid_ = true;
- this.retries_ = result[1];
+ this.retries_ = errorCode;
// retries_ may be null to indicate that there is currently no PIN set.
let focusTarget;
if (this.retries_ === null) {
- this.$.currentPINEntry.hidden = true;
+ this.showCurrentEntry_ = false;
focusTarget = this.$.newPIN;
this.title_ = this.i18n('securityKeysSetPINCreateTitle');
} else {
- this.$.currentPINEntry.hidden = false;
+ this.showCurrentEntry_ = true;
focusTarget = this.$.currentPIN;
this.title_ = this.i18n('securityKeysSetPINChangeTitle');
}
@@ -202,44 +214,116 @@ Polymer({
return;
}
this.complete_ = true;
+ // Setting |complete_| to true hides the |pinSubmitNew| button while it
+ // has focus, which in turn causes the browser to move focus to the <body>
+ // element, which in turn prevents subsequent "Enter" keystrokes to be
+ // handled by cr-dialog itself. Re-focusing manually fixes this.
+ this.$.dialog.focus();
this.browserProxy_.close();
},
- /** @private */
- updatePINButtonValid_: function() {
- this.setPINButtonValid_ =
- (this.$.currentPINEntry.hidden ||
- (this.currentPINValid_ && this.currentPIN_.length > 0)) &&
- this.newPINValid_ && this.newPIN_.length > 0 && this.confirmPINValid_ &&
- this.confirmPIN_.length > 0;
+ /**
+ * @param {!Event} e
+ * @private
+ */
+ onIronSelect_: function(e) {
+ // Prevent this event from bubbling since it is unnecessarily triggering the
+ // listener within settings-animated-pages.
+ e.stopPropagation();
},
/** @private */
- validateCurrentPIN_: function() {
- this.currentPINValid_ = isValidPIN(this.currentPIN_);
- this.updatePINButtonValid_();
+ onCurrentPINInput_: function() {
// Typing in the current PIN box after an error makes the error message
// disappear.
- this.mismatchErrorVisible_ = false;
+ this.currentPINError_ = '';
},
/** @private */
- validateNewPIN_: function() {
- this.newPINValid_ = isValidPIN(this.newPIN_);
- // The new PIN might have been changed to match the confirmation PIN, thus
- // changing it might make the confirmation PIN valid. An empty value is
- // considered valid to stop it immediately turning red before the user has
- // entered anything, but |updatePINButtonValid_| knows that it needs to be
- // non-empty before the dialog can be submitted.
- this.confirmPINValid_ = this.confirmPIN_.length == 0 ||
- (this.newPINValid_ && this.confirmPIN_ == this.newPIN_);
- this.updatePINButtonValid_();
+ onNewPINInput_: function() {
+ // Typing in the new PIN box after an error makes the error message
+ // disappear.
+ this.newPINError_ = '';
},
/** @private */
- validateConfirmPIN_: function() {
- this.confirmPINValid_ = this.confirmPIN_ == this.newPIN_;
- this.updatePINButtonValid_();
+ onConfirmPINInput_: function() {
+ // Typing in the confirm PIN box after an error makes the error message
+ // disappear.
+ this.confirmPINError_ = '';
+ },
+
+ /**
+ @param {string} pin A candidate PIN.
+ @return {string} An error string or else '' to indicate validity.
+ @private
+ */
+ isValidPIN_: function(pin) {
+ // The UTF-8 encoding of the PIN must be between 4 and 63 bytes, and the
+ // final byte cannot be zero.
+ const utf8Encoded = new TextEncoder().encode(pin);
+ if (utf8Encoded.length < 4) {
+ return this.i18n('securityKeysPINTooShort');
+ }
+ if (utf8Encoded.length > 63 ||
+ // If the PIN somehow has a NUL at the end then it's invalid, but this
+ // is so obscure that we don't try to message it. Rather we just say
+ // that it's too long because trimming the final character is the best
+ // response by the user.
+ utf8Encoded[utf8Encoded.length - 1] == 0) {
+ return this.i18n('securityKeysPINTooLong');
+ }
+
+ // A PIN must contain at least four code-points. Javascript strings are
+ // UCS-2 and the |length| property counts UCS-2 elements, not code-points.
+ // (For example, '\u{1f6b4}'.length == 2, but it's a single code-point.)
+ // Therefore, iterate over the string (which does yield codepoints) and
+ // check that four or more were seen.
+ let length = 0;
+ for (const codepoint of pin) {
+ length++;
+ }
+
+ if (length < 4) {
+ return this.i18n('securityKeysPINTooShort');
+ }
+
+ return '';
+ },
+
+ /**
+ * @param {number} retries The number of PIN attempts remaining.
+ * @return {string} The message to show under the text box.
+ * @private
+ */
+ mismatchError_: function(retries) {
+ // Warn the user if the number of retries is getting low.
+ if (1 < retries && retries <= 3) {
+ return this.i18n('securityKeysPINIncorrectRetriesPl', retries.toString());
+ }
+ if (retries == 1) {
+ return this.i18n('securityKeysPINIncorrectRetriesSin');
+ }
+ return this.i18n('securityKeysPINIncorrect');
+ },
+
+ /**
+ * Called to set focus from inside a callback.
+ * @private
+ */
+ focusOn_: function(focusTarget) {
+ // Focus cannot be set directly from within a backend callback. Also,
+ // directly focusing |currentPIN| doesn't always seem to work(!). Thus
+ // focus something else first, which is a hack that seems to solve the
+ // problem.
+ let preFocusTarget = this.$.newPIN;
+ if (preFocusTarget == focusTarget) {
+ preFocusTarget = this.$.currentPIN;
+ }
+ window.setTimeout(function() {
+ preFocusTarget.focus();
+ focusTarget.focus();
+ }, 0);
},
/**
@@ -247,6 +331,29 @@ Polymer({
* @private
*/
pinSubmitNew_: function() {
+ if (this.showCurrentEntry_) {
+ this.currentPINError_ = this.isValidPIN_(this.currentPIN_);
+ if (this.currentPINError_ != '') {
+ this.focusOn_(this.$.currentPIN);
+ this.fire('ui-ready'); // for test synchronization.
+ return;
+ }
+ }
+
+ this.newPINError_ = this.isValidPIN_(this.newPIN_);
+ if (this.newPINError_ != '') {
+ this.focusOn_(this.$.newPIN);
+ this.fire('ui-ready'); // for test synchronization.
+ return;
+ }
+
+ if (this.newPIN_ != this.confirmPIN_) {
+ this.confirmPINError_ = this.i18n('securityKeysPINMismatch');
+ this.focusOn_(this.$.confirmPIN);
+ this.fire('ui-ready'); // for test synchronization.
+ return;
+ }
+
this.setPINButtonValid_ = false;
this.browserProxy_.setPIN(this.currentPIN_, this.newPIN_).then(result => {
// This call always completes the process so result[0] is always 1.
@@ -262,21 +369,11 @@ Polymer({
this.shown_ = 'locked';
this.finish_();
} else if (result[1] == 49 /* PIN_INVALID */) {
- this.currentPIN_ = '';
this.currentPINValid_ = false;
this.retries_--;
- this.mismatchErrorVisible_ = true;
-
- // Focus cannot be set directly from within a backend callback. Also,
- // directly focusing |currentPIN| doesn't always seem to work(!). Thus
- // focus something else first, which is a hack that seems to solve the
- // problem.
- const preFocusTarget = this.$.newPIN;
- const focusTarget = this.$.currentPIN;
- window.setTimeout(function() {
- preFocusTarget.focus();
- focusTarget.focus();
- }, 0);
+ this.currentPINError_ = this.mismatchError_(this.retries_);
+ this.setPINButtonValid_ = true;
+ this.focusOn_(this.$.currentPIN);
this.fire('ui-ready'); // for test synchronization.
} else {
// Unknown error.
@@ -288,56 +385,73 @@ Polymer({
},
/**
- * Called by Polymer when |errorCode_| changes to set the error string.
- * @param {number} code A CTAP error code.
+ * onClick handler for the show/hide icon.
* @private
*/
- pinFailed_: function(code) {
- if (code === null) {
- return '';
- }
- return this.i18n('securityKeysPINError', code.toString());
+ showPINsClick_: function() {
+ this.pinsVisible_ = !this.pinsVisible_;
},
/**
- * Called by Polymer to set the error text displayed when the user enters an
- * incorrect PIN.
- * @param {boolean} show Whether or not an error message should be shown.
- * @param {number} retries The number of PIN attempts remaining.
- * @return {string} The message to show under the text box.
+ * Polymer helper function to detect when an error string is empty.
+ * @param {string} s Arbitrary string
+ * @return {boolean} True iff |s| is non-empty.
* @private
*/
- mismatchErrorText_: function(show, retries) {
- if (!show) {
- return '';
- }
+ isNonEmpty_: function(s) {
+ return s != '';
+ },
- // Warn the user if the number of retries is getting low.
- if (1 < retries && retries <= 3) {
- return this.i18n('securityKeysPINIncorrectRetriesPl', retries.toString());
- }
- if (retries == 1) {
- return this.i18n('securityKeysPINIncorrectRetriesSin');
+ /**
+ * Called by Polymer when |errorCode_| changes to set the error string.
+ * @private
+ */
+ pinFailed_: function() {
+ if (this.errorCode_ === null) {
+ return '';
}
- return this.i18n('securityKeysPINIncorrect');
+ return this.i18n('securityKeysPINError', this.errorCode_.toString());
},
/**
- * @param {boolean} complete Whether the dialog process is complete.
* @return {string} The class of the Ok / Cancel button.
* @private
*/
- maybeActionButton_: function(complete) {
- return complete ? 'action-button' : 'cancel-button';
+ maybeActionButton_: function() {
+ return this.complete_ ? 'action-button' : 'cancel-button';
},
/**
- * @param {boolean} complete Whether the dialog process is complete.
* @return {string} The label of the Ok / Cancel button.
* @private
*/
- closeText_: function(complete) {
- return this.i18n(complete ? 'ok' : 'cancel');
+ closeText_: function() {
+ return this.i18n(this.complete_ ? 'ok' : 'cancel');
+ },
+
+ /**
+ * @return {string} The class (and thus icon) to be displayed.
+ * @private
+ */
+ showPINsClass_: function() {
+ return 'icon-visibility' + (this.pinsVisible_ ? '-off' : '');
+ },
+
+ /**
+ * @return {string} The tooltip for the icon.
+ * @private
+ */
+ showPINsTitle_: function() {
+ return this.i18n(
+ this.pinsVisible_ ? 'securityKeysHidePINs' : 'securityKeysShowPINs');
+ },
+
+ /**
+ * @return {string} The PIN-input element type.
+ * @private
+ */
+ inputType_: function() {
+ return this.pinsVisible_ ? 'text' : 'password';
},
});
})();
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.html b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.html
index 496b5bf74d7..e1d58b335fd 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.html
+++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.html
@@ -5,6 +5,7 @@
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="../settings_shared_css.html">
+<link rel="import" href="security_keys_credential_management_dialog.html">
<link rel="import" href="security_keys_set_pin_dialog.html">
<link rel="import" href="security_keys_reset_dialog.html">
@@ -17,6 +18,14 @@
label="$i18n{securityKeysSetPIN}"
sub-label="$i18n{securityKeysSetPINDesc}"
on-click="onSetPIN_"></cr-link-row>
+ <template is="dom-if" if="[[enableCredentialManagement_]]">
+ <cr-link-row
+ id="credentialManagementButton"
+ class="hr"
+ label="$i18n{securityKeysCredentialManagementLabel}"
+ sub-label="$i18n{securityKeysCredentialManagementDesc}"
+ on-click="onCredentialManagement_"></cr-link-row>
+ </template>
<cr-link-row
id="resetButton"
class="hr"
@@ -29,6 +38,12 @@
</settings-security-keys-set-pin-dialog>
</template>
+ <template is="dom-if" if="[[showCredentialManagementDialog_]]" restamp>
+ <settings-security-keys-credential-management-dialog
+ on-close="onCredentialManagementDialogClosed_">
+ </settings-security-keys-credential-management-dialog>
+ </template>
+
<template is="dom-if" if="[[showResetDialog_]]" restamp>
<settings-security-keys-reset-dialog on-close="onResetDialogClosed_">
</settings-security-keys-reset-dialog>
diff --git a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.js b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.js
index a27010d8480..b0eee4155a2 100644
--- a/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.js
+++ b/chromium/chrome/browser/resources/settings/privacy_page/security_keys_subpage.js
@@ -11,11 +11,26 @@ Polymer({
properties: {
/** @private */
+ enableCredentialManagement_: {
+ type: Boolean,
+ readOnly: true,
+ value: function() {
+ return loadTimeData.getBoolean(
+ 'enableSecurityKeysCredentialManagement');
+ }
+ },
+
+ /** @private */
showSetPINDialog_: {
type: Boolean,
value: false,
},
/** @private */
+ showCredentialManagementDialog_: {
+ type: Boolean,
+ value: false,
+ },
+ /** @private */
showResetDialog_: {
type: Boolean,
value: false,
@@ -34,6 +49,17 @@ Polymer({
},
/** @private */
+ onCredentialManagement_: function() {
+ this.showCredentialManagementDialog_ = true;
+ },
+
+ /** @private */
+ onCredentialManagementDialogClosed_: function() {
+ this.showCredentialManagementDialog_ = false;
+ cr.ui.focusWithoutInk(this.$.credentialManagementButton);
+ },
+
+ /** @private */
onReset_: function() {
this.showResetDialog_ = true;
},
diff --git a/chromium/chrome/browser/resources/settings/reset_page/powerwash_dialog.html b/chromium/chrome/browser/resources/settings/reset_page/powerwash_dialog.html
index 90e2a12173d..965e35fc1e5 100644
--- a/chromium/chrome/browser/resources/settings/reset_page/powerwash_dialog.html
+++ b/chromium/chrome/browser/resources/settings/reset_page/powerwash_dialog.html
@@ -1,7 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../lifetime_browser_proxy.html">
<link rel="import" href="reset_browser_proxy.html">
<link rel="import" href="../settings_shared_css.html">
@@ -22,10 +22,10 @@
</span>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelTap_"
- id="cancel">$i18n{cancel}</paper-button>
- <paper-button class="action-button" id="powerwash"
- on-click="onRestartTap_">$i18n{powerwashDialogButton}</paper-button>
+ <cr-button class="cancel-button" on-click="onCancelTap_"
+ id="cancel">$i18n{cancel}</cr-button>
+ <cr-button class="action-button" id="powerwash"
+ on-click="onRestartTap_">$i18n{powerwashDialogButton}</cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/reset_page/reset_profile_banner.html b/chromium/chrome/browser/resources/settings/reset_page/reset_profile_banner.html
index 3eaaf424724..57fdf7ac742 100644
--- a/chromium/chrome/browser/resources/settings/reset_page/reset_profile_banner.html
+++ b/chromium/chrome/browser/resources/settings/reset_page/reset_profile_banner.html
@@ -1,7 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="reset_browser_proxy.html">
<link rel="import" href="../route.html">
@@ -19,12 +19,12 @@
</span>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onOkTap_" id="ok">
+ <cr-button class="cancel-button" on-click="onOkTap_" id="ok">
$i18n{ok}
- </paper-button>
- <paper-button class="action-button" on-click="onResetTap_" id="reset">
+ </cr-button>
+ <cr-button class="action-button" on-click="onResetTap_" id="reset">
$i18n{resetProfileBannerButton}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html b/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html
index fc3b7521d2a..5c5863d80ed 100644
--- a/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html
+++ b/chromium/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html
@@ -1,11 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
<link rel="import" href="reset_browser_proxy.html">
<link rel="import" href="../i18n_setup.html">
@@ -19,11 +19,9 @@
margin: 0 8px;
}
- cr-dialog {
- --cr-dialog-body: {
- /* Add space for the link focus ring. See https://crbug.com/909653. */
- padding-bottom: 2px;
- };
+ #dialog-body {
+ /* Add space for the link focus ring. See https://crbug.com/909653. */
+ padding-bottom: 2px;
}
</style>
<cr-dialog id="dialog" close-text="$i18n{close}"
@@ -31,7 +29,7 @@
<div slot="title">
[[getPageTitle_(isTriggered_, triggeredResetToolName_)]]
</div>
- <div slot="body">
+ <div id="dialog-body" slot="body">
<span>
[[getExplanationText_(isTriggered_, triggeredResetToolName_)]]
<a href="$i18nRaw{resetPageLearnMoreUrl}" target="_blank">
@@ -42,14 +40,14 @@
<div slot="button-container">
<paper-spinner-lite id="resetSpinner" active="[[clearingInProgress_]]">
</paper-spinner-lite>
- <paper-button class="cancel-button" on-click="onCancelTap_"
+ <cr-button class="cancel-button" on-click="onCancelTap_"
id="cancel" disabled="[[clearingInProgress_]]">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onResetTap_"
+ </cr-button>
+ <cr-button class="action-button" on-click="onResetTap_"
id="reset" disabled="[[clearingInProgress_]]">
$i18n{resetDialogCommit}
- </paper-button>
+ </cr-button>
</div>
<div slot="footer">
<cr-checkbox id="sendSettings" checked>
diff --git a/chromium/chrome/browser/resources/settings/route.js b/chromium/chrome/browser/resources/settings/route.js
index 01cb41b7b81..808fc7775c4 100644
--- a/chromium/chrome/browser/resources/settings/route.js
+++ b/chromium/chrome/browser/resources/settings/route.js
@@ -26,6 +26,7 @@
* BASIC: (undefined|!settings.Route),
* BLUETOOTH: (undefined|!settings.Route),
* BLUETOOTH_DEVICES: (undefined|!settings.Route),
+ * CAPTIONS: (undefined|!settings.Route),
* CERTIFICATES: (undefined|!settings.Route),
* CHANGE_PICTURE: (undefined|!settings.Route),
* CHROME_CLEANUP: (undefined|!settings.Route),
@@ -42,6 +43,7 @@
* EDIT_DICTIONARY: (undefined|!settings.Route),
* EXTERNAL_STORAGE_PREFERENCES: (undefined|!settings.Route),
* FINGERPRINT: (undefined|!settings.Route),
+ * FILES: (undefined|!settings.Route),
* FONTS: (undefined|!settings.Route),
* GOOGLE_ASSISTANT: (undefined|!settings.Route),
* IMPORT_DATA: (undefined|!settings.Route),
@@ -53,9 +55,11 @@
* KEYBOARD: (undefined|!settings.Route),
* KNOWN_NETWORKS: (undefined|!settings.Route),
* LANGUAGES: (undefined|!settings.Route),
+ * LANGUAGES_DETAILS: (undefined|!settings.Route),
* LOCK_SCREEN: (undefined|!settings.Route),
* MANAGE_ACCESSIBILITY: (undefined|!settings.Route),
* MANAGE_PROFILE: (undefined|!settings.Route),
+ * MANAGE_SWITCH_ACCESS_SETTINGS: (undefined|!settings.Route),
* MANAGE_TTS_SETTINGS: (undefined|!settings.Route),
* MULTIDEVICE: (undefined|!settings.Route),
* MULTIDEVICE_FEATURES: (undefined|!settings.Route),
@@ -64,6 +68,7 @@
* PASSWORDS: (undefined|!settings.Route),
* PAYMENTS: (undefined|!settings.Route),
* PEOPLE: (undefined|!settings.Route),
+ * PERSONALIZATION: (undefined|!settings.Route),
* PLUGIN_VM: (undefined|!settings.Route),
* PLUGIN_VM_DETAILS: (undefined|!settings.Route),
* PLUGIN_VM_SHARED_PATHS: (undefined|!settings.Route),
@@ -252,6 +257,7 @@ cr.define('settings', function() {
r.MULTIDEVICE_FEATURES = r.MULTIDEVICE.createChild('/multidevice/features');
r.SMART_LOCK =
r.MULTIDEVICE_FEATURES.createChild('/multidevice/features/smartLock');
+
// </if>
if (pageVisibility.appearance !== false) {
@@ -292,10 +298,11 @@ cr.define('settings', function() {
r.CROSTINI = r.BASIC.createSection('/crostini', 'crostini');
r.CROSTINI_DETAILS = r.CROSTINI.createChild('/crostini/details');
r.CROSTINI_EXPORT_IMPORT =
- r.CROSTINI.createChild('/crostini/exportImport');
- r.CROSTINI_SHARED_PATHS = r.CROSTINI.createChild('/crostini/sharedPaths');
+ r.CROSTINI_DETAILS.createChild('/crostini/exportImport');
+ r.CROSTINI_SHARED_PATHS =
+ r.CROSTINI_DETAILS.createChild('/crostini/sharedPaths');
r.CROSTINI_SHARED_USB_DEVICES =
- r.CROSTINI.createChild('/crostini/sharedUsbDevices');
+ r.CROSTINI_DETAILS.createChild('/crostini/sharedUsbDevices');
}
if (loadTimeData.valueExists('showPluginVm') &&
@@ -320,7 +327,14 @@ cr.define('settings', function() {
r.MANAGE_PROFILE = r.PEOPLE.createChild('/manageProfile');
// </if>
// <if expr="chromeos">
- r.CHANGE_PICTURE = r.PEOPLE.createChild('/changePicture');
+ // TODO(crbug.com/950007): Remove when SplitSettings is the default.
+ if (loadTimeData.getBoolean('isOSSettings')) {
+ r.PERSONALIZATION =
+ r.BASIC.createSection('/personalization', 'personalization');
+ r.CHANGE_PICTURE = r.PERSONALIZATION.createChild('/changePicture');
+ } else {
+ r.CHANGE_PICTURE = r.PEOPLE.createChild('/changePicture');
+ }
r.ACCOUNTS = r.PEOPLE.createChild('/accounts');
r.ACCOUNT_MANAGER = r.PEOPLE.createChild('/accountManager');
r.KERBEROS_ACCOUNTS = r.PEOPLE.createChild('/kerberosAccounts');
@@ -357,16 +371,9 @@ cr.define('settings', function() {
}
}
- if (loadTimeData.getBoolean('enableSiteSettings')) {
- r.SITE_SETTINGS_ALL = r.SITE_SETTINGS.createChild('all');
- r.SITE_SETTINGS_SITE_DETAILS =
- r.SITE_SETTINGS_ALL.createChild('/content/siteDetails');
- } else {
- // When there is no "All Sites", pressing 'back' from "Site Details"
- // should return to "Content Settings".
- r.SITE_SETTINGS_SITE_DETAILS =
- r.SITE_SETTINGS.createChild('/content/siteDetails');
- }
+ r.SITE_SETTINGS_ALL = r.SITE_SETTINGS.createChild('all');
+ r.SITE_SETTINGS_SITE_DETAILS =
+ r.SITE_SETTINGS_ALL.createChild('/content/siteDetails');
r.SITE_SETTINGS_HANDLERS = r.SITE_SETTINGS.createChild('/handlers');
@@ -426,7 +433,13 @@ cr.define('settings', function() {
r.LANGUAGES = r.ADVANCED.createSection('/languages', 'languages');
// <if expr="chromeos">
- r.INPUT_METHODS = r.LANGUAGES.createChild('/inputMethods');
+ if (loadTimeData.getBoolean('isOSSettings')) {
+ r.LANGUAGES_DETAILS = r.LANGUAGES.createChild('/languages/details');
+ r.INPUT_METHODS =
+ r.LANGUAGES_DETAILS.createChild('/languages/inputMethods');
+ } else {
+ r.INPUT_METHODS = r.LANGUAGES.createChild('/inputMethods');
+ }
// </if>
// <if expr="not is_macosx">
r.EDIT_DICTIONARY = r.LANGUAGES.createChild('/editDictionary');
@@ -435,7 +448,14 @@ cr.define('settings', function() {
if (pageVisibility.downloads !== false) {
r.DOWNLOADS = r.ADVANCED.createSection('/downloads', 'downloads');
// <if expr="chromeos">
- r.SMB_SHARES = r.DOWNLOADS.createChild('/smbShares');
+ // TODO(crbug.com/950007): Make unconditional and remove 'else' block
+ // when SplitSettings is the default.
+ if (loadTimeData.getBoolean('isOSSettings')) {
+ r.FILES = r.ADVANCED.createSection('/files', 'files');
+ r.SMB_SHARES = r.FILES.createChild('/smbShares');
+ } else {
+ r.SMB_SHARES = r.DOWNLOADS.createChild('/smbShares');
+ }
// </if>
}
@@ -446,9 +466,28 @@ cr.define('settings', function() {
// </if>
r.ACCESSIBILITY = r.ADVANCED.createSection('/accessibility', 'a11y');
+
+ // <if expr="chromeos or is_linux">
+ if (loadTimeData.getBoolean('enableCaptionSettings')) {
+ r.CAPTIONS = r.ACCESSIBILITY.createChild('/captions');
+ }
+ // </if>
+
+ // <if expr="is_win">
+ if (loadTimeData.getBoolean('enableCaptionSettings') &&
+ !loadTimeData.getBoolean('isWindows10OrNewer')) {
+ r.CAPTIONS = r.ACCESSIBILITY.createChild('/captions');
+ }
+ // </if>
+
// <if expr="chromeos">
r.MANAGE_ACCESSIBILITY =
r.ACCESSIBILITY.createChild('/manageAccessibility');
+ if (loadTimeData.getBoolean(
+ 'showExperimentalAccessibilitySwitchAccess')) {
+ r.MANAGE_SWITCH_ACCESS_SETTINGS = r.MANAGE_ACCESSIBILITY.createChild(
+ '/manageAccessibility/switchAccess');
+ }
r.MANAGE_TTS_SETTINGS =
r.MANAGE_ACCESSIBILITY.createChild('/manageAccessibility/tts');
// </if>
@@ -476,7 +515,10 @@ cr.define('settings', function() {
// "About" is the only section in About, but we still need to create the
// route in order to show the subpage on Chrome OS.
r.ABOUT_ABOUT = r.ABOUT.createSection('/help/about', 'about');
- r.DETAILED_BUILD_INFO = r.ABOUT_ABOUT.createChild('/help/details');
+ // TODO(aee): Remove once this file is forked.
+ if (loadTimeData.getBoolean('showOSSettings')) {
+ r.DETAILED_BUILD_INFO = r.ABOUT_ABOUT.createChild('/help/details');
+ }
// </if>
return r;
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html b/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html
index fff9623a602..a71de9853fe 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html
@@ -1,9 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="search_engines_browser_proxy.html">
@@ -33,12 +33,12 @@
</cr-input>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="cancel_" id="cancel">
- $i18n{cancel}</paper-button>
- <paper-button id="actionButton" class="action-button"
+ <cr-button class="cancel-button" on-click="cancel_" id="cancel">
+ $i18n{cancel}</cr-button>
+ <cr-button id="actionButton" class="action-button"
on-click="onActionButtonTap_">
[[actionButtonText_]]
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.html b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.html
index 4229a165c0e..6dc16d5cb0c 100644
--- a/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.html
+++ b/chromium/chrome/browser/resources/settings/search_engines_page/search_engines_page.html
@@ -1,8 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
@@ -46,10 +47,10 @@
<div class="settings-box first">
<h2 class="start">$i18n{searchEnginesOther}</h2>
- <paper-button class="secondary-button header-aligned-button"
+ <cr-button class="secondary-button header-aligned-button"
on-click="onAddSearchEngineTap_" id="addSearchEngine">
$i18n{add}
- </paper-button>
+ </cr-button>
</div>
<div id="noOtherEngines" hidden="[[otherEngines.length]]">
$i18n{searchEnginesNoOtherEngines}
diff --git a/chromium/chrome/browser/resources/settings/search_page/search_page.html b/chromium/chrome/browser/resources/settings/search_page/search_page.html
index 1f488de72d3..109fe94a163 100644
--- a/chromium/chrome/browser/resources/settings/search_page/search_page.html
+++ b/chromium/chrome/browser/resources/settings/search_page/search_page.html
@@ -5,7 +5,7 @@
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="../controls/extension_controlled_indicator.html">
<link rel="import" href="../controls/settings_toggle_button.html">
<link rel="import" href="../icons.html">
@@ -46,7 +46,7 @@
<!-- Omnibox search engine -->
<div class="settings-box first block">
<div id="search-wrapper">
- <div id="searchExplanation" class="start">
+ <div id="searchExplanation" class="start settings-box-text">
$i18nRaw{searchExplanation}
</div>
<template is="dom-if" if="[[isDefaultSearchControlledByPolicy_(
@@ -86,18 +86,14 @@
<if expr="chromeos">
<!-- Google Assistant -->
<template is="dom-if" if="[[isAssistantAllowed_]]">
- <div id="assistantSubpageTrigger" class="settings-box two-line"
- on-click="onGoogleAssistantTap_" actionable>
- <div class="start">
- $i18n{searchGoogleAssistant}
- <div class="secondary">
- [[getAssistantEnabledDisabledLabel_(
- prefs.settings.voice_interaction.enabled.value)]]
- </div>
- </div>
- <cr-icon-button class="subpage-arrow"
- aria-label="$i18n{searchGoogleAssistant}"></cr-icon-button>
- </div>
+ <cr-link-row
+ class="hr"
+ id="assistantSubpageTrigger"
+ label="$i18n{searchGoogleAssistant}"
+ sub-label="[[getAssistantEnabledDisabledLabel_(
+ prefs.settings.voice_interaction.enabled.value)]]"
+ on-click="onGoogleAssistantTap_">
+ </cr-link-row>
</template>
</if>
</div>
diff --git a/chromium/chrome/browser/resources/settings/settings.html b/chromium/chrome/browser/resources/settings/settings.html
index c99aed2da13..7842e793225 100644
--- a/chromium/chrome/browser/resources/settings/settings.html
+++ b/chromium/chrome/browser/resources/settings/settings.html
@@ -1,6 +1,5 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading"
- $i18n{dark}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading">
<head>
<meta charset="utf-8">
<title>$i18n{settings}</title>
@@ -31,6 +30,5 @@
<link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="settings_ui/settings_ui.html">
- <link rel="import" href="chrome://resources/html/dark_mode.html">
</body>
</html>
diff --git a/chromium/chrome/browser/resources/settings/settings_main/settings_main.html b/chromium/chrome/browser/resources/settings/settings_main/settings_main.html
index 6d7b9a7f77d..d75f667d3c3 100644
--- a/chromium/chrome/browser/resources/settings/settings_main/settings_main.html
+++ b/chromium/chrome/browser/resources/settings/settings_main/settings_main.html
@@ -7,7 +7,6 @@
<link rel="import" href="chrome://resources/html/promise_resolver.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-a11y-announcer/iron-a11y-announcer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../about_page/about_page.html">
<link rel="import" href="../basic_page/basic_page.html">
<link rel="import" href="../i18n_setup.html">
@@ -66,8 +65,8 @@
page-visibility="[[pageVisibility]]"
show-apps="[[showApps]]"
show-android-apps="[[showAndroidApps]]"
- show-kiosk-next-shell="[[showKioskNextShell]]"
show-crostini="[[showCrostini]]"
+ show-parental-controls="[[showParentalControls]]"
show-plugin-vm="[[showPluginVm]]"
have-play-store-app="[[havePlayStoreApp]]"
on-showing-section="onShowingSection_"
diff --git a/chromium/chrome/browser/resources/settings/settings_main/settings_main.js b/chromium/chrome/browser/resources/settings/settings_main/settings_main.js
index bf40b02dac1..f921d174922 100644
--- a/chromium/chrome/browser/resources/settings/settings_main/settings_main.js
+++ b/chromium/chrome/browser/resources/settings/settings_main/settings_main.js
@@ -81,6 +81,8 @@ Polymer({
showAndroidApps: Boolean,
+ showParentalControls: Boolean,
+
havePlayStoreApp: Boolean,
},
diff --git a/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html b/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html
index 8e94260953a..9369f5f5517 100644
--- a/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html
+++ b/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.html
@@ -1,11 +1,11 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-selector/iron-selector.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../icons.html">
<link rel="import" href="../route.html">
<link rel="import" href="../settings_shared_css.html">
@@ -20,11 +20,12 @@
padding-top: 8px;
}
+ :host * {
+ -webkit-tap-highlight-color: transparent;
+ }
+
a[href],
#advancedButton {
- --cr-selectable-focus: {
- outline: auto 5px -webkit-focus-ring-color;
- };
align-items: center;
color: var(--settings-nav-item-color);
display: flex;
@@ -41,6 +42,11 @@
color: var(--cr-link-color);
}
+ a[href]:focus {
+ background: transparent;
+ outline: auto 5px -webkit-focus-ring-color;
+ }
+
iron-icon {
--iron-icon-fill-color: var(--settings-nav-icon-color);
margin-inline-end: 24px;
@@ -53,8 +59,11 @@
}
#advancedButton {
+ --ink-color: var(--settings-nav-item-color);
+ background: none;
border: none;
border-radius: initial;
+ box-shadow: none;
height: unset;
margin-top: 8px;
padding-inline-end: 0;
@@ -62,11 +71,10 @@
}
#advancedButton:focus {
- box-shadow: none;
outline: none;
}
- #advancedButton.keyboard-focus:focus {
+ :host-context(.focus-outline-visible) #advancedButton:focus {
outline: auto 5px -webkit-focus-ring-color;
}
@@ -88,8 +96,10 @@
margin-top: 8px;
}
- :host-context([dark]) #menuSeparator {
- border-bottom: var(--cr-separator-line); /* override */
+ @media (prefers-color-scheme: dark) {
+ #menuSeparator {
+ border-bottom: var(--cr-separator-line); /* override */
+ }
}
</style>
<iron-selector id="topMenu" selectable="a:not(#extensionsLink)"
@@ -165,12 +175,12 @@
<iron-icon icon="settings:power-settings-new"></iron-icon>
$i18n{onStartup}
</a>
- <paper-button toggles id="advancedButton"
- aria-active-attribute="aria-expanded" active="{{advancedOpened}}"
+ <cr-button id="advancedButton" aria-active-attribute="aria-expanded"
+ on-click="onAdvancedButtonToggle_"
hidden="[[!pageVisibility.advancedSettings]]">
<span>$i18n{advancedPageTitle}</span>
<iron-icon icon="[[arrowState_(advancedOpened)]]">
- </iron-icon></paper-button>
+ </iron-icon></cr-button>
<iron-collapse id="advancedSubmenu" opened="[[advancedOpened]]"
hidden="[[!pageVisibility.advancedSettings]]">
<iron-selector id="subMenu" selectable="a" attr-for-selected="href"
diff --git a/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.js b/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.js
index a28c773d1ed..38bce70ccb4 100644
--- a/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.js
+++ b/chromium/chrome/browser/resources/settings/settings_menu/settings_menu.js
@@ -14,6 +14,7 @@ Polymer({
properties: {
advancedOpened: {
type: Boolean,
+ value: false,
notify: true,
},
@@ -40,6 +41,11 @@ Polymer({
this.setSelectedUrl_(''); // Nothing is selected.
},
+ /** @private */
+ onAdvancedButtonToggle_: function() {
+ this.advancedOpened = !this.advancedOpened;
+ },
+
/**
* Prevent clicks on sidebar items from navigating. These are only links for
* accessibility purposes, taps are handled separately by <iron-selector>.
diff --git a/chromium/chrome/browser/resources/settings/settings_page/main_page_behavior.js b/chromium/chrome/browser/resources/settings/settings_page/main_page_behavior.js
index 301eb7559b7..4a68b61aa47 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/main_page_behavior.js
+++ b/chromium/chrome/browser/resources/settings/settings_page/main_page_behavior.js
@@ -140,7 +140,12 @@ cr.define('settings', function() {
* @private
*/
shouldExpandAdvanced_: function(route) {
- return this.tagName == 'SETTINGS-BASIC-PAGE' &&
+ return (
+ this.tagName == 'SETTINGS-BASIC-PAGE'
+ // <if expr="chromeos">
+ || this.tagName == 'OS-SETTINGS-PAGE'
+ // </if>
+ ) &&
settings.routes.ADVANCED && settings.routes.ADVANCED.contains(route);
},
diff --git a/chromium/chrome/browser/resources/settings/settings_page/settings_animated_pages.js b/chromium/chrome/browser/resources/settings/settings_page/settings_animated_pages.js
index e857c8d3aac..0ca50ae7967 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/settings_animated_pages.js
+++ b/chromium/chrome/browser/resources/settings/settings_page/settings_animated_pages.js
@@ -110,6 +110,9 @@ Polymer({
return;
}
+ // Ensure focus-config was correctly specified as a Polymer property.
+ assert(this.focusConfig instanceof Map);
+
let pathConfig = this.focusConfig.get(this.previousRoute_.path);
if (pathConfig) {
let handler;
diff --git a/chromium/chrome/browser/resources/settings/settings_page/settings_section.html b/chromium/chrome/browser/resources/settings/settings_page/settings_section.html
index 8e4475d96c1..83723fd748a 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/settings_section.html
+++ b/chromium/chrome/browser/resources/settings/settings_page/settings_section.html
@@ -14,7 +14,14 @@
}
#header .title {
- @apply --cr-card-external-title;
+ color: var(--cr-primary-text-color);
+ font-size: 108%;
+ font-weight: 400;
+ letter-spacing: .25px;
+ margin-bottom: 12px;
+ margin-top: var(--cr-section-vertical-margin);
+ padding-bottom: 4px;
+ padding-top: 8px;
}
:host(:not(.expanded)) #card {
diff --git a/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html b/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html
index e84b0d5b745..4989fb87e41 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html
+++ b/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.html
@@ -4,6 +4,7 @@
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_search_field/cr_search_field.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
+<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
<link rel="import" href="chrome://resources/html/find_shortcut_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-resizable-behavior/iron-resizable-behavior.html">
@@ -14,7 +15,7 @@
<dom-module id="settings-subpage">
<template>
- <style include="settings-shared">
+ <style include="cr-shared-style settings-shared">
:host {
background-color: var(--cr-card-background-color);
box-sizing: border-box;
@@ -56,7 +57,6 @@
h1 {
flex: 1; /* Push other items to the end. */
- @apply --cr-title-text;
}
cr-search-field {
@@ -67,7 +67,7 @@
<div class="settings-box first" id="headerLine">
<cr-icon-button class="icon-arrow-back" id="closeButton"
on-click="onTapBack_" aria-label="$i18n{back}"></cr-icon-button>
- <h1>[[pageTitle]]</h1>
+ <h1 class="cr-title-text">[[pageTitle]]</h1>
<slot name="subpage-title-extra"></slot>
<template is="dom-if" if="[[learnMoreUrl]]">
<a id="learnMore" aria-label="$i18n{learnMore}"
@@ -82,7 +82,8 @@
</cr-search-field>
</template>
<template is="dom-if" if="[[showSpinner]]">
- <paper-spinner-lite active></paper-spinner-lite>
+ <paper-spinner-lite active title$="[[spinnerTitle]]">
+ </paper-spinner-lite>
</template>
</div>
<slot></slot>
diff --git a/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.js b/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.js
index 13a61bdfe08..b33ba416d65 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.js
+++ b/chromium/chrome/browser/resources/settings/settings_page/settings_subpage.js
@@ -38,6 +38,15 @@ Polymer({
},
/**
+ * Title (i.e., tooltip) to be displayed on the spinner. If |showSpinner| is
+ * false, this field has no effect.
+ */
+ spinnerTitle: {
+ type: String,
+ value: '',
+ },
+
+ /**
* Indicates which element triggers this subpage. Used by the searching
* algorithm to show search bubbles. It is |null| for subpages that are
* skipped during searching.
diff --git a/chromium/chrome/browser/resources/settings/settings_resources.grd b/chromium/chrome/browser/resources/settings/settings_resources.grd
index 4b220cb89db..f9f460935ef 100644
--- a/chromium/chrome/browser/resources/settings/settings_resources.grd
+++ b/chromium/chrome/browser/resources/settings/settings_resources.grd
@@ -21,6 +21,18 @@
type="chrome_html"
preprocess="true"
allowexternalscript="true" />
+ <structure name="IDR_SETTINGS_CAPTIONS_SUBPAGE_HTML"
+ file="a11y_page/captions_subpage.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CAPTIONS_SUBPAGE_JS"
+ file="a11y_page/captions_subpage.js"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CAPTIONS_BROWSER_PROXY_HTML"
+ file="a11y_page/captions_browser_proxy.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CAPTIONS_BROWSER_PROXY_JS"
+ file="a11y_page/captions_browser_proxy.js"
+ type="chrome_html" />
<if expr="chromeos">
<structure name="IDR_SETTINGS_MANAGE_A11Y_PAGE_JS"
file="a11y_page/manage_a11y_page.js"
@@ -28,6 +40,12 @@
<structure name="IDR_SETTINGS_MANAGE_A11Y_PAGE_HTML"
file="a11y_page/manage_a11y_page.html"
type="chrome_html" />
+ <structure name="IDR_SETTINGS_SWITCH_ACCESS_SUBPAGE_JS"
+ file="a11y_page/switch_access_subpage.js"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_SWITCH_ACCESS_SUBPAGE_HTML"
+ file="a11y_page/switch_access_subpage.html"
+ type="chrome_html" />
<structure name="IDR_SETTINGS_TTS_SUBPAGE_JS"
file="a11y_page/tts_subpage.js"
type="chrome_html" />
@@ -380,6 +398,18 @@
<structure name="IDR_SETTINGS_SECURITY_KEYS_SET_PIN_DIALOG_JS"
file="privacy_page/security_keys_set_pin_dialog.js"
type="chrome_html"/>
+ <structure name="IDR_SETTINGS_SECURITY_KEYS_PIN_FIELD_HTML"
+ file="privacy_page/security_keys_pin_field.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_SECURITY_KEYS_PIN_FIELD_JS"
+ file="privacy_page/security_keys_pin_field.js"
+ type="chrome_html"/>
+ <structure name="IDR_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_DIALOG_HTML"
+ file="privacy_page/security_keys_credential_management_dialog.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_DIALOG_JS"
+ file="privacy_page/security_keys_credential_management_dialog.js"
+ type="chrome_html"/>
<structure name="IDR_SETTINGS_SECURITY_KEYS_RESET_DIALOG_HTML"
file="privacy_page/security_keys_reset_dialog.html"
type="chrome_html" />
@@ -902,6 +932,12 @@
preprocess="true"
type="chrome_html" />
<if expr="chromeos">
+ <structure name="IDR_SETTINGS_CUPS_PRINTER_TYPES_HTML"
+ file="printing_page/cups_printer_types.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CUPS_PRINTER_TYPES_JS"
+ file="printing_page/cups_printer_types.js"
+ type="chrome_html" />
<structure name="IDR_SETTINGS_CUPS_PRINTER_SHARED_CSS_HTML"
file="printing_page/cups_printer_shared_css.html"
type="chrome_html" />
@@ -917,12 +953,36 @@
<structure name="IDR_SETTINGS_CUPS_PRINTERS_BROWSER_PROXY_JS"
file="printing_page/cups_printers_browser_proxy.js"
type="chrome_html" />
+ <structure name="IDR_SETTINGS_CUPS_PRINTERS_ENTRY_HTML"
+ file="printing_page/cups_printers_entry.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CUPS_PRINTERS_ENTRY_JS"
+ file="printing_page/cups_printers_entry.js"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CUPS_PRINTERS_ENTRY_LIST_HTML"
+ file="printing_page/cups_printers_entry_list.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CUPS_PRINTERS_ENTRY_LIST_JS"
+ file="printing_page/cups_printers_entry_list.js"
+ type="chrome_html" />
<structure name="IDR_SETTINGS_CUPS_PRINTERS_LIST_HTML"
file="printing_page/cups_printers_list.html"
type="chrome_html" />
<structure name="IDR_SETTINGS_CUPS_PRINTERS_LIST_JS"
file="printing_page/cups_printers_list.js"
type="chrome_html" />
+ <structure name="IDR_SETTINGS_CUPS_SAVED_PRINTERS_HTML"
+ file="printing_page/cups_saved_printers.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CUPS_SAVED_PRINTERS_JS"
+ file="printing_page/cups_saved_printers.js"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CUPS_NEARBY_PRINTERS_HTML"
+ file="printing_page/cups_nearby_printers.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_CUPS_NEARBY_PRINTERS_JS"
+ file="printing_page/cups_nearby_printers.js"
+ type="chrome_html" />
<structure name="IDR_SETTINGS_CUPS_EDIT_PRINTER_DIALOG_HTML"
file="printing_page/cups_edit_printer_dialog.html"
type="chrome_html" />
@@ -1308,17 +1368,11 @@
type="chrome_html"
preprocess="true"
allowexternalscript="true" />
- <structure name="IDR_SETTINGS_KIOSK_NEXT_SHELL_PAGE_HTML"
- file="kiosk_next_shell_page/kiosk_next_shell_page.html"
+ <structure name="IDR_SETTINGS_CROSTINI_IMPORT_CONFIRMATION_DIALOG_HTML"
+ file="crostini_page/crostini_import_confirmation_dialog.html"
type="chrome_html" />
- <structure name="IDR_SETTINGS_KIOSK_NEXT_SHELL_PAGE_JS"
- file="kiosk_next_shell_page/kiosk_next_shell_page.js"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_KIOSK_NEXT_SHELL_CONFIRMATION_DIALOG_HTML"
- file="kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.html"
- type="chrome_html" />
- <structure name="IDR_SETTINGS_KIOSK_NEXT_SHELL_CONFIRMATION_DIALOG_JS"
- file="kiosk_next_shell_page/kiosk_next_shell_confirmation_dialog.js"
+ <structure name="IDR_SETTINGS_CROSTINI_IMPORT_CONFIRMATION_DIALOG_JS"
+ file="crostini_page/crostini_import_confirmation_dialog.js"
type="chrome_html" />
<structure name="IDR_SETTINGS_BLUETOOTH_DEVICE_LIST_ITEM_HTML"
file="bluetooth_page/bluetooth_device_list_item.html"
@@ -1479,6 +1533,18 @@
<structure name="IDR_SETTINGS_NETWORK_SUMMARY_ITEM_JS"
file="internet_page/network_summary_item.js"
type="chrome_html" />
+ <structure name="IDR_SETTINGS_PARENTAL_CONTROLS_BROWSER_PROXY_HTML"
+ file="parental_controls_page/parental_controls_browser_proxy.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_PARENTAL_CONTROLS_BROWSER_PROXY_JS"
+ file="parental_controls_page/parental_controls_browser_proxy.js"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_PARENTAL_CONTROLS_HTML"
+ file="parental_controls_page/parental_controls_page.html"
+ type="chrome_html" />
+ <structure name="IDR_SETTINGS_PARENTAL_CONTROLS_PAGE_JS"
+ file="parental_controls_page/parental_controls_page.js"
+ type="chrome_html" />
<structure name="IDR_SETTINGS_TETHER_CONNECTION_DIALOG_HTML"
file="internet_page/tether_connection_dialog.html"
type="chrome_html" />
diff --git a/chromium/chrome/browser/resources/settings/settings_shared_css.html b/chromium/chrome/browser/resources/settings/settings_shared_css.html
index 5585da834a4..bc22b45af3c 100644
--- a/chromium/chrome/browser/resources/settings/settings_shared_css.html
+++ b/chromium/chrome/browser/resources/settings/settings_shared_css.html
@@ -1,4 +1,3 @@
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/search_highlight_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_style_css.html">
@@ -9,7 +8,7 @@
<!-- Common styles for Material Design settings. -->
<dom-module id="settings-shared">
<template>
- <style include="settings-icons paper-button-style cr-shared-style search-highlight-style">
+ <style include="settings-icons cr-shared-style search-highlight-style">
/* Prevent action-links from being selected to avoid accidental
* selection when trying to click it. */
a[is=action-link] {
@@ -61,15 +60,15 @@
}
/* Special case for buttons inside of toggle-buttons. */
- .settings-box settings-toggle-button paper-button:last-of-type {
+ .settings-box settings-toggle-button cr-button:last-of-type {
margin-inline-end: 16px;
}
/* Space out multiple buttons in the same row. */
- .settings-box paper-button + paper-button,
- .settings-box paper-button + controlled-button,
+ .settings-box cr-button + cr-button,
+ .settings-box cr-button + controlled-button,
.settings-box controlled-button + controlled-button,
- .settings-box controlled-button + paper-button {
+ .settings-box controlled-button + cr-button {
margin-inline-start: 8px;
}
@@ -112,8 +111,10 @@
outline: none;
}
- :host-context([dark]) cr-radio-group:focus {
- background-color: var(--google-grey-800);
+ @media (prefers-color-scheme: dark) {
+ cr-radio-group:focus {
+ background-color: var(--google-grey-800);
+ }
}
/* See also: .no-min-width below. */
@@ -131,7 +132,7 @@
}
.header-aligned-button {
- margin-top: 12px; /* Align paper-button with <h2>. */
+ margin-top: 12px; /* Align cr-button with <h2>. */
}
/* A list-frame is an outer container for list-items. It is intended to be
@@ -316,7 +317,7 @@
.separator {
border-inline-start: var(--cr-separator-line);
flex-shrink: 0;
- /* Match paper-button's default height. */
+ /* Match cr-button's default height. */
height: 32px;
margin: 0 16px;
}
diff --git a/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html b/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html
index d1dc39c3158..9d42840497d 100644
--- a/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html
+++ b/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.html
@@ -2,6 +2,7 @@
<link rel="import" href="chrome://resources/cr_elements/cr_container_shadow_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/cr_drawer/cr_drawer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_page_host_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
@@ -25,9 +26,8 @@
<dom-module id="settings-ui">
<template>
- <style include="settings-shared">
+ <style include="cr-page-host-style settings-shared">
:host {
- @apply --cr-page-host;
@apply --layout-fit;
display: flex;
flex-direction: column;
@@ -48,8 +48,10 @@
--cr-toolbar-center-basis: var(--settings-main-basis);
}
- :host-context(html:not([dark])) cr-toolbar {
- --iron-icon-fill-color: white;
+ @media (prefers-color-scheme: light) {
+ cr-toolbar {
+ --iron-icon-fill-color: white;
+ }
}
#cr-container-shadow-top {
@@ -127,8 +129,8 @@
show-apps="[[showApps_]]"
show-android-apps="[[showAndroidApps_]]"
show-crostini="[[showCrostini_]]"
+ show-parental-controls="[[showParentalControls_]]"
show-plugin-vm="[[showPluginVm_]]"
- show-multidevice="[[showMultidevice_]]"
have-play-store-app="[[havePlayStoreApp_]]"
on-iron-activate="onIronActivate_"
advanced-opened="{{advancedOpenedInMenu_}}">
@@ -142,8 +144,8 @@
show-apps="[[showApps_]]"
show-android-apps="[[showAndroidApps_]]"
show-crostini="[[showCrostini_]]"
+ show-parental-controls="[[showParentalControls_]]"
show-plugin-vm="[[showPluginVm_]]"
- show-multidevice="[[showMultidevice_]]"
have-play-store-app="[[havePlayStoreApp_]]"
on-iron-activate="onIronActivate_"
advanced-opened="{{advancedOpenedInMenu_}}">
@@ -154,10 +156,9 @@
page-visibility="[[pageVisibility_]]"
show-apps="[[showApps_]]"
show-android-apps="[[showAndroidApps_]]"
- show-kiosk-next-shell="[[showKioskNextShell_]]"
show-crostini="[[showCrostini_]]"
+ show-parental-controls="[[showParentalControls_]]"
show-plugin-vm="[[showPluginVm_]]"
- show-multidevice="[[showMultidevice_]]"
have-play-store-app="[[havePlayStoreApp_]]"
advanced-toggle-expanded="{{advancedOpenedInMain_}}">
</settings-main>
diff --git a/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js b/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js
index 02b96e43967..f3868ee260e 100644
--- a/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js
+++ b/chromium/chrome/browser/resources/settings/settings_ui/settings_ui.js
@@ -72,10 +72,10 @@ Polymer({
showAndroidApps_: Boolean,
/** @private */
- showKioskNextShell_: Boolean,
+ showCrostini_: Boolean,
/** @private */
- showCrostini_: Boolean,
+ showParentalControls_: Boolean,
/** @private */
showPluginVm_: Boolean,
@@ -134,6 +134,8 @@ Polymer({
loadTimeData.getString('controlledSettingNoOwner'),
controlledSettingParent:
loadTimeData.getString('controlledSettingParent'),
+ controlledSettingChildRestriction:
+ loadTimeData.getString('controlledSettingChildRestriction'),
// </if>
};
@@ -141,6 +143,7 @@ Polymer({
CrOncStrings = {
OncTypeCellular: loadTimeData.getString('OncTypeCellular'),
OncTypeEthernet: loadTimeData.getString('OncTypeEthernet'),
+ OncTypeMobile: loadTimeData.getString('OncTypeMobile'),
OncTypeTether: loadTimeData.getString('OncTypeTether'),
OncTypeVPN: loadTimeData.getString('OncTypeVPN'),
OncTypeWiFi: loadTimeData.getString('OncTypeWiFi'),
@@ -171,12 +174,12 @@ Polymer({
this.showAndroidApps_ = showOSSettings &&
loadTimeData.valueExists('androidAppsVisible') &&
loadTimeData.getBoolean('androidAppsVisible');
- this.showKioskNextShell_ = showOSSettings &&
- loadTimeData.valueExists('showKioskNextShell') &&
- loadTimeData.getBoolean('showKioskNextShell');
this.showCrostini_ = showOSSettings &&
loadTimeData.valueExists('showCrostini') &&
loadTimeData.getBoolean('showCrostini');
+ this.showParentalControls_ = showOSSettings &&
+ loadTimeData.valueExists('showParentalControls') &&
+ loadTimeData.getBoolean('showParentalControls');
this.showPluginVm_ = showOSSettings &&
loadTimeData.valueExists('showPluginVm') &&
loadTimeData.getBoolean('showPluginVm');
@@ -208,6 +211,11 @@ Polymer({
settings.setGlobalScrollTarget(this.$.container);
const scrollToTop = top => new Promise(resolve => {
+ if (this.$.container.scrollTop === top) {
+ resolve();
+ return;
+ }
+
// When transitioning back to main page from a subpage on ChromeOS, using
// 'smooth' scroll here results in the scroll changing to whatever is last
// value of |top|. This happens even after setting the scroll position the
diff --git a/chromium/chrome/browser/resources/settings/settings_vars_css.html b/chromium/chrome/browser/resources/settings/settings_vars_css.html
index 2a9c0c75704..481e31fd270 100644
--- a/chromium/chrome/browser/resources/settings/settings_vars_css.html
+++ b/chromium/chrome/browser/resources/settings/settings_vars_css.html
@@ -45,11 +45,13 @@
--cr-radio-group-item-padding: 0;
}
- html[dark] {
- --iron-icon-fill-color: var(--google-grey-refresh-500);
- --settings-error-color: var(--google-red-refresh-300);
- --settings-nav-icon-color: var(--google-grey-refresh-500);
- --settings-nav-item-color: var(--cr-primary-text-color);
+ @media (prefers-color-scheme: dark) {
+ html {
+ --iron-icon-fill-color: var(--google-grey-refresh-500);
+ --settings-error-color: var(--google-red-refresh-300);
+ --settings-nav-icon-color: var(--google-grey-refresh-500);
+ --settings-nav-item-color: var(--cr-primary-text-color);
+ }
}
</style>
</custom-style>
diff --git a/chromium/chrome/browser/resources/settings/site_favicon.js b/chromium/chrome/browser/resources/settings/site_favicon.js
index 7c5a812736e..09f30efc673 100644
--- a/chromium/chrome/browser/resources/settings/site_favicon.js
+++ b/chromium/chrome/browser/resources/settings/site_favicon.js
@@ -22,7 +22,7 @@ Polymer({
urlChanged_: function() {
let url = this.removePatternWildcard_(this.url);
url = this.ensureUrlHasScheme_(url);
- this.style.backgroundImage = cr.icon.getFavicon(url || '');
+ this.style.backgroundImage = cr.icon.getFavicon(url || '', false);
},
/**
@@ -58,4 +58,4 @@ Polymer({
}
return url.includes('://') ? url : 'http://' + url;
},
-}); \ No newline at end of file
+});
diff --git a/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.html b/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.html
index 3b2ddf0f8e2..938cfebaeac 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/add_site_dialog.html
@@ -1,10 +1,10 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="constants.html">
@@ -32,13 +32,13 @@
</cr-checkbox>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelTap_">
+ <cr-button class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" id="add" on-click="onSubmit_"
+ </cr-button>
+ <cr-button class="action-button" id="add" on-click="onSubmit_"
disabled>
$i18n{add}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/all_sites.html b/chromium/chrome/browser/resources/settings/site_settings/all_sites.html
index eb14758e277..53a046e4490 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/all_sites.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/all_sites.html
@@ -1,8 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_search_field/cr_search_field.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html">
<link rel="import" href="../global_scroll_target_behavior.html">
<link rel="import" href="../route.html">
@@ -97,12 +98,12 @@
actionMenuModel_.item.etldPlus1)]]
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCloseDialog_">
+ <cr-button class="cancel-button" on-click="onCloseDialog_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onResetSettings_">
+ </cr-button>
+ <cr-button class="action-button" on-click="onResetSettings_">
$i18n{siteSettingsSiteResetAll}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
@@ -121,12 +122,12 @@
actionMenuModel_.item.etldPlus1)]]
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCloseDialog_">
+ <cr-button class="cancel-button" on-click="onCloseDialog_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onClearData_">
+ </cr-button>
+ <cr-button class="action-button" on-click="onClearData_">
$i18n{siteSettingsSiteClearStorage}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/chooser_exception_list.js b/chromium/chrome/browser/resources/settings/site_settings/chooser_exception_list.js
index 7e37cdebf20..79c7539ca33 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/chooser_exception_list.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/chooser_exception_list.js
@@ -176,7 +176,9 @@ Polymer({
return Object.assign(exception, {sites});
});
- if (!this.updateList('chooserExceptions', x => x.displayName, exceptions)) {
+ if (!this.updateList(
+ 'chooserExceptions', x => x.displayName, exceptions,
+ true /* uidBasedUpdate */)) {
// The chooser objects have not been changed, so check if their site
// permissions have changed. The |exceptions| and |this.chooserExceptions|
// arrays should be the same length.
diff --git a/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.html b/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.html
index 3c4e9345729..2bc85d2723c 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/edit_exception_dialog.html
@@ -1,8 +1,8 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../i18n_setup.html">
<link rel="import" href="site_settings_prefs_browser_proxy.html">
@@ -19,12 +19,12 @@
</cr-input>
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCancelTap_"
- id="cancel">$i18n{cancel}</paper-button>
- <paper-button id="actionButton" class="action-button"
+ <cr-button class="cancel-button" on-click="onCancelTap_"
+ id="cancel">$i18n{cancel}</cr-button>
+ <cr-button id="actionButton" class="action-button"
on-click="onActionButtonTap_" disabled="[[invalid_]]">
$i18n{save}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/media_picker.html b/chromium/chrome/browser/resources/settings/site_settings/media_picker.html
index deba3436783..92f8c15fdf3 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/media_picker.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/media_picker.html
@@ -1,6 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="../settings_shared_css.html">
<link rel="import" href="../settings_vars_css.html">
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_data.html b/chromium/chrome/browser/resources/settings/site_settings/site_data.html
index ce8abf70394..b3c8d9bf131 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_data.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_data.html
@@ -5,6 +5,7 @@
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/list_property_update_behavior.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_search_field/cr_search_field.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
@@ -37,11 +38,10 @@
</style>
<div class="settings-box continuation">
<paper-spinner-lite active="[[isLoading_]]"></paper-spinner-lite>
- <paper-button class="secondary-button"
- disabled$="[[isLoading_]]" id="removeShowingSites"
+ <cr-button disabled$="[[isLoading_]]" id="removeShowingSites"
on-click="onRemoveShowingSitesTap_" hidden$="[[!sites.length]]">
[[computeRemoveLabel_(filter)]]
- </paper-button>
+ </cr-button>
</div>
<iron-list id="list" items="[[sites]]" preserve-focus
scroll-target="[[subpageScrollTarget]]" class="cr-separators">
@@ -63,12 +63,12 @@
</div>
<div slot="body">$i18n{siteSettingsCookieRemoveMultipleConfirmation}</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCloseDialog_">
+ <cr-button class="cancel-button" on-click="onCloseDialog_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onConfirmDelete_">
+ </cr-button>
+ <cr-button class="action-button" on-click="onConfirmDelete_">
$i18n{siteSettingsCookiesClearAll}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
</template>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_data.js b/chromium/chrome/browser/resources/settings/site_settings/site_data.js
index f15cb13e19b..06c8e742b30 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_data.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_data.js
@@ -176,8 +176,7 @@ Polymer({
updateSiteList_: function() {
this.isLoading_ = true;
this.browserProxy_.getDisplayList(this.filter).then(listInfo => {
- this.updateList(
- 'sites', item => `${item.site}_${item.localData}`, listInfo.items);
+ this.updateList('sites', item => item.site, listInfo.items);
this.isLoading_ = false;
this.fire('site-data-list-complete');
});
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_details.html b/chromium/chrome/browser/resources/settings/site_settings/site_details.html
index aa91a404f2b..5b373ff071c 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_details.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_details.html
@@ -1,11 +1,12 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/action_link.html">
-<link rel="import" href="chrome://resources/html/action_link_css.html">
+<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_link_row/cr_link_row.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
@@ -32,13 +33,6 @@
#storageText {
display: flex;
}
- /* When 'Usage' is omitted, subheadings are removed. Reduce the start
- * padding allowed for lists without headings and add back vertical space
- * that would normally be provided by the subheading. */
- .list-frame.without-heading {
- margin-top: 12px;
- padding-inline-start: var(--cr-section-padding);
- }
#resetSettingsButton {
margin-top: 24px;
@@ -51,12 +45,12 @@
[[i18n('siteSettingsSiteResetConfirmation', pageTitle)]]
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCloseDialog_">
+ <cr-button class="cancel-button" on-click="onCloseDialog_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onResetSettings_">
+ </cr-button>
+ <cr-button class="action-button" on-click="onResetSettings_">
$i18n{siteSettingsSiteResetAll}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
@@ -70,54 +64,51 @@
[[i18n('siteSettingsSiteClearStorageConfirmation', pageTitle)]]
</div>
<div slot="button-container">
- <paper-button class="cancel-button" on-click="onCloseDialog_">
+ <cr-button class="cancel-button" on-click="onCloseDialog_">
$i18n{cancel}
- </paper-button>
- <paper-button class="action-button" on-click="onClearStorage_">
+ </cr-button>
+ <cr-button class="action-button" on-click="onClearStorage_">
$i18n{siteSettingsSiteClearStorage}
- </paper-button>
+ </cr-button>
</div>
</cr-dialog>
- <template is="dom-if" if="[[enableSiteSettings_]]">
- <div id="usage">
- <div class="settings-box first line-only">
- <h2 class="first">$i18n{siteSettingsUsage}</h2>
+ <div id="usage">
+ <div class="settings-box first line-only">
+ <h2 class="first">$i18n{siteSettingsUsage}</h2>
+ </div>
+ <div class="list-frame">
+ <div class="list-item" id="noStorage"
+ hidden$="[[hasUsage_(storedData_, numCookies_)]]">
+ <div class="start">$i18n{siteSettingsUsageNone}</div>
</div>
- <div class="list-frame">
- <div class="list-item" id="noStorage"
- hidden$="[[hasUsage_(storedData_, numCookies_)]]">
- <div class="start">$i18n{siteSettingsUsageNone}</div>
- </div>
- <div class="list-item" id="storage"
- hidden$="[[!hasUsage_(storedData_, numCookies_)]]">
- <div class="start" id="storageText">
- <div hidden$="[[!storedData_]]">[[storedData_]]</div>
- <div hidden$="[[!hasDataAndCookies_(storedData_, numCookies_)]]">
- &nbsp;&middot;&nbsp;
- </div>
- <div hidden$="[[!numCookies_]]">[[numCookies_]]</div>
+ <div class="list-item" id="storage"
+ hidden$="[[!hasUsage_(storedData_, numCookies_)]]">
+ <div class="start" id="storageText">
+ <div hidden$="[[!storedData_]]">[[storedData_]]</div>
+ <div hidden$="[[!hasDataAndCookies_(storedData_, numCookies_)]]">
+ &nbsp;&middot;&nbsp;
</div>
- <paper-button class="secondary-button" id="clearStorage"
- role="button" aria-disabled="false"
- on-click="onConfirmClearStorage_"
- aria-label="$i18n{siteSettingsDelete}">
- $i18n{siteSettingsDelete}
- </paper-button>
+ <div hidden$="[[!numCookies_]]">[[numCookies_]]</div>
</div>
+ <cr-button id="clearStorage" role="button" aria-disabled="false"
+ on-click="onConfirmClearStorage_"
+ aria-label="$i18n{siteSettingsDelete}">
+ $i18n{siteSettingsDelete}
+ </cr-button>
</div>
</div>
+ </div>
- <div class="settings-box first">
- <h2 class="start">$i18n{siteSettingsPermissions}</h2>
- <paper-button id="resetSettingsButton"
- class="secondary-button header-aligned-button" role="button"
- aria-disabled="false" on-click="onConfirmClearSettings_">
- $i18n{siteSettingsReset}
- </paper-button>
- </div>
- </template>
- <div class$="list-frame [[permissionListClass_(enableSiteSettings_)]]">
+ <div class="settings-box first">
+ <h2 class="start">$i18n{siteSettingsPermissions}</h2>
+ <cr-button id="resetSettingsButton" class="header-aligned-button"
+ role="button" aria-disabled="false"
+ on-click="onConfirmClearSettings_">
+ $i18n{siteSettingsReset}
+ </cr-button>
+ </div>
+ <div class="list-frame">
<site-details-permission category="{{ContentSettingsTypes.GEOLOCATION}}"
icon="cr:location-on" id="geolocation"
label="$i18n{siteSettingsLocation}">
@@ -218,14 +209,6 @@
</template>
</div>
- <template is="dom-if" if="[[!enableSiteSettings_]]">
- <cr-link-row
- class="hr"
- id="resetSettingsButton"
- label="$i18n{siteSettingsReset}"
- on-click="onConfirmClearSettings_">
- </cr-link-row>
- </template>
<website-usage-private-api id="usageApi"
website-data-usage="{{storedData_}}"
website-cookie-usage="{{numCookies_}}">
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_details.js b/chromium/chrome/browser/resources/settings/site_settings/site_details.js
index 98b4cf5698f..da034ee588f 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_details.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_details.js
@@ -69,14 +69,6 @@ Polymer({
return loadTimeData.getBoolean('enableBluetoothScanningContentSetting');
}
},
-
- /** @private */
- enableSiteSettings_: {
- type: Boolean,
- value: function() {
- return loadTimeData.getBoolean('enableSiteSettings');
- },
- },
},
listeners: {
@@ -121,10 +113,7 @@ Polymer({
if (!valid) {
settings.navigateToPreviousRoute();
} else {
- if (this.enableSiteSettings_) {
- this.$.usageApi.fetchUsageTotal(this.toUrl(this.origin_).hostname);
- }
-
+ this.$.usageApi.fetchUsageTotal(this.toUrl(this.origin_).hostname);
this.updatePermissions_(this.getCategoryList());
}
});
@@ -242,10 +231,7 @@ Polymer({
* @private
*/
onClearStorage_: function(e) {
- // Since usage is only shown when "Site Settings" is enabled, don't
- // clear it when it's not shown.
- if (this.enableSiteSettings_ &&
- this.hasUsage_(this.storedData_, this.numCookies_)) {
+ if (this.hasUsage_(this.storedData_, this.numCookies_)) {
this.$.usageApi.clearUsage(this.toUrl(this.origin_).href);
}
@@ -266,16 +252,6 @@ Polymer({
},
/**
- * Checks whether the permission list is standalone or has a heading.
- * @return {string} CSS class applied when the permission list has no
- * heading.
- * @private
- */
- permissionListClass_: function(hasHeading) {
- return hasHeading ? '' : 'without-heading';
- },
-
- /**
* Checks whether this site has any usage information to show.
* @return {boolean} Whether there is any usage information to show (e.g.
* disk or battery).
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.html b/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.html
index 55250bf880c..c5a1e0091d3 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_details_permission.html
@@ -1,6 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_list.html b/chromium/chrome/browser/resources/settings/site_settings/site_list.html
index 1d6af8c04ae..a07b8c00068 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_list.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_list.html
@@ -3,6 +3,7 @@
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html">
<link rel="import" href="chrome://resources/cr_elements/cr_action_menu/cr_action_menu.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
@@ -31,11 +32,10 @@
<div id="category">
<div class="settings-box first">
<h2 class="start">[[categoryHeader]]</h2>
- <paper-button id="addSite"
- class="secondary-button header-aligned-button"
+ <cr-button id="addSite" class="header-aligned-button"
hidden="[[readOnlyList]]" on-click="onAddSiteTap_">
$i18n{add}
- </paper-button>
+ </cr-button>
</div>
<cr-action-menu>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_list.js b/chromium/chrome/browser/resources/settings/site_settings/site_list.js
index c1bcb458088..5e9cbba9943 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_list.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_list.js
@@ -339,14 +339,10 @@ Polymer({
site.setting == this.categorySubtype)
.map(site => this.expandSiteException(site));
- // <if expr="not chromeos">
- this.updateList('sites', (x) => x.origin, sites);
- // </if>
-
// <if expr="chromeos">
sites = this.processExceptionsForAndroidSmsInfo_(sites);
- this.updateList('sites', (x) => x.origin + x.showAndroidSmsNote, sites);
// </if>
+ this.updateList('sites', x => x.origin, sites);
},
/**
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_list_entry.html b/chromium/chrome/browser/resources/settings/site_settings/site_list_entry.html
index f1350d35534..f296bf59503 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_list_entry.html
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_list_entry.html
@@ -26,10 +26,8 @@
}
/* Tooltip is hidden since site-list will display a common tooltip. */
- cr-policy-pref-indicator {
- --cr-tooltip: {
- display: none;
- };
+ cr-policy-pref-indicator::part(tooltip) {
+ display: none;
}
</style>
<div class="list-item" focus-row-container>
diff --git a/chromium/chrome/browser/resources/settings/site_settings/site_list_entry.js b/chromium/chrome/browser/resources/settings/site_settings/site_list_entry.js
index d6d662e836e..fda7071af91 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/site_list_entry.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/site_list_entry.js
@@ -15,14 +15,6 @@ Polymer({
],
properties: {
- /** @private */
- enableSiteSettings_: {
- type: Boolean,
- value: function() {
- return loadTimeData.getBoolean('enableSiteSettings');
- },
- },
-
/**
* Some content types (like Location) do not allow the user to manually
* edit the exception list from within Settings.
@@ -209,7 +201,7 @@ Polymer({
return;
}
this.browserProxy.isOriginValid(this.model.origin).then((valid) => {
- this.allowNavigateToSiteDetail_ = valid && this.enableSiteSettings_;
+ this.allowNavigateToSiteDetail_ = valid;
});
}
});
diff --git a/chromium/chrome/browser/resources/settings/site_settings/zoom_levels.js b/chromium/chrome/browser/resources/settings/site_settings/zoom_levels.js
index 1614243c0be..e600e08fdee 100644
--- a/chromium/chrome/browser/resources/settings/site_settings/zoom_levels.js
+++ b/chromium/chrome/browser/resources/settings/site_settings/zoom_levels.js
@@ -47,7 +47,7 @@ Polymer({
* their zoom levels.
*/
onZoomLevelsChanged_: function(sites) {
- this.updateList('sites_', item => `${item.origin}_${item.zoom}`, sites);
+ this.updateList('sites_', item => item.origin, sites);
this.showNoSites_ = this.sites_.length == 0;
},
diff --git a/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html b/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html
index 6351c145209..f2b5e48bdc7 100644
--- a/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html
+++ b/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.html
@@ -23,17 +23,15 @@
--cr-section-min-height: var(--cr-section-two-line-min-height);
}
</style>
- <template is="dom-if" if="[[enableSiteSettings_]]">
- <div class="settings-box first line-only">
- <h2 class="first">$i18n{siteSettingsAllSites}</h2>
- </div>
- <cr-link-row data-route="SITE_SETTINGS_ALL" id="all-sites"
- label="$i18n{siteSettingsAllSitesDescription}"
- on-click="onTapNavigate_"></cr-link-row>
- <div class="settings-box first line-only">
- <h2>$i18n{siteSettingsPermissions}</h2>
- </div>
- </template>
+ <div class="settings-box first line-only">
+ <h2 class="first">$i18n{siteSettingsAllSites}</h2>
+ </div>
+ <cr-link-row data-route="SITE_SETTINGS_ALL" id="all-sites"
+ label="$i18n{siteSettingsAllSitesDescription}"
+ on-click="onTapNavigate_"></cr-link-row>
+ <div class="settings-box first line-only">
+ <h2>$i18n{siteSettingsPermissions}</h2>
+ </div>
<cr-link-row class="two-line" data-route="SITE_SETTINGS_COOKIES"
id="cookies" label="$i18n{siteSettingsCookies}"
diff --git a/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.js b/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.js
index 8eb6db69278..85c0349ce7d 100644
--- a/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.js
+++ b/chromium/chrome/browser/resources/settings/site_settings_page/site_settings_page.js
@@ -28,14 +28,6 @@ Polymer({
},
/** @private */
- enableSiteSettings_: {
- type: Boolean,
- value: function() {
- return loadTimeData.getBoolean('enableSiteSettings');
- },
- },
-
- /** @private */
isGuest_: {
type: Boolean,
value: function() {
diff --git a/chromium/chrome/browser/resources/settings/system_page/system_page.html b/chromium/chrome/browser/resources/settings/system_page/system_page.html
index 256673d3432..a6117d772a5 100644
--- a/chromium/chrome/browser/resources/settings/system_page/system_page.html
+++ b/chromium/chrome/browser/resources/settings/system_page/system_page.html
@@ -1,8 +1,8 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../controls/extension_controlled_indicator.html">
<link rel="import" href="../controls/settings_toggle_button.html">
<link rel="import" href="../lifetime_browser_proxy.html">
@@ -24,14 +24,25 @@
label="$i18n{hardwareAccelerationLabel}">
<template is="dom-if" if="[[shouldShowRestart_(
prefs.hardware_acceleration_mode.enabled.value)]]">
- <paper-button on-click="onRestartTap_" slot="more-actions">
+ <cr-button on-click="onRestartTap_" slot="more-actions">
$i18n{restart}
- </paper-button>
+ </cr-button>
</template>
</settings-toggle-button>
+
<div id="proxy" class="settings-box" on-click="onProxyTap_"
- actionable$="[[!isProxyEnforcedByPolicy_]]">
- <div class="start">$i18n{proxySettingsLabel}</div>
+ actionable$="[[isProxyDefault_]]">
+ <div class="start settings-box-text" hidden$="[[!isProxyDefault_]]">
+ $i18n{proxySettingsLabel}
+ </div>
+ <div class="start settings-box-text"
+ hidden$="[[!prefs.proxy.extensionId]]">
+ $i18n{proxySettingsExtensionLabel}
+ </div>
+ <div class="start settings-box-text"
+ hidden$="[[!isProxyEnforcedByPolicy_]]">
+ $i18n{proxySettingsPolicyLabel}
+ </div>
<cr-icon-button class="icon-external"
hidden$="[[isProxyEnforcedByPolicy_]]"
aria-label="$i18n{proxySettingsLabel}"></cr-icon-button>
diff --git a/chromium/chrome/browser/resources/settings/system_page/system_page.js b/chromium/chrome/browser/resources/settings/system_page/system_page.js
index c94b282ed9e..7707ed9cf67 100644
--- a/chromium/chrome/browser/resources/settings/system_page/system_page.js
+++ b/chromium/chrome/browser/resources/settings/system_page/system_page.js
@@ -19,19 +19,28 @@ Polymer({
/** @private */
isProxyEnforcedByPolicy_: {
type: Boolean,
- computed: 'computeIsProxyEnforcedByPolicy_(prefs.proxy.*)',
+ },
+
+ /** @private */
+ isProxyDefault_: {
+ type: Boolean,
},
},
+ observers: [
+ 'observeProxyPrefChanged_(prefs.proxy.*)',
+ ],
+
/**
- * @return {boolean}
* @private
*/
- computeIsProxyEnforcedByPolicy_: function() {
+ observeProxyPrefChanged_: function() {
const pref = this.get('prefs.proxy');
// TODO(dbeam): do types of policy other than USER apply on ChromeOS?
- return pref.enforcement == chrome.settingsPrivate.Enforcement.ENFORCED &&
+ this.isProxyEnforcedByPolicy_ =
+ pref.enforcement == chrome.settingsPrivate.Enforcement.ENFORCED &&
pref.controlledBy == chrome.settingsPrivate.ControlledBy.USER_POLICY;
+ this.isProxyDefault_ = !this.isProxyEnforcedByPolicy_ && !pref.extensionId;
},
/** @private */
@@ -46,7 +55,7 @@ Polymer({
/** @private */
onProxyTap_: function() {
- if (!this.isProxyEnforcedByPolicy_) {
+ if (this.isProxyDefault_) {
settings.SystemPageBrowserProxyImpl.getInstance().showProxySettings();
}
},
diff --git a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration.svg b/chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration.svg
deleted file mode 100644
index a0f12625866..00000000000
--- a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 168"><defs><style>.cls-1{fill:#fff}.cls-3{fill:#e8e9eb}.cls-5{fill:#bdc0c5}</style></defs><path class="cls-1" d="M256 89a41 41 0 0 0-41 39.13h82A41 41 0 0 0 256 89z"/><path d="M97.76 72H103c0-10.83 2.9-19.34 8.63-25.3 9-9.37 22.15-9.41 22.28-9.41L134 32c-.62 0-15.32 0-25.84 10.91-6.79 6.99-10.4 16.78-10.4 29.09z" fill="#4285f4"/><path class="cls-3" d="M82.41 102.42A35.27 35.27 0 0 1 67 106.75V112a40.36 40.36 0 0 0 18-5c8.23-4.61 18-14.42 18-35h-5.24c0 14.48-5.16 24.71-15.35 30.42zM143.78 33.27v5.33h7.41a6.35 6.35 0 0 1-2.77 4.15 8.28 8.28 0 0 1-12.36-4.35 8.29 8.29 0 0 1 7.71-10.91 7.52 7.52 0 0 1 5.23 2.05l4-3.95a13.22 13.22 0 0 0-9.22-3.59 13.75 13.75 0 0 0-12.3 7.6 13.64 13.64 0 0 0 0 12.35 13.76 13.76 0 0 0 12.3 7.59 13.15 13.15 0 0 0 9.12-3.33 13.46 13.46 0 0 0 4.1-10.12 15.82 15.82 0 0 0-.25-2.82zM433 109h18v-8.48a11 11 0 0 0-18 8.48zM491 59.49h-30.2a5.6 5.6 0 0 0-5.59 5.59v72.36a5.6 5.6 0 0 0 5.59 5.56H491a5.6 5.6 0 0 0 5.59-5.59V65.08a5.6 5.6 0 0 0-5.59-5.59zm4.89 77.95a4.89 4.89 0 0 1-4.89 4.89h-30.2a4.89 4.89 0 0 1-4.89-4.89V65.08a4.89 4.89 0 0 1 4.89-4.89H491a4.89 4.89 0 0 1 4.89 4.89zM418.43 92.8c6.1-10.92 17.06-16.46 32.56-16.46v-5.62c-22 0-32.53 10.52-37.46 19.34a43.35 43.35 0 0 0-5.36 19.27h5.62a37.88 37.88 0 0 1 4.64-16.53zM342 50.45a9.28 9.28 0 0 1-8.17-4.86l-9.38-16.21A21.84 21.84 0 0 0 321 40.92a21 21 0 0 0 17.56 20.86l7-11.94a10.66 10.66 0 0 1-3.56.61z"/><path class="cls-3" d="M347.91 33.67a9.58 9.58 0 0 1 3.54 7.33 8.47 8.47 0 0 1-1.28 4.61L340.66 62h1.26a20.93 20.93 0 0 0 15.21-6.49h-2.81a8.64 8.64 0 0 1 7.82-8.6 20.8 20.8 0 0 0 .87-5.82 21.63 21.63 0 0 0-1.23-7.35z"/><path class="cls-3" d="M342 31.55l18.69.07a20.52 20.52 0 0 0-13.78-11A50.49 50.49 0 0 0 341 .16V0h-6c.6.9 1.14 1.79 1.62 2.67A44.81 44.81 0 0 1 341.83 20a20.87 20.87 0 0 0-15.94 7.49l6.88 12a9.47 9.47 0 0 1 9.23-7.94z"/><circle class="cls-3" cx="342" cy="41" r="7.35" transform="rotate(-89.77 342 40.997)"/><path class="cls-3" d="M258.56 166.88A37.06 37.06 0 0 1 221.77 144H226v-8.48a11 11 0 0 0-6.86-2.51v-.48a37 37 0 0 1 34.36-39.47l-.07-1a38 38 0 0 0-35.29 40.53v.45A11 11 0 0 0 208 144h12.68a38 38 0 0 0 73.21-11.35l-1-.07a37 37 0 0 1-34.33 34.3z"/><path d="M62.72 48.5H0v88.33h67.51V53.28a4.78 4.78 0 0 0-4.79-4.78z" fill="#f4f4f4"/><path class="cls-5" d="M68 53.28A5.3 5.3 0 0 0 62.72 48H0v1h62.72A4.28 4.28 0 0 1 67 53.28v83.06H0v1h68zM0 143.01h86v.99H0zM451.72 139.1V63.73a7.9 7.9 0 0 1 7.89-7.89h25.07v-.7h-25.06a8.6 8.6 0 0 0-8.6 8.59v75.37a8.6 8.6 0 0 0 8.6 8.59H472V147h-12.38a7.9 7.9 0 0 1-7.9-7.9zM495.22 55.55v.75a7.9 7.9 0 0 1 5.26 7.43v75.37a7.9 7.9 0 0 1-7.89 7.89H480.2v.7h12.39a8.6 8.6 0 0 0 8.6-8.59V63.73a8.61 8.61 0 0 0-5.97-8.18z"/><path d="M499.48 7.6c-11.6 11.7-11.6 28-11.59 28.74 0 .15 0 14.78-10 24.78-6.34 6.37-15.38 9.6-26.89 9.6v5.62c13.08 0 23.48-3.8 30.91-11.3 11.6-11.7 11.6-28 11.59-28.74 0-.15 0-14.78 10-24.78a29.73 29.73 0 0 1 8.5-5.94V0h-1.28a35.46 35.46 0 0 0-11.24 7.6z" fill="#34a751"/><path class="cls-1" d="M62.56 99.28a11.77 11.77 0 0 0-9.48 5 7.42 7.42 0 0 0-2.7-.52c-4.49 0-8.12 4-8.12 9h32.49c0-7.46-5.46-13.48-12.19-13.48z"/><path class="cls-5" d="M68 70v.53a8.35 8.35 0 0 1 8.44 7.94H68V79h9v-.26A8.88 8.88 0 0 0 68 70zM166.5 81a2 2 0 0 1 2-2h4.72v-2a2.55 2.55 0 0 1 5.11 0v2h.49v-2a3 3 0 0 0-6.09 0v1.44h-4.23A2.48 2.48 0 0 0 166 81v4.5h.49zM187 85.19h-1.43V81a2.49 2.49 0 0 0-2.57-2.52h-3.25V79H183a2 2 0 0 1 2 2v4.72h2a2.55 2.55 0 0 1 0 5.11h-2v.49h2a3 3 0 0 0 0-6.09zM185 95.52a2 2 0 0 1-2 2h-4v-1.44a3.27 3.27 0 0 0-6.54 0V98h.54v-1.92a2.78 2.78 0 0 1 5.56 0V98H183a2.49 2.49 0 0 0 2.48-2.48v-3.26H185zM166.49 95.52v-4h1.43a3.27 3.27 0 1 0 0-6.54h-.24v.49h.24a2.78 2.78 0 0 1 0 5.56H166v4.5a2.49 2.49 0 0 0 2.48 2.47h3v-.49h-3a2 2 0 0 1-1.99-1.99zM231.5 32.3v14.81h2.64V32.3zm2.15 14.32H232V32.79h1.66z"/><path class="cls-5" d="M234.61 28h-27.22a2.4 2.4 0 0 0-2.39 2.39v3.1h.49v-3.1a1.9 1.9 0 0 1 1.9-1.9h27.21a1.9 1.9 0 0 1 1.9 1.9V49a1.9 1.9 0 0 1-1.9 1.9h-27.21a1.9 1.9 0 0 1-1.9-1.9v-6.52l1.87 2.58 2.14-1.55-2.13-2.93 3.44-1.12-.81-2.51-3.43 1.11v-3.62H205v.49h1.07v3.8l3.61-1.17.51 1.57-3.62 1.17 2.24 3.08-1.34 1L205 41v8a2.4 2.4 0 0 0 2.39 2.39h27.21A2.4 2.4 0 0 0 237 49V30.39a2.4 2.4 0 0 0-2.39-2.39z"/><path class="cls-5" d="M219.68 34.44v3.62l-3.43-1.11-.82 2.51 3.44 1.12-2.13 2.93 2.14 1.55 2.12-2.92 2.12 2.92 2.14-1.55-2.13-2.93 3.44-1.12-.82-2.51-3.43 1.11v-3.62zm5.75 3.13l.51 1.57-3.61 1.17 2.24 3.08-1.34 1-2.23-3.08-2.23 3.06-1.34-1 2.24-3.08-3.62-1.17.51-1.57 3.61 1.17v-3.8h1.66v3.8zM296.75 69.86h-.5v3.75l-5.2-5.2 5.2-5.21v3.76h.5V62l-6.41 6.41 6.41 6.41v-4.96zM296.25 87.28h.5v-3.75l5.2 5.2-5.2 5.21v-3.75h-.5v4.95l6.41-6.41-6.41-6.41v4.96z"/><path class="cls-5" d="M296.5 68.07v.5a10 10 0 0 1 8.62 15.08l.43.25a10.5 10.5 0 0 0-9-15.83zM296.5 88.57a10 10 0 0 1-8.62-15.08l-.43-.25a10.5 10.5 0 0 0 9 15.83zM47 31.7V20.58H23.49v-3a2.1 2.1 0 0 1 2.09-2.11H44.4a2.11 2.11 0 0 1 2.11 2.11v2H47v-2A2.6 2.6 0 0 0 44.4 15H25.6a2.59 2.59 0 0 0-2.6 2.6v3.48h23.51V31.7a2.11 2.11 0 0 1-2.11 2.11H25.6a2.11 2.11 0 0 1-2.11-2.11v-8h22.45v-.5H23v8.5a2.6 2.6 0 0 0 2.6 2.6h18.8a2.6 2.6 0 0 0 2.6-2.6zM354 101.55a4.78 4.78 0 1 0 4.78 4.78 4.79 4.79 0 0 0-4.78-4.78zm0 9.06a4.28 4.28 0 1 1 4.28-4.28 4.28 4.28 0 0 1-4.28 4.29z"/><path class="cls-5" d="M365.9 102.27l-2.41-4.18a.88.88 0 0 0-1.05-.38l-2.88 1.16a9 9 0 0 0-1.85-1.07l-.43-3.06a.85.85 0 0 0-.85-.73h-4.84a.84.84 0 0 0-.84.73l-.43 3.06a9.33 9.33 0 0 0-1.85 1.07l-2.88-1.16a.85.85 0 0 0-1 .38l-2.42 4.19a.84.84 0 0 0 .22 1.09l2.44 1.9a7.56 7.56 0 0 0-.09 1.07 8 8 0 0 0 .07 1.07l-2.44 1.91a.88.88 0 0 0-.21 1.09l2.41 4.18a.87.87 0 0 0 1.05.38l2.88-1.16a9 9 0 0 0 1.85 1.07l.44 3.07a.87.87 0 0 0 .85.72h4.84a.83.83 0 0 0 .84-.73l.43-3.06a9.34 9.34 0 0 0 1.85-1.07l2.88 1.16a.85.85 0 0 0 1-.38l2.42-4.19a.84.84 0 0 0-.22-1.09l-2.41-1.91a9.82 9.82 0 0 0 .06-1.07 7.93 7.93 0 0 0-.07-1.07l2.44-1.91a.88.88 0 0 0 .2-1.08zm-.52.7l-2.67 2.09v.15a7.28 7.28 0 0 1 .09 1.14 9.76 9.76 0 0 1-.07 1.15v.14l2.64 2.09a.33.33 0 0 1 .08.44l-2.45 4.17a.34.34 0 0 1-.43.16l-3.14-1.26-.11.09a8.89 8.89 0 0 1-2 1.15l-.13.05-.47 3.36a.33.33 0 0 1-.34.29h-4.84a.36.36 0 0 1-.36-.3l-.47-3.34-.13-.06a8.58 8.58 0 0 1-2-1.15l-.11-.09-3.12 1.26a.36.36 0 0 1-.44-.16l-2.41-4.18a.37.37 0 0 1 .08-.45l2.67-2.09v-.15a7.4 7.4 0 0 1-.09-1.14 7.28 7.28 0 0 1 .1-1.14v-.15l-2.62-2.04a.33.33 0 0 1-.08-.44l2.44-4.23a.34.34 0 0 1 .43-.16l3.14 1.26.11-.09a8.9 8.9 0 0 1 2-1.15l.13-.05.47-3.34a.34.34 0 0 1 .34-.3h4.84a.35.35 0 0 1 .36.3l.47 3.35.13.05a8.58 8.58 0 0 1 2 1.15l.11.09 3.12-1.26a.36.36 0 0 1 .44.16l2.41 4.18a.37.37 0 0 1-.13.48zM62.56 99a12 12 0 0 0-9.56 5 7.64 7.64 0 0 0-2.62-.47c-4.62 0-8.38 4.14-8.38 9.24v.23h33v-.28C75 105.15 69.42 99 62.56 99zm11.93 13.44h-32c.13-4.66 3.61-8.4 7.87-8.4a7.19 7.19 0 0 1 2.62.5l.17.07.11-.15a11.5 11.5 0 0 1 9.28-4.9c6.52 0 11.81 5.75 11.95 12.88zM375.91 42.28a13.18 13.18 0 0 0-10.17 4.77A8.89 8.89 0 0 0 354 55.51v.27h35.1v-.27a13.24 13.24 0 0 0-13.19-13.23zm-21.33 13a8.35 8.35 0 0 1 11.15-7.61l.18.06.12-.15a12.69 12.69 0 0 1 22.56 7.7zM441 33.51a2.5 2.5 0 1 0-2.5-2.5 2.51 2.51 0 0 0 2.5 2.5zm0-4.51a2 2 0 1 1-2 2 2 2 0 0 1 2-2z"/><path class="cls-5" d="M441 38a7 7 0 0 0 6.53-4.49H452V38h5v-4.49h2v-5h-11.47A7 7 0 1 0 441 38zm0-13.48a6.48 6.48 0 0 1 6.11 4.32l.06.17h11.32v4h-2v4.49h-4V33h-5.3l-.06.17a6.48 6.48 0 1 1-6.13-8.65z"/><path d="M256 92v1a37 37 0 0 1 37 37h1a38 38 0 0 0-38-38z" fill="#f7bb2a"/><path class="cls-1" d="M411.08 121a16.81 16.81 0 0 0-13.08 6.27 11.21 11.21 0 0 0-15 10.58h44.93A16.85 16.85 0 0 0 411.08 121z"/><path class="cls-3" d="M411.08 121.7a16.17 16.17 0 0 1 16.13 15.44h-43.48a10.5 10.5 0 0 1 14-9.22l.47.17.31-.39a16.09 16.09 0 0 1 12.56-6m0-.7a16.81 16.81 0 0 0-13.07 6.27 11.21 11.21 0 0 0-15 10.58h44.93A16.85 16.85 0 0 0 411.08 121z"/></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.html b/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.html
deleted file mode 100644
index 7654603c402..00000000000
--- a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}>
- <head>
- <meta charset="utf-8">
- <link rel="stylesheet" href="chrome://resources/css/md_colors.css">
- <link rel="import" href="sync_confirmation_app.html"></link>
- <style>
- body {
- margin: 0;
- padding: 0;
- width: 512px;
- }
- [dark] body {
- background-color: var(--md-background-color);
- }
- </style>
- </head>
- <body>
- <sync-confirmation-app></sync-confirmation-app>
- </body>
- <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
- <link rel="import" href="chrome://resources/html/cr.html"></script>
- <link rel="import" href="chrome://resources/html/util.html"></script>
- <script src="sync_confirmation.js"></script>
- <link rel="import" href="chrome://resources/html/dark_mode.html">
-</html>
diff --git a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.js b/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.js
deleted file mode 100644
index 31aa325f3ef..00000000000
--- a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.js
+++ /dev/null
@@ -1,32 +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. */
-
-cr.define('sync.confirmation', function() {
- 'use strict';
-
- function initialize() {
- const syncConfirmationBrowserProxy =
- sync.confirmation.SyncConfirmationBrowserProxyImpl.getInstance();
- // Prefer using |document.body.offsetHeight| instead of
- // |document.body.scrollHeight| as it returns the correct height of the
- // even when the page zoom in Chrome is different than 100%.
- syncConfirmationBrowserProxy.initializedWithSize(
- [document.body.offsetHeight]);
- // The web dialog size has been initialized, so reset the body width to
- // auto. This makes sure that the body only takes up the viewable width,
- // e.g. when there is a scrollbar.
- document.body.style.width = 'auto';
- }
-
- function clearFocus() {
- document.activeElement.blur();
- }
-
- return {
- clearFocus: clearFocus,
- initialize: initialize,
- };
-});
-
-document.addEventListener('DOMContentLoaded', sync.confirmation.initialize);
diff --git a/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.html b/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.html
index fb3ef3b0c09..b0ce42afce4 100644
--- a/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.html
+++ b/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.html
@@ -3,10 +3,9 @@
<head>
<meta charset="utf-8">
<link rel="import" href="chrome://resources/html/polymer.html">
+ <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_radio_button/cr_radio_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_radio_group/cr_radio_group.html">
- <link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
- <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="signin_shared_css.html">
<link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
@@ -14,7 +13,7 @@
<link rel="import" href="chrome://resources/html/load_time_data.html">
<link rel="import" href="chrome://resources/html/util.html">
<custom-style>
- <style include="signin-dialog-shared paper-button-style">
+ <style include="signin-dialog-shared">
.container {
/* The sign-in confirmation dialog uses a width that is larger than
* the other sign-in dialogs to fit cases when the user has an email
@@ -91,12 +90,12 @@
</cr-radio-group>
</div>
<div class="action-container">
- <paper-button class="action-button" id="confirmButton">
+ <cr-button class="action-button" id="confirmButton">
$i18n{signinEmailConfirmationConfirmLabel}
- </paper-button>
- <paper-button id="closeButton">
+ </cr-button>
+ <cr-button id="closeButton">
$i18n{signinEmailConfirmationCloseLabel}
- </paper-button>
+ </cr-button>
</div>
</div>
</body>
diff --git a/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.js b/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.js
index 3a531110d28..c09b83eaf95 100644
--- a/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.js
+++ b/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.js
@@ -26,7 +26,7 @@ cr.define('signin.emailConfirmation', function() {
// on "enter" being pressed and the user hits "enter", perform the default
// action of the dialog, which is "OK".
if (e.key == 'Enter' &&
- !/^(A|PAPER-BUTTON)$/.test(document.activeElement.tagName)) {
+ !/^(A|CR-BUTTON)$/.test(document.activeElement.tagName)) {
$('confirmButton').click();
e.preventDefault();
}
diff --git a/chromium/chrome/browser/resources/signin/signin_error/signin_error.html b/chromium/chrome/browser/resources/signin/signin_error/signin_error.html
index c0ba54d8367..8510d635a75 100644
--- a/chromium/chrome/browser/resources/signin/signin_error/signin_error.html
+++ b/chromium/chrome/browser/resources/signin/signin_error/signin_error.html
@@ -2,9 +2,8 @@
<html dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
<meta charset="utf-8">
- <link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
+ <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/html/polymer.html">
- <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="signin_shared_css.html">
<link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
@@ -12,7 +11,7 @@
<link rel="import" href="chrome://resources/html/load_time_data.html">
<link rel="import" href="chrome://resources/html/util.html">
<custom-style>
- <style include="signin-dialog-shared paper-button-style">
+ <style include="signin-dialog-shared">
.details {
line-height: 20px;
margin-bottom: 8px;
@@ -85,15 +84,15 @@
<p>$i18n{profileBlockedRemoveProfileSuggestion}</p>
</div>
<div class="action-container">
- <paper-button class="action-button" id="switchButton">
+ <cr-button class="action-button" id="switchButton">
$i18n{signinErrorSwitchLabel}
- </paper-button>
- <paper-button id="closeButton">
+ </cr-button>
+ <cr-button id="closeButton">
$i18n{signinErrorCloseLabel}
- </paper-button>
- <paper-button id="confirmButton" hidden>
+ </cr-button>
+ <cr-button id="confirmButton" hidden>
$i18n{signinErrorOkLabel}
- </paper-button>
+ </cr-button>
</div>
</div>
</body>
diff --git a/chromium/chrome/browser/resources/signin/signin_error/signin_error.js b/chromium/chrome/browser/resources/signin/signin_error/signin_error.js
index 749c99bc038..71d654cafcb 100644
--- a/chromium/chrome/browser/resources/signin/signin_error/signin_error.js
+++ b/chromium/chrome/browser/resources/signin/signin_error/signin_error.js
@@ -26,7 +26,7 @@ cr.define('signin.error', function() {
// on "enter" being pressed and the user hits "enter", perform the default
// action of the dialog, which is "OK".
if (e.key == 'Enter' &&
- !/^(A|PAPER-BUTTON)$/.test(document.activeElement.tagName)) {
+ !/^(A|CR-BUTTON)$/.test(document.activeElement.tagName)) {
$('confirmButton').click();
e.preventDefault();
}
diff --git a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/BUILD.gn b/chromium/chrome/browser/resources/signin/sync_confirmation/BUILD.gn
index 6f36b5e3c54..6f36b5e3c54 100644
--- a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/BUILD.gn
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/BUILD.gn
diff --git a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/ic_google.png b/chromium/chrome/browser/resources/signin/sync_confirmation/images/ic_google.png
index f7602a57b40..f7602a57b40 100644
--- a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/ic_google.png
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/images/ic_google.png
Binary files differ
diff --git a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/ic_google_2x.png b/chromium/chrome/browser/resources/signin/sync_confirmation/images/ic_google_2x.png
index 76d098584c9..76d098584c9 100644
--- a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/ic_google_2x.png
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/images/ic_google_2x.png
Binary files differ
diff --git a/chromium/chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration.svg b/chromium/chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration.svg
new file mode 100644
index 00000000000..324434e254a
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration.svg
@@ -0,0 +1 @@
+<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 168"><defs><style>.cls-1{fill:#fff}.cls-3{fill:#e8e9eb}.cls-5{fill:#bdc0c5}</style></defs><path class="cls-1" d="M256 89a41 41 0 0 0-41 39.13h82A41 41 0 0 0 256 89z"/><path d="M97.76 72H103c0-10.83 2.9-19.34 8.63-25.3 9-9.37 22.15-9.41 22.28-9.41L134 32c-.62 0-15.32 0-25.84 10.91-6.79 6.99-10.4 16.78-10.4 29.09z" fill="#4285f4"/><path class="cls-3" d="M82.41 102.42A35.27 35.27 0 0 1 67 106.75V112a40.36 40.36 0 0 0 18-5c8.23-4.61 18-14.42 18-35h-5.24c0 14.48-5.16 24.71-15.35 30.42zm61.37-69.15v5.33h7.41a6.35 6.35 0 0 1-2.77 4.15 8.28 8.28 0 0 1-12.36-4.35 8.29 8.29 0 0 1 7.71-10.91 7.52 7.52 0 0 1 5.23 2.05l4-3.95a13.22 13.22 0 0 0-9.22-3.59 13.75 13.75 0 0 0-12.3 7.6 13.64 13.64 0 0 0 0 12.35 13.76 13.76 0 0 0 12.3 7.59 13.15 13.15 0 0 0 9.12-3.33 13.46 13.46 0 0 0 4.1-10.12 15.82 15.82 0 0 0-.25-2.82zM433 109h18v-8.48a11 11 0 0 0-18 8.48zm58-49.51h-30.2a5.6 5.6 0 0 0-5.59 5.59v72.36a5.6 5.6 0 0 0 5.59 5.56H491a5.6 5.6 0 0 0 5.59-5.59V65.08a5.6 5.6 0 0 0-5.59-5.59zm4.89 77.95a4.89 4.89 0 0 1-4.89 4.89h-30.2a4.89 4.89 0 0 1-4.89-4.89V65.08a4.89 4.89 0 0 1 4.89-4.89H491a4.89 4.89 0 0 1 4.89 4.89zM418.43 92.8c6.1-10.92 17.06-16.46 32.56-16.46v-5.62c-22 0-32.53 10.52-37.46 19.34a43.35 43.35 0 0 0-5.36 19.27h5.62a37.88 37.88 0 0 1 4.64-16.53zM342 50.45a9.28 9.28 0 0 1-8.17-4.86l-9.38-16.21A21.84 21.84 0 0 0 321 40.92a21 21 0 0 0 17.56 20.86l7-11.94a10.66 10.66 0 0 1-3.56.61z"/><path class="cls-3" d="M347.91 33.67a9.58 9.58 0 0 1 3.54 7.33 8.47 8.47 0 0 1-1.28 4.61L340.66 62h1.26a20.93 20.93 0 0 0 15.21-6.49h-2.81a8.64 8.64 0 0 1 7.82-8.6 20.8 20.8 0 0 0 .87-5.82 21.63 21.63 0 0 0-1.23-7.35z"/><path class="cls-3" d="M342 31.55l18.69.07a20.52 20.52 0 0 0-13.78-11A50.49 50.49 0 0 0 341 .16V0h-6c.6.9 1.14 1.79 1.62 2.67A44.81 44.81 0 0 1 341.83 20a20.87 20.87 0 0 0-15.94 7.49l6.88 12a9.47 9.47 0 0 1 9.23-7.94z"/><circle class="cls-3" cx="342" cy="41" r="7.35" transform="rotate(-89.77 342 40.997)"/><path class="cls-3" d="M258.56 166.88A37.06 37.06 0 0 1 221.77 144H226v-8.48a11 11 0 0 0-6.86-2.51v-.48a37 37 0 0 1 34.36-39.47l-.07-1a38 38 0 0 0-35.29 40.53v.45A11 11 0 0 0 208 144h12.68a38 38 0 0 0 73.21-11.35l-1-.07a37 37 0 0 1-34.33 34.3z"/><path d="M62.72 48.5H0v88.33h67.51V53.28a4.78 4.78 0 0 0-4.79-4.78z" fill="#f4f4f4"/><path class="cls-5" d="M68 53.28A5.3 5.3 0 0 0 62.72 48H0v1h62.72A4.28 4.28 0 0 1 67 53.28v83.06H0v1h68zM0 143.01h86v.99H0zm451.72-3.91V63.73a7.9 7.9 0 0 1 7.89-7.89h25.07v-.7h-25.06a8.6 8.6 0 0 0-8.6 8.59v75.37a8.6 8.6 0 0 0 8.6 8.59H472V147h-12.38a7.9 7.9 0 0 1-7.9-7.9zm43.5-83.55v.75a7.9 7.9 0 0 1 5.26 7.43v75.37a7.9 7.9 0 0 1-7.89 7.89H480.2v.7h12.39a8.6 8.6 0 0 0 8.6-8.59V63.73a8.61 8.61 0 0 0-5.97-8.18z"/><path d="M499.48 7.6c-11.6 11.7-11.6 28-11.59 28.74 0 .15 0 14.78-10 24.78-6.34 6.37-15.38 9.6-26.89 9.6v5.62c13.08 0 23.48-3.8 30.91-11.3 11.6-11.7 11.6-28 11.59-28.74 0-.15 0-14.78 10-24.78a29.73 29.73 0 0 1 8.5-5.94V0h-1.28a35.46 35.46 0 0 0-11.24 7.6z" fill="#34a751"/><path class="cls-1" d="M62.56 99.28a11.77 11.77 0 0 0-9.48 5 7.42 7.42 0 0 0-2.7-.52c-4.49 0-8.12 4-8.12 9h32.49c0-7.46-5.46-13.48-12.19-13.48z"/><path class="cls-5" d="M68 70v.53a8.35 8.35 0 0 1 8.44 7.94H68V79h9v-.26A8.88 8.88 0 0 0 68 70zm98.5 11a2 2 0 0 1 2-2h4.72v-2a2.55 2.55 0 0 1 5.11 0v2h.49v-2a3 3 0 0 0-6.09 0v1.44h-4.23A2.48 2.48 0 0 0 166 81v4.5h.49zm20.5 4.19h-1.43V81a2.49 2.49 0 0 0-2.57-2.52h-3.25V79H183a2 2 0 0 1 2 2v4.72h2a2.55 2.55 0 0 1 0 5.11h-2v.49h2a3 3 0 0 0 0-6.09zm-2 10.33a2 2 0 0 1-2 2h-4v-1.44a3.27 3.27 0 0 0-6.54 0V98h.54v-1.92a2.78 2.78 0 0 1 5.56 0V98H183a2.49 2.49 0 0 0 2.48-2.48v-3.26H185zm-18.51 0v-4h1.43a3.27 3.27 0 1 0 0-6.54h-.24v.49h.24a2.78 2.78 0 0 1 0 5.56H166v4.5a2.49 2.49 0 0 0 2.48 2.47h3v-.49h-3a2 2 0 0 1-1.99-1.99zM231.5 32.3v14.81h2.64V32.3zm2.15 14.32H232V32.79h1.66z"/><path class="cls-5" d="M234.61 28h-27.22a2.4 2.4 0 0 0-2.39 2.39v3.1h.49v-3.1a1.9 1.9 0 0 1 1.9-1.9h27.21a1.9 1.9 0 0 1 1.9 1.9V49a1.9 1.9 0 0 1-1.9 1.9h-27.21a1.9 1.9 0 0 1-1.9-1.9v-6.52l1.87 2.58 2.14-1.55-2.13-2.93 3.44-1.12-.81-2.51-3.43 1.11v-3.62H205v.49h1.07v3.8l3.61-1.17.51 1.57-3.62 1.17 2.24 3.08-1.34 1L205 41v8a2.4 2.4 0 0 0 2.39 2.39h27.21A2.4 2.4 0 0 0 237 49V30.39a2.4 2.4 0 0 0-2.39-2.39z"/><path class="cls-5" d="M219.68 34.44v3.62l-3.43-1.11-.82 2.51 3.44 1.12-2.13 2.93 2.14 1.55 2.12-2.92 2.12 2.92 2.14-1.55-2.13-2.93 3.44-1.12-.82-2.51-3.43 1.11v-3.62zm5.75 3.13l.51 1.57-3.61 1.17 2.24 3.08-1.34 1-2.23-3.08-2.23 3.06-1.34-1 2.24-3.08-3.62-1.17.51-1.57 3.61 1.17v-3.8h1.66v3.8zm71.32 32.29h-.5v3.75l-5.2-5.2 5.2-5.21v3.76h.5V62l-6.41 6.41 6.41 6.41v-4.96zm-.5 17.42h.5v-3.75l5.2 5.2-5.2 5.21v-3.75h-.5v4.95l6.41-6.41-6.41-6.41v4.96z"/><path class="cls-5" d="M296.5 68.07v.5a10 10 0 0 1 8.62 15.08l.43.25a10.5 10.5 0 0 0-9-15.83zm0 20.5a10 10 0 0 1-8.62-15.08l-.43-.25a10.5 10.5 0 0 0 9 15.83zM47 31.7V20.58H23.49v-3a2.1 2.1 0 0 1 2.09-2.11H44.4a2.11 2.11 0 0 1 2.11 2.11v2H47v-2A2.6 2.6 0 0 0 44.4 15H25.6a2.59 2.59 0 0 0-2.6 2.6v3.48h23.51V31.7a2.11 2.11 0 0 1-2.11 2.11H25.6a2.11 2.11 0 0 1-2.11-2.11v-8h22.45v-.5H23v8.5a2.6 2.6 0 0 0 2.6 2.6h18.8a2.6 2.6 0 0 0 2.6-2.6zm307 69.85a4.78 4.78 0 1 0 4.78 4.78 4.79 4.79 0 0 0-4.78-4.78zm0 9.06a4.28 4.28 0 1 1 4.28-4.28 4.28 4.28 0 0 1-4.28 4.29z"/><path class="cls-5" d="M365.9 102.27l-2.41-4.18a.88.88 0 0 0-1.05-.38l-2.88 1.16a9 9 0 0 0-1.85-1.07l-.43-3.06a.85.85 0 0 0-.85-.73h-4.84a.84.84 0 0 0-.84.73l-.43 3.06a9.33 9.33 0 0 0-1.85 1.07l-2.88-1.16a.85.85 0 0 0-1 .38l-2.42 4.19a.84.84 0 0 0 .22 1.09l2.44 1.9a7.56 7.56 0 0 0-.09 1.07 8 8 0 0 0 .07 1.07l-2.44 1.91a.88.88 0 0 0-.21 1.09l2.41 4.18a.87.87 0 0 0 1.05.38l2.88-1.16a9 9 0 0 0 1.85 1.07l.44 3.07a.87.87 0 0 0 .85.72h4.84a.83.83 0 0 0 .84-.73l.43-3.06a9.34 9.34 0 0 0 1.85-1.07l2.88 1.16a.85.85 0 0 0 1-.38l2.42-4.19a.84.84 0 0 0-.22-1.09l-2.41-1.91a9.82 9.82 0 0 0 .06-1.07 7.93 7.93 0 0 0-.07-1.07l2.44-1.91a.88.88 0 0 0 .2-1.08zm-.52.7l-2.67 2.09v.15a7.28 7.28 0 0 1 .09 1.14 9.76 9.76 0 0 1-.07 1.15v.14l2.64 2.09a.33.33 0 0 1 .08.44l-2.45 4.17a.34.34 0 0 1-.43.16l-3.14-1.26-.11.09a8.89 8.89 0 0 1-2 1.15l-.13.05-.47 3.36a.33.33 0 0 1-.34.29h-4.84a.36.36 0 0 1-.36-.3l-.47-3.34-.13-.06a8.58 8.58 0 0 1-2-1.15l-.11-.09-3.12 1.26a.36.36 0 0 1-.44-.16l-2.41-4.18a.37.37 0 0 1 .08-.45l2.67-2.09v-.15a7.4 7.4 0 0 1-.09-1.14 7.28 7.28 0 0 1 .1-1.14v-.15l-2.62-2.04a.33.33 0 0 1-.08-.44l2.44-4.23a.34.34 0 0 1 .43-.16l3.14 1.26.11-.09a8.9 8.9 0 0 1 2-1.15l.13-.05.47-3.34a.34.34 0 0 1 .34-.3h4.84a.35.35 0 0 1 .36.3l.47 3.35.13.05a8.58 8.58 0 0 1 2 1.15l.11.09 3.12-1.26a.36.36 0 0 1 .44.16l2.41 4.18a.37.37 0 0 1-.13.48zM62.56 99a12 12 0 0 0-9.56 5 7.64 7.64 0 0 0-2.62-.47c-4.62 0-8.38 4.14-8.38 9.24v.23h33v-.28C75 105.15 69.42 99 62.56 99zm11.93 13.44h-32c.13-4.66 3.61-8.4 7.87-8.4a7.19 7.19 0 0 1 2.62.5l.17.07.11-.15a11.5 11.5 0 0 1 9.28-4.9c6.52 0 11.81 5.75 11.95 12.88zm301.42-70.16a13.18 13.18 0 0 0-10.17 4.77A8.89 8.89 0 0 0 354 55.51v.27h35.1v-.27a13.24 13.24 0 0 0-13.19-13.23zm-21.33 13a8.35 8.35 0 0 1 11.15-7.61l.18.06.12-.15a12.69 12.69 0 0 1 22.56 7.7zM441 33.51a2.5 2.5 0 1 0-2.5-2.5 2.51 2.51 0 0 0 2.5 2.5zm0-4.51a2 2 0 1 1-2 2 2 2 0 0 1 2-2z"/><path class="cls-5" d="M441 38a7 7 0 0 0 6.53-4.49H452V38h5v-4.49h2v-5h-11.47A7 7 0 1 0 441 38zm0-13.48a6.48 6.48 0 0 1 6.11 4.32l.06.17h11.32v4h-2v4.49h-4V33h-5.3l-.06.17a6.48 6.48 0 1 1-6.13-8.65z"/><path d="M256 92v1a37 37 0 0 1 37 37h1a38 38 0 0 0-38-38z" fill="#f7bb2a"/><path class="cls-1" d="M411.08 121a16.81 16.81 0 0 0-13.08 6.27 11.21 11.21 0 0 0-15 10.58h44.93A16.85 16.85 0 0 0 411.08 121z"/><path class="cls-3" d="M411.08 121.7a16.17 16.17 0 0 1 16.13 15.44h-43.48a10.5 10.5 0 0 1 14-9.22l.47.17.31-.39a16.09 16.09 0 0 1 12.56-6m0-.7a16.81 16.81 0 0 0-13.07 6.27 11.21 11.21 0 0 0-15 10.58h44.93A16.85 16.85 0 0 0 411.08 121z"/></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration_dark.svg b/chromium/chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration_dark.svg
index e75815eafcc..e75815eafcc 100644
--- a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/images/sync_confirmation_illustration_dark.svg
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/images/sync_confirmation_illustration_dark.svg
diff --git a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html
index 27758650650..52d93830335 100644
--- a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.html
@@ -1,425 +1,27 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="chrome://resources/css/md_colors.css">
+ <link rel="import" href="sync_confirmation_app.html"></link>
<style>
- html {
- background-color: var(--md-background-color);
+ body {
+ margin: 0;
+ padding: 0;
+ width: 512px;
}
- </style>
- </custom-style>
- <link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
- <link rel="import" href="chrome://resources/html/polymer.html">
- <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
- <link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
- <link rel="import" href="signin_shared_css.html">
- <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
- <custom-style>
- <style include="signin-dialog-shared paper-button-style">
- .picture img {
- border-radius: 50%;
- max-height: 100%;
- max-width: 100%;
- }
-
- .details {
- padding: 0 24px;
- }
-
- #picture-container {
- align-items: center;
- display: flex;
- justify-content: center;
- padding-bottom: 32px;
- padding-top: 24px;
- }
-
- .picture {
- height: 96px;
- margin-inline-start: 84px;
- position: relative;
- width: 96px;
- }
-
- #profile-picture,
- .checkmark-circle {
- position: absolute;
- }
-
- .message-container {
- display: flex;
- margin-bottom: 16px;
- }
-
- .message-container:last-child {
- margin-bottom: 32px;
- }
-
- .message-container .logo {
- background-size: cover;
- flex-shrink: 0;
- height: 20px;
- margin-inline-end: 20px;
- position: relative;
- top: -2px;
- width: 20px;
- }
-
- #chrome-logo {
- background-image: url(../../../../../ui/webui/resources/images/200-logo_chrome.png);
- }
-
- #googleg-logo {
- background-image: url(../../../../../ui/webui/resources/images/200-logo_googleg.png);
- }
-
- .message-container .title {
- font-weight: 500;
- margin-bottom: 4px;
- }
-
- .message-container .body {
- color: var(--cr-secondary-text-color);
- }
-
- .message-container .text {
- line-height: 20px;
- }
-
- .message-container #activityControlsCheckbox {
- margin-inline-start: 40px;
- }
-
- #undoButton {
-<if expr="is_macosx or is_linux">
- margin-inline-end: 8px;
-</if>
-<if expr="not is_macosx and not is_linux">
- margin-inline-start: 8px;
-</if>
- }
-
- #syncDisabledDetails {
- line-height: 20px;
- margin-bottom: 8px;
- margin-top: 16px;
- padding: 0 24px;
- }
-
- #illustration {
- height: 96px;
- margin: 0 auto;
- position: relative;
- width: 264px;
- }
-
- #checkmark-circle {
- background: var(--google-blue-refresh-500);
- border: 2px solid #fff;
- border-radius: 50%;
- bottom: 0;
- height: 24px;
- position: absolute;
- right: 0;
- transform: scale(0);
- width: 24px;
- }
-
- [dark] #checkmark-circle {
- background: var(--google-blue-refresh-300);
- border-color: var(--google-grey-900);
- }
-
- .loaded #checkmark-circle {
- animation: scale-circle 300ms cubic-bezier(0, 0, 0.2, 1) forwards;
- }
-
- @keyframes scale-circle {
- from { transform: scale(0); }
- to { transform: scale(1); }
- }
-
- #checkmark-check {
- left: 5px;
- position: absolute;
- top: 7px;
- }
-
- .loaded #checkmark-path {
- animation: draw-path 300ms cubic-bezier(0, 0, 0.2, 1) 100ms forwards;
- }
-
- @keyframes draw-path {
- from { stroke-dashoffset: 16; }
- to { stroke-dashoffset: 0; }
- }
-
- #icons {
- height: 96px;
- position: absolute;
- width: 264px;
- }
-
- #icons > div {
- -webkit-mask-repeat: no-repeat;
- -webkit-mask-size: cover;
- animation-delay: 200ms;
- animation-duration: 1.4s;
- animation-fill-mode: forwards;
- animation-timing-function: cubic-bezier(0.25, 0.45, 0.4, 0.7);
- background-color: black;
- opacity: 0;
- position: absolute;
- }
-
- [dark] #icons > div {
- background-color: white;
- }
-
- #icon-bookmarks {
- -webkit-mask-image: url(../../../../../ui/webui/resources/images/icon_bookmarks.svg);
- height: 36px;
- left: 58px;
- top: 0;
- width: 36px;
+ @media (prefers-color-scheme: dark) {
+ body {
+ background-color: var(--md-background-color);
}
-
- #icon-extensions {
- -webkit-mask-image: url(../../../../../ui/webui/resources/images/icon_extensions.svg);
- height: 24px;
- left: 30px;
- top: 30px;
- width: 24px;
- }
-
- #icon-passwords {
- -webkit-mask-image: url(../../../../../ui/webui/resources/images/icon_passwords.svg);
- height: 30px;
- left: 38px;
- top: 66px;
- width: 40px;
- }
-
- #icon-history {
- -webkit-mask-image: url(../../../../../ui/webui/resources/images/icon_history.svg);
- height: 36px;
- left: 190px;
- top: 6px;
- width: 36px;
- }
-
- #icon-tabs {
- -webkit-mask-image: url(../../../../../ui/webui/resources/images/icon_tabs.svg);
- height: 24px;
- left: 222px;
- top: 44px;
- width: 24px;
- }
-
- #icon-themes {
- -webkit-mask-image: url(../../../../../ui/webui/resources/images/icon_themes.svg);
- height: 30px;
- left: 184px;
- top: 62px;
- width: 32px;
- }
-
- #icon-circle-open {
- border: 2px solid #000;
- border-radius: 50%;
- height: 8px;
- left: 6px;
- top: 56px;
- width: 8px;
- }
-
- [dark] #icon-circle-open {
- border-color: white;
- }
-
- .icon-circle {
- border-radius: 50%;
- height: 4px;
- width: 4px;
- }
-
- #icon-circle-1 {
- left: 64px;
- top: 50px;
- }
-
- #icon-circle-2 {
- left: 178px;
- top: 18px;
- }
-
- #icon-circle-3 {
- left: 194px;
- top: 50px;
- }
-
- #icon-circle-4 {
- left: 258px;
- top: 36px;
- }
-
- .loaded .fade-top-left {
- animation-name: fade-in, icon-top-left;
- }
-
- .loaded .fade-top-right {
- animation-name: fade-in, icon-top-right;
- }
-
- .loaded .fade-middle-left {
- animation-name: fade-in, icon-middle-left;
- }
-
- .loaded .fade-middle-right {
- animation-name: fade-in, icon-middle-right;
- }
-
- .loaded .fade-bottom-left {
- animation-name: fade-in, icon-bottom-left;
- }
-
- .loaded .fade-bottom-right {
- animation-name: fade-in, icon-bottom-right;
- }
-
- @keyframes fade-in {
- from { opacity: 0; }
- to { opacity: .1; }
- }
-
- @keyframes icon-top-left {
- from { transform: translate(0, 0); }
- to { transform: translate(-4px, -4px); }
- }
-
- @keyframes icon-top-right {
- from { transform: translate(0, 0); }
- to { transform: translate(4px, -4px); }
- }
-
- @keyframes icon-middle-left {
- from { transform: translate(0, 0); }
- to { transform: translate(-4px, 0); }
- }
-
- @keyframes icon-middle-right {
- from { transform: translate(0, 0); }
- to { transform: translate(4px, 0); }
- }
-
- @keyframes icon-bottom-left {
- from { transform: translate(0, 0); }
- to { transform: translate(-4px, 4px); }
- }
-
- @keyframes icon-bottom-right {
- from { transform: translate(0, 0); }
- to { transform: translate(4px, 4px); }
- }
- </style>
- </custom-style>
+ }
+ </style>
</head>
<body>
- <!--
- Use the 'consent-description' attribute to annotate all the UI elements
- that are part of the text the user reads before consenting to the Sync
- data collection . Similarly, use 'consent-confirmation' on UI elements on
- which user clicks to indicate consent.
- -->
- <div class="container">
- <div class="top-title-bar" consent-description>
- $i18n{syncConfirmationTitle}
- </div>
- <div class="details" id="syncConfirmationDetails">
- <div id="picture-container">
- <div id="illustration">
- <div id="icons">
- <div id="icon-bookmarks" class="fade-top-left"></div>
- <div id="icon-extensions" class="fade-top-left"></div>
- <div id="icon-passwords" class="fade-bottom-left"></div>
- <div id="icon-history" class="fade-top-right"></div>
- <div id="icon-tabs" class="fade-middle-right"></div>
- <div id="icon-themes" class="fade-bottom-right"></div>
- <div id="icon-circle-open" class="fade-middle-left"></div>
- <div id="icon-circle-1" class="icon-circle fade-middle-left"></div>
- <div id="icon-circle-2" class="icon-circle fade-top-right"></div>
- <div id="icon-circle-3" class="icon-circle fade-middle-right"></div>
- <div id="icon-circle-4" class="icon-circle fade-top-right"></div>
- </div>
- <div class="picture">
- <img id="profile-picture">
- <div id="checkmark-circle">
- <svg id="checkmark-check" width="13" height="10" viewBox="0 0 13 10">
- <path id="checkmark-path" d="M1 5l3.5 3.5L12 1" stroke="#FFF"
- stroke-width="2" stroke-dasharray="16"
- stroke-dashoffset="16" fill="none"></path>
- </svg>
- </div>
- </div>
- </div>
- </div>
- <div class="message-container">
- <!--
- "Chrome sync" is the Google Cloud Based services used for sync. Thus
- this section uses the Chrome logo even for Chromium builds.
- -->
- <div id="chrome-logo" class="logo"></div>
- <div>
- <div class="title" consent-description>
- $i18n{syncConfirmationChromeSyncTitle}
- </div>
- <div class="body text" consent-description>
- $i18n{syncConfirmationChromeSyncBody}
- </div>
- </div>
- </div>
- <div class="message-container">
- <!--
- This section uses the Google logo even for Chromium builds as the
- user can personalize their Google services from this screen.
- -->
- <div id="googleg-logo" class="logo"></div>
- <div>
- <div class="title" consent-description>
- $i18n{syncConfirmationPersonalizeServicesTitle}
- </div>
- <div class="body text" consent-description>
- $i18n{syncConfirmationPersonalizeServicesBody}
- </div>
- </div>
- </div>
- <div class="message-container">
- <div class="body" consent-description consent-confirmation>
- $i18nRaw{syncConfirmationSyncSettingsLinkBody}
- </div>
- </div>
- </div>
- <div class="details" id="syncDisabledDetails">
- <div class="body text" consent-description>
- $i18n{syncDisabledConfirmationDetails}
- </div>
- </div>
- <div class="action-container">
- <paper-button class="action-button" id="confirmButton"
- consent-confirmation>
- $i18n{syncConfirmationConfirmLabel}
- </paper-button>
- <paper-button id="undoButton">
- $i18n{syncConfirmationUndoLabel}
- </paper-button>
- </div>
- </div>
+ <sync-confirmation-app></sync-confirmation-app>
</body>
- <link rel="import" href="chrome://resources/html/cr.html">
- <link rel="import" href="chrome://resources/html/load_time_data.html">
- <link rel="import" href="chrome://resources/html/util.html">
+ <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
+ <link rel="import" href="chrome://resources/html/cr.html"></script>
+ <link rel="import" href="chrome://resources/html/util.html"></script>
<script src="sync_confirmation.js"></script>
- <script src="chrome://sync-confirmation/strings.js"></script>
- <link rel="import" href="chrome://resources/html/dark_mode.html">
</html>
diff --git a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js
index 1611ba92f48..31aa325f3ef 100644
--- a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js
@@ -1,106 +1,31 @@
-/* Copyright 2015 The Chromium Authors. All rights reserved.
+/* 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. */
cr.define('sync.confirmation', function() {
'use strict';
- /**
- * @param {!Array<!HTMLElement>} path Path of the click event. Must contain
- * a consent confirmation element.
- * @return {string} The text of the consent confirmation element.
- * @private
- */
- function getConsentConfirmation(path) {
- let consentConfirmation;
- for (const element of path) {
- if (element.nodeType !== Node.DOCUMENT_FRAGMENT_NODE &&
- element.hasAttribute('consent-confirmation')) {
- return element.innerHTML.trim();
- }
- }
- assertNotReached('No consent confirmation element found.');
- return '';
- }
-
- /** @return {!Array<string>} Text of the consent description elements. */
- function getConsentDescription() {
- const consentDescription =
- Array.from(document.querySelectorAll('[consent-description]'))
- .filter(element => element.clientWidth * element.clientHeight > 0)
- .map(element => element.innerHTML.trim());
- assert(consentDescription);
- return consentDescription;
- }
-
- function onConfirm(e) {
- chrome.send(
- 'confirm', [getConsentDescription(), getConsentConfirmation(e.path)]);
- }
-
- function onUndo(e) {
- chrome.send('undo');
- }
-
- function onGoToSettings(e) {
- chrome.send(
- 'goToSettings',
- [getConsentDescription(), getConsentConfirmation(e.path)]);
- }
-
function initialize() {
- document.addEventListener('keydown', onKeyDown);
- $('confirmButton').addEventListener('click', onConfirm);
- $('undoButton').addEventListener('click', onUndo);
- if (loadTimeData.getBoolean('isSyncAllowed')) {
- $('settingsLink').addEventListener('click', onGoToSettings);
- $('profile-picture').addEventListener('load', onPictureLoaded);
- $('syncDisabledDetails').hidden = true;
- } else {
- $('syncConfirmationDetails').hidden = true;
- }
-
+ const syncConfirmationBrowserProxy =
+ sync.confirmation.SyncConfirmationBrowserProxyImpl.getInstance();
// Prefer using |document.body.offsetHeight| instead of
// |document.body.scrollHeight| as it returns the correct height of the
// even when the page zoom in Chrome is different than 100%.
- chrome.send('initializedWithSize', [document.body.offsetHeight]);
+ syncConfirmationBrowserProxy.initializedWithSize(
+ [document.body.offsetHeight]);
+ // The web dialog size has been initialized, so reset the body width to
+ // auto. This makes sure that the body only takes up the viewable width,
+ // e.g. when there is a scrollbar.
+ document.body.style.width = 'auto';
}
function clearFocus() {
document.activeElement.blur();
}
- function setUserImageURL(url) {
- if (loadTimeData.getBoolean('isSyncAllowed')) {
- $('profile-picture').src = url;
- }
- }
-
- function onPictureLoaded(e) {
- if (loadTimeData.getBoolean('isSyncAllowed')) {
- $('picture-container').classList.add('loaded');
- }
- }
-
- function onKeyDown(e) {
- // If the currently focused element isn't something that performs an action
- // on "enter" being pressed and the user hits "enter", perform the default
- // action of the dialog, which is "OK, Got It".
- if (e.key == 'Enter' &&
- !/^(A|PAPER-(BUTTON|CHECKBOX))$/.test(document.activeElement.tagName)) {
- $('confirmButton').click();
- e.preventDefault();
- }
- }
-
- // TODO(tangltom): clearFocus and setUserImageURL are called directly by the
- // C++ handler. C++ handlers should not be calling JS functions by name
- // anymore. They should be firing events with FireWebuiListener and have the
- // page itself decide whether to listen or not listen to the event.
return {
clearFocus: clearFocus,
initialize: initialize,
- setUserImageURL: setUserImageURL
};
});
diff --git a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.html b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.html
index badf36b444c..fffc18a7d60 100644
--- a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.html
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.html
@@ -1,10 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/load_time_data.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="signin_shared_css.html">
<link rel="import" href="sync_confirmation_browser_proxy.html">
@@ -13,13 +12,13 @@
<dom-module id="sync-confirmation-app">
<template>
- <style include="signin-dialog-shared paper-button-style">
+ <style include="signin-dialog-shared">
:host {
color: var(--cr-primary-text-color);
display: block;
}
- paper-button {
+ cr-button {
padding-inline-end: 16px;
padding-inline-start: 16px;
}
@@ -31,13 +30,13 @@
width: 100%;
}
- paper-button:not(.action-button) {
+ cr-button:not(.action-button) {
margin-inline-start: 8px;
}
<if expr="is_macosx or is_linux">
/* This works together with the button-flip in signin-dialog-shared. */
- paper-button:not(.action-button) {
+ cr-button:not(.action-button) {
margin-inline-end: 8px;
margin-inline-start: 0;
}
@@ -59,8 +58,11 @@
width: 100%;
}
- :host-context([dark]) #illustration {
- background-image: url(./images/sync_confirmation_illustration_dark.svg);
+ @media (prefers-color-scheme: dark) {
+ #illustration {
+ background-image:
+ url(./images/sync_confirmation_illustration_dark.svg);
+ }
}
#illustration-container > img {
@@ -98,11 +100,13 @@
color: var(--cr-secondary-text-color);
}
- :host-context(html:not([dark])) #grey-banner {
- background: var(--paper-grey-50);
- height: 128px;
- top: 0;
- width: 100%;
+ @media (prefers-color-scheme: light) {
+ #grey-banner {
+ background: var(--paper-grey-50);
+ height: 128px;
+ top: 0;
+ width: 100%;
+ }
}
#footer {
@@ -147,17 +151,17 @@
$i18n{syncConfirmationSettingsInfo}
</div>
<div class="action-container">
- <paper-button class="action-button" id="confirmButton"
+ <cr-button class="action-button" id="confirmButton"
on-click="onConfirm_" consent-confirmation>
$i18n{syncConfirmationConfirmLabel}
- </paper-button>
- <paper-button on-click="onUndo_">
+ </cr-button>
+ <cr-button on-click="onUndo_">
$i18n{syncConfirmationUndoLabel}
- </paper-button>
- <paper-button id="settingsButton" on-click="onGoToSettings_"
+ </cr-button>
+ <cr-button id="settingsButton" on-click="onGoToSettings_"
consent-confirmation>
$i18n{syncConfirmationSettingsLabel}
- </paper-button>
+ </cr-button>
</div>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.js b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.js
index 44c95eab914..57f29b847a5 100644
--- a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_app.js
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.js
@@ -63,7 +63,7 @@ Polymer({
/** @private */
onKeyDown_: function(e) {
- if (e.key == 'Enter' && !/^(A|PAPER-BUTTON)$/.test(e.path[0].tagName)) {
+ if (e.key == 'Enter' && !/^(A|CR-BUTTON)$/.test(e.path[0].tagName)) {
this.onConfirm_(e);
e.preventDefault();
}
diff --git a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.html b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.html
index 636a6b9e214..636a6b9e214 100644
--- a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.html
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.html
diff --git a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.js b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.js
index 2f8a6da22c5..c5cb104af72 100644
--- a/chromium/chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation_browser_proxy.js
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_browser_proxy.js
@@ -8,7 +8,6 @@
*/
cr.define('sync.confirmation', function() {
-
/** @interface */
class SyncConfirmationBrowserProxy {
/**
@@ -20,7 +19,8 @@ cr.define('sync.confirmation', function() {
*/
confirm(description, confirmation) {}
- /** Called when the user undoes the Sync confirmation.
+ /**
+ * Called when the user undoes the Sync confirmation.
*/
undo() {}
diff --git a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.html b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.html
new file mode 100644
index 00000000000..74e05238e9e
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.html
@@ -0,0 +1,73 @@
+<!doctype html>
+<html dir="$i18n{textdirection}" lang="$i18n{language}">
+ <head>
+ <meta charset="utf-8">
+ <link rel="stylesheet" href="chrome://resources/css/md_colors.css">
+ <style>
+ html {
+ background-color: var(--md-background-color);
+ }
+ </style>
+ </custom-style>
+ <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
+ <link rel="import" href="chrome://resources/html/polymer.html">
+ <link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
+ <link rel="import" href="signin_shared_css.html">
+ <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
+ <custom-style>
+ <style include="signin-dialog-shared">
+ .details {
+ padding: 0 24px;
+ }
+ #undoButton {
+<if expr="is_macosx or is_linux">
+ margin-inline-end: 8px;
+</if>
+<if expr="not is_macosx and not is_linux">
+ margin-inline-start: 8px;
+</if>
+ }
+
+ #syncDisabledDetails {
+ line-height: 20px;
+ margin-bottom: 8px;
+ margin-top: 16px;
+ padding: 0 24px;
+ }
+
+ </style>
+ </custom-style>
+ </head>
+ <body>
+ <!--
+ Use the 'consent-description' attribute to annotate all the UI elements
+ that are part of the text the user reads before consenting to the Sync
+ data collection . Similarly, use 'consent-confirmation' on UI elements on
+ which user clicks to indicate consent.
+ -->
+ <div class="container">
+ <div class="top-title-bar" consent-description>
+ $i18n{syncDisabledConfirmationTitle}
+ </div>
+ <div class="details" id="syncDisabledDetails">
+ <div class="body text" consent-description>
+ $i18n{syncDisabledConfirmationDetails}
+ </div>
+ </div>
+ <div class="action-container">
+ <cr-button class="action-button" id="confirmButton"
+ consent-confirmation>
+ $i18n{syncDisabledConfirmationConfirmLabel}
+ </cr-button>
+ <cr-button id="undoButton">
+ $i18n{syncDisabledConfirmationUndoLabel}
+ </cr-button>
+ </div>
+ </div>
+ </body>
+ <link rel="import" href="chrome://resources/html/cr.html">
+ <link rel="import" href="chrome://resources/html/load_time_data.html">
+ <link rel="import" href="chrome://resources/html/util.html">
+ <script src="sync_disabled_confirmation.js"></script>
+ <script src="chrome://sync-confirmation/strings.js"></script>
+</html>
diff --git a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.js b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.js
new file mode 100644
index 00000000000..12307c5704b
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation.js
@@ -0,0 +1,77 @@
+/* Copyright 2015 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file. */
+
+cr.define('sync.confirmation', function() {
+ 'use strict';
+
+ /**
+ * @param {!Array<!HTMLElement>} path Path of the click event. Must contain
+ * a consent confirmation element.
+ * @return {string} The text of the consent confirmation element.
+ * @private
+ */
+ function getConsentConfirmation(path) {
+ let consentConfirmation;
+ for (const element of path) {
+ if (element.nodeType !== Node.DOCUMENT_FRAGMENT_NODE &&
+ element.hasAttribute('consent-confirmation')) {
+ return element.innerHTML.trim();
+ }
+ }
+ assertNotReached('No consent confirmation element found.');
+ return '';
+ }
+
+ /** @return {!Array<string>} Text of the consent description elements. */
+ function getConsentDescription() {
+ const consentDescription =
+ Array.from(document.querySelectorAll('[consent-description]'))
+ .filter(element => element.clientWidth * element.clientHeight > 0)
+ .map(element => element.innerHTML.trim());
+ assert(consentDescription);
+ return consentDescription;
+ }
+
+ function onConfirm(e) {
+ chrome.send(
+ 'confirm', [getConsentDescription(), getConsentConfirmation(e.path)]);
+ }
+
+ function onUndo(e) {
+ chrome.send('undo');
+ }
+
+ function initialize() {
+ document.addEventListener('keydown', onKeyDown);
+ $('confirmButton').addEventListener('click', onConfirm);
+ $('undoButton').addEventListener('click', onUndo);
+ // Prefer using |document.body.offsetHeight| instead of
+ // |document.body.scrollHeight| as it returns the correct height of the
+ // even when the page zoom in Chrome is different than 100%.
+ chrome.send('initializedWithSize', [document.body.offsetHeight]);
+ }
+
+ function clearFocus() {
+ document.activeElement.blur();
+ }
+
+ function onKeyDown(e) {
+ // If the currently focused element isn't something that performs an action
+ // on "enter" being pressed and the user hits "enter", perform the default
+ // action of the dialog, which is "OK, Got It".
+ if (e.key == 'Enter' &&
+ !/^(A|PAPER-(BUTTON|CHECKBOX))$/.test(document.activeElement.tagName)) {
+ $('confirmButton').click();
+ e.preventDefault();
+ }
+ }
+
+ // TODO(tangltom): clearFocus is called directly by the C++ handler.
+ // C++ handlers should not be calling JS functions by name anymore. They
+ // should be firing events with FireWebuiListener and have the page itself
+ // decide whether to listen or not listen to the event.
+ return {clearFocus: clearFocus, initialize: initialize};
+});
+
+document.addEventListener('DOMContentLoaded', sync.confirmation.initialize);
diff --git a/chromium/chrome/browser/resources/snippets_internals/snippets_internals.js b/chromium/chrome/browser/resources/snippets_internals/snippets_internals.js
index a76d8b318c0..d3d057d16a6 100644
--- a/chromium/chrome/browser/resources/snippets_internals/snippets_internals.js
+++ b/chromium/chrome/browser/resources/snippets_internals/snippets_internals.js
@@ -261,7 +261,7 @@ document.addEventListener('DOMContentLoaded', function() {
snippetsInternals.mojom.PageHandlerFactory.getProxy();
// Give backend mojo a reference to frontend mojo.
- const client = new snippetsInternals.mojom.Page(page).createProxy();
+ const client = new snippetsInternals.mojom.Page(page).$.createProxy();
pageHandlerFactory.createPageHandler(client).then((response) => {
pageHandler = response.handler;
diff --git a/chromium/chrome/browser/resources/sync_file_system_internals/main.html b/chromium/chrome/browser/resources/sync_file_system_internals/main.html
index b0fe20625eb..f0c42da2847 100644
--- a/chromium/chrome/browser/resources/sync_file_system_internals/main.html
+++ b/chromium/chrome/browser/resources/sync_file_system_internals/main.html
@@ -4,7 +4,7 @@ Copyright 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
-<html dir="$i18n{textdirection}" lang="$i18n{language}">
+<html dir="ltr" lang="en">
<meta charset="utf-8">
<title>Sync File System Internals</title>
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
diff --git a/chromium/chrome/browser/resources/usb_internals/descriptor_panel.js b/chromium/chrome/browser/resources/usb_internals/descriptor_panel.js
index f894ea5e9df..62d2910203f 100644
--- a/chromium/chrome/browser/resources/usb_internals/descriptor_panel.js
+++ b/chromium/chrome/browser/resources/usb_internals/descriptor_panel.js
@@ -8,17 +8,24 @@
*/
cr.define('descriptor_panel', function() {
+ const INPUT_TYPE_DECIMAL_WITH_DROPDOWN = 0;
+ const INPUT_TYPE_HEX_BYTE = 1;
+
// Standard USB requests and descriptor types:
const GET_DESCRIPTOR_REQUEST = 0x06;
+ const CONTROL_TRANSFER_DIRECTION_HOST_TO_DEVICE = 0;
+ const CONTROL_TRANSFER_DIRECTION_DEVICE_TO_HOST = 1;
+
const DEVICE_DESCRIPTOR_TYPE = 0x01;
const CONFIGURATION_DESCRIPTOR_TYPE = 0x02;
const STRING_DESCRIPTOR_TYPE = 0x03;
const INTERFACE_DESCRIPTOR_TYPE = 0x04;
const ENDPOINT_DESCRIPTOR_TYPE = 0x05;
const BOS_DESCRIPTOR_TYPE = 0x0F;
+ const DEVICE_CAPABILITY_DESCRIPTOR_TYPE = 0x10;
- const DEVICE_CAPABILITY_DESCRIPTOR_TYPE_PLATFORM = 0x05;
+ const DEVICE_CAPABILITY_DESCRIPTOR_TYPE_PLATFORM_TYPE = 0x05;
const DEVICE_DESCRIPTOR_LENGTH = 18;
const CONFIGURATION_DESCRIPTOR_LENGTH = 9;
@@ -106,57 +113,23 @@ cr.define('descriptor_panel', function() {
/**
* @param {!device.mojom.UsbDeviceInterface} usbDeviceProxy
* @param {!HTMLElement} rootElement
- * @param {DescriptorPanel=} stringDescriptorPanel
*/
- constructor(
- usbDeviceProxy, rootElement, stringDescriptorPanel = undefined) {
- /** @private {!device.mojom.UsbDeviceInterface} */
+ constructor(usbDeviceProxy, rootElement) {
+ /** @type {!device.mojom.UsbDeviceInterface} */
this.usbDeviceProxy_ = usbDeviceProxy;
- /** @private {!HTMLElement} */
+ /** @type {!HTMLElement} */
this.rootElement_ = rootElement;
-
- this.clearView();
-
- if (stringDescriptorPanel) {
- /** @private {!DescriptorPanel} */
- this.stringDescriptorPanel_ = stringDescriptorPanel;
- }
}
/**
- * Adds a display area which contains a tree view and a byte view.
- * @param {string=} descriptorPanelTitle
- * @return {{rawDataTreeRoot:!cr.ui.Tree,rawDataByteElement:!HTMLElement}}
- * @private
+ * Adds the reference of the string descriptor panel of the device for
+ * string descriptor functionality.
+ * @param {!DescriptorPanel} stringDescriptorPanel
*/
- addNewDescriptorDisplayElement_(descriptorPanelTitle = undefined) {
- const descriptorPanelTemplate =
- document.querySelector('#descriptor-panel-template');
- const descriptorPanelClone =
- document.importNode(descriptorPanelTemplate.content, true);
-
- /** @private {!HTMLElement} */
- const rawDataTreeRoot =
- descriptorPanelClone.querySelector('#raw-data-tree-view');
- /** @private {!HTMLElement} */
- const rawDataByteElement =
- descriptorPanelClone.querySelector('#raw-data-byte-view');
-
- cr.ui.decorate(rawDataTreeRoot, cr.ui.Tree);
- rawDataTreeRoot.detail = {payload: {}, children: {}};
-
- if (descriptorPanelTitle) {
- const descriptorPanelTitleTemplate =
- document.querySelector('#descriptor-panel-title');
- const clone =
- document.importNode(descriptorPanelTitleTemplate.content, true)
- .querySelector('descriptorpaneltitle');
- clone.textContent = descriptorPanelTitle;
- this.rootElement_.appendChild(clone);
- }
- this.rootElement_.appendChild(descriptorPanelClone);
- return {rawDataTreeRoot, rawDataByteElement};
+ setStringDescriptorPanel(stringDescriptorPanel) {
+ /** @type {!DescriptorPanel} */
+ this.stringDescriptorPanel_ = stringDescriptorPanel;
}
/**
@@ -171,58 +144,6 @@ cr.define('descriptor_panel', function() {
}
/**
- * Renders a tree view to display the raw data in readable text.
- * @param {!cr.ui.Tree|!cr.ui.TreeItem} root
- * @param {!HTMLElement} rawDataByteElement
- * @param {!Array<Object>} fields
- * @param {!Uint8Array} rawData
- * @param {number} offset The start offset of the descriptor structure that
- * want to be rendered.
- * @param {...string} parentClassNames
- * @return {number} The end offset of descriptor structure that want to be
- * rendered.
- * @private
- */
- renderRawDataTree_(
- root, rawDataByteElement, fields, rawData, offset,
- ...parentClassNames) {
- const rawDataByteElements = rawDataByteElement.querySelectorAll('span');
-
- for (const field of fields) {
- const className = `field-offset-${offset}`;
- let item;
- try {
- item = customTreeItem(
- `${field.label}${field.formatter(rawData, offset)}`, className);
-
- for (let i = 0; i < field.size; i++) {
- rawDataByteElements[offset + i].classList.add(className);
- for (const parentClassName of parentClassNames) {
- rawDataByteElements[offset + i].classList.add(parentClassName);
- }
- }
- } catch (e) {
- this.showError_(`Field at offset ${offset} is invalid.`);
- break;
- }
-
- try {
- if (field.extraTreeItemFormatter) {
- field.extraTreeItemFormatter(rawData, offset, item, field.label);
- }
- } catch (e) {
- this.showError_(
- `Error at rendering field at index ${offset}: ${e.message}`);
- }
-
- root.add(item);
- offset += field.size;
- }
-
- return offset;
- }
-
- /**
* Adds a button for getting string descriptor to the string descriptor
* index item, and adds an autocomplete value to the index input area in
* the string descriptor panel.
@@ -236,7 +157,7 @@ cr.define('descriptor_panel', function() {
const index = rawData[offset];
if (index > 0) {
if (!this.stringDescriptorPanel_.stringDescriptorIndexes.has(index)) {
- const optionElement = cr.doc.createElement('option');
+ const optionElement = document.createElement('option');
optionElement.label = index;
optionElement.value = index;
this.stringDescriptorPanel_.indexesListElement.appendChild(
@@ -248,46 +169,49 @@ cr.define('descriptor_panel', function() {
const buttonTemplate = document.querySelector('#raw-data-tree-button');
const button = document.importNode(buttonTemplate.content, true)
.querySelector('button');
- item.querySelector('.tree-row').appendChild(button);
+ item.labelElement.appendChild(button);
button.addEventListener('click', (event) => {
event.stopPropagation();
// Clear the previous string descriptors.
item.querySelector('.tree-children').textContent = '';
this.stringDescriptorPanel_.clearView();
- this.stringDescriptorPanel_.renderStringDescriptorForAllLanguages(
+ this.stringDescriptorPanel_.getStringDescriptorForAllLanguages_(
index, item);
});
} else if (index < 0) {
// Delete the ': ' in fieldLabel.
const fieldName = fieldLabel.slice(0, -2);
- this.showError_(`Invalid String Descriptor occurs in field ${
- fieldName} of this descriptor.`);
+ showError(
+ `Invalid String Descriptor occurs in field ${
+ fieldName} of this descriptor.`,
+ this.rootElement_);
}
}
/**
- * Renders a URL descriptor item for the URL Descriptor Index and
- * adds it to the URL descriptor index item.
+ * Adds a button for getting URL descriptor.
* @param {!Uint8Array} rawData
- * @param {number} offset The offset of the URL descriptor index field.
+ * @param {number} offset The offset of the URL descriptor index.
* @param {!cr.ui.TreeItem} item
* @param {string} fieldLabel Not used in this function, but used to match
* other extraTreeItemFormatter.
* @private
*/
- async renderLandingPageItem_(rawData, offset, item, fieldLabel) {
- // The second to last byte is the vendor code used to query URL
- // descriptor. Last byte is index of url descriptor. These are defined by
- // the WebUSB specification: http://wicg.github.io/webusb/
- const vendorCode = rawData[offset + WEB_USB_VENDOR_CODE_OFFSET];
- const urlIndex = rawData[offset + WEB_USB_URL_DESCRIPTOR_INDEX_OFFSET];
- const url = await this.getUrlDescriptor_(vendorCode, urlIndex);
-
- const landingPageItem = customTreeItem(url);
- item.add(landingPageItem);
-
- landingPageItem.querySelector('.tree-label')
- .addEventListener('click', () => window.open(url, '_blank'));
+ renderUrlDescriptorIndexItem_(rawData, offset, item, fieldLabel) {
+ const index = rawData[offset];
+ if (index > 0) {
+ const buttonTemplate = document.querySelector('#raw-data-tree-button');
+ const button = document.importNode(buttonTemplate.content, true)
+ .querySelector('button');
+ item.labelElement.appendChild(button);
+ button.addEventListener('click', (event) => {
+ event.stopPropagation();
+ // Clear the previous URL descriptors.
+ item.querySelector('.tree-children').textContent = '';
+ this.getUrlDescriptor_(
+ rawData, offset - WEB_USB_URL_DESCRIPTOR_INDEX_OFFSET, item);
+ });
+ }
}
/**
@@ -317,7 +241,7 @@ cr.define('descriptor_panel', function() {
const buttonTemplate = document.querySelector('#raw-data-tree-button');
const button = document.importNode(buttonTemplate.content, true)
.querySelector('button');
- item.querySelector('.tree-row').appendChild(button);
+ item.labelElement.appendChild(button);
button.addEventListener('click', async (event) => {
event.stopPropagation();
// Clear all the descriptor display elements except the first one, which
@@ -356,7 +280,7 @@ cr.define('descriptor_panel', function() {
const buttonTemplate = document.querySelector('#raw-data-tree-button');
const button = document.importNode(buttonTemplate.content, true)
.querySelector('button');
- item.querySelector('.tree-row').appendChild(button);
+ item.labelElement.appendChild(button);
button.addEventListener('click', async (event) => {
event.stopPropagation();
await this.sendMsOs20DescriptorSetAltEnumCommand_(
@@ -408,68 +332,124 @@ cr.define('descriptor_panel', function() {
}
/**
- * Checks if the status of a descriptor read indicates success.
- * @param {number} status
- * @param {string} defaultMessage
+ * Renders a view to display standard descriptor hex data in both tree view
+ * and raw form view.
+ * @param {!Uint8Array} data
+ * @param {number=} languageCode
+ * @param {cr.ui.TreeItem=} treeItem
* @private
*/
- checkDescriptorGetSuccess_(status, defaultMessage) {
- let failReason = '';
- switch (status) {
- case device.mojom.UsbTransferStatus.COMPLETED:
- return;
- case device.mojom.UsbTransferStatus.SHORT_PACKET:
- this.showError_('Descriptor is too short.');
- return;
- case device.mojom.UsbTransferStatus.BABBLE:
- this.showError_('Descriptor is too long.');
- return;
- case device.mojom.UsbTransferStatus.TRANSFER_ERROR:
- failReason = 'Transfer Error';
- break;
- case device.mojom.UsbTransferStatus.TIMEOUT:
- failReason = 'Timeout';
- break;
- case device.mojom.UsbTransferStatus.CANCELLED:
- failReason = 'Transfer was cancelled';
- break;
- case device.mojom.UsbTransferStatus.STALLED:
- failReason = 'Transfer Error';
- break;
- case device.mojom.UsbTransferStatus.DISCONNECT:
- failReason = 'Transfer stalled';
- break;
- case device.mojom.UsbTransferStatus.PERMISSION_DENIED:
- failReason = 'Permission denied';
- break;
- }
- // Throws an error to stop rendering descriptor.
- throw new Error(`${defaultMessage} (Reason: ${failReason})`);
- }
+ async renderStandardDescriptor_(
+ data, languageCode = 0, treeItem = undefined) {
+ const displayElement = addNewDescriptorDisplayElement(this.rootElement_);
+ /** @type {!cr.ui.Tree} */
+ const rawDataTreeRoot = displayElement.rawDataTreeRoot;
+ /** @type {!HTMLElement} */
+ const rawDataByteElement = displayElement.rawDataByteElement;
- /**
- * Shows an error message if error occurs in getting or rendering
- * descriptors.
- * @param {string} message
- * @private
- */
- showError_(message) {
- const errorTemplate = document.querySelector('#error');
+ renderRawDataBytes(rawDataByteElement, data);
- const clone = document.importNode(errorTemplate.content, true);
+ let offset = 0;
+ let indexInterface = 0;
+ let indexEndpoint = 0;
+ let indexUnknown = 0;
+ let indexDevCapability = 0;
- const errorText = clone.querySelector('error');
- errorText.textContent = message;
+ let expectNumInterfaces = 0;
+ let expectNumEndpoints = 0;
+ let expectNumDevCapabilities = 0;
+
+ let lastInterfaceItem;
+ // Continue parsing while there are still unparsed standard descriptor.
+ // Stop if accessing the descriptor type would cause us to read past the
+ // end of the buffer.
+ while (offset + STANDARD_DESCRIPTOR_TYPE_OFFSET < data.length) {
+ const length = data[offset + STANDARD_DESCRIPTOR_LENGTH_OFFSET];
+ const descriptorType = data[offset + STANDARD_DESCRIPTOR_TYPE_OFFSET];
+ switch (descriptorType) {
+ case DEVICE_DESCRIPTOR_TYPE:
+ this.renderDeviceDescriptor_(
+ rawDataTreeRoot, rawDataByteElement, data, offset);
+ break;
+ case CONFIGURATION_DESCRIPTOR_TYPE:
+ if (CONFIGURATION_DESCRIPTOR_NUM_INTERFACES_OFFSET < length) {
+ expectNumInterfaces =
+ data[offset + CONFIGURATION_DESCRIPTOR_NUM_INTERFACES_OFFSET];
+ }
+ this.renderConfigurationDescriptor_(
+ rawDataTreeRoot, rawDataByteElement, data, offset);
+ break;
+ case STRING_DESCRIPTOR_TYPE:
+ this.renderStringDescriptorForLanguageCode_(
+ rawDataTreeRoot, rawDataByteElement, data, offset, languageCode,
+ treeItem);
+ break;
+ case INTERFACE_DESCRIPTOR_TYPE:
+ if (INTERFACE_DESCRIPTOR_NUM_ENDPOINTS_OFFSET < length) {
+ expectNumEndpoints +=
+ data[offset + INTERFACE_DESCRIPTOR_NUM_ENDPOINTS_OFFSET];
+ }
+ lastInterfaceItem = this.renderInterfaceDescriptor_(
+ rawDataTreeRoot, rawDataByteElement, data, offset,
+ indexInterface);
+ indexInterface++;
+ break;
+ case ENDPOINT_DESCRIPTOR_TYPE:
+ const treeRoot = lastInterfaceItem || rawDataTreeRoot;
+ this.renderEndpointDescriptor_(
+ treeRoot, rawDataByteElement, data, offset, indexEndpoint);
+ indexEndpoint++;
+ break;
+ case BOS_DESCRIPTOR_TYPE:
+ this.renderBosDescriptor_(
+ rawDataTreeRoot, rawDataByteElement, data, offset);
+ expectNumDevCapabilities =
+ data[BOS_DESCRIPTOR_NUM_DEVICE_CAPABILITIES_OFFSET];
+ break;
+ case DEVICE_CAPABILITY_DESCRIPTOR_TYPE:
+ await this.renderDeviceCapabilityDescriptor_(
+ rawDataTreeRoot, rawDataByteElement, data, offset,
+ indexDevCapability);
+ indexDevCapability++;
+ break;
+ default:
+ this.renderUnknownDescriptor_(
+ rawDataTreeRoot, rawDataByteElement, data, offset,
+ indexUnknown);
+ indexUnknown++;
+ break;
+ }
+ offset += length;
+ }
+
+ if (expectNumInterfaces != indexInterface) {
+ showError(
+ `Expected to find ${expectNumInterfaces} interface descriptors ` +
+ `but only encountered ${indexInterface}.`,
+ this.rootElement_);
+ }
+
+ if (expectNumEndpoints != indexEndpoint) {
+ showError(
+ `Expected to find ${expectNumEndpoints} interface descriptors ` +
+ `but only encountered ${indexEndpoint}.`,
+ this.rootElement_);
+ }
- this.rootElement_.prepend(clone);
+ if (expectNumDevCapabilities != indexDevCapability) {
+ showError(
+ `Expected to find ${expectNumDevCapabilities} ` +
+ `device capability descriptors but only encountered ${
+ indexDevCapability}.`,
+ this.rootElement_);
+ }
+ addMappingAction(rawDataTreeRoot, rawDataByteElement);
}
/**
- * Gets device descriptor of current device.
- * @return {!Uint8Array}
- * @private
+ * Gets device descriptor of current device, and display it.
*/
- async getDeviceDescriptor_() {
+ async getDeviceDescriptor() {
/** @type {!device.mojom.UsbControlTransferParams} */
const usbControlTransferParams = {};
usbControlTransferParams.type =
@@ -480,36 +460,36 @@ cr.define('descriptor_panel', function() {
usbControlTransferParams.value = (DEVICE_DESCRIPTOR_TYPE << 8);
usbControlTransferParams.index = 0;
- const response = await this.usbDeviceProxy_.controlTransferIn(
- usbControlTransferParams, DEVICE_DESCRIPTOR_LENGTH,
- CONTROL_TRANSFER_TIMEOUT_MS);
-
- this.checkDescriptorGetSuccess_(
- response.status, 'Failed to read the device descriptor.');
-
- return new Uint8Array(response.data);
- }
-
- /**
- * Renders a view to display device descriptor hex data in both tree view
- * and raw form.
- */
- async renderDeviceDescriptor() {
- let rawData;
try {
await this.usbDeviceProxy_.open();
- rawData = await this.getDeviceDescriptor_();
+ const response = await this.usbDeviceProxy_.controlTransferIn(
+ usbControlTransferParams, DEVICE_DESCRIPTOR_LENGTH,
+ CONTROL_TRANSFER_TIMEOUT_MS);
+ checkTransferSuccess(
+ response.status, 'Failed to read the device descriptor.',
+ this.rootElement_);
+ this.renderStandardDescriptor_(new Uint8Array(response.data));
} catch (e) {
- this.showError_(e.message);
- // Stop rendering if failed to read the device descriptor.
- return;
+ showError(e.message, this.rootElement_);
} finally {
await this.usbDeviceProxy_.close();
}
+ }
+ /**
+ * Renders a view to display device descriptor hex data in both tree view
+ * and raw form.
+ * @param {!cr.ui.Tree} rawDataTreeRoot
+ * @param {!HTMLElement} rawDataByteElement
+ * @param {!Uint8Array} rawData
+ * @param {number} offset The start offset of the device descriptor.
+ * @private
+ */
+ async renderDeviceDescriptor_(
+ rawDataTreeRoot, rawDataByteElement, rawData, offset) {
const fields = [
{
- label: 'Length (should be 18): ',
+ label: `Length (should be ${DEVICE_DESCRIPTOR_LENGTH}): `,
size: 1,
formatter: formatByte,
},
@@ -583,18 +563,9 @@ cr.define('descriptor_panel', function() {
},
];
- const displayElement = this.addNewDescriptorDisplayElement_();
- /** @type {!cr.ui.Tree} */
- const rawDataTreeRoot = displayElement.rawDataTreeRoot;
- /** @type {!HTMLElement} */
- const rawDataByteElement = displayElement.rawDataByteElement;
-
- renderRawDataBytes(rawDataByteElement, rawData);
-
- this.renderRawDataTree_(
- rawDataTreeRoot, rawDataByteElement, fields, rawData, 0);
-
- addMappingAction(rawDataTreeRoot, rawDataByteElement);
+ renderRawDataTree(
+ rawDataTreeRoot, rawDataByteElement, fields, rawData, offset,
+ this.rootElement_);
// window.deviceDescriptorCompleteFn() provides a hook for the test suite
// to perform test actions after the device descriptor is rendered.
@@ -602,11 +573,9 @@ cr.define('descriptor_panel', function() {
}
/**
- * Gets configuration descriptor of current device.
- * @return {!Uint8Array}
- * @private
+ * Gets configuration descriptor of current device, and display it.
*/
- async getConfigurationDescriptor_() {
+ async getConfigurationDescriptor() {
/** @type {!device.mojom.UsbControlTransferParams} */
const usbControlTransferParams = {};
usbControlTransferParams.type =
@@ -617,49 +586,48 @@ cr.define('descriptor_panel', function() {
usbControlTransferParams.value = (CONFIGURATION_DESCRIPTOR_TYPE << 8);
usbControlTransferParams.index = 0;
- let response = await this.usbDeviceProxy_.controlTransferIn(
- usbControlTransferParams, CONFIGURATION_DESCRIPTOR_LENGTH,
- CONTROL_TRANSFER_TIMEOUT_MS);
-
- this.checkDescriptorGetSuccess_(
- response.status,
- 'Failed to read the device configuration descriptor to determine ' +
- 'the total descriptor length.');
-
- const data = new DataView(new Uint8Array(response.data).buffer);
- const length =
- data.getUint16(CONFIGURATION_DESCRIPTOR_TOTAL_LENGTH_OFFSET, true);
- // Re-gets the data use the full length.
- response = await this.usbDeviceProxy_.controlTransferIn(
- usbControlTransferParams, length, CONTROL_TRANSFER_TIMEOUT_MS);
-
- this.checkDescriptorGetSuccess_(
- response.status,
- 'Failed to read the complete configuration descriptor.');
-
- return new Uint8Array(response.data);
- }
-
- /**
- * Renders a view to display configuration descriptor hex data in both tree
- * view and raw form.
- */
- async renderConfigurationDescriptor() {
- let rawData;
try {
await this.usbDeviceProxy_.open();
- rawData = await this.getConfigurationDescriptor_();
+ let response = await this.usbDeviceProxy_.controlTransferIn(
+ usbControlTransferParams, CONFIGURATION_DESCRIPTOR_LENGTH,
+ CONTROL_TRANSFER_TIMEOUT_MS);
+ checkTransferSuccess(
+ response.status,
+ 'Failed to read the device configuration descriptor to determine ' +
+ 'the total descriptor length.',
+ this.rootElement_);
+ const dataView = new DataView(new Uint8Array(response.data).buffer);
+ const length = dataView.getUint16(
+ CONFIGURATION_DESCRIPTOR_TOTAL_LENGTH_OFFSET, true);
+ // Re-gets the data using the full length.
+ response = await this.usbDeviceProxy_.controlTransferIn(
+ usbControlTransferParams, length, CONTROL_TRANSFER_TIMEOUT_MS);
+ checkTransferSuccess(
+ response.status,
+ 'Failed to read the complete configuration descriptor.',
+ this.rootElement_);
+ this.renderStandardDescriptor_(new Uint8Array(response.data));
} catch (e) {
- this.showError_(e.message);
- // Stop rendering if failed to read the configuration descriptor.
- return;
+ showError(e.message, this.rootElement_);
} finally {
await this.usbDeviceProxy_.close();
}
+ }
+ /**
+ * Renders a view to display configuration descriptor hex data in both tree
+ * view and raw form.
+ * @param {!cr.ui.Tree} rawDataTreeRoot
+ * @param {!HTMLElement} rawDataByteElement
+ * @param {!Uint8Array} rawData
+ * @param {number} offset The start offset of the configuration descriptor.
+ * @private
+ */
+ async renderConfigurationDescriptor_(
+ rawDataTreeRoot, rawDataByteElement, rawData, offset) {
const fields = [
{
- label: 'Length (should be 9): ',
+ label: `Length (should be ${CONFIGURATION_DESCRIPTOR_LENGTH}): `,
size: 1,
formatter: formatByte,
},
@@ -701,69 +669,9 @@ cr.define('descriptor_panel', function() {
},
];
- const displayElement = this.addNewDescriptorDisplayElement_();
- /** @type {!cr.ui.Tree} */
- const rawDataTreeRoot = displayElement.rawDataTreeRoot;
- /** @type {!HTMLElement} */
- const rawDataByteElement = displayElement.rawDataByteElement;
-
- renderRawDataBytes(rawDataByteElement, rawData);
-
- const expectNumInterfaces =
- rawData[CONFIGURATION_DESCRIPTOR_NUM_INTERFACES_OFFSET];
-
- let offset = this.renderRawDataTree_(
- rawDataTreeRoot, rawDataByteElement, fields, rawData, 0);
-
- if (offset !== CONFIGURATION_DESCRIPTOR_LENGTH) {
- this.showError_(
- 'An error occurred while rendering configuration descriptor.');
- }
-
- let indexInterface = 0;
- let indexEndpoint = 0;
- let indexUnknown = 0;
- let expectNumEndpoints = 0;
-
- // Continue parsing while there are still unparsed interface, endpoint,
- // or endpoint companion descriptors. Stop if accessing the descriptor
- // type would cause us to read past the end of the buffer.
- while ((offset + STANDARD_DESCRIPTOR_TYPE_OFFSET) < rawData.length) {
- switch (rawData[offset + STANDARD_DESCRIPTOR_TYPE_OFFSET]) {
- case INTERFACE_DESCRIPTOR_TYPE:
- [offset, expectNumEndpoints] = this.renderInterfaceDescriptor_(
- rawDataTreeRoot, rawDataByteElement, rawData, offset,
- indexInterface, expectNumEndpoints);
- indexInterface++;
- break;
- case ENDPOINT_DESCRIPTOR_TYPE:
- offset = this.renderEndpointDescriptor_(
- rawDataTreeRoot, rawDataByteElement, rawData, offset,
- indexEndpoint);
- indexEndpoint++;
- break;
- default:
- offset = this.renderUnknownDescriptor_(
- rawDataTreeRoot, rawDataByteElement, rawData, offset,
- indexUnknown);
- indexUnknown++;
- break;
- }
- }
-
- if (expectNumInterfaces !== indexInterface) {
- this.showError_(`Expected to find ${
- expectNumInterfaces} interface descriptors but only encountered ${
- indexInterface}.`);
- }
-
- if (expectNumEndpoints !== indexEndpoint) {
- this.showError_(`Expected to find ${
- expectNumEndpoints} interface descriptors but only encountered ${
- indexEndpoint}.`);
- }
-
- addMappingAction(rawDataTreeRoot, rawDataByteElement);
+ renderRawDataTree(
+ rawDataTreeRoot, rawDataByteElement, fields, rawData, offset,
+ this.rootElement_);
}
/**
@@ -772,21 +680,14 @@ cr.define('descriptor_panel', function() {
* @param {!cr.ui.Tree} rawDataTreeRoot
* @param {!HTMLElement} rawDataByteElement
* @param {!Uint8Array} rawData
- * @param {number} originalOffset The start offset of the interface
+ * @param {number} offset The start offset of the interface
* descriptor.
* @param {number} indexInterface
- * @param {number} expectNumEndpoints
* @return {!Array<number>}
* @private
*/
renderInterfaceDescriptor_(
- rawDataTreeRoot, rawDataByteElement, rawData, originalOffset,
- indexInterface, expectNumEndpoints) {
- if (originalOffset + INTERFACE_DESCRIPTOR_LENGTH > rawData.length) {
- this.showError_(`Failed to read the interface descriptor at index ${
- indexInterface}.`);
- }
-
+ rawDataTreeRoot, rawDataByteElement, rawData, offset, indexInterface) {
const parentClassName = `descriptor-interface-${indexInterface}`;
const interfaceItem =
customTreeItem(`Interface ${indexInterface}`, parentClassName);
@@ -794,7 +695,7 @@ cr.define('descriptor_panel', function() {
const fields = [
{
- label: 'Length (should be 7): ',
+ label: `Length (should be ${INTERFACE_DESCRIPTOR_LENGTH}): `,
size: 1,
formatter: formatByte,
},
@@ -841,20 +742,11 @@ cr.define('descriptor_panel', function() {
},
];
- expectNumEndpoints +=
- rawData[originalOffset + INTERFACE_DESCRIPTOR_NUM_ENDPOINTS_OFFSET];
-
- const offset = this.renderRawDataTree_(
- interfaceItem, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ renderRawDataTree(
+ interfaceItem, rawDataByteElement, fields, rawData, offset,
+ this.rootElement_, parentClassName);
- if (offset !== originalOffset + INTERFACE_DESCRIPTOR_LENGTH) {
- this.showError_(
- `An error occurred while rendering interface descriptor at index ${
- indexInterface}.`);
- }
-
- return [offset, expectNumEndpoints];
+ return interfaceItem;
}
/**
@@ -863,20 +755,14 @@ cr.define('descriptor_panel', function() {
* @param {!cr.ui.Tree} rawDataTreeRoot
* @param {!HTMLElement} rawDataByteElement
* @param {!Uint8Array} rawData
- * @param {number} originalOffset The start offset of the endpoint
+ * @param {number} offset The start offset of the endpoint
* descriptor.
* @param {number} indexEndpoint
* @return {number}
* @private
*/
renderEndpointDescriptor_(
- rawDataTreeRoot, rawDataByteElement, rawData, originalOffset,
- indexEndpoint) {
- if (originalOffset + ENDPOINT_DESCRIPTOR_LENGTH > rawData.length) {
- this.showError_(`Failed to read the endpoint descriptor at index ${
- indexEndpoint}.`);
- }
-
+ rawDataTreeRoot, rawDataByteElement, rawData, offset, indexEndpoint) {
const parentClassName = `descriptor-endpoint-${indexEndpoint}`;
const endpointItem =
customTreeItem(`Endpoint ${indexEndpoint}`, parentClassName);
@@ -884,7 +770,7 @@ cr.define('descriptor_panel', function() {
const fields = [
{
- label: 'Length (should be 7): ',
+ label: `Length (should be ${ENDPOINT_DESCRIPTOR_LENGTH}): `,
size: 1,
formatter: formatByte,
},
@@ -915,17 +801,9 @@ cr.define('descriptor_panel', function() {
},
];
- const offset = this.renderRawDataTree_(
- endpointItem, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
-
- if (offset !== originalOffset + ENDPOINT_DESCRIPTOR_LENGTH) {
- this.showError_(
- `An error occurred while rendering endpoint descriptor at index ${
- indexEndpoint}.`);
- }
-
- return offset;
+ renderRawDataTree(
+ endpointItem, rawDataByteElement, fields, rawData, offset,
+ this.rootElement_, parentClassName);
}
/**
@@ -944,13 +822,6 @@ cr.define('descriptor_panel', function() {
indexUnknown) {
const length =
rawData[originalOffset + STANDARD_DESCRIPTOR_LENGTH_OFFSET];
-
- if (originalOffset + length > rawData.length) {
- this.showError_(
- `Failed to read the unknown descriptor at index ${indexUnknown}.`);
- return;
- }
-
const parentClassName = `descriptor-unknown-${indexUnknown}`;
const unknownItem =
customTreeItem(`Unknown Descriptor ${indexUnknown}`, parentClassName);
@@ -969,9 +840,9 @@ cr.define('descriptor_panel', function() {
},
];
- let offset = this.renderRawDataTree_(
+ let offset = renderRawDataTree(
unknownItem, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ this.rootElement_, parentClassName);
const rawDataByteElements = rawDataByteElement.querySelectorAll('span');
@@ -979,8 +850,6 @@ cr.define('descriptor_panel', function() {
rawDataByteElements[offset].classList.add(`field-offset-${offset}`);
rawDataByteElements[offset].classList.add(parentClassName);
}
-
- return offset;
}
/**
@@ -1008,12 +877,13 @@ cr.define('descriptor_panel', function() {
usbControlTransferParams, MAX_STRING_DESCRIPTOR_LENGTH,
CONTROL_TRANSFER_TIMEOUT_MS);
- this.checkDescriptorGetSuccess_(
+ checkTransferSuccess(
response.status,
'Failed to read the device string descriptor to determine ' +
- 'all supported languages.');
+ 'all supported languages.',
+ this.rootElement_);
} catch (e) {
- this.showError_(e.message);
+ showError(e.message, this.rootElement_);
// Stop rendering autocomplete datalist if failed to read the string
// descriptor.
return new Uint8Array();
@@ -1024,7 +894,7 @@ cr.define('descriptor_panel', function() {
const responseData = new Uint8Array(response.data);
this.languageCodesListElement_.innerText = '';
- const optionAllElement = cr.doc.createElement('option');
+ const optionAllElement = document.createElement('option');
optionAllElement.value = 'All';
this.languageCodesListElement_.appendChild(optionAllElement);
@@ -1033,7 +903,7 @@ cr.define('descriptor_panel', function() {
for (let i = 2; i < responseData.length; i += 2) {
const languageCode = parseShort(responseData, i);
- const optionElement = cr.doc.createElement('option');
+ const optionElement = document.createElement('option');
optionElement.label = parseLanguageCode(languageCode);
optionElement.value = `0x${toHex(languageCode, 4)}`;
@@ -1041,19 +911,20 @@ cr.define('descriptor_panel', function() {
languageCodesList.push(languageCode);
}
-
return languageCodesList;
}
/**
* Gets the string descriptor for the current device with the given index
- * and language code.
+ * and language code, and display it.
* @param {number} index
* @param {number} languageCode
+ * @param {!cr.ui.TreeItem=} treeItem
* @return {{languageCode:string,rawData:!Uint8Array}}
* @private
*/
- async getStringDescriptorForLanguageCode_(index, languageCode) {
+ async getStringDescriptorForLanguageCode_(
+ index, languageCode, treeItem = undefined) {
/** @type {!device.mojom.UsbControlTransferParams} */
const usbControlTransferParams = {};
usbControlTransferParams.type =
@@ -1061,60 +932,47 @@ cr.define('descriptor_panel', function() {
usbControlTransferParams.recipient =
device.mojom.UsbControlTransferRecipient.DEVICE;
usbControlTransferParams.request = GET_DESCRIPTOR_REQUEST;
-
usbControlTransferParams.index = languageCode;
-
usbControlTransferParams.value = (STRING_DESCRIPTOR_TYPE << 8) | index;
- const response = await this.usbDeviceProxy_.controlTransferIn(
- usbControlTransferParams, MAX_STRING_DESCRIPTOR_LENGTH,
- CONTROL_TRANSFER_TIMEOUT_MS);
-
- const languageCodeStr = parseLanguageCode(languageCode);
- this.checkDescriptorGetSuccess_(
- response.status,
- `Failed to read the device string descriptor of index: ${
- index}, language: ${languageCodeStr}.`);
+ try {
+ await this.usbDeviceProxy_.open();
+ const response = await this.usbDeviceProxy_.controlTransferIn(
+ usbControlTransferParams, MAX_STRING_DESCRIPTOR_LENGTH,
+ CONTROL_TRANSFER_TIMEOUT_MS);
+ checkTransferSuccess(
+ response.status,
+ `Failed to read the device string descriptor of index: ${
+ index}, language: ${parseLanguageCode(languageCode)}.`,
+ this.rootElement_);
- const rawData = new Uint8Array(response.data);
- return {languageCodeStr, rawData};
+ this.indexInput_.value = index;
+ this.renderStandardDescriptor_(
+ new Uint8Array(response.data), languageCode, treeItem);
+ } catch (e) {
+ showError(e.message, this.rootElement_);
+ } finally {
+ await this.usbDeviceProxy_.close();
+ }
}
/**
* Renders string descriptor of current device with given index and language
* code.
- * @param {number} index
- * @param {number} languageCode
+ * @param {!cr.ui.Tree} rawDataTreeRoot
+ * @param {!HTMLElement} rawDataByteElement
+ * @param {!Uint8Array} rawData
+ * @param {number} offset The start offset of the string descriptor.
+ * @param {number=} languageCode
* @param {cr.ui.TreeItem=} treeItem
+ * @private
*/
- async renderStringDescriptorForLanguageCode(
- index, languageCode, treeItem = undefined) {
+ renderStringDescriptorForLanguageCode_(
+ rawDataTreeRoot, rawDataByteElement, rawData, offset, languageCode = 0,
+ treeItem = undefined) {
this.rootElement_.hidden = false;
- this.indexInput_.value = index;
-
- let rawDataMap;
- try {
- await this.usbDeviceProxy_.open();
- rawDataMap =
- await this.getStringDescriptorForLanguageCode_(index, languageCode);
- } catch (e) {
- this.showError_(e.message);
- // Stop rendering if failed to read the string descriptor.
- return;
- } finally {
- await this.usbDeviceProxy_.close();
- }
-
- const languageStr = rawDataMap.languageCodeStr;
- const rawData = rawDataMap.rawData;
-
- const length = rawData[STANDARD_DESCRIPTOR_LENGTH_OFFSET];
- if (length > rawData.length) {
- this.showError_(`Failed to read the string descriptor at index ${
- index} in ${languageStr}.`);
- return;
- }
+ const languageStr = parseLanguageCode(languageCode);
const fields = [
{
@@ -1139,16 +997,9 @@ cr.define('descriptor_panel', function() {
fields.push(field);
}
- const displayElement = this.addNewDescriptorDisplayElement_();
- /** @type {!cr.ui.Tree} */
- const rawDataTreeRoot = displayElement.rawDataTreeRoot;
- /** @type {!HTMLElement} */
- const rawDataByteElement = displayElement.rawDataByteElement;
-
// The first two elements of rawData are length and descriptor type.
const stringDescriptor = decodeUtf16Array(rawData.slice(2), true);
- const parentClassName =
- `descriptor-string-${index}-language-code-${languageStr}`;
+ const parentClassName = `descriptor-string-language-${languageStr}`;
const stringDescriptorItem = customTreeItem(
`${languageStr}: ${stringDescriptor}`, parentClassName);
rawDataTreeRoot.add(stringDescriptorItem);
@@ -1157,13 +1008,9 @@ cr.define('descriptor_panel', function() {
treeItem.expanded = true;
}
- renderRawDataBytes(rawDataByteElement, rawData);
-
- this.renderRawDataTree_(
- stringDescriptorItem, rawDataByteElement, fields, rawData, 0,
- parentClassName);
-
- addMappingAction(rawDataTreeRoot, rawDataByteElement);
+ renderRawDataTree(
+ stringDescriptorItem, rawDataByteElement, fields, rawData, offset,
+ this.rootElement_, parentClassName);
}
/**
@@ -1171,8 +1018,9 @@ cr.define('descriptor_panel', function() {
* given index.
* @param {number} index
* @param {cr.ui.TreeItem=} treeItem
+ * @private
*/
- async renderStringDescriptorForAllLanguages(index, treeItem = undefined) {
+ async getStringDescriptorForAllLanguages_(index, treeItem = undefined) {
this.rootElement_.hidden = false;
this.indexInput_.value = index;
@@ -1181,7 +1029,7 @@ cr.define('descriptor_panel', function() {
const languageCodesList = await this.getAllLanguageCodes();
for (const languageCode of languageCodesList) {
- await this.renderStringDescriptorForLanguageCode(
+ await this.getStringDescriptorForLanguageCode_(
index, languageCode, treeItem);
}
}
@@ -1205,16 +1053,18 @@ cr.define('descriptor_panel', function() {
const languageCodeInput =
this.rootElement_.querySelector('#language-code-input');
- button.addEventListener('click', () => {
+ button.addEventListener('click', async () => {
this.clearView();
const index = Number.parseInt(this.indexInput_.value);
- if (this.checkIndexValueValid_(index)) {
+ if (this.checkParamValid_(index, 'Index', 1, 255)) {
if (languageCodeInput.value === 'All') {
- this.renderStringDescriptorForAllLanguages(index);
+ await this.getStringDescriptorForAllLanguages_(index);
} else {
const languageCode = Number.parseInt(languageCodeInput.value);
- if (this.checkLanguageCodeValueValid_(languageCode)) {
- this.renderStringDescriptorForLanguageCode(index, languageCode);
+ if (this.checkParamValid_(
+ languageCode, 'Language Code', 0, 65535)) {
+ await this.getStringDescriptorForLanguageCode_(
+ index, languageCode);
}
}
}
@@ -1231,43 +1081,11 @@ cr.define('descriptor_panel', function() {
}
/**
- * Checks if the user input index is a valid uint8 number.
- * @param {number} index
- * @return {boolean}
- * @private
- */
- checkIndexValueValid_(index) {
- // index is 8 bit. 0 is reserved to query all supported language codes.
- if (Number.isNaN(index) || index < 1 || index > 255) {
- this.showError_('Invalid Index.');
- return false;
- }
- return true;
- }
-
- /**
- * Checks if the user input language code is a valid uint16 number.
- * @param {number} languageCode
- * @return {boolean}
- * @private
- */
- checkLanguageCodeValueValid_(languageCode) {
- if (Number.isNaN(languageCode) || languageCode < 0 ||
- languageCode > 65535) {
- this.showError_('Invalid Language Code.');
- return false;
- }
- return true;
- }
-
- /**
* Gets the Binary device Object Store (BOS) descriptor of the current
* device, which contains the WebUSB descriptor and Microsoft OS 2.0
- * descriptor.
- * @return {!Uint8Array}
- * @private
+ * descriptor, and display it.
*/
- async getBosDescriptor_() {
+ async getBosDescriptor() {
/** @type {!device.mojom.UsbControlTransferParams} */
const usbControlTransferParams = {};
usbControlTransferParams.type =
@@ -1278,45 +1096,43 @@ cr.define('descriptor_panel', function() {
usbControlTransferParams.value = (BOS_DESCRIPTOR_TYPE << 8);
usbControlTransferParams.index = 0;
- let response = await this.usbDeviceProxy_.controlTransferIn(
- usbControlTransferParams, BOS_DESCRIPTOR_HEADER_LENGTH,
- CONTROL_TRANSFER_TIMEOUT_MS);
-
- this.checkDescriptorGetSuccess_(
- response.status,
- 'Failed to read the device BOS descriptor to determine ' +
- 'the total descriptor length.');
-
- const data = new DataView(new Uint8Array(response.data).buffer);
- const length = data.getUint16(BOS_DESCRIPTOR_TOTAL_LENGTH_OFFSET, true);
-
- // Re-gets the data use the full length.
- response = await this.usbDeviceProxy_.controlTransferIn(
- usbControlTransferParams, length, CONTROL_TRANSFER_TIMEOUT_MS);
-
- this.checkDescriptorGetSuccess_(
- response.status, 'Failed to read the complete BOS descriptor.');
-
- return new Uint8Array(response.data);
- }
-
- /**
- * Renders a view to display BOS descriptor hex data in both tree view
- * and raw form.
- */
- async renderBosDescriptor() {
- let rawData;
try {
await this.usbDeviceProxy_.open();
- rawData = await this.getBosDescriptor_();
+ let response = await this.usbDeviceProxy_.controlTransferIn(
+ usbControlTransferParams, BOS_DESCRIPTOR_HEADER_LENGTH,
+ CONTROL_TRANSFER_TIMEOUT_MS);
+ checkTransferSuccess(
+ response.status,
+ 'Failed to read the device BOS descriptor to determine ' +
+ 'the total descriptor length.',
+ this.rootElement_);
+ const dataView = new DataView(new Uint8Array(response.data).buffer);
+ const length =
+ dataView.getUint16(BOS_DESCRIPTOR_TOTAL_LENGTH_OFFSET, true);
+ // Re-gets the data using the full length.
+ response = await this.usbDeviceProxy_.controlTransferIn(
+ usbControlTransferParams, length, CONTROL_TRANSFER_TIMEOUT_MS);
+ checkTransferSuccess(
+ response.status, 'Failed to read the complete BOS descriptor.',
+ this.rootElement_);
+ await this.renderStandardDescriptor_(new Uint8Array(response.data));
} catch (e) {
- this.showError_(e.message);
- // Stop rendering if failed to read the BOS descriptor.
- return;
+ showError(e.message, this.rootElement_);
} finally {
await this.usbDeviceProxy_.close();
}
+ }
+ /**
+ * Renders a view to display Binary device Object Store (BOS) descriptor hex
+ * data in both tree view and raw form.
+ * @param {!cr.ui.Tree} rawDataTreeRoot
+ * @param {!HTMLElement} rawDataByteElement
+ * @param {!Uint8Array} rawData
+ * @param {number} offset The start offset of the BOS descriptor.
+ * @private
+ */
+ renderBosDescriptor_(rawDataTreeRoot, rawDataByteElement, rawData, offset) {
const fields = [
{
'label': 'Length (should be 5): ',
@@ -1340,68 +1156,43 @@ cr.define('descriptor_panel', function() {
},
];
- const displayElement = this.addNewDescriptorDisplayElement_();
- /** @type {!cr.ui.Tree} */
- const rawDataTreeRoot = displayElement.rawDataTreeRoot;
- /** @type {!HTMLElement} */
- const rawDataByteElement = displayElement.rawDataByteElement;
-
- renderRawDataBytes(rawDataByteElement, rawData);
-
- let offset = this.renderRawDataTree_(
- rawDataTreeRoot, rawDataByteElement, fields, rawData, 0);
-
- if (offset !== BOS_DESCRIPTOR_HEADER_LENGTH) {
- this.showError_(
- 'An error occurred while rendering BOS descriptor header.');
- }
+ renderRawDataTree(
+ rawDataTreeRoot, rawDataByteElement, fields, rawData, offset,
+ this.rootElement_);
+ }
- let indexWebUsb = 0;
- let indexMsOs20 = 0;
- let indexUnknownBos = 0;
- // Continue parsing while there are still unparsed device capability
- // descriptors. Stop if accessing the device capability type would cause
- // us to read past the end of the buffer.
- while ((offset + BOS_DESCRIPTOR_DEVICE_CAPABILITY_TYPE_OFFSET) <
- rawData.length) {
- switch (
- rawData[offset + BOS_DESCRIPTOR_DEVICE_CAPABILITY_TYPE_OFFSET]) {
- case DEVICE_CAPABILITY_DESCRIPTOR_TYPE_PLATFORM:
- if (isSameUuid(rawData, offset, WEB_USB_CAPABILITY_UUID)) {
- offset = this.renderWebUsbPlatformDescriptor_(
- rawDataTreeRoot, rawDataByteElement, rawData, offset,
- indexWebUsb);
- indexWebUsb++;
- break;
- } else if (isSameUuid(
- rawData, offset,
- MS_OS_20_PLATFORM_CAPABILITY_UUID)) {
- offset = this.renderMsOs20PlatformDescriptor_(
- rawDataTreeRoot, rawDataByteElement, rawData, offset,
- indexMsOs20);
- indexMsOs20++;
- break;
- }
- default:
- offset = this.renderUnknownBosDescriptor_(
+ /**
+ * Renders a view to display device capability descriptor hex data in both
+ * tree view and raw form.
+ * @param {!cr.ui.Tree} rawDataTreeRoot
+ * @param {!HTMLElement} rawDataByteElement
+ * @param {!Uint8Array} rawData
+ * @param {number} offset The start offset of the BOS descriptor.
+ * @param {number} indexDevCapability
+ * @private
+ */
+ async renderDeviceCapabilityDescriptor_(
+ rawDataTreeRoot, rawDataByteElement, rawData, offset,
+ indexDevCapability) {
+ switch (rawData[offset + BOS_DESCRIPTOR_DEVICE_CAPABILITY_TYPE_OFFSET]) {
+ case DEVICE_CAPABILITY_DESCRIPTOR_TYPE_PLATFORM_TYPE:
+ if (isSameUuid(rawData, offset, WEB_USB_CAPABILITY_UUID)) {
+ this.renderWebUsbPlatformDescriptor_(
rawDataTreeRoot, rawDataByteElement, rawData, offset,
- indexUnknownBos);
- indexUnknownBos++;
- }
- }
-
- const expectNumBosDescriptors =
- rawData[BOS_DESCRIPTOR_NUM_DEVICE_CAPABILITIES_OFFSET];
- const encounteredNumBosDescriptors =
- indexWebUsb + indexMsOs20 + indexUnknownBos;
- if (encounteredNumBosDescriptors !== expectNumBosDescriptors) {
- this.showError_(
- `Expected to find ${expectNumBosDescriptors} ` +
- `interface descriptors but only encountered ` +
- `${encounteredNumBosDescriptors}.`);
+ indexDevCapability);
+ break;
+ } else if (isSameUuid(
+ rawData, offset, MS_OS_20_PLATFORM_CAPABILITY_UUID)) {
+ offset = this.renderMsOs20PlatformDescriptor_(
+ rawDataTreeRoot, rawDataByteElement, rawData, offset,
+ indexDevCapability);
+ break;
+ }
+ default:
+ offset = this.renderUnknownBosDescriptor_(
+ rawDataTreeRoot, rawDataByteElement, rawData, offset,
+ indexDevCapability);
}
-
- addMappingAction(rawDataTreeRoot, rawDataByteElement);
}
/**
@@ -1410,20 +1201,13 @@ cr.define('descriptor_panel', function() {
* @param {!cr.ui.Tree} rawDataTreeRoot
* @param {!HTMLElement} rawDataByteElement
* @param {!Uint8Array} rawData
- * @param {number} originalOffset The start offset of the WebUSB platform
+ * @param {number} offset The start offset of the WebUSB platform
* capability descriptor.
* @param {number} indexWebUsb
- * @return {number}
* @private
*/
renderWebUsbPlatformDescriptor_(
- rawDataTreeRoot, rawDataByteElement, rawData, originalOffset,
- indexWebUsb) {
- if (originalOffset + WEB_USB_DESCRIPTOR_LENGTH > rawData.length) {
- this.showError_(
- `Failed to read the WebUSB descriptor at index ${indexWebUsb}.`);
- }
-
+ rawDataTreeRoot, rawDataByteElement, rawData, offset, indexWebUsb) {
const parentClassName = `descriptor-webusb-${indexWebUsb}`;
const webUsbItem = customTreeItem('WebUSB Descriptor', parentClassName);
rawDataTreeRoot.add(webUsbItem);
@@ -1468,24 +1252,12 @@ cr.define('descriptor_panel', function() {
label: 'Landing Page: ',
size: 1,
formatter: formatByte,
- extraTreeItemFormatter: (rawData, offset, item, fieldLabel) =>
- this.renderLandingPageItem_(
- rawData, offset - WEB_USB_URL_DESCRIPTOR_INDEX_OFFSET, item,
- fieldLabel)
+ extraTreeItemFormatter: this.renderUrlDescriptorIndexItem_.bind(this),
},
];
-
- const offset = this.renderRawDataTree_(
- webUsbItem, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
-
- if (offset !== originalOffset + WEB_USB_DESCRIPTOR_LENGTH) {
- this.showError_(
- `An error occurred while rendering WebUSB descriptor at index ${
- indexWebUsb}.`);
- }
-
- return offset;
+ renderRawDataTree(
+ webUsbItem, rawDataByteElement, fields, rawData, offset,
+ this.rootElement_, parentClassName);
}
/**
@@ -1494,21 +1266,13 @@ cr.define('descriptor_panel', function() {
* @param {!cr.ui.Tree} rawDataTreeRoot
* @param {!HTMLElement} rawDataByteElement
* @param {!Uint8Array} rawData
- * @param {number} originalOffset The start offset of the Microsoft OS 2.0
- * platform capability descriptor.
+ * @param {number} offset The start offset of the Microsoft OS 2.0 platform
+ * capability descriptor.
* @param {number} indexMsOs20
- * @return {number}
* @private
*/
renderMsOs20PlatformDescriptor_(
- rawDataTreeRoot, rawDataByteElement, rawData, originalOffset,
- indexMsOs20) {
- if (originalOffset + PLATFORM_DESCRIPTOR_HEADER_LENGTH > rawData.length) {
- this.showError_(
- `Failed to read the Microsoft OS 2.0 descriptor at index ${
- indexMsOs20}.`);
- }
-
+ rawDataTreeRoot, rawDataByteElement, rawData, offset, indexMsOs20) {
const parentClassName = `descriptor-ms-os-20-${indexMsOs20}`;
const msOs20Item =
customTreeItem(`Microsoft OS 2.0 Descriptor`, parentClassName);
@@ -1541,39 +1305,22 @@ cr.define('descriptor_panel', function() {
formatter: formatUuid,
},
];
- const msOs20DescriptorLength =
- rawData[originalOffset + STANDARD_DESCRIPTOR_LENGTH_OFFSET];
-
- let offset = this.renderRawDataTree_(
- msOs20Item, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
- if (offset !== originalOffset + PLATFORM_DESCRIPTOR_HEADER_LENGTH) {
- this.showError_(
- `An error occurred while rendering Microsoft OS 2.0 descriptor at` +
- ` index ${indexMsOs20}.`);
- }
+ offset = renderRawDataTree(
+ msOs20Item, rawDataByteElement, fields, rawData, offset,
+ this.rootElement_, parentClassName);
let indexMsOs20DescriptorSetInfo = 0;
// Continue parsing while there are still unparsed Microsoft OS 2.0
// descriptor set information structures. Stop if accessing the descriptor
// set information structure would cause us to read past the end of the
// buffer.
- while ((offset + MS_OS_20_DESCRIPTOR_SET_INFORMATION_LENGTH) <=
- rawData.length) {
+ while (offset < rawData.length) {
offset = this.renderMsOs20DescriptorSetInfo_(
msOs20Item, rawDataByteElement, rawData, offset,
indexMsOs20DescriptorSetInfo, indexMsOs20);
indexMsOs20DescriptorSetInfo++;
}
-
- if (offset !== originalOffset + msOs20DescriptorLength) {
- this.showError_(
- `An error occurred while rendering Microsoft OS 2.0 descriptor at` +
- ` index ${indexMsOs20}.`);
- }
-
- return offset;
}
/**
@@ -1582,7 +1329,7 @@ cr.define('descriptor_panel', function() {
* @param {!cr.ui.Tree} rawDataTreeRoot
* @param {!HTMLElement} rawDataByteElement
* @param {!Uint8Array} rawData
- * @param {number} originalOffset The start offset of the Microsoft OS 2.0
+ * @param {number} offset The start offset of the Microsoft OS 2.0
* set information structure.
* @param {number} indexMsOs20DescriptorSetInfo
* @param {number} indexMsOs20
@@ -1590,15 +1337,8 @@ cr.define('descriptor_panel', function() {
* @private
*/
renderMsOs20DescriptorSetInfo_(
- rawDataTreeRoot, rawDataByteElement, rawData, originalOffset,
+ rawDataTreeRoot, rawDataByteElement, rawData, offset,
indexMsOs20DescriptorSetInfo, indexMsOs20) {
- if (originalOffset + MS_OS_20_DESCRIPTOR_SET_INFORMATION_LENGTH >
- rawData.length) {
- this.showError_(
- `Failed to read the Microsoft OS 2.0 descriptor set information ` +
- `at index ${indexMsOs20DescriptorSetInfo}.`);
- }
-
const parentClassName =
`descriptor-ms-os-20-set-info-${indexMsOs20DescriptorSetInfo}`;
const msOs20SetInfoItem = customTreeItem(
@@ -1636,39 +1376,31 @@ cr.define('descriptor_panel', function() {
},
];
- const offset = this.renderRawDataTree_(
- msOs20SetInfoItem, rawDataByteElement, fields, rawData,
- originalOffset, parentClassName,
+ return renderRawDataTree(
+ msOs20SetInfoItem, rawDataByteElement, fields, rawData, offset,
+ this.rootElement_, parentClassName,
`descriptor-ms-os-20-${indexMsOs20}`);
-
- if (offset !==
- originalOffset + MS_OS_20_DESCRIPTOR_SET_INFORMATION_LENGTH) {
- this.showError_(
- `An error occurred while rendering Microsoft OS 2.0 descriptor ` +
- `set information at index ${indexMsOs20DescriptorSetInfo}.`);
- }
-
- return offset;
}
/**
- * Renders a tree item to display unknown BOS descriptor at indexUnknownBos
+ * Renders a tree item to display unknown device capability descriptor at
+ * indexUnknownDevCapability
* @param {!cr.ui.Tree} rawDataTreeRoot
* @param {!HTMLElement} rawDataByteElement
* @param {!Uint8Array} rawData
- * @param {number} originalOffset The start offset of the unknown BOS
- * descriptor.
- * @param {number} indexUnknownBos
- * @return {number}
+ * @param {number} originalOffset The start offset of the unknown device
+ * capability descriptor.
+ * @param {number} indexUnknownDevCapability
* @private
*/
renderUnknownBosDescriptor_(
rawDataTreeRoot, rawDataByteElement, rawData, originalOffset,
- indexUnknownBos) {
+ indexUnknownDevCapability) {
const length =
rawData[originalOffset + STANDARD_DESCRIPTOR_LENGTH_OFFSET];
- const parentClassName = `descriptor-unknownbos-${indexUnknownBos}`;
+ const parentClassName =
+ `descriptor-unknownbos-${indexUnknownDevCapability}`;
const unknownBosItem =
customTreeItem(`Unknown BOS Descriptor`, parentClassName);
rawDataTreeRoot.add(unknownBosItem);
@@ -1691,9 +1423,9 @@ cr.define('descriptor_panel', function() {
},
];
- let offset = this.renderRawDataTree_(
+ let offset = renderRawDataTree(
unknownBosItem, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ this.rootElement_, parentClassName);
const rawDataByteElements = rawDataByteElement.querySelectorAll('span');
@@ -1701,18 +1433,23 @@ cr.define('descriptor_panel', function() {
rawDataByteElements[offset].classList.add(`field-offset-${offset}`);
rawDataByteElements[offset].classList.add(parentClassName);
}
-
- return offset;
}
/**
- * Gets the URL Descriptor, and returns the parsed URL.
- * @param {number} vendorCode
- * @param {number} urlIndex
- * @return {string}
+ * Gets the URL Descriptor, renders a URL descriptor item and adds it to
+ * the URL descriptor index item.
+ * @param {!Uint8Array} rawData
+ * @param {number} offset The offset of the WebUSB descriptor.
+ * @param {!cr.ui.TreeItem} item The URL descriptor index item.
* @private
*/
- async getUrlDescriptor_(vendorCode, urlIndex) {
+ async getUrlDescriptor_(rawData, offset, item) {
+ // The second to last byte is the vendor code used to query URL
+ // descriptor. Last byte is index of url descriptor. These are defined by
+ // the WebUSB specification: http://wicg.github.io/webusb/
+ const vendorCode = rawData[offset + WEB_USB_VENDOR_CODE_OFFSET];
+ const urlIndex = rawData[offset + WEB_USB_URL_DESCRIPTOR_INDEX_OFFSET];
+
/** @type {!device.mojom.UsbControlTransferParams} */
const usbControlTransferParams = {};
usbControlTransferParams.recipient =
@@ -1725,44 +1462,48 @@ cr.define('descriptor_panel', function() {
usbControlTransferParams.value = urlIndex;
usbControlTransferParams.index = GET_URL_REQUEST;
- let urlResponse;
try {
await this.usbDeviceProxy_.open();
// Gets the URL descriptor.
- urlResponse = await this.usbDeviceProxy_.controlTransferIn(
+ const urlResponse = await this.usbDeviceProxy_.controlTransferIn(
usbControlTransferParams, MAX_URL_DESCRIPTOR_LENGTH,
CONTROL_TRANSFER_TIMEOUT_MS);
- this.checkDescriptorGetSuccess_(
- urlResponse.status, 'Failed to read the device URL descriptor.');
+ checkTransferSuccess(
+ urlResponse.status, 'Failed to read the device URL descriptor.',
+ this.rootElement_);
+
+ let url;
+ // URL Prefixes are defined by Chapter 4.3.1 of the WebUSB
+ // specification: http://wicg.github.io/webusb/
+ switch (urlResponse.data[2]) {
+ case 0:
+ url = 'http://';
+ break;
+ case 1:
+ url = 'https://';
+ break;
+ case 255:
+ default:
+ url = '';
+ }
+ // The first three elements of urlResponse.data are length, descriptor
+ // type and URL scheme prefix.
+ url += decodeUtf8Array(new Uint8Array(urlResponse.data.slice(3)));
+
+ const landingPageItem = customTreeItem(url, 'descriptor-url');
+ landingPageItem.labelElement.addEventListener(
+ 'click', () => window.open(url, '_blank'));
+ item.add(landingPageItem);
+ item.expanded = true;
} catch (e) {
- this.showError_(e.message);
+ showError(e.message, this.rootElement_);
// Stops parsing to string format URL if failed to read the URL
// descriptor.
return '';
} finally {
await this.usbDeviceProxy_.close();
}
-
- let urlDescriptor;
- // URL Prefixes are defined by Chapter 4.3.1 of the WebUSB specification:
- // http://wicg.github.io/webusb/
- switch (urlResponse.data[2]) {
- case 0:
- urlDescriptor = 'http://';
- break;
- case 1:
- urlDescriptor = 'https://';
- break;
- case 255:
- default:
- urlDescriptor = '';
- }
- // The first three elements of urlResponse.data are length, descriptor
- // type and URL scheme prefix.
- urlDescriptor +=
- decodeUtf8Array(new Uint8Array(urlResponse.data.slice(3)));
- return urlDescriptor;
}
/**
@@ -1792,11 +1533,12 @@ cr.define('descriptor_panel', function() {
usbControlTransferParams, msOs20DescriptorSetLength,
CONTROL_TRANSFER_TIMEOUT_MS);
- this.checkDescriptorGetSuccess_(
+ checkTransferSuccess(
response.status,
- 'Failed to read the Microsoft OS 2.0 descriptor set.');
+ 'Failed to read the Microsoft OS 2.0 descriptor set.',
+ this.rootElement_);
} catch (e) {
- this.showError_(e.message);
+ showError(e.message, this.rootElement_);
// Returns an empty array if failed to read the Microsoft OS 2.0
// descriptor set.
return new Uint8Array();
@@ -1834,12 +1576,13 @@ cr.define('descriptor_panel', function() {
const response = await this.usbDeviceProxy_.controlTransferOut(
usbControlTransferParams, [], CONTROL_TRANSFER_TIMEOUT_MS);
- this.checkDescriptorGetSuccess_(
+ checkTransferSuccess(
response.status,
- 'Failed to read the Microsoft OS 2.0 ' +
- 'descriptor alternate enumeration set.');
+ 'Failed to read the Microsoft OS 2.0 descriptor ' +
+ 'alternate enumeration set.',
+ this.rootElement_);
} catch (e) {
- this.showError_(e.message);
+ showError(e.message, this.rootElement_);
} finally {
await this.usbDeviceProxy_.close();
}
@@ -1852,8 +1595,8 @@ cr.define('descriptor_panel', function() {
* @private
*/
renderMsOs20DescriptorSet_(msOs20RawData) {
- const displayElement = this.addNewDescriptorDisplayElement_(
- 'Microsoft OS 2.0 Descriptor Set');
+ const displayElement = addNewDescriptorDisplayElement(
+ this.rootElement_, 'Microsoft OS 2.0 Descriptor Set');
/** @type {!cr.ui.Tree} */
const rawDataTreeRoot = displayElement.rawDataTreeRoot;
/** @type {!HTMLElement} */
@@ -1975,13 +1718,15 @@ cr.define('descriptor_panel', function() {
},
];
- const offset = this.renderRawDataTree_(
- rawDataTreeRoot, rawDataByteElement, fields, rawData, originalOffset);
+ const offset = renderRawDataTree(
+ rawDataTreeRoot, rawDataByteElement, fields, rawData, originalOffset,
+ this.rootElement_);
if (offset !== originalOffset + length) {
- this.showError_(
+ showError(
'An error occurred while rendering Microsoft OS 2.0 Descriptor ' +
- 'Set header.');
+ 'Set header.',
+ this.rootElement_);
}
return offset;
@@ -2040,14 +1785,15 @@ cr.define('descriptor_panel', function() {
},
];
- const offset = this.renderRawDataTree_(
+ const offset = renderRawDataTree(
item, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ this.rootElement_, parentClassName);
if (offset !== originalOffset + length) {
- this.showError_(
+ showError(
'An error occurred while rendering Microsoft OS 2.0 ' +
- 'Configuration Subset Header.');
+ 'Configuration Subset Header.',
+ this.rootElement_);
}
return offset;
@@ -2104,14 +1850,15 @@ cr.define('descriptor_panel', function() {
},
];
- const offset = this.renderRawDataTree_(
+ const offset = renderRawDataTree(
item, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ this.rootElement_, parentClassName);
if (offset !== originalOffset + length) {
- this.showError_(
+ showError(
'An error occurred while rendering Microsoft OS 2.0 ' +
- 'Function Subset Header.');
+ 'Function Subset Header.',
+ this.rootElement_);
}
return offset;
@@ -2163,14 +1910,15 @@ cr.define('descriptor_panel', function() {
},
];
- const offset = this.renderRawDataTree_(
+ const offset = renderRawDataTree(
item, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ this.rootElement_, parentClassName);
if (offset !== originalOffset + length) {
- this.showError_(
+ showError(
'An error occurred while rendering Microsoft OS 2.0 ' +
- 'Compatible ID Descriptor.');
+ 'Compatible ID Descriptor.',
+ this.rootElement_);
}
return offset;
@@ -2239,9 +1987,9 @@ cr.define('descriptor_panel', function() {
},
];
- let offset = this.renderRawDataTree_(
+ let offset = renderRawDataTree(
item, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ this.rootElement_, parentClassName);
while (offset < originalOffset + length) {
const propertyDataLength = data.getUint16(offset, true);
@@ -2261,15 +2009,16 @@ cr.define('descriptor_panel', function() {
featureRegistryPropertyDataType, propertyDataLength),
},
];
- offset = this.renderRawDataTree_(
+ offset = renderRawDataTree(
item, rawDataByteElement, propertyDataFields, rawData, offset,
- parentClassName);
+ this.rootElement_, parentClassName);
}
if (offset !== originalOffset + length) {
- this.showError_(
+ showError(
'An error occurred while rendering Microsoft OS 2.0 ' +
- 'Registry Property Descriptor.');
+ 'Registry Property Descriptor.',
+ this.rootElement_);
}
return offset;
@@ -2323,14 +2072,15 @@ cr.define('descriptor_panel', function() {
},
];
- const offset = this.renderRawDataTree_(
+ const offset = renderRawDataTree(
item, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ this.rootElement_, parentClassName);
if (offset !== originalOffset + length) {
- this.showError_(
+ showError(
'An error occurred while rendering Microsoft OS 2.0 ' +
- 'Minimum USB Resume Time Descriptor.');
+ 'Minimum USB Resume Time Descriptor.',
+ this.rootElement_);
}
return offset;
@@ -2377,14 +2127,15 @@ cr.define('descriptor_panel', function() {
},
];
- const offset = this.renderRawDataTree_(
+ const offset = renderRawDataTree(
item, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ this.rootElement_, parentClassName);
if (offset !== originalOffset + length) {
- this.showError_(
+ showError(
'An error occurred while rendering Microsoft OS 2.0 ' +
- 'Model ID Descriptor.');
+ 'Model ID Descriptor.',
+ this.rootElement_);
}
return offset;
@@ -2429,14 +2180,15 @@ cr.define('descriptor_panel', function() {
},
];
- const offset = this.renderRawDataTree_(
+ const offset = renderRawDataTree(
item, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ this.rootElement_, parentClassName);
if (offset !== originalOffset + length) {
- this.showError_(
+ showError(
'An error occurred while rendering Microsoft OS 2.0 ' +
- 'CCGP Device Descriptor.');
+ 'CCGP Device Descriptor.',
+ this.rootElement_);
}
return offset;
@@ -2484,14 +2236,15 @@ cr.define('descriptor_panel', function() {
},
];
- const offset = this.renderRawDataTree_(
+ const offset = renderRawDataTree(
item, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ this.rootElement_, parentClassName);
if (offset !== originalOffset + length) {
- this.showError_(
+ showError(
'An error occurred while rendering Microsoft OS 2.0 ' +
- 'Vendor Revision Descriptor.');
+ 'Vendor Revision Descriptor.',
+ this.rootElement_);
}
return offset;
@@ -2533,9 +2286,9 @@ cr.define('descriptor_panel', function() {
},
];
- let offset = this.renderRawDataTree_(
+ let offset = renderRawDataTree(
item, rawDataByteElement, fields, rawData, originalOffset,
- parentClassName);
+ this.rootElement_, parentClassName);
const rawDataByteElements = rawDataByteElement.querySelectorAll('span');
@@ -2545,13 +2298,407 @@ cr.define('descriptor_panel', function() {
}
if (offset !== originalOffset + length) {
- this.showError_(
+ showError(
'An error occurred while rendering Microsoft OS 2.0 ' +
- 'Unknown Descriptor.');
+ 'Unknown Descriptor.',
+ this.rootElement_);
}
return offset;
}
+
+ /**
+ * Gets response of the given request.
+ * @param {!device.mojom.UsbControlTransferParams} usbControlTransferParams
+ * @param {number} length
+ * @param {number} direction
+ * @private
+ */
+ async sendTestingRequest_(usbControlTransferParams, length, direction) {
+ try {
+ await this.usbDeviceProxy_.open();
+
+ if (direction === 'Device-to-Host') {
+ const response = await this.usbDeviceProxy_.controlTransferIn(
+ usbControlTransferParams, length, CONTROL_TRANSFER_TIMEOUT_MS);
+ checkTransferSuccess(
+ response.status, 'Failed to send request.', this.rootElement_);
+ this.renderTestingData_(new Uint8Array(response.data));
+ } else if (direction === 'Host-to-Device') {
+ const dataString = this.rootElement_.querySelector('textarea').value;
+
+ const data = [];
+ for (let i = 0; i < dataString.length; i += 2) {
+ data.push(Number.parseInt(dataString.substring(i, i + 2), 16));
+ }
+
+ const response = await this.usbDeviceProxy_.controlTransferOut(
+ usbControlTransferParams, new Uint8Array(data),
+ CONTROL_TRANSFER_TIMEOUT_MS);
+ checkTransferSuccess(
+ response.status, 'Failed to send request.', this.rootElement_);
+ }
+ } catch (e) {
+ showError(e.message, this.rootElement_);
+ return;
+ } finally {
+ await this.usbDeviceProxy_.close();
+ }
+ }
+
+ /**
+ * Renders a view to display response data in hex format.
+ * @param {!Uint8Array} rawData
+ * @private
+ */
+ async renderTestingData_(rawData) {
+ const displayElement = addNewDescriptorDisplayElement(this.rootElement_);
+ /** @type {!cr.ui.Tree} */
+ const rawDataTreeRoot = displayElement.rawDataTreeRoot;
+ rawDataTreeRoot.style.display = 'none';
+ /** @type {!HTMLElement} */
+ const rawDataByteElement = displayElement.rawDataByteElement;
+ renderRawDataBytes(rawDataByteElement, rawData);
+ }
+
+ /**
+ * Initializes the testing tool panel for input and query functionality.
+ */
+ initialTestingToolPanel() {
+ showWarn(
+ 'Warning: This tool can send arbitrary commands to the device. ' +
+ 'Invalid commands may cause unexpected results.',
+ this.rootElement_);
+ const inputTableRows =
+ this.rootElement_.querySelector('tbody').querySelectorAll('tr');
+ const buttons =
+ this.rootElement_.querySelector('tbody').querySelectorAll('button');
+ const dataInputArea = this.rootElement_.querySelector('textarea');
+ dataInputArea.addEventListener('keypress', () => {
+ const index = dataInputArea.selectionStart;
+ dataInputArea.value = dataInputArea.value.substring(0, index) +
+ dataInputArea.value.substring(index + 1);
+ dataInputArea.selectionEnd = index;
+ });
+
+ const testingToolPanelInputTypeSelector =
+ this.rootElement_.querySelector('#input-type');
+ testingToolPanelInputTypeSelector.addEventListener('change', () => {
+ this.clearView();
+ const index = testingToolPanelInputTypeSelector.selectedIndex;
+ inputTableRows.forEach(row => row.hidden = true);
+ inputTableRows[index].hidden = false;
+
+ const direction = getRequestTypeDirection(inputTableRows[index], index);
+ const length = getRequestLength(inputTableRows[index], index);
+ this.rootElement_.querySelector('#data-input-area').hidden =
+ (direction !== 'Host-to-Device');
+ dataInputArea.value = '00'.repeat(length);
+ dataInputArea.maxLength = length * 2;
+ });
+
+ for (const [i, inputTableRow] of inputTableRows.entries()) {
+ let directionInputElement;
+ switch (i) {
+ case INPUT_TYPE_DECIMAL_WITH_DROPDOWN:
+ directionInputElement =
+ inputTableRow.querySelector('#transfer-direction');
+ break;
+ case INPUT_TYPE_HEX_BYTE:
+ directionInputElement =
+ inputTableRow.querySelector('#query-request-type');
+ break;
+ }
+ directionInputElement.addEventListener('change', () => {
+ this.rootElement_.querySelector('#data-input-area').hidden =
+ (getRequestTypeDirection(inputTableRow, i) !== 'Host-to-Device');
+ });
+
+ inputTableRow.querySelector('#query-length')
+ .addEventListener('blur', () => {
+ const length = getRequestLength(inputTableRow, i);
+ dataInputArea.value = '00'.repeat(length);
+ dataInputArea.maxLength = length * 2;
+ });
+ }
+
+ for (const [i, button] of buttons.entries()) {
+ button.addEventListener('click', () => {
+ this.clearView();
+
+ const direction = getRequestTypeDirection(inputTableRows[i], i);
+ const type = getRequestType(inputTableRows[i], i);
+ const recipient = getRequestTypeRecipient(inputTableRows[i], i);
+ const request = getRequestCode(inputTableRows[i], i);
+ const value = getRequestValue(inputTableRows[i], i);
+ const index = getRequestIndex(inputTableRows[i], i);
+ const dataLength = getRequestLength(inputTableRows[i], i);
+
+ if (this.checkEnumParamValid_(
+ type, 'Transfer Type', device.mojom.UsbControlTransferType) &&
+ this.checkEnumParamValid_(
+ recipient, 'Transfer Recipient',
+ device.mojom.UsbControlTransferRecipient) &&
+ this.checkParamValid_(request, 'Transfer Request', 0, 255) &&
+ this.checkParamValid_(value, 'wValue', 0, 65535) &&
+ this.checkParamValid_(index, 'wIndex', 0, 65535) &&
+ this.checkParamValid_(dataLength, 'Length', 0, 65535)) {
+ /** @type {!device.mojom.UsbControlTransferParams} */
+ const usbControlTransferParams = {
+ type: device.mojom.UsbControlTransferType[type],
+ recipient: device.mojom.UsbControlTransferRecipient[recipient],
+ request,
+ value,
+ index,
+ };
+ this.sendTestingRequest_(
+ usbControlTransferParams, dataLength, direction);
+ }
+ });
+ }
+ }
+
+ /**
+ * Checks if the user input is a valid number.
+ * @param {number} paramValue
+ * @param {string} paramName
+ * @param {number} min
+ * @param {number} max
+ * @return {boolean}
+ * @private
+ */
+ checkParamValid_(paramValue, paramName, min, max) {
+ if (Number.isNaN(paramValue) || paramValue < min || paramValue > max) {
+ showError(`Invalid ${paramName}.`, this.rootElement_);
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Checks if the user input for a enum field is valid.
+ * @param {string} enumString
+ * @param {string} paramName
+ * @param {!Object} enumObject
+ * @return {boolean}
+ * @private
+ */
+ checkEnumParamValid_(enumString, paramName, enumObject) {
+ if (enumObject[enumString] !== undefined) {
+ return true;
+ }
+ showError(`Invalid ${paramName}`, this.rootElement_);
+ return false;
+ }
+ }
+
+ /**
+ * Get the USB control transfer type.
+ * @param {!HTMLElement} inputRow
+ * @param {number} inputType
+ * @return {string}
+ */
+ function getRequestType(inputRow, inputType) {
+ switch (inputType) {
+ case INPUT_TYPE_DECIMAL_WITH_DROPDOWN:
+ return inputRow.querySelector('#transfer-type').value;
+ case INPUT_TYPE_HEX_BYTE:
+ const value = Number.parseInt(
+ inputRow.querySelector('#query-request-type').value, 16);
+ switch (value >> 5 & 0x03) {
+ case 0:
+ return 'STANDARD';
+ case 1:
+ return 'CLASS';
+ case 2:
+ return 'VENDOR';
+ }
+ default:
+ return '';
+ }
+ }
+
+ /**
+ * Get the USB control transfer recipient.
+ * @param {!HTMLElement} inputRow
+ * @param {number} inputType
+ * @return {string}
+ */
+ function getRequestTypeRecipient(inputRow, inputType) {
+ switch (inputType) {
+ case INPUT_TYPE_DECIMAL_WITH_DROPDOWN:
+ return inputRow.querySelector('#transfer-recipient').value;
+ case INPUT_TYPE_HEX_BYTE:
+ const value = Number.parseInt(
+ inputRow.querySelector('#query-request-type').value, 16);
+ switch (value & 0x1F) {
+ case 0:
+ return 'DEVICE';
+ case 1:
+ return 'INTERFACE';
+ case 2:
+ return 'ENDPOINT';
+ case 3:
+ return 'OTHER';
+ }
+ default:
+ return '';
+ }
+ }
+
+ /**
+ * Get the USB control transfer direction. 0 for device-to-host, 1 for
+ * host-to-device.
+ * @param {!HTMLElement} inputRow
+ * @param {number} inputType
+ * @return {number}
+ */
+ function getRequestTypeDirection(inputRow, inputType) {
+ switch (inputType) {
+ case INPUT_TYPE_DECIMAL_WITH_DROPDOWN:
+ return inputRow.querySelector('#transfer-direction').value;
+ case INPUT_TYPE_HEX_BYTE:
+ const value = Number.parseInt(
+ inputRow.querySelector('#query-request-type').value, 16);
+ switch (value >> 7) {
+ case CONTROL_TRANSFER_DIRECTION_HOST_TO_DEVICE:
+ return 'Host-to-Device';
+ case CONTROL_TRANSFER_DIRECTION_DEVICE_TO_HOST:
+ return 'Device-to-Host';
+ }
+ default:
+ return 'Device-to-Host';
+ }
+ }
+
+ /**
+ * Get the USB control transfer request code.
+ * @param {!HTMLElement} inputRow
+ * @param {number} inputType
+ * @return {number}
+ */
+ function getRequestCode(inputRow, inputType) {
+ switch (inputType) {
+ case INPUT_TYPE_DECIMAL_WITH_DROPDOWN:
+ return Number.parseInt(inputRow.querySelector('#query-request').value);
+ case INPUT_TYPE_HEX_BYTE:
+ return Number.parseInt(
+ inputRow.querySelector('#query-request').value, 16);
+ default:
+ return Number.NaN;
+ }
+ }
+
+ /**
+ * Get the value of USB control transfer request wValue field.
+ * @param {!HTMLElement} inputRow
+ * @param {number} inputType
+ * @return {number}
+ */
+ function getRequestValue(inputRow, inputType) {
+ switch (inputType) {
+ case INPUT_TYPE_DECIMAL_WITH_DROPDOWN:
+ return Number.parseInt(inputRow.querySelector('#query-value').value);
+ case INPUT_TYPE_HEX_BYTE:
+ return Number.parseInt(
+ inputRow.querySelector('#query-value').value, 16);
+ default:
+ return Number.NaN;
+ }
+ }
+
+ /**
+ * Get the value of USB control transfer request wIndex field.
+ * @param {!HTMLElement} inputRow
+ * @param {number} inputType
+ * @return {number}
+ */
+ function getRequestIndex(inputRow, inputType) {
+ switch (inputType) {
+ case INPUT_TYPE_DECIMAL_WITH_DROPDOWN:
+ return Number.parseInt(inputRow.querySelector('#query-index').value);
+ case INPUT_TYPE_HEX_BYTE:
+ return Number.parseInt(
+ inputRow.querySelector('#query-index').value, 16);
+ default:
+ return Number.NaN;
+ }
+ }
+
+ /**
+ * Get the length of the data transferred during USB control transfer.
+ * @param {!HTMLElement} inputRow
+ * @param {number} inputType
+ * @return {number}
+ */
+ function getRequestLength(inputRow, inputType) {
+ switch (inputType) {
+ case INPUT_TYPE_DECIMAL_WITH_DROPDOWN:
+ return Number.parseInt(inputRow.querySelector('#query-length').value);
+ case INPUT_TYPE_HEX_BYTE:
+ return Number.parseInt(
+ inputRow.querySelector('#query-length').value, 16);
+ default:
+ return Number.NaN;
+ }
+ }
+
+ /**
+ * Adds a display area which contains a tree view and a byte view.
+ * @param {!HTMLElement} rootElement
+ * @param {string=} descriptorPanelTitle
+ * @return {{rawDataTreeRoot:!cr.ui.Tree,rawDataByteElement:!HTMLElement}}
+ */
+ function addNewDescriptorDisplayElement(
+ rootElement, descriptorPanelTitle = undefined) {
+ const descriptorPanelTemplate =
+ document.querySelector('#descriptor-panel-template');
+ const descriptorPanelClone =
+ document.importNode(descriptorPanelTemplate.content, true);
+
+ /** @type {!HTMLElement} */
+ const rawDataTreeRoot =
+ descriptorPanelClone.querySelector('.raw-data-tree-view');
+ /** @type {!HTMLElement} */
+ const rawDataByteElement =
+ descriptorPanelClone.querySelector('.raw-data-byte-view');
+
+ cr.ui.decorate(rawDataTreeRoot, cr.ui.Tree);
+ rawDataTreeRoot.detail = {payload: {}, children: {}};
+
+ if (descriptorPanelTitle) {
+ const descriptorPanelTitleTemplate =
+ document.querySelector('#descriptor-panel-title');
+ const clone =
+ document.importNode(descriptorPanelTitleTemplate.content, true)
+ .querySelector('descriptorpaneltitle');
+ clone.textContent = descriptorPanelTitle;
+ rootElement.appendChild(clone);
+ }
+ rootElement.appendChild(descriptorPanelClone);
+ return {rawDataTreeRoot, rawDataByteElement};
+ }
+
+ /**
+ * Shows an error message.
+ * @param {string} message
+ * @param {!HTMLElement} rootElement
+ */
+ function showError(message, rootElement) {
+ const errorElement = document.createElement('error');
+ errorElement.textContent = message;
+ rootElement.prepend(errorElement);
+ }
+
+ /**
+ * Shows a warning message.
+ * @param {string} message
+ * @param {!HTMLElement} rootElement
+ */
+ function showWarn(message, rootElement) {
+ const warnElement = document.createElement('warn');
+ warnElement.textContent = message;
+ rootElement.prepend(warnElement);
}
/**
@@ -2566,7 +2713,7 @@ cr.define('descriptor_panel', function() {
icon: '',
});
if (className) {
- item.querySelector('.tree-row').classList.add(className);
+ item.rowElement.classList.add(className);
}
return item;
}
@@ -2602,7 +2749,7 @@ cr.define('descriptor_panel', function() {
el.addEventListener('click', (event) => {
if (event.target.className != 'expand-icon') {
// Clears all the selected elements before select another.
- rawDataByteElement.querySelectorAll('#raw-data-byte-view span')
+ rawDataByteElement.querySelectorAll('.raw-data-byte-view span')
.forEach((el) => el.classList.remove('selected-field'));
rawDataByteElement
@@ -2652,6 +2799,58 @@ cr.define('descriptor_panel', function() {
}
/**
+ * Renders a tree view to display the raw data in readable text.
+ * @param {!cr.ui.Tree|!cr.ui.TreeItem} root
+ * @param {!HTMLElement} rawDataByteElement
+ * @param {!Array<Object>} fields
+ * @param {!Uint8Array} rawData
+ * @param {number} offset The start offset of the descriptor structure that
+ * want to be rendered.
+ * @param {!HTMLElement} rootElement
+ * @param {...string} parentClassNames
+ * @return {number} The end offset of descriptor structure that want to be
+ * rendered.
+ */
+ function renderRawDataTree(
+ root, rawDataByteElement, fields, rawData, offset, rootElement,
+ ...parentClassNames) {
+ const rawDataByteElements = rawDataByteElement.querySelectorAll('span');
+
+ for (const field of fields) {
+ const className = `field-offset-${offset}`;
+ let item;
+ try {
+ item = customTreeItem(
+ `${field.label}${field.formatter(rawData, offset)}`, className);
+
+ for (let i = 0; i < field.size; i++) {
+ rawDataByteElements[offset + i].classList.add(className);
+ for (const parentClassName of parentClassNames) {
+ rawDataByteElements[offset + i].classList.add(parentClassName);
+ }
+ }
+ } catch (e) {
+ showError(`Field at offset ${offset} is invalid.`, rootElement);
+ break;
+ }
+
+ try {
+ if (field.extraTreeItemFormatter) {
+ field.extraTreeItemFormatter(rawData, offset, item, field.label);
+ }
+ } catch (e) {
+ showError(
+ `Error at rendering field at index ${offset}: ${e.message}`,
+ rootElement);
+ }
+
+ root.add(item);
+ offset += field.size;
+ }
+ return offset;
+ }
+
+ /**
* Renders an element to display the raw data in hex, byte by byte.
* @param {!HTMLElement} rawDataByteElement
* @param {!Uint8Array} rawData
@@ -2678,6 +2877,47 @@ cr.define('descriptor_panel', function() {
}
/**
+ * Checks if the status of a control transfer indicates success.
+ * @param {number} status
+ * @param {string} defaultMessage
+ * @param {!HTMLElement} rootElement
+ */
+ function checkTransferSuccess(status, defaultMessage, rootElement) {
+ let failReason = '';
+ switch (status) {
+ case device.mojom.UsbTransferStatus.COMPLETED:
+ return;
+ case device.mojom.UsbTransferStatus.SHORT_PACKET:
+ showError('Descriptor is too short.', rootElement);
+ return;
+ case device.mojom.UsbTransferStatus.BABBLE:
+ showError('Descriptor is too long.', rootElement);
+ return;
+ case device.mojom.UsbTransferStatus.TRANSFER_ERROR:
+ failReason = 'Transfer Error';
+ break;
+ case device.mojom.UsbTransferStatus.TIMEOUT:
+ failReason = 'Timeout';
+ break;
+ case device.mojom.UsbTransferStatus.CANCELLED:
+ failReason = 'Transfer was cancelled';
+ break;
+ case device.mojom.UsbTransferStatus.STALLED:
+ failReason = 'Transfer Error';
+ break;
+ case device.mojom.UsbTransferStatus.DISCONNECT:
+ failReason = 'Transfer stalled';
+ break;
+ case device.mojom.UsbTransferStatus.PERMISSION_DENIED:
+ failReason = 'Permission denied';
+ break;
+ }
+ // Response data will be null if |status| is neither COMPLETED, BABBLE, or
+ // SHORT_PACKET. Throws an error to stop rendering response data.
+ throw new Error(`${defaultMessage} (Reason: ${failReason})`);
+ }
+
+ /**
* Converts a number to a hexadecimal string padded with zeros to the given
* number of digits.
* @param {number} number
diff --git a/chromium/chrome/browser/resources/usb_internals/devices_page.js b/chromium/chrome/browser/resources/usb_internals/devices_page.js
index f6196e0251f..e7743ac9062 100644
--- a/chromium/chrome/browser/resources/usb_internals/devices_page.js
+++ b/chromium/chrome/browser/resources/usb_internals/devices_page.js
@@ -124,14 +124,15 @@ cr.define('devices_page', function() {
cr.ui.decorate('tab', cr.ui.Tab);
const tabPanels = document.querySelector('tabpanels');
- const tabPanelTemplate = document.querySelector('#tabpanel-template');
+ const tabPanelTemplate =
+ document.querySelector('#device-tabpanel-template');
const tabPanelClone = document.importNode(tabPanelTemplate.content, true);
/**
* Root of the WebContents tree of current device.
* @type {?cr.ui.Tree}
*/
- const treeViewRoot = tabPanelClone.querySelector('#tree-view');
+ const treeViewRoot = tabPanelClone.querySelector('.tree-view');
cr.ui.decorate(treeViewRoot, cr.ui.Tree);
treeViewRoot.detail = {payload: {}, children: {}};
// Clear the tree first before populating it with the new content.
@@ -148,83 +149,29 @@ cr.define('devices_page', function() {
/**
* Initializes all the descriptor panels.
* @param {!HTMLElement} tabPanel
- * @param {number} guid
+ * @param {string} guid
* @private
*/
async initializeDescriptorPanels_(tabPanel, guid) {
const usbDeviceProxy = new UsbDeviceProxy;
await this.usbManager_.getDevice(guid, usbDeviceProxy.$.createRequest());
- const getStringDescriptorButton =
- tabPanel.querySelector('#string-descriptor-button');
- const stringDescriptorElement =
- tabPanel.querySelector('.string-descriptor-panel');
- const stringDescriptorPanel = new descriptor_panel.DescriptorPanel(
- usbDeviceProxy, stringDescriptorElement);
- stringDescriptorPanel.initialStringDescriptorPanel(guid);
- getStringDescriptorButton.addEventListener('click', () => {
- stringDescriptorElement.hidden = !stringDescriptorElement.hidden;
-
- // Clear the panel before rendering new data.
- stringDescriptorPanel.clearView();
-
- if (!stringDescriptorElement.hidden) {
- stringDescriptorPanel.getAllLanguageCodes();
- }
- });
-
- const getDeviceDescriptorButton =
- tabPanel.querySelector('#device-descriptor-button');
- const deviceDescriptorElement =
- tabPanel.querySelector('.device-descriptor-panel');
- const deviceDescriptorPanel = new descriptor_panel.DescriptorPanel(
- usbDeviceProxy, deviceDescriptorElement, stringDescriptorPanel);
- getDeviceDescriptorButton.addEventListener('click', () => {
- deviceDescriptorElement.hidden = !deviceDescriptorElement.hidden;
-
- // Clear the panel before rendering new data.
- deviceDescriptorPanel.clearView();
-
- if (!deviceDescriptorElement.hidden) {
- deviceDescriptorPanel.renderDeviceDescriptor();
- }
- });
-
- const getConfigurationDescriptorButton =
- tabPanel.querySelector('#configuration-descriptor-button');
- const configurationDescriptorElement =
- tabPanel.querySelector('.configuration-descriptor-panel');
- const configurationDescriptorPanel = new descriptor_panel.DescriptorPanel(
- usbDeviceProxy, configurationDescriptorElement,
+ const deviceDescriptorPanel = initialInspectorPanel(
+ tabPanel, 'device-descriptor', usbDeviceProxy, guid);
+
+ const configurationDescriptorPanel = initialInspectorPanel(
+ tabPanel, 'configuration-descriptor', usbDeviceProxy, guid);
+
+ const stringDescriptorPanel = initialInspectorPanel(
+ tabPanel, 'string-descriptor', usbDeviceProxy, guid);
+ deviceDescriptorPanel.setStringDescriptorPanel(stringDescriptorPanel);
+ configurationDescriptorPanel.setStringDescriptorPanel(
stringDescriptorPanel);
- getConfigurationDescriptorButton.addEventListener('click', () => {
- configurationDescriptorElement.hidden =
- !configurationDescriptorElement.hidden;
- // Clear the panel before rendering new data.
- configurationDescriptorPanel.clearView();
+ initialInspectorPanel(tabPanel, 'bos-descriptor', usbDeviceProxy, guid);
+
+ initialInspectorPanel(tabPanel, 'testing-tool', usbDeviceProxy, guid);
- if (!configurationDescriptorElement.hidden) {
- configurationDescriptorPanel.renderConfigurationDescriptor();
- }
- });
-
- const getBosDescriptorButton =
- tabPanel.querySelector('#bos-descriptor-button');
- const bosDescriptorElement =
- tabPanel.querySelector('.bos-descriptor-panel');
- const bosDescriptorPanel = new descriptor_panel.DescriptorPanel(
- usbDeviceProxy, bosDescriptorElement);
- getBosDescriptorButton.addEventListener('click', () => {
- bosDescriptorElement.hidden = !bosDescriptorElement.hidden;
-
- // Clear the panel before rendering new data.
- bosDescriptorPanel.clearView();
-
- if (!bosDescriptorElement.hidden) {
- bosDescriptorPanel.renderBosDescriptor();
- }
- });
// window.deviceTabInitializedFn() provides a hook for the test suite to
// perform test actions after the device tab query descriptors actions are
// initialized.
@@ -406,6 +353,53 @@ cr.define('devices_page', function() {
}
/**
+ * Initialize a descriptor panel.
+ * @param {!HTMLElement} tabPanel
+ * @param {string} panelType
+ * @param {!device.mojom.UsbDeviceInterface} usbDeviceProxy
+ * @param {string} guid
+ * @return {!descriptor_panel.DescriptorPanel}
+ */
+ function initialInspectorPanel(tabPanel, panelType, usbDeviceProxy, guid) {
+ const button = tabPanel.querySelector(`.${panelType}-button`);
+ const displayElement = tabPanel.querySelector(`.${panelType}-panel`);
+ const descriptorPanel =
+ new descriptor_panel.DescriptorPanel(usbDeviceProxy, displayElement);
+ switch (panelType) {
+ case 'string-descriptor':
+ descriptorPanel.initialStringDescriptorPanel(guid);
+ break;
+ case 'testing-tool':
+ descriptorPanel.initialTestingToolPanel();
+ break;
+ }
+
+ button.addEventListener('click', async () => {
+ displayElement.hidden = !displayElement.hidden;
+ // Clear the panel before rendering new data.
+ descriptorPanel.clearView();
+
+ if (!displayElement.hidden) {
+ switch (panelType) {
+ case 'device-descriptor':
+ await descriptorPanel.getDeviceDescriptor();
+ break;
+ case 'configuration-descriptor':
+ await descriptorPanel.getConfigurationDescriptor();
+ break;
+ case 'string-descriptor':
+ await descriptorPanel.getAllLanguageCodes();
+ break;
+ case 'bos-descriptor':
+ await descriptorPanel.getBosDescriptor();
+ break;
+ }
+ }
+ });
+ return descriptorPanel;
+ }
+
+ /**
* Parses utf16 coded string.
* @param {!mojoBase.mojom.String16} arr
* @return {string}
@@ -437,7 +431,6 @@ cr.define('devices_page', function() {
}
return {
- DevicePage,
DevicesPage,
};
});
diff --git a/chromium/chrome/browser/resources/usb_internals/usb_internals.css b/chromium/chrome/browser/resources/usb_internals/usb_internals.css
index 393e91fe3b1..8b640a3bbc2 100644
--- a/chromium/chrome/browser/resources/usb_internals/usb_internals.css
+++ b/chromium/chrome/browser/resources/usb_internals/usb_internals.css
@@ -69,58 +69,58 @@ descriptorpaneltitle {
margin-inline-start: 8px;
}
-#raw-data-byte-view,
-#raw-data-tree-view {
+.raw-data-byte-view,
+.raw-data-tree-view {
flex: 1 0;
}
-#raw-data-byte-view {
+.raw-data-byte-view {
font-size: 14px;
line-height: 250%;
white-space: pre;
}
-#raw-data-byte-view div {
+.raw-data-byte-view div {
position: sticky;
/* height of <tabs> and button */
top: 41px;
}
@media screen and (min-width: 1200px) {
- #raw-data-byte-view div span:nth-child(16n)::after {
+ .raw-data-byte-view div span:nth-child(16n)::after {
content: '\A';
}
}
@media screen and (min-width: 600px) and (max-width: 1199px) {
- #raw-data-byte-view div span:nth-child(8n)::after {
+ .raw-data-byte-view div span:nth-child(8n)::after {
content: '\A';
}
}
@media screen and (min-width: 300px) and (max-width: 599px) {
- #raw-data-byte-view div span:nth-child(4n)::after {
+ .raw-data-byte-view div span:nth-child(4n)::after {
content: '\A';
}
}
@media screen and (min-width: 150px) and (max-width: 299px) {
- #raw-data-byte-view div span:nth-child(2n)::after {
+ .raw-data-byte-view div span:nth-child(2n)::after {
content: '\A';
}
}
-#raw-data-byte-view div span {
+.raw-data-byte-view div span {
font-family: monospace;
padding-inline-end: .5em;
padding-inline-start: .5em;
}
-#raw-data-byte-view .selected-field {
+.raw-data-byte-view .selected-field {
background: red;
}
-#raw-data-byte-view .hovered-field {
+.raw-data-byte-view .hovered-field {
background: yellow;
}
@@ -134,9 +134,29 @@ descriptorpaneltitle {
margin-inline-start: 16px;
}
+#input-type {
+ display: block;
+}
+
+#testing-tool tr td select {
+ display: block;
+ width: 100%;
+}
+
+textarea {
+ display: block;
+ font-family: monospace;
+}
+
error {
color: red;
display: block;
font-size: 16px;
padding-inline-start: 20px;
+}
+
+warn {
+ color: red;
+ display: block;
+ font-size: 24px;
} \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/usb_internals/usb_internals.html b/chromium/chrome/browser/resources/usb_internals/usb_internals.html
index 1450f51fb8a..f709b1255bf 100644
--- a/chromium/chrome/browser/resources/usb_internals/usb_internals.html
+++ b/chromium/chrome/browser/resources/usb_internals/usb_internals.html
@@ -135,21 +135,21 @@
<tab></tab>
</template>
- <template id="tabpanel-template">
+ <template id="device-tabpanel-template">
<tabpanel>
- <tree id="tree-view"></tree>
+ <tree class="tree-view"></tree>
<div class="descriptor-button">
- <button id="device-descriptor-button">Get Device Descriptor</button>
+ <button class="device-descriptor-button">Get Device Descriptor</button>
</div>
<div class="device-descriptor-panel" hidden></div>
<div class="descriptor-button">
- <button id="configuration-descriptor-button">
+ <button class="configuration-descriptor-button">
Get Configuration Descriptor
</button>
</div>
<div class="configuration-descriptor-panel" hidden></div>
<div class="descriptor-button">
- <button id="string-descriptor-button">Get String Descriptor</button>
+ <button class="string-descriptor-button">Get String Descriptor</button>
</div>
<div class="string-descriptor-panel" hidden>
String Descriptor Index:
@@ -161,18 +161,78 @@
<button>GET</button>
</div>
<div class="descriptor-button">
- <button id="bos-descriptor-button">
+ <button class="bos-descriptor-button">
Get WebUSB & Microsoft OS 2.0 Descriptors
</button>
</div>
<div class="bos-descriptor-panel" hidden></div>
+ <div class="descriptor-button">
+ <button class="testing-tool-button">Testing Tool Panel</button>
+ </div>
+ <div class="testing-tool-panel" hidden>
+ <select id="input-type">
+ <option label="Decimal with Dropdown Menu"></option>
+ <option label="Hex Bytes"></option>
+ </select>
+ <table class="styled-table">
+ <thead>
+ <tr>
+ <th>bmRequestType</th>
+ <th>bRequest</th>
+ <th>wValue</th>
+ <th>wIndex</th>
+ <th>wLength</th>
+ </tr>
+ </thead>
+ <tbody id="testing-tool">
+ <tr>
+ <td>
+ <select id="transfer-direction">
+ <option label="Host-to-Device" value="Host-to-Device">
+ </option>
+ <option label="Device-to-Host" value="Device-to-Host">
+ </option>
+ </select>
+ <select id="transfer-type">
+ <option label="Standard" value="STANDARD"></option>
+ <option label="Class" value="CLASS"></option>
+ <option label="Vendor" value="VENDOR"></option>
+ </select>
+ <select id="transfer-recipient">
+ <option label="Device" value="DEVICE"></option>
+ <option label="Interface" value="INTERFACE"></option>
+ <option label="Endpoint" value="ENDPOINT"></option>
+ <option label="Other" value="OTHER"></option>
+ </select>
+ </td>
+ <td><input id="query-request" type="number" placeholder="0"></td>
+ <td><input id="query-value" type="number" placeholder="0"></td>
+ <td><input id="query-index" type="number" placeholder="0"></td>
+ <td><input id="query-length" type="number" placeholder="0"></td>
+ <td><button>Send</button></td>
+ </tr>
+ <tr hidden>
+ <td>0x<input id="query-request-type" placeholder="00"></td>
+ <td>0x<input id="query-request" placeholder="00"></td>
+ <td>0x<input id="query-value" placeholder="0000"></td>
+ <td>0x<input id="query-index" placeholder="0000"></td>
+ <td>0x<input id="query-length" placeholder="0000"></td>
+ <td><button>Send</button></td>
+ </tr>
+ </tbody>
+ </table>
+ <div id="data-input-area">
+ Data (in Hex):
+ <textarea cols="31"></textarea>
+ </div>
+ </div>
</tabpanel>
</template>
<template id="descriptor-panel-template">
<descriptorpanel>
- <tree id="raw-data-tree-view"></tree>
- <div id="raw-data-byte-view"></div>
+ <tree class="raw-data-tree-view"></tree>
+ <div class="raw-data-byte-view"></div>
</descriptorpanel>
</template>
@@ -188,10 +248,6 @@
<button>GET</button>
</template>
- <template id="error">
- <error></error>
- </template>
-
<template id="descriptor-panel-title">
<descriptorpaneltitle></descriptorpaneltitle>
</template>
diff --git a/chromium/chrome/browser/resources/user_manager/control_bar.html b/chromium/chrome/browser/resources/user_manager/control_bar.html
index 08b1f572811..ec00b56bc9e 100644
--- a/chromium/chrome/browser/resources/user_manager/control_bar.html
+++ b/chromium/chrome/browser/resources/user_manager/control_bar.html
@@ -3,13 +3,14 @@
<link rel="import" href="/profile_browser_proxy.html">
<link rel="import" href="/shared_styles.html">
<link rel="import" href="/strings.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<dom-module id="control-bar">
<template>
- <style include="shared-styles iron-flex iron-flex-alignment iron-positioning">
+ <style include="shared-styles iron-flex iron-flex-alignment
+ iron-positioning">
#container {
align-items: center;
min-height: 32px;
@@ -24,17 +25,16 @@
user-select: none;
}
- paper-button + paper-button {
+ cr-button + cr-button {
margin-inline-start: 8px;
}
</style>
<div id="container" class="layout horizontal end-justified">
<div id="logo" class="product-logo" alt=""></div>
- <paper-button id="launchGuest"
- on-tap="onLaunchGuestTap_"
- hidden="[[!showGuest]]">$i18n{browseAsGuest}</paper-button>
- <paper-button id="addUser" on-tap="onAddUserTap_"
- hidden="[[!showAddPerson]]">$i18n{addUser}</paper-button>
+ <cr-button id="launchGuest" on-click="onLaunchGuestTap_"
+ hidden="[[!showGuest]]">$i18n{browseAsGuest}</cr-button>
+ <cr-button id="addUser" on-click="onAddUserTap_"
+ hidden="[[!showAddPerson]]">$i18n{addUser}</cr-button>
</div>
</template>
<script src="control_bar.js"></script>
diff --git a/chromium/chrome/browser/resources/user_manager/create_profile.html b/chromium/chrome/browser/resources/user_manager/create_profile.html
index 8dd775543f9..f7f2e767768 100644
--- a/chromium/chrome/browser/resources/user_manager/create_profile.html
+++ b/chromium/chrome/browser/resources/user_manager/create_profile.html
@@ -2,6 +2,7 @@
<link rel="import" href="/profile_browser_proxy.html">
<link rel="import" href="/shared_styles.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html">
<link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html">
<link rel="import" href="chrome://resources/cr_elements/cr_profile_avatar_selector/cr_profile_avatar_selector.html">
@@ -10,17 +11,15 @@
<link rel="import" href="chrome://resources/html/action_link.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner-lite.html">
<dom-module id="create-profile">
<template>
- <style
- include="shared-styles iron-positioning md-select">
+ <style include="shared-styles iron-positioning md-select">
:host {
align-self: center;
}
@@ -48,10 +47,12 @@
visibility: hidden;
}
- :host-context([dark]) #message-container {
- background-color: unset;
- border-bottom: var(--cr-separator-line);
- box-shadow: none;
+ @media (prefers-color-scheme: dark) {
+ #message-container {
+ background-color: unset;
+ border-bottom: var(--cr-separator-line);
+ box-shadow: none;
+ }
}
#message-container[visible] {
@@ -82,9 +83,7 @@
#nameInput {
--cr-input-color: var(--cr-primary-text-color);
- --cr-input-input: {
- border-bottom: 1px solid var(--cr-secondary-text-color);
- }
+ --cr-input-border-bottom: 1px solid var(--cr-secondary-text-color);
margin-bottom: 24px;
margin-top: 32px;
width: 300px;
@@ -127,6 +126,7 @@
<div class="container">
<div id="title-bar">$i18n{createProfileTitle}</div>
<cr-input id="nameInput" value="{{profileName_}}" pattern=".*\S.*"
+ placeholder="$i18n{createProfileNamePlaceholder}"
auto-validate spellcheck="false">
</cr-input>
<cr-profile-avatar-selector avatars="[[availableIcons_]]"
@@ -139,14 +139,13 @@
<div id="actions">
<paper-spinner-lite active="[[isSpinnerActive_(createInProgress_)]]">
</paper-spinner-lite>
- <paper-button id="cancel" class="cancel-button"
- on-tap="onCancelTap_">
+ <cr-button id="cancel" class="cancel-button" on-click="onCancelTap_">
$i18n{cancel}
- </paper-button>
- <paper-button id="save" class="action-button" on-tap="onSaveTap_"
+ </cr-button>
+ <cr-button id="save" class="action-button" on-click="onSaveTap_"
disabled="[[isSaveDisabled_(createInProgress_, profileName_)]]">
$i18n{createProfileConfirm}
- </paper-button>
+ </cr-button>
</div>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/user_manager/create_profile.js b/chromium/chrome/browser/resources/user_manager/create_profile.js
index 3ddd8cec635..24aa9d51403 100644
--- a/chromium/chrome/browser/resources/user_manager/create_profile.js
+++ b/chromium/chrome/browser/resources/user_manager/create_profile.js
@@ -103,8 +103,6 @@ Polymer({
this.addWebUIListener('profile-icons-received', icons => {
this.availableIcons_ = icons;
});
- this.addWebUIListener(
- 'profile-defaults-received', this.handleProfileDefaults_.bind(this));
this.browserProxy_.getAvailableIcons();
},
@@ -136,15 +134,6 @@ Polymer({
},
/**
- * Handler for when the profile defaults are pushed from the browser.
- * @param {!ProfileInfo} profileInfo Default Info for the new profile.
- * @private
- */
- handleProfileDefaults_: function(profileInfo) {
- this.profileName_ = profileInfo.name;
- },
-
- /**
* Handler for the 'Save' button tap event.
* @param {!Event} event
* @private
diff --git a/chromium/chrome/browser/resources/user_manager/shared_styles.html b/chromium/chrome/browser/resources/user_manager/shared_styles.html
index 6c729aa7d25..3bc6fc49a49 100644
--- a/chromium/chrome/browser/resources/user_manager/shared_styles.html
+++ b/chromium/chrome/browser/resources/user_manager/shared_styles.html
@@ -1,10 +1,9 @@
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<dom-module id="shared-styles">
<template>
- <style include="paper-button-style">
+ <style>
html,
:host {
--error-color: var(--google-red-700);
@@ -13,10 +12,12 @@
--user-manager-separator-line: 1px solid rgba(0, 0, 0, .12);
}
- html[dark],
- :host-context([dark]) {
- --error-color: var(--google-red-refresh-300);
- --user-manager-separator-line: var(--cr-separator-line);
+ @media (prefers-color-scheme: dark) {
+ html,
+ :host {
+ --error-color: var(--google-red-refresh-300);
+ --user-manager-separator-line: var(--cr-separator-line);
+ }
}
a,
@@ -35,10 +36,12 @@
height: 22px;
}
- :host-context([dark]) .product-logo {
- content: -webkit-image-set(
- url(../../../app/theme/default_100_percent/%DISTRIBUTION%/product_logo_white.png) 1x,
- url(../../../app/theme/default_200_percent/%DISTRIBUTION%/product_logo_white.png) 2x);
+ @media (prefers-color-scheme: dark) {
+ .product-logo {
+ content: -webkit-image-set(
+ url(../../../app/theme/default_100_percent/%DISTRIBUTION%/product_logo_white.png) 1x,
+ url(../../../app/theme/default_200_percent/%DISTRIBUTION%/product_logo_white.png) 2x);
+ }
}
</style>
</template>
diff --git a/chromium/chrome/browser/resources/user_manager/user_manager.html b/chromium/chrome/browser/resources/user_manager/user_manager.html
index 43c8ecd46ac..77561990e0d 100644
--- a/chromium/chrome/browser/resources/user_manager/user_manager.html
+++ b/chromium/chrome/browser/resources/user_manager/user_manager.html
@@ -2,8 +2,7 @@
<html build="$i18n{buildType}"
dir="$i18n{textdirection}"
lang="$i18n{language}"
- screen="$i18n{screenType}"
- $i18n{dark}>
+ screen="$i18n{screenType}">
<head>
<meta charset="utf-8">
<meta name="google" value="notranslate">
@@ -24,6 +23,8 @@
<link rel="import" href="/strings.html">
<link rel="import" href="/user_manager_pages.html">
<link rel="import" href="/user_manager_tutorial.html">
+ <!-- Make sure cr-button is imported to use in user_pod_template.html -->
+ <link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/html/cr/ui.html">
<link rel="import" href="chrome://resources/html/util.html">
<!-- Make sure iron-icon and cr iconset are imported to use in
@@ -31,12 +32,12 @@
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
- <!-- Make sure paper-button is imported to use in user_pod_template.html -->
- <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<custom-style>
<style is="custom-style" include="shared-styles">
- html[dark] body {
- background-color: var(--google-grey-900);
+ @media (prefers-color-scheme: dark) {
+ body {
+ background-color: var(--google-grey-900);
+ }
}
user-manager-pages,
@@ -147,12 +148,16 @@
width: 92px;
}
- html[dark] .pod .main-pane .name-container {
- background-color: transparent;
+ @media (prefers-color-scheme: dark) {
+ .pod .main-pane .name-container {
+ background-color: transparent;
+ }
}
- html[dark] .name {
- color: inherit;
+ @media (prefers-color-scheme: dark) {
+ .name {
+ color: inherit;
+ }
}
.pod .indicator-container {
@@ -180,8 +185,10 @@
width: 20px;
}
- html[dark] .pod .indicator-container > .indicator {
- background: var(--google-grey-refresh-500);
+ @media (prefers-color-scheme: dark) {
+ .pod .indicator-container > .indicator {
+ background: var(--google-grey-refresh-500);
+ }
}
.pod.locked .locked-indicator {
@@ -286,17 +293,19 @@
right: auto;
}
- html[dark] .action-box-area.active ~ .action-box-menu {
- background-color: var(--cr-menu-background-color);
- /* Adds 4% white on top of GG900. To/from are intentionally the same. */
- background-image: linear-gradient(rgba(255, 255, 255, .04),
- rgba(255, 255, 255, .04));
- box-shadow: var(--cr-menu-shadow);
- }
+ @media (prefers-color-scheme: dark) {
+ .action-box-area.active ~ .action-box-menu {
+ background-color: var(--cr-menu-background-color);
+ /* Adds 4% white on top of GG900. To/from are intentionally the same. */
+ background-image: linear-gradient(rgba(255, 255, 255, .04),
+ rgba(255, 255, 255, .04));
+ box-shadow: var(--cr-menu-shadow);
+ }
- html[dark] .action-box-menu-remove:focus,
- html[dark] .action-box-menu-remove:hover {
- background-color: var(--cr-menu-background-focus-color);
+ .action-box-menu-remove:focus,
+ .action-box-menu-remove:hover {
+ background-color: var(--cr-menu-background-focus-color);
+ }
}
.action-box-menu-title {
@@ -304,8 +313,10 @@
padding: 16px 12px;
}
- html[dark] .action-box-menu-title {
- border-bottom: var(--cr-separator-line);
+ @media (prefers-color-scheme: dark) {
+ .action-box-menu-title {
+ border-bottom: var(--cr-separator-line);
+ }
}
.action-box-menu-title-name,
@@ -330,11 +341,13 @@
padding: var(--vertical-gap) var(--side-gap);
}
- html[dark] .action-box-menu-remove {
- border-radius: 0;
- border-top: none;
- margin: var(--vertical-gap) 0;
- padding: 0 var(--side-gap);
+ @media (prefers-color-scheme: dark) {
+ .action-box-menu-remove {
+ border-radius: 0;
+ border-top: none;
+ margin: var(--vertical-gap) 0;
+ padding: 0 var(--side-gap);
+ }
}
.action-box-remove-user-warning {
@@ -408,6 +421,5 @@
<include src="../../../../ui/login/account_picker/user_pod_template.html">
</user-manager-pages>
<script src="user_manager.js"></script>
- <link rel="import" href="chrome://resources/html/dark_mode.html">
</body>
</html>
diff --git a/chromium/chrome/browser/resources/user_manager/user_manager_tutorial.html b/chromium/chrome/browser/resources/user_manager/user_manager_tutorial.html
index f714e514b4e..bdffe5546ff 100644
--- a/chromium/chrome/browser/resources/user_manager/user_manager_tutorial.html
+++ b/chromium/chrome/browser/resources/user_manager/user_manager_tutorial.html
@@ -1,9 +1,9 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="/shared_styles.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<dom-module id="user-manager-tutorial">
<template>
@@ -104,6 +104,7 @@
border-top: 10px solid transparent;
bottom: -10px;
box-shadow: var(--cr-card-shadow);
+ clip-path: inset(0 0 -5px -5px);
height: 0;
position: absolute;
right: 40px;
@@ -116,10 +117,12 @@
right: auto;
}
- :host-context([dark]) .arrow-down {
- --gg900-blended-with-4percent-white: rgb(40, 41, 44);
- border-bottom-color: var(--gg900-blended-with-4percent-white);
- border-left-color: var(--gg900-blended-with-4percent-white); /* csschecker-disable-line left-right */
+ @media (prefers-color-scheme: dark) {
+ .arrow-down {
+ --gg900-blended-with-4percent-white: rgb(40, 41, 44);
+ border-bottom-color: var(--gg900-blended-with-4percent-white);
+ border-left-color: var(--gg900-blended-with-4percent-white); /* csschecker-disable-line left-right */
+ }
}
#guests .arrow-down {
@@ -160,8 +163,10 @@
url(chrome://theme/IDR_ICON_USER_MANAGER_TUTORIAL_COMPLETE);
}
- :host-context([dark]) #notYou {
- color: var(--cr-primary-text-color);
+ @media (prefers-color-scheme: dark) {
+ #notYou {
+ color: var(--cr-primary-text-color);
+ }
}
#notYou #dismiss {
@@ -171,8 +176,10 @@
top: 5px;
}
- :host-context([dark]) #notYou #dismiss {
- color: var(--google-grey-500);
+ @media (prefers-color-scheme: dark) {
+ #notYou #dismiss {
+ color: var(--google-grey-500);
+ }
}
#notYou #slide-add-user {
@@ -194,9 +201,9 @@
<div class="slide-text">$i18n{slideYourChromeText}</div>
</div>
<div class="slide-buttons">
- <paper-button on-tap="onNextTap_" data-next$="[[steps_.GUESTS]]">
+ <cr-button on-click="onNextClick_" data-next$="[[steps_.GUESTS]]">
$i18n{tutorialNext}
- </paper-button>
+ </cr-button>
</div>
</div>
</template>
@@ -209,9 +216,9 @@
<div class="slide-text">$i18n{slideGuestsText}</div>
</div>
<div class="slide-buttons">
- <paper-button on-tap="onNextTap_" data-next$="[[steps_.FRIENDS]]">
+ <cr-button on-click="onNextClick_" data-next$="[[steps_.FRIENDS]]">
$i18n{tutorialNext}
- </paper-button>
+ </cr-button>
</div>
<div class="arrow-down"></div>
</div>
@@ -225,9 +232,9 @@
<div class="slide-text">$i18n{slideFriendsText}</div>
</div>
<div class="slide-buttons">
- <paper-button on-tap="onNextTap_" data-next$="[[steps_.COMPLETE]]">
+ <cr-button on-click="onNextClick_" data-next$="[[steps_.COMPLETE]]">
$i18n{tutorialNext}
- </paper-button>
+ </cr-button>
</div>
<div class="arrow-down"></div>
</div>
@@ -241,9 +248,9 @@
<div class="slide-text">$i18n{slideCompleteText}</div>
</div>
<div class="slide-buttons">
- <paper-button on-tap="onNextTap_" data-next$="[[steps_.NOT_YOU]]">
+ <cr-button on-click="onNextClick_" data-next$="[[steps_.NOT_YOU]]">
$i18n{tutorialDone}
- </paper-button>
+ </cr-button>
</div>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/user_manager/user_manager_tutorial.js b/chromium/chrome/browser/resources/user_manager/user_manager_tutorial.js
index d365ca5b925..8fb553fc566 100644
--- a/chromium/chrome/browser/resources/user_manager/user_manager_tutorial.js
+++ b/chromium/chrome/browser/resources/user_manager/user_manager_tutorial.js
@@ -55,9 +55,9 @@ Polymer({
* @param {!Event} event
* @private
*/
- onNextTap_: function(event) {
- const element = Polymer.dom(event).rootTarget;
- this.currentStep_ = element.dataset.next;
+ onNextClick_: function(event) {
+ this.currentStep_ =
+ event.composedPath().find(e => e.tagName == 'CR-BUTTON').dataset.next;
},
/**
diff --git a/chromium/chrome/browser/resources/webapks/BUILD.gn b/chromium/chrome/browser/resources/webapks/BUILD.gn
index 2b91364a254..6e4c0a57cda 100644
--- a/chromium/chrome/browser/resources/webapks/BUILD.gn
+++ b/chromium/chrome/browser/resources/webapks/BUILD.gn
@@ -12,7 +12,9 @@ js_type_check("closure_compile") {
js_library("about_webapks") {
deps = [
- "../../../../ui/webui/resources/js:util",
+ "//ui/webui/resources/js:cr",
+ "//ui/webui/resources/js:load_time_data",
+ "//ui/webui/resources/js:util",
]
externs_list = [ "$externs_path/chrome_send.js" ]
}
diff --git a/chromium/chrome/browser/resources/webapks/about_webapks.html b/chromium/chrome/browser/resources/webapks/about_webapks.html
index fb87afd543c..f09ce2c5d08 100644
--- a/chromium/chrome/browser/resources/webapks/about_webapks.html
+++ b/chromium/chrome/browser/resources/webapks/about_webapks.html
@@ -11,11 +11,10 @@ about:webapks template page
<title>About WebAPKs</title>
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
<link rel="stylesheet" href="about_webapks.css">
+ <link rel="import" href="chrome://resources/html/cr.html">
+ <link rel="import" href="chrome://resources/html/load_time_data.html">
+ <link rel="import" href="chrome://resources/html/util.html">
- <script src="chrome://resources/js/cr.js"></script>
- <script src="chrome://resources/js/load_time_data.js"></script>
- <script src="chrome://resources/js/parse_html_subset.js"></script>
- <script src="chrome://resources/js/util.js"></script>
<script src="chrome://webapks/webapks.js"></script>
<script src="chrome://webapks/strings.js"></script>
</head>
diff --git a/chromium/chrome/browser/resources/webapks/about_webapks.js b/chromium/chrome/browser/resources/webapks/about_webapks.js
index 2be657652b1..b21be02901e 100644
--- a/chromium/chrome/browser/resources/webapks/about_webapks.js
+++ b/chromium/chrome/browser/resources/webapks/about_webapks.js
@@ -7,6 +7,7 @@
* name: string,
* shortName: string,
* packageName: string,
+ * id: string,
* shellApkVersion: number,
* versionCode: number,
* uri: string,
@@ -18,12 +19,26 @@
* themeColor: string,
* backgroundColor: string,
* lastUpdateCheckTimeMs: number,
+ * lastUpdateCompletionTimeMs: number,
* relaxUpdates: boolean,
+ * backingBrowser: string,
+ * isBackingBrowser: boolean,
+ * updateStatus: string,
* }}
*/
let WebApkInfo;
/**
+ * @typedef {{
+ * id: string,
+ * status: string,
+ * }}
+ */
+let UpdateStatus;
+
+const UPDATE_TIMEOUT = 60 * 1000; // milliseconds.
+
+/**
* Creates and returns an element (with |text| as content) assigning it the
* |className| class.
*
@@ -40,16 +55,13 @@ function createElementWithTextAndClass(text, type, className) {
/**
* Callback from the backend with the information of a WebAPK to display.
- * This will be called once for each WebAPK available on the device and each
- * one will be appended at the end of the other.
+ * This will be called once per WebAPK.
*
- * @param {!Array<WebApkInfo>} webApkList List of objects with information about
- * WebAPKs installed.
+ * @param {!WebApkInfo} webApkInfo Object with information about an
+ * installed WebAPK.
*/
-function returnWebApksInfo(webApkList) {
- for (const webApkInfo of webApkList) {
- addWebApk(webApkInfo);
- }
+function returnWebApkInfo(webApkInfo) {
+ addWebApk(webApkInfo);
}
/**
@@ -67,6 +79,21 @@ function addWebApkField(webApkList, label, value) {
}
/**
+ * @param {HTMLElement} webApkList List of elements which contain WebAPK
+ * attributes.
+ * @param {string} text For the button.
+ * @param {function()} callback Invoked on click.
+ * @return {Element} The button that was created.
+ */
+function addWebApkButton(webApkList, text, callback) {
+ const divElement =
+ createElementWithTextAndClass(text, 'button', 'update-button');
+ divElement.onclick = callback;
+ webApkList.appendChild(divElement);
+ return divElement;
+}
+
+/**
* Adds a new entry to the page with the information of a WebAPK.
*
* @param {WebApkInfo} webApkInfo Information about an installed WebAPK.
@@ -98,8 +125,38 @@ function addWebApk(webApkInfo) {
webApkList, 'Last Update Check Time: ',
new Date(webApkInfo.lastUpdateCheckTimeMs).toString());
addWebApkField(
+ webApkList, 'Last Update Completion Time: ',
+ new Date(webApkInfo.lastUpdateCompletionTimeMs).toString());
+ addWebApkField(
webApkList, 'Check for Updates Less Frequently: ',
webApkInfo.relaxUpdates.toString());
+ addWebApkField(webApkList, 'Owning Browser: ', webApkInfo.backingBrowser);
+ addWebApkField(webApkList, 'Update Status: ', webApkInfo.updateStatus);
+
+ // TODO(ckitagawa): Convert to an enum using mojom handlers.
+ if (webApkInfo.updateStatus == 'Not updatable' ||
+ !webApkInfo.isBackingBrowser) {
+ return;
+ }
+
+ const buttonElement =
+ addWebApkButton(webApkList, 'Update ' + webApkInfo.name, () => {
+ alert(
+ 'The WebAPK will check for an update the next time it launches. ' +
+ 'If an update is available, the "Update Status" on this page ' +
+ 'will switch to "Scheduled". The update will be installed once ' +
+ 'the WebAPK is closed (this may take a few minutes).');
+ chrome.send('requestWebApkUpdate', [webApkInfo.id]);
+ });
+
+ // Prevent updates in the WebAPK server caching window as they will fail.
+ const msSinceLastUpdate = Date.now() - webApkInfo.lastUpdateCompletionTimeMs;
+ if (msSinceLastUpdate < UPDATE_TIMEOUT) {
+ buttonElement.disabled = true;
+ window.setTimeout(() => {
+ buttonElement.disabled = false;
+ }, UPDATE_TIMEOUT - msSinceLastUpdate);
+ }
}
document.addEventListener('DOMContentLoaded', function() {
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/BUILD.gn b/chromium/chrome/browser/resources/welcome/BUILD.gn
index c817f1fde8a..ad2a0c5b1a2 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/BUILD.gn
+++ b/chromium/chrome/browser/resources/welcome/BUILD.gn
@@ -67,7 +67,6 @@ js_library("welcome_app") {
"./shared:nux_types",
"//ui/webui/resources/cr_elements/cr_view_manager:cr_view_manager",
"//ui/webui/resources/js:load_time_data",
- "//ui/webui/resources/js:promise_resolver",
]
}
diff --git a/chromium/chrome/browser/resources/welcome/default.webp b/chromium/chrome/browser/resources/welcome/default.webp
deleted file mode 100644
index eb75d055893..00000000000
--- a/chromium/chrome/browser/resources/welcome/default.webp
+++ /dev/null
Binary files differ
diff --git a/chromium/chrome/browser/resources/welcome/dice_welcome/BUILD.gn b/chromium/chrome/browser/resources/welcome/dice_welcome/BUILD.gn
deleted file mode 100644
index fd1472df2d5..00000000000
--- a/chromium/chrome/browser/resources/welcome/dice_welcome/BUILD.gn
+++ /dev/null
@@ -1,27 +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("//third_party/closure_compiler/compile_js.gni")
-
-js_type_check("closure_compile") {
- deps = [
- ":welcome_app",
- ":welcome_browser_proxy",
- ]
-}
-
-js_library("welcome_app") {
- deps = [
- ":welcome_browser_proxy",
- "//ui/webui/resources/js:cr",
- ]
- externs_list = [ "$externs_path/web_animations.js" ]
-}
-
-js_library("welcome_browser_proxy") {
- deps = [
- "//ui/webui/resources/js:cr",
- ]
- externs_list = [ "$externs_path/chrome_send.js" ]
-}
diff --git a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome.css b/chromium/chrome/browser/resources/welcome/dice_welcome/welcome.css
deleted file mode 100644
index e3641d8dc6c..00000000000
--- a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome.css
+++ /dev/null
@@ -1,42 +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. */
-
-body {
- align-items: center;
- color: var(--google-grey-700);
- display: flex;
- flex-direction: column;
- font-size: 100%;
- justify-content: center;
- margin: 0;
- min-height: 100vh;
- text-align: center;
-}
-
-[dark] body {
- background: var(--md-background-color);
- color: var(--cr-secondary-text-color);
-}
-
-.watermark {
- -webkit-mask-image: url(chrome://resources/images/google_logo.svg);
- -webkit-mask-repeat: no-repeat;
- -webkit-mask-size: 100%;
- animation: fadeIn 1s cubic-bezier(0, 0, .2, 1) both;
- background: var(--paper-grey-400);
- bottom: 24px;
- height: 24px;
- position: absolute;
- width: 74px;
-}
-
-[dark] .watermark {
- background: var(--cr-secondary-text-color);
-}
-
-@media(max-height: 608px) {
- .watermark {
- display: none;
- }
-}
diff --git a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome.html b/chromium/chrome/browser/resources/welcome/dice_welcome/welcome.html
deleted file mode 100644
index f9fc786f18a..00000000000
--- a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome.html
+++ /dev/null
@@ -1,22 +0,0 @@
-<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}>
- <head>
- <meta charset="utf-8">
- <title>$i18n{headerText}</title>
-
- <link rel="import" href="chrome://resources/html/polymer.html">
-
- <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
- <link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
- <link rel="import" href="welcome_app.html">
-
- <link rel="stylesheet" href="chrome://resources/css/md_colors.css">
- <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
- <link rel="stylesheet" href="chrome://welcome/welcome.css">
- </head>
- <body>
- <welcome-app></welcome-app>
- <div class="watermark"></div>
- <link rel="import" href="chrome://resources/html/dark_mode.html">
- </body>
-</html>
diff --git a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome_app.html b/chromium/chrome/browser/resources/welcome/dice_welcome/welcome_app.html
deleted file mode 100644
index 6dc83f14f0f..00000000000
--- a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome_app.html
+++ /dev/null
@@ -1,181 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
-<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
-<link rel="import" href="welcome_browser_proxy.html">
-
-<dom-module id="welcome-app">
- <template>
- <style include="paper-button-style">
- @keyframes slideUpContent {
- from {
- transform: translateY(120px);
- }
- }
-
- @keyframes fadeIn {
- from {
- opacity: 0;
- }
- }
-
- @keyframes fadeInAndSlideUp {
- from {
- opacity: 0;
- transform: translateY(8px);
- }
- }
-
- @keyframes fadeOutAndSlideUp {
- to {
- height: 0;
- opacity: 0;
- transform: translateY(-8px);
- }
- }
-
- @keyframes spin {
- from {
- transform: rotate(1440deg) scale(0.8);
- }
- }
-
- @keyframes colorize {
- from {
- filter: grayscale(100%) brightness(128%) contrast(20%) brightness(161%);
- opacity: .6;
- }
- }
-
- @keyframes bounce {
- 0% {
- transform: matrix3d(0.8, 0, 0, 0, 0, 0.8, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 7.61% {
- transform: matrix3d(0.907, 0, 0, 0, 0, 0.907, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 11.41% {
- transform: matrix3d(0.948, 0, 0, 0, 0, 0.948, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 15.12% {
- transform: matrix3d(0.976, 0, 0, 0, 0, 0.976, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 18.92% {
- transform: matrix3d(0.996, 0, 0, 0, 0, 0.996, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 22.72% {
- transform: matrix3d(1.008, 0, 0, 0, 0, 1.008, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 30.23% {
- transform: matrix3d(1.014, 0, 0, 0, 0, 1.014, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 50.25% {
- transform: matrix3d(1.003, 0, 0, 0, 0, 1.003, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 70.27% {
- transform: matrix3d(0.999, 0, 0, 0, 0, 0.999, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 100% {
- transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- }
-
- .slider {
- align-items: center;
- animation: slideUpContent 600ms 2.5s cubic-bezier(.4, .2, 0, 1) both;
- display: flex;
- flex: 1;
- flex-direction: column;
- justify-content: center;
- max-width: 500px;
- }
-
- .heading-container {
- animation: fadeInAndSlideUp 1s 400ms cubic-bezier(.4, .2, 0, 1) both;
- color: var(--paper-grey-800);
- font-size: 2.5em;
- line-height: 1em;
- margin-bottom: 0.25em;
- margin-top: 1.5em;
- position: relative;
- }
-
- :host-context([dark]) .heading-container {
- color: var(--cr-primary-text-color);
- }
-
- .heading {
- animation: fadeOutAndSlideUp 600ms 2.1s cubic-bezier(.4, .2, 0, 1) forwards;
- /* Makes sure fading-in/out doesn't impact the logo position. */
- position: absolute;
- }
-
- .second-heading {
- animation: fadeInAndSlideUp 600ms 2.5s cubic-bezier(.4, .2, 0, 1) both;
- font-size: 0.6em;
- }
-
- #logoWrapper {
- animation: fadeIn 600ms both, bounce 1s 600ms linear both;
- height: 96px;
- position: relative;
- width: 96px;
- }
-
- #logo {
- animation: spin 2.4s cubic-bezier(.4, .2, 0, 1) both,
- colorize 300ms 700ms linear both;
- background-image: -webkit-image-set(url(chrome://welcome/logo.png) 1x,
- url(chrome://welcome/logo2x.png) 2x);
- background-size: 100%;
- height: 96px;
- width: 96px;
- }
-
- .signin {
- animation: fadeInAndSlideUp 600ms 2.5s cubic-bezier(.4, .2, 0, 1) both;
- }
-
- .signin-description {
- font-size: 1em;
- line-height: 1.725em;
- max-width: 344px;
- }
-
- .signin-buttons {
- align-items: center;
- display: flex;
- font-size: .8125em;
- justify-content: space-between;
- margin-top: 2.5em;
- }
-
- paper-button {
- min-width: 92px;
- }
- </style>
- <div class="slider">
- <div id="logoWrapper">
- <div id="logo" on-tap="onLogoTap_"></div>
- </div>
- <div class="heading-container">
- <div class="heading">$i18n{headerText}</div>
- <div class="second-heading">$i18n{secondHeaderText}</div>
- </div>
- <div class="signin">
- <div class="signin-description">$i18n{descriptionText}</div>
- <div class="signin-buttons">
- <paper-button on-tap="onDecline_">
- $i18n{declineText}
- </paper-button>
- <paper-button class="action-button" on-tap="onAccept_">
- $i18n{acceptText}
- </paper-button>
- </div>
- </div>
- </div>
- </template>
- <script src="welcome_app.js"></script>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome_app.js b/chromium/chrome/browser/resources/welcome/dice_welcome/welcome_app.js
deleted file mode 100644
index 8b663ea5f91..00000000000
--- a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome_app.js
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-Polymer({
- is: 'welcome-app',
-
- welcomeBrowserProxy_: null,
-
- /** @override */
- ready: function() {
- this.welcomeBrowserProxy_ = welcome.WelcomeBrowserProxyImpl.getInstance();
- },
-
- /** @private */
- onAccept_: function() {
- this.welcomeBrowserProxy_.handleActivateSignIn();
- },
-
- /** @private */
- onDecline_: function() {
- this.welcomeBrowserProxy_.handleUserDecline();
- },
-
- /** @private */
- onLogoTap_: function() {
- this.$.logo.animate(
- {
- transform: ['none', 'rotate(-10turn)'],
- },
- /** @type {!KeyframeEffectOptions} */ ({
- duration: 500,
- easing: 'cubic-bezier(1, 0, 0, 1)',
- }));
- },
-});
diff --git a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome_browser_proxy.js b/chromium/chrome/browser/resources/welcome/dice_welcome/welcome_browser_proxy.js
deleted file mode 100644
index 9511779ccfb..00000000000
--- a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome_browser_proxy.js
+++ /dev/null
@@ -1,37 +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.
-
-/**
- * @fileoverview A helper object used by the welcome page to interact with
- * the browser.
- */
-
-cr.define('welcome', function() {
-
- /** @interface */
- class WelcomeBrowserProxy {
- handleActivateSignIn() {}
- handleUserDecline() {}
- }
-
- /** @implements {welcome.WelcomeBrowserProxy} */
- class WelcomeBrowserProxyImpl {
- /** @override */
- handleActivateSignIn() {
- chrome.send('handleActivateSignIn');
- }
-
- /** @override */
- handleUserDecline() {
- chrome.send('handleUserDecline');
- }
- }
-
- cr.addSingletonGetter(WelcomeBrowserProxyImpl);
-
- return {
- WelcomeBrowserProxy: WelcomeBrowserProxy,
- WelcomeBrowserProxyImpl: WelcomeBrowserProxyImpl,
- };
-});
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/BUILD.gn b/chromium/chrome/browser/resources/welcome/google_apps/BUILD.gn
index d9032151c75..6566c5e490b 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/BUILD.gn
+++ b/chromium/chrome/browser/resources/welcome/google_apps/BUILD.gn
@@ -6,6 +6,8 @@ import("//third_party/closure_compiler/compile_js.gni")
js_type_check("closure_compile") {
deps = [
+ ":google_app_proxy",
+ ":google_apps_metrics_proxy",
":nux_google_apps",
]
}
@@ -13,9 +15,9 @@ js_type_check("closure_compile") {
js_library("nux_google_apps") {
deps = [
":google_app_proxy",
+ ":google_apps_metrics_proxy",
"../:navigation_behavior",
"../shared:bookmark_proxy",
- "../shared:module_metrics_proxy",
"../shared:nux_types",
"../shared:step_indicator",
"//third_party/polymer/v1_0/components-chromium/iron-a11y-announcer:iron-a11y-announcer-extracted",
@@ -27,8 +29,13 @@ js_library("nux_google_apps") {
js_library("google_app_proxy") {
deps = [
- "../shared:app_proxy",
"//ui/webui/resources/js:cr",
]
externs_list = [ "$externs_path/chrome_send.js" ]
}
+
+js_library("google_apps_metrics_proxy") {
+ deps = [
+ "../shared:module_metrics_proxy",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_app_proxy.html b/chromium/chrome/browser/resources/welcome/google_apps/google_app_proxy.html
index 88d70dd927f..3c50ce8ea88 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_app_proxy.html
+++ b/chromium/chrome/browser/resources/welcome/google_apps/google_app_proxy.html
@@ -1,3 +1,2 @@
<link rel="import" href="chrome://resources/html/cr.html">
-<link rel="import" href="chrome://welcome/shared/i18n_setup.html">
<script src="google_app_proxy.js"></script>
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_app_proxy.js b/chromium/chrome/browser/resources/welcome/google_apps/google_app_proxy.js
index fb620e6eb13..b4edc677e8a 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/google_app_proxy.js
+++ b/chromium/chrome/browser/resources/welcome/google_apps/google_app_proxy.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.define('nux', function() {
+cr.define('welcome', function() {
/**
* NuxGoogleAppsSelections enum.
* These values are persisted to logs and should not be renumbered or
@@ -19,7 +19,29 @@ cr.define('nux', function() {
CHROME_WEB_STORE: 5,
};
- /** @implements {nux.AppProxy} */
+ /** @interface */
+ class GoogleAppProxy {
+ /**
+ * Google app IDs are local to the list of Google apps, so their icon must
+ * be cached by the handler that provided the IDs.
+ * @param {number} appId
+ */
+ cacheBookmarkIcon(appId) {}
+
+ /**
+ * Returns a promise for an array of Google apps.
+ * @return {!Promise<!Array<!welcome.BookmarkListItem>>}
+ */
+ getAppList() {}
+
+ /**
+ * @param {number} providerId This should match one of the histogram enum
+ * value for NuxGoogleAppsSelections.
+ */
+ recordProviderSelected(providerId) {}
+ }
+
+ /** @implements {welcome.GoogleAppProxy} */
class GoogleAppProxyImpl {
/** @override */
cacheBookmarkIcon(appId) {
@@ -42,6 +64,7 @@ cr.define('nux', function() {
cr.addSingletonGetter(GoogleAppProxyImpl);
return {
+ GoogleAppProxy: GoogleAppProxy,
GoogleAppProxyImpl: GoogleAppProxyImpl,
};
});
diff --git a/chromium/chrome/browser/resources/welcome/google_apps/google_apps_metrics_proxy.html b/chromium/chrome/browser/resources/welcome/google_apps/google_apps_metrics_proxy.html
new file mode 100644
index 00000000000..222483c7329
--- /dev/null
+++ b/chromium/chrome/browser/resources/welcome/google_apps/google_apps_metrics_proxy.html
@@ -0,0 +1,3 @@
+<link rel="import" href="chrome://resources/html/cr.html">
+<link rel="import" href="../shared/module_metrics_proxy.html">
+<script src="google_apps_metrics_proxy.js"></script>
diff --git a/chromium/chrome/browser/resources/welcome/google_apps/google_apps_metrics_proxy.js b/chromium/chrome/browser/resources/welcome/google_apps/google_apps_metrics_proxy.js
new file mode 100644
index 00000000000..77886462fcd
--- /dev/null
+++ b/chromium/chrome/browser/resources/welcome/google_apps/google_apps_metrics_proxy.js
@@ -0,0 +1,19 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+cr.define('welcome', function() {
+ class GoogleAppsMetricsProxyImpl extends welcome.ModuleMetricsProxyImpl {
+ constructor() {
+ super(
+ 'FirstRun.NewUserExperience.GoogleAppsInteraction',
+ welcome.NuxGoogleAppsInteractions);
+ }
+ }
+
+ cr.addSingletonGetter(GoogleAppsMetricsProxyImpl);
+
+ return {
+ GoogleAppsMetricsProxyImpl: GoogleAppsMetricsProxyImpl,
+ };
+});
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.html b/chromium/chrome/browser/resources/welcome/google_apps/nux_google_apps.html
index 4416a947e2f..a5d31e14e95 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.html
+++ b/chromium/chrome/browser/resources/welcome/google_apps/nux_google_apps.html
@@ -1,26 +1,25 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-a11y-announcer/iron-a11y-announcer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../navigation_behavior.html">
<link rel="import" href="../shared/animations_css.html">
<link rel="import" href="../shared/bookmark_proxy.html">
<link rel="import" href="../shared/chooser_shared_css.html">
<link rel="import" href="../shared/i18n_setup.html">
-<link rel="import" href="../shared/module_metrics_proxy.html">
<link rel="import" href="../shared/step_indicator.html">
<link rel="import" href="google_app_proxy.html">
+<link rel="import" href="google_apps_metrics_proxy.html">
<dom-module id="nux-google-apps">
<template>
- <style include="animations chooser-shared-css paper-button-style">
+ <style include="animations chooser-shared-css">
.apps-ask {
text-align: center;
}
@@ -33,8 +32,10 @@
width: 42px;
}
- :host-context([dark]) .chrome-logo {
- content: url(../images/module_icons/google_dark.svg);
+ @media (prefers-color-scheme: dark) {
+ .chrome-logo {
+ content: url(../images/module_icons/google_dark.svg);
+ }
}
h1 {
@@ -196,15 +197,15 @@
</div>
<div class="button-bar">
- <paper-button id="noThanksButton" on-click="onNoThanksClicked_">
+ <cr-button id="noThanksButton" on-click="onNoThanksClicked_">
$i18n{skip}
- </paper-button>
+ </cr-button>
<step-indicator model="[[indicatorModel]]"></step-indicator>
- <paper-button class="action-button" disabled$="[[!hasAppsSelected_]]"
+ <cr-button class="action-button" disabled$="[[!hasAppsSelected_]]"
on-click="onGetStartedClicked_">
$i18n{next}
<iron-icon icon="cr:chevron-right"></iron-icon>
- </paper-button>
+ </cr-button>
</div>
</div>
</div>
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.js b/chromium/chrome/browser/resources/welcome/google_apps/nux_google_apps.js
index 2ed67e53333..8452574c807 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.js
+++ b/chromium/chrome/browser/resources/welcome/google_apps/nux_google_apps.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.exportPath('nux');
+cr.exportPath('welcome');
/**
* @typedef {{
@@ -14,15 +14,15 @@ cr.exportPath('nux');
* selected: boolean,
* }}
*/
-nux.AppItem;
+welcome.AppItem;
/**
* @typedef {{
- * item: !nux.AppItem,
+ * item: !welcome.AppItem,
* set: function(string, boolean):void
* }}
*/
-nux.AppItemModel;
+welcome.AppItemModel;
const KEYBOARD_FOCUSED = 'keyboard-focused';
@@ -32,11 +32,11 @@ Polymer({
behaviors: [welcome.NavigationBehavior, I18nBehavior],
properties: {
- /** @type {nux.stepIndicatorModel} */
+ /** @type {welcome.stepIndicatorModel} */
indicatorModel: Object,
/**
- * @type {!Array<!nux.AppItem>}
+ * @type {!Array<!welcome.AppItem>}
* @private
*/
appList_: Array,
@@ -48,19 +48,19 @@ Polymer({
},
},
- /** @private {nux.AppProxy} */
+ /** @private {welcome.GoogleAppProxy} */
appProxy_: null,
- /** @private {?nux.ModuleMetricsManager} */
+ /** @private {?welcome.ModuleMetricsManager} */
metricsManager_: null,
/** @private */
finalized_: false,
- /** @private {nux.BookmarkProxy} */
+ /** @private {welcome.BookmarkProxy} */
bookmarkProxy_: null,
- /** @private {nux.BookmarkBarManager} */
+ /** @private {welcome.BookmarkBarManager} */
bookmarkBarManager_: null,
/** @private {boolean} */
@@ -68,11 +68,11 @@ Polymer({
/** @override */
ready: function() {
- this.appProxy_ = nux.GoogleAppProxyImpl.getInstance();
- this.metricsManager_ = new nux.ModuleMetricsManager(
- nux.GoogleAppsMetricsProxyImpl.getInstance());
- this.bookmarkProxy_ = nux.BookmarkProxyImpl.getInstance();
- this.bookmarkBarManager_ = nux.BookmarkBarManager.getInstance();
+ this.appProxy_ = welcome.GoogleAppProxyImpl.getInstance();
+ this.metricsManager_ = new welcome.ModuleMetricsManager(
+ welcome.GoogleAppsMetricsProxyImpl.getInstance());
+ this.bookmarkProxy_ = welcome.BookmarkProxyImpl.getInstance();
+ this.bookmarkBarManager_ = welcome.BookmarkBarManager.getInstance();
},
/** @override */
@@ -164,7 +164,7 @@ Polymer({
/**
* Handle toggling the apps selected.
- * @param {!{model: !nux.AppItemModel}} e
+ * @param {!{model: !welcome.AppItemModel}} e
* @private
*/
onAppClick_: function(e) {
@@ -235,7 +235,7 @@ Polymer({
this.appList_.forEach(app => this.updateBookmark_(app));
} else {
this.appProxy_.getAppList().then(list => {
- this.appList_ = /** @type(!Array<!nux.AppItem>) */ (list);
+ this.appList_ = /** @type(!Array<!welcome.AppItem>) */ (list);
this.appList_.forEach((app, index) => {
// Default select first few items.
app.selected = index < 3;
@@ -248,7 +248,7 @@ Polymer({
},
/**
- * @param {!nux.AppItem} item
+ * @param {!welcome.AppItem} item
* @private
*/
updateBookmark_: function(item) {
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/blue_circle.svg b/chromium/chrome/browser/resources/welcome/images/background_svgs/blue_circle.svg
index e177d8c531f..e177d8c531f 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/blue_circle.svg
+++ b/chromium/chrome/browser/resources/welcome/images/background_svgs/blue_circle.svg
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/green_rectangle.svg b/chromium/chrome/browser/resources/welcome/images/background_svgs/green_rectangle.svg
index ca840fb14b2..ca840fb14b2 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/green_rectangle.svg
+++ b/chromium/chrome/browser/resources/welcome/images/background_svgs/green_rectangle.svg
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/grey_oval.svg b/chromium/chrome/browser/resources/welcome/images/background_svgs/grey_oval.svg
index e45a4973f0f..e45a4973f0f 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/grey_oval.svg
+++ b/chromium/chrome/browser/resources/welcome/images/background_svgs/grey_oval.svg
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/grey_rounded_rectangle.svg b/chromium/chrome/browser/resources/welcome/images/background_svgs/grey_rounded_rectangle.svg
index 8154764d47e..8154764d47e 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/grey_rounded_rectangle.svg
+++ b/chromium/chrome/browser/resources/welcome/images/background_svgs/grey_rounded_rectangle.svg
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/red_triangle.svg b/chromium/chrome/browser/resources/welcome/images/background_svgs/red_triangle.svg
index cc7e87d52ed..cc7e87d52ed 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/red_triangle.svg
+++ b/chromium/chrome/browser/resources/welcome/images/background_svgs/red_triangle.svg
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/yellow_dots.svg b/chromium/chrome/browser/resources/welcome/images/background_svgs/yellow_dots.svg
index cba006f436c..cba006f436c 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/yellow_dots.svg
+++ b/chromium/chrome/browser/resources/welcome/images/background_svgs/yellow_dots.svg
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/yellow_semicircle.svg b/chromium/chrome/browser/resources/welcome/images/background_svgs/yellow_semicircle.svg
index 027d197e3b3..027d197e3b3 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/background_svgs/yellow_semicircle.svg
+++ b/chromium/chrome/browser/resources/welcome/images/background_svgs/yellow_semicircle.svg
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view.html b/chromium/chrome/browser/resources/welcome/landing_view.html
index 891d21751f9..2ae537dc474 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view.html
+++ b/chromium/chrome/browser/resources/welcome/landing_view.html
@@ -1,7 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="landing_view_proxy.html">
<link rel="import" href="navigation_behavior.html">
@@ -13,9 +12,7 @@
<dom-module id="landing-view">
<template>
- <style
- include="animations paper-button-style action-link-style
- splash-pages-shared-css">
+ <style include="animations action-link-style splash-pages-shared-css">
onboarding-background {
--animation-delay: 275ms;
}
@@ -33,9 +30,9 @@
<onboarding-background class="fade-in"></onboarding-background>
<h2 class="fade-in">$i18n{landingDescription}</h2>
<h1 class="fade-in" tabindex="-1">$i18n{landingTitle}</h1>
- <paper-button class="action-button fade-in" on-click="onNewUserClick_">
+ <cr-button class="action-button fade-in" on-click="onNewUserClick_">
$i18n{landingNewUser}
- </paper-button>
+ </cr-button>
<button class="action-link fade-in" on-click="onExistingUserClick_">
<span hidden$="[[!signinAllowed_]]">$i18n{landingExistingUser}</span>
<span hidden$="[[signinAllowed_]]">$i18n{skip}</span>
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view.js b/chromium/chrome/browser/resources/welcome/landing_view.js
index aa2900478fa..94f6d4ad5e7 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view.js
+++ b/chromium/chrome/browser/resources/welcome/landing_view.js
@@ -15,7 +15,7 @@ Polymer({
}
},
- /** @private {?nux.LandingViewProxy} */
+ /** @private {?welcome.LandingViewProxy} */
landingViewProxy_: null,
/** @private {boolean} */
@@ -23,7 +23,7 @@ Polymer({
/** @override */
ready() {
- this.landingViewProxy_ = nux.LandingViewProxyImpl.getInstance();
+ this.landingViewProxy_ = welcome.LandingViewProxyImpl.getInstance();
},
onRouteEnter: function() {
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view_proxy.html b/chromium/chrome/browser/resources/welcome/landing_view_proxy.html
index 84eb5be238e..84eb5be238e 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view_proxy.html
+++ b/chromium/chrome/browser/resources/welcome/landing_view_proxy.html
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view_proxy.js b/chromium/chrome/browser/resources/welcome/landing_view_proxy.js
index 50d9fc06073..1ccfbec4ef1 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/landing_view_proxy.js
+++ b/chromium/chrome/browser/resources/welcome/landing_view_proxy.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.define('nux', function() {
+cr.define('welcome', function() {
const NUX_LANDING_PAGE_INTERACTION_METRIC_NAME =
'FirstRun.NewUserExperience.LandingPageInteraction';
@@ -33,7 +33,7 @@ cr.define('nux', function() {
recordExistingUser() {}
}
- /** @implements {nux.LandingViewProxy} */
+ /** @implements {welcome.LandingViewProxy} */
class LandingViewProxyImpl {
/** @override */
recordPageShown() {
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/navigation_behavior.html b/chromium/chrome/browser/resources/welcome/navigation_behavior.html
index 1488b4d3f79..1488b4d3f79 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/navigation_behavior.html
+++ b/chromium/chrome/browser/resources/welcome/navigation_behavior.html
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/navigation_behavior.js b/chromium/chrome/browser/resources/welcome/navigation_behavior.js
index 5e10ba646d0..5e10ba646d0 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/navigation_behavior.js
+++ b/chromium/chrome/browser/resources/welcome/navigation_behavior.js
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/BUILD.gn b/chromium/chrome/browser/resources/welcome/ntp_background/BUILD.gn
index f15e7605c2c..32399f99cf3 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/BUILD.gn
+++ b/chromium/chrome/browser/resources/welcome/ntp_background/BUILD.gn
@@ -6,15 +6,17 @@ import("//third_party/closure_compiler/compile_js.gni")
js_type_check("closure_compile") {
deps = [
+ ":ntp_background_metrics_proxy",
+ ":ntp_background_proxy",
":nux_ntp_background",
]
}
js_library("nux_ntp_background") {
deps = [
+ ":ntp_background_metrics_proxy",
":ntp_background_proxy",
"../:navigation_behavior",
- "../shared:module_metrics_proxy",
"../shared:nux_types",
"//ui/webui/resources/js:cr",
"//ui/webui/resources/js:i18n_behavior",
@@ -28,3 +30,9 @@ js_library("ntp_background_proxy") {
]
externs_list = [ "$externs_path/chrome_send.js" ]
}
+
+js_library("ntp_background_metrics_proxy") {
+ deps = [
+ "../shared:module_metrics_proxy",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_metrics_proxy.html b/chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_metrics_proxy.html
new file mode 100644
index 00000000000..a5bbfe09db6
--- /dev/null
+++ b/chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_metrics_proxy.html
@@ -0,0 +1,3 @@
+<link rel="import" href="chrome://resources/html/cr.html">
+<link rel="import" href="../shared/module_metrics_proxy.html">
+<script src="ntp_background_metrics_proxy.js"></script>
diff --git a/chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_metrics_proxy.js b/chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_metrics_proxy.js
new file mode 100644
index 00000000000..dcdb0ffe959
--- /dev/null
+++ b/chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_metrics_proxy.js
@@ -0,0 +1,23 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+cr.define('welcome', function() {
+ class NtpBackgroundMetricsProxyImpl extends welcome.ModuleMetricsProxyImpl {
+ constructor() {
+ super(
+ 'FirstRun.NewUserExperience.NtpBackgroundInteraction',
+ welcome.NuxNtpBackgroundInteractions);
+ }
+
+ getInteractions() {
+ return this.interactions_;
+ }
+ }
+
+ cr.addSingletonGetter(NtpBackgroundMetricsProxyImpl);
+
+ return {
+ NtpBackgroundMetricsProxyImpl: NtpBackgroundMetricsProxyImpl,
+ };
+});
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_proxy.html b/chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_proxy.html
index a15c5167582..a15c5167582 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_proxy.html
+++ b/chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_proxy.html
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_proxy.js b/chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_proxy.js
index d0715a1177d..17b8ee697bd 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/ntp_background_proxy.js
+++ b/chromium/chrome/browser/resources/welcome/ntp_background/ntp_background_proxy.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.define('nux', function() {
+cr.define('welcome', function() {
/**
* @typedef {{
* id: number,
@@ -17,7 +17,7 @@ cr.define('nux', function() {
class NtpBackgroundProxy {
clearBackground() {}
- /** @return {!Promise<!Array<!nux.NtpBackgroundData>>} */
+ /** @return {!Promise<!Array<!welcome.NtpBackgroundData>>} */
getBackgrounds() {}
/**
@@ -37,7 +37,7 @@ cr.define('nux', function() {
setBackground(id) {}
}
- /** @implements {nux.NtpBackgroundProxy} */
+ /** @implements {welcome.NtpBackgroundProxy} */
class NtpBackgroundProxyImpl {
/** @override */
clearBackground() {
@@ -62,7 +62,7 @@ cr.define('nux', function() {
/** @override */
recordBackgroundImageFailedToLoad() {
const ntpInteractions =
- nux.NtpBackgroundMetricsProxyImpl.getInstance().getInteractions();
+ welcome.NtpBackgroundMetricsProxyImpl.getInstance().getInteractions();
chrome.metricsPrivate.recordEnumerationValue(
'FirstRun.NewUserExperience.NtpBackgroundInteraction',
ntpInteractions.BackgroundImageFailedToLoad,
@@ -78,7 +78,7 @@ cr.define('nux', function() {
/** @override */
recordBackgroundImageNeverLoaded() {
const ntpInteractions =
- nux.NtpBackgroundMetricsProxyImpl.getInstance().getInteractions();
+ welcome.NtpBackgroundMetricsProxyImpl.getInstance().getInteractions();
chrome.metricsPrivate.recordEnumerationValue(
'FirstRun.NewUserExperience.NtpBackgroundInteraction',
ntpInteractions.BackgroundImageNeverLoaded,
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.html b/chromium/chrome/browser/resources/welcome/ntp_background/nux_ntp_background.html
index 96b0b413ec9..c6d03b9a488 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.html
+++ b/chromium/chrome/browser/resources/welcome/ntp_background/nux_ntp_background.html
@@ -1,24 +1,23 @@
<link rel="import" href="chrome://resources/html/polymer.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/icons.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
<link rel="import" href="chrome://resources/html/cr.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../navigation_behavior.html">
<link rel="import" href="../shared/animations_css.html">
<link rel="import" href="../shared/chooser_shared_css.html">
<link rel="import" href="../shared/i18n_setup.html">
-<link rel="import" href="../shared/module_metrics_proxy.html">
<link rel="import" href="../shared/step_indicator.html">
+<link rel="import" href="ntp_background_metrics_proxy.html">
<link rel="import" href="ntp_background_proxy.html">
<dom-module id="nux-ntp-background">
<template>
- <style include="animations chooser-shared-css paper-button-style">
+ <style include="animations chooser-shared-css">
:host {
text-align: center;
}
@@ -66,8 +65,10 @@
width: 44px;
}
- :host-context([dark]) .ntp-background-logo {
- content: url(../images/module_icons/wallpaper_dark.svg);
+ @media (prefers-color-scheme: dark) {
+ .ntp-background-logo {
+ content: url(../images/module_icons/wallpaper_dark.svg);
+ }
}
h1 {
@@ -196,15 +197,14 @@
</div>
<div class="button-bar">
- <paper-button id="skipButton" on-click="onSkipClicked_">
+ <cr-button id="skipButton" on-click="onSkipClicked_">
$i18n{skip}
- </paper-button>
+ </cr-button>
<step-indicator model="[[indicatorModel]]"></step-indicator>
- <paper-button class="action-button"
- on-click="onNextClicked_">
+ <cr-button class="action-button" on-click="onNextClicked_">
$i18n{next}
<iron-icon icon="cr:chevron-right"></iron-icon>
- </paper-button>
+ </cr-button>
</div>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.js b/chromium/chrome/browser/resources/welcome/ntp_background/nux_ntp_background.js
index 99e37a65861..1af8a41fe97 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.js
+++ b/chromium/chrome/browser/resources/welcome/ntp_background/nux_ntp_background.js
@@ -13,17 +13,17 @@ Polymer({
],
properties: {
- /** @type {nux.stepIndicatorModel} */
+ /** @type {welcome.stepIndicatorModel} */
indicatorModel: Object,
- /** @private {?nux.NtpBackgroundData} */
+ /** @private {?welcome.NtpBackgroundData} */
selectedBackground_: {
observer: 'onSelectedBackgroundChange_',
type: Object,
},
},
- /** @private {?Array<!nux.NtpBackgroundData>} */
+ /** @private {?Array<!welcome.NtpBackgroundData>} */
backgrounds_: null,
/** @private */
@@ -32,17 +32,17 @@ Polymer({
/** @private {boolean} */
imageIsLoading_: false,
- /** @private {?nux.ModuleMetricsManager} */
+ /** @private {?welcome.ModuleMetricsManager} */
metricsManager_: null,
- /** @private {?nux.NtpBackgroundProxy} */
+ /** @private {?welcome.NtpBackgroundProxy} */
ntpBackgroundProxy_: null,
/** @override */
ready: function() {
- this.ntpBackgroundProxy_ = nux.NtpBackgroundProxyImpl.getInstance();
- this.metricsManager_ = new nux.ModuleMetricsManager(
- nux.NtpBackgroundMetricsProxyImpl.getInstance());
+ this.ntpBackgroundProxy_ = welcome.NtpBackgroundProxyImpl.getInstance();
+ this.metricsManager_ = new welcome.ModuleMetricsManager(
+ welcome.NtpBackgroundMetricsProxyImpl.getInstance());
},
onRouteEnter: function() {
@@ -98,7 +98,7 @@ Polymer({
},
/**
- * @param {!nux.NtpBackgroundData} background
+ * @param {!welcome.NtpBackgroundData} background
* @private
*/
isSelectedBackground_: function(background) {
@@ -144,7 +144,7 @@ Polymer({
},
/**
- * @param {!{model: !{item: !nux.NtpBackgroundData}}} e
+ * @param {!{model: !{item: !welcome.NtpBackgroundData}}} e
* @private
*/
onBackgroundClick_: function(e) {
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/google_dark.svg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/google_dark.svg
deleted file mode 100644
index 40991d56857..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/google_dark.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg width="42" height="38" xmlns="http://www.w3.org/2000/svg"><g transform="translate(-2 -2)" fill="none" fill-rule="evenodd"><path d="M31.235 26.057l11.432-.566a1.157 1.157 0 0 1 1.157 1.16 1.142 1.142 0 0 1-.128.515L38.52 37.192a1.174 1.174 0 0 1-1.977.163l-6.257-9.461a1.144 1.144 0 0 1 .247-1.612c.203-.148.45-.227.702-.225z" fill="#EE675C"/><path d="M23.239 25.28v-4.464h11.455c.171.756.306 1.464.306 2.46C35 30.128 30.313 35 23.25 35 16.484 35 11 29.624 11 23s5.483-12 12.239-12c3.304 0 6.07 1.188 8.187 3.132l-3.475 3.312c-.882-.816-2.411-1.788-4.712-1.788-4.051 0-7.356 3.3-7.356 7.344 0 4.044 3.305 7.344 7.356 7.344 4.687 0 6.413-3.18 6.73-5.064h-6.73z" fill="#8AB4F8" fill-rule="nonzero"/><path d="M7 7h32v32H7z"/><circle fill="#81C995" cx="10" cy="37.398" r="2"/><path d="M6.592 5.039c4.904-4.183 12.017-3.946 16.689.284.464.42 1.274 1.412-.187 2.658L6.321 22.291c-1.324 1.13-1.914.198-2.202-.254C.655 16.597 1.616 9.284 6.592 5.039z" fill="#FDD663" style="mix-blend-mode:screen"/></g></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/google_light.svg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/google_light.svg
deleted file mode 100644
index a0bed3be3f1..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/google_light.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg width="42" height="38" xmlns="http://www.w3.org/2000/svg"><g transform="translate(-2 -2)" fill="none" fill-rule="evenodd"><path d="M31.235 26.057l11.432-.566a1.157 1.157 0 0 1 1.157 1.16 1.142 1.142 0 0 1-.128.515L38.52 37.192a1.174 1.174 0 0 1-1.977.163l-6.257-9.461a1.144 1.144 0 0 1 .247-1.612c.203-.148.45-.227.702-.225z" fill="#E74133"/><path d="M23.239 25.678v-4.464h11.455c.171.756.306 1.464.306 2.46 0 6.852-4.687 11.724-11.75 11.724-6.767 0-12.25-5.376-12.25-12s5.483-12 12.239-12c3.304 0 6.07 1.188 8.187 3.132l-3.475 3.312c-.882-.816-2.411-1.788-4.712-1.788-4.051 0-7.356 3.3-7.356 7.344 0 4.044 3.305 7.344 7.356 7.344 4.687 0 6.413-3.18 6.73-5.064h-6.73z" fill="#1A73E8" fill-rule="nonzero"/><path d="M7 7.398h32v32H7z"/><circle fill="#31A753" cx="10" cy="37.398" r="2"/><path d="M6.592 5.039c4.904-4.183 12.017-3.946 16.689.284.464.42 1.274 1.412-.187 2.658L6.321 22.291c-1.324 1.13-1.914.198-2.202-.254C.655 16.597 1.616 9.284 6.592 5.039z" fill="#FACF4C" style="mix-blend-mode:multiply"/></g></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/set_default_dark.svg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/set_default_dark.svg
deleted file mode 100644
index 414dff58eae..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/set_default_dark.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg width="44" height="39" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><path d="M14 3C7.929 3 3 7.929 3 14s4.929 11 11 11 11-4.929 11-11S20.071 3 14 3zm0-3c7.728 0 14 6.272 14 14s-6.272 14-14 14S0 21.728 0 14 6.272 0 14 0z" id="a"/><path d="M14 .667C21.36.667 27.333 6.64 27.333 14S21.36 27.333 14 27.333.667 21.36.667 14 6.64.667 14 .667zM3.333 14H9.2c4.543.029 6.562 2.308 6.058 6.836H10.65v3.293c1.054.349 2.18.538 3.35.538 5.887 0 10.667-4.78 10.667-10.667 0-.217-.007-.433-.02-.647-.876 1.32-2.203 1.98-3.98 1.98-2.85 0-4.275-1.222-4.275-3.665h-4.998c-.365-3.638.91-5.457 3.827-5.457 0-1.3.436-2.13 1.082-2.628A10.69 10.69 0 0 0 14 3.333C8.113 3.333 3.333 8.113 3.333 14z" id="c"/></defs><g transform="translate(-2 -2)" fill="none" fill-rule="evenodd"><path d="M33.235 28.659l11.432-.566a1.157 1.157 0 0 1 1.157 1.16 1.142 1.142 0 0 1-.128.515L40.52 39.794a1.174 1.174 0 0 1-1.977.163l-6.257-9.461a1.144 1.144 0 0 1 .247-1.612c.203-.148.45-.227.702-.225z" fill="#EE675C"/><g transform="translate(11 9)"><mask id="b" fill="#fff"><use xlink:href="#a"/></mask><use fill="#000" fill-rule="nonzero" xlink:href="#a"/><g mask="url(#b)" fill="#1A73E8"><path d="M-2-2h32v32H-2z"/></g><use fill="#8AB4F8" fill-rule="nonzero" xlink:href="#c"/></g><circle fill="#81C995" cx="9" cy="38.398" r="2"/><path d="M6.592 5.039c4.904-4.183 12.017-3.946 16.689.284.464.42 1.274 1.412-.187 2.658L6.321 22.291c-1.324 1.13-1.914.198-2.202-.254C.655 16.597 1.616 9.284 6.592 5.039z" fill="#FDDF8B" style="mix-blend-mode:screen"/></g></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/set_default_light.svg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/set_default_light.svg
deleted file mode 100644
index 2a0c6ebd8ae..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/set_default_light.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg width="44" height="39" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><path d="M16 5C9.929 5 5 9.929 5 16s4.929 11 11 11 11-4.929 11-11S22.071 5 16 5zm0-3c7.728 0 14 6.272 14 14s-6.272 14-14 14S2 23.728 2 16 8.272 2 16 2z" id="a"/><path d="M16 2.667c7.36 0 13.333 5.973 13.333 13.333S23.36 29.333 16 29.333 2.667 23.36 2.667 16 8.64 2.667 16 2.667zM5.333 16H11.2c4.543.029 6.562 2.308 6.058 6.836H12.65v3.293c1.054.349 2.18.538 3.35.538 5.887 0 10.667-4.78 10.667-10.667 0-.217-.007-.433-.02-.647-.876 1.32-2.203 1.98-3.98 1.98-2.85 0-4.275-1.222-4.275-3.665h-4.998c-.365-3.638.91-5.457 3.827-5.457 0-1.3.436-2.13 1.082-2.628A10.69 10.69 0 0 0 16 5.333c-5.887 0-10.667 4.78-10.667 10.667z" id="c"/></defs><g transform="translate(-2 -2)" fill="none" fill-rule="evenodd"><path d="M33.235 28.659l11.432-.566a1.157 1.157 0 0 1 1.157 1.16 1.142 1.142 0 0 1-.128.515L40.52 39.794a1.174 1.174 0 0 1-1.977.163l-6.257-9.461a1.144 1.144 0 0 1 .247-1.612c.203-.148.45-.227.702-.225z" fill="#E74133"/><g transform="translate(9 7.398)"><mask id="b" fill="#fff"><use xlink:href="#a"/></mask><use fill="#000" fill-rule="nonzero" xlink:href="#a"/><g mask="url(#b)" fill="#1A73E8"><path d="M0 0h32v32H0z"/></g><mask id="d" fill="#fff"><use xlink:href="#c"/></mask><use fill="#000" fill-rule="nonzero" xlink:href="#c"/><g mask="url(#d)" fill="#1A73E8"><path d="M0 0h32v32H0z"/></g></g><circle fill="#31A753" cx="9" cy="38.398" r="2"/><path d="M6.592 5.039c4.904-4.183 12.017-3.946 16.689.284.464.42 1.274 1.412-.187 2.658L6.321 22.291c-1.324 1.13-1.914.198-2.202-.254C.655 16.597 1.616 9.284 6.592 5.039z" fill="#FACF4C" style="mix-blend-mode:multiply"/></g></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/wallpaper_dark.svg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/wallpaper_dark.svg
deleted file mode 100644
index 45cfa17c7c9..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/wallpaper_dark.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg width="44" height="39" xmlns="http://www.w3.org/2000/svg"><g transform="translate(-2 -2)" fill="none" fill-rule="evenodd"><path d="M33.235 28.659l11.432-.566a1.157 1.157 0 0 1 1.157 1.16 1.142 1.142 0 0 1-.128.515L40.52 39.794a1.174 1.174 0 0 1-1.977.163l-6.257-9.461a1.144 1.144 0 0 1 .247-1.612c.203-.148.45-.227.702-.225z" fill="#EE675C"/><circle fill="#31A753" cx="9" cy="38.398" r="2"/><path d="M9 7h32v32H9z"/><path d="M34.333 13.667v18.666H15.667V13.667h18.666zm0-2.667H15.667A2.675 2.675 0 0 0 13 13.667v18.666C13 33.8 14.2 35 15.667 35h18.666C35.8 35 37 33.8 37 32.333V13.667C37 12.2 35.8 11 34.333 11zm-6.48 11.813l-4 5.16L21 24.52l-4 5.147h16l-5.147-6.854z" fill="#8AB4F8" fill-rule="nonzero"/><path d="M6.592 5.039c4.904-4.183 12.017-3.946 16.689.284.464.42 1.274 1.412-.187 2.658L6.321 22.291c-1.324 1.13-1.914.198-2.202-.254C.655 16.597 1.616 9.284 6.592 5.039z" fill="#FDDB79" style="mix-blend-mode:screen"/></g></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/wallpaper_light.svg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/wallpaper_light.svg
deleted file mode 100644
index 300ae229be4..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/module_icons/wallpaper_light.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg width="44" height="39" xmlns="http://www.w3.org/2000/svg"><g transform="translate(-2 -2)" fill="none" fill-rule="evenodd"><path d="M33.235 28.659l11.432-.566a1.157 1.157 0 0 1 1.157 1.16 1.142 1.142 0 0 1-.128.515L40.52 39.794a1.174 1.174 0 0 1-1.977.163l-6.257-9.461a1.144 1.144 0 0 1 .247-1.612c.203-.148.45-.227.702-.225z" fill="#E74133"/><circle fill="#31A753" cx="9" cy="38.398" r="2"/><path d="M6.592 5.039c4.904-4.183 12.017-3.946 16.689.284.464.42 1.274 1.412-.187 2.658L6.321 22.291c-1.324 1.13-1.914.198-2.202-.254C.655 16.597 1.616 9.284 6.592 5.039z" fill="#FACF4C" style="mix-blend-mode:multiply"/><path d="M9 7h32v32H9z"/><path d="M34.333 13.667v18.666H15.667V13.667h18.666zm0-2.667H15.667A2.675 2.675 0 0 0 13 13.667v18.666C13 33.8 14.2 35 15.667 35h18.666C35.8 35 37 33.8 37 32.333V13.667C37 12.2 35.8 11 34.333 11zm-6.48 11.813l-4 5.16L21 24.52l-4 5.147h16l-5.147-6.854z" fill="#1A73E8" fill-rule="nonzero"/></g></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/art.jpg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/art.jpg
deleted file mode 100644
index 2514b17ed22..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/art.jpg
+++ /dev/null
Binary files differ
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/cityscape.jpg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/cityscape.jpg
deleted file mode 100644
index 4c36cf1e27b..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/cityscape.jpg
+++ /dev/null
Binary files differ
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/earth.jpg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/earth.jpg
deleted file mode 100644
index c4cbdc6608e..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/earth.jpg
+++ /dev/null
Binary files differ
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/geometric_shapes.jpg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/geometric_shapes.jpg
deleted file mode 100644
index 6092436d711..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/geometric_shapes.jpg
+++ /dev/null
Binary files differ
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/landscape.jpg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/landscape.jpg
deleted file mode 100644
index 340ddff2e52..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/ntp_thumbnails/landscape.jpg
+++ /dev/null
Binary files differ
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/set_default_dark.svg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/set_default_dark.svg
deleted file mode 100644
index c17a605032e..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/set_default_dark.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg width="454" height="185" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><path id="a" d="M.707.43h56.32v56.32H.707z"/><path d="M7.527 0C3.668 0 .528 3.14.528 7v126c0 3.86 3.14 7 6.999 7h213c3.86 0 7-3.14 7-7V7c0-3.86-3.14-7-7-7" id="c"/><path d="M7.527 0C3.668 0 .528 3.14.528 7v126c0 3.86 3.14 7 6.999 7h213c3.86 0 7-3.14 7-7V7c0-3.86-3.14-7-7-7h-213z" id="e"/><path d="M7.527 0C3.668 0 .528 3.14.528 7v126c0 3.86 3.14 7 6.999 7h213c3.86 0 7-3.14 7-7V7c0-3.86-3.14-7-7-7" id="g"/><path d="M7.527 0C3.668 0 .528 3.14.528 7v126c0 3.86 3.14 7 6.999 7h213c3.86 0 7-3.14 7-7V7c0-3.86-3.14-7-7-7" id="i"/></defs><g fill="none" fill-rule="evenodd"><path d="M292.172 9.494l-38.26 10.251c-2.134.572-2.848 3.24-1.286 4.802l28.008 28.008c1.562 1.562 4.23.847 4.802-1.287l10.252-38.259c.57-2.134-1.382-4.087-3.516-3.515l-38.26 10.251c-2.134.572-2.848 3.24-1.286 4.802l28.008 28.008c1.562 1.562 4.23.847 4.802-1.287l10.252-38.259c.57-2.134-1.382-4.087-3.516-3.515" fill="#F1F3F4"/><path d="M90.398 148.926c-1.172.677-1.51 2.225-.714 3.32 7.039 9.677 20.395 12.674 30.99 6.557 10.595-6.117 14.678-19.182 9.815-30.117-.549-1.237-2.059-1.718-3.231-1.04l-36.86 21.28zM359.03 138.41l-28.754 28.755a3.115 3.115 0 0 1-4.406 0l-28.754-28.754a3.115 3.115 0 0 1 0-4.406l28.754-28.754a3.117 3.117 0 0 1 4.406 0l28.754 28.754a3.115 3.115 0 0 1 0 4.406" fill="#3C4043"/><g transform="translate(116 -.43)"><mask id="b" fill="#fff"><use xlink:href="#a"/></mask><path d="M57.027 28.59c0 15.553-12.607 28.16-28.16 28.16-15.552 0-28.16-12.607-28.16-28.16C.707 13.038 13.315.43 28.867.43c15.553 0 28.16 12.608 28.16 28.16" fill="#3C4043" mask="url(#b)"/></g><path d="M112.527 168.57c-3.859 0-7-3.14-7-7v-126c0-3.86 3.141-7 7-7h213c3.86 0 7 3.14 7 7v126c0 3.86-3.14 7-7 7h-213z" fill="#202124"/><g><g transform="translate(105 28.57)"><mask id="d" fill="#fff"><use xlink:href="#c"/></mask><path d="M186.408-14.069L152.47-4.976c-1.892.508-2.527 2.874-1.14 4.26l24.843 24.844c1.386 1.386 3.753.751 4.26-1.142l9.093-33.937c.507-1.893-1.225-3.625-3.118-3.118L152.47-4.976c-1.892.508-2.527 2.874-1.14 4.26l24.843 24.844c1.386 1.386 3.753.751 4.26-1.142l9.093-33.937c.507-1.893-1.225-3.625-3.118-3.118" fill="#E74133" mask="url(#d)"/></g><g transform="translate(105 28.57)"><mask id="f" fill="#fff"><use xlink:href="#e"/></mask><path d="M-15.803 120.8c-1.191.688-1.535 2.261-.726 3.373 7.154 9.836 20.727 12.881 31.495 6.665 10.768-6.217 14.917-19.495 9.976-30.608-.56-1.257-2.093-1.745-3.284-1.058L-15.803 120.8z" fill="#81C995" mask="url(#f)"/></g><g transform="translate(105 28.57)"><mask id="h" fill="#fff"><use xlink:href="#g"/></mask><path d="M252.702 109.755l-28.26 28.261a3.062 3.062 0 0 1-4.332 0l-28.262-28.26a3.064 3.064 0 0 1 0-4.332l28.262-28.26a3.062 3.062 0 0 1 4.331 0l28.261 28.26a3.064 3.064 0 0 1 0 4.331" fill="#FDDB79" mask="url(#h)"/></g><g transform="translate(105 28.57)"><mask id="j" fill="#fff"><use xlink:href="#i"/></mask><path d="M68.027-.25c0 15.464-12.536 28-28 28s-28-12.536-28-28 12.536-28 28-28 28 12.536 28 28" fill="#8AB4F8" mask="url(#j)"/></g></g><g><path d="M328.527 161.57a3 3 0 0 1-3 3h-213a3 3 0 0 1-3-3v-126a3 3 0 0 1 3-3h213a3 3 0 0 1 3 3v126zm4.5-141.5h-228a6.508 6.508 0 0 0-6.5 6.5v153.5h241V26.57c0-3.584-2.916-6.5-6.5-6.5z" fill="#3C4043"/><path d="M98.527 180.07V26.57c0-3.584 2.916-6.5 6.5-6.5h228c3.584 0 6.5 2.916 6.5 6.5v153.5h-241z" stroke="#202124" stroke-width="2"/><path d="M220.527 26.57a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0" fill="#DADCE0"/><path d="M325.527 176.57h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5M307.527 176.57h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5M289.527 176.57h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5M124.527 176.57h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5M142.527 176.57h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5M160.527 176.57h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5M271.527 176.57h-105a1.5 1.5 0 0 0-1.5 1.5h108a1.5 1.5 0 0 0-1.5-1.5" fill="#202124"/><path d="M222.027 86.382c6.316 0 11.438 5.121 11.438 11.438s-5.122 11.438-11.438 11.438c-6.316 0-11.438-5.121-11.438-11.438s5.122-11.438 11.438-11.438" fill="#F1F1F1"/><path d="M217.527 97.82a7.5 7.5 0 0 1 7.5-7.5h14.701c-2.73-5.342-8.289-9-14.7-9-5.826 0-10.945 3.019-13.882 7.576v12.674h7.386l.001-.001a7.455 7.455 0 0 1-1.006-3.749" fill="#E74133"/><path d="M225.027 105.32a7.496 7.496 0 0 1-6.494-3.75l-7.389-12.671a16.424 16.424 0 0 0-2.617 8.921c0 8.853 6.973 16.077 15.726 16.481l7.271-7.271v-5.46h-.003a7.496 7.496 0 0 1-6.494 3.75" fill="#32A753"/><path d="M239.729 90.32h-14.701a7.5 7.5 0 0 1 6.495 11.248l.002.002-7.28 12.731c.259.012.52.019.783.019 9.112 0 16.5-7.387 16.5-16.5 0-2.701-.65-5.25-1.8-7.5" fill="#F9BB00"/><path d="M225.027 91.82a6 6 0 0 1 0 12 6 6 0 0 1 0-12" fill="#4285F4"/><path d="M81.027 184.57c-1.103 0-2-.897-2-2v-3a.5.5 0 0 1 .5-.5h279a.5.5 0 0 1 .5.5v3c0 1.103-.897 2-2 2h-276zM376.788 48.278c-1.15 1.04-1.092 2.885.145 3.822 5.88 4.453 14.278 4.246 19.948-.884 5.67-5.13 6.714-13.466 2.87-19.76-.81-1.324-2.64-1.567-3.79-.526l-19.173 17.348zM423.668 162.996c-.307 6.134-5.528 10.86-11.663 10.552-6.134-.306-10.858-5.528-10.552-11.662.307-6.135 5.528-10.859 11.662-10.553 6.135.307 10.859 5.53 10.553 11.663" fill="#3C4043"/><path d="M373.426 95.324l.34-6.812c.077-1.538-1.54-2.582-2.91-1.88l-6.07 3.111c-1.37.703-1.465 2.625-.172 3.46l5.729 3.701c1.293.836 3.006-.042 3.083-1.58l.34-6.812c.077-1.538-1.54-2.582-2.91-1.88l-6.07 3.111c-1.37.703-1.465 2.625-.172 3.46l5.729 3.701c1.293.836 3.006-.042 3.083-1.58" fill="#4285F4"/><path d="M67.022 136.045a4.5 4.5 0 1 1-8.99-.45 4.5 4.5 0 0 1 8.99.45" fill="#81C995"/><path d="M28.022 68.045a4.5 4.5 0 1 1-8.99-.45 4.5 4.5 0 0 1 8.99.45" fill="#FDDB79"/><path d="M426.024 87.47a2.999 2.999 0 0 1-3.147 2.846 2.999 2.999 0 1 1 3.146-2.846" fill="#3C4043"/><path d="M441.376 117.08a4 4 0 1 0 5.412 5.892l5.891-5.412a4 4 0 0 0-5.412-5.892l-5.891 5.413z" fill="#EE675C"/><path d="M13.507 125.467c4.518-2.411 6.563-7.644 5.12-12.363a1.701 1.701 0 0 0-2.427-1.013L.897 120.256a1.703 1.703 0 0 0-.511 2.58c3.117 3.827 8.602 5.042 13.12 2.631M67.06 68.092l-4.362-4.362c-2.266-2.266-2.266-5.973 0-8.24 2.266-2.265 5.973-2.265 8.24 0l4.361 4.363c2.266 2.265 2.266 5.973 0 8.239-2.266 2.266-5.973 2.266-8.239 0" fill="#3C4043"/></g></g></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/set_default_light.svg b/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/set_default_light.svg
deleted file mode 100644
index e2cf75680eb..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/images/set_default_light.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="454" height="185"><defs><path id="a" d="M.707.43h56.32v56.32H.707z"/><path id="c" d="M7.527 0C3.668 0 .528 3.14.528 7v126c0 3.86 3.14 7 6.999 7h213c3.86 0 7-3.14 7-7V7c0-3.86-3.14-7-7-7"/><path id="e" d="M7.527 0C3.668 0 .528 3.14.528 7v126c0 3.86 3.14 7 6.999 7h213c3.86 0 7-3.14 7-7V7c0-3.86-3.14-7-7-7h-213z"/><path id="g" d="M7.527 0C3.668 0 .528 3.14.528 7v126c0 3.86 3.14 7 6.999 7h213c3.86 0 7-3.14 7-7V7c0-3.86-3.14-7-7-7"/><path id="i" d="M7.527 0C3.668 0 .528 3.14.528 7v126c0 3.86 3.14 7 6.999 7h213c3.86 0 7-3.14 7-7V7c0-3.86-3.14-7-7-7"/></defs><g fill="none" fill-rule="evenodd"><path fill="#F1F3F4" d="M292.172 9.494l-38.26 10.251c-2.134.572-2.848 3.24-1.286 4.802l28.008 28.008c1.562 1.562 4.23.847 4.802-1.287l10.252-38.259c.57-2.134-1.382-4.087-3.516-3.515l-38.26 10.251c-2.134.572-2.848 3.24-1.286 4.802l28.008 28.008c1.562 1.562 4.23.847 4.802-1.287l10.252-38.259c.57-2.134-1.382-4.087-3.516-3.515M90.398 148.926c-1.172.677-1.51 2.225-.714 3.32 7.039 9.677 20.395 12.674 30.99 6.557 10.595-6.117 14.678-19.182 9.815-30.117-.549-1.237-2.059-1.718-3.231-1.04l-36.86 21.28zm268.632-10.515l-28.754 28.754a3.115 3.115 0 0 1-4.406 0l-28.754-28.754a3.115 3.115 0 0 1 0-4.406l28.754-28.754a3.117 3.117 0 0 1 4.406 0l28.754 28.754a3.115 3.115 0 0 1 0 4.406"/><g transform="translate(116 -.43)"><mask id="b" fill="#fff"><use xlink:href="#a"/></mask><path fill="#F1F3F4" d="M57.027 28.59c0 15.553-12.607 28.16-28.16 28.16-15.552 0-28.16-12.607-28.16-28.16C.707 13.038 13.315.43 28.867.43c15.553 0 28.16 12.608 28.16 28.16" mask="url(#b)"/></g><path fill="#FFF" d="M112.527 168.57c-3.859 0-7-3.14-7-7v-126c0-3.86 3.141-7 7-7h213c3.86 0 7 3.14 7 7v126c0 3.86-3.14 7-7 7h-213z"/><g transform="translate(105 28.57)"><mask id="d" fill="#fff"><use xlink:href="#c"/></mask><path fill="#E74133" d="M186.408-14.069L152.47-4.976c-1.892.508-2.527 2.874-1.14 4.26l24.843 24.844c1.386 1.386 3.753.751 4.26-1.142l9.093-33.937c.507-1.893-1.225-3.625-3.118-3.118L152.47-4.976c-1.892.508-2.527 2.874-1.14 4.26l24.843 24.844c1.386 1.386 3.753.751 4.26-1.142l9.093-33.937c.507-1.893-1.225-3.625-3.118-3.118" mask="url(#d)"/><mask id="f" fill="#fff"><use xlink:href="#e"/></mask><path fill="#32A753" d="M-15.803 120.8c-1.191.688-1.535 2.261-.726 3.373 7.154 9.836 20.727 12.881 31.495 6.665 10.768-6.217 14.917-19.495 9.976-30.608-.56-1.257-2.093-1.745-3.284-1.058L-15.803 120.8z" mask="url(#f)"/><mask id="h" fill="#fff"><use xlink:href="#g"/></mask><path fill="#F9BB00" d="M252.702 109.755l-28.26 28.261a3.062 3.062 0 0 1-4.332 0l-28.262-28.26a3.064 3.064 0 0 1 0-4.332l28.262-28.26a3.062 3.062 0 0 1 4.331 0l28.261 28.26a3.064 3.064 0 0 1 0 4.331" mask="url(#h)"/><mask id="j" fill="#fff"><use xlink:href="#i"/></mask><path fill="#4285F4" d="M68.027-.25c0 15.464-12.536 28-28 28s-28-12.536-28-28 12.536-28 28-28 28 12.536 28 28" mask="url(#j)"/></g><g><path fill="#F1F3F4" d="M328.527 161.57a3 3 0 0 1-3 3h-213a3 3 0 0 1-3-3v-126a3 3 0 0 1 3-3h213a3 3 0 0 1 3 3v126zm4.5-141.5h-228a6.508 6.508 0 0 0-6.5 6.5v153.5h241V26.57c0-3.584-2.916-6.5-6.5-6.5z"/><path stroke="#DADCE0" stroke-width="2" d="M98.527 180.07V26.57c0-3.584 2.916-6.5 6.5-6.5h228c3.584 0 6.5 2.916 6.5 6.5v153.5h-241z"/><path fill="#DADCE0" d="M220.527 26.57a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m105 150h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5m-18 0h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5m-18 0h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5m-165 0h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5m18 0h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5m18 0h-12a1.5 1.5 0 0 0-1.5 1.5h15a1.5 1.5 0 0 0-1.5-1.5m111 0h-105a1.5 1.5 0 0 0-1.5 1.5h108a1.5 1.5 0 0 0-1.5-1.5"/><path fill="#F1F1F1" d="M219.027 86.382c6.316 0 11.438 5.121 11.438 11.438s-5.122 11.438-11.438 11.438c-6.316 0-11.438-5.121-11.438-11.438s5.122-11.438 11.438-11.438"/><path fill="#E74133" d="M217.527 97.82a7.5 7.5 0 0 1 7.5-7.5h14.701c-2.73-5.342-8.289-9-14.7-9-5.826 0-10.945 3.019-13.882 7.576v12.674h7.386l.001-.001a7.455 7.455 0 0 1-1.006-3.749"/><path fill="#32A753" d="M225.027 105.32a7.496 7.496 0 0 1-6.494-3.75l-7.389-12.671a16.424 16.424 0 0 0-2.617 8.921c0 8.853 6.973 16.077 15.726 16.481l7.271-7.271v-5.46h-.003a7.496 7.496 0 0 1-6.494 3.75"/><path fill="#F9BB00" d="M239.729 90.32h-14.701a7.5 7.5 0 0 1 6.495 11.248l.002.002-7.28 12.731c.259.012.52.019.783.019 9.112 0 16.5-7.387 16.5-16.5 0-2.701-.65-5.25-1.8-7.5"/><path fill="#4285F4" d="M225.027 91.82a6 6 0 0 1 0 12 6 6 0 0 1 0-12"/><path fill="#F1F3F4" d="M81.027 184.57c-1.103 0-2-.897-2-2v-3a.5.5 0 0 1 .5-.5h279a.5.5 0 0 1 .5.5v3c0 1.103-.897 2-2 2h-276zM376.788 48.278c-1.15 1.04-1.092 2.884.145 3.821 5.88 4.453 14.278 4.246 19.948-.884 5.67-5.13 6.714-13.466 2.87-19.76-.81-1.324-2.64-1.567-3.79-.526l-19.173 17.348zm46.88 114.718c-.307 6.134-5.528 10.86-11.663 10.552-6.134-.306-10.858-5.528-10.552-11.662.307-6.135 5.528-10.859 11.662-10.553 6.135.307 10.859 5.53 10.553 11.663"/><path fill="#4285F4" d="M373.426 95.324l.34-6.812c.077-1.538-1.54-2.582-2.91-1.88l-6.07 3.111c-1.37.703-1.465 2.625-.172 3.46l5.729 3.701c1.293.836 3.006-.042 3.083-1.58l.34-6.812c.077-1.538-1.54-2.582-2.91-1.88l-6.07 3.111c-1.37.703-1.465 2.625-.172 3.46l5.729 3.701c1.293.836 3.006-.042 3.083-1.58"/><path fill="#32A753" d="M67.022 136.045a4.5 4.5 0 1 1-8.99-.45 4.5 4.5 0 0 1 8.99.45"/><path fill="#F9BB00" d="M28.022 68.045a4.5 4.5 0 1 1-8.99-.45 4.5 4.5 0 0 1 8.99.45"/><path fill="#F1F3F4" d="M426.024 87.47a2.999 2.999 0 0 1-3.147 2.846 2.999 2.999 0 1 1 3.146-2.846"/><path fill="#E74133" d="M441.376 117.08a4 4 0 1 0 5.412 5.892l5.891-5.412a4 4 0 0 0-5.412-5.892l-5.891 5.413z"/><path fill="#F1F3F4" d="M13.507 125.467c4.518-2.411 6.563-7.644 5.12-12.363a1.701 1.701 0 0 0-2.427-1.013L.897 120.256a1.703 1.703 0 0 0-.511 2.58c3.117 3.827 8.602 5.042 13.12 2.631M67.06 68.092l-4.362-4.362c-2.266-2.266-2.266-5.973 0-8.24 2.266-2.265 5.973-2.265 8.24 0l4.361 4.363c2.266 2.265 2.266 5.973 0 8.239-2.266 2.266-5.973 2.266-8.239 0"/></g></g></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/app_proxy.js b/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/app_proxy.js
deleted file mode 100644
index 1b04fd07672..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/app_proxy.js
+++ /dev/null
@@ -1,31 +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.
-
-cr.define('nux', function() {
- /** @interface */
- class AppProxy {
- /**
- * Google app IDs are local to the list of Google apps, so their icon must
- * be cached by the handler that provided the IDs.
- * @param {number} appId
- */
- cacheBookmarkIcon(appId) {}
-
- /**
- * Returns a promise for an array of Google apps.
- * @return {!Promise<!Array<!nux.BookmarkListItem>>}
- */
- getAppList() {}
-
- /**
- * @param {number} providerId This should match one of the histogram enum
- * value for NuxGoogleAppsSelections.
- */
- recordProviderSelected(providerId) {}
- }
-
- return {
- AppProxy: AppProxy,
- };
-});
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/navi_colors_css.html b/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/navi_colors_css.html
deleted file mode 100644
index 66c0fd81df9..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/navi_colors_css.html
+++ /dev/null
@@ -1,53 +0,0 @@
-<link rel="import" href="chrome://resources/html/polymer.html">
-
-<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
-
-<dom-module id="navi-colors-css">
- <template>
- <style>
- :host {
- --navi-border-color: var(--google-grey-refresh-300);
- --navi-check-icon-color: lightgrey;
- --navi-keyboard-focus-color: rgba(var(--google-blue-600-rgb), .4);
- --navi-option-box-shadow:
- 0 1px 2px 0 rgba(var(--google-grey-800-rgb), .3),
- 0 3px 6px 2px rgba(var(--google-grey-800-rgb), .15);
- --navi-option-icon-shadow-color: var(--google-grey-refresh-100);
- --navi-shape-blue-color: rgb(26, 115, 232); /* #1A73E8 */
- --navi-shape-green-color: rgb(49, 167, 83); /* #31A753 */
- --navi-shape-grey-color: rgb(241, 243, 244); /* #F1F3F4 */
- --navi-shape-red-color: rgb(233, 66, 53); /* #E94235 */
- --navi-shape-yellow-dots-color: rgb(253, 214, 99); /* #FDD663 */
- --navi-shape-yellow-semicircle-color: rgb(250, 207, 76); /* #FACF4C */
- --navi-step-indicator-active: {
- background: var(--google-blue-600);
- opacity: .5; /* Only in light mode */
- };
- --navi-step-indicator-color: var(--google-grey-200);
- --navi-wallpaper-text-color: var(--google-grey-refresh-700);
- }
-
- :host-context([dark]) {
- --navi-border-color: var(--google-grey-refresh-700);
- --navi-check-icon-color: var(--google-grey-refresh-700);
- --navi-keyboard-focus-color:
- rgba(var(--google-blue-refresh-300-rgb), .5);
- --navi-option-box-shadow: 0 1px 2px 0 rgba(0, 0, 0, .3),
- 0 3px 6px 2px rgba(0, 0, 0, .15);
- --navi-option-icon-shadow-color: var(--google-grey-refresh-700);
- --navi-shape-blue-color: rgb(138, 180, 248); /* #8AB4F8 */
- --navi-shape-green-color: rgb(129, 201, 149); /* #81C995 */
- --navi-shape-grey-color: rgb(154, 160, 166); /* #9AA0A6 */
- --navi-shape-red-color: rgb(238, 103, 92); /* #EE675C */
- /* --navi-shape-yellow-dots-color is same color in dark mode */
- --navi-shape-yellow-semicircle-color: rgb(253, 214, 99); /* #FDD663 */
- --navi-step-indicator-active: {
- background: var(--google-blue-refresh-300);
- };
- --navi-step-indicator-color: var(--google-grey-refresh-500);
- --navi-wallpaper-text-color: var(--google-grey-200);
- }
- </style>
- </template>
-</dom-module>
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome.html b/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome.html
deleted file mode 100644
index d4bb3e8b950..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}>
- <head>
- <meta charset="utf-8">
- <title>$i18n{headerText}</title>
- <link rel="import" href="welcome_app.html">
- <link rel="stylesheet" href="chrome://resources/css/md_colors.css">
- <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
- </head>
- <body>
- <style>
- html[dark] {
- background: var(--md-background-color);
- }
- </style>
- <welcome-app></welcome-app>
- <script src="/welcome.js"></script>
- <link rel="import" href="chrome://resources/html/dark_mode.html">
- <link rel="stylesheet" href="chrome://welcome/welcome.css">
- </body>
-</html>
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome.js b/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome.js
deleted file mode 100644
index 2e78a6476da..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome.js
+++ /dev/null
@@ -1,15 +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.
-
-/**
- * This file should only be included once. It will generate an assert error if
- * it's included more than once, which can happen when an include is misspelled.
- */
-
-cr.exportPath('welcome');
-assert(
- !welcome.defaultResourceLoaded,
- 'welcome.js run twice. You probably have an invalid import.');
-/** Global defined when the main welcome script runs. */
-welcome.defaultResourceLoaded = true;
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_browser_proxy.html b/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_browser_proxy.html
deleted file mode 100644
index 24f332053f2..00000000000
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_browser_proxy.html
+++ /dev/null
@@ -1,2 +0,0 @@
-<link rel="import" href="chrome://resources/html/cr.html">
-<script src="welcome_browser_proxy.js"></script>
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/onboarding_welcome_resources.grd b/chromium/chrome/browser/resources/welcome/onboarding_welcome_resources.grd
index 4793fd505a0..011b9b184a4 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/onboarding_welcome_resources.grd
+++ b/chromium/chrome/browser/resources/welcome/onboarding_welcome_resources.grd
@@ -14,53 +14,6 @@
</outputs>
<release seq="1">
<includes>
- <include name="IDR_NUX_MODULE_ICONS_GOOGLE_DARK"
- file="images/module_icons/google_dark.svg"
- compress="gzip"
- type="BINDATA" />
- <include name="IDR_NUX_MODULE_ICONS_GOOGLE_LIGHT"
- file="images/module_icons/google_light.svg"
- compress="gzip"
- type="BINDATA" />
- <include name="IDR_NUX_MODULE_ICONS_SET_DEFAULT_DARK"
- file="images/module_icons/set_default_dark.svg"
- compress="gzip"
- type="BINDATA" />
- <include name="IDR_NUX_MODULE_ICONS_SET_DEFAULT_LIGHT"
- file="images/module_icons/set_default_light.svg"
- compress="gzip"
- type="BINDATA" />
- <include name="IDR_NUX_MODULE_ICONS_WALLPAPER_DARK"
- file="images/module_icons/wallpaper_dark.svg"
- compress="gzip"
- type="BINDATA" />
- <include name="IDR_NUX_MODULE_ICONS_WALLPAPER_LIGHT"
- file="images/module_icons/wallpaper_light.svg"
- compress="gzip"
- type="BINDATA" />
- <include name="IDR_NUX_NTP_BACKGROUND_THUMBNAIL_ART"
- file="images/ntp_thumbnails/art.jpg"
- type="BINDATA" />
- <include name="IDR_NUX_NTP_BACKGROUND_THUMBNAIL_CITYSCAPE"
- file="images/ntp_thumbnails/cityscape.jpg"
- type="BINDATA" />
- <include name="IDR_NUX_NTP_BACKGROUND_THUMBNAIL_EARTH"
- file="images/ntp_thumbnails/earth.jpg"
- type="BINDATA" />
- <include name="IDR_NUX_NTP_BACKGROUND_THUMBNAIL_GEOMETRIC_SHAPES"
- file="images/ntp_thumbnails/geometric_shapes.jpg"
- type="BINDATA" />
- <include name="IDR_NUX_NTP_BACKGROUND_THUMBNAIL_LANDSCAPE"
- file="images/ntp_thumbnails/landscape.jpg"
- type="BINDATA" />
- <include name="IDR_NUX_SET_DEFAULT_DARK"
- file="images\set_default_dark.svg"
- compress="gzip"
- type="BINDATA" />
- <include name="IDR_NUX_SET_DEFAULT_LIGHT"
- file="images\set_default_light.svg"
- compress="gzip"
- type="BINDATA" />
<include name="IDR_WELCOME_ONBOARDING_WELCOME_IMAGES_BACKGROUND_SVGS_BLUE_CIRCLE_SVG"
file="images/background_svgs/blue_circle.svg"
compress="gzip"
@@ -270,6 +223,14 @@
file="set_as_default/nux_set_as_default_proxy.js"
compress="gzip"
type="chrome_html" />
+ <structure name="IDR_GOOGLE_APPS_METRICS_PROXY_HTML"
+ file="google_apps/google_apps_metrics_proxy.html"
+ compress="gzip"
+ type="chrome_html" />
+ <structure name="IDR_GOOGLE_APPS_METRICS_PROXY_JS"
+ file="google_apps/google_apps_metrics_proxy.js"
+ compress="gzip"
+ type="chrome_html" />
<!-- NUX NTP background-->
<structure name="IDR_NUX_NTP_BACKGROUND_HTML"
@@ -288,6 +249,14 @@
file="ntp_background/ntp_background_proxy.js"
compress="gzip"
type="chrome_html" />
+ <structure name="IDR_NUX_NTP_BACKGROUND_METRICS_PROXY_HTML"
+ file="ntp_background/ntp_background_metrics_proxy.html"
+ compress="gzip"
+ type="chrome_html" />
+ <structure name="IDR_NUX_NTP_BACKGROUND_METRICS_PROXY_JS"
+ file="ntp_background/ntp_background_metrics_proxy.js"
+ compress="gzip"
+ type="chrome_html" />
</structures>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/welcome/pin.webp b/chromium/chrome/browser/resources/welcome/pin.webp
deleted file mode 100644
index a5281755428..00000000000
--- a/chromium/chrome/browser/resources/welcome/pin.webp
+++ /dev/null
Binary files differ
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/BUILD.gn b/chromium/chrome/browser/resources/welcome/set_as_default/BUILD.gn
index e633bc817e4..e633bc817e4 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/BUILD.gn
+++ b/chromium/chrome/browser/resources/welcome/set_as_default/BUILD.gn
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default.html b/chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default.html
index 306a4e39de9..53688f8c549 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default.html
+++ b/chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default.html
@@ -1,9 +1,8 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="../navigation_behavior.html">
<link rel="import" href="../shared/animations_css.html">
<link rel="import" href="../shared/i18n_setup.html">
@@ -16,7 +15,7 @@
<dom-module id="nux-set-as-default">
<template>
- <style include="animations paper-button-style">
+ <style include="animations">
.container {
text-align: center;
}
@@ -29,8 +28,10 @@
width: 42px;
}
- :host-context([dark]) .logo {
- content: url(../images/module_icons/set_default_dark.svg);
+ @media (prefers-color-scheme: dark) {
+ .logo {
+ content: url(../images/module_icons/set_default_dark.svg);
+ }
}
.illustration {
@@ -39,8 +40,10 @@
width: 454px;
}
- :host-context([dark]) .illustration {
- content: url(../images/set_default_dark.svg);
+ @media (prefers-color-scheme: dark) {
+ .illustration {
+ content: url(../images/set_default_dark.svg);
+ }
}
h1 {
@@ -84,16 +87,16 @@
<h2>$i18n{setDefaultSubHeader}</h2>
<div class="illustration slide-in" aria-hidden="true"></div>
<div class="button-bar">
- <paper-button id="decline-button" on-click="onDeclineClick_">
- $i18n{setDefaultSkip}
- </paper-button>
+ <cr-button id="decline-button" on-click="onDeclineClick_">
+ $i18n{skip}
+ </cr-button>
<step-indicator model="[[indicatorModel]]"></step-indicator>
- <paper-button class="action-button" on-click="onSetDefaultClick_">
+ <cr-button class="action-button" on-click="onSetDefaultClick_">
$i18n{setDefaultConfirm}
<if expr="is_win">
<iron-icon icon="cr:open-in-new" hidden="[[!isWin10]]"></iron-icon>
</if>
- </paper-button>
+ </cr-button>
</div>
</div>
</template>
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default.js b/chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default.js
index 6f0477b9db5..37e69a2de97 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default.js
+++ b/chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default.js
@@ -11,7 +11,7 @@ Polymer({
],
properties: {
- /** @type {nux.stepIndicatorModel} */
+ /** @type {welcome.stepIndicatorModel} */
indicatorModel: Object,
// <if expr="is_win">
@@ -22,7 +22,7 @@ Polymer({
// </if>
},
- /** @private {nux.NuxSetAsDefaultProxy} */
+ /** @private {welcome.NuxSetAsDefaultProxy} */
browserProxy_: null,
/** @private {boolean} */
@@ -30,7 +30,7 @@ Polymer({
/** @override */
ready: function() {
- this.browserProxy_ = nux.NuxSetAsDefaultProxyImpl.getInstance();
+ this.browserProxy_ = welcome.NuxSetAsDefaultProxyImpl.getInstance();
this.addWebUIListener(
'browser-default-state-changed',
@@ -80,7 +80,7 @@ Polymer({
/**
* Automatically navigate to the next onboarding step once default changed.
- * @param {!nux.DefaultBrowserInfo} status
+ * @param {!welcome.DefaultBrowserInfo} status
* @private
*/
onDefaultBrowserChange_: function(status) {
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default_proxy.html b/chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default_proxy.html
index b1dcbde23a5..b1dcbde23a5 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default_proxy.html
+++ b/chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default_proxy.html
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default_proxy.js b/chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default_proxy.js
index 1fe1cec973f..e7668ffa467 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default_proxy.js
+++ b/chromium/chrome/browser/resources/welcome/set_as_default/nux_set_as_default_proxy.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.define('nux', function() {
+cr.define('welcome', function() {
const NUX_SET_AS_DEFAULT_INTERACTION_METRIC_NAME =
'FirstRun.NewUserExperience.SetAsDefaultInteraction';
@@ -26,7 +26,7 @@ cr.define('nux', function() {
/** @interface */
class NuxSetAsDefaultProxy {
- /** @return {!Promise<!nux.DefaultBrowserInfo>} */
+ /** @return {!Promise<!welcome.DefaultBrowserInfo>} */
requestDefaultBrowserState() {}
setAsDefault() {}
recordPageShown() {}
@@ -37,7 +37,7 @@ cr.define('nux', function() {
recordSuccessfullySetDefault() {}
}
- /** @implements {nux.NuxSetAsDefaultProxy} */
+ /** @implements {welcome.NuxSetAsDefaultProxy} */
class NuxSetAsDefaultProxyImpl {
/** @override */
requestDefaultBrowserState() {
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/BUILD.gn b/chromium/chrome/browser/resources/welcome/shared/BUILD.gn
index b3cb8800223..9a06f4194e1 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/BUILD.gn
+++ b/chromium/chrome/browser/resources/welcome/shared/BUILD.gn
@@ -7,6 +7,7 @@ import("//third_party/closure_compiler/compile_js.gni")
js_type_check("closure_compile") {
deps = [
":bookmark_proxy",
+ ":module_metrics_proxy",
":nux_types",
":step_indicator",
]
@@ -22,12 +23,6 @@ js_library("bookmark_proxy") {
]
}
-js_library("app_proxy") {
- deps = [
- "//ui/webui/resources/js:cr",
- ]
-}
-
js_library("module_metrics_proxy") {
deps = [
"//ui/webui/resources/js:cr",
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/action_link_style.js b/chromium/chrome/browser/resources/welcome/shared/action_link_style.js
index b4e52c4ba58..b4e52c4ba58 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/action_link_style.js
+++ b/chromium/chrome/browser/resources/welcome/shared/action_link_style.js
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/action_link_style_css.html b/chromium/chrome/browser/resources/welcome/shared/action_link_style_css.html
index 6e51989f3df..96d00fb8bcc 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/action_link_style_css.html
+++ b/chromium/chrome/browser/resources/welcome/shared/action_link_style_css.html
@@ -8,11 +8,11 @@
<template>
<style>
button.action-link {
- @apply --cr-actionable;
-webkit-appearance: none;
background: none;
border: none;
color: var(--cr-link-color);
+ cursor: pointer;
display: inline-block;
font-family: inherit;
text-decoration: none;
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/animations_css.html b/chromium/chrome/browser/resources/welcome/shared/animations_css.html
index c79bd5443f6..c79bd5443f6 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/animations_css.html
+++ b/chromium/chrome/browser/resources/welcome/shared/animations_css.html
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/bookmark_proxy.html b/chromium/chrome/browser/resources/welcome/shared/bookmark_proxy.html
index 0336d1ff108..0336d1ff108 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/bookmark_proxy.html
+++ b/chromium/chrome/browser/resources/welcome/shared/bookmark_proxy.html
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/bookmark_proxy.js b/chromium/chrome/browser/resources/welcome/shared/bookmark_proxy.js
index d7a4da7656d..42bf8060736 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/bookmark_proxy.js
+++ b/chromium/chrome/browser/resources/welcome/shared/bookmark_proxy.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.define('nux', function() {
+cr.define('welcome', function() {
/**
* @typedef {{
* parentId: string,
@@ -30,7 +30,7 @@ cr.define('nux', function() {
isBookmarkBarShown() {}
}
- /** @implements {nux.BookmarkProxy} */
+ /** @implements {welcome.BookmarkProxy} */
class BookmarkProxyImpl {
/** @override */
addBookmark(data, callback) {
@@ -58,7 +58,7 @@ cr.define('nux', function() {
// Wrapper for bookmark proxy to keep some additional states.
class BookmarkBarManager {
constructor() {
- /** @private {nux.BookmarkProxy} */
+ /** @private {welcome.BookmarkProxy} */
this.proxy_ = BookmarkProxyImpl.getInstance();
/** @private {boolean} */
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/chooser_shared_css.html b/chromium/chrome/browser/resources/welcome/shared/chooser_shared_css.html
index 97449a20159..52b75a13193 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/chooser_shared_css.html
+++ b/chromium/chrome/browser/resources/welcome/shared/chooser_shared_css.html
@@ -1,7 +1,7 @@
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
-<link rel="import" href="chrome://resources/html/md_select_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
<link rel="import" href="navi_colors_css.html">
<dom-module id="chooser-shared-css">
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/i18n_setup.html b/chromium/chrome/browser/resources/welcome/shared/i18n_setup.html
index c505b2c1365..c505b2c1365 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/i18n_setup.html
+++ b/chromium/chrome/browser/resources/welcome/shared/i18n_setup.html
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/module_metrics_proxy.html b/chromium/chrome/browser/resources/welcome/shared/module_metrics_proxy.html
index 5c10f79489a..5c10f79489a 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/module_metrics_proxy.html
+++ b/chromium/chrome/browser/resources/welcome/shared/module_metrics_proxy.html
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/module_metrics_proxy.js b/chromium/chrome/browser/resources/welcome/shared/module_metrics_proxy.js
index 159a1870be0..d6a437b7163 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/module_metrics_proxy.js
+++ b/chromium/chrome/browser/resources/welcome/shared/module_metrics_proxy.js
@@ -2,7 +2,50 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.define('nux', function() {
+cr.define('welcome', function() {
+ /**
+ * NuxNtpBackgroundInteractions enum.
+ * These values are persisted to logs and should not be renumbered or
+ * re-used.
+ * See tools/metrics/histograms/enums.xml.
+ * @enum {number}
+ */
+ const NuxNtpBackgroundInteractions = {
+ PageShown: 0,
+ DidNothingAndNavigatedAway: 1,
+ DidNothingAndChoseSkip: 2,
+ DidNothingAndChoseNext: 3,
+ ChoseAnOptionAndNavigatedAway: 4,
+ ChoseAnOptionAndChoseSkip: 5,
+ ChoseAnOptionAndChoseNext: 6,
+ NavigatedAwayThroughBrowserHistory: 7,
+ BackgroundImageFailedToLoad: 8,
+ BackgroundImageNeverLoaded: 9,
+ };
+
+ /**
+ * NuxGoogleAppsInteractions enum.
+ * These values are persisted to logs and should not be renumbered or
+ * re-used.
+ * See tools/metrics/histograms/enums.xml.
+ * @enum {number}
+ */
+ const NuxGoogleAppsInteractions = {
+ PageShown: 0,
+ NotUsed_DEPRECATED: 1,
+ GetStarted_DEPRECATED: 2,
+ DidNothingAndNavigatedAway: 3,
+ DidNothingAndChoseSkip: 4,
+ ChoseAnOptionAndNavigatedAway: 5,
+ ChoseAnOptionAndChoseSkip: 6,
+ ChoseAnOptionAndChoseNext: 7,
+ ClickedDisabledNextButtonAndNavigatedAway: 8,
+ ClickedDisabledNextButtonAndChoseSkip: 9,
+ ClickedDisabledNextButtonAndChoseNext: 10,
+ DidNothingAndChoseNext: 11,
+ NavigatedAwayThroughBrowserHistory: 12,
+ };
+
/** @interface */
class ModuleMetricsProxy {
recordPageShown() {}
@@ -28,7 +71,7 @@ cr.define('nux', function() {
recordNavigatedAwayThroughBrowserHistory() {}
}
- /** @implements {nux.ModuleMetricsProxy} */
+ /** @implements {welcome.ModuleMetricsProxy} */
class ModuleMetricsProxyImpl {
/**
* @param {string} histogramName The histogram that will record the module
@@ -125,7 +168,7 @@ cr.define('nux', function() {
}
class ModuleMetricsManager {
- /** @param {nux.ModuleMetricsProxy} metricsProxy */
+ /** @param {welcome.ModuleMetricsProxy} metricsProxy */
constructor(metricsProxy) {
this.metricsProxy_ = metricsProxy;
@@ -190,74 +233,10 @@ cr.define('nux', function() {
}
return {
- ModuleMetricsProxy: ModuleMetricsProxy,
- ModuleMetricsProxyImpl: ModuleMetricsProxyImpl,
ModuleMetricsManager: ModuleMetricsManager,
+ ModuleMetricsProxyImpl: ModuleMetricsProxyImpl,
+ ModuleMetricsProxy: ModuleMetricsProxy,
+ NuxGoogleAppsInteractions: NuxGoogleAppsInteractions,
+ NuxNtpBackgroundInteractions: NuxNtpBackgroundInteractions,
};
});
-
-nux.GoogleAppsMetricsProxyImpl = class extends nux.ModuleMetricsProxyImpl {
- constructor() {
- /**
- * NuxGoogleAppsInteractions enum.
- * These values are persisted to logs and should not be renumbered or
- * re-used.
- * See tools/metrics/histograms/enums.xml.
- * @enum {number}
- */
- const NuxGoogleAppsInteractions = {
- PageShown: 0,
- NotUsed_DEPRECATED: 1,
- GetStarted_DEPRECATED: 2,
- DidNothingAndNavigatedAway: 3,
- DidNothingAndChoseSkip: 4,
- ChoseAnOptionAndNavigatedAway: 5,
- ChoseAnOptionAndChoseSkip: 6,
- ChoseAnOptionAndChoseNext: 7,
- ClickedDisabledNextButtonAndNavigatedAway: 8,
- ClickedDisabledNextButtonAndChoseSkip: 9,
- ClickedDisabledNextButtonAndChoseNext: 10,
- DidNothingAndChoseNext: 11,
- NavigatedAwayThroughBrowserHistory: 12,
- };
-
- super(
- 'FirstRun.NewUserExperience.GoogleAppsInteraction',
- NuxGoogleAppsInteractions);
- }
-};
-
-nux.NtpBackgroundMetricsProxyImpl = class extends nux.ModuleMetricsProxyImpl {
- constructor() {
- /**
- * NuxNtpBackgroundInteractions enum.
- * These values are persisted to logs and should not be renumbered or
- * re-used.
- * See tools/metrics/histograms/enums.xml.
- * @enum {number}
- */
- const NuxNtpBackgroundInteractions = {
- PageShown: 0,
- DidNothingAndNavigatedAway: 1,
- DidNothingAndChoseSkip: 2,
- DidNothingAndChoseNext: 3,
- ChoseAnOptionAndNavigatedAway: 4,
- ChoseAnOptionAndChoseSkip: 5,
- ChoseAnOptionAndChoseNext: 6,
- NavigatedAwayThroughBrowserHistory: 7,
- BackgroundImageFailedToLoad: 8,
- BackgroundImageNeverLoaded: 9,
- };
-
- super(
- 'FirstRun.NewUserExperience.NtpBackgroundInteraction',
- NuxNtpBackgroundInteractions);
- }
-
- getInteractions() {
- return this.interactions_;
- }
-};
-
-cr.addSingletonGetter(nux.GoogleAppsMetricsProxyImpl);
-cr.addSingletonGetter(nux.NtpBackgroundMetricsProxyImpl);
diff --git a/chromium/chrome/browser/resources/welcome/shared/navi_colors_css.html b/chromium/chrome/browser/resources/welcome/shared/navi_colors_css.html
new file mode 100644
index 00000000000..99846f3120f
--- /dev/null
+++ b/chromium/chrome/browser/resources/welcome/shared/navi_colors_css.html
@@ -0,0 +1,51 @@
+<link rel="import" href="chrome://resources/html/polymer.html">
+
+<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
+<link rel="import" href="chrome://resources/cr_elements/md_select_css.html">
+
+<dom-module id="navi-colors-css">
+ <template>
+ <style>
+ :host {
+ --navi-border-color: var(--google-grey-refresh-300);
+ --navi-check-icon-color: lightgrey;
+ --navi-keyboard-focus-color: rgba(var(--google-blue-600-rgb), .4);
+ --navi-option-box-shadow:
+ 0 1px 2px 0 rgba(var(--google-grey-800-rgb), .3),
+ 0 3px 6px 2px rgba(var(--google-grey-800-rgb), .15);
+ --navi-option-icon-shadow-color: var(--google-grey-refresh-100);
+ --navi-shape-blue-color: rgb(26, 115, 232); /* #1A73E8 */
+ --navi-shape-green-color: rgb(49, 167, 83); /* #31A753 */
+ --navi-shape-grey-color: rgb(241, 243, 244); /* #F1F3F4 */
+ --navi-shape-red-color: rgb(233, 66, 53); /* #E94235 */
+ --navi-shape-yellow-dots-color: rgb(253, 214, 99); /* #FDD663 */
+ --navi-shape-yellow-semicircle-color: rgb(250, 207, 76); /* #FACF4C */
+ --navi-step-indicator-active-color:
+ rgba(var(--google-blue-600-rgb), .5);
+ --navi-step-indicator-color: var(--google-grey-200);
+ --navi-wallpaper-text-color: var(--google-grey-refresh-700);
+ }
+
+ @media (prefers-color-scheme: dark) {
+ :host {
+ --navi-border-color: var(--google-grey-refresh-700);
+ --navi-check-icon-color: var(--google-grey-refresh-700);
+ --navi-keyboard-focus-color:
+ rgba(var(--google-blue-refresh-300-rgb), .5);
+ --navi-option-box-shadow: 0 1px 2px 0 rgba(0, 0, 0, .3),
+ 0 3px 6px 2px rgba(0, 0, 0, .15);
+ --navi-option-icon-shadow-color: var(--google-grey-refresh-700);
+ --navi-shape-blue-color: rgb(138, 180, 248); /* #8AB4F8 */
+ --navi-shape-green-color: rgb(129, 201, 149); /* #81C995 */
+ --navi-shape-grey-color: rgb(154, 160, 166); /* #9AA0A6 */
+ --navi-shape-red-color: rgb(238, 103, 92); /* #EE675C */
+ /* --navi-shape-yellow-dots-color is same color in dark mode */
+ --navi-shape-yellow-semicircle-color: rgb(253, 214, 99); /* #FDD663 */
+ --navi-step-indicator-active-color: var(--google-blue-refresh-300);
+ --navi-step-indicator-color: var(--google-grey-refresh-500);
+ --navi-wallpaper-text-color: var(--google-grey-200);
+ }
+ }
+ </style>
+ </template>
+</dom-module>
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/nux_types.js b/chromium/chrome/browser/resources/welcome/shared/nux_types.js
index f0222776a8f..d8fd86dfc57 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/nux_types.js
+++ b/chromium/chrome/browser/resources/welcome/shared/nux_types.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.exportPath('nux');
+cr.exportPath('welcome');
/**
* @typedef {{
@@ -12,7 +12,7 @@ cr.exportPath('nux');
* url: string,
* }}
*/
-nux.BookmarkListItem;
+welcome.BookmarkListItem;
/**
* @typedef {{
@@ -20,11 +20,11 @@ nux.BookmarkListItem;
* active: number,
* }}
*/
-nux.stepIndicatorModel;
+welcome.stepIndicatorModel;
/**
* TODO(hcarmona): somehow reuse from
- * chrome/browser/resources/settings/default_browser_page/default_browser_browser_proxy.js
+ * c/b/r/s/default_browser_page/default_browser_browser_proxy.js
* @typedef {{
* canBeDefault: boolean,
* isDefault: boolean,
@@ -32,4 +32,4 @@ nux.stepIndicatorModel;
* isUnknownError: boolean,
* }};
*/
-nux.DefaultBrowserInfo; \ No newline at end of file
+welcome.DefaultBrowserInfo;
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/onboarding_background.html b/chromium/chrome/browser/resources/welcome/shared/onboarding_background.html
index b77b5945646..643c8eff8ee 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/onboarding_background.html
+++ b/chromium/chrome/browser/resources/welcome/shared/onboarding_background.html
@@ -164,8 +164,10 @@
width: 100px;
}
- :host-context([dark]) #grey-oval {
- mix-blend-mode: screen;
+ @media (prefers-color-scheme: dark) {
+ #grey-oval {
+ mix-blend-mode: screen;
+ }
}
</style>
<div id="container">
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/onboarding_background.js b/chromium/chrome/browser/resources/welcome/shared/onboarding_background.js
index 12358fa84c5..12358fa84c5 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/onboarding_background.js
+++ b/chromium/chrome/browser/resources/welcome/shared/onboarding_background.js
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/splash_pages_shared_css.html b/chromium/chrome/browser/resources/welcome/shared/splash_pages_shared_css.html
index d213efc69e8..3d662b4dac4 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/splash_pages_shared_css.html
+++ b/chromium/chrome/browser/resources/welcome/shared/splash_pages_shared_css.html
@@ -35,7 +35,7 @@
text-align: center;
}
- paper-button {
+ cr-button {
font-size: 1rem;
height: 3rem;
padding-bottom: 12px;
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/step_indicator.html b/chromium/chrome/browser/resources/welcome/shared/step_indicator.html
index 4ee644b06a9..4123eb53301 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/step_indicator.html
+++ b/chromium/chrome/browser/resources/welcome/shared/step_indicator.html
@@ -21,7 +21,7 @@
}
span.active {
- @apply --navi-step-indicator-active;
+ background: var(--navi-step-indicator-active-color);
}
</style>
<template is="dom-repeat" items="[[dots_]]">
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/step_indicator.js b/chromium/chrome/browser/resources/welcome/shared/step_indicator.js
index 4a0bee38e92..4af45dc89f1 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/shared/step_indicator.js
+++ b/chromium/chrome/browser/resources/welcome/shared/step_indicator.js
@@ -10,7 +10,7 @@ Polymer({
is: 'step-indicator',
properties: {
- /** @type {nux.stepIndicatorModel} */
+ /** @type {welcome.stepIndicatorModel} */
model: Object,
/** @private */
@@ -37,4 +37,4 @@ Polymer({
getActiveClass_: function(index) {
return index == this.model.active ? 'active' : '';
},
-}); \ No newline at end of file
+});
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view.html b/chromium/chrome/browser/resources/welcome/signin_view.html
index 42e83873004..d5fc11e623e 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view.html
+++ b/chromium/chrome/browser/resources/welcome/signin_view.html
@@ -1,7 +1,6 @@
<link rel="import" href="chrome://resources/html/polymer.html">
-<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
-<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
+<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
<link rel="import" href="navigation_behavior.html">
<link rel="import" href="shared/action_link_style_css.html">
@@ -14,9 +13,7 @@
<dom-module id="signin-view">
<template>
- <style
- include="animations paper-button-style action-link-style
- splash-pages-shared-css">
+ <style include="animations action-link-style splash-pages-shared-css">
onboarding-background {
--animation-delay: 150ms;
}
@@ -29,9 +26,9 @@
<onboarding-background class="fade-in"></onboarding-background>
<h2>$i18n{signInSubHeader}</h2>
<h1 tabindex="-1">$i18n{signInHeader}</h1>
- <paper-button class="action-button" on-click="onSignInClick_">
+ <cr-button class="action-button" on-click="onSignInClick_">
$i18n{signIn}
- </paper-button>
+ </cr-button>
<button class="action-link" on-click="onNoThanksClick_">
$i18n{noThanks}
</button>
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view.js b/chromium/chrome/browser/resources/welcome/signin_view.js
index 6d8532f640f..15096824fc1 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view.js
+++ b/chromium/chrome/browser/resources/welcome/signin_view.js
@@ -13,13 +13,13 @@ Polymer({
/** @private {?welcome.WelcomeBrowserProxy} */
welcomeBrowserProxy_: null,
- /** @private {?nux.SigninViewProxy} */
+ /** @private {?welcome.SigninViewProxy} */
signinViewProxy_: null,
/** @override */
ready: function() {
this.welcomeBrowserProxy_ = welcome.WelcomeBrowserProxyImpl.getInstance();
- this.signinViewProxy_ = nux.SigninViewProxyImpl.getInstance();
+ this.signinViewProxy_ = welcome.SigninViewProxyImpl.getInstance();
},
onRouteEnter: function() {
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view_proxy.html b/chromium/chrome/browser/resources/welcome/signin_view_proxy.html
index 5d26af4e3f0..5d26af4e3f0 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view_proxy.html
+++ b/chromium/chrome/browser/resources/welcome/signin_view_proxy.html
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view_proxy.js b/chromium/chrome/browser/resources/welcome/signin_view_proxy.js
index 0d90282e7ec..0e731b9df18 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/signin_view_proxy.js
+++ b/chromium/chrome/browser/resources/welcome/signin_view_proxy.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-cr.define('nux', function() {
+cr.define('welcome', function() {
const NUX_SIGNIN_VIEW_INTERACTION_METRIC_NAME =
'FirstRun.NewUserExperience.SignInInterstitialInteraction';
@@ -32,7 +32,7 @@ cr.define('nux', function() {
recordSignIn() {}
}
- /** @implements {nux.SigninViewProxy} */
+ /** @implements {welcome.SigninViewProxy} */
class SigninViewProxyImpl {
/** @override */
recordPageShown() {
diff --git a/chromium/chrome/browser/resources/welcome/welcome.css b/chromium/chrome/browser/resources/welcome/welcome.css
index 2d08e69e941..6eb7d706567 100644
--- a/chromium/chrome/browser/resources/welcome/welcome.css
+++ b/chromium/chrome/browser/resources/welcome/welcome.css
@@ -1,42 +1,7 @@
-/* Copyright 2016 The Chromium Authors. All rights reserved.
+/* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
body {
- align-items: center;
- box-sizing: border-box;
- color: var(--paper-grey-900);
- display: flex;
- flex-direction: column;
- font-size: 100%;
- justify-content: center;
margin: 0;
- min-height: 100vh;
- padding: 8px;
-}
-
-[dark] body {
- color: var(--cr-primary-text-color);
-}
-
-.watermark {
- -webkit-mask-image: url(chrome://resources/images/google_logo.svg);
- -webkit-mask-repeat: no-repeat;
- -webkit-mask-size: 100%;
- animation: fadeIn 1s cubic-bezier(0, 0, .2, 1) both;
- background: var(--paper-grey-400);
- bottom: 24px;
- height: 24px;
- position: absolute;
- width: 74px;
-}
-
-[dark] .watermark {
- background: var(--cr-secondary-text-color);
-}
-
-@media(max-height: 608px) {
- .watermark {
- display: none;
- }
}
diff --git a/chromium/chrome/browser/resources/welcome/welcome.html b/chromium/chrome/browser/resources/welcome/welcome.html
index 4aa0ce861ec..e2a37c5b0a1 100644
--- a/chromium/chrome/browser/resources/welcome/welcome.html
+++ b/chromium/chrome/browser/resources/welcome/welcome.html
@@ -1,242 +1,22 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}>
-<head>
- <meta charset="utf-8">
- <title>$i18n{headerText}</title>
-
- <link rel="import" href="chrome://resources/html/polymer.html">
-
- <link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
- <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html">
- <link rel="import" href="chrome://resources/html/cr.html">
- <link rel="import" href="chrome://resources/html/util.html">
- <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
-
- <link rel="stylesheet" href="chrome://resources/css/md_colors.css">
- <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
- <link rel="stylesheet" href="chrome://welcome/welcome.css">
-
- <style>
- html[dark] {
- background-color: var(--md-background-color);
- }
- </style>
-
- <dom-module id="welcome-app">
- <template>
- <style include="paper-button-style">
- @keyframes slideUpContent {
- from {
- transform: translateY(186px);
- }
- }
-
- @keyframes fadeIn {
- from {
- opacity: 0;
- }
- }
-
- @keyframes fadeOut {
- to {
- opacity: 0;
- }
- }
-
-
- @keyframes fadeInAndSlideUp {
- from {
- opacity: 0;
- transform: translateY(8px);
- }
- }
-
- @keyframes spin {
- from {
- transform: rotate(1440deg) scale(0.8);
- }
- }
-
- @keyframes fadeInAndSlideDownShadow {
- from {
- opacity: .6;
- top: 0;
- }
- }
-
- @keyframes scaleUp {
- 0% {
- transform: scale(.8);
- }
- }
-
- @keyframes colorize {
- from {
- filter: grayscale(100%) brightness(128%) contrast(20%) brightness(161%);
- opacity: .6;
- }
- }
-
- @keyframes bounce {
- 0% {
- transform: matrix3d(0.8, 0, 0, 0, 0, 0.8, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 7.61% {
- transform: matrix3d(0.907, 0, 0, 0, 0, 0.907, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 11.41% {
- transform: matrix3d(0.948, 0, 0, 0, 0, 0.948, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 15.12% {
- transform: matrix3d(0.976, 0, 0, 0, 0, 0.976, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 18.92% {
- transform: matrix3d(0.996, 0, 0, 0, 0, 0.996, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 22.72% {
- transform: matrix3d(1.008, 0, 0, 0, 0, 1.008, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 30.23% {
- transform: matrix3d(1.014, 0, 0, 0, 0, 1.014, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 50.25% {
- transform: matrix3d(1.003, 0, 0, 0, 0, 1.003, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 70.27% {
- transform: matrix3d(0.999, 0, 0, 0, 0, 0.999, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- 100% {
- transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- }
- }
-
- .content {
- height: 100%;
- overflow-y: hidden;
- }
-
- .slider {
- align-items: center;
- animation: slideUpContent 600ms 1.8s cubic-bezier(.4, .2, 0, 1) both;
- display: flex;
- flex: 1;
- flex-direction: column;
- justify-content: center;
- max-width: 500px;
- }
-
- .heading {
- animation: fadeInAndSlideUp 600ms 1.9s cubic-bezier(.4, .2, 0, 1) both;
- font-size: 2.125em;
- margin-bottom: .25em;
- margin-top: 1.5em;
- text-align: center;
- }
-
- .subheading {
- animation: fadeInAndSlideUp 600ms 1.9s cubic-bezier(.4, .2, 0, 1) both;
- color: rgb(95, 99, 104);
- font-size: 1em;
- font-weight: 500;
- margin-top: .25em;
- text-align: center;
- }
-
- :host-context([dark]) .subheading {
- color: var(--cr-secondary-text-color);
- }
-
- .logo {
- animation: fadeIn 600ms both, bounce 1s 600ms linear both;
- height: 96px;
- position: relative;
- width: 96px;
- }
-
- .logo-icon {
- animation: spin 2.4s cubic-bezier(.4, .2, 0, 1) both,
- colorize 300ms 700ms linear both;
- background-image: -webkit-image-set(url(chrome://welcome/logo.png) 1x,
- url(chrome://welcome/logo2x.png) 2x);
- background-size: 100%;
- height: 96px;
- width: 96px;
- }
-
- .logo-shadow {
- animation: fadeInAndSlideDownShadow 300ms 600ms both;
- background: rgba(0, 0, 0, .2);
- border-radius: 50%;
- filter: blur(16px);
- height: 96px;
- position: absolute;
- top: 16px;
- width: 96px;
- z-index: -1;
- }
-
- .signin {
- animation: fadeInAndSlideUp 600ms 2s cubic-bezier(.4, .2, 0, 1) both;
- margin-top: 3em;
- }
-
- .signin-description {
- font-size: .875em;
- line-height: 1.725em;
- max-width: 344px;
- }
-
- .signin-buttons {
- align-items: center;
- display: flex;
- flex-direction: column;
- margin: auto;
- margin-top: 2em;
- width: fit-content;
- }
-
- paper-button {
- font-size: .8125em;
- /* Makes sure the two paper-buttons are the same width since they're
- placed vertically. Requires parent to be "width: fit-content;". */
- width: 100%;
- }
-
- #cancel {
- margin-bottom: 2px; /* Prevent focus ring from being chopped. */
- margin-top: 1.5em;
- }
- </style>
- <div class="content">
- <div class="slider">
- <div class="logo">
- <div class="logo-icon" on-click="onLogoTap_"></div>
- <div class="logo-shadow"></div>
- </div>
- <div class="heading">$i18n{headerText}</div>
- <if expr="_google_chrome">
- <div class="subheading">$i18n{subheaderText}</div>
- </if>
- <div class="signin">
- <div class="signin-description">$i18n{descriptionText}</div>
- <div class="signin-buttons">
- <paper-button class="action-button" on-tap="onAccept_">
- $i18n{acceptText}
- </paper-button>
- <paper-button id="cancel" on-tap="onDecline_">
- $i18n{declineText}
- </paper-button>
- </div>
- </div>
- </div>
- </div>
- </template>
- <script src="welcome.js"></script>
- </dom-module>
-</head>
-<body>
- <welcome-app></welcome-app>
- <div class="watermark"></div>
- <link rel="import" href="chrome://resources/html/dark_mode.html">
-</body>
+<html dir="$i18n{textdirection}" lang="$i18n{language}">
+ <head>
+ <meta charset="utf-8">
+ <title>$i18n{headerText}</title>
+ <link rel="import" href="welcome_app.html">
+ <link rel="stylesheet" href="chrome://resources/css/md_colors.css">
+ <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
+ </head>
+ <body>
+ <style>
+ @media (prefers-color-scheme: dark) {
+ html {
+ background: var(--md-background-color);
+ }
+ }
+ </style>
+ <welcome-app></welcome-app>
+ <script src="/welcome.js"></script>
+ <link rel="stylesheet" href="chrome://welcome/welcome.css">
+ </body>
</html>
diff --git a/chromium/chrome/browser/resources/welcome/welcome.js b/chromium/chrome/browser/resources/welcome/welcome.js
index 7343242cd79..2e78a6476da 100644
--- a/chromium/chrome/browser/resources/welcome/welcome.js
+++ b/chromium/chrome/browser/resources/welcome/welcome.js
@@ -1,30 +1,15 @@
-// Copyright 2016 The Chromium Authors. All rights reserved.
+// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-Polymer({
- is: 'welcome-app',
-
- /** @private */
- onAccept_: function() {
- chrome.send('handleActivateSignIn');
- },
-
- /** @private */
- onDecline_: function() {
- chrome.send('handleUserDecline');
- },
-
- /** @private */
- onLogoTap_: function() {
- this.$$('.logo-icon')
- .animate(
- {
- transform: ['none', 'rotate(-10turn)'],
- },
- /** @type {!KeyframeEffectOptions} */ ({
- duration: 500,
- easing: 'cubic-bezier(1, 0, 0, 1)',
- }));
- },
-});
+/**
+ * This file should only be included once. It will generate an assert error if
+ * it's included more than once, which can happen when an include is misspelled.
+ */
+
+cr.exportPath('welcome');
+assert(
+ !welcome.defaultResourceLoaded,
+ 'welcome.js run twice. You probably have an invalid import.');
+/** Global defined when the main welcome script runs. */
+welcome.defaultResourceLoaded = true;
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_app.html b/chromium/chrome/browser/resources/welcome/welcome_app.html
index cda34d44f91..a520eaaaf11 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_app.html
+++ b/chromium/chrome/browser/resources/welcome/welcome_app.html
@@ -3,7 +3,7 @@
<link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast.html">
<link rel="import" href="chrome://resources/cr_elements/cr_view_manager/cr_view_manager.html">
<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html">
-<link rel="import" href="chrome://resources/html/promise_resolver.html">
+<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="google_apps/nux_google_apps.html">
<link rel="import" href="landing_view.html">
<link rel="import" href="navigation_behavior.html">
@@ -16,7 +16,7 @@
<dom-module id="welcome-app">
<template>
- <style include="paper-button-style cr-hidden-style">
+ <style include="cr-hidden-style">
#viewManager {
display: flex;
font-size: 100%;
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_app.js b/chromium/chrome/browser/resources/welcome/welcome_app.js
index 03529888160..9830c921b2a 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_app.js
+++ b/chromium/chrome/browser/resources/welcome/welcome_app.js
@@ -111,7 +111,7 @@ Polymer({
/** @type {!Promise} */
const defaultBrowserPromise =
- nux.NuxSetAsDefaultProxyImpl.getInstance()
+ welcome.NuxSetAsDefaultProxyImpl.getInstance()
.requestDefaultBrowserState()
.then((status) => {
if (status.isDefault || !status.canBeDefault) {
@@ -128,7 +128,7 @@ Polymer({
return Promise
.all([
defaultBrowserPromise,
- nux.BookmarkBarManager.getInstance().initialized,
+ welcome.BookmarkBarManager.getInstance().initialized,
])
.then(([canSetDefault]) => {
modules = modules.filter(module => {
diff --git a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome_browser_proxy.html b/chromium/chrome/browser/resources/welcome/welcome_browser_proxy.html
index 24f332053f2..24f332053f2 100644
--- a/chromium/chrome/browser/resources/welcome/dice_welcome/welcome_browser_proxy.html
+++ b/chromium/chrome/browser/resources/welcome/welcome_browser_proxy.html
diff --git a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_browser_proxy.js b/chromium/chrome/browser/resources/welcome/welcome_browser_proxy.js
index 8e97cb96c28..f549f22e255 100644
--- a/chromium/chrome/browser/resources/welcome/onboarding_welcome/welcome_browser_proxy.js
+++ b/chromium/chrome/browser/resources/welcome/welcome_browser_proxy.js
@@ -8,7 +8,6 @@
*/
cr.define('welcome', function() {
-
/** @interface */
class WelcomeBrowserProxy {
/** @param {?string} redirectUrl the URL to go to, after signing in. */
diff --git a/chromium/chrome/browser/resources/welcome/welcome_win10.css b/chromium/chrome/browser/resources/welcome/welcome_win10.css
deleted file mode 100644
index 13e1025a420..00000000000
--- a/chromium/chrome/browser/resources/welcome/welcome_win10.css
+++ /dev/null
@@ -1,15 +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. */
-
-body {
- align-items: center;
- box-sizing: border-box;
- color: var(--paper-grey-900);
- display: flex;
- flex-direction: column;
- font-size: 100%;
- justify-content: center;
- margin: 0;
- min-height: 100vh;
-}
diff --git a/chromium/chrome/browser/resources/welcome/welcome_win10.html b/chromium/chrome/browser/resources/welcome/welcome_win10.html
deleted file mode 100644
index 8b7f82aa32f..00000000000
--- a/chromium/chrome/browser/resources/welcome/welcome_win10.html
+++ /dev/null
@@ -1,356 +0,0 @@
-<!DOCTYPE html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}">
-<head>
- <meta charset="utf-8">
- <title>$i18n{headerText}</title>
-
- <link rel="import" href="chrome://resources/html/polymer.html">
-
- <link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html">
- <link rel="import" href="chrome://resources/cr_elements/icons.html">
- <link rel="import" href="chrome://resources/html/cr.html">
- <link rel="import" href="chrome://resources/html/load_time_data.html">
- <link rel="import" href="chrome://resources/html/util.html">
-
- <link rel="import" href="chrome://resources/html/action_link.html">
- <link rel="import" href="chrome://resources/html/action_link_css.html">
-
- <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html">
- <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
- <link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html">
-
- <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
- <link rel="stylesheet" href="/welcome_win10.css">
-
- <script src="strings.js"></script>
-
- <dom-module id="welcome-win10">
- <template>
- <style include="action-link paper-button-style">
- :host {
- align-items: flex-start;
- display: inline-flex;
- flex-direction: column;
- opacity: 0;
- padding: 4em 1.5em 1.5em 1.5em;
- transition: opacity 300ms;
- }
-
- :host .section {
- --expandable-section-height: 28.375em;
- }
-
- :host([is-accelerated]) .section {
- --expandable-section-height: 26.375em;
- }
-
- a {
- color: var(--google-blue-500);
- text-decoration: none;
- }
-
- ol {
- margin: 0;
- overflow: auto;
- padding: 0;
- }
-
- strong {
- font-weight: 500;
- }
-
- .header-logo {
- content: url(chrome://welcome-win10/logo-large.png);
- height: 3.125em;
- margin: 0 -0.0625em;
- }
-
- h1 {
- font-size: 2.125em;
- font-weight: normal;
- margin: 0;
- padding-bottom: 2rem;
- padding-top: 1rem;
- }
-
- .sections {
- margin-bottom: 2em;
- }
-
- .section.expandable:first-child {
- border-top: 1px solid var(--google-grey-300);
- }
-
- .section.expandable {
- border-bottom: 1px solid var(--google-grey-300);
- }
-
- .section.expandable .section-heading {
- color: var(--google-blue-500);
- cursor: pointer;
- }
-
- .section-heading {
- align-items: center;
- display: flex;
- padding: 1.5em 0;
- }
-
- .section-heading-text {
- flex: 1;
- font-weight: 500;
- }
-
- .section.expandable .section-heading-text {
- font-weight: normal;
- }
-
- .section.expandable.expanded .section-heading-text {
- font-weight: 500;
- }
-
- .section-heading-expand {
- height: 1.25em;
- transition: transform 150ms cubic-bezier(.4, .2, 0, 1) 50ms;
- width: 1.25em;
- }
-
- .section.expandable.expanded .section-heading-expand {
- transform: rotate(180deg);
- transition-delay: 150ms;
- }
-
- .section-steps {
- overflow: hidden;
- }
-
- .section-steps li {
- margin-bottom: 1em;
- margin-inline-start: 1.25em;
- padding-inline-start: 1em;
- }
-
- .section-steps li:last-child {
- margin-bottom: 1em;
- }
-
- .section.expandable .section-steps {
- height: var(--expandable-section-height);
- max-height: 0;
- opacity: 0;
- transition: max-height 300ms cubic-bezier(.4, .2, 0, 1) 50ms,
- opacity 150ms;
- visibility: hidden;
- }
-
- .section.expandable.expanded .section-steps {
- max-height: var(--expandable-section-height);
- opacity: 1;
- transition: max-height 300ms cubic-bezier(.4, .2, 0, 1) 50ms,
- opacity 150ms 250ms;
- visibility: visible;
- }
-
- paper-button {
- font-size: .8125em;
- }
-
- .logo-small {
- content: url(chrome://welcome-win10/logo-small.png);
- display: inline;
- height: 1.25em;
- vertical-align: top;
- width: 1.25em;
- }
-
- .screenshot {
- display: block;
- height: 440px;
- margin: 0 auto;
- max-width: 100%;
- position: relative;
- top: -96px;
- width: 720px;
- }
-
- .screenshot-image {
- box-shadow: 0 0 0 1px rgba(0, 0, 0, .12), 0 1px 2px
- rgba(0, 0, 0, .24);
- height: 48vw;
- margin: 1em 0;
- max-height: 300px;
- max-width: 400px;
- min-height: 150px;
- min-width: 200px;
- position: relative;
- width: 64vw;
- }
-
- #default-image {
- background: url(chrome://welcome-win10/default.webp);
- background-repeat: no-repeat;
- background-size: cover;
- }
-
- #taskbar-image {
- background: url(chrome://welcome-win10/pin.webp);
- background-repeat: no-repeat;
- background-size: cover;
- }
-
- .screenshot-overlay {
- box-sizing: border-box;
- line-height: 0;
- position: absolute;
- user-select: none;
- }
-
- .screenshot-overlay div {
- cursor: default;
- }
-
- #taskbar-overlay {
- left: 31%;
- top: 73%;
- }
-
- #taskbar-overlay div {
- color: #ccc;
- font-family: Tahoma, Verdana, Segoe, sans-serif;
- font-weight: 500;
- }
-
- #switch-anyway-overlay {
- left: 38%;
- top: 83%;
- }
-
- #switch-anyway-overlay div {
- color: rgb(0, 117, 218);
- font-family: Segoe UI;
- }
-
- #icon-overlay {
- background-image: url(chrome://welcome-win10/logo-small.png);
- background-size: cover;
- height: 8%;
- left: 46%;
- top: 90%;
- width: 6%;
- }
-
- /* These values are precisely set so that the text over the screenshot
- * starts scaling at the same time the image starts scaling too. */
- @media (max-width: 626px) {
- #taskbar-overlay {
- font-size: 1.95vw;
- }
-
- #switch-anyway-overlay {
- font-size: 1.92vw;
- }
- }
-
- /* Font-sizes used when the screenshot exactly reaches its max size. */
- @media (min-width: 626px) {
- #taskbar-overlay {
- font-size: 12.2px;
- }
-
- #switch-anyway-overlay {
- font-size: 12px;
- }
- }
- </style>
- <div class="header-logo" role="presentation"></div>
- <h1>$i18n{headerText}</h1>
- <div class="sections">
- <div class$="[[computeClasses(isCombined)]]">
- <template is="dom-if" if="[[isCombined]]">
- <div role="heading" aria-level="2">
- <a id="tab1" is="action-link" class="section-heading"
- on-tap="onToggle" role="button" aria-controls="panel1"
- aria-expanded="true">
- <div class="section-heading-text" role="presentation">
- $i18n{defaultBrowserSubheaderText}
- </div>
- <iron-icon class="section-heading-expand" icon="cr:expand-more"
- role="presentation">
- </iron-icon>
- </a>
- </div>
- </template>
- <template is="dom-if" if="[[!isCombined]]">
- <div class="section-heading" role="text">
- <div class="section-heading-text" role="presentation">
- $i18n{defaultBrowserSubheaderText}
- </div>
- </div>
- </template>
- <ol id="panel1" class="section-steps" aria-labelledby="tab1">
- <li>
- <a is="action-link" on-tap="onOpenSettings">
- $i18n{openSettingsText}
- </a>
- </li>
- <template is="dom-if" if="[[!isAccelerated]]">
- <li>
- <div role="presentation">$i18nRaw{clickEdgeText}</div>
- </li>
- </template>
- <li>
- <div role="presentation">$i18nRaw{clickSelectChrome}</div>
- </li>
- <li>
- <div role="presentation">$i18nRaw{clickSwitchAnywayText}</div>
- <div class="screenshot-image" id="default-image"
- role="presentation">
- <div class="screenshot-overlay" id="switch-anyway-overlay">
- <div aria-hidden="true">$i18n{switchAnywayLabel}</div>
- </div>
- </div>
- </li>
- </ol>
- </div>
- <template is="dom-if" if="[[isCombined]]">
- <div class="section expandable">
- <div role="heading" aria-level="2">
- <a id="tab2" is="action-link" class="section-heading"
- on-tap="onToggle" role="button" aria-controls="panel2"
- aria-expanded="false">
- <div class="section-heading-text" role="presentation">
- $i18n{pinSubheaderText}
- </div>
- <iron-icon class="section-heading-expand" icon="cr:expand-more"
- role="presentation">
- </iron-icon>
- </a>
- </div>
- <ol id="panel2" class="section-steps" aria-labelledby="tab2">
- <li>$i18nRaw{rightClickText}</li>
- <li>
- <div role="presentation">$i18nRaw{pinInstructionText}</div>
- <div class="screenshot-image" id="taskbar-image"
- role="presentation">
- <div class="screenshot-overlay" id="taskbar-overlay">
- <div aria-hidden="true">$i18n{pinToTaskbarLabel}</div>
- </div>
- <div class="screenshot-overlay" id="icon-overlay">
- </div>
- </div>
- </li>
- </ol>
- </div>
- </template>
- </div>
- <paper-button class="action-button" on-tap="onContinue">
- $i18n{continueText}
- </paper-button>
- </template>
- <script src="/welcome_win10.js"></script>
- </dom-module>
-</head>
-<body>
- <welcome-win10></welcome-win10>
-</body>
-</html>
diff --git a/chromium/chrome/browser/resources/welcome/welcome_win10.js b/chromium/chrome/browser/resources/welcome/welcome_win10.js
deleted file mode 100644
index 0f3ac5edcb5..00000000000
--- a/chromium/chrome/browser/resources/welcome/welcome_win10.js
+++ /dev/null
@@ -1,86 +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.
-
-Polymer({
- is: 'welcome-win10',
-
- properties: {
- // Determines if the combined variant should be displayed. The combined
- // variant includes instructions on how to pin Chrome to the taskbar.
- isCombined: {
- type: Boolean,
- value: false,
- },
-
- // Indicates if the accelerated flow is enabled.
- isAccelerated: {
- type: Boolean,
- value: function() {
- return loadTimeData.getBoolean('acceleratedFlowEnabled');
- },
- reflectToAttribute: true,
- },
- },
-
- receivePinnedState_: function(isPinnedToTaskbar) {
- // Allow overriding of the result via a query parameter.
- // TODO(pmonette): Remove these checks when they are no longer needed.
- const VARIANT_KEY = 'variant';
- const VARIANT_TYPE_MAP = {'defaultonly': false, 'combined': true};
- const params = new URLSearchParams(location.search);
- if (params.has(VARIANT_KEY) &&
- params.get(VARIANT_KEY) in VARIANT_TYPE_MAP) {
- this.isCombined = VARIANT_TYPE_MAP[params.get(VARIANT_KEY)];
- } else {
- this.isCombined = !isPinnedToTaskbar;
- }
-
- // Show the module.
- this.style.opacity = 1;
- },
-
- ready: function() {
- // The accelerated flow can be overridden with a query parameter.
- const FLOWTYPE_KEY = 'flowtype';
- const FLOW_TYPE_MAP = {'regular': false, 'accelerated': true};
- const params = new URLSearchParams(location.search);
- if (params.has(FLOWTYPE_KEY)) {
- if (params.get(FLOWTYPE_KEY) in FLOW_TYPE_MAP) {
- this.isAccelerated = FLOW_TYPE_MAP[params.get(FLOWTYPE_KEY)];
- } else {
- console.error(
- 'Found invalid value for the \'flowtype\' parameter: %s',
- params.get(FLOWTYPE_KEY));
- }
- }
-
- // Asynchronously check if Chrome is pinned to the taskbar.
- cr.sendWithPromise('getPinnedToTaskbarState')
- .then(this.receivePinnedState_.bind(this));
- },
-
- computeClasses: function(isCombined) {
- return isCombined ? 'section expandable expanded' : 'section';
- },
-
- onContinue: function() {
- chrome.send('handleContinue');
- },
-
- onOpenSettings: function() {
- chrome.send('handleSetDefaultBrowser');
- },
-
- onToggle: function() {
- if (!this.isCombined) {
- return;
- }
- const sections = this.shadowRoot.querySelectorAll('.section.expandable');
- sections.forEach(function(section) {
- const isExpanded = section.classList.toggle('expanded');
- section.querySelector('[role~="button"]')
- .setAttribute('aria-expanded', isExpanded);
- });
- }
-});
diff --git a/chromium/chrome/browser/safe_browsing/BUILD.gn b/chromium/chrome/browser/safe_browsing/BUILD.gn
index cc98a0bf4f1..2be129ce18a 100644
--- a/chromium/chrome/browser/safe_browsing/BUILD.gn
+++ b/chromium/chrome/browser/safe_browsing/BUILD.gn
@@ -36,10 +36,10 @@ jumbo_static_library("safe_browsing") {
"//components/safe_browsing/web_ui",
"//components/search_engines",
"//components/sessions",
+ "//components/signin/public/identity_manager",
"//components/url_formatter",
"//mojo/public/cpp/platform",
"//mojo/public/cpp/system",
- "//services/identity/public/cpp",
"//services/preferences/public/cpp",
]
@@ -98,10 +98,12 @@ jumbo_static_library("safe_browsing") {
"//components/safe_browsing/browser",
"//components/safe_browsing/common",
"//components/safe_browsing/common:safe_browsing_prefs",
+ "//components/safe_browsing/db:allowlist_checker_client",
"//components/safe_browsing/db:metadata_proto",
- "//components/safe_browsing/db:whitelist_checker_client",
"//components/safe_browsing/password_protection",
"//components/safe_browsing/triggers",
+ "//components/safe_browsing/triggers:ad_popup_trigger",
+ "//components/safe_browsing/triggers:ad_redirect_trigger",
"//components/safe_browsing/triggers:ad_sampler_trigger",
"//components/safe_browsing/triggers:suspicious_site_trigger",
"//components/safe_browsing/triggers:trigger_throttler",
@@ -112,8 +114,6 @@ jumbo_static_library("safe_browsing") {
sources += [
"../download/download_completion_blocker.cc",
"../download/download_completion_blocker.h",
- "../loader/safe_browsing_resource_throttle.cc",
- "../loader/safe_browsing_resource_throttle.h",
"browser_feature_extractor.cc",
"browser_feature_extractor.h",
"browser_features.cc",
@@ -126,6 +126,8 @@ jumbo_static_library("safe_browsing") {
"client_side_detection_service.h",
"client_side_model_loader.cc",
"client_side_model_loader.h",
+ "download_protection/binary_upload_service.cc",
+ "download_protection/binary_upload_service.h",
"download_protection/check_client_download_request.cc",
"download_protection/check_client_download_request.h",
"download_protection/download_feedback.cc",
@@ -140,6 +142,8 @@ jumbo_static_library("safe_browsing") {
"download_protection/download_url_sb_client.h",
"download_protection/file_analyzer.cc",
"download_protection/file_analyzer.h",
+ "download_protection/multipart_uploader.cc",
+ "download_protection/multipart_uploader.h",
"download_protection/path_sanitizer.cc",
"download_protection/path_sanitizer.h",
"download_protection/ppapi_download_request.cc",
@@ -208,9 +212,9 @@ jumbo_static_library("safe_browsing") {
"//components/content_settings/core/browser",
"//components/language/core/common",
"//components/prefs",
+ "//components/safe_browsing:webprotect_proto",
"//components/safe_browsing/db",
"//components/security_interstitials/content:security_interstitial_page",
- "//components/signin/core/browser",
"//content/public/browser",
"//net",
]
@@ -219,8 +223,6 @@ jumbo_static_library("safe_browsing") {
}
} else if (safe_browsing_mode == 2) {
sources += [
- "../loader/safe_browsing_resource_throttle.cc",
- "../loader/safe_browsing_resource_throttle.h",
"android/file_type_policies.cc",
"android/services_delegate_android.cc",
"android/services_delegate_android.h",
@@ -233,8 +235,6 @@ jumbo_static_library("safe_browsing") {
]
} else if (safe_browsing_mode == 3) {
sources += [
- "../loader/safe_browsing_resource_throttle.cc",
- "../loader/safe_browsing_resource_throttle.h",
"android/file_type_policies.cc",
"android/services_delegate_android.cc",
"android/services_delegate_android.h",
@@ -262,9 +262,8 @@ static_library("advanced_protection") {
"//components/prefs",
"//components/safe_browsing/common",
"//components/safe_browsing/common:safe_browsing_prefs",
- "//components/signin/core/browser",
+ "//components/signin/public/identity_manager",
"//content/public/browser",
- "//services/identity/public/cpp",
]
}
diff --git a/chromium/chrome/browser/safe_browsing/chrome_cleaner/BUILD.gn b/chromium/chrome/browser/safe_browsing/chrome_cleaner/BUILD.gn
index 7b7d767ce54..630f878f95c 100644
--- a/chromium/chrome/browser/safe_browsing/chrome_cleaner/BUILD.gn
+++ b/chromium/chrome/browser/safe_browsing/chrome_cleaner/BUILD.gn
@@ -3,6 +3,7 @@
# found in the LICENSE file.
import("//build/config/jumbo.gni")
+import("//third_party/protobuf/proto_library.gni")
source_set("public") {
sources = [
@@ -41,12 +42,14 @@ jumbo_static_library("chrome_cleaner") {
"chrome_cleaner_reboot_dialog_controller_impl_win.h",
"chrome_cleaner_runner_win.cc",
"chrome_cleaner_runner_win.h",
+ "chrome_prompt_actions_win.cc",
+ "chrome_prompt_actions_win.h",
+ "chrome_prompt_channel_win.cc",
+ "chrome_prompt_channel_win.h",
"reporter_runner_win.cc",
"reporter_runner_win.h",
"settings_resetter_win.cc",
"settings_resetter_win.h",
- "srt_chrome_prompt_impl_win.cc",
- "srt_chrome_prompt_impl_win.h",
"srt_client_info_win.cc",
"srt_client_info_win.h",
]
@@ -61,6 +64,7 @@ jumbo_static_library("chrome_cleaner") {
"//chrome/installer/util:with_no_strings",
"//components/chrome_cleaner/public/constants",
"//components/chrome_cleaner/public/interfaces",
+ "//components/chrome_cleaner/public/proto",
"//components/component_updater",
"//components/crx_file",
"//components/pref_registry",
@@ -68,5 +72,6 @@ jumbo_static_library("chrome_cleaner") {
"//components/safe_browsing/common:safe_browsing_prefs",
"//content/public/browser",
"//extensions/browser",
+ "//third_party/protobuf:protobuf_lite",
]
}
diff --git a/chromium/chrome/browser/search/BUILD.gn b/chromium/chrome/browser/search/BUILD.gn
index b9a569ff93c..338bfa87e33 100644
--- a/chromium/chrome/browser/search/BUILD.gn
+++ b/chromium/chrome/browser/search/BUILD.gn
@@ -8,7 +8,7 @@ action("local_ntp_code_generate") {
script = "tools/generate_integrity_header.py"
header_path = "$target_gen_dir/local_ntp_js_integrity.h"
animations_js = local_ntp_resources + "/animations.js"
- custom_bg_js = local_ntp_resources + "/custom_backgrounds.js"
+ customize_js = local_ntp_resources + "/customize.js"
doodles_js = local_ntp_resources + "/doodles.js"
local_ntp_js = local_ntp_resources + "/local_ntp.js"
utils_js = local_ntp_resources + "/utils.js"
@@ -16,7 +16,7 @@ action("local_ntp_code_generate") {
inputs = [
animations_js,
- custom_bg_js,
+ customize_js,
doodles_js,
local_ntp_js,
utils_js,
@@ -30,7 +30,7 @@ action("local_ntp_code_generate") {
args = [
"--output_path=" + rebase_path(header_path, root_build_dir),
rebase_path(animations_js, root_build_dir),
- rebase_path(custom_bg_js, root_build_dir),
+ rebase_path(customize_js, root_build_dir),
rebase_path(doodles_js, root_build_dir),
rebase_path(local_ntp_js, root_build_dir),
rebase_path(utils_js, root_build_dir),
diff --git a/chromium/chrome/browser/sharing/proto/BUILD.gn b/chromium/chrome/browser/sharing/proto/BUILD.gn
index 5971cdb4dde..832182ad6d2 100644
--- a/chromium/chrome/browser/sharing/proto/BUILD.gn
+++ b/chromium/chrome/browser/sharing/proto/BUILD.gn
@@ -13,6 +13,7 @@ group("proto_lite") {
proto_library("proto") {
sources = [
+ "click_to_call_message.proto",
"sharing_message.proto",
]
}
diff --git a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc
index 0832417a9ff..2a8968b4ee2 100644
--- a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc
+++ b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc
@@ -10,20 +10,20 @@
#include "chrome/browser/spellchecker/spellcheck_factory.h"
#include "chrome/browser/spellchecker/spellcheck_service.h"
#include "components/spellcheck/browser/spellcheck_host_metrics.h"
-#include "components/spellcheck/common/spellcheck_result.h"
+#include "components/spellcheck/browser/spellcheck_platform.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
-#if !defined(OS_MACOSX)
-// Mac needs different constructor and destructor for Mac-only members.
+#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+#include "chrome/browser/spellchecker/spelling_request.h"
+#endif
SpellCheckHostChromeImpl::SpellCheckHostChromeImpl(
const service_manager::Identity& renderer_identity)
- : renderer_identity_(renderer_identity), weak_factory_(this) {}
+ : renderer_identity_(renderer_identity) {}
SpellCheckHostChromeImpl::~SpellCheckHostChromeImpl() = default;
-#endif
// static
void SpellCheckHostChromeImpl::Create(
@@ -64,7 +64,7 @@ void SpellCheckHostChromeImpl::NotifyChecked(const base::string16& word,
spellcheck->GetMetrics()->RecordCheckedWordStats(word, misspelled);
}
-#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+#if BUILDFLAG(USE_RENDERER_SPELLCHECKER)
void SpellCheckHostChromeImpl::CallSpellingService(
const base::string16& text,
CallSpellingServiceCallback callback) {
@@ -123,7 +123,74 @@ std::vector<SpellCheckResult> SpellCheckHostChromeImpl::FilterCustomWordResults(
return results;
}
-#endif // !BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+#endif // BUILDFLAG(USE_RENDERER_SPELLCHECKER)
+
+#if defined(OS_MACOSX) || defined(OS_WIN)
+
+void SpellCheckHostChromeImpl::CheckSpelling(const base::string16& word,
+ int route_id,
+ CheckSpellingCallback callback) {
+ bool correct = spellcheck_platform::CheckSpelling(word, route_id);
+ std::move(callback).Run(correct);
+}
+
+void SpellCheckHostChromeImpl::FillSuggestionList(
+ const base::string16& word,
+ FillSuggestionListCallback callback) {
+ std::vector<base::string16> suggestions;
+ spellcheck_platform::FillSuggestionList(word, &suggestions);
+ std::move(callback).Run(suggestions);
+}
+
+void SpellCheckHostChromeImpl::RequestTextCheck(
+ const base::string16& text,
+ int route_id,
+ RequestTextCheckCallback callback) {
+ DCHECK(!text.empty());
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+
+ // Initialize the spellcheck service if needed. The service will send the
+ // language code for text breaking to the renderer. (Text breaking is required
+ // for the context menu to show spelling suggestions.) Initialization must
+ // happen on UI thread.
+ GetSpellcheckService();
+
+ // |SpellingRequest| self-destructs on completion.
+ // OK to store unretained |this| in a |SpellingRequest| owned by |this|.
+ requests_.insert(std::make_unique<SpellingRequest>(
+ &client_, text, renderer_identity_, route_id, std::move(callback),
+ base::BindOnce(&SpellCheckHostChromeImpl::OnRequestFinished,
+ base::Unretained(this))));
+}
+
+void SpellCheckHostChromeImpl::OnRequestFinished(SpellingRequest* request) {
+ auto iterator = requests_.find(request);
+ requests_.erase(iterator);
+}
+
+// static
+void SpellCheckHostChromeImpl::CombineResultsForTesting(
+ std::vector<SpellCheckResult>* remote_results,
+ const std::vector<SpellCheckResult>& local_results) {
+ SpellingRequest::CombineResults(remote_results, local_results);
+}
+#endif // defined(OS_MACOSX) || defined(OS_WIN)
+
+#if defined(OS_MACOSX)
+int SpellCheckHostChromeImpl::ToDocumentTag(int route_id) {
+ if (!tag_map_.count(route_id))
+ tag_map_[route_id] = spellcheck_platform::GetDocumentTag();
+ return tag_map_[route_id];
+}
+
+// TODO(groby): We are currently not notified of retired tags. We need
+// to track destruction of RenderViewHosts on the browser process side
+// to update our mappings when a document goes away.
+void SpellCheckHostChromeImpl::RetireDocumentTag(int route_id) {
+ spellcheck_platform::CloseDocumentWithTag(ToDocumentTag(route_id));
+ tag_map_.erase(route_id);
+}
+#endif // defined(OS_MACOSX)
SpellcheckService* SpellCheckHostChromeImpl::GetSpellcheckService() const {
return SpellcheckServiceFactory::GetForRenderer(renderer_identity_);
diff --git a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h
index be996ad2b8f..dd3af7f8d09 100644
--- a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h
+++ b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h
@@ -35,7 +35,7 @@ class SpellCheckHostChromeImpl : public SpellCheckHostImpl {
void RequestDictionary() override;
void NotifyChecked(const base::string16& word, bool misspelled) override;
-#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+#if BUILDFLAG(USE_RENDERER_SPELLCHECKER)
void CallSpellingService(const base::string16& text,
CallSpellingServiceCallback callback) override;
@@ -55,9 +55,9 @@ class SpellCheckHostChromeImpl : public SpellCheckHostImpl {
const std::vector<SpellCheckResult>& service_results);
#endif
-#if defined(OS_MACOSX)
- // Non-Mac (i.e., Android) implementations of the following APIs are in the
- // base class SpellCheckHostImpl.
+#if defined(OS_MACOSX) || defined(OS_WIN)
+ // Non-Mac and non-Win(i.e., Android) implementations of the following APIs
+ // are in the base class SpellCheckHostImpl.
void CheckSpelling(const base::string16& word,
int route_id,
CheckSpellingCallback callback) override;
@@ -75,13 +75,15 @@ class SpellCheckHostChromeImpl : public SpellCheckHostImpl {
std::vector<SpellCheckResult>* remote_results,
const std::vector<SpellCheckResult>& local_results);
- int ToDocumentTag(int route_id);
- void RetireDocumentTag(int route_id);
- std::map<int, int> tag_map_;
-
// All pending requests.
std::set<std::unique_ptr<SpellingRequest>, base::UniquePtrComparator>
requests_;
+#endif // defined(OS_MACOSX) || defined(OS_WIN)
+
+#if defined(OS_MACOSX)
+ int ToDocumentTag(int route_id);
+ void RetireDocumentTag(int route_id);
+ std::map<int, int> tag_map_;
#endif // defined(OS_MACOSX)
// Returns the SpellcheckService of our |render_process_id_|. The return
@@ -94,7 +96,7 @@ class SpellCheckHostChromeImpl : public SpellCheckHostImpl {
// A JSON-RPC client that calls the remote Spelling service.
SpellingServiceClient client_;
- base::WeakPtrFactory<SpellCheckHostChromeImpl> weak_factory_;
+ base::WeakPtrFactory<SpellCheckHostChromeImpl> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SpellCheckHostChromeImpl);
};
diff --git a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_mac.cc b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_mac.cc
deleted file mode 100644
index 6ab03af88c4..00000000000
--- a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_mac.cc
+++ /dev/null
@@ -1,272 +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/spellchecker/spell_check_host_chrome_impl.h"
-
-#include "base/barrier_closure.h"
-#include "base/bind.h"
-#include "base/task/post_task.h"
-#include "chrome/browser/spellchecker/spellcheck_factory.h"
-#include "chrome/browser/spellchecker/spellcheck_service.h"
-#include "components/spellcheck/browser/spellcheck_platform.h"
-#include "content/public/browser/browser_context.h"
-#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/render_process_host.h"
-#include "services/service_manager/public/cpp/identity.h"
-
-using content::BrowserThread;
-using content::BrowserContext;
-
-namespace {
-
-bool CompareLocation(const SpellCheckResult& r1, const SpellCheckResult& r2) {
- return r1.location < r2.location;
-}
-
-// Adjusts remote_results by examining local_results. Any result that's both
-// local and remote stays type SPELLING, all others are flagged GRAMMAR.
-// (This is needed to force gray underline for remote-only results.)
-void CombineResults(std::vector<SpellCheckResult>* remote_results,
- const std::vector<SpellCheckResult>& local_results) {
- std::vector<SpellCheckResult>::const_iterator local_iter(
- local_results.begin());
- std::vector<SpellCheckResult>::iterator remote_iter;
-
- for (remote_iter = remote_results->begin();
- remote_iter != remote_results->end(); ++remote_iter) {
- // Discard all local results occurring before remote result.
- while (local_iter != local_results.end() &&
- local_iter->location < remote_iter->location) {
- local_iter++;
- }
-
- // Unless local and remote result coincide, result is GRAMMAR.
- remote_iter->decoration = SpellCheckResult::GRAMMAR;
- if (local_iter != local_results.end() &&
- local_iter->location == remote_iter->location &&
- local_iter->length == remote_iter->length) {
- remote_iter->decoration = SpellCheckResult::SPELLING;
- }
- }
-}
-
-} // namespace
-
-// SpellingRequest is owned by SpellCheckHostChromeImpl.
-class SpellingRequest {
- public:
- using RequestTextCheckCallback =
- spellcheck::mojom::SpellCheckHost::RequestTextCheckCallback;
- using DestructionCallback = base::OnceCallback<void(SpellingRequest*)>;
-
- SpellingRequest(SpellingServiceClient* client,
- const base::string16& text,
- const service_manager::Identity& renderer_identity,
- int document_tag,
- RequestTextCheckCallback callback,
- DestructionCallback destruction_callback);
-
- private:
- // Request server-side checking for |text_|.
- void RequestRemoteCheck(SpellingServiceClient* client,
- const service_manager::Identity& renderer_identity);
-
- // Request a check for |text_| from local spell checker.
- void RequestLocalCheck(int document_tag);
-
- // Check if all pending requests are done, send reply to render process if so.
- void OnCheckCompleted();
-
- // Called when server-side checking is complete. Must be called on UI thread.
- void OnRemoteCheckCompleted(bool success,
- const base::string16& text,
- const std::vector<SpellCheckResult>& results);
-
- // Called when local checking is complete. Must be called on UI thread.
- void OnLocalCheckCompleted(const std::vector<SpellCheckResult>& results);
-
- // Forwards the results back to UI thread when local checking completes.
- static void OnLocalCheckCompletedOnAnyThread(
- base::WeakPtr<SpellingRequest> request,
- const std::vector<SpellCheckResult>& results);
-
- std::vector<SpellCheckResult> local_results_;
- std::vector<SpellCheckResult> remote_results_;
-
- // Barrier closure for completion of both remote and local check.
- base::RepeatingClosure completion_barrier_;
- bool remote_success_;
-
- // The string to be spell-checked.
- base::string16 text_;
-
- // Callback to send the results to renderer.
- RequestTextCheckCallback callback_;
-
- // Callback to delete |this|. Called on |this| after everything is done.
- DestructionCallback destruction_callback_;
-
- base::WeakPtrFactory<SpellingRequest> weak_factory_;
-};
-
-SpellingRequest::SpellingRequest(
- SpellingServiceClient* client,
- const base::string16& text,
- const service_manager::Identity& renderer_identity,
- int document_tag,
- RequestTextCheckCallback callback,
- DestructionCallback destruction_callback)
- : remote_success_(false),
- text_(text),
- callback_(std::move(callback)),
- destruction_callback_(std::move(destruction_callback)),
- weak_factory_(this) {
- DCHECK(!text_.empty());
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
-
- completion_barrier_ =
- BarrierClosure(2, base::BindOnce(&SpellingRequest::OnCheckCompleted,
- weak_factory_.GetWeakPtr()));
- RequestRemoteCheck(client, renderer_identity);
- RequestLocalCheck(document_tag);
-}
-
-void SpellingRequest::RequestRemoteCheck(
- SpellingServiceClient* client,
- const service_manager::Identity& renderer_identity) {
- BrowserContext* context =
- content::BrowserContext::GetBrowserContextForServiceInstanceGroup(
- renderer_identity.instance_group());
-
- // |this| may be gone at callback invocation if the owner has been removed.
- client->RequestTextCheck(
- context, SpellingServiceClient::SPELLCHECK, text_,
- base::BindOnce(&SpellingRequest::OnRemoteCheckCompleted,
- weak_factory_.GetWeakPtr()));
-}
-
-void SpellingRequest::RequestLocalCheck(int document_tag) {
- // |this| may be gone at callback invocation if the owner has been removed.
- spellcheck_platform::RequestTextCheck(
- document_tag, text_,
- base::BindOnce(&SpellingRequest::OnLocalCheckCompletedOnAnyThread,
- weak_factory_.GetWeakPtr()));
-}
-
-void SpellingRequest::OnCheckCompleted() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
-
- std::vector<SpellCheckResult>* check_results = &local_results_;
- if (remote_success_) {
- std::sort(remote_results_.begin(), remote_results_.end(), CompareLocation);
- std::sort(local_results_.begin(), local_results_.end(), CompareLocation);
- CombineResults(&remote_results_, local_results_);
- check_results = &remote_results_;
- }
-
- std::move(callback_).Run(*check_results);
-
- std::move(destruction_callback_).Run(this);
-
- // |destruction_callback_| removes |this|. No more operations allowed.
-}
-
-void SpellingRequest::OnRemoteCheckCompleted(
- bool success,
- const base::string16& text,
- const std::vector<SpellCheckResult>& results) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- remote_success_ = success;
- remote_results_ = results;
- completion_barrier_.Run();
-}
-
-// static
-void SpellingRequest::OnLocalCheckCompletedOnAnyThread(
- base::WeakPtr<SpellingRequest> request,
- const std::vector<SpellCheckResult>& results) {
- // Local checking can happen on any thread - don't DCHECK thread.
- base::PostTaskWithTraits(
- FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&SpellingRequest::OnLocalCheckCompleted, request,
- results));
-}
-
-void SpellingRequest::OnLocalCheckCompleted(
- const std::vector<SpellCheckResult>& results) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- local_results_ = results;
- completion_barrier_.Run();
-}
-
-SpellCheckHostChromeImpl::SpellCheckHostChromeImpl(
- const service_manager::Identity& renderer_identity)
- : renderer_identity_(renderer_identity), weak_factory_(this) {}
-
-SpellCheckHostChromeImpl::~SpellCheckHostChromeImpl() = default;
-
-// static
-void SpellCheckHostChromeImpl::CombineResultsForTesting(
- std::vector<SpellCheckResult>* remote_results,
- const std::vector<SpellCheckResult>& local_results) {
- CombineResults(remote_results, local_results);
-}
-
-void SpellCheckHostChromeImpl::CheckSpelling(const base::string16& word,
- int route_id,
- CheckSpellingCallback callback) {
- bool correct =
- spellcheck_platform::CheckSpelling(word, ToDocumentTag(route_id));
- std::move(callback).Run(correct);
-}
-
-void SpellCheckHostChromeImpl::FillSuggestionList(
- const base::string16& word,
- FillSuggestionListCallback callback) {
- std::vector<base::string16> suggestions;
- spellcheck_platform::FillSuggestionList(word, &suggestions);
- std::move(callback).Run(suggestions);
-}
-
-void SpellCheckHostChromeImpl::RequestTextCheck(
- const base::string16& text,
- int route_id,
- RequestTextCheckCallback callback) {
- DCHECK(!text.empty());
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
-
- // Initialize the spellcheck service if needed. The service will send the
- // language code for text breaking to the renderer. (Text breaking is required
- // for the context menu to show spelling suggestions.) Initialization must
- // happen on UI thread.
- GetSpellcheckService();
-
- // |SpellingRequest| self-destructs on completion.
- // OK to store unretained |this| in a |SpellingRequest| owned by |this|.
- requests_.insert(std::make_unique<SpellingRequest>(
- &client_, text, renderer_identity_, ToDocumentTag(route_id),
- std::move(callback),
- base::BindOnce(&SpellCheckHostChromeImpl::OnRequestFinished,
- base::Unretained(this))));
-}
-
-void SpellCheckHostChromeImpl::OnRequestFinished(SpellingRequest* request) {
- auto iterator = requests_.find(request);
- requests_.erase(iterator);
-}
-
-int SpellCheckHostChromeImpl::ToDocumentTag(int route_id) {
- if (!tag_map_.count(route_id))
- tag_map_[route_id] = spellcheck_platform::GetDocumentTag();
- return tag_map_[route_id];
-}
-
-// TODO(groby): We are currently not notified of retired tags. We need
-// to track destruction of RenderViewHosts on the browser process side
-// to update our mappings when a document goes away.
-void SpellCheckHostChromeImpl::RetireDocumentTag(int route_id) {
- spellcheck_platform::CloseDocumentWithTag(ToDocumentTag(route_id));
- tag_map_.erase(route_id);
-}
diff --git a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_unittest.cc b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_unittest.cc
index 8f777b56fa5..83cf0cb522c 100644
--- a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_unittest.cc
+++ b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_unittest.cc
@@ -14,8 +14,8 @@
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
-#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
-#error !BUILDFLAG(USE_BROWSER_SPELLCHECKER) is required for these tests.
+#if !BUILDFLAG(USE_RENDERER_SPELLCHECKER)
+#error BUILDFLAG(USE_RENDERER_SPELLCHECKER) is required for these tests.
#endif
class TestSpellCheckHostChromeImpl {
diff --git a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_win_browsertest.cc b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_win_browsertest.cc
new file mode 100644
index 00000000000..f1c65ad82a7
--- /dev/null
+++ b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_win_browsertest.cc
@@ -0,0 +1,97 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h"
+
+#include "base/bind.h"
+#include "base/run_loop.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/test/scoped_feature_list.h"
+#include "base/win/windows_version.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/test/base/in_process_browser_test.h"
+#include "components/spellcheck/browser/spellcheck_platform.h"
+#include "components/spellcheck/common/spellcheck_features.h"
+#include "content/public/browser/browser_context.h"
+#include "content/public/test/mock_render_process_host.h"
+
+class SpellCheckHostChromeImplWinBrowserTest : public InProcessBrowserTest {
+ public:
+ void SetUpOnMainThread() override {
+ content::BrowserContext* context = browser()->profile();
+ renderer_.reset(new content::MockRenderProcessHost(context));
+
+ service_manager::BindSourceInfo source_info;
+ source_info.identity = renderer_->GetChildIdentity();
+
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndEnableFeature(spellcheck::kWinUseBrowserSpellChecker);
+
+ SpellCheckHostChromeImpl::Create(mojo::MakeRequest(&spell_check_host_),
+ source_info);
+ }
+
+ void TearDownOnMainThread() override { renderer_.reset(); }
+
+ void LogResult(const std::vector<SpellCheckResult>& result) {
+ received_result_ = true;
+ result_ = result;
+ if (quit_)
+ std::move(quit_).Run();
+ }
+
+ void SetLanguageCompletionCallback(bool result) {
+ received_result_ = true;
+ if (quit_)
+ std::move(quit_).Run();
+ }
+
+ void RunUntilResultReceived() {
+ if (received_result_)
+ return;
+ base::RunLoop run_loop;
+ quit_ = run_loop.QuitClosure();
+ run_loop.Run();
+
+ // reset status
+ received_result_ = false;
+ }
+
+ protected:
+ std::unique_ptr<content::MockRenderProcessHost> renderer_;
+ spellcheck::mojom::SpellCheckHostPtr spell_check_host_;
+
+ bool received_result_ = false;
+ std::vector<SpellCheckResult> result_;
+ base::OnceClosure quit_;
+};
+
+// Uses browsertest to setup chrome threads.
+IN_PROC_BROWSER_TEST_F(SpellCheckHostChromeImplWinBrowserTest,
+ SpellCheckReturnMessage) {
+ if (base::win::GetVersion() < base::win::Version::WIN8)
+ return;
+
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndEnableFeature(spellcheck::kWinUseBrowserSpellChecker);
+
+ spellcheck_platform::SetLanguage(
+ "en-US", base::BindOnce(&SpellCheckHostChromeImplWinBrowserTest::
+ SetLanguageCompletionCallback,
+ base::Unretained(this)));
+
+ RunUntilResultReceived();
+
+ spell_check_host_->RequestTextCheck(
+ base::UTF8ToUTF16("zz."), 123,
+ base::BindOnce(&SpellCheckHostChromeImplWinBrowserTest::LogResult,
+ base::Unretained(this)));
+ RunUntilResultReceived();
+
+ ASSERT_EQ(1U, result_.size());
+ EXPECT_EQ(result_[0].location, 0);
+ EXPECT_EQ(result_[0].length, 2);
+ EXPECT_EQ(result_[0].decoration, SpellCheckResult::SPELLING);
+}
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc b/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc
index 5f9e87ac386..31619d7e7ae 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc
@@ -226,8 +226,7 @@ SpellcheckCustomDictionary::SpellcheckCustomDictionary(
base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})),
custom_dictionary_path_(
dictionary_directory_name.Append(chrome::kCustomDictionaryFileName)),
- is_loaded_(false),
- weak_ptr_factory_(this) {}
+ is_loaded_(false) {}
SpellcheckCustomDictionary::~SpellcheckCustomDictionary() {
}
@@ -262,7 +261,7 @@ bool SpellcheckCustomDictionary::RemoveWord(const std::string& word) {
}
bool SpellcheckCustomDictionary::HasWord(const std::string& word) const {
- return base::ContainsKey(words_, word);
+ return base::Contains(words_, word);
}
void SpellcheckCustomDictionary::AddObserver(Observer* observer) {
@@ -453,9 +452,9 @@ void SpellcheckCustomDictionary::OnLoaded(
fix_invalid_file_.Reset(
base::BindOnce(&SpellcheckCustomDictionary::FixInvalidFile,
weak_ptr_factory_.GetWeakPtr(), std::move(result)));
- BrowserThread::PostAfterStartupTask(
+ base::PostTaskWithTraits(
FROM_HERE,
- base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}),
+ {content::BrowserThread::UI, base::TaskPriority::BEST_EFFORT},
fix_invalid_file_.callback());
}
}
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.h b/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.h
index e3ba992c9f1..7ea9991617c 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.h
+++ b/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.h
@@ -226,7 +226,7 @@ class SpellcheckCustomDictionary : public SpellcheckDictionary,
base::CancelableOnceClosure fix_invalid_file_;
// Used to create weak pointers for an instance of this class.
- base::WeakPtrFactory<SpellcheckCustomDictionary> weak_ptr_factory_;
+ base::WeakPtrFactory<SpellcheckCustomDictionary> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SpellcheckCustomDictionary);
};
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
index 5c22d2cf923..d4ac62ef820 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
@@ -24,6 +24,7 @@
#include "chrome/common/chrome_paths.h"
#include "components/spellcheck/browser/spellcheck_platform.h"
#include "components/spellcheck/common/spellcheck_common.h"
+#include "components/spellcheck/common/spellcheck_features.h"
#include "components/spellcheck/spellcheck_buildflags.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
@@ -117,8 +118,7 @@ SpellcheckHunspellDictionary::SpellcheckHunspellDictionary(
#if !defined(OS_ANDROID)
spellcheck_service_(spellcheck_service),
#endif
- download_status_(DOWNLOAD_NONE),
- weak_ptr_factory_(this) {
+ download_status_(DOWNLOAD_NONE) {
}
SpellcheckHunspellDictionary::~SpellcheckHunspellDictionary() {
@@ -127,27 +127,31 @@ SpellcheckHunspellDictionary::~SpellcheckHunspellDictionary() {
FROM_HERE,
base::BindOnce(&CloseDictionary, std::move(dictionary_file_.file)));
}
+
+#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+ // Disable the language from platform spellchecker.
+ if (spellcheck::UseBrowserSpellChecker())
+ spellcheck_platform::DisableLanguage(language_);
+#endif
}
void SpellcheckHunspellDictionary::Load() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
- if (spellcheck_platform::SpellCheckerAvailable() &&
- spellcheck_platform::PlatformSupportsLanguage(language_)) {
- use_browser_spellchecker_ = true;
- spellcheck_platform::SetLanguage(language_);
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE,
- base::BindOnce(
- &SpellcheckHunspellDictionary::InformListenersOfInitialization,
- weak_ptr_factory_.GetWeakPtr()));
+ if (spellcheck::UseBrowserSpellChecker()) {
+ if (spellcheck_platform::SpellCheckerAvailable() &&
+ spellcheck_platform::PlatformSupportsLanguage(language_)) {
+ spellcheck_platform::SetLanguage(
+ language_, base::BindOnce(&SpellcheckHunspellDictionary::
+ SpellCheckPlatformSetLanguageCompleted,
+ base::Unretained(this)));
+ }
return;
}
#endif // USE_BROWSER_SPELLCHECKER
-// Mac falls back on hunspell if its platform spellchecker isn't available.
-// However, Android does not support hunspell.
+// Android does not support hunspell.
#if !defined(OS_ANDROID)
base::PostTaskAndReplyWithResult(
task_runner_.get(), FROM_HERE,
@@ -441,3 +445,20 @@ void SpellcheckHunspellDictionary::InformListenersOfDownloadFailure() {
for (Observer& observer : observers_)
observer.OnHunspellDictionaryDownloadFailure(language_);
}
+
+#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+void SpellcheckHunspellDictionary::SpellCheckPlatformSetLanguageCompleted(
+ bool result) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ if (!result)
+ return;
+
+ use_browser_spellchecker_ = true;
+ base::ThreadTaskRunnerHandle::Get()->PostTask(
+ FROM_HERE,
+ base::BindOnce(
+ &SpellcheckHunspellDictionary::InformListenersOfInitialization,
+ weak_ptr_factory_.GetWeakPtr()));
+}
+#endif
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h
index 715378b8763..9181170f6a8 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h
+++ b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h
@@ -17,6 +17,7 @@
#include "base/sequenced_task_runner.h"
#include "build/build_config.h"
#include "components/spellcheck/browser/spellcheck_dictionary.h"
+#include "components/spellcheck/spellcheck_buildflags.h"
#include "services/network/public/cpp/simple_url_loader.h"
class GURL;
@@ -134,6 +135,10 @@ class SpellcheckHunspellDictionary
void InitializeDictionaryLocationComplete(DictionaryFile file);
#endif
+#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+ void SpellCheckPlatformSetLanguageCompleted(bool result);
+#endif
+
// The reply point for PostTaskAndReplyWithResult, called after the dictionary
// file has been saved.
void SaveDictionaryDataComplete(bool dictionary_saved);
@@ -173,7 +178,7 @@ class SpellcheckHunspellDictionary
// Dictionary file path and descriptor.
DictionaryFile dictionary_file_;
- base::WeakPtrFactory<SpellcheckHunspellDictionary> weak_ptr_factory_;
+ base::WeakPtrFactory<SpellcheckHunspellDictionary> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SpellcheckHunspellDictionary);
};
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_service.cc b/chromium/chrome/browser/spellchecker/spellcheck_service.cc
index 0e200c58a16..c408235b3c4 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_service.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_service.cc
@@ -30,6 +30,7 @@
#include "components/spellcheck/browser/spelling_service_client.h"
#include "components/spellcheck/common/spellcheck.mojom.h"
#include "components/spellcheck/common/spellcheck_common.h"
+#include "components/spellcheck/common/spellcheck_features.h"
#include "components/spellcheck/spellcheck_buildflags.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/browser_context.h"
@@ -51,8 +52,7 @@ SpellcheckService::EventType g_status_type =
SpellcheckService::BDICT_NOTINITIALIZED;
SpellcheckService::SpellcheckService(content::BrowserContext* context)
- : context_(context),
- weak_ptr_factory_(this) {
+ : context_(context) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
PrefService* prefs = user_prefs::UserPrefs::Get(context);
pref_change_registrar_.Init(prefs);
@@ -60,12 +60,11 @@ SpellcheckService::SpellcheckService(content::BrowserContext* context)
dictionaries_pref.Init(spellcheck::prefs::kSpellCheckDictionaries, prefs);
std::string first_of_dictionaries;
-#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
- // Ensure that the renderer always knows the platform spellchecking language.
- // This language is used for initialization of the text iterator. If the
- // iterator is not initialized, then the context menu does not show spellcheck
- // suggestions.
- //
+#if defined(OS_MACOSX) || defined(OS_ANDROID)
+ // Ensure that the renderer always knows the platform spellchecking
+ // language. This language is used for initialization of the text iterator.
+ // If the iterator is not initialized, then the context menu does not show
+ // spellcheck suggestions.
// No migration is necessary, because the spellcheck language preference is
// not user visible or modifiable in Chrome on Mac.
dictionaries_pref.SetValue(std::vector<std::string>(
@@ -87,7 +86,7 @@ SpellcheckService::SpellcheckService(content::BrowserContext* context)
}
single_dictionary_pref.SetValue("");
-#endif // BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+#endif // defined(OS_MACOSX) || defined(OS_ANDROID)
pref_change_registrar_.Add(
spellcheck::prefs::kSpellCheckDictionaries,
@@ -181,6 +180,11 @@ void SpellcheckService::StartRecordingMetrics(bool spellcheck_enabled) {
metrics_ = std::make_unique<SpellCheckHostMetrics>();
metrics_->RecordEnabledStats(spellcheck_enabled);
OnUseSpellingServiceChanged();
+
+#if defined(OS_WIN)
+ RecordMissingLanguagePacksCount();
+ RecordHunspellUnsupportedLanguageCount(GetNormalizedAcceptLanguages());
+#endif // defined(OS_WIN)
}
void SpellcheckService::InitForRenderer(
@@ -265,6 +269,10 @@ void SpellcheckService::LoadHunspellDictionaries() {
hunspell_dictionaries_.back()->AddObserver(this);
hunspell_dictionaries_.back()->Load();
}
+
+#if defined(OS_WIN)
+ RecordMissingLanguagePacksCount();
+#endif // defined(OS_WIN)
}
const std::vector<std::unique_ptr<SpellcheckHunspellDictionary>>&
@@ -384,24 +392,61 @@ void SpellcheckService::OnUseSpellingServiceChanged() {
}
void SpellcheckService::OnAcceptLanguagesChanged() {
- PrefService* prefs = user_prefs::UserPrefs::Get(context_);
- std::vector<std::string> accept_languages =
- base::SplitString(prefs->GetString(language::prefs::kAcceptLanguages),
- ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
- std::transform(accept_languages.begin(), accept_languages.end(),
- accept_languages.begin(),
- &spellcheck::GetCorrespondingSpellCheckLanguage);
+ std::vector<std::string> accept_languages = GetNormalizedAcceptLanguages();
StringListPrefMember dictionaries_pref;
- dictionaries_pref.Init(spellcheck::prefs::kSpellCheckDictionaries, prefs);
+ dictionaries_pref.Init(spellcheck::prefs::kSpellCheckDictionaries,
+ user_prefs::UserPrefs::Get(context_));
std::vector<std::string> dictionaries = dictionaries_pref.GetValue();
std::vector<std::string> filtered_dictionaries;
for (const auto& dictionary : dictionaries) {
- if (base::ContainsValue(accept_languages, dictionary)) {
+ if (base::Contains(accept_languages, dictionary)) {
filtered_dictionaries.push_back(dictionary);
}
}
dictionaries_pref.SetValue(filtered_dictionaries);
+
+#if defined(OS_WIN)
+ RecordHunspellUnsupportedLanguageCount(accept_languages);
+#endif // defined(OS_WIN)
+}
+
+std::vector<std::string> SpellcheckService::GetNormalizedAcceptLanguages()
+ const {
+ PrefService* prefs = user_prefs::UserPrefs::Get(context_);
+ std::vector<std::string> accept_languages =
+ base::SplitString(prefs->GetString(language::prefs::kAcceptLanguages),
+ ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
+ std::transform(accept_languages.begin(), accept_languages.end(),
+ accept_languages.begin(),
+ &spellcheck::GetCorrespondingSpellCheckLanguage);
+ return accept_languages;
+}
+
+#if defined(OS_WIN)
+void SpellcheckService::RecordMissingLanguagePacksCount() {
+ if (spellcheck::WindowsVersionSupportsSpellchecker() && metrics_ &&
+ !hunspell_dictionaries_.empty()) {
+ std::vector<std::string> hunspell_locales;
+ for (auto& dict : hunspell_dictionaries_) {
+ hunspell_locales.push_back(dict->GetLanguage());
+ }
+ spellcheck_platform::RecordMissingLanguagePacksCount(
+ std::move(hunspell_locales), metrics_.get());
+ }
+}
+
+void SpellcheckService::RecordHunspellUnsupportedLanguageCount(
+ const std::vector<std::string>& accept_languages) {
+ if (spellcheck::WindowsVersionSupportsSpellchecker() && metrics_ &&
+ !accept_languages.empty()) {
+ metrics_->RecordHunspellUnsupportedLanguageCount(std::count_if(
+ accept_languages.begin(), accept_languages.end(),
+ [](const std::string& s) {
+ return spellcheck::GetCorrespondingSpellCheckLanguage(s).empty();
+ }));
+ }
}
+#endif // defined(OS_WIN)
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_service.h b/chromium/chrome/browser/spellchecker/spellcheck_service.h
index 60d5a74b2d4..39a29325264 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_service.h
+++ b/chromium/chrome/browser/spellchecker/spellcheck_service.h
@@ -167,6 +167,19 @@ class SpellcheckService : public KeyedService,
// prefs::kAcceptLanguages.
void OnAcceptLanguagesChanged();
+ // Gets the user languages from the accept_languages pref and normalizes them
+ // to official language codes.
+ std::vector<std::string> GetNormalizedAcceptLanguages() const;
+
+ // Records how many user languages are not supported by Hunspell, and how many
+ // user spellcheck languages are currently not supported by the Windows OS
+ // spellchecker (due to missing language packs).
+#if defined(OS_WIN)
+ void RecordMissingLanguagePacksCount();
+ void RecordHunspellUnsupportedLanguageCount(
+ const std::vector<std::string>& accept_languages);
+#endif // defined(OS_WIN)
+
PrefChangeRegistrar pref_change_registrar_;
content::NotificationRegistrar registrar_;
@@ -180,7 +193,7 @@ class SpellcheckService : public KeyedService,
std::vector<std::unique_ptr<SpellcheckHunspellDictionary>>
hunspell_dictionaries_;
- base::WeakPtrFactory<SpellcheckService> weak_ptr_factory_;
+ base::WeakPtrFactory<SpellcheckService> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SpellcheckService);
};
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc b/chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc
index c73a908ea81..38b52079c0f 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc
@@ -27,6 +27,7 @@
#include "chrome/common/chrome_paths.h"
#include "chrome/common/constants.mojom.h"
#include "chrome/test/base/in_process_browser_test.h"
+#include "components/browser_sync/browser_sync_switches.h"
#include "components/language/core/browser/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/spellcheck/browser/pref_names.h"
@@ -54,6 +55,16 @@ class SpellcheckServiceBrowserTest : public InProcessBrowserTest,
prefs_ = user_prefs::UserPrefs::Get(GetContext());
}
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ // Sync causes the SpellcheckService to be instantiated (and initialized)
+ // during startup. However, several tests rely on control over when exactly
+ // the SpellcheckService gets created (e.g. by calling
+ // GetEnableSpellcheckState() after InitSpellcheck(), which will wait
+ // forever if the service already existed). So disable sync of the custom
+ // dictionary for these tests.
+ command_line->AppendSwitchASCII(switches::kDisableSyncTypes, "Dictionary");
+ }
+
void TearDownOnMainThread() override {
binding_.Close();
prefs_ = nullptr;
@@ -432,13 +443,13 @@ IN_PROC_BROWSER_TEST_F(SpellcheckServiceHostBrowserTest, NotifyChecked) {
tester.ExpectTotalCount(kMisspellRatio, 1);
}
-#if !BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+#if BUILDFLAG(USE_RENDERER_SPELLCHECKER)
// When the renderer requests the spelling service for correcting text, the
// render process host should call the remote spelling service.
IN_PROC_BROWSER_TEST_F(SpellcheckServiceHostBrowserTest, CallSpellingService) {
CallSpellingService();
}
-#endif // !BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+#endif // BUILDFLAG(USE_RENDERER_SPELLCHECKER)
// Tests that we can delete a corrupted BDICT file used by hunspell. We do not
// run this test on Mac because Mac does not use hunspell by default.
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc b/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc
index 2e7e09038d6..c2cab605889 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc
@@ -45,7 +45,7 @@ struct TestCase {
for (const auto& language : languages) {
dictionary.language = language;
dictionary.used_for_spellcheck =
- base::ContainsValue(used_for_spellcheck, language);
+ base::Contains(used_for_spellcheck, language);
expected_dictionaries.push_back(dictionary);
}
}
diff --git a/chromium/chrome/browser/spellchecker/spelling_request.cc b/chromium/chrome/browser/spellchecker/spelling_request.cc
new file mode 100644
index 00000000000..7453651013c
--- /dev/null
+++ b/chromium/chrome/browser/spellchecker/spelling_request.cc
@@ -0,0 +1,144 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/spellchecker/spelling_request.h"
+
+#include "base/barrier_closure.h"
+#include "base/bind.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/task/post_task.h"
+#include "chrome/browser/spellchecker/spellcheck_custom_dictionary.h"
+#include "chrome/browser/spellchecker/spellcheck_factory.h"
+#include "components/spellcheck/browser/spellcheck_platform.h"
+#include "components/spellcheck/common/spellcheck_result.h"
+#include "content/public/browser/browser_context.h"
+#include "content/public/browser/browser_task_traits.h"
+#include "content/public/browser/browser_thread.h"
+#include "mojo/public/cpp/bindings/strong_binding.h"
+
+namespace {
+
+bool CompareLocation(const SpellCheckResult& r1, const SpellCheckResult& r2) {
+ return r1.location < r2.location;
+}
+
+} // namespace
+
+SpellingRequest::SpellingRequest(
+ SpellingServiceClient* client,
+ const base::string16& text,
+ const service_manager::Identity& renderer_identity,
+ int document_tag,
+ RequestTextCheckCallback callback,
+ DestructionCallback destruction_callback)
+ : remote_success_(false),
+ text_(text),
+ callback_(std::move(callback)),
+ destruction_callback_(std::move(destruction_callback)),
+ weak_factory_(this) {
+ DCHECK(!text_.empty());
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+
+ completion_barrier_ =
+ BarrierClosure(2, base::BindOnce(&SpellingRequest::OnCheckCompleted,
+ weak_factory_.GetWeakPtr()));
+ RequestRemoteCheck(client, renderer_identity);
+ RequestLocalCheck(document_tag);
+}
+
+SpellingRequest::~SpellingRequest() = default;
+
+// static
+void SpellingRequest::CombineResults(
+ std::vector<SpellCheckResult>* remote_results,
+ const std::vector<SpellCheckResult>& local_results) {
+ std::vector<SpellCheckResult>::const_iterator local_iter(
+ local_results.begin());
+ std::vector<SpellCheckResult>::iterator remote_iter;
+
+ for (remote_iter = remote_results->begin();
+ remote_iter != remote_results->end(); ++remote_iter) {
+ // Discard all local results occurring before remote result.
+ while (local_iter != local_results.end() &&
+ local_iter->location < remote_iter->location) {
+ local_iter++;
+ }
+
+ // Unless local and remote result coincide, result is GRAMMAR.
+ remote_iter->decoration = SpellCheckResult::GRAMMAR;
+ if (local_iter != local_results.end() &&
+ local_iter->location == remote_iter->location &&
+ local_iter->length == remote_iter->length) {
+ remote_iter->decoration = SpellCheckResult::SPELLING;
+ }
+ }
+}
+
+void SpellingRequest::RequestRemoteCheck(
+ SpellingServiceClient* client,
+ const service_manager::Identity& renderer_identity) {
+ content::BrowserContext* context =
+ content::BrowserContext::GetBrowserContextForServiceInstanceGroup(
+ renderer_identity.instance_group());
+
+ // |this| may be gone at callback invocation if the owner has been removed.
+ client->RequestTextCheck(
+ context, SpellingServiceClient::SPELLCHECK, text_,
+ base::BindOnce(&SpellingRequest::OnRemoteCheckCompleted,
+ weak_factory_.GetWeakPtr()));
+}
+
+void SpellingRequest::RequestLocalCheck(int document_tag) {
+ // |this| may be gone at callback invocation if the owner has been removed.
+ spellcheck_platform::RequestTextCheck(
+ document_tag, text_,
+ base::BindOnce(&SpellingRequest::OnLocalCheckCompletedOnAnyThread,
+ weak_factory_.GetWeakPtr()));
+}
+
+void SpellingRequest::OnCheckCompleted() {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+
+ std::vector<SpellCheckResult>* check_results = &local_results_;
+ if (remote_success_) {
+ std::sort(remote_results_.begin(), remote_results_.end(), CompareLocation);
+ std::sort(local_results_.begin(), local_results_.end(), CompareLocation);
+ CombineResults(&remote_results_, local_results_);
+ check_results = &remote_results_;
+ }
+
+ std::move(callback_).Run(*check_results);
+
+ std::move(destruction_callback_).Run(this);
+
+ // |destruction_callback_| removes |this|. No more operations allowed.
+}
+
+void SpellingRequest::OnRemoteCheckCompleted(
+ bool success,
+ const base::string16& text,
+ const std::vector<SpellCheckResult>& results) {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ remote_success_ = success;
+ remote_results_ = results;
+ completion_barrier_.Run();
+}
+
+// static
+void SpellingRequest::OnLocalCheckCompletedOnAnyThread(
+ base::WeakPtr<SpellingRequest> request,
+ const std::vector<SpellCheckResult>& results) {
+ // Local checking can happen on any thread - don't DCHECK thread.
+ base::PostTaskWithTraits(
+ FROM_HERE, {content::BrowserThread::UI},
+ base::BindOnce(&SpellingRequest::OnLocalCheckCompleted, request,
+ results));
+}
+
+void SpellingRequest::OnLocalCheckCompleted(
+ const std::vector<SpellCheckResult>& results) {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ local_results_ = results;
+ completion_barrier_.Run();
+}
diff --git a/chromium/chrome/browser/spellchecker/spelling_request.h b/chromium/chrome/browser/spellchecker/spelling_request.h
new file mode 100644
index 00000000000..7877e93591b
--- /dev/null
+++ b/chromium/chrome/browser/spellchecker/spelling_request.h
@@ -0,0 +1,83 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_SPELLCHECKER_SPELLING_REQUEST_H_
+#define CHROME_BROWSER_SPELLCHECKER_SPELLING_REQUEST_H_
+
+#include "base/containers/unique_ptr_adapters.h"
+#include "components/spellcheck/browser/spell_check_host_impl.h"
+#include "components/spellcheck/browser/spelling_service_client.h"
+#include "services/service_manager/public/cpp/bind_source_info.h"
+
+class SpellingRequest;
+
+struct SpellCheckResult;
+
+// SpellingRequest is owned by SpellCheckHostChromeImpl.
+class SpellingRequest {
+ public:
+ using RequestTextCheckCallback =
+ spellcheck::mojom::SpellCheckHost::RequestTextCheckCallback;
+ using DestructionCallback = base::OnceCallback<void(SpellingRequest*)>;
+
+ SpellingRequest(SpellingServiceClient* client,
+ const base::string16& text,
+ const service_manager::Identity& renderer_identity,
+ int document_tag,
+ RequestTextCheckCallback callback,
+ DestructionCallback destruction_callback);
+
+ ~SpellingRequest();
+
+ // Exposed to tests only.
+ static void CombineResults(
+ std::vector<SpellCheckResult>* remote_results,
+ const std::vector<SpellCheckResult>& local_results);
+
+ private:
+ // Request server-side checking for |text_|.
+ void RequestRemoteCheck(SpellingServiceClient* client,
+ const service_manager::Identity& renderer_identity);
+
+ // Request a check for |text_| from local spell checker.
+ void RequestLocalCheck(int document_tag);
+
+ // Check if all pending requests are done, send reply to render process if so.
+ void OnCheckCompleted();
+
+ // Called when server-side checking is complete. Must be called on UI thread.
+ void OnRemoteCheckCompleted(bool success,
+ const base::string16& text,
+ const std::vector<SpellCheckResult>& results);
+
+ // Called when local checking is complete. Must be called on UI thread.
+ void OnLocalCheckCompleted(const std::vector<SpellCheckResult>& results);
+
+ // Forwards the results back to UI thread when local checking completes.
+ static void OnLocalCheckCompletedOnAnyThread(
+ base::WeakPtr<SpellingRequest> request,
+ const std::vector<SpellCheckResult>& results);
+
+ std::vector<SpellCheckResult> local_results_;
+ std::vector<SpellCheckResult> remote_results_;
+
+ // Barrier closure for completion of both remote and local check.
+ base::RepeatingClosure completion_barrier_;
+ bool remote_success_;
+
+ // The string to be spell-checked.
+ base::string16 text_;
+
+ // Callback to send the results to renderer.
+ RequestTextCheckCallback callback_;
+
+ // Callback to delete |this|. Called on |this| after everything is done.
+ DestructionCallback destruction_callback_;
+
+ base::WeakPtrFactory<SpellingRequest> weak_factory_;
+
+ DISALLOW_COPY_AND_ASSIGN(SpellingRequest);
+};
+
+#endif // CHROME_BROWSER_SPELLCHECKER_SPELLING_REQUEST_H_
diff --git a/chromium/chrome/browser/supervised_user/kids_chrome_management/BUILD.gn b/chromium/chrome/browser/supervised_user/kids_chrome_management/BUILD.gn
new file mode 100644
index 00000000000..6bdd7ebb960
--- /dev/null
+++ b/chromium/chrome/browser/supervised_user/kids_chrome_management/BUILD.gn
@@ -0,0 +1,12 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/protobuf/proto_library.gni")
+
+proto_library("proto") {
+ sources = [
+ "families_common.proto",
+ "kidschromemanagement_messages.proto",
+ ]
+}
diff --git a/chromium/chrome/browser/ui/BUILD.gn b/chromium/chrome/browser/ui/BUILD.gn
index ff5b402eb7a..3ec0ed426c7 100644
--- a/chromium/chrome/browser/ui/BUILD.gn
+++ b/chromium/chrome/browser/ui/BUILD.gn
@@ -112,10 +112,10 @@ jumbo_split_static_library("ui") {
"find_bar/find_bar_state_factory.cc",
"find_bar/find_bar_state_factory.h",
"find_bar/find_notification_details.h",
+ "find_bar/find_result_observer.h",
"find_bar/find_tab_helper.cc",
"find_bar/find_tab_helper.h",
- "infobars/tab_sharing_infobar_delegate.cc",
- "infobars/tab_sharing_infobar_delegate.h",
+ "find_bar/find_types.h",
"interventions/framebust_block_message_delegate.cc",
"interventions/framebust_block_message_delegate.h",
"interventions/intervention_delegate.h",
@@ -129,6 +129,8 @@ jumbo_split_static_library("ui") {
"login/login_handler.h",
"login/login_interstitial_delegate.cc",
"login/login_interstitial_delegate.h",
+ "login/login_tab_helper.cc",
+ "login/login_tab_helper.h",
"navigation_correction_tab_observer.cc",
"navigation_correction_tab_observer.h",
"page_info/page_info.cc",
@@ -235,12 +237,12 @@ jumbo_split_static_library("ui") {
"webui/download_internals/download_internals_ui_message_handler.h",
"webui/engagement/site_engagement_ui.cc",
"webui/engagement/site_engagement_ui.h",
- "webui/favicon_source.cc",
- "webui/favicon_source.h",
"webui/fileicon_source.cc",
"webui/fileicon_source.h",
"webui/flags_ui.cc",
"webui/flags_ui.h",
+ "webui/flags_ui_handler.cc",
+ "webui/flags_ui_handler.h",
"webui/gcm_internals_ui.cc",
"webui/gcm_internals_ui.h",
"webui/interstitials/interstitial_ui.cc",
@@ -271,6 +273,10 @@ jumbo_split_static_library("ui") {
"webui/net_export_ui.h",
"webui/net_internals/net_internals_ui.cc",
"webui/net_internals/net_internals_ui.h",
+ "webui/notifications_internals/notifications_internals_ui.cc",
+ "webui/notifications_internals/notifications_internals_ui.h",
+ "webui/notifications_internals/notifications_internals_ui_message_handler.cc",
+ "webui/notifications_internals/notifications_internals_ui_message_handler.h",
"webui/ntp_tiles_internals_ui.cc",
"webui/ntp_tiles_internals_ui.h",
"webui/omnibox/omnibox_page_handler.cc",
@@ -299,10 +305,6 @@ jumbo_split_static_library("ui") {
"webui/quota_internals/quota_internals_ui.h",
"webui/signin_internals_ui.cc",
"webui/signin_internals_ui.h",
- "webui/supervised_user_internals_message_handler.cc",
- "webui/supervised_user_internals_message_handler.h",
- "webui/supervised_user_internals_ui.cc",
- "webui/supervised_user_internals_ui.h",
"webui/sync_internals_message_handler.cc",
"webui/sync_internals_message_handler.h",
"webui/sync_internals_ui.cc",
@@ -327,10 +329,19 @@ jumbo_split_static_library("ui") {
"webui/version_handler.h",
"webui/version_ui.cc",
"webui/version_ui.h",
+ "webui/webui_load_timer.cc",
+ "webui/webui_load_timer.h",
"webui/webui_util.cc",
"webui/webui_util.h",
]
+ if (is_win || is_mac) {
+ sources += [
+ "webui/settings/captions_handler.cc",
+ "webui/settings/captions_handler.h",
+ ]
+ }
+
if (enable_vr) {
if (is_win) {
sources += [
@@ -387,6 +398,7 @@ jumbo_split_static_library("ui") {
"//chrome/browser/devtools",
"//chrome/browser/engagement:mojo_bindings",
"//chrome/browser/media:mojo_bindings",
+ "//chrome/browser/notifications/scheduler/public",
"//chrome/browser/profiling_host",
"//chrome/browser/safe_browsing",
"//chrome/browser/ssl:proto",
@@ -453,8 +465,10 @@ jumbo_split_static_library("ui") {
"//components/onc",
"//components/password_manager/content/browser",
"//components/password_manager/core/browser",
+ "//components/password_manager/core/browser:affiliation",
"//components/payments/content:utils",
"//components/payments/content/icon",
+ "//components/payments/core:error_strings",
"//components/pdf/browser",
"//components/policy/core/browser",
"//components/pref_registry",
@@ -471,6 +485,8 @@ jumbo_split_static_library("ui") {
"//components/safe_browsing/db:database_manager",
"//components/safe_browsing/db:util",
"//components/safe_browsing/password_protection",
+ "//components/safe_browsing/triggers:ad_popup_trigger",
+ "//components/safe_browsing/triggers:ad_redirect_trigger",
"//components/safe_browsing/web_ui",
"//components/search",
"//components/search_engines",
@@ -481,7 +497,8 @@ jumbo_split_static_library("ui") {
"//components/send_tab_to_self",
"//components/sessions",
"//components/signin/core/browser",
- "//components/signin/core/browser:signin_buildflags",
+ "//components/signin/public/base:signin_buildflags",
+ "//components/signin/public/identity_manager",
"//components/spellcheck/browser",
"//components/ssl_errors",
"//components/startup_metric_utils/browser:lib",
@@ -524,7 +541,6 @@ jumbo_split_static_library("ui") {
"//printing/buildflags",
"//rlz/buildflags",
"//services/device/public/cpp:device_features",
- "//services/identity/public/cpp",
"//services/metrics/public/cpp:ukm_builders",
"//services/network/public/mojom",
"//skia",
@@ -619,8 +635,6 @@ jumbo_split_static_library("ui") {
"android/autofill/card_unmask_prompt_view_android.h",
"android/autofill/credit_card_scanner_view_android.cc",
"android/autofill/credit_card_scanner_view_android.h",
- "android/bluetooth_chooser_android.cc",
- "android/bluetooth_chooser_android.h",
"android/chrome_http_auth_handler.cc",
"android/chrome_http_auth_handler.h",
"android/color_chooser_dialog_android.cc",
@@ -630,6 +644,12 @@ jumbo_split_static_library("ui") {
"android/content_settings/popup_blocked_infobar_delegate.h",
"android/context_menu_helper.cc",
"android/context_menu_helper.h",
+ "android/device_dialog/bluetooth_chooser_android.cc",
+ "android/device_dialog/bluetooth_chooser_android.h",
+ "android/device_dialog/bluetooth_scanning_prompt_android.cc",
+ "android/device_dialog/bluetooth_scanning_prompt_android.h",
+ "android/device_dialog/usb_chooser_dialog_android.cc",
+ "android/device_dialog/usb_chooser_dialog_android.h",
"android/external_protocol_dialog_android.cc",
"android/infobars/ads_blocked_infobar.cc",
"android/infobars/ads_blocked_infobar.h",
@@ -690,6 +710,7 @@ jumbo_split_static_library("ui") {
"android/omnibox/omnibox_view_util.cc",
"android/omnibox/omnibox_view_util.h",
"android/overlay/overlay_window_android.cc",
+ "android/overlay/overlay_window_android.h",
"android/page_info/certificate_chain_helper.cc",
"android/page_info/certificate_viewer_android.cc",
"android/page_info/connection_info_popup_android.cc",
@@ -703,6 +724,8 @@ jumbo_split_static_library("ui") {
"android/passwords/password_generation_editing_popup_view_android.cc",
"android/passwords/password_generation_editing_popup_view_android.h",
"android/simple_message_box_android.cc",
+ "android/sms_dialog_android.cc",
+ "android/sms_dialog_android.h",
"android/snackbars/auto_signin_prompt_controller.cc",
"android/snackbars/auto_signin_prompt_controller.h",
"android/ssl_client_certificate_request.cc",
@@ -725,8 +748,6 @@ jumbo_split_static_library("ui") {
"android/tab_model/tab_model_observer_jni_bridge.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",
"android/view_android_helper.h",
"browser_otr_state_android.cc",
@@ -870,7 +891,6 @@ jumbo_split_static_library("ui") {
"exclusive_access/exclusive_access_bubble_hide_callback.h",
"exclusive_access/exclusive_access_bubble_type.cc",
"exclusive_access/exclusive_access_bubble_type.h",
- "exclusive_access/exclusive_access_context.cc",
"exclusive_access/exclusive_access_context.h",
"exclusive_access/exclusive_access_controller_base.cc",
"exclusive_access/exclusive_access_controller_base.h",
@@ -878,6 +898,7 @@ jumbo_split_static_library("ui") {
"exclusive_access/exclusive_access_manager.h",
"exclusive_access/fullscreen_controller.cc",
"exclusive_access/fullscreen_controller.h",
+ "exclusive_access/fullscreen_observer.h",
"exclusive_access/fullscreen_within_tab_helper.cc",
"exclusive_access/fullscreen_within_tab_helper.h",
"exclusive_access/keyboard_lock_controller.cc",
@@ -892,10 +913,19 @@ jumbo_split_static_library("ui") {
"global_error/global_error.cc",
"global_error/global_error.h",
"global_error/global_error_bubble_view_base.h",
+ "global_error/global_error_observer.h",
"global_error/global_error_service.cc",
"global_error/global_error_service.h",
"global_error/global_error_service_factory.cc",
"global_error/global_error_service_factory.h",
+ "global_media_controls/media_dialog_controller.cc",
+ "global_media_controls/media_dialog_controller.h",
+ "global_media_controls/media_dialog_controller_delegate.cc",
+ "global_media_controls/media_dialog_controller_delegate.h",
+ "global_media_controls/media_toolbar_button_controller.cc",
+ "global_media_controls/media_toolbar_button_controller.h",
+ "global_media_controls/media_toolbar_button_controller_delegate.cc",
+ "global_media_controls/media_toolbar_button_controller_delegate.h",
"hats/hats_helper.cc",
"hats/hats_helper.h",
"hats/hats_service.cc",
@@ -904,8 +934,19 @@ jumbo_split_static_library("ui") {
"hats/hats_service_factory.h",
"hid/hid_chooser.cc",
"hid/hid_chooser.h",
+ "hid/hid_chooser_controller.cc",
+ "hid/hid_chooser_controller.h",
"hung_renderer/hung_renderer_core.cc",
"hung_renderer/hung_renderer_core.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",
"intent_picker_tab_helper.cc",
"intent_picker_tab_helper.h",
"javascript_dialogs/javascript_dialog_views.cc",
@@ -924,12 +965,8 @@ jumbo_split_static_library("ui") {
"media_router/cloud_services_dialog.h",
"media_router/media_cast_mode.cc",
"media_router/media_cast_mode.h",
- "media_router/media_router_dialog_controller_impl_base.cc",
- "media_router/media_router_dialog_controller_impl_base.h",
"media_router/media_router_file_dialog.cc",
"media_router/media_router_file_dialog.h",
- "media_router/media_router_ui_base.cc",
- "media_router/media_router_ui_base.h",
"media_router/media_router_ui_helper.cc",
"media_router/media_router_ui_helper.h",
"media_router/media_router_ui_service.cc",
@@ -1045,6 +1082,9 @@ jumbo_split_static_library("ui") {
"tab_contents/tab_contents_iterator.h",
"tab_modal_confirm_dialog_delegate.cc",
"tab_modal_confirm_dialog_delegate.h",
+ "tab_sharing/tab_sharing_infobar_delegate.cc",
+ "tab_sharing/tab_sharing_infobar_delegate.h",
+ "tab_sharing/tab_sharing_ui.h",
"tabs/existing_tab_group_sub_menu_model.cc",
"tabs/existing_tab_group_sub_menu_model.h",
"tabs/hover_tab_selector.cc",
@@ -1108,6 +1148,7 @@ jumbo_split_static_library("ui") {
"toolbar/recent_tabs_sub_menu_model.cc",
"toolbar/recent_tabs_sub_menu_model.h",
"toolbar/toolbar_action_view_controller.h",
+ "toolbar/toolbar_action_view_delegate.cc",
"toolbar/toolbar_action_view_delegate.h",
"toolbar/toolbar_actions_bar.cc",
"toolbar/toolbar_actions_bar.h",
@@ -1142,8 +1183,6 @@ jumbo_split_static_library("ui") {
"webui/chrome_web_contents_handler.h",
"webui/constrained_web_dialog_delegate_base.cc",
"webui/constrained_web_dialog_delegate_base.h",
- "webui/dark_mode_handler.cc",
- "webui/dark_mode_handler.h",
"webui/devtools_ui.cc",
"webui/devtools_ui.h",
"webui/downloads/downloads_dom_handler.cc",
@@ -1156,12 +1195,10 @@ jumbo_split_static_library("ui") {
"webui/extensions/extensions_internals_source.h",
"webui/extensions/extensions_ui.cc",
"webui/extensions/extensions_ui.h",
+ "webui/favicon_source.cc",
+ "webui/favicon_source.h",
"webui/foreign_session_handler.cc",
"webui/foreign_session_handler.h",
- "webui/hats/hats_handler.cc",
- "webui/hats/hats_handler.h",
- "webui/hats/hats_ui.cc",
- "webui/hats/hats_ui.h",
"webui/help/version_updater.h",
"webui/history_login_handler.cc",
"webui/history_login_handler.h",
@@ -1177,20 +1214,10 @@ jumbo_split_static_library("ui") {
"webui/management_ui.h",
"webui/management_ui_handler.cc",
"webui/management_ui_handler.h",
- "webui/media_router/media_router_dialog_controller_webui_impl.cc",
- "webui/media_router/media_router_dialog_controller_webui_impl.h",
"webui/media_router/media_router_internals_ui.cc",
"webui/media_router/media_router_internals_ui.h",
"webui/media_router/media_router_internals_webui_message_handler.cc",
"webui/media_router/media_router_internals_webui_message_handler.h",
- "webui/media_router/media_router_localized_strings_provider.cc",
- "webui/media_router/media_router_localized_strings_provider.h",
- "webui/media_router/media_router_resources_provider.cc",
- "webui/media_router/media_router_resources_provider.h",
- "webui/media_router/media_router_ui.cc",
- "webui/media_router/media_router_ui.h",
- "webui/media_router/media_router_webui_message_handler.cc",
- "webui/media_router/media_router_webui_message_handler.h",
"webui/media_router/web_contents_display_observer.h",
"webui/ntp/app_icon_webui_handler.cc",
"webui/ntp/app_icon_webui_handler.h",
@@ -1304,6 +1331,8 @@ jumbo_split_static_library("ui") {
"zoom/chrome_zoom_level_prefs.h",
]
deps += [
+ "//base/util/values:values_util",
+ "//build:branding_buildflags",
"//chrome/app/vector_icons",
"//chrome/browser:theme_properties",
"//chrome/browser/media/router",
@@ -1314,12 +1343,12 @@ jumbo_split_static_library("ui") {
"//chrome/browser/ui/webui/app_management:mojo_bindings",
"//chrome/common:buildflags",
"//chrome/common:search_mojom",
- "//chrome/services/app_service/public/cpp:app_service_proxy",
"//chrome/services/app_service/public/cpp:app_update",
"//chrome/services/app_service/public/mojom",
"//components/feedback/proto",
"//components/keep_alive_registry",
"//components/network_session_configurator/common",
+ "//components/profile_metrics",
"//components/ui_metrics",
"//components/url_formatter",
"//components/vector_icons",
@@ -1328,7 +1357,6 @@ jumbo_split_static_library("ui") {
"//device/bluetooth",
"//device/fido",
"//services/device/public/mojom",
- "//services/identity/public/cpp",
"//services/metrics/public/cpp:metrics_cpp",
"//third_party/libaddressinput",
"//third_party/libaddressinput:strings",
@@ -1360,6 +1388,7 @@ jumbo_split_static_library("ui") {
}
}
+ # TODO(crbug.com/980869): Remove the section below.
if (enable_supervised_users && !is_android && !is_chromeos) {
sources += [
"startup/supervised_users_deprecated_infobar_delegate.cc",
@@ -1367,6 +1396,15 @@ jumbo_split_static_library("ui") {
]
}
+ if (enable_supervised_users) {
+ sources += [
+ "webui/supervised_user_internals_message_handler.cc",
+ "webui/supervised_user_internals_message_handler.h",
+ "webui/supervised_user_internals_ui.cc",
+ "webui/supervised_user_internals_ui.h",
+ ]
+ }
+
if (is_chromeos) {
assert(enable_extensions)
assert(toolkit_views)
@@ -1389,6 +1427,10 @@ jumbo_split_static_library("ui") {
"app_list/search/launcher_search/launcher_search_result.h",
"ash/accessibility/accessibility_controller_client.cc",
"ash/accessibility/accessibility_controller_client.h",
+ "ash/ambient/photo_controller_impl.cc",
+ "ash/ambient/photo_controller_impl.h",
+ "ash/arc_chrome_actions_client.cc",
+ "ash/arc_chrome_actions_client.h",
"ash/ash_shell_init.cc",
"ash/ash_shell_init.h",
"ash/ash_util.cc",
@@ -1420,8 +1462,6 @@ jumbo_split_static_library("ui") {
"ash/keyboard/chrome_keyboard_ui_factory.h",
"ash/keyboard/chrome_keyboard_web_contents.cc",
"ash/keyboard/chrome_keyboard_web_contents.h",
- "ash/kiosk_next_shell_client.cc",
- "ash/kiosk_next_shell_client.h",
"ash/launcher/app_shortcut_launcher_item_controller.cc",
"ash/launcher/app_shortcut_launcher_item_controller.h",
"ash/launcher/app_window_launcher_controller.cc",
@@ -1462,8 +1502,8 @@ jumbo_split_static_library("ui") {
"ash/launcher/settings_window_observer.h",
"ash/login_screen_client.cc",
"ash/login_screen_client.h",
- "ash/media_client.cc",
- "ash/media_client.h",
+ "ash/media_client_impl.cc",
+ "ash/media_client_impl.h",
"ash/multi_user/multi_profile_support.cc",
"ash/multi_user/multi_profile_support.h",
"ash/multi_user/multi_user_context_menu.h",
@@ -1561,6 +1601,8 @@ jumbo_split_static_library("ui") {
"webui/chromeos/add_supervision/add_supervision_handler_utils.h",
"webui/chromeos/add_supervision/add_supervision_ui.cc",
"webui/chromeos/add_supervision/add_supervision_ui.h",
+ "webui/chromeos/add_supervision/confirm_signout_dialog.cc",
+ "webui/chromeos/add_supervision/confirm_signout_dialog.h",
"webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc",
"webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.h",
"webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc",
@@ -1573,6 +1615,8 @@ jumbo_split_static_library("ui") {
"webui/chromeos/bluetooth_dialog_localized_strings_provider.h",
"webui/chromeos/bluetooth_pairing_dialog.cc",
"webui/chromeos/bluetooth_pairing_dialog.h",
+ "webui/chromeos/camera/camera_ui.cc",
+ "webui/chromeos/camera/camera_ui.h",
"webui/chromeos/cellular_setup/cellular_setup_dialog.cc",
"webui/chromeos/cellular_setup/cellular_setup_dialog.h",
"webui/chromeos/cellular_setup/cellular_setup_dialog_launcher.cc",
@@ -1599,10 +1643,14 @@ jumbo_split_static_library("ui") {
"webui/chromeos/first_run/first_run_ui.h",
"webui/chromeos/image_source.cc",
"webui/chromeos/image_source.h",
- "webui/chromeos/insession_password_change_handler_chromeos.cc",
- "webui/chromeos/insession_password_change_handler_chromeos.h",
- "webui/chromeos/insession_password_change_ui.cc",
- "webui/chromeos/insession_password_change_ui.h",
+ "webui/chromeos/in_session_password_change/confirm_password_change_handler.cc",
+ "webui/chromeos/in_session_password_change/confirm_password_change_handler.h",
+ "webui/chromeos/in_session_password_change/password_change_handler.cc",
+ "webui/chromeos/in_session_password_change/password_change_handler.h",
+ "webui/chromeos/in_session_password_change/password_change_ui.cc",
+ "webui/chromeos/in_session_password_change/password_change_ui.h",
+ "webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.cc",
+ "webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.h",
"webui/chromeos/internet_config_dialog.cc",
"webui/chromeos/internet_config_dialog.h",
"webui/chromeos/internet_detail_dialog.cc",
@@ -1701,8 +1749,6 @@ jumbo_split_static_library("ui") {
"webui/chromeos/login/reset_screen_handler.h",
"webui/chromeos/login/signin_screen_handler.cc",
"webui/chromeos/login/signin_screen_handler.h",
- "webui/chromeos/login/supervision_onboarding_screen_handler.cc",
- "webui/chromeos/login/supervision_onboarding_screen_handler.h",
"webui/chromeos/login/supervision_transition_screen_handler.cc",
"webui/chromeos/login/supervision_transition_screen_handler.h",
"webui/chromeos/login/sync_consent_screen_handler.cc",
@@ -1755,6 +1801,10 @@ jumbo_split_static_library("ui") {
"webui/chromeos/sys_internals/sys_internals_ui.h",
"webui/chromeos/system_web_dialog_delegate.cc",
"webui/chromeos/system_web_dialog_delegate.h",
+ "webui/chromeos/terminal/terminal_source.cc",
+ "webui/chromeos/terminal/terminal_source.h",
+ "webui/chromeos/terminal/terminal_ui.cc",
+ "webui/chromeos/terminal/terminal_ui.h",
"webui/chromeos/user_image_source.cc",
"webui/chromeos/user_image_source.h",
"webui/chromeos/video_source.cc",
@@ -1801,6 +1851,8 @@ jumbo_split_static_library("ui") {
"webui/settings/chromeos/multidevice_handler.h",
"webui/settings/chromeos/os_settings_ui.cc",
"webui/settings/chromeos/os_settings_ui.h",
+ "webui/settings/chromeos/parental_controls_handler.cc",
+ "webui/settings/chromeos/parental_controls_handler.h",
"webui/settings/chromeos/plugin_vm_handler.cc",
"webui/settings/chromeos/plugin_vm_handler.h",
"webui/settings/tts_handler.cc",
@@ -1823,9 +1875,10 @@ jumbo_split_static_library("ui") {
"//ash/public/cpp/resources:ash_public_unscaled_resources",
"//ash/public/cpp/vector_icons",
"//chrome/browser/chromeos",
- "//chrome/browser/chromeos/supervision/mojom",
+ "//chrome/browser/resources/chromeos:camera_resources",
"//chrome/browser/ui/webui/chromeos/add_supervision:mojo_bindings",
"//chrome/browser/ui/webui/chromeos/machine_learning:mojo_bindings",
+ "//chrome/services/file_util/public/cpp",
"//chromeos",
"//chromeos/assistant:buildflags",
"//chromeos/audio",
@@ -1860,6 +1913,7 @@ jumbo_split_static_library("ui") {
"//chromeos/services/multidevice_setup/public/cpp:prefs",
"//chromeos/services/multidevice_setup/public/cpp:url_provider",
"//chromeos/services/multidevice_setup/public/mojom",
+ "//chromeos/services/network_config/public/mojom",
"//chromeos/settings",
"//chromeos/strings",
"//chromeos/system",
@@ -1872,10 +1926,10 @@ jumbo_split_static_library("ui") {
"//components/session_manager/core",
"//components/user_manager",
"//google_apis/drive",
+ "//mojo/public/js:resources_grit",
"//services/data_decoder/public/cpp",
"//services/device/public/cpp:device_features",
"//services/device/public/mojom",
- "//services/ws/public/mojom",
"//ui/base/ime/chromeos",
"//ui/chromeos",
"//ui/chromeos/events",
@@ -1909,6 +1963,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/hats/hats_web_dialog.cc",
+ "views/hats/hats_web_dialog.h",
"views/profiles/incognito_menu_view.cc",
"views/profiles/incognito_menu_view.h",
"views/profiles/profile_menu_view_base.cc",
@@ -2292,10 +2348,8 @@ jumbo_split_static_library("ui") {
"webui/settings_utils_win.cc",
"webui/version_handler_win.cc",
"webui/version_handler_win.h",
- "webui/welcome/welcome_win10_handler.cc",
- "webui/welcome/welcome_win10_handler.h",
- "webui/welcome/welcome_win10_ui.cc",
- "webui/welcome/welcome_win10_ui.h",
+ "webui/version_util_win.cc",
+ "webui/version_util_win.h",
]
public_deps += [
"//ui/views",
@@ -2362,10 +2416,16 @@ jumbo_split_static_library("ui") {
if (use_dbus) {
sources += [
+ "views/status_icons/concat_menu_model.cc",
+ "views/status_icons/concat_menu_model.h",
"views/status_icons/status_icon_linux_dbus.cc",
"views/status_icons/status_icon_linux_dbus.h",
]
defines += [ "USE_DBUS" ]
+ deps += [
+ "//components/dbus/menu",
+ "//components/dbus/thread_linux",
+ ]
}
if (use_x11) {
@@ -2390,6 +2450,7 @@ jumbo_split_static_library("ui") {
deps += [
"//ui/events/devices",
"//ui/events/devices/x11",
+ "//ui/events/platform/x11",
]
}
if (use_ozone) {
@@ -2607,18 +2668,16 @@ jumbo_split_static_library("ui") {
"views/extensions/extensions_toolbar_button.h",
"views/extensions/extensions_toolbar_container.cc",
"views/extensions/extensions_toolbar_container.h",
- "views/extensions/pwa_confirmation.cc",
- "views/extensions/pwa_confirmation.h",
"views/extensions/pwa_confirmation_bubble_view.cc",
"views/extensions/pwa_confirmation_bubble_view.h",
- "views/extensions/pwa_confirmation_dialog_view.cc",
- "views/extensions/pwa_confirmation_dialog_view.h",
"views/extensions/web_app_info_image_source.cc",
"views/extensions/web_app_info_image_source.h",
"views/feature_promos/feature_promo_bubble_timeout.cc",
"views/feature_promos/feature_promo_bubble_timeout.h",
"views/feature_promos/feature_promo_bubble_view.cc",
"views/feature_promos/feature_promo_bubble_view.h",
+ "views/feature_promos/reopen_tab_promo_controller.cc",
+ "views/feature_promos/reopen_tab_promo_controller.h",
"views/find_bar_host.cc",
"views/find_bar_host.h",
"views/find_bar_view.cc",
@@ -2681,6 +2740,14 @@ jumbo_split_static_library("ui") {
"views/fullscreen_control/fullscreen_control_view.h",
"views/global_error_bubble_view.cc",
"views/global_error_bubble_view.h",
+ "views/global_media_controls/media_dialog_view.cc",
+ "views/global_media_controls/media_dialog_view.h",
+ "views/global_media_controls/media_notification_container_impl.cc",
+ "views/global_media_controls/media_notification_container_impl.h",
+ "views/global_media_controls/media_notification_list_view.cc",
+ "views/global_media_controls/media_notification_list_view.h",
+ "views/global_media_controls/media_toolbar_button_view.cc",
+ "views/global_media_controls/media_toolbar_button_view.h",
"views/hover_button.cc",
"views/hover_button.h",
"views/hung_renderer_view.cc",
@@ -2757,6 +2824,18 @@ jumbo_split_static_library("ui") {
"views/media_router/presentation_receiver_window_view.h",
"views/media_router/web_contents_display_observer_view.cc",
"views/media_router/web_contents_display_observer_view.h",
+ "views/native_file_system/native_file_system_access_icon_view.cc",
+ "views/native_file_system/native_file_system_access_icon_view.h",
+ "views/native_file_system/native_file_system_directory_access_confirmation_view.cc",
+ "views/native_file_system/native_file_system_directory_access_confirmation_view.h",
+ "views/native_file_system/native_file_system_permission_view.cc",
+ "views/native_file_system/native_file_system_permission_view.h",
+ "views/native_file_system/native_file_system_restricted_directory_dialog_view.cc",
+ "views/native_file_system/native_file_system_restricted_directory_dialog_view.h",
+ "views/native_file_system/native_file_system_ui_helpers.cc",
+ "views/native_file_system/native_file_system_ui_helpers.h",
+ "views/native_file_system/native_file_system_usage_bubble_view.cc",
+ "views/native_file_system/native_file_system_usage_bubble_view.h",
"views/omnibox/omnibox_match_cell_view.cc",
"views/omnibox/omnibox_match_cell_view.h",
"views/omnibox/omnibox_popup_contents_view.cc",
@@ -2804,6 +2883,8 @@ jumbo_split_static_library("ui") {
"views/page_info/page_info_bubble_view.h",
"views/page_info/page_info_bubble_view_base.cc",
"views/page_info/page_info_bubble_view_base.h",
+ "views/page_info/page_info_hover_button.cc",
+ "views/page_info/page_info_hover_button.h",
"views/page_info/permission_selector_row.cc",
"views/page_info/permission_selector_row.h",
"views/page_info/permission_selector_row_observer.h",
@@ -2882,12 +2963,12 @@ jumbo_split_static_library("ui") {
"views/permission_bubble/permission_prompt_impl_views.cc",
"views/profiles/avatar_toolbar_button.cc",
"views/profiles/avatar_toolbar_button.h",
+ "views/reader_mode/reader_mode_icon_view.cc",
+ "views/reader_mode/reader_mode_icon_view.h",
"views/relaunch_notification/relaunch_notification_controller.cc",
"views/relaunch_notification/relaunch_notification_controller.h",
"views/relaunch_notification/relaunch_notification_metrics.cc",
"views/relaunch_notification/relaunch_notification_metrics.h",
- "views/relaunch_notification/relaunch_recommended_timer.cc",
- "views/relaunch_notification/relaunch_recommended_timer.h",
"views/relaunch_notification/relaunch_required_timer.cc",
"views/relaunch_notification/relaunch_required_timer.h",
"views/relaunch_notification/relaunch_required_timer_internal.cc",
@@ -2906,6 +2987,10 @@ jumbo_split_static_library("ui") {
"views/send_tab_to_self/send_tab_to_self_icon_view.h",
"views/session_crashed_bubble_view.cc",
"views/session_crashed_bubble_view.h",
+ "views/sharing/click_to_call/click_to_call_dialog_view.cc",
+ "views/sharing/click_to_call/click_to_call_dialog_view.h",
+ "views/sharing/click_to_call/click_to_call_icon_view.cc",
+ "views/sharing/click_to_call/click_to_call_icon_view.h",
"views/simple_message_box_views.cc",
"views/simple_message_box_views.h",
"views/status_bubble_views.cc",
@@ -2922,6 +3007,8 @@ jumbo_split_static_library("ui") {
"views/tab_icon_view.h",
"views/tab_modal_confirm_dialog_views.cc",
"views/tab_modal_confirm_dialog_views.h",
+ "views/tab_sharing/tab_sharing_ui_views.cc",
+ "views/tab_sharing/tab_sharing_ui_views.h",
"views/tabs/alert_indicator.cc",
"views/tabs/alert_indicator.h",
"views/tabs/browser_tab_strip_controller.cc",
@@ -3011,6 +3098,10 @@ jumbo_split_static_library("ui") {
"views/webauthn/authenticator_client_pin_entry_sheet_view.h",
"views/webauthn/authenticator_client_pin_entry_view.cc",
"views/webauthn/authenticator_client_pin_entry_view.h",
+ "views/webauthn/authenticator_qr_code.cc",
+ "views/webauthn/authenticator_qr_code.h",
+ "views/webauthn/authenticator_qr_sheet_view.cc",
+ "views/webauthn/authenticator_qr_sheet_view.h",
"views/webauthn/authenticator_request_dialog_view.cc",
"views/webauthn/authenticator_request_dialog_view.h",
"views/webauthn/authenticator_request_sheet_view.cc",
@@ -3045,14 +3136,16 @@ jumbo_split_static_library("ui") {
"webauthn/transport_utils.h",
]
deps += [
+ "//build:branding_buildflags",
"//chrome/browser/ui/views",
"//components/constrained_window",
+ "//components/media_message_center",
"//components/payments/content",
"//components/payments/core",
"//components/tab_count_metrics",
"//components/ui_devtools/views",
"//device/vr/buildflags:buildflags",
- "//services/ws/public/cpp/input_devices",
+ "//services/media_session/public/mojom",
"//ui/views:buildflags",
]
@@ -3116,8 +3209,6 @@ jumbo_split_static_library("ui") {
}
if (use_aura) {
- deps += [ "//services/ws/public/mojom" ]
-
# These files can do Gtk+-based theming for builds with gtk enabled.
if (is_desktop_linux) {
sources += [
@@ -3147,6 +3238,7 @@ jumbo_split_static_library("ui") {
"views/relaunch_notification/relaunch_notification_controller_platform_impl_chromeos.cc",
"views/relaunch_notification/relaunch_notification_controller_platform_impl_chromeos.h",
]
+ deps += [ "//ui/ozone" ]
} else {
sources += [
"views/frame/opaque_browser_frame_view.cc",
@@ -3167,6 +3259,8 @@ jumbo_split_static_library("ui") {
"views/relaunch_notification/relaunch_notification_controller_platform_impl_desktop.h",
"views/relaunch_notification/relaunch_recommended_bubble_view.cc",
"views/relaunch_notification/relaunch_recommended_bubble_view.h",
+ "views/relaunch_notification/relaunch_recommended_timer.cc",
+ "views/relaunch_notification/relaunch_recommended_timer.h",
"views/relaunch_notification/relaunch_required_dialog_view.cc",
"views/relaunch_notification/relaunch_required_dialog_view.h",
"views/screen_capture_notification_ui_views.cc",
@@ -3180,7 +3274,6 @@ jumbo_split_static_library("ui") {
"views/sync/dice_signin_button_view.h",
"views/sync/one_click_signin_dialog_view.cc",
"views/sync/one_click_signin_dialog_view.h",
- "views/tabs/window_finder.cc",
]
deps += [ "//ui/views/window/vector_icons" ]
}
@@ -3198,10 +3291,10 @@ jumbo_split_static_library("ui") {
"aura/native_window_tracker_aura.h",
"aura/tab_contents/web_drag_bookmark_handler_aura.cc",
"aura/tab_contents/web_drag_bookmark_handler_aura.h",
- "ime/ime_native_window.h",
- "ime/ime_window.cc",
- "ime/ime_window.h",
- "ime/ime_window_observer.h",
+ "input_method/ime_native_window.h",
+ "input_method/ime_window.cc",
+ "input_method/ime_window.h",
+ "input_method/ime_window_observer.h",
"views/accelerator_utils_aura.cc",
"views/apps/app_window_desktop_native_widget_aura_win.cc",
"views/apps/app_window_desktop_native_widget_aura_win.h",
@@ -3254,8 +3347,6 @@ jumbo_split_static_library("ui") {
"app_list/app_context_menu.cc",
"app_list/app_context_menu.h",
"app_list/app_context_menu_delegate.h",
- "app_list/app_launch_event_logger.cc",
- "app_list/app_launch_event_logger.h",
"app_list/app_list_client_impl.cc",
"app_list/app_list_client_impl.h",
"app_list/app_list_controller_delegate.cc",
@@ -3313,12 +3404,10 @@ jumbo_split_static_library("ui") {
"app_list/search/chrome_search_result.h",
"app_list/search/common/url_icon_source.cc",
"app_list/search/common/url_icon_source.h",
- "app_list/search/crostini/crostini_repository_search_provider.cc",
- "app_list/search/crostini/crostini_repository_search_provider.h",
- "app_list/search/crostini/crostini_repository_search_result.cc",
- "app_list/search/crostini/crostini_repository_search_result.h",
"app_list/search/extension_app_result.cc",
"app_list/search/extension_app_result.h",
+ "app_list/search/logging/search_ranking_event_logger.cc",
+ "app_list/search/logging/search_ranking_event_logger.h",
"app_list/search/mixer.cc",
"app_list/search/mixer.h",
"app_list/search/omnibox_provider.cc",
@@ -3333,6 +3422,10 @@ jumbo_split_static_library("ui") {
"app_list/search/search_provider.h",
"app_list/search/search_resource_manager.cc",
"app_list/search/search_resource_manager.h",
+ "app_list/search/search_result_ranker/app_launch_data.cc",
+ "app_list/search/search_result_ranker/app_launch_data.h",
+ "app_list/search/search_result_ranker/app_launch_event_logger.cc",
+ "app_list/search/search_result_ranker/app_launch_event_logger.h",
"app_list/search/search_result_ranker/app_launch_predictor.cc",
"app_list/search/search_result_ranker/app_launch_predictor.h",
"app_list/search/search_result_ranker/app_list_launch_metrics_provider.cc",
@@ -3353,6 +3446,8 @@ jumbo_split_static_library("ui") {
"app_list/search/search_result_ranker/recurrence_predictor.h",
"app_list/search/search_result_ranker/recurrence_ranker.cc",
"app_list/search/search_result_ranker/recurrence_ranker.h",
+ "app_list/search/search_result_ranker/recurrence_ranker_util.cc",
+ "app_list/search/search_result_ranker/recurrence_ranker_util.h",
"app_list/search/search_result_ranker/search_result_ranker.cc",
"app_list/search/search_result_ranker/search_result_ranker.h",
"app_list/search/settings_shortcut/settings_shortcut_metadata.cc",
@@ -3368,8 +3463,8 @@ jumbo_split_static_library("ui") {
"//ash/app_list",
"//ash/public/cpp/app_list/vector_icons",
"//ash/resources/vector_icons",
- "//chrome/browser/ui:app_launch_event_logger_proto",
"//chrome/browser/ui/app_list/search/logging:search_ranking_event_proto",
+ "//chrome/browser/ui/app_list/search/search_result_ranker:app_launch_event_logger_proto",
"//chrome/browser/ui/app_list/search/search_result_ranker:app_launch_predictor_proto",
"//chrome/browser/ui/app_list/search/search_result_ranker:app_list_launch_recorder_proto",
"//chrome/browser/ui/app_list/search/search_result_ranker:recurrence_ranker_proto",
@@ -3494,8 +3589,6 @@ 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_installer_view.cc",
- "views/crostini/crostini_app_installer_view.h",
"views/crostini/crostini_app_restart_view.cc",
"views/crostini/crostini_app_restart_view.h",
"views/crostini/crostini_app_uninstaller_view.cc",
@@ -3532,8 +3625,6 @@ jumbo_split_static_library("ui") {
"ash/assistant/assistant_context_util.h",
"ash/assistant/assistant_image_downloader.cc",
"ash/assistant/assistant_image_downloader.h",
- "ash/assistant/assistant_pref_util.cc",
- "ash/assistant/assistant_pref_util.h",
"ash/assistant/assistant_setup.cc",
"ash/assistant/assistant_setup.h",
"ash/assistant/device_actions.cc",
@@ -3541,22 +3632,6 @@ jumbo_split_static_library("ui") {
]
}
- if (enable_desktop_in_product_help) {
- sources += [
- "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",
- ]
- }
-
if (enable_extensions) {
deps += [
"//apps",
@@ -3568,7 +3643,7 @@ jumbo_split_static_library("ui") {
"//components/drive",
"//components/guest_view/browser",
"//extensions/browser",
- "//extensions/common:mojo",
+ "//extensions/common:mojom",
"//extensions/components/native_app_window",
"//extensions/strings",
]
@@ -3633,16 +3708,18 @@ jumbo_split_static_library("ui") {
"web_applications/app_browser_controller.h",
"web_applications/system_web_app_ui_utils_chromeos.cc",
"web_applications/system_web_app_ui_utils_chromeos.h",
+ "web_applications/web_app_dialog_manager.cc",
+ "web_applications/web_app_dialog_manager.h",
"web_applications/web_app_dialog_utils.cc",
"web_applications/web_app_dialog_utils.h",
+ "web_applications/web_app_launch_manager.cc",
+ "web_applications/web_app_launch_manager.h",
"web_applications/web_app_metrics.cc",
"web_applications/web_app_metrics.h",
"web_applications/web_app_metrics_factory.cc",
"web_applications/web_app_metrics_factory.h",
- "web_applications/web_app_ui_service.cc",
- "web_applications/web_app_ui_service.h",
- "web_applications/web_app_ui_service_factory.cc",
- "web_applications/web_app_ui_service_factory.h",
+ "web_applications/web_app_ui_manager_impl.cc",
+ "web_applications/web_app_ui_manager_impl.h",
"webui/extensions/extension_basic_info.cc",
"webui/extensions/extension_basic_info.h",
"webui/extensions/extension_icon_source.cc",
@@ -3720,6 +3797,8 @@ jumbo_split_static_library("ui") {
"webui/print_preview/local_printer_handler_chromeos.cc",
"webui/print_preview/local_printer_handler_chromeos.h",
]
+
+ deps += [ "//services/identity/public/cpp:cpp_types" ]
} else {
sources += [
"webui/print_preview/local_printer_handler_default.cc",
@@ -3874,6 +3953,8 @@ static_library("test_support") {
"exclusive_access/fullscreen_controller_state_tests.h",
"exclusive_access/fullscreen_controller_test.cc",
"exclusive_access/fullscreen_controller_test.h",
+ "global_error/global_error_waiter.cc",
+ "global_error/global_error_waiter.h",
"passwords/manage_passwords_ui_controller_mock.cc",
"passwords/manage_passwords_ui_controller_mock.h",
"passwords/password_dialog_controller_mock.cc",
@@ -3888,6 +3969,7 @@ static_library("test_support") {
deps += [
"//chrome/test:test_support_ui",
"//components/signin/core/browser",
+ "//components/signin/public/identity_manager",
"//components/ukm:test_support",
"//components/zoom",
"//services/metrics/public/mojom",
@@ -3896,6 +3978,8 @@ static_library("test_support") {
if (is_chromeos) {
sources += [
+ "ash/ash_test_util.cc",
+ "ash/ash_test_util.h",
"ash/fake_tablet_mode_controller.cc",
"ash/fake_tablet_mode_controller.h",
"ash/test_login_screen.cc",
@@ -3935,9 +4019,3 @@ if (is_android) {
]
}
}
-
-proto_library("app_launch_event_logger_proto") {
- sources = [
- "app_list/app_launch_event_logger.proto",
- ]
-}
diff --git a/chromium/chrome/browser/ui/app_list/search/search_result_ranker/BUILD.gn b/chromium/chrome/browser/ui/app_list/search/search_result_ranker/BUILD.gn
index 6e811a3c565..d23cd7bca16 100644
--- a/chromium/chrome/browser/ui/app_list/search/search_result_ranker/BUILD.gn
+++ b/chromium/chrome/browser/ui/app_list/search/search_result_ranker/BUILD.gn
@@ -4,6 +4,12 @@
import("//third_party/protobuf/proto_library.gni")
+proto_library("app_launch_event_logger_proto") {
+ sources = [
+ "app_launch_event_logger.proto",
+ ]
+}
+
proto_library("app_launch_predictor_proto") {
sources = [
"app_launch_predictor.proto",
diff --git a/chromium/chrome/browser/ui/views/BUILD.gn b/chromium/chrome/browser/ui/views/BUILD.gn
index 9e4f35b6eb3..6862437bcc8 100644
--- a/chromium/chrome/browser/ui/views/BUILD.gn
+++ b/chromium/chrome/browser/ui/views/BUILD.gn
@@ -25,6 +25,7 @@ component("views") {
deps = [
"//base",
+ "//build:branding_buildflags",
"//chrome/app:command_ids",
"//components/keep_alive_registry",
"//components/vector_icons",
diff --git a/chromium/chrome/browser/ui/webui/OWNERS b/chromium/chrome/browser/ui/webui/OWNERS
index 5e97af03896..be3a2059016 100644
--- a/chromium/chrome/browser/ui/webui/OWNERS
+++ b/chromium/chrome/browser/ui/webui/OWNERS
@@ -25,5 +25,6 @@ per-file sync_internals*=file://components/sync/OWNERS
per-file invalidations_message_handler.*=file://components/invalidation/OWNERS
per-file policy*=file://chromeos/policy/OWNERS
+per-file policy*=file://chrome/browser/policy/OWNERS
# COMPONENT: UI>Browser>WebUI
diff --git a/chromium/chrome/browser/ui/webui/about_ui.cc b/chromium/chrome/browser/ui/webui/about_ui.cc
index f673c9c74d3..d4cff184227 100644
--- a/chromium/chrome/browser/ui/webui/about_ui.cc
+++ b/chromium/chrome/browser/ui/webui/about_ui.cc
@@ -580,7 +580,7 @@ AboutUIHTMLSource::AboutUIHTMLSource(const std::string& source_name,
AboutUIHTMLSource::~AboutUIHTMLSource() {}
-std::string AboutUIHTMLSource::GetSource() const {
+std::string AboutUIHTMLSource::GetSource() {
return source_name_;
}
@@ -640,7 +640,7 @@ void AboutUIHTMLSource::FinishDataRequest(
callback.Run(base::RefCountedString::TakeString(&html_copy));
}
-std::string AboutUIHTMLSource::GetMimeType(const std::string& path) const {
+std::string AboutUIHTMLSource::GetMimeType(const std::string& path) {
if (path == kCreditsJsPath ||
#if defined(OS_CHROMEOS)
path == kKeyboardUtilsPath ||
@@ -652,7 +652,7 @@ std::string AboutUIHTMLSource::GetMimeType(const std::string& path) const {
return "text/html";
}
-bool AboutUIHTMLSource::ShouldAddContentSecurityPolicy() const {
+bool AboutUIHTMLSource::ShouldAddContentSecurityPolicy() {
#if defined(OS_CHROMEOS)
if (source_name_ == chrome::kChromeUIOSCreditsHost ||
source_name_ == chrome::kChromeUILinuxCreditsHost) {
@@ -663,7 +663,7 @@ bool AboutUIHTMLSource::ShouldAddContentSecurityPolicy() const {
}
std::string AboutUIHTMLSource::GetAccessControlAllowOriginForOrigin(
- const std::string& origin) const {
+ const std::string& origin) {
#if defined(OS_CHROMEOS)
// Allow chrome://oobe to load chrome://terms via XHR.
if (source_name_ == chrome::kChromeUITermsHost &&
diff --git a/chromium/chrome/browser/ui/webui/about_ui.h b/chromium/chrome/browser/ui/webui/about_ui.h
index 801b98e1b78..6860148d33b 100644
--- a/chromium/chrome/browser/ui/webui/about_ui.h
+++ b/chromium/chrome/browser/ui/webui/about_ui.h
@@ -23,15 +23,15 @@ class AboutUIHTMLSource : public content::URLDataSource {
~AboutUIHTMLSource() override;
// content::URLDataSource implementation.
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override;
- std::string GetMimeType(const std::string& path) const override;
- bool ShouldAddContentSecurityPolicy() const override;
+ std::string GetMimeType(const std::string& path) override;
+ bool ShouldAddContentSecurityPolicy() override;
std::string GetAccessControlAllowOriginForOrigin(
- const std::string& origin) const override;
+ const std::string& origin) override;
// Send the response data.
void FinishDataRequest(
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 575ff1b69c8..4b44c8cfcf5 100644
--- a/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc
+++ b/chromium/chrome/browser/ui/webui/app_launcher_login_handler.cc
@@ -29,12 +29,12 @@
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/signin_metrics.h"
-#include "components/signin/core/browser/signin_pref_names.h"
+#include "components/signin/public/base/signin_metrics.h"
+#include "components/signin/public/base/signin_pref_names.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#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"
diff --git a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc
index 3bb63dbd340..7005dd6a16a 100644
--- a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc
+++ b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc
@@ -94,7 +94,7 @@ AppLauncherPageUI::HTMLSource::HTMLSource(Profile* profile)
: profile_(profile) {
}
-std::string AppLauncherPageUI::HTMLSource::GetSource() const {
+std::string AppLauncherPageUI::HTMLSource::GetSource() {
return chrome::kChromeUIAppLauncherPageHost;
}
@@ -118,33 +118,30 @@ void AppLauncherPageUI::HTMLSource::StartDataRequest(
}
std::string AppLauncherPageUI::HTMLSource::GetMimeType(
- const std::string& resource) const {
+ const std::string& resource) {
return "text/html";
}
-bool AppLauncherPageUI::HTMLSource::ShouldReplaceExistingSource() const {
+bool AppLauncherPageUI::HTMLSource::ShouldReplaceExistingSource() {
return false;
}
-bool AppLauncherPageUI::HTMLSource::AllowCaching() const {
+bool AppLauncherPageUI::HTMLSource::AllowCaching() {
// Should not be cached to reflect dynamically-generated contents that may
// depend on user profiles.
return false;
}
-std::string AppLauncherPageUI::HTMLSource::GetContentSecurityPolicyScriptSrc()
- const {
+std::string AppLauncherPageUI::HTMLSource::GetContentSecurityPolicyScriptSrc() {
// 'unsafe-inline' is added to script-src.
return "script-src chrome://resources 'self' 'unsafe-eval' 'unsafe-inline';";
}
-std::string AppLauncherPageUI::HTMLSource::GetContentSecurityPolicyStyleSrc()
- const {
+std::string AppLauncherPageUI::HTMLSource::GetContentSecurityPolicyStyleSrc() {
return "style-src 'self' chrome://resources chrome://theme 'unsafe-inline';";
}
-std::string AppLauncherPageUI::HTMLSource::GetContentSecurityPolicyImgSrc()
- const {
+std::string AppLauncherPageUI::HTMLSource::GetContentSecurityPolicyImgSrc() {
return "img-src chrome://extension-icon chrome://theme chrome://resources "
"data:;";
}
diff --git a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h
index 2bed010924c..0b632d6adb4 100644
--- a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h
+++ b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h
@@ -37,17 +37,17 @@ class AppLauncherPageUI : public content::WebUIController {
~HTMLSource() override;
// content::URLDataSource implementation.
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override;
- std::string GetMimeType(const std::string&) const override;
- bool ShouldReplaceExistingSource() const override;
- bool AllowCaching() const override;
- std::string GetContentSecurityPolicyScriptSrc() const override;
- std::string GetContentSecurityPolicyStyleSrc() const override;
- std::string GetContentSecurityPolicyImgSrc() const override;
+ std::string GetMimeType(const std::string&) override;
+ bool ShouldReplaceExistingSource() override;
+ bool AllowCaching() override;
+ std::string GetContentSecurityPolicyScriptSrc() override;
+ std::string GetContentSecurityPolicyStyleSrc() override;
+ std::string GetContentSecurityPolicyImgSrc() override;
private:
diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management.mojom b/chromium/chrome/browser/ui/webui/app_management/app_management.mojom
index 9779a9e95b6..c62180bf2b0 100644
--- a/chromium/chrome/browser/ui/webui/app_management/app_management.mojom
+++ b/chromium/chrome/browser/ui/webui/app_management/app_management.mojom
@@ -17,10 +17,13 @@ struct App {
string? description;
apps.mojom.OptionalBool is_pinned;
+ apps.mojom.OptionalBool is_policy_pinned;
string? version;
string? size;
map<uint32, apps.mojom.Permission> permissions;
apps.mojom.InstallSource install_source;
+ bool hide_more_settings;
+ bool hide_pin_to_shelf;
};
// Extension-based apps primarily use install-time permissions that cannot be
@@ -52,6 +55,7 @@ interface Page {
OnAppAdded(App app);
OnAppChanged(App update);
OnAppRemoved(string app_id);
+ OnArcSupportChanged(bool supported);
};
// Permission Type Enums for each App Publisher. The App Publishers are
@@ -66,6 +70,8 @@ enum ArcPermissionType {
LOCATION = 1,
MICROPHONE = 2,
NOTIFICATIONS = 3,
+ CONTACTS = 4,
+ STORAGE = 5,
};
// This enum takes the important permission values from the
diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc
index 2235200a6b2..8df423bb254 100644
--- a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc
+++ b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc
@@ -8,14 +8,16 @@
#include <vector>
#include "base/containers/flat_map.h"
+#include "base/stl_util.h"
#include "base/strings/utf_string_conversions.h"
+#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/services/app_service/public/cpp/app_registry_cache.h"
-#include "chrome/services/app_service/public/cpp/app_service_proxy.h"
#include "chrome/services/app_service/public/mojom/types.mojom.h"
#include "extensions/browser/extension_registry.h"
+#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
#include "extensions/common/permissions/permission_message.h"
#include "extensions/common/permissions/permissions_data.h"
@@ -24,6 +26,15 @@ using apps::mojom::OptionalBool;
namespace {
+constexpr char const* kAppIdsWithHiddenMoreSettings[] = {
+ extension_misc::kFilesManagerAppId,
+ extensions::kWebStoreAppId,
+};
+
+constexpr char const* kAppIdsWithHiddenPinToShelf[] = {
+ extension_misc::kChromeAppId,
+};
+
app_management::mojom::ExtensionAppPermissionMessagePtr
CreateExtensionAppPermissionMessage(
const extensions::PermissionMessage& message) {
@@ -35,6 +46,15 @@ CreateExtensionAppPermissionMessage(
base::UTF16ToUTF8(message.message()), std::move(submessages));
}
+bool ShouldHideMoreSettings(const std::string app_id) {
+ return base::Contains(kAppIdsWithHiddenMoreSettings, app_id);
+}
+
+bool ShouldHidePinToShelf(const std::string app_id) {
+ return base::Contains(kAppIdsWithHiddenPinToShelf, app_id);
+}
+
+
} // namespace
AppManagementPageHandler::AppManagementPageHandler(
@@ -197,8 +217,14 @@ app_management::mojom::AppPtr AppManagementPageHandler::CreateUIAppPtr(
app->is_pinned = shelf_delegate_.IsPinned(update.AppId())
? OptionalBool::kTrue
: OptionalBool::kFalse;
+ app->is_policy_pinned = shelf_delegate_.IsPolicyPinned(update.AppId())
+ ? OptionalBool::kTrue
+ : OptionalBool::kFalse;
#endif
+ app->hide_more_settings = ShouldHideMoreSettings(app->id);
+ app->hide_pin_to_shelf = ShouldHidePinToShelf(app->id);
+
return app;
}
@@ -221,6 +247,10 @@ void AppManagementPageHandler::OnAppUpdate(const apps::AppUpdate& update) {
}
}
+void AppManagementPageHandler::OnArcSupportChanged(bool supported) {
+ page_->OnArcSupportChanged(supported);
+}
+
void AppManagementPageHandler::OnAppRegistryCacheWillBeDestroyed(
apps::AppRegistryCache* cache) {
Observe(nullptr);
diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h
index 0c7cb77ae66..25f0a826171 100644
--- a/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h
+++ b/chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h
@@ -26,6 +26,7 @@ class AppManagementPageHandler : public app_management::mojom::PageHandler,
~AppManagementPageHandler() override;
void OnPinnedChanged(const std::string& app_id, bool pinned);
+ void OnArcSupportChanged(bool supported);
// app_management::mojom::PageHandler:
void GetApps(GetAppsCallback callback) override;
diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.cc b/chromium/chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.cc
index 1070ace06ff..0a3d90a6dfd 100644
--- a/chromium/chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.cc
+++ b/chromium/chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.cc
@@ -8,6 +8,7 @@
#include "ash/public/cpp/shelf_model.h"
#include "ash/public/cpp/shelf_types.h"
#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h"
+#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller_util.h"
#include "chrome/browser/ui/webui/app_management/app_management_page_handler.h"
#include "chrome/services/app_service/public/mojom/types.mojom.h"
@@ -27,6 +28,15 @@ bool AppManagementShelfDelegate::IsPinned(const std::string& app_id) {
return ChromeLauncherController::instance()->IsAppPinned(app_id);
}
+bool AppManagementShelfDelegate::IsPolicyPinned(
+ const std::string& app_id) const {
+ auto* shelf_item =
+ ChromeLauncherController::instance()->GetItem(ash::ShelfID(app_id));
+ // If the app does not exist on the launcher, it has not been pinned by
+ // policy.
+ return shelf_item && shelf_item->pinned_by_policy;
+}
+
void AppManagementShelfDelegate::SetPinned(const std::string& app_id,
OptionalBool pinned) {
if (pinned == OptionalBool::kTrue) {
diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.h b/chromium/chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.h
index 40c3ba4f7b8..6471cccb454 100644
--- a/chromium/chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.h
+++ b/chromium/chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.h
@@ -23,6 +23,8 @@ class AppManagementShelfDelegate : public ash::ShelfModelObserver {
bool IsPinned(const std::string& app_id);
void SetPinned(const std::string& app_id, apps::mojom::OptionalBool pinned);
+ bool IsPolicyPinned(const std::string& app_id) const;
+
private:
// ash::ShelfModelObserver:
void ShelfItemAdded(int index) override;
diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc
index fd026bd0e47..d59a0bd6351 100644
--- a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc
+++ b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.cc
@@ -4,6 +4,7 @@
#include "chrome/browser/ui/webui/app_management/app_management_ui.h"
+#include <memory>
#include <utility>
#include "base/bind.h"
@@ -18,13 +19,25 @@
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
+#include "components/prefs/pref_service.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "ui/base/resource/resource_bundle.h"
+#if defined(OS_CHROMEOS)
+#include "chrome/browser/chromeos/arc/arc_util.h"
+#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
+#include "components/arc/arc_prefs.h"
+#endif
+
namespace {
+#if defined(OS_CHROMEOS)
+constexpr char kArcFrameworkPackage[] = "android";
+constexpr int kMinAndroidFrameworkVersion = 28; // Android P
+#endif
+
content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIAppManagementHost);
@@ -34,28 +47,37 @@ content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) {
{"appNoPermission", IDS_APPLICATION_INFO_APP_NO_PERMISSIONS_TEXT},
{"back", IDS_APP_MANAGEMENT_BACK},
{"camera", IDS_APP_MANAGEMENT_CAMERA},
+ {"contacts", IDS_APP_MANAGEMENT_CONTACTS},
+ {"controlledByPolicy", IDS_CONTROLLED_SETTING_POLICY},
{"lessApps", IDS_APP_MANAGEMENT_LESS_APPS},
{"location", IDS_APP_MANAGEMENT_LOCATION},
{"microphone", IDS_APP_MANAGEMENT_MICROPHONE},
{"moreApps", IDS_APP_MANAGEMENT_MORE_APPS},
+ {"moreSettings", IDS_APP_MANAGEMENT_MORE_SETTINGS},
{"noSearchResults", IDS_APP_MANAGEMENT_NO_RESULTS},
- {"notificationSublabel", IDS_APP_MANAGEMENT_NOTIFICATIONS_SUBLABEL},
{"notifications", IDS_APP_MANAGEMENT_NOTIFICATIONS},
+ {"notificationSublabel", IDS_APP_MANAGEMENT_NOTIFICATIONS_SUBLABEL},
{"openAndroidSettings", IDS_APP_MANAGEMENT_ANDROID_SETTINGS},
{"openExtensionsSettings", IDS_APP_MANAGEMENT_EXTENSIONS_SETTINGS},
{"openSiteSettings", IDS_APP_MANAGEMENT_SITE_SETTING},
{"permissions", IDS_APP_MANAGEMENT_PERMISSIONS},
- {"morePermissions", IDS_APP_MANAGEMENT_MORE_PERMISSIONS},
- {"thisAppCan", IDS_APP_MANAGEMENT_THIS_APP_CAN},
+ {"pinControlledByPolicy", IDS_APP_MANAGEMENT_PIN_ENFORCED_BY_POLICY},
{"pinToShelf", IDS_APP_MANAGEMENT_PIN_TO_SHELF},
{"searchPrompt", IDS_APP_MANAGEMENT_SEARCH_PROMPT},
{"size", IDS_APP_MANAGEMENT_SIZE},
+ {"storage", IDS_APP_MANAGEMENT_STORAGE},
+ {"thisAppCan", IDS_APP_MANAGEMENT_THIS_APP_CAN},
{"title", IDS_APP_MANAGEMENT_TITLE},
{"uninstall", IDS_APP_MANAGEMENT_UNINSTALL},
{"version", IDS_APP_MANAGEMENT_VERSION},
};
AddLocalizedStringsBulk(source, kStrings, base::size(kStrings));
+#if defined(OS_CHROMEOS)
+ source->AddBoolean("isSupportedArcVersion",
+ AppManagementUI::IsCurrentArcVersionSupported(profile));
+#endif // OS_CHROMEOS
+
source->AddResourcePath("app_management.mojom-lite.js",
IDR_APP_MANAGEMENT_MOJO_LITE_JS);
source->AddResourcePath("types.mojom-lite.js",
@@ -73,10 +95,10 @@ content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) {
IDR_APP_MANAGEMENT_API_LISTENER_HTML);
source->AddResourcePath("api_listener.js",
IDR_APP_MANAGEMENT_API_LISTENER_JS);
- source->AddResourcePath("app.html", IDR_APP_MANAGEMENT_APP_HTML);
- source->AddResourcePath("app.js", IDR_APP_MANAGEMENT_APP_JS);
source->AddResourcePath("app_item.html", IDR_APP_MANAGEMENT_APP_ITEM_HTML);
source->AddResourcePath("app_item.js", IDR_APP_MANAGEMENT_APP_ITEM_JS);
+ source->AddResourcePath("app.html", IDR_APP_MANAGEMENT_APP_HTML);
+ source->AddResourcePath("app.js", IDR_APP_MANAGEMENT_APP_JS);
source->AddResourcePath("arc_permission_view.html",
IDR_APP_MANAGEMENT_ARC_PERMISSION_VIEW_HTML);
source->AddResourcePath("arc_permission_view.js",
@@ -91,29 +113,26 @@ content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) {
IDR_APP_MANAGEMENT_CHROME_APP_PERMISSION_VIEW_JS);
source->AddResourcePath("constants.html", IDR_APP_MANAGEMENT_CONSTANTS_HTML);
source->AddResourcePath("constants.js", IDR_APP_MANAGEMENT_CONSTANTS_JS);
+ source->AddResourcePath("dom_switch.html",
+ IDR_APP_MANAGEMENT_DOM_SWITCH_HTML);
+ source->AddResourcePath("dom_switch.js", IDR_APP_MANAGEMENT_DOM_SWITCH_JS);
source->AddResourcePath("expandable_app_list.html",
IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_HTML);
source->AddResourcePath("expandable_app_list.js",
IDR_APP_MANAGEMENT_EXPANDABLE_APP_LIST_JS);
- source->AddResourcePath("dom_switch.html",
- IDR_APP_MANAGEMENT_DOM_SWITCH_HTML);
- source->AddResourcePath("dom_switch.js", IDR_APP_MANAGEMENT_DOM_SWITCH_JS);
source->AddResourcePath("fake_page_handler.js",
IDR_APP_MANAGEMENT_FAKE_PAGE_HANDLER_JS);
+ source->AddResourcePath("icons.html", IDR_APP_MANAGEMENT_ICONS_HTML);
source->AddResourcePath("main_view.html", IDR_APP_MANAGEMENT_MAIN_VIEW_HTML);
source->AddResourcePath("main_view.js", IDR_APP_MANAGEMENT_MAIN_VIEW_JS);
- source->AddResourcePath("notifications_view.html",
- IDR_APP_MANAGEMENT_NOTIFICATIONS_VIEW_HTML);
- source->AddResourcePath("notifications_view.js",
- IDR_APP_MANAGEMENT_NOTIFICATIONS_VIEW_JS);
- source->AddResourcePath("permission_view_header.html",
- IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_HTML);
- source->AddResourcePath("permission_view_header.js",
- IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_JS);
source->AddResourcePath("metadata_view.html",
IDR_APP_MANAGEMENT_METADATA_VIEW_HTML);
source->AddResourcePath("metadata_view.js",
IDR_APP_MANAGEMENT_METADATA_VIEW_JS);
+ source->AddResourcePath("notifications_view.html",
+ IDR_APP_MANAGEMENT_NOTIFICATIONS_VIEW_HTML);
+ source->AddResourcePath("notifications_view.js",
+ IDR_APP_MANAGEMENT_NOTIFICATIONS_VIEW_JS);
source->AddResourcePath("permission_item.html",
IDR_APP_MANAGEMENT_PERMISSION_ITEM_HTML);
source->AddResourcePath("permission_item.js",
@@ -122,6 +141,14 @@ content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) {
IDR_APP_MANAGEMENT_PERMISSION_TOGGLE_HTML);
source->AddResourcePath("permission_toggle.js",
IDR_APP_MANAGEMENT_PERMISSION_TOGGLE_JS);
+ source->AddResourcePath("permission_view_header.html",
+ IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_HTML);
+ source->AddResourcePath("permission_view_header.js",
+ IDR_APP_MANAGEMENT_PERMISSION_VIEW_HEADER_JS);
+ source->AddResourcePath("pin_to_shelf_item.html",
+ IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_HTML);
+ source->AddResourcePath("pin_to_shelf_item.js",
+ IDR_APP_MANAGEMENT_PIN_TO_SHELF_ITEM_JS);
source->AddResourcePath("pwa_permission_view.html",
IDR_APP_MANAGEMENT_PWA_PERMISSION_VIEW_HTML);
source->AddResourcePath("pwa_permission_view.js",
@@ -137,12 +164,15 @@ content::WebUIDataSource* CreateAppManagementUIHTMLSource(Profile* profile) {
IDR_APP_MANAGEMENT_SHARED_STYLE_HTML);
source->AddResourcePath("shared_vars.html",
IDR_APP_MANAGEMENT_SHARED_VARS_HTML);
- source->AddResourcePath("store.html", IDR_APP_MANAGEMENT_STORE_HTML);
- source->AddResourcePath("store.js", IDR_APP_MANAGEMENT_STORE_JS);
source->AddResourcePath("store_client.html",
IDR_APP_MANAGEMENT_STORE_CLIENT_HTML);
source->AddResourcePath("store_client.js",
IDR_APP_MANAGEMENT_STORE_CLIENT_JS);
+ source->AddResourcePath("store.html", IDR_APP_MANAGEMENT_STORE_HTML);
+ source->AddResourcePath("store.js", IDR_APP_MANAGEMENT_STORE_JS);
+ source->AddResourcePath("toggle_row.html",
+ IDR_APP_MANAGEMENT_TOGGLE_ROW_HTML);
+ source->AddResourcePath("toggle_row.js", IDR_APP_MANAGEMENT_TOGGLE_ROW_JS);
source->AddResourcePath("types.js", IDR_APP_MANAGEMENT_TYPES_JS);
source->AddResourcePath("util.html", IDR_APP_MANAGEMENT_UTIL_HTML);
source->AddResourcePath("util.js", IDR_APP_MANAGEMENT_UTIL_JS);
@@ -182,6 +212,12 @@ AppManagementUI::AppManagementUI(content::WebUI* web_ui)
plural_string_handler->AddLocalizedString(
"appListPreview", IDS_APP_MANAGEMENT_APP_LIST_PREVIEW);
web_ui->AddMessageHandler(std::move(plural_string_handler));
+
+#if defined(OS_CHROMEOS)
+ if (arc::IsArcAllowedForProfile(profile)) {
+ ArcAppListPrefs::Get(profile)->AddObserver(this);
+ }
+#endif
}
AppManagementUI::~AppManagementUI() = default;
@@ -192,8 +228,9 @@ bool AppManagementUI::IsEnabled() {
void AppManagementUI::BindPageHandlerFactory(
app_management::mojom::PageHandlerFactoryRequest request) {
- if (page_factory_binding_.is_bound())
+ if (page_factory_binding_.is_bound()) {
page_factory_binding_.Unbind();
+ }
page_factory_binding_.Bind(std::move(request));
}
@@ -203,6 +240,41 @@ void AppManagementUI::CreatePageHandler(
app_management::mojom::PageHandlerRequest request) {
DCHECK(page);
- page_handler_.reset(new AppManagementPageHandler(std::move(request),
- std::move(page), web_ui()));
+ page_handler_ = std::make_unique<AppManagementPageHandler>(
+ std::move(request), std::move(page), web_ui());
+}
+
+#if defined(OS_CHROMEOS)
+bool AppManagementUI::IsCurrentArcVersionSupported(Profile* profile) {
+ if (arc::IsArcAllowedForProfile(profile)) {
+ auto package =
+ ArcAppListPrefs::Get(profile)->GetPackage(kArcFrameworkPackage);
+ return package && (package->package_version >= kMinAndroidFrameworkVersion);
+ }
+ return false;
+}
+
+void AppManagementUI::NotifyAndroidVersionChange(int androidVersion) {
+ if (!page_handler_) {
+ return;
+ }
+ const bool supported = androidVersion >= kMinAndroidFrameworkVersion;
+ page_handler_->OnArcSupportChanged(supported);
+}
+
+void AppManagementUI::OnPackageInstalled(
+ const arc::mojom::ArcPackageInfo& package_info) {
+ if (package_info.package_name != kArcFrameworkPackage) {
+ return;
+ }
+ NotifyAndroidVersionChange(package_info.package_version);
+}
+
+void AppManagementUI::OnPackageModified(
+ const arc::mojom::ArcPackageInfo& package_info) {
+ if (package_info.package_name != kArcFrameworkPackage) {
+ return;
+ }
+ NotifyAndroidVersionChange(package_info.package_version);
}
+#endif // OS_CHROMEOS
diff --git a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h
index a0187ee104e..56caea216f0 100644
--- a/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h
+++ b/chromium/chrome/browser/ui/webui/app_management/app_management_ui.h
@@ -12,17 +12,31 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "ui/webui/mojo_web_ui_controller.h"
+#if defined(OS_CHROMEOS)
+#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
+#endif
+
class AppManagementPageHandler;
+class Profile;
class AppManagementUI : public ui::MojoWebUIController,
- public app_management::mojom::PageHandlerFactory {
+ public app_management::mojom::PageHandlerFactory
+#if defined(OS_CHROMEOS)
+ ,
+ public ArcAppListPrefs::Observer
+#endif // OS_CHROMEOS
+{
public:
explicit AppManagementUI(content::WebUI* web_ui);
~AppManagementUI() override;
static bool IsEnabled();
+#if defined(OS_CHROMEOS)
+ static bool IsCurrentArcVersionSupported(Profile* profile);
+#endif // OS_CHROMEOS
private:
+ void NotifyAndroidVersionChange(int androidVersion);
void BindPageHandlerFactory(
app_management::mojom::PageHandlerFactoryRequest request);
@@ -35,6 +49,14 @@ class AppManagementUI : public ui::MojoWebUIController,
mojo::Binding<app_management::mojom::PageHandlerFactory>
page_factory_binding_;
+#if defined(OS_CHROMEOS)
+ // ArcAppListPrefs::Observer:
+ void OnPackageInstalled(
+ const arc::mojom::ArcPackageInfo& package_info) override;
+ void OnPackageModified(
+ const arc::mojom::ArcPackageInfo& package_info) override;
+#endif
+
DISALLOW_COPY_AND_ASSIGN(AppManagementUI);
};
diff --git a/chromium/chrome/browser/ui/webui/autofill_internals_ui.cc b/chromium/chrome/browser/ui/webui/autofill_internals_ui.cc
index ef2f3d3bf10..489a5d65bd6 100644
--- a/chromium/chrome/browser/ui/webui/autofill_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/autofill_internals_ui.cc
@@ -6,17 +6,20 @@
#include <string>
-#include "chrome/browser/autofill/autofill_internals_logging_impl.h"
+#include "base/bind.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
-#include "components/autofill/core/browser/autofill_internals_logging.h"
+#include "components/autofill/content/browser/autofill_log_router_factory.h"
+#include "components/autofill/core/browser/logging/log_receiver.h"
+#include "components/autofill/core/browser/logging/log_router.h"
#include "components/grit/components_resources.h"
+#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "content/public/browser/web_ui_message_handler.h"
-#include "base/bind.h"
-#include "content/public/browser/storage_partition.h"
-#include "content/public/browser/web_ui.h"
+using autofill::AutofillLogRouterFactory;
+using autofill::LogRouter;
namespace {
@@ -31,28 +34,100 @@ content::WebUIDataSource* CreateAutofillInternalsHTMLSource() {
return source;
}
-} // namespace
+// Message handler for AutofillInternalsLoggingImpl. The purpose of this class
+// is to enable safe calls to JavaScript, while the renderer is fully loaded.
+class AutofillInternalsUIHandler : public content::WebUIMessageHandler,
+ public autofill::LogReceiver {
+ public:
+ AutofillInternalsUIHandler() = default;
+ ~AutofillInternalsUIHandler() override;
-AutofillInternalsUI::AutofillInternalsUI(content::WebUI* web_ui)
- : WebUIController(web_ui), WebContentsObserver(web_ui->GetWebContents()) {
- // Set up the chrome://autofill-internals source.
- Profile* profile = Profile::FromWebUI(web_ui);
- content::WebUIDataSource::Add(profile, CreateAutofillInternalsHTMLSource());
+ private:
+ // content::WebUIMessageHandler:
+ void RegisterMessages() override;
+
+ // Implements content::WebUIMessageHandler.
+ void OnJavascriptAllowed() override;
+ void OnJavascriptDisallowed() override;
+
+ // LogReceiver implementation.
+ void LogEntry(const base::Value& entry) override;
+
+ void StartSubscription();
+ void EndSubscription();
+
+ // JavaScript call handler.
+ void OnLoaded(const base::ListValue* args);
+
+ // Whether |this| is registered as a log receiver with the LogRouter.
+ bool registered_with_log_router_ = false;
+
+ DISALLOW_COPY_AND_ASSIGN(AutofillInternalsUIHandler);
+};
+
+AutofillInternalsUIHandler::~AutofillInternalsUIHandler() {
+ EndSubscription();
+}
+
+void AutofillInternalsUIHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "loaded", base::BindRepeating(&AutofillInternalsUIHandler::OnLoaded,
+ base::Unretained(this)));
+}
- autofill::AutofillInternalsLoggingImpl* internals_logging_impl =
- new autofill::AutofillInternalsLoggingImpl();
- internals_logging_impl->set_web_ui(web_ui);
- autofill::AutofillInternalsLogging* internals_logging =
- static_cast<autofill::AutofillInternalsLogging*>(internals_logging_impl);
- autofill::AutofillInternalsLogging::SetAutofillInternalsLogger(
- std::unique_ptr<autofill::AutofillInternalsLogging>(internals_logging));
+void AutofillInternalsUIHandler::OnJavascriptAllowed() {
+ StartSubscription();
}
-void AutofillInternalsUI::DidStartLoading() {}
+void AutofillInternalsUIHandler::OnJavascriptDisallowed() {
+ EndSubscription();
+}
-void AutofillInternalsUI::DidStopLoading() {
- web_ui()->CallJavascriptFunctionUnsafe("setUpAutofillInternals");
- web_ui()->CallJavascriptFunctionUnsafe(
+void AutofillInternalsUIHandler::OnLoaded(const base::ListValue* args) {
+ AllowJavascript();
+ CallJavascriptFunction("setUpAutofillInternals");
+ CallJavascriptFunction(
"notifyAboutIncognito",
base::Value(Profile::FromWebUI(web_ui())->IsIncognitoProfile()));
}
+
+void AutofillInternalsUIHandler::LogEntry(const base::Value& entry) {
+ if (!registered_with_log_router_ || entry.is_none())
+ return;
+ CallJavascriptFunction("addRawLog", entry);
+}
+
+void AutofillInternalsUIHandler::StartSubscription() {
+ LogRouter* log_router = AutofillLogRouterFactory::GetForBrowserContext(
+ Profile::FromWebUI(web_ui()));
+
+ if (!log_router)
+ return;
+
+ registered_with_log_router_ = true;
+
+ const auto& past_logs = log_router->RegisterReceiver(this);
+ for (const auto& entry : past_logs)
+ LogEntry(entry);
+}
+
+void AutofillInternalsUIHandler::EndSubscription() {
+ if (!registered_with_log_router_)
+ return;
+ registered_with_log_router_ = false;
+ LogRouter* log_router = AutofillLogRouterFactory::GetForBrowserContext(
+ Profile::FromWebUI(web_ui()));
+ if (log_router)
+ log_router->UnregisterReceiver(this);
+}
+
+} // namespace
+
+AutofillInternalsUI::AutofillInternalsUI(content::WebUI* web_ui)
+ : WebUIController(web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+ content::WebUIDataSource::Add(profile, CreateAutofillInternalsHTMLSource());
+ web_ui->AddMessageHandler(std::make_unique<AutofillInternalsUIHandler>());
+}
+
+AutofillInternalsUI::~AutofillInternalsUI() = default;
diff --git a/chromium/chrome/browser/ui/webui/autofill_internals_ui.h b/chromium/chrome/browser/ui/webui/autofill_internals_ui.h
index 85d9095f492..3a22afcb067 100644
--- a/chromium/chrome/browser/ui/webui/autofill_internals_ui.h
+++ b/chromium/chrome/browser/ui/webui/autofill_internals_ui.h
@@ -6,20 +6,13 @@
#define CHROME_BROWSER_UI_WEBUI_AUTOFILL_INTERNALS_UI_H_
#include "base/macros.h"
-#include "chrome/browser/autofill/autofill_internals_logging_impl.h"
-#include "components/autofill/core/browser/autofill_internals_logging.h"
-#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_controller.h"
-class AutofillInternalsUI : public content::WebUIController,
- public content::WebContentsObserver {
+class AutofillInternalsUI : public content::WebUIController {
public:
explicit AutofillInternalsUI(content::WebUI* web_ui);
-
- // WebContentsObserver implementation.
- void DidStartLoading() override;
- void DidStopLoading() override;
+ ~AutofillInternalsUI() override;
private:
DISALLOW_COPY_AND_ASSIGN(AutofillInternalsUI);
diff --git a/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn
index 15a534e3b70..c50c38a1ffc 100644
--- a/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn
+++ b/chromium/chrome/browser/ui/webui/bluetooth_internals/BUILD.gn
@@ -33,4 +33,7 @@ mojom("mojo_bindings") {
deps = [
"//device/bluetooth/public/mojom:deprecated_experimental_interfaces",
]
+
+ # TODO(https://crbug.com/968369): Change to use new names.
+ use_old_js_lite_bindings_names = true
}
diff --git a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.cc b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.cc
index 62ed38cfb5b..a65ef86a115 100644
--- a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.cc
+++ b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.cc
@@ -15,7 +15,7 @@
BluetoothInternalsHandler::BluetoothInternalsHandler(
mojom::BluetoothInternalsHandlerRequest request)
- : binding_(this, std::move(request)), weak_ptr_factory_(this) {}
+ : binding_(this, std::move(request)) {}
BluetoothInternalsHandler::~BluetoothInternalsHandler() {}
diff --git a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.h b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.h
index 59cf500ef31..3de443d2c5b 100644
--- a/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.h
+++ b/chromium/chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_handler.h
@@ -26,7 +26,7 @@ class BluetoothInternalsHandler : public mojom::BluetoothInternalsHandler {
scoped_refptr<device::BluetoothAdapter> adapter);
mojo::Binding<mojom::BluetoothInternalsHandler> binding_;
- base::WeakPtrFactory<BluetoothInternalsHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<BluetoothInternalsHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(BluetoothInternalsHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc
index 9c03d9fa3fe..483ef599b63 100644
--- a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_browsertest.cc
@@ -65,7 +65,7 @@ void BookmarksBrowserTest::SetupExtensionAPITest() {
node->Set("children", std::make_unique<base::ListValue>());
list.Append(std::move(node));
profile->GetPrefs()->Set(bookmarks::prefs::kManagedBookmarks, list);
- ASSERT_EQ(2, managed->managed_node()->child_count());
+ ASSERT_EQ(2u, managed->managed_node()->children().size());
}
void BookmarksBrowserTest::SetupExtensionAPIEditDisabledTest() {
diff --git a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc
index b0900378c61..dc7678bab36 100644
--- a/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc
+++ b/chromium/chrome/browser/ui/webui/bookmarks/bookmarks_ui.cc
@@ -13,7 +13,7 @@
#include "base/strings/string16.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/bookmarks/bookmarks_message_handler.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
+#include "chrome/browser/ui/webui/favicon_source.h"
#include "chrome/browser/ui/webui/localized_string.h"
#include "chrome/browser/ui/webui/managed_ui_handler.h"
#include "chrome/browser/ui/webui/metrics_handler.h"
@@ -23,7 +23,9 @@
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/grit/theme_resources.h"
+#include "components/favicon_base/favicon_url_parser.h"
#include "components/strings/grit/components_strings.h"
+#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "ui/base/accelerators/accelerator.h"
@@ -110,9 +112,6 @@ content::WebUIDataSource* CreateBookmarksUIHTMLSource(Profile* profile) {
AddLocalizedString(source, str.name, str.id);
// Resources.
- source->AddResourcePath("images/folder_open.svg",
- IDR_BOOKMARKS_IMAGES_FOLDER_OPEN_SVG);
- source->AddResourcePath("images/folder.svg", IDR_BOOKMARKS_IMAGES_FOLDER_SVG);
#if BUILDFLAG(OPTIMIZE_WEBUI)
source->AddResourcePath("crisper.js", IDR_BOOKMARKS_CRISPER_JS);
source->SetDefaultResource(IDR_BOOKMARKS_VULCANIZED_HTML);
@@ -179,10 +178,13 @@ BookmarksUI::BookmarksUI(content::WebUI* web_ui) : WebUIController(web_ui) {
// Set up the chrome://bookmarks/ source.
Profile* profile = Profile::FromWebUI(web_ui);
auto* source = CreateBookmarksUIHTMLSource(profile);
- DarkModeHandler::Initialize(web_ui, source);
ManagedUIHandler::Initialize(web_ui, source);
content::WebUIDataSource::Add(profile, source);
+ content::URLDataSource::Add(
+ profile, std::make_unique<FaviconSource>(
+ profile, chrome::FaviconUrlFormat::kFavicon2));
+
auto plural_string_handler = std::make_unique<PluralStringHandler>();
plural_string_handler->AddLocalizedString(
"listChanged", IDS_BOOKMARK_MANAGER_FOLDER_LIST_CHANGED);
diff --git a/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc b/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc
index 55fc6f0c1fd..89a24827fde 100644
--- a/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc
+++ b/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.cc
@@ -9,6 +9,7 @@
#include "base/bind.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
+#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/browser_switcher/alternative_browser_driver.h"
#include "chrome/browser/browser_switcher/browser_switcher_service.h"
@@ -18,7 +19,6 @@
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/chromium_strings.h"
@@ -153,6 +153,8 @@ content::WebUIDataSource* CreateBrowserSwitchUIHTMLSource(
return source;
}
+} // namespace
+
class BrowserSwitchHandler : public content::WebUIMessageHandler {
public:
BrowserSwitchHandler();
@@ -160,8 +162,19 @@ class BrowserSwitchHandler : public content::WebUIMessageHandler {
// WebUIMessageHandler
void RegisterMessages() override;
+ void OnJavascriptAllowed() override;
+ void OnJavascriptDisallowed() override;
private:
+ void OnAllRulesetsParsed(browser_switcher::BrowserSwitcherService* service);
+
+ void OnBrowserSwitcherPrefsChanged(
+ browser_switcher::BrowserSwitcherPrefs* prefs,
+ const std::vector<std::string>& changed_prefs);
+
+ // For the internals page: tell JS to update all the page contents.
+ void UpdateEverything();
+
// Launches the given URL in the configured alternative browser. Acts as a
// bridge for |AlternativeBrowserDriver::TryLaunch()|. Then, if that succeeds,
// closes the current tab.
@@ -196,10 +209,42 @@ class BrowserSwitchHandler : public content::WebUIMessageHandler {
// }
void HandleGetDecision(const base::ListValue* args);
+ // Resolves a promise with the time of the last policy fetch and next policy
+ // fetch, as JS timestamps.
+ //
+ // {
+ // "last_fetch": 123456789,
+ // "next_fetch": 234567890
+ // }
+ void HandleGetTimestamps(const base::ListValue* args);
+
+ // Resolves a promise with the configured sitelist XML download URLs. The keys
+ // are the name of the pref associated with the sitelist.
+ //
+ // {
+ // "browser_switcher": {
+ // "use_ie_sitelist": "http://example.com/sitelist.xml",
+ // "external_sitelist_url": "http://example.com/other_sitelist.xml",
+ // "external_greylist_url": null
+ // }
+ // }
+ void HandleGetRulesetSources(const base::ListValue* args);
+
+ // Immediately re-download and apply XML rules.
+ void HandleRefreshXml(const base::ListValue* args);
+
+ std::unique_ptr<browser_switcher::BrowserSwitcherPrefs::CallbackSubscription>
+ prefs_subscription_;
+
+ std::unique_ptr<
+ browser_switcher::BrowserSwitcherService::CallbackSubscription>
+ service_subscription_;
+
DISALLOW_COPY_AND_ASSIGN(BrowserSwitchHandler);
};
-BrowserSwitchHandler::BrowserSwitchHandler() = default;
+BrowserSwitchHandler::BrowserSwitchHandler() {}
+
BrowserSwitchHandler::~BrowserSwitchHandler() = default;
void BrowserSwitchHandler::RegisterMessages() {
@@ -220,6 +265,47 @@ void BrowserSwitchHandler::RegisterMessages() {
"getDecision",
base::BindRepeating(&BrowserSwitchHandler::HandleGetDecision,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "getTimestamps",
+ base::BindRepeating(&BrowserSwitchHandler::HandleGetTimestamps,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "getRulesetSources",
+ base::BindRepeating(&BrowserSwitchHandler::HandleGetRulesetSources,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "refreshXml", base::BindRepeating(&BrowserSwitchHandler::HandleRefreshXml,
+ base::Unretained(this)));
+}
+
+void BrowserSwitchHandler::OnJavascriptAllowed() {
+ auto* service = GetBrowserSwitcherService(web_ui());
+ prefs_subscription_ = service->prefs().RegisterPrefsChangedCallback(
+ base::BindRepeating(&BrowserSwitchHandler::OnBrowserSwitcherPrefsChanged,
+ base::Unretained(this)));
+ service_subscription_ =
+ service->RegisterAllRulesetsParsedCallback(base::BindRepeating(
+ &BrowserSwitchHandler::OnAllRulesetsParsed, base::Unretained(this)));
+}
+
+void BrowserSwitchHandler::OnJavascriptDisallowed() {
+ prefs_subscription_.reset();
+ service_subscription_.reset();
+}
+
+void BrowserSwitchHandler::OnAllRulesetsParsed(
+ browser_switcher::BrowserSwitcherService* service) {
+ UpdateEverything();
+}
+
+void BrowserSwitchHandler::OnBrowserSwitcherPrefsChanged(
+ browser_switcher::BrowserSwitcherPrefs* prefs,
+ const std::vector<std::string>& changed_prefs) {
+ UpdateEverything();
+}
+
+void BrowserSwitchHandler::UpdateEverything() {
+ CallJavascriptFunction("updateEverything", base::Value());
}
void BrowserSwitchHandler::HandleLaunchAlternativeBrowserAndCloseTab(
@@ -335,16 +421,62 @@ void BrowserSwitchHandler::HandleGetDecision(const base::ListValue* args) {
ResolveJavascriptCallback(args->GetList()[0], retval);
}
-} // namespace
+void BrowserSwitchHandler::HandleGetTimestamps(const base::ListValue* args) {
+ DCHECK(args);
+ AllowJavascript();
+
+ auto* service = GetBrowserSwitcherService(web_ui());
+ auto* downloader = service->sitelist_downloader();
+
+ if (!downloader) {
+ ResolveJavascriptCallback(args->GetList()[0], base::Value());
+ return;
+ }
+
+ base::DictionaryValue retval;
+ retval.Set("last_fetch", std::make_unique<base::Value>(
+ downloader->last_refresh_time().ToJsTime()));
+ retval.Set("next_fetch", std::make_unique<base::Value>(
+ downloader->next_refresh_time().ToJsTime()));
+
+ ResolveJavascriptCallback(args->GetList()[0], retval);
+}
+
+void BrowserSwitchHandler::HandleGetRulesetSources(
+ const base::ListValue* args) {
+ DCHECK(args);
+ AllowJavascript();
+
+ auto* service = GetBrowserSwitcherService(web_ui());
+ std::vector<browser_switcher::RulesetSource> sources =
+ service->GetRulesetSources();
+
+ base::DictionaryValue retval;
+ for (const auto& source : sources) {
+ std::unique_ptr<base::Value> val;
+ if (source.url.is_valid())
+ val = std::make_unique<base::Value>(source.url.spec());
+ else
+ val = std::make_unique<base::Value>();
+ // |pref_name| is something like "browser_switcher.blah", so this will be in
+ // a nested object.
+ retval.Set(source.pref_name, std::move(val));
+ }
+ ResolveJavascriptCallback(args->GetList()[0], retval);
+}
+
+void BrowserSwitchHandler::HandleRefreshXml(const base::ListValue* args) {
+ DCHECK(args);
+ auto* service = GetBrowserSwitcherService(web_ui());
+ service->StartDownload(base::TimeDelta());
+}
BrowserSwitchUI::BrowserSwitchUI(content::WebUI* web_ui)
: WebUIController(web_ui) {
- content::WebUIDataSource* data_source =
- CreateBrowserSwitchUIHTMLSource(web_ui);
- DarkModeHandler::Initialize(web_ui, data_source);
web_ui->AddMessageHandler(std::make_unique<BrowserSwitchHandler>());
// Set up the chrome://browser-switch source.
Profile* profile = Profile::FromWebUI(web_ui);
- content::WebUIDataSource::Add(profile, data_source);
+ content::WebUIDataSource::Add(profile,
+ CreateBrowserSwitchUIHTMLSource(web_ui));
}
diff --git a/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.h b/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.h
index ee9dc5cffc2..b2e43b62242 100644
--- a/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.h
+++ b/chromium/chrome/browser/ui/webui/browser_switch/browser_switch_ui.h
@@ -6,6 +6,7 @@
#define CHROME_BROWSER_UI_WEBUI_BROWSER_SWITCH_BROWSER_SWITCH_UI_H_
#include "base/macros.h"
+#include "chrome/browser/browser_switcher/browser_switcher_prefs.h"
#include "content/public/browser/web_ui_controller.h"
class BrowserSwitchUI : public content::WebUIController {
diff --git a/chromium/chrome/browser/ui/webui/browsing_history_handler.cc b/chromium/chrome/browser/ui/webui/browsing_history_handler.cc
index 29eda8f33d0..389bc5d5767 100644
--- a/chromium/chrome/browser/ui/webui/browsing_history_handler.cc
+++ b/chromium/chrome/browser/ui/webui/browsing_history_handler.cc
@@ -35,6 +35,7 @@
#include "components/bookmarks/browser/bookmark_utils.h"
#include "components/favicon/core/fallback_url_util.h"
#include "components/favicon/core/large_icon_service.h"
+#include "components/favicon_base/favicon_url_parser.h"
#include "components/keyed_service/core/service_access_type.h"
#include "components/prefs/pref_service.h"
#include "components/query_parser/snippet.h"
@@ -132,11 +133,27 @@ void SetHistoryEntryUrlAndTitle(
result->SetString("title", title_to_set);
}
+// Helper function to check if entry is present in user remote data (server-side
+// history).
+bool IsEntryInRemoteUserData(
+ const BrowsingHistoryService::HistoryEntry& entry) {
+ switch (entry.entry_type) {
+ case BrowsingHistoryService::HistoryEntry::EntryType::EMPTY_ENTRY:
+ case BrowsingHistoryService::HistoryEntry::EntryType::LOCAL_ENTRY:
+ return false;
+ case BrowsingHistoryService::HistoryEntry::EntryType::REMOTE_ENTRY:
+ case BrowsingHistoryService::HistoryEntry::EntryType::COMBINED_ENTRY:
+ return true;
+ }
+ NOTREACHED();
+ return false;
+}
+
// Converts |entry| to a DictionaryValue to be owned by the caller.
std::unique_ptr<base::DictionaryValue> HistoryEntryToValue(
const BrowsingHistoryService::HistoryEntry& entry,
BookmarkModel* bookmark_model,
- SupervisedUserService* supervised_user_service,
+ Profile* profile,
const syncer::DeviceInfoTracker* tracker,
base::Clock* clock) {
std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue());
@@ -206,6 +223,11 @@ std::unique_ptr<base::DictionaryValue> HistoryEntryToValue(
result->SetString("deviceType", device_type);
#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
+ SupervisedUserService* supervised_user_service = nullptr;
+ if (profile->IsSupervised()) {
+ supervised_user_service =
+ SupervisedUserServiceFactory::GetForProfile(profile);
+ }
if (supervised_user_service) {
const SupervisedUserURLFilter* url_filter =
supervised_user_service->GetURLFilter();
@@ -222,6 +244,7 @@ std::unique_ptr<base::DictionaryValue> HistoryEntryToValue(
result->SetBoolean("starred", bookmark_model->IsBookmarked(entry.url));
result->SetInteger("hostFilteringBehavior", host_filtering_behavior);
result->SetBoolean("blockedVisit", is_blocked_visit);
+ result->SetBoolean("isUrlInRemoteUserData", IsEntryInRemoteUserData(entry));
return result;
}
@@ -244,8 +267,9 @@ void BrowsingHistoryHandler::RegisterMessages() {
this, local_history, sync_service);
// Create our favicon data source.
- content::URLDataSource::Add(profile,
- std::make_unique<FaviconSource>(profile));
+ content::URLDataSource::Add(
+ profile, std::make_unique<FaviconSource>(
+ profile, chrome::FaviconUrlFormat::kFavicon2));
web_ui()->RegisterMessageCallback(
"queryHistory",
@@ -356,12 +380,6 @@ void BrowsingHistoryHandler::OnQueryComplete(
Profile* profile = Profile::FromWebUI(web_ui());
BookmarkModel* bookmark_model =
BookmarkModelFactory::GetForBrowserContext(profile);
- SupervisedUserService* supervised_user_service = NULL;
-#if defined(ENABLE_SUPERVISED_USERS)
- if (profile->IsSupervised())
- supervised_user_service =
- SupervisedUserServiceFactory::GetForProfile(profile);
-#endif
const syncer::DeviceInfoTracker* tracker =
DeviceInfoSyncServiceFactory::GetForProfile(profile)
@@ -371,8 +389,8 @@ void BrowsingHistoryHandler::OnQueryComplete(
DCHECK(tracker);
base::ListValue results_value;
for (const BrowsingHistoryService::HistoryEntry& entry : results) {
- std::unique_ptr<base::Value> value(HistoryEntryToValue(
- entry, bookmark_model, supervised_user_service, tracker, clock_));
+ std::unique_ptr<base::Value> value(
+ HistoryEntryToValue(entry, bookmark_model, profile, tracker, clock_));
results_value.Append(std::move(value));
}
diff --git a/chromium/chrome/browser/ui/webui/certificates_handler.cc b/chromium/chrome/browser/ui/webui/certificates_handler.cc
index 799279d73fa..78dd1df58d1 100644
--- a/chromium/chrome/browser/ui/webui/certificates_handler.cc
+++ b/chromium/chrome/browser/ui/webui/certificates_handler.cc
@@ -56,7 +56,7 @@ static const char kCertificatesHandlerNameField[] = "name";
static const char kCertificatesHandlerObjSignField[] = "objSign";
static const char kCertificatesHandlerPolicyInstalledField[] = "policy";
static const char kCertificatesHandlerWebTrustAnchorField[] = "webTrustAnchor";
-static const char kCertificatesHandlerReadonlyField[] = "readonly";
+static const char kCertificatesHandlerCanBeDeletedField[] = "canBeDeleted";
static const char kCertificatesHandlerSslField[] = "ssl";
static const char kCertificatesHandlerSubnodesField[] = "subnodes";
static const char kCertificatesHandlerContainsPolicyCertsField[] =
@@ -80,7 +80,7 @@ enum {
#if defined(OS_CHROMEOS)
// Enumeration of certificate management permissions which corresponds to
-// values of policy CertificateManagementAllowed.
+// values of policy ClientCertificateManagementAllowed.
enum class CertificateManagementPermission : int {
// Allow users to manage all certificates
kAll = 0,
@@ -287,8 +287,7 @@ void FileAccessProvider::DoWrite(const base::FilePath& path,
CertificatesHandler::CertificatesHandler()
: requested_certificate_manager_model_(false),
use_hardware_backed_(false),
- file_access_provider_(base::MakeRefCounted<FileAccessProvider>()),
- weak_ptr_factory_(this) {}
+ file_access_provider_(base::MakeRefCounted<FileAccessProvider>()) {}
CertificatesHandler::~CertificatesHandler() {}
@@ -577,7 +576,7 @@ void CertificatesHandler::HandleImportPersonal(const base::ListValue* args) {
CHECK(args->GetBoolean(1, &use_hardware_backed_));
#if defined(OS_CHROMEOS)
- CHECK(IsCertificateManagementAllowedPolicy(Slot::kUser))
+ CHECK(IsClientCertificateManagementAllowedPolicy(Slot::kUser))
<< "Importing certificates not allowed by policy";
#endif
@@ -742,7 +741,7 @@ void CertificatesHandler::HandleImportServer(const base::ListValue* args) {
AssignWebUICallbackId(args);
#if defined(OS_CHROMEOS)
- CHECK(IsCertificateManagementAllowedPolicy(Slot::kUser))
+ CHECK(IsClientCertificateManagementAllowedPolicy(Slot::kUser))
<< "Importing certificates not allowed by policy";
#endif
@@ -813,11 +812,6 @@ void CertificatesHandler::HandleImportCA(const base::ListValue* args) {
CHECK_EQ(1U, args->GetSize());
AssignWebUICallbackId(args);
-#if defined(OS_CHROMEOS)
- CHECK(IsCertificateManagementAllowedPolicy(Slot::kUser))
- << "Importing certificates not allowed by policy";
-#endif
-
select_file_dialog_ = ui::SelectFileDialog::Create(
this,
std::make_unique<ChromeSelectFilePolicy>(web_ui()->GetWebContents()));
@@ -950,12 +944,14 @@ void CertificatesHandler::OnCertificateManagerModelCreated(
}
void CertificatesHandler::CertificateManagerModelReady() {
- bool import_allowed = true;
+ bool client_import_allowed = true;
#if defined(OS_CHROMEOS)
- import_allowed = IsCertificateManagementAllowedPolicy(Slot::kUser);
+ client_import_allowed =
+ IsClientCertificateManagementAllowedPolicy(Slot::kUser);
#endif
if (IsJavascriptAllowed()) {
- FireWebUIListener("certificates-model-ready", base::Value(import_allowed));
+ FireWebUIListener("certificates-model-ready",
+ base::Value(client_import_allowed));
}
certificate_manager_model_->Refresh();
}
@@ -1021,8 +1017,8 @@ void CertificatesHandler::PopulateTree(const std::string& tab_name,
cert_dict.SetKey(kCertificatesHandlerKeyField, base::Value(id));
cert_dict.SetKey(kCertificatesHandlerNameField,
base::Value(cert_info->name()));
- cert_dict.SetKey(kCertificatesHandlerReadonlyField,
- base::Value(IsCertificateReadOnly(cert_info)));
+ cert_dict.SetKey(kCertificatesHandlerCanBeDeletedField,
+ base::Value(CanDeleteCertificate(cert_info)));
cert_dict.SetKey(kCertificatesHandlerUntrustedField,
base::Value(cert_info->untrusted()));
cert_dict.SetKey(
@@ -1136,12 +1132,12 @@ CertificatesHandler::GetCertInfoFromCallbackArgs(const base::Value& args,
}
#if defined(OS_CHROMEOS)
-bool CertificatesHandler::IsCertificateManagementAllowedPolicy(
+bool CertificatesHandler::IsClientCertificateManagementAllowedPolicy(
Slot slot) const {
Profile* profile = Profile::FromWebUI(web_ui());
PrefService* prefs = profile->GetPrefs();
auto policy_value = static_cast<CertificateManagementPermission>(
- prefs->GetInteger(prefs::kCertificateManagementAllowed));
+ prefs->GetInteger(prefs::kClientCertificateManagementAllowed));
if (slot == Slot::kUser) {
return policy_value != CertificateManagementPermission::kNone;
@@ -1150,17 +1146,20 @@ bool CertificatesHandler::IsCertificateManagementAllowedPolicy(
}
#endif // defined(OS_CHROMEOS)
-bool CertificatesHandler::IsCertificateReadOnly(
+bool CertificatesHandler::CanDeleteCertificate(
const CertificateManagerModel::CertInfo* cert_info) {
- if (cert_info->read_only()) {
- return true;
+ if (!cert_info->can_be_deleted() ||
+ cert_info->source() ==
+ CertificateManagerModel::CertInfo::Source::kPolicy) {
+ return false;
}
#if defined(OS_CHROMEOS)
- return !IsCertificateManagementAllowedPolicy(
- cert_info->device_wide() ? Slot::kSystem : Slot::kUser);
+ return cert_info->type() == net::CertType::USER_CERT &&
+ IsClientCertificateManagementAllowedPolicy(
+ cert_info->device_wide() ? Slot::kSystem : Slot::kUser);
#else
- return false;
+ return true;
#endif
}
@@ -1170,7 +1169,7 @@ void CertificatesHandler::RegisterProfilePrefs(
// Allow users to manage all certificates by default. This can be overridden
// by enterprise policy.
registry->RegisterIntegerPref(
- prefs::kCertificateManagementAllowed,
+ prefs::kClientCertificateManagementAllowed,
static_cast<int>(CertificateManagementPermission::kAll));
}
#endif // defined(OS_CHROMEOS)
diff --git a/chromium/chrome/browser/ui/webui/certificates_handler.h b/chromium/chrome/browser/ui/webui/certificates_handler.h
index 50df1075a72..76ff163b1e7 100644
--- a/chromium/chrome/browser/ui/webui/certificates_handler.h
+++ b/chromium/chrome/browser/ui/webui/certificates_handler.h
@@ -178,15 +178,14 @@ class CertificatesHandler : public content::WebUIMessageHandler,
#if defined(OS_CHROMEOS)
// Returns true if the user may manage certificates on |slot| according
- // CertificateManagementAllowed to policy.
- bool IsCertificateManagementAllowedPolicy(Slot slot) const;
+ // ClientCertificateManagementAllowed to policy.
+ bool IsClientCertificateManagementAllowedPolicy(Slot slot) const;
#endif
- // Returns true if the certificate represented by |cert_info| is read-only
- // (i.e. can not be deleted). Evaluates the certificate attributes and, on
- // Chrome OS devices, the enterprise policy CertificateManagementAllowed.
- bool IsCertificateReadOnly(
- const CertificateManagerModel::CertInfo* cert_info);
+ // Returns true if the certificate represented by |cert_info| can be deleted.
+ // Evaluates the certificate attributes and, on Chrome OS devices, the
+ // enterprise policy ClientCertificateManagementAllowed.
+ bool CanDeleteCertificate(const CertificateManagerModel::CertInfo* cert_info);
// The Certificates Manager model
bool requested_certificate_manager_model_;
@@ -213,7 +212,7 @@ class CertificatesHandler : public content::WebUIMessageHandler,
base::IDMap<std::unique_ptr<CertificateManagerModel::CertInfo>>
cert_info_id_map_;
- base::WeakPtrFactory<CertificatesHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<CertificatesHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(CertificatesHandler);
};
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 dab98c74480..8f6d49bfdb3 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
@@ -26,7 +26,8 @@
#include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h"
#include "chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h"
#include "chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h"
-#include "chrome/browser/ui/webui/chromeos/insession_password_change_ui.h"
+#include "chrome/browser/ui/webui/chromeos/camera/camera_ui.h"
+#include "chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h"
#include "chrome/browser/ui/webui/components_ui.h"
#include "chrome/browser/ui/webui/constrained_web_dialog_ui.h"
#include "chrome/browser/ui/webui/crashes_ui.h"
@@ -36,7 +37,6 @@
#include "chrome/browser/ui/webui/engagement/site_engagement_ui.h"
#include "chrome/browser/ui/webui/flags_ui.h"
#include "chrome/browser/ui/webui/gcm_internals_ui.h"
-#include "chrome/browser/ui/webui/hats/hats_ui.h"
#include "chrome/browser/ui/webui/identity_internals_ui.h"
#include "chrome/browser/ui/webui/interstitials/interstitial_ui.h"
#include "chrome/browser/ui/webui/interventions_internals/interventions_internals_ui.h"
@@ -48,6 +48,7 @@
#include "chrome/browser/ui/webui/memory_internals_ui.h"
#include "chrome/browser/ui/webui/net_export_ui.h"
#include "chrome/browser/ui/webui/net_internals/net_internals_ui.h"
+#include "chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.h"
#include "chrome/browser/ui/webui/ntp_tiles_internals_ui.h"
#include "chrome/browser/ui/webui/omnibox/omnibox_ui.h"
#include "chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h"
@@ -57,7 +58,6 @@
#include "chrome/browser/ui/webui/settings/settings_ui.h"
#include "chrome/browser/ui/webui/settings_utils.h"
#include "chrome/browser/ui/webui/signin_internals_ui.h"
-#include "chrome/browser/ui/webui/supervised_user_internals_ui.h"
#include "chrome/browser/ui/webui/sync_internals_ui.h"
#include "chrome/browser/ui/webui/translate_internals/translate_internals_ui.h"
#include "chrome/browser/ui/webui/ukm/ukm_internals_ui.h"
@@ -85,8 +85,6 @@
#include "components/safe_browsing/web_ui/safe_browsing_ui.h"
#include "components/security_interstitials/content/connection_help_ui.h"
#include "components/security_interstitials/content/urls.h"
-#include "components/signin/core/browser/account_consistency_method.h"
-#include "components/signin/core/browser/signin_buildflags.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/common/content_client.h"
@@ -113,7 +111,6 @@
#include "chrome/browser/ui/webui/app_management/app_management_ui.h"
#include "chrome/browser/ui/webui/management_ui.h"
#include "chrome/browser/ui/webui/media_router/media_router_internals_ui.h"
-#include "chrome/browser/ui/webui/media_router/media_router_ui.h"
#endif
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
#include "chrome/browser/ui/webui/cast/cast_ui.h"
@@ -171,6 +168,7 @@
#include "chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.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/chromeos/terminal/terminal_ui.h"
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h"
#include "chrome/browser/ui/webui/signin/inline_login_ui.h"
#include "chromeos/components/multidevice/debug_webui/proximity_auth_ui.h"
@@ -196,13 +194,13 @@
#include "chrome/browser/ui/webui/signin/signin_error_ui.h"
#include "chrome/browser/ui/webui/signin/sync_confirmation_ui.h"
#include "chrome/browser/ui/webui/signin/user_manager_ui.h"
+#include "chrome/browser/ui/webui/welcome/nux_helper.h"
#include "chrome/browser/ui/webui/welcome/welcome_ui.h"
#endif
#if defined(OS_WIN)
#include "chrome/browser/ui/webui/conflicts/conflicts_ui.h"
#include "chrome/browser/ui/webui/set_as_default_browser_ui_win.h"
-#include "chrome/browser/ui/webui/welcome/welcome_win10_ui.h"
#endif
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
@@ -237,6 +235,10 @@
#include "chrome/browser/ui/webui/reset_password/reset_password_ui.h"
#endif
+#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
+#include "chrome/browser/ui/webui/supervised_user_internals_ui.h"
+#endif
+
using content::WebUI;
using content::WebUIController;
using ui::WebDialogUI;
@@ -312,13 +314,6 @@ WebUIController* NewWebUI<WelcomeUI>(WebUI* web_ui, const GURL& url) {
}
#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
-#if defined(OS_WIN)
-template <>
-WebUIController* NewWebUI<WelcomeWin10UI>(WebUI* web_ui, const GURL& url) {
- return new WelcomeWin10UI(web_ui, url);
-}
-#endif // defined(OS_WIN)
-
bool IsAboutUI(const GURL& url) {
return (url.host_piece() == chrome::kChromeUIChromeURLsHost ||
url.host_piece() == chrome::kChromeUICreditsHost
@@ -393,6 +388,8 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
return &NewWebUI<NetExportUI>;
if (url.host_piece() == chrome::kChromeUINetInternalsHost)
return &NewWebUI<NetInternalsUI>;
+ if (url.host_piece() == chrome::kChromeUINotificationsInternalsHost)
+ return &NewWebUI<NotificationsInternalsUI>;
if (url.host_piece() == chrome::kChromeUINTPTilesInternalsHost)
return &NewWebUI<NTPTilesInternalsUI>;
if (url.host_piece() == chrome::kChromeUIOmniboxHost)
@@ -409,14 +406,10 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
return &NewWebUI<SignInInternalsUI>;
if (url.host_piece() == chrome::kChromeUISuggestionsHost)
return &NewWebUI<suggestions::SuggestionsUI>;
- if (url.host_piece() == chrome::kChromeUISupervisedUserInternalsHost)
- return &NewWebUI<SupervisedUserInternalsUI>;
if (url.host_piece() == chrome::kChromeUISupervisedUserPassphrasePageHost)
return &NewWebUI<ConstrainedWebDialogUI>;
if (url.host_piece() == chrome::kChromeUISyncInternalsHost)
return &NewWebUI<SyncInternalsUI>;
- if (url.host_piece() == chrome::kChromeUISyncResourcesHost)
- return &NewWebUI<WebDialogUI>;
if (url.host_piece() == chrome::kChromeUITranslateInternalsHost)
return &NewWebUI<TranslateInternalsUI>;
if (url.host_piece() == chrome::kChromeUIUkmHost)
@@ -446,12 +439,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
return &NewWebUI<AppLauncherPageUI>;
}
#endif // !defined(OS_CHROMEOS)
- // HaTS for Desktop is distinct from the Android implementation of HaTS
- if (url.host_piece() == chrome::kChromeUIHatsHost &&
- base::FeatureList::IsEnabled(
- features::kHappinessTrackingSurveysForDesktop)) {
- return &NewWebUI<HatsUI>;
- }
if (profile->IsGuestSession() &&
(url.host_piece() == chrome::kChromeUIAppLauncherPageHost ||
url.host_piece() == chrome::kChromeUIAppManagementHost ||
@@ -498,13 +485,28 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
prefs::kSamlInSessionPasswordChangeEnabled)) {
return nullptr;
}
- return &NewWebUI<chromeos::InSessionPasswordChangeUI>;
+ return &NewWebUI<chromeos::PasswordChangeUI>;
+ }
+ if (url.host_piece() == chrome::kChromeUIConfirmPasswordChangeHost) {
+ if (!profile->GetPrefs()->GetBoolean(
+ prefs::kSamlInSessionPasswordChangeEnabled)) {
+ return nullptr;
+ }
+ return &NewWebUI<chromeos::ConfirmPasswordChangeUI>;
+ }
+ if (url.host_piece() ==
+ chrome::kChromeUIUrgentPasswordExpiryNotificationHost) {
+ if (!profile->GetPrefs()->GetBoolean(
+ prefs::kSamlInSessionPasswordChangeEnabled)) {
+ return nullptr;
+ }
+ return &NewWebUI<chromeos::UrgentPasswordExpiryNotificationUI>;
}
if (url.host_piece() == chrome::kChromeUIAccountManagerWelcomeHost)
return &NewWebUI<chromeos::AccountManagerWelcomeUI>;
if (url.host_piece() == chrome::kChromeUIAccountMigrationWelcomeHost)
return &NewWebUI<chromeos::AccountMigrationWelcomeUI>;
- if (chromeos::switches::IsAddSupervisionEnabled()) {
+ if (chromeos::switches::IsParentalControlsSettingsEnabled()) {
if (url.host_piece() == chrome::kChromeUIAddSupervisionHost)
return &NewWebUI<chromeos::AddSupervisionUI>;
}
@@ -552,8 +554,17 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
return &NewWebUI<chromeos::smb_dialog::SmbShareDialogUI>;
if (url.host_piece() == chrome::kChromeUISysInternalsHost)
return &NewWebUI<SysInternalsUI>;
+ if (url.host_piece() == chrome::kChromeUITerminalHost) {
+ if (!base::FeatureList::IsEnabled(features::kTerminalSystemApp))
+ return nullptr;
+ return &NewWebUI<TerminalUI>;
+ }
if (url.host_piece() == chrome::kChromeUIAssistantOptInHost)
return &NewWebUI<chromeos::AssistantOptInUI>;
+ if (url.host_piece() == chrome::kChromeUICameraHost &&
+ chromeos::CameraUI::IsEnabled()) {
+ return &NewWebUI<chromeos::CameraUI>;
+ }
if (url.host_piece() == chrome::kChromeUIArcGraphicsTracingHost) {
if (!base::FeatureList::IsEnabled(arc::kGraphicBuffersVisualizationTool))
@@ -612,13 +623,10 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
if (url.host_piece() == chrome::kChromeUISigninEmailConfirmationHost &&
!profile->IsOffTheRecord())
return &NewWebUI<SigninEmailConfirmationUI>;
- if (url.host_piece() == chrome::kChromeUIWelcomeHost)
+ if (url.host_piece() == chrome::kChromeUIWelcomeHost &&
+ nux::IsNuxOnboardingEnabled(profile))
return &NewWebUI<WelcomeUI>;
#endif
-#if defined(OS_WIN)
- if (url.host_piece() == chrome::kChromeUIWelcomeWin10Host)
- return &NewWebUI<WelcomeWin10UI>;
-#endif // defined(OS_WIN)
/****************************************************************************
* Other #defines and special logics.
@@ -657,10 +665,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
if (url.host_piece() == chrome::kChromeUIWebRtcLogsHost)
return &NewWebUI<WebRtcLogsUI>;
#if !defined(OS_ANDROID)
- if (url.host_piece() == chrome::kChromeUIMediaRouterHost &&
- media_router::MediaRouterEnabled(profile)) {
- return &NewWebUI<media_router::MediaRouterUI>;
- }
if (url.host_piece() == chrome::kChromeUIMediaRouterInternalsHost &&
media_router::MediaRouterEnabled(profile)) {
return &NewWebUI<media_router::MediaRouterInternalsUI>;
@@ -715,32 +719,39 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
}
#endif
+#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
+ if (url.host_piece() == chrome::kChromeUISupervisedUserInternalsHost)
+ return &NewWebUI<SupervisedUserInternalsUI>;
+#endif
+
return NULL;
}
} // namespace
WebUI::TypeID ChromeWebUIControllerFactory::GetWebUIType(
- content::BrowserContext* browser_context, const GURL& url) const {
+ content::BrowserContext* browser_context,
+ const GURL& url) {
Profile* profile = Profile::FromBrowserContext(browser_context);
WebUIFactoryFunction function = GetWebUIFactoryFunction(NULL, profile, url);
return function ? reinterpret_cast<WebUI::TypeID>(function) : WebUI::kNoWebUI;
}
bool ChromeWebUIControllerFactory::UseWebUIForURL(
- content::BrowserContext* browser_context, const GURL& url) const {
+ content::BrowserContext* browser_context,
+ const GURL& url) {
return GetWebUIType(browser_context, url) != WebUI::kNoWebUI;
}
bool ChromeWebUIControllerFactory::UseWebUIBindingsForURL(
- content::BrowserContext* browser_context, const GURL& url) const {
+ content::BrowserContext* browser_context,
+ const GURL& url) {
return UseWebUIForURL(browser_context, url);
}
std::unique_ptr<WebUIController>
-ChromeWebUIControllerFactory::CreateWebUIControllerForURL(
- WebUI* web_ui,
- const GURL& url) const {
+ChromeWebUIControllerFactory::CreateWebUIControllerForURL(WebUI* web_ui,
+ const GURL& url) {
Profile* profile = Profile::FromWebUI(web_ui);
WebUIFactoryFunction function = GetWebUIFactoryFunction(web_ui, profile, url);
if (!function)
diff --git a/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h b/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h
index acf59898cc6..92245af05e9 100644
--- a/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h
+++ b/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.h
@@ -38,14 +38,14 @@ class ChromeWebUIControllerFactory : public content::WebUIControllerFactory {
// content::WebUIControllerFactory:
content::WebUI::TypeID GetWebUIType(content::BrowserContext* browser_context,
- const GURL& url) const override;
+ const GURL& url) override;
bool UseWebUIForURL(content::BrowserContext* browser_context,
- const GURL& url) const override;
+ const GURL& url) override;
bool UseWebUIBindingsForURL(content::BrowserContext* browser_context,
- const GURL& url) const override;
+ const GURL& url) override;
std::unique_ptr<content::WebUIController> CreateWebUIControllerForURL(
content::WebUI* web_ui,
- const GURL& url) const override;
+ const GURL& url) override;
// Get the favicon for |page_url| and run |callback| with result when loaded.
// Note. |callback| is always run asynchronously.
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc
index 4dcc6ff6af3..d678bfe3343 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc
@@ -14,6 +14,7 @@
#include "chrome/common/webui_url_constants.h"
#include "components/prefs/pref_service.h"
#include "ui/aura/window.h"
+#include "ui/views/widget/widget.h"
#include "ui/wm/core/shadow_types.h"
#include "url/gurl.h"
@@ -60,12 +61,12 @@ bool AccountManagerWelcomeDialog::ShowIfRequired() {
// Will be deleted by |SystemWebDialogDelegate::OnDialogClosed|.
g_dialog = new AccountManagerWelcomeDialog();
g_dialog->ShowSystemDialog();
-
return true;
}
void AccountManagerWelcomeDialog::AdjustWidgetInitParams(
views::Widget::InitParams* params) {
+ params->z_order = ui::ZOrderLevel::kNormal;
params->type = views::Widget::InitParams::Type::TYPE_WINDOW_FRAMELESS;
params->shadow_type = views::Widget::InitParams::ShadowType::SHADOW_TYPE_DROP;
params->shadow_elevation = wm::kShadowElevationActiveWindow;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc
index a165ac64597..33407733834 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc
@@ -17,6 +17,7 @@
#include "components/prefs/pref_service.h"
#include "net/base/url_util.h"
#include "ui/aura/window.h"
+#include "ui/views/widget/widget.h"
#include "ui/wm/core/shadow_types.h"
namespace chromeos {
@@ -62,6 +63,7 @@ AccountMigrationWelcomeDialog* AccountMigrationWelcomeDialog::Show(
void AccountMigrationWelcomeDialog::AdjustWidgetInitParams(
views::Widget::InitParams* params) {
+ params->z_order = ui::ZOrderLevel::kNormal;
params->type = views::Widget::InitParams::Type::TYPE_WINDOW_FRAMELESS;
params->shadow_type = views::Widget::InitParams::ShadowType::SHADOW_TYPE_DROP;
params->shadow_elevation = wm::kShadowElevationActiveWindow;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc
index f8925d695f0..78f338045ea 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc
@@ -78,6 +78,8 @@ AccountMigrationWelcomeUI::AccountMigrationWelcomeUI(content::WebUI* web_ui)
html_source->SetJsonPath("strings.js");
// Add localized strings.
+ html_source->AddLocalizedString("welcomePageTitle",
+ IDS_ACCOUNT_MIGRATION_WELCOME_PAGE_TITLE);
html_source->AddLocalizedString("welcomeTitle",
IDS_ACCOUNT_MIGRATION_WELCOME_TITLE);
html_source->AddLocalizedString("welcomeMessage",
diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn
index 54b63f6b00a..2829e6d376d 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn
+++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/BUILD.gn
@@ -8,4 +8,7 @@ mojom("mojo_bindings") {
sources = [
"add_supervision.mojom",
]
+
+ # TODO(https://crbug.com/968369): Change to use new names.
+ use_old_js_lite_bindings_names = true
}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision.mojom b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision.mojom
index 7d50324583c..c46353f4823 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision.mojom
+++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision.mojom
@@ -12,12 +12,20 @@ enum OAuthTokenFetchStatus {
// Interface that supports integration between the AddSupervision WebUI and
// ChromeOS.
interface AddSupervisionHandler {
- // Triggers a logout from the current login session.
- LogOut() => ();
+ // Attempts to close the AddSupervision WebUI. Returns a bool indicating
+ // whether the WebUI was closed.
+ RequestClose() => (bool closed);
// Returns an array of package names of installed ARC apps.
GetInstalledArcApps() => (array<string> package_names);
// Returns the oauth token to be passed to the server.
GetOAuthToken() => (OAuthTokenFetchStatus status, string oauth_token);
+
+ // Triggers a logout from the current login session.
+ LogOut();
+
+ // Indicates to the system that Supervision has been enabled for the primary
+ // user.
+ NotifySupervisionEnabled();
};
diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc
index 2bf9775a908..0acab1a5249 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc
@@ -9,31 +9,39 @@
#include <vector>
#include "base/stl_util.h"
+#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
+#include "chrome/browser/supervised_user/supervised_user_service.h"
+#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
#include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h"
#include "chrome/services/app_service/public/cpp/app_registry_cache.h"
-#include "chrome/services/app_service/public/cpp/app_service_proxy.h"
+#include "components/signin/public/identity_manager/access_token_fetcher.h"
+#include "components/signin/public/identity_manager/access_token_info.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/web_ui.h"
#include "google_apis/gaia/gaia_constants.h"
-#include "services/identity/public/cpp/access_token_fetcher.h"
-#include "services/identity/public/cpp/identity_manager.h"
+
+namespace chromeos {
AddSupervisionHandler::AddSupervisionHandler(
add_supervision::mojom::AddSupervisionHandlerRequest request,
- content::WebUI* web_ui)
- : binding_(this, std::move(request)),
- web_ui_(web_ui),
+ content::WebUI* web_ui,
+ Delegate* delegate)
+ : web_ui_(web_ui),
identity_manager_(
- IdentityManagerFactory::GetForProfile(Profile::FromWebUI(web_ui))) {}
+ IdentityManagerFactory::GetForProfile(Profile::FromWebUI(web_ui))),
+ binding_(this, std::move(request)),
+ delegate_(delegate) {}
AddSupervisionHandler::~AddSupervisionHandler() = default;
-void AddSupervisionHandler::LogOut(LogOutCallback callback) {
- chrome::AttemptUserExit();
+void AddSupervisionHandler::RequestClose(RequestCloseCallback callback) {
+ bool dialog_closed = delegate_->CloseDialog();
+ std::move(callback).Run(dialog_closed);
}
void AddSupervisionHandler::GetInstalledArcApps(
@@ -64,20 +72,33 @@ void AddSupervisionHandler::GetInstalledArcApps(
void AddSupervisionHandler::GetOAuthToken(GetOAuthTokenCallback callback) {
identity::ScopeSet scopes;
- scopes.insert(GaiaConstants::kKidFamilyOAuth2Scope);
+ scopes.insert(GaiaConstants::kKidsSupervisionSetupChildOAuth2Scope);
+ scopes.insert(GaiaConstants::kPeopleApiReadOnlyOAuth2Scope);
+ scopes.insert(GaiaConstants::kAccountsReauthOAuth2Scope);
oauth2_access_token_fetcher_ =
identity_manager_->CreateAccessTokenFetcherForAccount(
identity_manager_->GetPrimaryAccountId(), "add_supervision", scopes,
base::BindOnce(&AddSupervisionHandler::OnAccessTokenFetchComplete,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)),
- identity::AccessTokenFetcher::Mode::kImmediate);
+ signin::AccessTokenFetcher::Mode::kImmediate);
+}
+
+void AddSupervisionHandler::LogOut() {
+ chrome::AttemptUserExit();
+}
+
+void AddSupervisionHandler::NotifySupervisionEnabled() {
+ SupervisedUserService* service =
+ SupervisedUserServiceFactory::GetForProfile(Profile::FromWebUI(web_ui_));
+
+ service->set_signout_required_after_supervision_enabled();
}
void AddSupervisionHandler::OnAccessTokenFetchComplete(
GetOAuthTokenCallback callback,
GoogleServiceAuthError error,
- identity::AccessTokenInfo access_token_info) {
+ signin::AccessTokenInfo access_token_info) {
oauth2_access_token_fetcher_.reset();
if (error.state() != GoogleServiceAuthError::NONE) {
DLOG(ERROR) << "AddSupervisionHandler: OAuth2 token request failed. "
@@ -91,3 +112,5 @@ void AddSupervisionHandler::OnAccessTokenFetchComplete(
access_token_info.token);
}
}
+
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h
index d07c2886152..63db8d65ecd 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h
@@ -15,44 +15,63 @@ namespace content {
class WebUI;
} // namespace content
-namespace identity {
+namespace signin {
class AccessTokenFetcher;
struct AccessTokenInfo;
class IdentityManager;
-} // namespace identity
+} // namespace signin
class GoogleServiceAuthError;
+namespace chromeos {
+
class AddSupervisionHandler
: public add_supervision::mojom::AddSupervisionHandler {
public:
+ // Interface for Delegates for specific behavior of AddSupervisionHandler.
+ class Delegate {
+ public:
+ // Implementing methods should override this to implement
+ // the request to close the Add Supervision dialog and return
+ // a boolean to indicate whether the dialog is closing.
+ virtual bool CloseDialog() = 0;
+ };
+
+ // |delegate| is owned by the caller and its lifetime must outlive |this|.
AddSupervisionHandler(
add_supervision::mojom::AddSupervisionHandlerRequest request,
- content::WebUI* web_ui);
+ content::WebUI* web_ui,
+ Delegate* delegate);
~AddSupervisionHandler() override;
// add_supervision::mojom::AddSupervisionHandler overrides:
- void LogOut(LogOutCallback callback) override;
+ void RequestClose(RequestCloseCallback callback) override;
void GetInstalledArcApps(GetInstalledArcAppsCallback callback) override;
void GetOAuthToken(GetOAuthTokenCallback callback) override;
+ void LogOut() override;
+ void NotifySupervisionEnabled() override;
private:
void OnAccessTokenFetchComplete(GetOAuthTokenCallback callback,
GoogleServiceAuthError error,
- identity::AccessTokenInfo access_token_info);
-
- mojo::Binding<add_supervision::mojom::AddSupervisionHandler> binding_;
+ signin::AccessTokenInfo access_token_info);
// The AddSupervisionUI that this AddSupervisionHandler belongs to.
content::WebUI* web_ui_;
// Used to fetch OAuth2 access tokens.
- identity::IdentityManager* identity_manager_;
- std::unique_ptr<identity::AccessTokenFetcher> oauth2_access_token_fetcher_;
+ signin::IdentityManager* identity_manager_;
+ std::unique_ptr<signin::AccessTokenFetcher> oauth2_access_token_fetcher_;
+
+ mojo::Binding<add_supervision::mojom::AddSupervisionHandler> binding_;
+
+ Delegate* delegate_;
base::WeakPtrFactory<AddSupervisionHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(AddSupervisionHandler);
};
+} // namespace chromeos
+
#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_ADD_SUPERVISION_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc
index bcabd382cea..b0dcfb1cfef 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.cc
@@ -8,22 +8,143 @@
#include <utility>
#include "base/bind.h"
+#include "base/no_destructor.h"
+#include "base/system/sys_info.h"
+#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h"
+#include "chrome/browser/profiles/profile_manager.h"
+#include "chrome/browser/supervised_user/supervised_user_service.h"
+#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
+#include "chrome/browser/ui/views/chrome_web_dialog_view.h"
+#include "chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/generated_resources.h"
+#include "components/google/core/common/google_util.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/resources/grit/ui_resources.h"
+#include "ui/web_dialogs/web_dialog_delegate.h"
namespace chromeos {
-const char kAddSupervisionURL[] =
- "https://families.google.com/supervision/chrome";
-const char kAddSupervisionEventOriginFilter[] = "https://families.google.com";
+namespace {
+
+constexpr int kDialogHeightPx = 608;
+constexpr int kDialogWidthPx = 768;
+// Id of System Dialog used to show the Add Supervision flow.
+std::string& GetDialogId() {
+ static base::NoDestructor<std::string> dialog_id;
+ return *dialog_id;
+}
+
+// Shows the dialog indicating that user has to sign out if supervision has been
+// enabled for their account. Returns a boolean indicating whether the
+// ConfirmSignoutDialog is being shown.
+bool MaybeShowConfirmSignoutDialog() {
+ SupervisedUserService* service = SupervisedUserServiceFactory::GetForProfile(
+ ProfileManager::GetPrimaryUserProfile());
+ if (service->signout_required_after_supervision_enabled()) {
+ ConfirmSignoutDialog::Show();
+ return true;
+ }
+ return false;
+}
+
+const char kAddSupervisionDefaultURL[] =
+ "https://families.google.com/supervision/setup";
+const char kAddSupervisionFlowType[] = "1";
+const char kAddSupervisionSwitch[] = "add-supervision-url";
+
+// Returns the URL of the Add Supervision flow from the command-line switch,
+// or the default value if it's not defined.
+GURL GetAddSupervisionURL() {
+ std::string url;
+ base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
+ if (command_line->HasSwitch(kAddSupervisionSwitch)) {
+ url = command_line->GetSwitchValueASCII(kAddSupervisionSwitch);
+ } else {
+ url = kAddSupervisionDefaultURL;
+ }
+ const GURL result(url);
+ DCHECK(result.is_valid()) << "Invalid URL \"" << url << "\" for switch \""
+ << kAddSupervisionSwitch << "\"";
+ return result;
+}
+
+} // namespace
+
+// AddSupervisionDialog implementations.
+
+// static
+void AddSupervisionDialog::Show(gfx::NativeView parent) {
+ // Get the system singleton instance of the AddSupervisionDialog.
+ SystemWebDialogDelegate* current_instance = GetInstance();
+ if (current_instance) {
+ // Focus the dialog if it is already there. Currently, this is
+ // effectively a no-op, since the dialog is system-modal, but
+ // it's here nonethless so that if the dialog becomes non-modal
+ // at some point, the correct focus behavior occurs.
+ current_instance->Focus();
+ return;
+ }
+ // Note: |current_instance|'s memory is freed when
+ // SystemWebDialogDelegate::OnDialogClosed() is called.
+ current_instance = new AddSupervisionDialog();
+
+ GetDialogId() = current_instance->Id();
+
+ current_instance->ShowSystemDialogForBrowserContext(
+ ProfileManager::GetPrimaryUserProfile(), parent);
+}
+
+// static
+void AddSupervisionDialog::Close() {
+ SystemWebDialogDelegate* current_instance = GetInstance();
+ if (current_instance) {
+ current_instance->Close();
+ GetDialogId() = std::string();
+ }
+}
+
+ui::ModalType AddSupervisionDialog::GetDialogModalType() const {
+ return ui::ModalType::MODAL_TYPE_WINDOW;
+}
+
+void AddSupervisionDialog::GetDialogSize(gfx::Size* size) const {
+ size->SetSize(kDialogWidthPx, kDialogHeightPx);
+}
+
+bool AddSupervisionDialog::OnDialogCloseRequested() {
+ bool showing_confirm_dialog = MaybeShowConfirmSignoutDialog();
+ return !showing_confirm_dialog;
+}
+
+void AddSupervisionDialog::OnCloseContents(content::WebContents* source,
+ bool* out_close_dialog) {
+ // This code gets called by a different path that OnDialogCloseRequested(),
+ // and actually masks the call to OnDialogCloseRequested() the first time the
+ // user clicks on the [x]. Because the first [x] click comes here, we need to
+ // show the confirmation dialog here and signal the caller to possibly close
+ // the dialog. Subsequent clicks on [x] during the lifetime of the dialog
+ // will result in calls to OnDialogCloseRequested().
+ *out_close_dialog = OnDialogCloseRequested();
+}
+
+AddSupervisionDialog::AddSupervisionDialog()
+ : SystemWebDialogDelegate(GURL(chrome::kChromeUIAddSupervisionURL),
+ base::string16()) {}
+
+AddSupervisionDialog::~AddSupervisionDialog() = default;
+
+// static
+SystemWebDialogDelegate* AddSupervisionDialog::GetInstance() {
+ return SystemWebDialogDelegate::FindInstance(GetDialogId());
+}
+
+// AddSupervisionUI implementations.
AddSupervisionUI::AddSupervisionUI(content::WebUI* web_ui)
: ui::MojoWebUIController(web_ui) {
@@ -40,12 +161,26 @@ void AddSupervisionUI::SetupResources() {
std::unique_ptr<content::WebUIDataSource> source(
content::WebUIDataSource::Create(chrome::kChromeUIAddSupervisionHost));
+ // Initialize supervision URL from the command-line arguments (if provided).
+ supervision_url_ = GetAddSupervisionURL();
+ DCHECK(supervision_url_.DomainIs("google.com"));
+
+ // Forward data to the WebUI.
source->AddResourcePath("post_message_api.js",
IDR_ADD_SUPERVISION_POST_MESSAGE_API_JS);
source->AddResourcePath("add_supervision_api_server.js",
IDR_ADD_SUPERVISION_API_SERVER_JS);
source->AddResourcePath("add_supervision.js", IDR_ADD_SUPERVISION_JS);
+ source->AddResourcePath("images/network_unavailable.svg",
+ IDR_ADD_SUPERVISION_NETWORK_UNAVAILABLE_SVG);
+
source->AddLocalizedString("pageTitle", IDS_ADD_SUPERVISION_PAGE_TITLE);
+ source->AddLocalizedString("networkDownHeading",
+ IDS_ADD_SUPERVISION_NETWORK_DOWN_HEADING);
+ source->AddLocalizedString("networkDownDescription",
+ IDS_ADD_SUPERVISION_NETWORK_DOWN_DESCRIPTION);
+ source->AddLocalizedString("networkDownButtonLabel",
+ IDS_ADD_SUPERVISION_NETWORK_DOWN_BUTTON_LABEL);
// Full paths (relative to src) are important for Mojom generated files.
source->AddResourcePath(
@@ -55,18 +190,34 @@ void AddSupervisionUI::SetupResources() {
source->SetJsonPath("strings.js");
source->SetDefaultResource(IDR_ADD_SUPERVISION_HTML);
- source->AddString("webviewUrl", kAddSupervisionURL);
- source->AddString("eventOriginFilter", kAddSupervisionEventOriginFilter);
+ source->AddString("webviewUrl", supervision_url_.spec());
+ source->AddString("eventOriginFilter", supervision_url_.GetOrigin().spec());
+ source->AddString("platformVersion", base::SysInfo::OperatingSystemVersion());
+ source->AddString("flowType", kAddSupervisionFlowType);
+
+ // Forward the browser language code.
+ source->AddString(
+ "languageCode",
+ google_util::GetGoogleLocale(g_browser_process->GetApplicationLocale()));
content::WebUIDataSource::Add(profile, source.release());
}
AddSupervisionUI::~AddSupervisionUI() = default;
+bool AddSupervisionUI::CloseDialog() {
+ bool showing_confirm_dialog = MaybeShowConfirmSignoutDialog();
+ if (!showing_confirm_dialog) {
+ // We aren't showing the confirm dialog, so close the AddSupervisionDialog.
+ AddSupervisionDialog::Close();
+ }
+ return !showing_confirm_dialog;
+}
+
void AddSupervisionUI::BindAddSupervisionHandler(
add_supervision::mojom::AddSupervisionHandlerRequest request) {
- mojo_api_handler_.reset(
- new AddSupervisionHandler(std::move(request), web_ui()));
+ mojo_api_handler_ = std::make_unique<AddSupervisionHandler>(
+ std::move(request), web_ui(), this);
}
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h
index 336956d2153..25a2c1b2068 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h
@@ -9,16 +9,55 @@
#include "base/macros.h"
#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision.mojom.h"
+#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.h"
+#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h"
+#include "ui/base/ui_base_types.h"
+#include "ui/gfx/native_widget_types.h"
+#include "ui/views/controls/label.h"
#include "ui/webui/mojo_web_ui_controller.h"
+#include "url/gurl.h"
namespace chromeos {
+// Dialog which displays the add-supervision flow which allows users to
+// convert a regular Google account into a Family-Link managed account.
+class AddSupervisionDialog : public SystemWebDialogDelegate {
+ public:
+ // Shows the dialog; if the dialog is already displayed, this function is a
+ // no-op.
+ static void Show(gfx::NativeView parent);
+
+ // Closes the dialog, if the dialog doesn't exist, this function is a
+ // no-op.
+ static void Close();
+
+ // ui::WebDialogDelegate:
+ ui::ModalType GetDialogModalType() const override;
+ void GetDialogSize(gfx::Size* size) const override;
+ bool OnDialogCloseRequested() override;
+ void OnCloseContents(content::WebContents* source,
+ bool* out_close_dialog) override;
+
+ protected:
+ AddSupervisionDialog();
+ ~AddSupervisionDialog() override;
+
+ private:
+ static SystemWebDialogDelegate* GetInstance();
+
+ DISALLOW_COPY_AND_ASSIGN(AddSupervisionDialog);
+};
+
// Controller for chrome://add-supervision
-class AddSupervisionUI : public ui::MojoWebUIController {
+class AddSupervisionUI : public ui::MojoWebUIController,
+ public AddSupervisionHandler::Delegate {
public:
explicit AddSupervisionUI(content::WebUI* web_ui);
~AddSupervisionUI() override;
+ // AddSupervisionHandler::Delegate:
+ bool CloseDialog() override;
+
private:
void BindAddSupervisionHandler(
add_supervision::mojom::AddSupervisionHandlerRequest request);
@@ -27,6 +66,8 @@ class AddSupervisionUI : public ui::MojoWebUIController {
std::unique_ptr<add_supervision::mojom::AddSupervisionHandler>
mojo_api_handler_;
+ GURL supervision_url_;
+
DISALLOW_COPY_AND_ASSIGN(AddSupervisionUI);
};
diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc
new file mode 100644
index 00000000000..9ee08568e9b
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.cc
@@ -0,0 +1,90 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.h"
+
+#include <memory>
+
+#include "base/strings/utf_string_conversions.h"
+#include "chrome/browser/lifetime/application_lifetime.h"
+#include "chrome/browser/ui/browser_dialogs.h"
+#include "chrome/grit/generated_resources.h"
+#include "components/constrained_window/constrained_window_views.h"
+#include "components/user_manager/user_manager.h"
+#include "ui/base/l10n/l10n_util.h"
+#include "ui/base/resource/resource_bundle.h"
+#include "ui/resources/grit/ui_resources.h"
+#include "ui/views/border.h"
+#include "ui/views/controls/label.h"
+#include "ui/views/layout/fill_layout.h"
+#include "ui/views/layout/layout_provider.h"
+#include "ui/views/widget/widget.h"
+#include "ui/views/window/dialog_delegate.h"
+
+namespace chromeos {
+
+namespace {
+// The width of the text body in the dialog.
+const int kDialogBodyTextWidth = 250;
+} // namespace
+
+ConfirmSignoutDialog::ConfirmSignoutDialog() {
+ SetLayoutManager(std::make_unique<views::FillLayout>());
+ SetBorder(views::CreateEmptyBorder(
+ views::LayoutProvider::Get()->GetDialogInsetsForContentType(
+ views::DialogContentType::TEXT, views::DialogContentType::TEXT)));
+
+ base::string16 given_name =
+ user_manager::UserManager::Get()->GetPrimaryUser()->GetGivenName();
+
+ // |body_| will be owned by the views system.
+ views::Label* body = new views::Label;
+ body->SetHorizontalAlignment(gfx::ALIGN_LEFT);
+ body->SetMultiLine(true);
+ body->SetText(l10n_util::GetStringFUTF16(IDS_ADD_SUPERVISION_EXIT_DIALOG_BODY,
+ given_name));
+ body->SizeToFit(kDialogBodyTextWidth);
+ AddChildView(body);
+}
+
+ConfirmSignoutDialog::~ConfirmSignoutDialog() = default;
+
+ui::ModalType ConfirmSignoutDialog::GetModalType() const {
+ return ui::ModalType::MODAL_TYPE_SYSTEM;
+}
+
+base::string16 ConfirmSignoutDialog::GetWindowTitle() const {
+ return l10n_util::GetStringUTF16(IDS_ADD_SUPERVISION_EXIT_DIALOG_TITLE);
+}
+
+bool ConfirmSignoutDialog::Accept() {
+ chrome::AttemptUserExit();
+ return true;
+}
+
+int ConfirmSignoutDialog::GetDialogButtons() const {
+ return ui::DialogButton::DIALOG_BUTTON_OK |
+ ui::DialogButton::DIALOG_BUTTON_CANCEL;
+}
+
+base::string16 ConfirmSignoutDialog::GetDialogButtonLabel(
+ ui::DialogButton button) const {
+ if (button == ui::DialogButton::DIALOG_BUTTON_OK) {
+ return l10n_util::GetStringUTF16(
+ IDS_ADD_SUPERVISION_EXIT_DIALOG_SIGNOUT_BUTTON_LABEL);
+ }
+ return l10n_util::GetStringUTF16(
+ IDS_ADD_SUPERVISION_EXIT_DIALOG_CANCEL_BUTTON_LABEL);
+}
+
+// static
+void ConfirmSignoutDialog::Show() {
+ // Ownership of the ConfirmSignoutDialog is passed to the views system.
+ // Dialog is system-modal, so no parent window is needed.
+ constrained_window::CreateBrowserModalDialogViews(new ConfirmSignoutDialog(),
+ nullptr /* parent window */)
+ ->Show();
+}
+
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.h
new file mode 100644
index 00000000000..6e7bff69d73
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/confirm_signout_dialog.h
@@ -0,0 +1,40 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_CONFIRM_SIGNOUT_DIALOG_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_CONFIRM_SIGNOUT_DIALOG_H_
+
+#include "base/macros.h"
+#include "ui/base/ui_base_types.h"
+#include "ui/views/window/dialog_delegate.h"
+
+namespace chromeos {
+
+// Dialog shown when the user tries to close the flow when account has already
+// become supervised, and the user only has the choice of finishing the flow, or
+// signing out.
+class ConfirmSignoutDialog : public views::DialogDelegateView {
+ public:
+ ~ConfirmSignoutDialog() override;
+
+ // views::WidgetDelegate:
+ ui::ModalType GetModalType() const override;
+ base::string16 GetWindowTitle() const override;
+
+ // views::DialogDelegate:
+ bool Accept() override;
+ int GetDialogButtons() const override;
+ base::string16 GetDialogButtonLabel(ui::DialogButton button) const override;
+
+ static void Show();
+
+ private:
+ ConfirmSignoutDialog();
+
+ DISALLOW_COPY_AND_ASSIGN(ConfirmSignoutDialog);
+};
+
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ADD_SUPERVISION_CONFIRM_SIGNOUT_DIALOG_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc
index 9e65e59a7d7..de20b5eedd0 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_handler.cc
@@ -376,7 +376,7 @@ void ArcGraphicsTracingHandler::StartTracing() {
base::trace_event::TraceConfig config(
"-*,exo,viz,toplevel,gpu,cc,blink,disabled-by-default-android "
- "gfx,disabled-by-default-android hal",
+ "gfx,disabled-by-default-android hal,disabled-by-default-android view",
base::trace_event::RECORD_CONTINUOUSLY);
config.EnableSystrace();
tracing_active_ = true;
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 de99715706a..2e65bdfe483 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
@@ -15,13 +15,14 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/ash/ash_util.h"
-#include "chrome/browser/ui/ash/assistant/assistant_pref_util.h"
#include "chrome/browser/ui/views/chrome_web_dialog_view.h"
#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
+#include "chromeos/services/assistant/public/cpp/assistant_prefs.h"
#include "components/arc/arc_prefs.h"
#include "components/prefs/pref_service.h"
+#include "components/session_manager/core/session_manager.h"
#include "content/public/browser/host_zoom_map.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_ui.h"
@@ -118,6 +119,12 @@ void AssistantOptInUI::Initialize() {
void AssistantOptInDialog::Show(
ash::FlowType type,
ash::AssistantSetup::StartAssistantOptInFlowCallback callback) {
+ // Check session state here to prevent timing issue -- session state might
+ // have changed during the mojom calls to launch the opt-in dalog.
+ if (session_manager::SessionManager::Get()->session_state() !=
+ session_manager::SessionState::ACTIVE) {
+ return;
+ }
if (g_dialog) {
g_dialog->Focus();
std::move(callback).Run(false);
@@ -141,7 +148,7 @@ AssistantOptInDialog::~AssistantOptInDialog() {
void AssistantOptInDialog::AdjustWidgetInitParams(
views::Widget::InitParams* params) {
- params->keep_on_top = false;
+ params->z_order = ui::ZOrderLevel::kNormal;
}
void AssistantOptInDialog::GetDialogSize(gfx::Size* size) const {
@@ -166,8 +173,8 @@ void AssistantOptInDialog::OnDialogClosed(const std::string& json_retval) {
PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
const bool completed =
prefs->GetBoolean(arc::prefs::kVoiceInteractionEnabled) &&
- (::assistant::prefs::GetConsentStatus(prefs) ==
- ash::mojom::ConsentStatus::kActivityControlAccepted);
+ (prefs->GetInteger(assistant::prefs::kAssistantConsentStatus) ==
+ assistant::prefs::ConsentStatus::kActivityControlAccepted);
std::move(callback_).Run(completed);
SystemWebDialogDelegate::OnDialogClosed(json_retval);
}
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 24fabe19d7c..4287e686189 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
@@ -4,6 +4,8 @@
#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.h"
+#include <utility>
+
#include "base/metrics/histogram_macros.h"
#include "chrome/browser/consent_auditor/consent_auditor_factory.h"
#include "chrome/browser/signin/identity_manager_factory.h"
@@ -15,8 +17,8 @@
#include "components/arc/arc_prefs.h"
#include "components/consent_auditor/consent_auditor.h"
#include "components/prefs/pref_service.h"
+#include "components/signin/public/identity_manager/identity_manager.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"
@@ -45,16 +47,6 @@ bool IsScreenContextToggleDisabled(PrefService* prefs) {
arc::prefs::kVoiceInteractionContextEnabled);
}
-bool IsHotwordDefaultEnabled(PrefService* prefs) {
- return IsPreferenceDefaultEnabled(
- prefs, arc::prefs::kVoiceInteractionHotwordEnabled);
-}
-
-bool IsHotwordToggleDisabled(PrefService* prefs) {
- return prefs->IsManagedPreference(
- arc::prefs::kVoiceInteractionHotwordEnabled);
-}
-
} // namespace
namespace chromeos {
@@ -149,27 +141,6 @@ base::Value CreateGetMoreData(bool email_optin_needed,
PrefService* prefs) {
base::Value get_more_data(base::Value::Type::LIST);
- if (!IsVoiceMatchEnabled(prefs)) {
- // 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(IsHotwordDefaultEnabled(prefs)));
- hotword_data.SetKey("toggleDisabled",
- base::Value(IsHotwordToggleDisabled(prefs)));
- 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"));
@@ -266,26 +237,15 @@ void RecordActivityControlConsent(Profile* profile,
}
bool IsHotwordDspAvailable() {
- chromeos::AudioDeviceList devices;
- chromeos::CrasAudioHandler::Get()->GetAudioDevices(&devices);
- for (const chromeos::AudioDevice& device : devices) {
- if (device.type == chromeos::AUDIO_TYPE_HOTWORD) {
- return true;
- }
- }
- return false;
+ return chromeos::CrasAudioHandler::Get()->HasHotwordDevice();
}
-bool IsVoiceMatchEnabled(const PrefService* prefs) {
- if (!base::FeatureList::IsEnabled(assistant::features::kAssistantVoiceMatch))
- return false;
-
- // If the hotword preference is managed, then we should not do Voice Match
- // if the administrator has disabled the hotword.
- if (prefs->IsManagedPreference(arc::prefs::kVoiceInteractionHotwordEnabled))
- return prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled);
-
- return true;
+bool IsVoiceMatchEnforcedOff(const PrefService* prefs) {
+ // If the hotword preference is managed to always disabled, then we should not
+ // show Voice Match flow.
+ return prefs->IsManagedPreference(
+ arc::prefs::kVoiceInteractionHotwordEnabled) &&
+ !prefs->GetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled);
}
} // namespace chromeos
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 53d49d18dca..166a1014ba7 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
@@ -76,7 +76,7 @@ void RecordActivityControlConsent(Profile* profile,
bool IsHotwordDspAvailable();
-bool IsVoiceMatchEnabled(const PrefService* prefs);
+bool IsVoiceMatchEnforcedOff(const PrefService* prefs);
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc
new file mode 100644
index 00000000000..c6110b2fde4
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc
@@ -0,0 +1,85 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/chromeos/camera/camera_ui.h"
+
+#include <utility>
+
+#include "base/bind.h"
+#include "base/feature_list.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/web_applications/system_web_app_manager.h"
+#include "chrome/common/url_constants.h"
+#include "chrome/grit/browser_resources.h"
+#include "chrome/grit/camera_resources.h"
+#include "chrome/grit/camera_resources_map.h"
+#include "chromeos/constants/chromeos_features.h"
+#include "content/public/browser/web_ui_data_source.h"
+#include "mojo/public/js/grit/mojo_bindings_resources.h"
+
+namespace chromeos {
+
+namespace {
+
+content::WebUIDataSource* CreateCameraUIHTMLSource() {
+ content::WebUIDataSource* source =
+ content::WebUIDataSource::Create(chrome::kChromeUICameraHost);
+
+ // Add all settings resources.
+ for (size_t i = 0; i < kCameraResourcesSize; ++i) {
+ source->AddResourcePath(kCameraResources[i].name,
+ kCameraResources[i].value);
+ }
+
+ // Add WebUI version of the CCA browser proxy.
+ source->AddResourcePath("src/js/browser_proxy/browser_proxy.js",
+ IDR_CAMERA_WEBUI_BROWSER_PROXY);
+
+ // Add mojom-lite files under expected paths.
+ source->AddResourcePath("src/js/mojo/image_capture.mojom-lite.js",
+ IDR_CAMERA_IMAGE_CAPTURE_MOJOM_LITE_JS);
+ source->AddResourcePath("src/js/mojo/camera_common.mojom-lite.js",
+ IDR_CAMERA_CAMERA_COMMON_MOJOM_LITE_JS);
+ source->AddResourcePath("src/js/mojo/camera_metadata.mojom-lite.js",
+ IDR_CAMERA_CAMERA_METADATA_MOJOM_LITE_JS);
+ source->AddResourcePath("src/js/mojo/camera_metadata_tags.mojom-lite.js",
+ IDR_CAMERA_CAMERA_METADATA_TAGS_MOJOM_LITE_JS);
+ source->AddResourcePath("src/js/mojo/cros_image_capture.mojom-lite.js",
+ IDR_CAMERA_CROS_IMAGE_CAPTURE_MOJOM_LITE_JS);
+ source->AddResourcePath("src/js/mojo/mojo_bindings_lite.js",
+ IDR_MOJO_MOJO_BINDINGS_LITE_JS);
+
+ // Add System Web App resources.
+ source->AddResourcePath("pwa.html", IDR_PWA_HTML);
+
+ source->SetJsonPath("strings.js");
+
+ return source;
+}
+
+} // namespace
+
+///////////////////////////////////////////////////////////////////////////////
+//
+// CameraUI
+//
+///////////////////////////////////////////////////////////////////////////////
+
+CameraUI::CameraUI(content::WebUI* web_ui) : ui::MojoWebUIController(web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+
+ // Set up the data source.
+ content::WebUIDataSource* source = CreateCameraUIHTMLSource();
+ content::WebUIDataSource::Add(profile, source);
+}
+
+CameraUI::~CameraUI() = default;
+
+// static
+bool CameraUI::IsEnabled() {
+ return web_app::SystemWebAppManager::IsAppEnabled(
+ web_app::SystemAppType::CAMERA);
+}
+
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.h b/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.h
new file mode 100644
index 00000000000..31dabca4e5e
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.h
@@ -0,0 +1,27 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_CAMERA_CAMERA_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_CAMERA_CAMERA_UI_H_
+
+#include "base/macros.h"
+#include "ui/webui/mojo_web_ui_controller.h"
+
+namespace chromeos {
+
+class CameraUI : public ui::MojoWebUIController {
+ public:
+ explicit CameraUI(content::WebUI* web_ui);
+ ~CameraUI() override;
+
+ // True when the Camera as a System Web App flag is true.
+ static bool IsEnabled();
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(CameraUI);
+};
+
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_CAMERA_CAMERA_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc
index 77976c56841..981076b2c11 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_localized_strings_provider.cc
@@ -24,8 +24,10 @@ constexpr LocalizedString kLocalizedStringsWithoutPlaceholders[] = {
{"tryAgain", IDS_CELLULAR_SETUP_TRY_AGAIN_LABEL},
{"simDetectPageTitle", IDS_CELLULAR_SETUP_SIM_DETECT_PAGE_TITLE},
{"provisioningPageTitle", IDS_CELLULAR_SETUP_PROVISIONING_PAGE_TITLE},
- {"successPageTitle", IDS_CELLULAR_SETUP_SUCCESS_PAGE_TITLE},
- {"successPageMessage", IDS_CELLULAR_SETUP_SUCCESS_PAGE_MESSAGE}};
+ {"finalPageTitle", IDS_CELLULAR_SETUP_FINAL_PAGE_TITLE},
+ {"finalPageMessage", IDS_CELLULAR_SETUP_FINAL_PAGE_MESSAGE},
+ {"finalPageErrorTitle", IDS_CELLULAR_SETUP_FINAL_PAGE_ERROR_TITLE},
+ {"finalPageErrorMessage", IDS_CELLULAR_SETUP_FINAL_PAGE_ERROR_MESSAGE}};
} // namespace
diff --git a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc
index 060cab439e7..5eaf0f3a48c 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/cellular_setup/mobile_setup_ui.cc
@@ -175,16 +175,14 @@ class MobileSetupUIHTMLSource : public content::URLDataSource {
~MobileSetupUIHTMLSource() override {}
// content::URLDataSource implementation.
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override;
- std::string GetMimeType(const std::string&) const override {
- return "text/html";
- }
- bool ShouldAddContentSecurityPolicy() const override { return false; }
- bool AllowCaching() const override {
+ std::string GetMimeType(const std::string&) override { return "text/html"; }
+ bool ShouldAddContentSecurityPolicy() override { return false; }
+ bool AllowCaching() override {
// Should not be cached to reflect dynamically-generated contents that may
// depend on current settings.
return false;
@@ -266,7 +264,7 @@ class MobileSetupHandler : public content::WebUIMessageHandler,
MobileSetupUIHTMLSource::MobileSetupUIHTMLSource() : weak_ptr_factory_(this) {}
-std::string MobileSetupUIHTMLSource::GetSource() const {
+std::string MobileSetupUIHTMLSource::GetSource() {
return chrome::kChromeUIMobileSetupHost;
}
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 670f76e0edf..cce737b51cf 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc
@@ -8,8 +8,11 @@
#include <stdint.h>
#include <fstream>
+#include <map>
#include <memory>
+#include <string>
#include <utility>
+#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
@@ -24,6 +27,8 @@
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/task/post_task.h"
+#include "base/task/task_traits.h"
+#include "base/threading/sequenced_task_runner_handle.h"
#include "chrome/browser/chromeos/drive/debug_info_collector.h"
#include "chrome/browser/chromeos/drive/drive_integration_service.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
@@ -33,7 +38,10 @@
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
+#include "chrome/services/file_util/public/cpp/zip_file_creator.h"
#include "chromeos/constants/chromeos_features.h"
+#include "components/download/content/public/all_download_item_notifier.h"
+#include "components/download/public/common/download_item.h"
#include "components/drive/drive.pb.h"
#include "components/drive/drive_api_util.h"
#include "components/drive/drive_notification_manager.h"
@@ -42,7 +50,11 @@
#include "components/drive/job_list.h"
#include "components/drive/service/drive_service_interface.h"
#include "components/prefs/pref_service.h"
+#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/navigation_controller.h"
+#include "content/public/browser/system_connector.h"
+#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
@@ -277,6 +289,11 @@ std::pair<ino_t, base::ListValue> GetServiceLogContents(
return {inode, std::move(result)};
}
+class DriveInternalsWebUIHandler;
+
+void ZipLogs(Profile* profile,
+ base::WeakPtr<DriveInternalsWebUIHandler> drive_internals);
+
// Class to handle messages from chrome://drive-internals.
class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
public:
@@ -285,6 +302,13 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
~DriveInternalsWebUIHandler() override {}
+ void DownloadLogsZip(const base::FilePath& path) {
+ web_ui()->GetWebContents()->GetController().LoadURL(
+ net::FilePathToFileURL(path), {}, {}, {});
+ }
+
+ void OnZipDone() { MaybeCallJavascript("onZipDone", base::Value()); }
+
private:
void MaybeCallJavascript(const std::string& function,
base::Value data1,
@@ -327,6 +351,10 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
"listFileEntries",
base::BindRepeating(&DriveInternalsWebUIHandler::ListFileEntries,
weak_ptr_factory_.GetWeakPtr()));
+ web_ui()->RegisterMessageCallback(
+ "zipLogs",
+ base::BindRepeating(&DriveInternalsWebUIHandler::ZipDriveFsLogs,
+ weak_ptr_factory_.GetWeakPtr()));
}
// Called when the page is first loaded.
@@ -877,6 +905,19 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
UpdateFileSystemContentsSection();
}
+ void ZipDriveFsLogs(const base::ListValue* args) {
+ AllowJavascript();
+
+ drive::DriveIntegrationService* integration_service =
+ GetIntegrationService();
+ if (!integration_service ||
+ integration_service->GetDriveFsLogPath().empty()) {
+ return;
+ }
+
+ ZipLogs(profile(), weak_ptr_factory_.GetWeakPtr());
+ }
+
// Called after file system reset for ResetDriveFileSystem is done.
void ResetFinished(bool success) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -929,6 +970,106 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
DISALLOW_COPY_AND_ASSIGN(DriveInternalsWebUIHandler);
};
+class LogsZipper : public download::AllDownloadItemNotifier::Observer {
+ public:
+ LogsZipper(Profile* profile,
+ base::WeakPtr<DriveInternalsWebUIHandler> drive_internals)
+ : profile_(profile),
+ logs_directory_(
+ drive::DriveIntegrationServiceFactory::FindForProfile(profile)
+ ->GetDriveFsLogPath()
+ .DirName()),
+ zip_path_(logs_directory_.AppendASCII(kLogsZipName)),
+ drive_internals_(std::move(drive_internals)) {}
+
+ void Start() {
+ base::PostTaskWithTraitsAndReplyWithResult(
+ FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
+ base::BindOnce(&LogsZipper::EnumerateLogFiles, logs_directory_,
+ zip_path_),
+ base::BindOnce(&LogsZipper::ZipLogFiles, base::Unretained(this)));
+ }
+
+ private:
+ static constexpr char kLogsZipName[] = "drivefs_logs.zip";
+
+ void ZipLogFiles(const std::vector<base::FilePath>& files) {
+ (new ZipFileCreator(
+ base::BindRepeating(&LogsZipper::OnZipDone, base::Unretained(this)),
+ logs_directory_, files, zip_path_))
+ ->Start(content::GetSystemConnector());
+ }
+
+ static std::vector<base::FilePath> EnumerateLogFiles(
+ base::FilePath logs_path,
+ base::FilePath zip_path) {
+ // Note: this may be racy if multiple attempts to export logs are run
+ // concurrently, but it's a debug page and it requires explicit action to
+ // cause problems.
+ base::DeleteFile(zip_path, false);
+ std::vector<base::FilePath> log_files;
+ base::FileEnumerator enumerator(logs_path, false /* recursive */,
+ base::FileEnumerator::FILES);
+
+ for (base::FilePath current = enumerator.Next(); !current.empty();
+ current = enumerator.Next()) {
+ if (!current.MatchesExtension(".zip")) {
+ log_files.push_back(current.BaseName());
+ }
+ }
+ return log_files;
+ }
+
+ void OnZipDone(bool success) {
+ if (!drive_internals_ || !success) {
+ CleanUp();
+ return;
+ }
+ download_notifier_ = std::make_unique<download::AllDownloadItemNotifier>(
+ content::BrowserContext::GetDownloadManager(profile_), this);
+ drive_internals_->DownloadLogsZip(zip_path_);
+ }
+
+ void OnDownloadUpdated(content::DownloadManager* manager,
+ download::DownloadItem* item) override {
+ if (item->GetState() == download::DownloadItem::IN_PROGRESS ||
+ item->GetURL() != net::FilePathToFileURL(zip_path_)) {
+ return;
+ }
+ CleanUp();
+ }
+
+ void CleanUp() {
+ base::PostTaskWithTraits(
+ FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
+ base::BindOnce(base::IgnoreResult(&base::DeleteFile), zip_path_,
+ false));
+ download_notifier_.reset();
+ if (drive_internals_) {
+ drive_internals_->OnZipDone();
+ }
+ base::SequencedTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
+ }
+
+ Profile* const profile_;
+ const base::FilePath logs_directory_;
+ const base::FilePath zip_path_;
+
+ const base::WeakPtr<DriveInternalsWebUIHandler> drive_internals_;
+
+ std::unique_ptr<download::AllDownloadItemNotifier> download_notifier_;
+
+ DISALLOW_COPY_AND_ASSIGN(LogsZipper);
+};
+
+constexpr char LogsZipper::kLogsZipName[];
+
+void ZipLogs(Profile* profile,
+ base::WeakPtr<DriveInternalsWebUIHandler> drive_internals) {
+ auto* logs_zipper = new LogsZipper(profile, std::move(drive_internals));
+ logs_zipper->Start();
+}
+
} // namespace
DriveInternalsUI::DriveInternalsUI(content::WebUI* web_ui)
diff --git a/chromium/chrome/browser/ui/webui/chromeos/image_source.cc b/chromium/chrome/browser/ui/webui/chromeos/image_source.cc
index 0c8e627e816..d5942fc36e6 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/image_source.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/image_source.cc
@@ -49,7 +49,7 @@ ImageSource::ImageSource() : weak_factory_(this) {
ImageSource::~ImageSource() {
}
-std::string ImageSource::GetSource() const {
+std::string ImageSource::GetSource() {
return chrome::kChromeOSAssetHost;
}
@@ -87,7 +87,7 @@ void ImageSource::StartDataRequestAfterPathExists(
}
}
-std::string ImageSource::GetMimeType(const std::string& path) const {
+std::string ImageSource::GetMimeType(const std::string& path) {
std::string mime_type;
std::string ext = base::FilePath(path).Extension();
if (!ext.empty())
diff --git a/chromium/chrome/browser/ui/webui/chromeos/image_source.h b/chromium/chrome/browser/ui/webui/chromeos/image_source.h
index 94f0deda1be..5d7a5afcec0 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/image_source.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/image_source.h
@@ -26,14 +26,14 @@ class ImageSource : public content::URLDataSource {
~ImageSource() override;
// content::URLDataSource implementation.
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& got_data_callback)
override;
- std::string GetMimeType(const std::string& path) const override;
+ std::string GetMimeType(const std::string& path) override;
private:
// Continuation from StartDataRequest().
diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/OWNERS b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/OWNERS
new file mode 100644
index 00000000000..e7edf2e630f
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/OWNERS
@@ -0,0 +1,2 @@
+olsen@chromium.org
+rsorokin@chromium.org
diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc
new file mode 100644
index 00000000000..e46a6eabfa8
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.cc
@@ -0,0 +1,58 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h"
+
+#include <string>
+
+#include "base/logging.h"
+#include "base/macros.h"
+#include "base/values.h"
+#include "chrome/browser/chromeos/login/saml/in_session_password_change_manager.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/common/pref_names.h"
+#include "chromeos/login/auth/saml_password_attributes.h"
+#include "components/prefs/pref_service.h"
+#include "components/user_manager/user_manager.h"
+
+namespace chromeos {
+
+ConfirmPasswordChangeHandler::ConfirmPasswordChangeHandler() {
+ if (InSessionPasswordChangeManager::IsInitialized()) {
+ InSessionPasswordChangeManager::Get()->AddObserver(this);
+ }
+}
+
+ConfirmPasswordChangeHandler::~ConfirmPasswordChangeHandler() {
+ if (InSessionPasswordChangeManager::IsInitialized()) {
+ InSessionPasswordChangeManager::Get()->RemoveObserver(this);
+ }
+}
+
+void ConfirmPasswordChangeHandler::OnEvent(
+ InSessionPasswordChangeManager::Event event) {
+ if (event ==
+ InSessionPasswordChangeManager::CRYPTOHOME_PASSWORD_CHANGE_FAILURE) {
+ AllowJavascript();
+ FireWebUIListener("incorrect-old-password");
+ }
+}
+
+void ConfirmPasswordChangeHandler::HandleChangePassword(
+ const base::ListValue* params) {
+ const std::string old_password = params->GetList()[0].GetString();
+ const std::string new_password = params->GetList()[1].GetString();
+ InSessionPasswordChangeManager::Get()->ChangePassword(old_password,
+ new_password);
+}
+
+void ConfirmPasswordChangeHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "changePassword",
+ base::BindRepeating(&ConfirmPasswordChangeHandler::HandleChangePassword,
+ weak_factory_.GetWeakPtr()));
+}
+
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h
new file mode 100644
index 00000000000..7a69e7c624e
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h
@@ -0,0 +1,39 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_CONFIRM_PASSWORD_CHANGE_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_CONFIRM_PASSWORD_CHANGE_HANDLER_H_
+
+#include "base/memory/weak_ptr.h"
+#include "base/values.h"
+#include "chrome/browser/chromeos/login/saml/in_session_password_change_manager.h"
+#include "content/public/browser/web_ui_message_handler.h"
+
+namespace chromeos {
+
+class ConfirmPasswordChangeHandler
+ : public content::WebUIMessageHandler,
+ public InSessionPasswordChangeManager::Observer {
+ public:
+ ConfirmPasswordChangeHandler();
+ ~ConfirmPasswordChangeHandler() override;
+
+ // Tries to change the cryptohome password once the confirm-password-change
+ // dialog is filled in and the password change is confirmed.
+ void HandleChangePassword(const base::ListValue* passwords);
+
+ // InSessionPasswordChangeManager::Observer:
+ void OnEvent(InSessionPasswordChangeManager::Event event) override;
+
+ // content::WebUIMessageHandler:
+ void RegisterMessages() override;
+
+ private:
+ base::WeakPtrFactory<ConfirmPasswordChangeHandler> weak_factory_{this};
+ DISALLOW_COPY_AND_ASSIGN(ConfirmPasswordChangeHandler);
+};
+
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_CONFIRM_PASSWORD_CHANGE_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.cc
new file mode 100644
index 00000000000..fa57cf5d524
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.cc
@@ -0,0 +1,76 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.h"
+
+#include <string>
+
+#include "base/logging.h"
+#include "base/macros.h"
+#include "base/values.h"
+#include "chrome/browser/chromeos/login/auth/chrome_cryptohome_authenticator.h"
+#include "chrome/browser/chromeos/login/saml/in_session_password_change_manager.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/common/pref_names.h"
+#include "chromeos/login/auth/saml_password_attributes.h"
+#include "components/prefs/pref_service.h"
+#include "components/user_manager/user_manager.h"
+
+namespace chromeos {
+
+PasswordChangeHandler::PasswordChangeHandler(
+ const std::string& password_change_url)
+ : password_change_url_(password_change_url) {}
+PasswordChangeHandler::~PasswordChangeHandler() = default;
+
+void PasswordChangeHandler::HandleInitialize(const base::ListValue* value) {
+ Profile* profile = Profile::FromWebUI(web_ui());
+ CHECK(profile->GetPrefs()->GetBoolean(
+ prefs::kSamlInSessionPasswordChangeEnabled));
+
+ AllowJavascript();
+ base::Value params(base::Value::Type::DICTIONARY);
+ if (password_change_url_.empty()) {
+ LOG(ERROR) << "Password change url is empty";
+ return;
+ }
+ params.SetKey("passwordChangeUrl", base::Value(password_change_url_));
+ const user_manager::User* user =
+ ProfileHelper::Get()->GetUserByProfile(profile);
+ if (user)
+ params.SetKey("userName", base::Value(user->GetDisplayEmail()));
+ CallJavascriptFunction("insession.password.change.loadAuthExtension", params);
+}
+
+void PasswordChangeHandler::HandleChangePassword(
+ const base::ListValue* params) {
+ const base::Value& old_passwords = params->GetList()[0];
+ const base::Value& new_passwords = params->GetList()[1];
+ VLOG(4) << "Scraped " << old_passwords.GetList().size() << " old passwords";
+ VLOG(4) << "Scraped " << new_passwords.GetList().size() << " new passwords";
+
+ const std::string old_password = (old_passwords.GetList().size() > 0)
+ ? old_passwords.GetList()[0].GetString()
+ : "";
+ const std::string new_password = (new_passwords.GetList().size() == 1)
+ ? new_passwords.GetList()[0].GetString()
+ : "";
+
+ InSessionPasswordChangeManager::Get()->OnSamlPasswordChanged(old_password,
+ new_password);
+}
+
+void PasswordChangeHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "initialize",
+ base::BindRepeating(&PasswordChangeHandler::HandleInitialize,
+ weak_factory_.GetWeakPtr()));
+ web_ui()->RegisterMessageCallback(
+ "changePassword",
+ base::BindRepeating(&PasswordChangeHandler::HandleChangePassword,
+ weak_factory_.GetWeakPtr()));
+}
+
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.h b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.h
new file mode 100644
index 00000000000..e74afbe622b
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.h
@@ -0,0 +1,36 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_HANDLER_H_
+
+#include "base/memory/weak_ptr.h"
+#include "base/values.h"
+#include "chromeos/login/auth/cryptohome_authenticator.h"
+#include "content/public/browser/web_ui_message_handler.h"
+
+namespace chromeos {
+
+class PasswordChangeHandler : public content::WebUIMessageHandler {
+ public:
+ explicit PasswordChangeHandler(const std::string& password_change_url);
+ ~PasswordChangeHandler() override;
+
+ // content::WebUIMessageHandler:
+ void RegisterMessages() override;
+
+ void HandleInitialize(const base::ListValue*);
+ void HandleChangePassword(const base::ListValue* passwords);
+
+ private:
+ const std::string password_change_url_;
+ scoped_refptr<CryptohomeAuthenticator> authenticator_;
+
+ base::WeakPtrFactory<PasswordChangeHandler> weak_factory_{this};
+ DISALLOW_COPY_AND_ASSIGN(PasswordChangeHandler);
+};
+
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc
new file mode 100644
index 00000000000..8b85995d13c
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.cc
@@ -0,0 +1,357 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h"
+
+#include <memory>
+
+#include "base/bind.h"
+#include "base/command_line.h"
+#include "base/json/json_writer.h"
+#include "base/strings/utf_string_conversions.h"
+#include "chrome/browser/chromeos/login/saml/password_expiry_notification.h"
+#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/webui/chromeos/in_session_password_change/confirm_password_change_handler.h"
+#include "chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_handler.h"
+#include "chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.h"
+#include "chrome/browser/ui/webui/localized_string.h"
+#include "chrome/common/pref_names.h"
+#include "chrome/common/webui_url_constants.h"
+#include "chrome/grit/browser_resources.h"
+#include "chrome/grit/generated_resources.h"
+#include "chromeos/constants/chromeos_switches.h"
+#include "chromeos/login/auth/saml_password_attributes.h"
+#include "chromeos/strings/grit/chromeos_strings.h"
+#include "components/prefs/pref_service.h"
+#include "components/strings/grit/components_strings.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/web_ui_data_source.h"
+#include "net/base/url_util.h"
+#include "ui/base/l10n/l10n_util.h"
+#include "ui/display/display.h"
+#include "ui/display/screen.h"
+#include "ui/strings/grit/ui_strings.h"
+
+namespace chromeos {
+
+namespace {
+
+PasswordChangeDialog* g_dialog = nullptr;
+
+ConfirmPasswordChangeDialog* g_confirm_dialog = nullptr;
+
+UrgentPasswordExpiryNotificationDialog* g_notification_dialog = nullptr;
+
+std::string GetPasswordChangeUrl(Profile* profile) {
+ if (base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kSamlPasswordChangeUrl)) {
+ return base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
+ switches::kSamlPasswordChangeUrl);
+ }
+
+ const policy::UserCloudPolicyManagerChromeOS* user_cloud_policy_manager =
+ profile->GetUserCloudPolicyManagerChromeOS();
+ if (user_cloud_policy_manager) {
+ const enterprise_management::PolicyData* policy =
+ user_cloud_policy_manager->core()->store()->policy();
+ if (policy->has_change_password_uri()) {
+ return policy->change_password_uri();
+ }
+ }
+
+ return SamlPasswordAttributes::LoadFromPrefs(profile->GetPrefs())
+ .password_change_url();
+}
+
+base::string16 GetHostedHeaderText(const std::string& password_change_url) {
+ base::string16 host =
+ base::UTF8ToUTF16(net::GetHostAndOptionalPort(GURL(password_change_url)));
+ DCHECK(!host.empty());
+ return l10n_util::GetStringFUTF16(IDS_LOGIN_SAML_PASSWORD_CHANGE_NOTICE,
+ host);
+}
+
+constexpr int kMaxPasswordChangeDialogWidth = 768;
+constexpr int kMaxPasswordChangeDialogHeight = 640;
+
+// TODO(https://crbug.com/930109): Change these numbers depending on what is
+// shown in the dialog.
+constexpr int kMaxConfirmPasswordChangeDialogWidth = 520;
+constexpr int kMaxConfirmPasswordChangeDialogHeight = 380;
+
+constexpr int kMaxNotificationDialogWidth = 768;
+constexpr int kMaxNotificationDialogHeight = 640;
+
+// Given a desired width and height, returns the same size if it fits on screen,
+// or the closest possible size that will fit on the screen.
+gfx::Size FitSizeToDisplay(int max_width, int max_height) {
+ const display::Display display =
+ display::Screen::GetScreen()->GetPrimaryDisplay();
+
+ gfx::Size display_size = display.size();
+
+ if (display.rotation() == display::Display::ROTATE_90 ||
+ display.rotation() == display::Display::ROTATE_270) {
+ display_size = gfx::Size(display_size.height(), display_size.width());
+ }
+
+ display_size = gfx::Size(std::min(display_size.width(), max_width),
+ std::min(display_size.height(), max_height));
+
+ return display_size;
+}
+
+} // namespace
+
+PasswordChangeDialog::PasswordChangeDialog()
+ : SystemWebDialogDelegate(GURL(chrome::kChromeUIPasswordChangeUrl),
+ /*title=*/base::string16()) {}
+
+PasswordChangeDialog::~PasswordChangeDialog() {
+ DCHECK_EQ(this, g_dialog);
+ g_dialog = nullptr;
+}
+
+void PasswordChangeDialog::GetDialogSize(gfx::Size* size) const {
+ *size = FitSizeToDisplay(kMaxPasswordChangeDialogWidth,
+ kMaxPasswordChangeDialogHeight);
+}
+
+void PasswordChangeDialog::AdjustWidgetInitParams(
+ views::Widget::InitParams* params) {
+ params->type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS;
+}
+
+ui::ModalType PasswordChangeDialog::GetDialogModalType() const {
+ return ui::ModalType::MODAL_TYPE_SYSTEM;
+}
+
+// static
+void PasswordChangeDialog::Show() {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ if (g_dialog) {
+ g_dialog->Focus();
+ return;
+ }
+ g_dialog = new PasswordChangeDialog();
+ g_dialog->ShowSystemDialog();
+}
+
+// static
+void PasswordChangeDialog::Dismiss() {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ if (g_dialog)
+ g_dialog->Close();
+}
+
+PasswordChangeUI::PasswordChangeUI(content::WebUI* web_ui)
+ : ui::WebDialogUI(web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+ CHECK(profile->GetPrefs()->GetBoolean(
+ prefs::kSamlInSessionPasswordChangeEnabled));
+ content::WebUIDataSource* source =
+ content::WebUIDataSource::Create(chrome::kChromeUIPasswordChangeHost);
+
+ const std::string password_change_url = GetPasswordChangeUrl(profile);
+ web_ui->AddMessageHandler(
+ std::make_unique<PasswordChangeHandler>(password_change_url));
+
+ source->AddString("hostedHeader", GetHostedHeaderText(password_change_url));
+ source->SetJsonPath("strings.js");
+
+ source->SetDefaultResource(IDR_PASSWORD_CHANGE_HTML);
+
+ source->AddResourcePath("password_change.css", IDR_PASSWORD_CHANGE_CSS);
+ source->AddResourcePath("authenticator.js",
+ IDR_PASSWORD_CHANGE_AUTHENTICATOR_JS);
+ source->AddResourcePath("password_change.js", IDR_PASSWORD_CHANGE_JS);
+
+ content::WebUIDataSource::Add(profile, source);
+}
+
+PasswordChangeUI::~PasswordChangeUI() = default;
+
+// static
+void ConfirmPasswordChangeDialog::Show(const std::string& scraped_old_password,
+ const std::string& scraped_new_password,
+ bool show_spinner_initially) {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ if (g_confirm_dialog) {
+ g_confirm_dialog->Focus();
+ return;
+ }
+ g_confirm_dialog = new ConfirmPasswordChangeDialog(
+ scraped_old_password, scraped_new_password, show_spinner_initially);
+ g_confirm_dialog->ShowSystemDialog();
+}
+
+// static
+void ConfirmPasswordChangeDialog::Dismiss() {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ if (g_confirm_dialog)
+ g_confirm_dialog->Close();
+}
+
+ConfirmPasswordChangeDialog::ConfirmPasswordChangeDialog(
+ const std::string& scraped_old_password,
+ const std::string& scraped_new_password,
+ bool show_spinner_initially)
+ : SystemWebDialogDelegate(GURL(chrome::kChromeUIConfirmPasswordChangeUrl),
+ /*title=*/base::string16()),
+ scraped_old_password_(scraped_old_password),
+ scraped_new_password_(scraped_new_password),
+ show_spinner_initially_(show_spinner_initially) {}
+
+ConfirmPasswordChangeDialog::~ConfirmPasswordChangeDialog() {
+ DCHECK_EQ(this, g_confirm_dialog);
+ g_confirm_dialog = nullptr;
+}
+
+void ConfirmPasswordChangeDialog::GetDialogSize(gfx::Size* size) const {
+ *size = FitSizeToDisplay(kMaxConfirmPasswordChangeDialogWidth,
+ kMaxConfirmPasswordChangeDialogHeight);
+}
+
+std::string ConfirmPasswordChangeDialog::GetDialogArgs() const {
+ // TODO(https://crbug.com/930109): Configure the embedded UI to only display
+ // prompts for the passwords that were not scraped.
+ std::string data;
+ base::DictionaryValue dialog_args;
+ dialog_args.SetBoolean("showSpinnerInitially", show_spinner_initially_);
+ base::JSONWriter::Write(dialog_args, &data);
+ return data;
+}
+
+void ConfirmPasswordChangeDialog::AdjustWidgetInitParams(
+ views::Widget::InitParams* params) {
+ params->type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS;
+}
+
+ui::ModalType ConfirmPasswordChangeDialog::GetDialogModalType() const {
+ return ui::ModalType::MODAL_TYPE_SYSTEM;
+}
+
+ConfirmPasswordChangeUI::ConfirmPasswordChangeUI(content::WebUI* web_ui)
+ : ui::WebDialogUI(web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+ CHECK(profile->GetPrefs()->GetBoolean(
+ prefs::kSamlInSessionPasswordChangeEnabled));
+ content::WebUIDataSource* source = content::WebUIDataSource::Create(
+ chrome::kChromeUIConfirmPasswordChangeHost);
+
+ static constexpr LocalizedString kLocalizedStrings[] = {
+ {"title", IDS_PASSWORD_CHANGE_CONFIRM_DIALOG_TITLE},
+ {"bothPasswordsPrompt",
+ IDS_PASSWORD_CHANGE_CONFIRM_DIALOG_BOTH_PASSWORDS_PROMPT},
+ {"oldPasswordPrompt",
+ IDS_PASSWORD_CHANGE_CONFIRM_DIALOG_OLD_PASSWORD_PROMPT},
+ {"newPasswordPrompt",
+ IDS_PASSWORD_CHANGE_CONFIRM_DIALOG_NEW_PASSWORD_PROMPT},
+ {"oldPassword", IDS_PASSWORD_CHANGE_OLD_PASSWORD_LABEL},
+ {"newPassword", IDS_PASSWORD_CHANGE_NEW_PASSWORD_LABEL},
+ {"confirmNewPassword", IDS_PASSWORD_CHANGE_CONFIRM_NEW_PASSWORD_LABEL},
+ {"matchError", IDS_PASSWORD_CHANGE_PASSWORDS_DONT_MATCH},
+ {"save", IDS_PASSWORD_CHANGE_CONFIRM_SAVE_BUTTON}};
+
+ AddLocalizedStringsBulk(source, kLocalizedStrings,
+ base::size(kLocalizedStrings));
+
+ source->SetJsonPath("strings.js");
+ source->SetDefaultResource(IDR_CONFIRM_PASSWORD_CHANGE_HTML);
+ source->AddResourcePath("confirm_password_change.js",
+ IDR_CONFIRM_PASSWORD_CHANGE_JS);
+
+ web_ui->AddMessageHandler(std::make_unique<ConfirmPasswordChangeHandler>());
+
+ content::WebUIDataSource::Add(profile, source);
+}
+
+ConfirmPasswordChangeUI::~ConfirmPasswordChangeUI() = default;
+
+UrgentPasswordExpiryNotificationDialog::UrgentPasswordExpiryNotificationDialog()
+ : SystemWebDialogDelegate(
+ GURL(chrome::kChromeUIUrgentPasswordExpiryNotificationUrl),
+ /*title=*/base::string16()) {}
+
+UrgentPasswordExpiryNotificationDialog::
+ ~UrgentPasswordExpiryNotificationDialog() {
+ DCHECK_EQ(this, g_notification_dialog);
+ g_notification_dialog = nullptr;
+}
+
+void UrgentPasswordExpiryNotificationDialog::GetDialogSize(
+ gfx::Size* size) const {
+ *size = FitSizeToDisplay(kMaxNotificationDialogWidth,
+ kMaxNotificationDialogHeight);
+}
+
+void UrgentPasswordExpiryNotificationDialog::AdjustWidgetInitParams(
+ views::Widget::InitParams* params) {
+ params->type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS;
+}
+
+ui::ModalType UrgentPasswordExpiryNotificationDialog::GetDialogModalType()
+ const {
+ return ui::ModalType::MODAL_TYPE_SYSTEM;
+}
+
+// static
+void UrgentPasswordExpiryNotificationDialog::Show() {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ if (g_notification_dialog) {
+ g_notification_dialog->Focus();
+ return;
+ }
+ g_notification_dialog = new UrgentPasswordExpiryNotificationDialog();
+ g_notification_dialog->ShowSystemDialog();
+}
+
+// static
+void UrgentPasswordExpiryNotificationDialog::Dismiss() {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ if (g_notification_dialog)
+ g_notification_dialog->Close();
+}
+
+UrgentPasswordExpiryNotificationUI::UrgentPasswordExpiryNotificationUI(
+ content::WebUI* web_ui)
+ : ui::WebDialogUI(web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+ PrefService* prefs = profile->GetPrefs();
+ CHECK(prefs->GetBoolean(prefs::kSamlInSessionPasswordChangeEnabled));
+
+ content::WebUIDataSource* source = content::WebUIDataSource::Create(
+ chrome::kChromeUIUrgentPasswordExpiryNotificationHost);
+
+ SamlPasswordAttributes attrs = SamlPasswordAttributes::LoadFromPrefs(prefs);
+ if (attrs.has_expiration_time()) {
+ const base::Time expiration_time = attrs.expiration_time();
+ source->AddString("initialTitle", PasswordExpiryNotification::GetTitleText(
+ expiration_time - base::Time::Now()));
+ source->AddString("expirationTime",
+ base::NumberToString(expiration_time.ToJsTime()));
+ }
+
+ static constexpr LocalizedString kLocalizedStrings[] = {
+ {"body", IDS_PASSWORD_EXPIRY_CALL_TO_ACTION_CRITICAL},
+ {"button", IDS_OK}};
+ AddLocalizedStringsBulk(source, kLocalizedStrings,
+ base::size(kLocalizedStrings));
+
+ source->SetJsonPath("strings.js");
+ source->SetDefaultResource(IDR_URGENT_PASSWORD_EXPIRY_NOTIFICATION_HTML);
+ source->AddResourcePath("urgent_password_expiry_notification.js",
+ IDR_URGENT_PASSWORD_EXPIRY_NOTIFICATION_JS);
+
+ web_ui->AddMessageHandler(
+ std::make_unique<UrgentPasswordExpiryNotificationHandler>());
+
+ content::WebUIDataSource::Add(profile, source);
+}
+
+UrgentPasswordExpiryNotificationUI::~UrgentPasswordExpiryNotificationUI() =
+ default;
+
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h
new file mode 100644
index 00000000000..d1b2cb7e877
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h
@@ -0,0 +1,113 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_UI_H_
+
+#include "base/macros.h"
+#include "base/strings/string16.h"
+#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h"
+#include "ui/web_dialogs/web_dialog_ui.h"
+
+namespace chromeos {
+
+// System dialog wrapping chrome:://password-change
+class PasswordChangeDialog : public SystemWebDialogDelegate {
+ public:
+ static void Show();
+ static void Dismiss();
+
+ protected:
+ PasswordChangeDialog();
+ ~PasswordChangeDialog() override;
+
+ // ui::WebDialogDelegate:
+ void GetDialogSize(gfx::Size* size) const override;
+ void AdjustWidgetInitParams(views::Widget::InitParams* params) override;
+ ui::ModalType GetDialogModalType() const override;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(PasswordChangeDialog);
+};
+
+// For chrome:://password-change
+class PasswordChangeUI : public ui::WebDialogUI {
+ public:
+ explicit PasswordChangeUI(content::WebUI* web_ui);
+ ~PasswordChangeUI() override;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(PasswordChangeUI);
+};
+
+// System dialog wrapping chrome://confirm-password-change
+class ConfirmPasswordChangeDialog : public SystemWebDialogDelegate {
+ public:
+ static void Show(const std::string& scraped_old_password,
+ const std::string& scraped_new_password,
+ bool show_spinner_initially);
+ static void Dismiss();
+
+ protected:
+ ConfirmPasswordChangeDialog(const std::string& scraped_old_password,
+ const std::string& scraped_new_password,
+ bool show_spinner_initially);
+ ~ConfirmPasswordChangeDialog() override;
+
+ // ui::WebDialogDelegate:
+ void GetDialogSize(gfx::Size* size) const override;
+ std::string GetDialogArgs() const override;
+ void AdjustWidgetInitParams(views::Widget::InitParams* params) override;
+ ui::ModalType GetDialogModalType() const override;
+
+ private:
+ std::string scraped_old_password_;
+ std::string scraped_new_password_;
+ bool show_spinner_initially_ = false;
+
+ DISALLOW_COPY_AND_ASSIGN(ConfirmPasswordChangeDialog);
+};
+
+// For chrome:://confirm-password-change
+class ConfirmPasswordChangeUI : public ui::WebDialogUI {
+ public:
+ explicit ConfirmPasswordChangeUI(content::WebUI* web_ui);
+ ~ConfirmPasswordChangeUI() override;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ConfirmPasswordChangeUI);
+};
+
+// System dialog wrapping chrome://urgent-password-expiry-notification
+class UrgentPasswordExpiryNotificationDialog : public SystemWebDialogDelegate {
+ public:
+ static void Show();
+ static void Dismiss();
+
+ protected:
+ UrgentPasswordExpiryNotificationDialog();
+ ~UrgentPasswordExpiryNotificationDialog() override;
+
+ // ui::WebDialogDelegate:
+ void GetDialogSize(gfx::Size* size) const override;
+ void AdjustWidgetInitParams(views::Widget::InitParams* params) override;
+ ui::ModalType GetDialogModalType() const override;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(UrgentPasswordExpiryNotificationDialog);
+};
+
+// For chrome:://urgent-password-expiry-notification
+class UrgentPasswordExpiryNotificationUI : public ui::WebDialogUI {
+ public:
+ explicit UrgentPasswordExpiryNotificationUI(content::WebUI* web_ui);
+ ~UrgentPasswordExpiryNotificationUI() override;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(UrgentPasswordExpiryNotificationUI);
+};
+
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_PASSWORD_CHANGE_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.cc
new file mode 100644
index 00000000000..627e1577cf9
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.cc
@@ -0,0 +1,58 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.h"
+
+#include <string>
+
+#include "base/logging.h"
+#include "base/macros.h"
+#include "base/values.h"
+#include "chrome/browser/chromeos/login/saml/in_session_password_change_manager.h"
+#include "chrome/browser/chromeos/login/saml/password_expiry_notification.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/common/pref_names.h"
+#include "chromeos/login/auth/saml_password_attributes.h"
+#include "components/prefs/pref_service.h"
+#include "components/user_manager/user_manager.h"
+
+namespace chromeos {
+
+UrgentPasswordExpiryNotificationHandler::
+ UrgentPasswordExpiryNotificationHandler() = default;
+
+UrgentPasswordExpiryNotificationHandler::
+ ~UrgentPasswordExpiryNotificationHandler() = default;
+
+void UrgentPasswordExpiryNotificationHandler::HandleContinue(
+ const base::ListValue* params) {
+ InSessionPasswordChangeManager::Get()->StartInSessionPasswordChange();
+}
+
+void UrgentPasswordExpiryNotificationHandler::HandleGetTitleText(
+ const base::ListValue* params) {
+ const std::string callback_id = params->GetList()[0].GetString();
+ const int ms_until_expiry = params->GetList()[1].GetInt();
+
+ const base::string16 title = PasswordExpiryNotification::GetTitleText(
+ base::TimeDelta::FromMilliseconds(ms_until_expiry));
+
+ AllowJavascript();
+ ResolveJavascriptCallback(base::Value(callback_id), base::Value(title));
+}
+
+void UrgentPasswordExpiryNotificationHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "continue", base::BindRepeating(
+ &UrgentPasswordExpiryNotificationHandler::HandleContinue,
+ weak_factory_.GetWeakPtr()));
+ web_ui()->RegisterMessageCallback(
+ "getTitleText",
+ base::BindRepeating(
+ &UrgentPasswordExpiryNotificationHandler::HandleGetTitleText,
+ weak_factory_.GetWeakPtr()));
+}
+
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.h b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.h
new file mode 100644
index 00000000000..06c83b15712
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/urgent_password_expiry_notification_handler.h
@@ -0,0 +1,37 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_URGENT_PASSWORD_EXPIRY_NOTIFICATION_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_URGENT_PASSWORD_EXPIRY_NOTIFICATION_HANDLER_H_
+
+#include "base/memory/weak_ptr.h"
+#include "base/values.h"
+#include "content/public/browser/web_ui_message_handler.h"
+
+namespace chromeos {
+
+class UrgentPasswordExpiryNotificationHandler
+ : public content::WebUIMessageHandler {
+ public:
+ UrgentPasswordExpiryNotificationHandler();
+ ~UrgentPasswordExpiryNotificationHandler() override;
+
+ // content::WebUIMessageHandler:
+ void RegisterMessages() override;
+
+ // User taps the button and agrees to change their password.
+ void HandleContinue(const base::ListValue* params);
+
+ // Need to update title to show new time remaining until password expiry.
+ void HandleGetTitleText(const base::ListValue* params);
+
+ private:
+ base::WeakPtrFactory<UrgentPasswordExpiryNotificationHandler> weak_factory_{
+ this};
+ DISALLOW_COPY_AND_ASSIGN(UrgentPasswordExpiryNotificationHandler);
+};
+
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_IN_SESSION_PASSWORD_CHANGE_URGENT_PASSWORD_EXPIRY_NOTIFICATION_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_handler_chromeos.cc
deleted file mode 100644
index 6ff7c112f23..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_handler_chromeos.cc
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/chromeos/insession_password_change_handler_chromeos.h"
-
-#include <string>
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/values.h"
-#include "chrome/browser/chromeos/login/auth/chrome_cryptohome_authenticator.h"
-#include "chrome/browser/chromeos/login/saml/saml_password_expiry_notification.h"
-#include "chrome/browser/chromeos/profiles/profile_helper.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/common/pref_names.h"
-#include "chromeos/login/auth/saml_password_attributes.h"
-#include "components/prefs/pref_service.h"
-#include "components/user_manager/user_manager.h"
-
-namespace chromeos {
-
-InSessionPasswordChangeHandler::InSessionPasswordChangeHandler(
- const std::string& password_change_url)
- : password_change_url_(password_change_url) {}
-InSessionPasswordChangeHandler::~InSessionPasswordChangeHandler() = default;
-
-void InSessionPasswordChangeHandler::HandleInitialize(
- const base::ListValue* value) {
- Profile* profile = Profile::FromWebUI(web_ui());
- CHECK(profile->GetPrefs()->GetBoolean(
- prefs::kSamlInSessionPasswordChangeEnabled));
-
- AllowJavascript();
- base::Value params(base::Value::Type::DICTIONARY);
- if (password_change_url_.empty()) {
- LOG(ERROR) << "Password change url is empty";
- return;
- }
- params.SetKey("passwordChangeUrl", base::Value(password_change_url_));
- const user_manager::User* user =
- ProfileHelper::Get()->GetUserByProfile(profile);
- if (user)
- params.SetKey("userName", base::Value(user->GetDisplayEmail()));
- CallJavascriptFunction("insession.password.change.loadAuthExtension", params);
-}
-
-void InSessionPasswordChangeHandler::HandleChangePassword(
- const base::ListValue* params) {
- const base::Value& old_passwords = params->GetList()[0];
- const base::Value& new_passwords = params->GetList()[1];
- VLOG(4) << "Scraped " << old_passwords.GetList().size() << " old passwords";
- VLOG(4) << "Scraped " << new_passwords.GetList().size() << " new passwords";
- user_manager::User* user =
- ProfileHelper::Get()->GetUserByProfile(Profile::FromWebUI(web_ui()));
- user_manager::UserManager::Get()->SaveForceOnlineSignin(user->GetAccountId(),
- true);
- if (new_passwords.GetList().size() == 1 &&
- old_passwords.GetList().size() > 0) {
- UserContext user_context(*user);
- user_context.SetKey(Key(new_passwords.GetList()[0].GetString()));
- authenticator_ = new ChromeCryptohomeAuthenticator(this);
- authenticator_->MigrateKey(user_context,
- old_passwords.GetList()[0].GetString());
- }
-}
-
-void InSessionPasswordChangeHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "initialize",
- base::BindRepeating(&InSessionPasswordChangeHandler::HandleInitialize,
- weak_factory_.GetWeakPtr()));
- web_ui()->RegisterMessageCallback(
- "changePassword",
- base::BindRepeating(&InSessionPasswordChangeHandler::HandleChangePassword,
- weak_factory_.GetWeakPtr()));
-}
-
-void InSessionPasswordChangeHandler::OnAuthSuccess(
- const UserContext& user_context) {
- VLOG(3) << "Cryptohome password is changed.";
- user_manager::UserManager::Get()->SaveForceOnlineSignin(
- user_context.GetAccountId(), false);
- authenticator_.reset();
-
- // Clear expiration time from prefs so that we don't keep nagging the user to
- // change password (until the SAML provider tells us a new expiration time).
- Profile* profile = Profile::FromWebUI(web_ui());
- SamlPasswordAttributes loaded =
- SamlPasswordAttributes::LoadFromPrefs(profile->GetPrefs());
- SamlPasswordAttributes(
- /*modified_time=*/base::Time::Now(), /*expiration_time=*/base::Time(),
- loaded.password_change_url())
- .SaveToPrefs(profile->GetPrefs());
- DismissSamlPasswordExpiryNotification(profile);
-}
-
-void InSessionPasswordChangeHandler::OnAuthFailure(const AuthFailure& error) {
- // TODO(rsorokin): Ask user for the old password
- VLOG(1) << "Failed to change cryptohome password: " << error.GetErrorString();
- authenticator_.reset();
-}
-
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_handler_chromeos.h b/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_handler_chromeos.h
deleted file mode 100644
index 97eb55ef0dd..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_handler_chromeos.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_INSESSION_PASSWORD_CHANGE_HANDLER_CHROMEOS_H_
-#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_INSESSION_PASSWORD_CHANGE_HANDLER_CHROMEOS_H_
-
-#include "base/memory/weak_ptr.h"
-#include "base/values.h"
-#include "chromeos/login/auth/auth_status_consumer.h"
-#include "chromeos/login/auth/cryptohome_authenticator.h"
-#include "content/public/browser/web_ui_message_handler.h"
-
-namespace chromeos {
-
-class InSessionPasswordChangeHandler : public content::WebUIMessageHandler,
- AuthStatusConsumer {
- public:
- explicit InSessionPasswordChangeHandler(
- const std::string& password_change_url);
- ~InSessionPasswordChangeHandler() override;
-
- // content::WebUIMessageHandler:
- void RegisterMessages() override;
-
- void HandleInitialize(const base::ListValue*);
- void HandleChangePassword(const base::ListValue* passwords);
-
- // AuthStatusConsumer:
- void OnAuthFailure(const AuthFailure& error) override;
- void OnAuthSuccess(const UserContext& user_context) override;
-
- private:
- const std::string password_change_url_;
- scoped_refptr<CryptohomeAuthenticator> authenticator_;
- base::WeakPtrFactory<InSessionPasswordChangeHandler> weak_factory_{this};
- DISALLOW_COPY_AND_ASSIGN(InSessionPasswordChangeHandler);
-};
-
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_INSESSION_PASSWORD_CHANGE_HANDLER_CHROMEOS_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_ui.cc
deleted file mode 100644
index 76cc7570a69..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_ui.cc
+++ /dev/null
@@ -1,135 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/chromeos/insession_password_change_ui.h"
-
-#include <memory>
-
-#include "base/bind.h"
-#include "base/command_line.h"
-#include "base/strings/utf_string_conversions.h"
-#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/chromeos/insession_password_change_handler_chromeos.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/common/webui_url_constants.h"
-#include "chrome/grit/browser_resources.h"
-#include "chrome/grit/generated_resources.h"
-#include "chromeos/constants/chromeos_switches.h"
-#include "chromeos/login/auth/saml_password_attributes.h"
-#include "components/prefs/pref_service.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/web_ui_data_source.h"
-#include "net/base/url_util.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/display/display.h"
-#include "ui/display/screen.h"
-#include "ui/strings/grit/ui_strings.h"
-
-namespace chromeos {
-
-namespace {
-
-PasswordChangeDialog* g_dialog = nullptr;
-
-std::string GetPasswordChangeUrl(Profile* profile) {
- if (base::CommandLine::ForCurrentProcess()->HasSwitch(
- switches::kSamlPasswordChangeUrl)) {
- return base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
- switches::kSamlPasswordChangeUrl);
- }
-
- const policy::UserCloudPolicyManagerChromeOS* user_cloud_policy_manager =
- profile->GetUserCloudPolicyManagerChromeOS();
- if (user_cloud_policy_manager) {
- const enterprise_management::PolicyData* policy =
- user_cloud_policy_manager->core()->store()->policy();
- if (policy->has_change_password_uri()) {
- return policy->change_password_uri();
- }
- }
-
- return SamlPasswordAttributes::LoadFromPrefs(profile->GetPrefs())
- .password_change_url();
-}
-
-base::string16 GetManagementNotice(Profile* profile) {
- base::string16 host = base::UTF8ToUTF16(
- net::GetHostAndOptionalPort(GURL(GetPasswordChangeUrl(profile))));
- DCHECK(!host.empty());
- return l10n_util::GetStringFUTF16(IDS_LOGIN_SAML_PASSWORD_CHANGE_NOTICE,
- host);
-}
-
-constexpr int kMaxDialogWidth = 768;
-constexpr int kMaxDialogHeight = 640;
-
-gfx::Size GetPasswordChangeDialogSize() {
- const display::Display display =
- display::Screen::GetScreen()->GetPrimaryDisplay();
-
- gfx::Size display_size = display.size();
-
- if (display.rotation() == display::Display::ROTATE_90 ||
- display.rotation() == display::Display::ROTATE_270) {
- display_size = gfx::Size(display_size.height(), display_size.width());
- }
-
- display_size = gfx::Size(std::min(display_size.width(), kMaxDialogWidth),
- std::min(display_size.height(), kMaxDialogHeight));
-
- return display_size;
-}
-
-} // namespace
-
-PasswordChangeDialog::PasswordChangeDialog(const base::string16& title)
- : SystemWebDialogDelegate(GURL(chrome::kChromeUIPasswordChangeUrl), title) {
-}
-
-PasswordChangeDialog::~PasswordChangeDialog() {
- DCHECK_EQ(this, g_dialog);
- g_dialog = nullptr;
-}
-
-void PasswordChangeDialog::GetDialogSize(gfx::Size* size) const {
- *size = GetPasswordChangeDialogSize();
-}
-
-void PasswordChangeDialog::Show(Profile* profile) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- if (g_dialog) {
- g_dialog->Focus();
- return;
- }
- g_dialog = new PasswordChangeDialog(GetManagementNotice(profile));
- g_dialog->ShowSystemDialog();
-}
-
-InSessionPasswordChangeUI::InSessionPasswordChangeUI(content::WebUI* web_ui)
- : ui::WebDialogUI(web_ui) {
- Profile* profile = Profile::FromWebUI(web_ui);
- CHECK(profile->GetPrefs()->GetBoolean(
- prefs::kSamlInSessionPasswordChangeEnabled));
- content::WebUIDataSource* source =
- content::WebUIDataSource::Create(chrome::kChromeUIPasswordChangeHost);
-
- web_ui->AddMessageHandler(std::make_unique<InSessionPasswordChangeHandler>(
- GetPasswordChangeUrl(profile)));
-
- source->SetJsonPath("strings.js");
-
- source->SetDefaultResource(IDR_PASSWORD_CHANGE_HTML);
-
- source->AddResourcePath("password_change.css", IDR_PASSWORD_CHANGE_CSS);
- source->AddResourcePath("authenticator.js",
- IDR_PASSWORD_CHANGE_AUTHENTICATOR_JS);
- source->AddResourcePath("password_change.js", IDR_PASSWORD_CHANGE_JS);
-
- content::WebUIDataSource::Add(profile, source);
-}
-
-InSessionPasswordChangeUI::~InSessionPasswordChangeUI() = default;
-
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_ui.h b/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_ui.h
deleted file mode 100644
index 32007ce3973..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/insession_password_change_ui.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_INSESSION_PASSWORD_CHANGE_UI_H_
-#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_INSESSION_PASSWORD_CHANGE_UI_H_
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h"
-#include "ui/web_dialogs/web_dialog_ui.h"
-
-class Profile;
-
-namespace chromeos {
-
-class PasswordChangeDialog : public SystemWebDialogDelegate {
- public:
- static void Show(Profile* profile);
-
- protected:
- explicit PasswordChangeDialog(const base::string16& title);
- ~PasswordChangeDialog() override;
-
- // ui::WebDialogDelegate:
- void GetDialogSize(gfx::Size* size) const override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(PasswordChangeDialog);
-};
-
-// For chrome:://password-change
-class InSessionPasswordChangeUI : public ui::WebDialogUI {
- public:
- explicit InSessionPasswordChangeUI(content::WebUI* web_ui);
- ~InSessionPasswordChangeUI() override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(InSessionPasswordChangeUI);
-};
-
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_INSESSION_PASSWORD_CHANGE_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc
index 562a67ac3b8..b1faef7f2de 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.cc
@@ -16,9 +16,11 @@
#include "chromeos/network/network_state.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/network_util.h"
+#include "chromeos/services/network_config/public/mojom/constants.mojom.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/service_manager/public/cpp/connector.h"
#include "ui/base/l10n/l10n_util.h"
namespace chromeos {
@@ -133,7 +135,7 @@ std::string InternetDetailDialog::GetDialogArgs() const {
// InternetDetailDialogUI
InternetDetailDialogUI::InternetDetailDialogUI(content::WebUI* web_ui)
- : ui::WebDialogUI(web_ui) {
+ : ui::MojoWebDialogUI(web_ui) {
content::WebUIDataSource* source = content::WebUIDataSource::Create(
chrome::kChromeUIInternetDetailDialogHost);
source->AddBoolean("showTechnologyBadge",
@@ -150,8 +152,20 @@ InternetDetailDialogUI::InternetDetailDialogUI(content::WebUI* web_ui)
IDR_INTERNET_DETAIL_DIALOG_JS);
#endif
content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source);
+
+ // Add Mojo bindings to this WebUI so that Mojo calls can occur in JavaScript.
+ AddHandlerToRegistry(base::BindRepeating(
+ &InternetDetailDialogUI::BindCrosNetworkConfig, base::Unretained(this)));
}
InternetDetailDialogUI::~InternetDetailDialogUI() {}
+void InternetDetailDialogUI::BindCrosNetworkConfig(
+ chromeos::network_config::mojom::CrosNetworkConfigRequest request) {
+ content::BrowserContext::GetConnectorFor(
+ web_ui()->GetWebContents()->GetBrowserContext())
+ ->BindInterface(chromeos::network_config::mojom::kServiceName,
+ std::move(request));
+}
+
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.h
index 27d483a666e..eec6c4d9a98 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/internet_detail_dialog.h
@@ -7,6 +7,7 @@
#include "base/macros.h"
#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h"
+#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" // nogncheck
#include "ui/web_dialogs/web_dialog_ui.h"
namespace chromeos {
@@ -43,12 +44,15 @@ class InternetDetailDialog : public SystemWebDialogDelegate {
// A WebUI to host a subset of the network details page to allow setting of
// proxy, IP address, and nameservers in the login screen.
-class InternetDetailDialogUI : public ui::WebDialogUI {
+class InternetDetailDialogUI : public ui::MojoWebDialogUI {
public:
explicit InternetDetailDialogUI(content::WebUI* web_ui);
~InternetDetailDialogUI() override;
private:
+ void BindCrosNetworkConfig(
+ chromeos::network_config::mojom::CrosNetworkConfigRequest request);
+
DISALLOW_COPY_AND_ASSIGN(InternetDetailDialogUI);
};
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 cf4abce8683..29601c934c8 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
@@ -28,10 +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/public/identity_manager/identity_manager.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 =
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 ae12b9083da..622537cfdff 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc
@@ -15,9 +15,9 @@
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
-#include "chrome/browser/ui/ash/assistant/assistant_pref_util.h"
#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_utils.h"
#include "chrome/grit/generated_resources.h"
+#include "chromeos/services/assistant/public/cpp/assistant_prefs.h"
#include "chromeos/services/assistant/public/features.h"
#include "chromeos/services/assistant/public/mojom/constants.mojom.h"
#include "chromeos/services/assistant/public/proto/settings_ui.pb.h"
@@ -141,8 +141,6 @@ void AssistantOptInFlowScreenHandler::RegisterMessages() {
&AssistantOptInFlowScreenHandler::HandleGetMoreScreenShown);
AddCallback("login.AssistantOptInFlowScreen.LoadingScreen.timeout",
&AssistantOptInFlowScreenHandler::HandleLoadingTimeout);
- AddCallback("login.AssistantOptInFlowScreen.hotwordResult",
- &AssistantOptInFlowScreenHandler::HandleHotwordResult);
AddCallback("login.AssistantOptInFlowScreen.flowFinished",
&AssistantOptInFlowScreenHandler::HandleFlowFinished);
AddCallback("login.AssistantOptInFlowScreen.initialized",
@@ -203,12 +201,19 @@ void AssistantOptInFlowScreenHandler::OnSpeakerIdEnrollmentFailure() {
RecordAssistantOptInStatus(VOICE_MATCH_ENROLLMENT_ERROR);
CallJS("login.AssistantOptInFlowScreen.onVoiceMatchUpdate",
base::Value("failure"));
- LOG(ERROR) << "Speaker ID enrollmend failure.";
+ LOG(ERROR) << "Speaker ID enrollment failure.";
}
void AssistantOptInFlowScreenHandler::SetupAssistantConnection() {
- // Make sure enable Assistant service since we need it during the flow.
PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
+
+ // If Assistant is disabled by domain admin, end the flow.
+ if (prefs->GetBoolean(assistant::prefs::kAssistantDisabledByPolicy)) {
+ HandleFlowFinished();
+ return;
+ }
+
+ // Make sure enable Assistant service since we need it during the flow.
prefs->SetBoolean(arc::prefs::kVoiceInteractionEnabled, true);
if (arc::VoiceInteractionControllerClient::Get()->voice_interaction_state() ==
@@ -236,8 +241,8 @@ void AssistantOptInFlowScreenHandler::OnActivityControlOptInResult(
weak_factory_.GetWeakPtr()));
} else {
RecordAssistantOptInStatus(ACTIVITY_CONTROL_SKIPPED);
- ::assistant::prefs::SetConsentStatus(profile->GetPrefs(),
- ash::mojom::ConsentStatus::kUnknown);
+ profile->GetPrefs()->SetInteger(assistant::prefs::kAssistantConsentStatus,
+ assistant::prefs::ConsentStatus::kUnknown);
HandleFlowFinished();
}
}
@@ -329,10 +334,19 @@ void AssistantOptInFlowScreenHandler::OnGetSettingsResponse(
if (settings_ui.has_gaia_user_context_ui()) {
auto gaia_user_context_ui = settings_ui.gaia_user_context_ui();
- if (gaia_user_context_ui.waa_disabled_by_dasher_domain() ||
- gaia_user_context_ui.assistant_disabled_by_dasher_domain()) {
- DVLOG(1) << "Assistant/web & app activity is disabled by dasher domain. "
- "Skip Assistant opt-in flow.";
+ if (gaia_user_context_ui.assistant_disabled_by_dasher_domain()) {
+ DVLOG(1) << "Assistant is disabled by domain policy. Skip Assistant "
+ "opt-in flow.";
+ PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
+ prefs->SetBoolean(assistant::prefs::kAssistantDisabledByPolicy, true);
+ prefs->SetBoolean(arc::prefs::kVoiceInteractionEnabled, false);
+ HandleFlowFinished();
+ return;
+ }
+
+ if (gaia_user_context_ui.waa_disabled_by_dasher_domain()) {
+ DVLOG(1) << "Web & app activity is disabled by domain policy. Skip "
+ "Assistant opt-in flow.";
HandleFlowFinished();
return;
}
@@ -361,9 +375,10 @@ void AssistantOptInFlowScreenHandler::OnGetSettingsResponse(
settings_ui.consent_flow_ui().consent_status() ==
assistant::ConsentFlowUi_ConsentStatus_ASK_FOR_CONSENT;
- ::assistant::prefs::SetConsentStatus(
- prefs, consented ? ash::mojom::ConsentStatus::kActivityControlAccepted
- : ash::mojom::ConsentStatus::kUnknown);
+ prefs->SetInteger(
+ assistant::prefs::kAssistantConsentStatus,
+ consented ? assistant::prefs::ConsentStatus::kActivityControlAccepted
+ : assistant::prefs::ConsentStatus::kUnknown);
} else {
AddSettingZippy("settings",
CreateZippyData(activity_control_ui.setting_zippy()));
@@ -402,9 +417,9 @@ void AssistantOptInFlowScreenHandler::OnGetSettingsResponse(
// Pass string constants dictionary.
auto dictionary = GetSettingsUiStrings(settings_ui, activity_control_needed_);
- const bool voice_match_enabled =
- IsVoiceMatchEnabled(ProfileManager::GetActiveUserProfile()->GetPrefs());
- dictionary.SetKey("voiceMatchEnabled", base::Value(voice_match_enabled));
+ PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
+ dictionary.SetKey("voiceMatchEnforcedOff",
+ base::Value(IsVoiceMatchEnforcedOff(prefs)));
ReloadContent(dictionary);
// Now that screen's content has been reloaded, skip screens that can be
@@ -422,7 +437,7 @@ void AssistantOptInFlowScreenHandler::OnGetSettingsResponse(
// If voice match is enabled, the screen that follows third party disclosure
// is the "voice match" screen, not "get more" screen.
- if (skip_get_more && !voice_match_enabled)
+ if (skip_get_more && IsVoiceMatchEnforcedOff(prefs))
ShowNextScreen();
}
@@ -439,8 +454,9 @@ void AssistantOptInFlowScreenHandler::OnUpdateSettingsResponse(
} else if (activity_control_needed_) {
activity_control_needed_ = false;
PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
- ::assistant::prefs::SetConsentStatus(
- prefs, ash::mojom::ConsentStatus::kActivityControlAccepted);
+ prefs->SetInteger(
+ assistant::prefs::kAssistantConsentStatus,
+ assistant::prefs::ConsentStatus::kActivityControlAccepted);
}
}
@@ -450,12 +466,6 @@ void AssistantOptInFlowScreenHandler::OnUpdateSettingsResponse(
// TODO(updowndta): Handle email optin update failure.
LOG(ERROR) << "Email OptIn udpate error.";
}
- // Update hotword will cause Assistant restart. In order to make sure email
- // optin request is successfully sent to server, update the hotword after
- // email optin result has been received.
- PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
- prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled,
- enable_hotword_);
HandleFlowFinished();
return;
}
@@ -490,9 +500,6 @@ void AssistantOptInFlowScreenHandler::HandleVoiceMatchScreenUserAction(
const std::string& action) {
PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
- if (!IsVoiceMatchEnabled(prefs))
- return;
-
if (action == kVoiceMatchDone) {
RecordAssistantOptInStatus(VOICE_MATCH_ENROLLMENT_DONE);
voice_match_enrollment_done_ = true;
@@ -547,26 +554,15 @@ void AssistantOptInFlowScreenHandler::HandleLoadingTimeout() {
++loading_timeout_counter_;
}
-void AssistantOptInFlowScreenHandler::HandleHotwordResult(bool enable_hotword) {
- enable_hotword_ = enable_hotword;
-
- if (!email_optin_needed_) {
- // No need to send email optin result. Safe to update hotword pref and
- // restart Assistant here.
- PrefService* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
- prefs->SetBoolean(arc::prefs::kVoiceInteractionHotwordEnabled,
- enable_hotword);
- }
-}
-
void AssistantOptInFlowScreenHandler::HandleFlowFinished() {
auto* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
- if (!prefs->GetUserPrefValue(::assistant::prefs::kAssistantConsentStatus)) {
+ if (!prefs->GetUserPrefValue(assistant::prefs::kAssistantConsentStatus)) {
// Set consent status to unknown if user consent is needed but not provided.
- ::assistant::prefs::SetConsentStatus(
- prefs, activity_control_needed_
- ? ash::mojom::ConsentStatus::kUnknown
- : ash::mojom::ConsentStatus::kActivityControlAccepted);
+ prefs->SetInteger(
+ assistant::prefs::kAssistantConsentStatus,
+ activity_control_needed_
+ ? assistant::prefs::ConsentStatus::kUnknown
+ : assistant::prefs::ConsentStatus::kActivityControlAccepted);
}
UMA_HISTOGRAM_EXACT_LINEAR("Assistant.OptInFlow.LoadingTimeoutCount",
@@ -579,6 +575,12 @@ void AssistantOptInFlowScreenHandler::HandleFlowFinished() {
void AssistantOptInFlowScreenHandler::HandleFlowInitialized(
const int flow_type) {
+ auto* prefs = ProfileManager::GetActiveUserProfile()->GetPrefs();
+ if (!prefs->GetBoolean(arc::prefs::kVoiceInteractionEnabled)) {
+ HandleFlowFinished();
+ return;
+ }
+
initialized_ = true;
if (on_initialized_)
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 ad2ac660f7e..8a24e879ca3 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
@@ -124,7 +124,6 @@ class AssistantOptInFlowScreenHandler
void HandleVoiceMatchScreenShown();
void HandleGetMoreScreenShown();
void HandleLoadingTimeout();
- void HandleHotwordResult(bool enable_hotword);
void HandleFlowFinished();
void HandleFlowInitialized(const int flow_type);
@@ -147,9 +146,6 @@ class AssistantOptInFlowScreenHandler
// Whether email optin is needed for user.
bool email_optin_needed_ = false;
- // Whether user chose to enable hotword.
- bool enable_hotword_ = true;
-
// Whether the use has completed voice match enrollment.
bool voice_match_enrollment_done_ = false;
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 15dc59bff2c..5326b0b1233 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
@@ -7,8 +7,8 @@
#include <type_traits>
#include "ash/public/cpp/ash_features.h"
+#include "ash/public/cpp/event_rewriter_controller.h"
#include "ash/public/interfaces/constants.mojom.h"
-#include "ash/public/interfaces/event_rewriter_controller.mojom.h"
#include "ash/shell.h"
#include "base/bind.h"
#include "base/command_line.h"
@@ -20,16 +20,15 @@
#include "chrome/browser/chromeos/login/configuration_keys.h"
#include "chrome/browser/chromeos/login/demo_mode/demo_session.h"
#include "chrome/browser/chromeos/login/demo_mode/demo_setup_controller.h"
-#include "chrome/browser/chromeos/login/enrollment/auto_enrollment_controller.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/lock/screen_locker.h"
+#include "chrome/browser/chromeos/login/screens/reset_screen.h"
#include "chrome/browser/chromeos/login/ui/login_display_host.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h"
#include "chrome/browser/chromeos/system/input_device_settings.h"
#include "chrome/browser/chromeos/system/timezone_resolver_manager.h"
-#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/keyboard/chrome_keyboard_controller_client.h"
@@ -51,12 +50,11 @@
#include "components/prefs/pref_service.h"
#include "components/strings/grit/components_strings.h"
#include "components/version_info/version_info.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.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"
@@ -104,7 +102,7 @@ CoreOobeHandler::CoreOobeHandler(JSCallsContainer* js_calls_container)
tablet_mode_client->AddObserver(this);
// |connector| may be null in tests.
- auto* connector = ash_util::GetServiceManagerConnector();
+ auto* connector = content::GetSystemConnector();
if (connector) {
connector->BindInterface(ash::mojom::kServiceName,
&cros_display_config_ptr_);
@@ -323,13 +321,7 @@ void CoreOobeHandler::HandleUpdateCurrentScreen(
const std::string& screen_name) {
const OobeScreenId screen(screen_name);
GetOobeUI()->CurrentScreenChanged(screen);
-
- content::ServiceManagerConnection* connection =
- content::ServiceManagerConnection::GetForProcess();
- ash::mojom::EventRewriterControllerPtr event_rewriter_controller_ptr;
- connection->GetConnector()->BindInterface(ash::mojom::kServiceName,
- &event_rewriter_controller_ptr);
- event_rewriter_controller_ptr->SetArrowToTabRewritingEnabled(
+ ash::EventRewriterController::Get()->SetArrowToTabRewritingEnabled(
screen == EulaView::kScreenId);
}
@@ -414,42 +406,25 @@ void CoreOobeHandler::HandleSkipToUpdateForTesting() {
}
void CoreOobeHandler::HandleToggleResetScreen() {
- // Powerwash is generally not available on enterprise devices. First, check
- // the common case of a correctly enrolled device.
- if (g_browser_process->platform_part()
- ->browser_policy_connector_chromeos()
- ->IsEnterpriseManaged()) {
- // Powerwash is only available if allowed by the admin specifically for the
- // purpose of installing a TPM firmware update.
- tpm_firmware_update::GetAvailableUpdateModes(
- base::BindOnce([](const std::set<tpm_firmware_update::Mode>& modes) {
- using tpm_firmware_update::Mode;
- for (Mode mode : {Mode::kPowerwash, Mode::kCleanup}) {
- if (modes.count(mode) == 0)
- continue;
-
- // Force the TPM firmware update option to be enabled.
- g_browser_process->local_state()->SetInteger(
- prefs::kFactoryResetTPMFirmwareUpdateMode,
- static_cast<int>(mode));
- LaunchResetScreen();
- return;
- }
- }),
- base::TimeDelta());
- return;
- }
+ base::OnceCallback<void(bool, base::Optional<tpm_firmware_update::Mode>)>
+ callback =
+ base::BindOnce(&CoreOobeHandler::HandleToggleResetScreenCallback,
+ weak_ptr_factory_.GetWeakPtr());
+ ResetScreen::CheckIfPowerwashAllowed(std::move(callback));
+}
- // Devices that are still in OOBE may be subject to forced re-enrollment (FRE)
- // and thus pending for enterprise management. These should not be allowed to
- // powerwash either. Note that taking consumer device ownership has the side
- // effect of dropping the FRE requirement if it was previously in effect.
- const AutoEnrollmentController::FRERequirement requirement =
- AutoEnrollmentController::GetFRERequirement();
- if (requirement !=
- AutoEnrollmentController::FRERequirement::kExplicitlyRequired) {
- LaunchResetScreen();
+void CoreOobeHandler::HandleToggleResetScreenCallback(
+ bool is_reset_allowed,
+ base::Optional<tpm_firmware_update::Mode> tpm_firmware_update_mode) {
+ if (!is_reset_allowed)
+ return;
+ if (tpm_firmware_update_mode.has_value()) {
+ // Force the TPM firmware update option to be enabled.
+ g_browser_process->local_state()->SetInteger(
+ prefs::kFactoryResetTPMFirmwareUpdateMode,
+ static_cast<int>(tpm_firmware_update_mode.value()));
}
+ LaunchResetScreen();
}
void CoreOobeHandler::HandleEnableDebuggingScreen() {
@@ -488,18 +463,11 @@ void CoreOobeHandler::UpdateA11yState() {
"enableExperimentalA11yFeatures",
base::CommandLine::ForCurrentProcess()->HasSwitch(
::switches::kEnableExperimentalAccessibilityFeatures));
- if (!features::IsMultiProcessMash()) {
- DCHECK(MagnificationManager::Get());
- a11y_info.SetBoolean("screenMagnifierEnabled",
- MagnificationManager::Get()->IsMagnifierEnabled());
- a11y_info.SetBoolean(
- "dockedMagnifierEnabled",
- MagnificationManager::Get()->IsDockedMagnifierEnabled());
- } else {
- // TODO: get MagnificationManager working with mash.
- // https://crbug.com/817157
- NOTIMPLEMENTED_LOG_ONCE();
- }
+ DCHECK(MagnificationManager::Get());
+ a11y_info.SetBoolean("screenMagnifierEnabled",
+ MagnificationManager::Get()->IsMagnifierEnabled());
+ a11y_info.SetBoolean("dockedMagnifierEnabled",
+ MagnificationManager::Get()->IsDockedMagnifierEnabled());
a11y_info.SetBoolean("virtualKeyboardEnabled",
AccessibilityManager::Get()->IsVirtualKeyboardEnabled());
CallJS("cr.ui.Oobe.refreshA11yInfo", a11y_info);
@@ -561,13 +529,9 @@ void CoreOobeHandler::UpdateDeviceRequisition() {
}
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()) {
- const bool is_keyboard_shown =
- ChromeKeyboardControllerClient::Get()->is_keyboard_visible();
- SetVirtualKeyboardShown(is_keyboard_shown);
- }
+ const bool is_keyboard_shown =
+ ChromeKeyboardControllerClient::Get()->is_keyboard_visible();
+ SetVirtualKeyboardShown(is_keyboard_shown);
}
void CoreOobeHandler::OnTabletModeToggled(bool enabled) {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h
index 41232f4a2f3..cb7db18c545 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h
@@ -13,12 +13,14 @@
#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
+#include "base/optional.h"
#include "base/values.h"
#include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
#include "chrome/browser/chromeos/login/demo_mode/demo_mode_detector.h"
#include "chrome/browser/chromeos/login/help_app_launcher.h"
#include "chrome/browser/chromeos/login/oobe_configuration.h"
#include "chrome/browser/chromeos/login/version_info_updater.h"
+#include "chrome/browser/chromeos/tpm_firmware_update.h"
#include "chrome/browser/ui/ash/tablet_mode_client_observer.h"
#include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h"
#include "ui/events/event_source.h"
@@ -177,6 +179,12 @@ class CoreOobeHandler : public BaseWebUIHandler,
// |demo_config|.
void HandleStartDemoModeSetupForTesting(const std::string& demo_config);
+ // Shows the reset screen if |is_reset_allowed| and updates the
+ // tpm_firmware_update in settings.
+ void HandleToggleResetScreenCallback(
+ bool is_reset_allowed,
+ base::Optional<tpm_firmware_update::Mode> tpm_firmware_update_mode);
+
// When keyboard_utils.js arrow key down event is reached, raise it
// to tab/shift-tab event.
void HandleRaiseTabKeyEvent(bool reverse);
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 638501b0a7f..ed23aaa3cda 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
@@ -39,7 +39,7 @@
#include "components/login/localized_values_builder.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/device/public/mojom/wake_lock_provider.mojom.h"
@@ -624,17 +624,14 @@ device::mojom::WakeLock* EncryptionMigrationScreenHandler::GetWakeLock() {
// Service manager connection might be not initialized in some testing
// contexts.
- if (!content::ServiceManagerConnection::GetForProcess())
+ if (!content::GetSystemConnector())
return wake_lock_.get();
- service_manager::Connector* connector =
- content::ServiceManagerConnection::GetForProcess()->GetConnector();
- DCHECK(connector);
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
device::mojom::WakeLockProviderPtr wake_lock_provider;
- connector->BindInterface(device::mojom::kServiceName,
- mojo::MakeRequest(&wake_lock_provider));
+ content::GetSystemConnector()->BindInterface(
+ device::mojom::kServiceName, mojo::MakeRequest(&wake_lock_provider));
wake_lock_provider->GetWakeLockWithoutContext(
device::mojom::WakeLockType::kPreventAppSuspension,
device::mojom::WakeLockReason::kOther,
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 f94c2671f9d..5c9688e360d 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
@@ -365,25 +365,19 @@ void EnrollmentScreenHandler::ShowAuthError(
const GoogleServiceAuthError& error) {
switch (error.state()) {
case GoogleServiceAuthError::NONE:
- case GoogleServiceAuthError::CAPTCHA_REQUIRED:
- case GoogleServiceAuthError::TWO_FACTOR:
case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS:
case GoogleServiceAuthError::REQUEST_CANCELED:
case GoogleServiceAuthError::UNEXPECTED_SERVICE_RESPONSE:
case GoogleServiceAuthError::SERVICE_ERROR:
- case GoogleServiceAuthError::WEB_LOGIN_REQUIRED:
ShowError(IDS_ENTERPRISE_ENROLLMENT_AUTH_FATAL_ERROR, false);
return;
case GoogleServiceAuthError::USER_NOT_SIGNED_UP:
- case GoogleServiceAuthError::ACCOUNT_DELETED:
- case GoogleServiceAuthError::ACCOUNT_DISABLED:
ShowError(IDS_ENTERPRISE_ENROLLMENT_AUTH_ACCOUNT_ERROR, true);
return;
case GoogleServiceAuthError::CONNECTION_FAILED:
case GoogleServiceAuthError::SERVICE_UNAVAILABLE:
ShowError(IDS_ENTERPRISE_ENROLLMENT_AUTH_NETWORK_ERROR, true);
return;
- case GoogleServiceAuthError::HOSTED_NOT_ALLOWED_DEPRECATED:
case GoogleServiceAuthError::NUM_STATES:
break;
}
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 df238a19d5d..bf674ae60fb 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
@@ -6,6 +6,7 @@
#include "base/bind.h"
#include "base/strings/string_number_conversions.h"
+#include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_utils.h"
#include "chrome/browser/chromeos/login/screens/fingerprint_setup_screen.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/profiles/profile.h"
@@ -14,7 +15,7 @@
#include "chrome/grit/generated_resources.h"
#include "components/login/localized_values_builder.h"
#include "components/prefs/pref_service.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "ui/base/l10n/l10n_util.h"
@@ -54,9 +55,8 @@ FingerprintSetupScreenHandler::FingerprintSetupScreenHandler(
: BaseScreenHandler(kScreenId, js_calls_container) {
set_user_acted_method_path("login.FingerprintSetupScreen.userActed");
- service_manager::Connector* connector =
- content::ServiceManagerConnection::GetForProcess()->GetConnector();
- connector->BindInterface(device::mojom::kServiceName, &fp_service_);
+ content::GetSystemConnector()->BindInterface(device::mojom::kServiceName,
+ &fp_service_);
device::mojom::FingerprintObserverPtr observer;
binding_.Bind(mojo::MakeRequest(&observer));
fp_service_->AddFingerprintObserver(std::move(observer));
@@ -68,8 +68,6 @@ void FingerprintSetupScreenHandler::DeclareLocalizedValues(
::login::LocalizedValuesBuilder* builder) {
builder->Add("setupFingerprintScreenTitle",
IDS_OOBE_FINGERPINT_SETUP_SCREEN_TITLE);
- builder->Add("setupFingerprintScreenDescription",
- IDS_OOBE_FINGERPINT_SETUP_SCREEN_SENSOR_DESCRIPTION);
builder->Add("skipFingerprintSetup",
IDS_OOBE_FINGERPINT_SETUP_SCREEN_BUTTON_SKIP);
builder->Add("fingerprintSetupLater",
@@ -92,6 +90,19 @@ void FingerprintSetupScreenHandler::DeclareLocalizedValues(
IDS_OOBE_FINGERPINT_SETUP_SCREEN_INSTRUCTION_MOVE_FINGER);
builder->Add("setupFingerprintScanTryAgain",
IDS_OOBE_FINGERPINT_SETUP_SCREEN_INSTRUCTION_TRY_AGAIN);
+ int description_id;
+ switch (quick_unlock::GetFingerprintLocation()) {
+ case quick_unlock::FingerprintLocation::TABLET_POWER_BUTTON:
+ description_id =
+ IDS_OOBE_FINGERPINT_SETUP_SCREEN_SENSOR_POWER_BUTTON_DESCRIPTION;
+ break;
+ case quick_unlock::FingerprintLocation::KEYBOARD_BOTTOM_RIGHT:
+ case quick_unlock::FingerprintLocation::KEYBOARD_TOP_RIGHT:
+ description_id =
+ IDS_OOBE_FINGERPINT_SETUP_SCREEN_SENSOR_GENERAL_DESCRIPTION;
+ break;
+ }
+ builder->Add("setupFingerprintScreenDescription", description_id);
}
void FingerprintSetupScreenHandler::RegisterMessages() {
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 15e03543fa2..7ea94468de3 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
@@ -16,6 +16,7 @@
#include "base/guid.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
+#include "base/memory/ref_counted.h"
#include "base/metrics/histogram_macros.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
@@ -54,9 +55,12 @@
#include "chrome/common/pref_names.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/installer/util/google_update_settings.h"
+#include "chromeos/constants/chromeos_features.h"
#include "chromeos/constants/chromeos_switches.h"
#include "chromeos/constants/devicetype.h"
#include "chromeos/dbus/util/version_loader.h"
+#include "chromeos/login/auth/challenge_response/cert_utils.h"
+#include "chromeos/login/auth/cryptohome_key_constants.h"
#include "chromeos/login/auth/saml_password_attributes.h"
#include "chromeos/login/auth/user_context.h"
#include "chromeos/settings/cros_settings_names.h"
@@ -73,6 +77,7 @@
#include "google_apis/gaia/gaia_auth_util.h"
#include "google_apis/gaia/gaia_urls.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
+#include "net/cert/x509_certificate.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"
@@ -184,7 +189,7 @@ void PushFrontIMIfNotExists(const std::string& input_method,
if (input_method.empty())
return;
- if (!base::ContainsValue(*input_methods, input_method))
+ if (!base::Contains(*input_methods, input_method))
input_methods->insert(input_methods->begin(), input_method);
}
@@ -201,7 +206,7 @@ user_manager::UserType GetUsertypeFromServicesString(
const ::login::StringList& services) {
bool is_child = false;
const bool support_usm =
- base::FeatureList::IsEnabled(features::kCrOSEnableUSMUserService);
+ base::FeatureList::IsEnabled(::features::kCrOSEnableUSMUserService);
using KnownFlags = base::flat_set<std::string>;
const KnownFlags known_flags =
support_usm ? KnownFlags({"uca", "usm"}) : KnownFlags({"uca"});
@@ -241,8 +246,11 @@ std::string GetAdErrorMessage(authpolicy::ErrorType error) {
}
bool ExtractSamlPasswordAttributesEnabled() {
- return ProfileHelper::Get()->GetSigninProfile()->GetPrefs()->GetBoolean(
- prefs::kSamlInSessionPasswordChangeEnabled);
+ return base::FeatureList::IsEnabled(::features::kInSessionPasswordChange);
+}
+
+bool GaiaActionButtonsEnabled() {
+ return base::FeatureList::IsEnabled(chromeos::features::kGaiaActionButtons);
}
} // namespace
@@ -475,6 +483,7 @@ void GaiaScreenHandler::LoadGaiaWithPartitionAndVersionAndConsent(
params.SetBoolean("extractSamlPasswordAttributes",
ExtractSamlPasswordAttributesEnabled());
+ params.SetBoolean("enableGaiaActionButtons", GaiaActionButtonsEnabled());
frame_state_ = FRAME_STATE_LOADING;
CallJS("login.GaiaSigninScreen.loadAuthExtension", params);
@@ -542,8 +551,7 @@ void GaiaScreenHandler::DeclareLocalizedValues(
IDS_OFFLINE_LOGIN_FORGOT_PASSWORD_DIALOG_TEXT);
builder->Add("offlineLoginCloseBtn", IDS_OFFLINE_LOGIN_CLOSE_BUTTON_TEXT);
builder->Add("enterpriseInfoMessage", IDS_LOGIN_DEVICE_MANAGED_BY_NOTICE);
- builder->Add("samlInterstitialMessage",
- IDS_LOGIN_SAML_INTERSTITIAL_MESSAGE);
+ builder->Add("samlInterstitialMessage", IDS_LOGIN_SAML_INTERSTITIAL_MESSAGE);
builder->Add("samlInterstitialChangeAccountLink",
IDS_LOGIN_SAML_INTERSTITIAL_CHANGE_ACCOUNT_LINK_TEXT);
builder->Add("samlInterstitialNextBtn",
@@ -639,6 +647,10 @@ void GaiaScreenHandler::HandleIdentifierEntered(const std::string& user_email) {
void GaiaScreenHandler::HandleAuthExtensionLoaded() {
VLOG(1) << "Auth extension finished loading";
auth_extension_being_loaded_ = false;
+ // Recreate the client cert usage observer, in order to track only the certs
+ // used during the current sign-in attempt.
+ extension_provided_client_cert_usage_observer_ =
+ std::make_unique<LoginClientCertUsageObserver>();
}
void GaiaScreenHandler::HandleWebviewLoadAborted(
@@ -748,10 +760,12 @@ void GaiaScreenHandler::HandleCompleteAdAuthentication(
set_populated_email(username);
DCHECK(authpolicy_login_helper_);
+ Key key(password);
+ key.SetLabel(kCryptohomeGaiaKeyLabel);
authpolicy_login_helper_->AuthenticateUser(
username, std::string() /* object_guid */, password,
base::BindOnce(&GaiaScreenHandler::DoAdAuth, weak_factory_.GetWeakPtr(),
- username, Key(password)));
+ username, key));
}
void GaiaScreenHandler::HandleCancelActiveDirectoryAuth() {
@@ -818,23 +832,18 @@ void GaiaScreenHandler::OnGetCookiesForCompleteAuthentication(
const std::string sanitized_email = gaia::SanitizeEmail(email);
LoginDisplayHost::default_host()->SetDisplayEmail(sanitized_email);
- const user_manager::UserType user_type =
- GetUsertypeFromServicesString(services);
-
- UserContext user_context(user_type,
- GetAccountId(email, gaia_id, AccountType::GOOGLE));
- user_context.SetKey(Key(password));
- // Save the user's plaintext password for possible authentication to a
- // network. See https://crbug.com/386606 for details.
- user_context.SetPasswordKey(Key(password));
- user_context.SetAuthCode(auth_code);
- user_context.SetAuthFlow(using_saml
- ? UserContext::AUTH_FLOW_GAIA_WITH_SAML
- : UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML);
- user_context.SetGAPSCookie(gaps_cookie);
- if (using_saml && ExtractSamlPasswordAttributesEnabled()) {
- user_context.SetSamlPasswordAttributes(password_attributes);
+ UserContext user_context;
+ std::string error_message;
+ if (!BuildUserContextForGaiaSignIn(
+ GetUsertypeFromServicesString(services),
+ GetAccountId(email, gaia_id, AccountType::GOOGLE), using_saml,
+ password, auth_code, gaps_cookie, password_attributes, &user_context,
+ &error_message)) {
+ core_oobe_view_->ShowSignInError(0, error_message, std::string(),
+ HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
+ return;
}
+
LoginDisplayHost::default_host()->CompleteLogin(user_context);
}
@@ -855,8 +864,8 @@ void GaiaScreenHandler::HandleScrapedPasswordCount(int password_count) {
SetSAMLPrincipalsAPIUsed(false);
// Use a histogram that has 11 buckets, one for each of the values in [0, 9]
// and an overflow bucket at the end.
- UMA_HISTOGRAM_ENUMERATION(
- "ChromeOS.SAML.Scraping.PasswordCount", std::min(password_count, 10), 11);
+ UMA_HISTOGRAM_ENUMERATION("ChromeOS.SAML.Scraping.PasswordCount",
+ std::min(password_count, 10), 11);
if (password_count == 0)
HandleScrapedPasswordVerificationFailed();
}
@@ -921,11 +930,11 @@ void GaiaScreenHandler::HandleGetIsSamlUserPasswordless(
const std::string& typed_email,
const std::string& gaia_id) {
AllowJavascript();
- // TODO(emaxx,https://crbug.com/826417): Determine the result value based on
- // known_user properties if the user already existed, or the
- // DeviceSamlLoginAuthenticationType policy if that's a new user.
+ const bool is_saml_user_passwordless =
+ extension_provided_client_cert_usage_observer_ &&
+ extension_provided_client_cert_usage_observer_->ClientCertsWereUsed();
ResolveJavascriptCallback(base::Value(callback_id),
- base::Value(false) /* isSamlUserPasswordless */);
+ base::Value(is_saml_user_passwordless));
}
void GaiaScreenHandler::HandleUpdateSigninUIState(int state) {
@@ -963,29 +972,17 @@ void GaiaScreenHandler::DoCompleteLogin(
const user_manager::User* const user =
user_manager::UserManager::Get()->FindUser(account_id);
- UserContext user_context =
- user ? UserContext(*user)
- : UserContext(CalculateUserType(account_id), account_id);
- user_context.SetKey(Key(password));
- // Save the user's plaintext password for possible authentication to a
- // network. If the user's OpenNetworkConfiguration policy contains a
- // ${PASSWORD} variable, then the user's password will be used to authenticate
- // to the specified network.
- //
- // The user's password needs to be saved in memory until the policy can be
- // examined. When the policy comes in, if it does not contain the ${PASSWORD}
- // variable, the user's password will be discarded. If it contains the
- // password, it will be sent to the session manager, which will then save it
- // in a keyring so it can be retrieved for authenticating to the network.
- //
- // More details can be found in https://crbug.com/386606
- user_context.SetPasswordKey(Key(password));
- user_context.SetAuthFlow(using_saml
- ? UserContext::AUTH_FLOW_GAIA_WITH_SAML
- : UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML);
-
- if (using_saml && ExtractSamlPasswordAttributesEnabled()) {
- user_context.SetSamlPasswordAttributes(password_attributes);
+ UserContext user_context;
+ std::string error_message;
+ if (!BuildUserContextForGaiaSignIn(
+ user ? user->GetType() : CalculateUserType(account_id),
+ GetAccountId(typed_email, gaia_id, AccountType::GOOGLE), using_saml,
+ password, std::string() /* auth_code */,
+ std::string() /* gaps_cookie */, password_attributes, &user_context,
+ &error_message)) {
+ core_oobe_view_->ShowSignInError(0, error_message, std::string(),
+ HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
+ return;
}
LoginDisplayHost::default_host()->CompleteLogin(user_context);
@@ -1052,9 +1049,12 @@ void GaiaScreenHandler::SubmitLoginFormForTest() {
content::RenderFrameHost* frame =
signin::GetAuthFrame(web_ui()->GetWebContents(), kAuthIframeParentName);
+ // clang-format off
std::string code =
"document.getElementById('identifier').value = '" + test_user_ + "';"
"document.getElementById('nextButton').click();";
+ // clang-format on
+
frame->ExecuteJavaScriptForTests(base::ASCIIToUTF16(code),
base::NullCallback());
@@ -1241,10 +1241,8 @@ void GaiaScreenHandler::ShowWhitelistCheckFailedError() {
CallJS("login.GaiaSigninScreen.showWhitelistCheckFailedError", true, params);
}
-void GaiaScreenHandler::LoadAuthExtension(bool force,
- bool offline) {
- VLOG(1) << "LoadAuthExtension, force: " << force
- << ", offline: " << offline;
+void GaiaScreenHandler::LoadAuthExtension(bool force, bool offline) {
+ VLOG(1) << "LoadAuthExtension, force: " << force << ", offline: " << offline;
if (auth_extension_being_loaded_) {
VLOG(1) << "Skip loading the Auth extension as it's already being loaded";
@@ -1288,4 +1286,54 @@ bool GaiaScreenHandler::IsRestrictiveProxy() const {
!IsOnline(captive_portal_status_);
}
+bool GaiaScreenHandler::BuildUserContextForGaiaSignIn(
+ user_manager::UserType user_type,
+ const AccountId& account_id,
+ bool using_saml,
+ const std::string& password,
+ const std::string& auth_code,
+ const std::string& gaps_cookie,
+ const SamlPasswordAttributes& password_attributes,
+ UserContext* user_context,
+ std::string* error_message) {
+ // TODO(emaxx,https://crbug.com/826417): Localize the error messages.
+ *user_context = UserContext(user_type, account_id);
+ if (using_saml && extension_provided_client_cert_usage_observer_ &&
+ extension_provided_client_cert_usage_observer_->ClientCertsWereUsed()) {
+ scoped_refptr<net::X509Certificate> saml_client_cert;
+ std::vector<ChallengeResponseKey::SignatureAlgorithm> signature_algorithms;
+ if (!extension_provided_client_cert_usage_observer_->GetOnlyUsedClientCert(
+ &saml_client_cert, &signature_algorithms)) {
+ *error_message = "Multiple client certificates are not supported";
+ return false;
+ }
+ ChallengeResponseKey challenge_response_key;
+ if (!ExtractChallengeResponseKeyFromCert(
+ *saml_client_cert, signature_algorithms, &challenge_response_key)) {
+ *error_message = "Internal error";
+ return false;
+ }
+ user_context->GetMutableChallengeResponseKeys()->push_back(
+ challenge_response_key);
+ } else {
+ Key key(password);
+ key.SetLabel(kCryptohomeGaiaKeyLabel);
+ user_context->SetKey(key);
+ user_context->SetPasswordKey(Key(password));
+ }
+ if (!auth_code.empty())
+ user_context->SetAuthCode(auth_code);
+ user_context->SetAuthFlow(using_saml
+ ? UserContext::AUTH_FLOW_GAIA_WITH_SAML
+ : UserContext::AUTH_FLOW_GAIA_WITHOUT_SAML);
+ if (using_saml)
+ user_context->SetIsUsingSamlPrincipalsApi(using_saml_api_);
+ if (!gaps_cookie.empty())
+ user_context->SetGAPSCookie(gaps_cookie);
+ if (using_saml && ExtractSamlPasswordAttributesEnabled()) {
+ user_context->SetSamlPasswordAttributes(password_attributes);
+ }
+ return true;
+}
+
} // namespace chromeos
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 5dcd490d57f..1b1dd70e282 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h
@@ -12,10 +12,12 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "chrome/browser/chromeos/authpolicy/authpolicy_helper.h"
+#include "chrome/browser/chromeos/login/login_client_cert_usage_observer.h"
#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h"
#include "chromeos/network/portal_detector/network_portal_detector.h"
+#include "components/user_manager/user_type.h"
#include "net/base/net_errors.h"
class AccountId;
@@ -38,6 +40,7 @@ class ActiveDirectoryPasswordChangeScreenHandler;
class Key;
class SamlPasswordAttributes;
class SigninScreenHandler;
+class UserContext;
class GaiaView {
public:
@@ -293,6 +296,19 @@ class GaiaScreenHandler : public BaseScreenHandler,
// Records whether WebUI is currently in offline mode.
void SetOfflineLoginIsActive(bool is_active);
+ // Builds the UserContext with the information from the given Gaia user
+ // sign-in. On failure, returns false and sets |error_message|.
+ bool BuildUserContextForGaiaSignIn(
+ user_manager::UserType user_type,
+ const AccountId& account_id,
+ bool using_saml,
+ const std::string& password,
+ const std::string& auth_code,
+ const std::string& gaps_cookie,
+ const SamlPasswordAttributes& password_attributes,
+ UserContext* user_context,
+ std::string* error_message);
+
// Current state of Gaia frame.
FrameState frame_state_ = FRAME_STATE_UNKNOWN;
@@ -334,6 +350,10 @@ class GaiaScreenHandler : public BaseScreenHandler,
// If the user authenticated via SAML, this indicates whether the principals
// API was used.
+ // TODO(emaxx): This is also currently set when the user authenticated via
+ // Gaia, since Gaia uses the same API for passing the password to Chrome.
+ // Either fix this behavior, or change the naming and the comments to reflect
+ // it.
bool using_saml_api_ = false;
// Test credentials.
@@ -374,6 +394,9 @@ class GaiaScreenHandler : public BaseScreenHandler,
// The type of Gaia page to show.
GaiaScreenMode screen_mode_ = GAIA_SCREEN_MODE_DEFAULT;
+ std::unique_ptr<LoginClientCertUsageObserver>
+ extension_provided_client_cert_usage_observer_;
+
base::WeakPtrFactory<GaiaScreenHandler> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(GaiaScreenHandler);
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 69825fc0d4e..c3dbe6c9ffb 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/l10n_util.cc
@@ -155,7 +155,7 @@ std::unique_ptr<base::ListValue> GetLanguageList(
if (lang.empty() || lang == language_id)
continue;
- if (base::ContainsValue(base_language_codes, language_id)) {
+ if (base::Contains(base_language_codes, language_id)) {
// Language is supported. No need to replace
continue;
}
@@ -163,7 +163,7 @@ std::unique_ptr<base::ListValue> GetLanguageList(
if (!l10n_util::CheckAndResolveLocale(language_id, &resolved_locale))
continue;
- if (!base::ContainsValue(base_language_codes, resolved_locale)) {
+ if (!base::Contains(base_language_codes, resolved_locale)) {
// Resolved locale is not supported.
continue;
}
@@ -186,7 +186,7 @@ std::unique_ptr<base::ListValue> GetLanguageList(
it != language_codes.end(); ++it) {
// Exclude the language which is not in |base_langauge_codes| even it has
// input methods.
- if (!base::ContainsValue(base_language_codes, *it))
+ if (!base::Contains(base_language_codes, *it))
continue;
const base::string16 display_name =
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc
index a0e563f6057..57c06c6fd28 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc
@@ -14,11 +14,11 @@
#include "chrome/browser/ui/ash/ash_util.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "services/service_manager/public/cpp/connector.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
-#include "ui/events/devices/input_device_manager.h"
+#include "ui/events/devices/device_data_manager.h"
#include "ui/events/devices/touchscreen_device.h"
using content::BrowserThread;
@@ -37,7 +37,7 @@ const uint16_t kDeviceIds[] = {0x0457, 0x266e, 0x222a};
// Returns true if |vendor_id| is a valid vendor id that may be made the primary
// display.
bool IsWhiteListedVendorId(uint16_t vendor_id) {
- return base::ContainsValue(kDeviceIds, vendor_id);
+ return base::Contains(kDeviceIds, vendor_id);
}
} // namespace
@@ -45,7 +45,7 @@ bool IsWhiteListedVendorId(uint16_t vendor_id) {
OobeDisplayChooser::OobeDisplayChooser()
: scoped_observer_(this), weak_ptr_factory_(this) {
// |connector| may be null in tests.
- auto* connector = ash_util::GetServiceManagerConnector();
+ auto* connector = content::GetSystemConnector();
if (connector) {
connector->BindInterface(ash::mojom::kServiceName,
&cros_display_config_ptr_);
@@ -74,13 +74,13 @@ void OobeDisplayChooser::TryToPlaceUiOnTouchDisplay() {
}
void OobeDisplayChooser::MaybeMoveToTouchDisplay() {
- ui::InputDeviceManager* input_device_manager =
- ui::InputDeviceManager::GetInstance();
- if (input_device_manager->AreDeviceListsComplete() &&
- input_device_manager->AreTouchscreenTargetDisplaysValid()) {
+ ui::DeviceDataManager* device_data_manager =
+ ui::DeviceDataManager::GetInstance();
+ if (device_data_manager->AreDeviceListsComplete() &&
+ device_data_manager->AreTouchscreenTargetDisplaysValid()) {
MoveToTouchDisplay();
- } else if (!scoped_observer_.IsObserving(input_device_manager)) {
- scoped_observer_.Add(input_device_manager);
+ } else if (!scoped_observer_.IsObserving(device_data_manager)) {
+ scoped_observer_.Add(device_data_manager);
}
}
@@ -89,10 +89,10 @@ void OobeDisplayChooser::MoveToTouchDisplay() {
scoped_observer_.RemoveAll();
- const ui::InputDeviceManager* input_device_manager =
- ui::InputDeviceManager::GetInstance();
+ const ui::DeviceDataManager* device_data_manager =
+ ui::DeviceDataManager::GetInstance();
for (const ui::TouchscreenDevice& device :
- input_device_manager->GetTouchscreenDevices()) {
+ device_data_manager->GetTouchscreenDevices()) {
if (IsWhiteListedVendorId(device.vendor_id) &&
device.target_display_id != display::kInvalidDisplayId) {
auto config_properties = ash::mojom::DisplayConfigProperties::New();
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h
index 7fdd90e532d..5f2c67645d4 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.h
@@ -12,7 +12,7 @@
#include "ui/events/devices/input_device_event_observer.h"
namespace ui {
-class InputDeviceManager;
+class DeviceDataManager;
}
namespace chromeos {
@@ -43,7 +43,7 @@ class OobeDisplayChooser : public ui::InputDeviceEventObserver {
void OnTouchDeviceAssociationChanged() override;
void OnDeviceListsComplete() override;
- ScopedObserver<ui::InputDeviceManager, ui::InputDeviceEventObserver>
+ ScopedObserver<ui::DeviceDataManager, ui::InputDeviceEventObserver>
scoped_observer_;
ash::mojom::CrosDisplayConfigControllerPtr cros_display_config_ptr_;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc
index 3a5adc9c22c..2fd04181e8a 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser_unittest.cc
@@ -13,7 +13,6 @@
#include "base/strings/string_number_conversions.h"
#include "chrome/test/base/chrome_ash_test_base.h"
#include "mojo/public/cpp/bindings/binding.h"
-#include "services/ws/public/cpp/input_devices/input_device_client_test_api.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/display/display.h"
#include "ui/display/display_observer.h"
@@ -21,6 +20,7 @@
#include "ui/display/manager/test/touch_device_manager_test_api.h"
#include "ui/display/screen.h"
#include "ui/display/test/display_manager_test_api.h"
+#include "ui/events/devices/device_data_manager_test_api.h"
#include "ui/events/devices/touchscreen_device.h"
namespace chromeos {
@@ -91,7 +91,7 @@ class OobeDisplayChooserTest : public ChromeAshTestBase {
display_chooser_->set_cros_display_config_ptr_for_test(
cros_display_config_->CreateInterfacePtrAndBind());
- ws::InputDeviceClientTestApi().OnDeviceListsComplete();
+ ui::DeviceDataManagerTestApi().OnDeviceListsComplete();
}
OobeDisplayChooser* display_chooser() { return display_chooser_.get(); }
@@ -125,7 +125,7 @@ TEST_F(OobeDisplayChooserTest, PreferTouchAsPrimary) {
ui::TouchscreenDevice(1, ui::InputDeviceType::INPUT_DEVICE_USB,
"Touchscreen", gfx::Size(800, 600), 1);
touchscreen.vendor_id = kWhitelistedId;
- ws::InputDeviceClientTestApi().SetTouchscreenDevices({touchscreen});
+ ui::DeviceDataManagerTestApi().SetTouchscreenDevices({touchscreen});
base::RunLoop().RunUntilIdle();
// Associate touchscreen device with display
@@ -141,7 +141,7 @@ TEST_F(OobeDisplayChooserTest, PreferTouchAsPrimary) {
// ws::mojom::InputDeviceObserverMojo. In unit tests InputDeviceClient is not
// wired to the window server (the window server isn't running).
touchscreen.target_display_id = display_info[1].id();
- ws::InputDeviceClientTestApi().SetTouchscreenDevices({touchscreen}, true);
+ ui::DeviceDataManagerTestApi().SetTouchscreenDevices({touchscreen}, true);
EXPECT_EQ(1, GetPrimaryDisplay());
display_chooser()->TryToPlaceUiOnTouchDisplay();
@@ -168,7 +168,7 @@ TEST_F(OobeDisplayChooserTest, DontSwitchFromTouch) {
ui::TouchscreenDevice(1, ui::InputDeviceType::INPUT_DEVICE_USB,
"Touchscreen", gfx::Size(800, 600), 1);
touchscreen.vendor_id = kWhitelistedId;
- ws::InputDeviceClientTestApi().SetTouchscreenDevices({touchscreen});
+ ui::DeviceDataManagerTestApi().SetTouchscreenDevices({touchscreen});
base::RunLoop().RunUntilIdle();
// Associate touchscreen device with display
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 691f6680a05..b780e5acb2d 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc
@@ -66,7 +66,6 @@
#include "chrome/browser/ui/webui/chromeos/login/recommend_apps_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/reset_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h"
-#include "chrome/browser/ui/webui/chromeos/login/supervision_onboarding_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/supervision_transition_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.h"
@@ -89,6 +88,7 @@
#include "chrome/grit/component_extension_resources.h"
#include "chromeos/constants/chromeos_switches.h"
#include "chromeos/services/multidevice_setup/public/mojom/constants.mojom.h"
+#include "chromeos/services/network_config/public/mojom/constants.mojom.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h"
@@ -102,8 +102,8 @@
#include "ui/base/webui/web_ui_util.h"
#include "ui/chromeos/resources/grit/ui_chromeos_resources.h"
#include "ui/display/display.h"
+#include "ui/events/devices/device_data_manager.h"
#include "ui/events/devices/input_device.h"
-#include "ui/events/devices/input_device_manager.h"
namespace chromeos {
@@ -164,11 +164,6 @@ void AddSyncConsentResources(content::WebUIDataSource* source) {
#endif
}
-void AddSupervisionOnboardingScreenResources(content::WebUIDataSource* source) {
- source->AddResourcePath("supervision/onboarding_controller.mojom-lite.js",
- IDR_SUPERVISION_ONBOARDING_CONTROLLER_MOJOM_LITE_JS);
-}
-
// Adds resources for ARC-dependent screens (PlayStore ToS, Assistant, etc...)
void AddArcScreensResources(content::WebUIDataSource* source) {
// Required for postprocessing of Goolge PlayStore Terms and Overlay help.
@@ -185,13 +180,21 @@ void AddArcScreensResources(content::WebUIDataSource* source) {
}
void AddFingerprintResources(content::WebUIDataSource* source) {
- if (quick_unlock::IsFingerprintReaderOnKeyboard()) {
- source->AddResourcePath("fingerprint_scanner_animation.png",
- IDR_LOGIN_FINGERPRINT_SCANNER_LAPTOP_ANIMATION);
- } else {
- source->AddResourcePath("fingerprint_scanner_animation.png",
- IDR_LOGIN_FINGERPRINT_SCANNER_TABLET_ANIMATION);
+ int animation_id;
+ switch (quick_unlock::GetFingerprintLocation()) {
+ case quick_unlock::FingerprintLocation::TABLET_POWER_BUTTON:
+ animation_id =
+ IDR_LOGIN_FINGERPRINT_SCANNER_TABLET_POWER_BUTTON_ANIMATION;
+ break;
+ case quick_unlock::FingerprintLocation::KEYBOARD_BOTTOM_RIGHT:
+ animation_id =
+ IDR_LOGIN_FINGERPRINT_SCANNER_LAPTOP_BOTTOM_RIGHT_ANIMATION;
+ break;
+ case quick_unlock::FingerprintLocation::KEYBOARD_TOP_RIGHT:
+ animation_id = IDR_LOGIN_FINGERPRINT_SCANNER_LAPTOP_TOP_RIGHT_ANIMATION;
+ break;
}
+ source->AddResourcePath("fingerprint_scanner_animation.png", animation_id);
}
// Default and non-shared resource definition for kOobeDisplay display type.
@@ -252,7 +255,6 @@ content::WebUIDataSource* CreateOobeUIDataSource(
AddFingerprintResources(source);
AddSyncConsentResources(source);
AddArcScreensResources(source);
- AddSupervisionOnboardingScreenResources(source);
source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS);
source->OverrideContentSecurityPolicyObjectSrc(
@@ -271,7 +273,7 @@ content::WebUIDataSource* CreateOobeUIDataSource(
std::string GetDisplayType(const GURL& url) {
std::string path = url.path().size() ? url.path().substr(1) : "";
- if (!base::ContainsValue(kKnownDisplayTypes, path)) {
+ if (!base::Contains(kKnownDisplayTypes, path)) {
LOG(ERROR) << "Unknown display type '" << path << "'. Setting default.";
return OobeUI::kLoginDisplay;
}
@@ -421,9 +423,6 @@ void OobeUI::ConfigureOobeDisplay() {
AddScreenHandler(std::make_unique<EncryptionMigrationScreenHandler>(
js_calls_container_.get()));
- AddScreenHandler(std::make_unique<SupervisionOnboardingScreenHandler>(
- js_calls_container_.get()));
-
AddScreenHandler(std::make_unique<SupervisionTransitionScreenHandler>(
js_calls_container_.get()));
@@ -481,6 +480,14 @@ void OobeUI::BindPrivilegedHostDeviceSetter(
multidevice_setup::mojom::kServiceName, std::move(request));
}
+void OobeUI::BindCrosNetworkConfig(
+ chromeos::network_config::mojom::CrosNetworkConfigRequest request) {
+ content::BrowserContext::GetConnectorFor(
+ web_ui()->GetWebContents()->GetBrowserContext())
+ ->BindInterface(chromeos::network_config::mojom::kServiceName,
+ std::move(request));
+}
+
OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url)
: ui::MojoWebUIController(web_ui, true /* enable_chrome_send */) {
display_type_ = GetDisplayType(url);
@@ -522,6 +529,8 @@ OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url)
base::Unretained(this)));
AddHandlerToRegistry(base::BindRepeating(
&OobeUI::BindPrivilegedHostDeviceSetter, base::Unretained(this)));
+ AddHandlerToRegistry(base::BindRepeating(&OobeUI::BindCrosNetworkConfig,
+ base::Unretained(this)));
}
OobeUI::~OobeUI() {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h
index 6361eaea06a..84dc0d2d4ca 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h
@@ -18,6 +18,7 @@
#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h"
#include "chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom.h"
+#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" // nogncheck
#include "ui/webui/mojo_web_ui_controller.h"
namespace base {
@@ -161,6 +162,8 @@ class OobeUI : public ui::MojoWebUIController {
multidevice_setup::mojom::MultiDeviceSetupRequest request);
void BindPrivilegedHostDeviceSetter(
multidevice_setup::mojom::PrivilegedHostDeviceSetterRequest request);
+ void BindCrosNetworkConfig(
+ chromeos::network_config::mojom::CrosNetworkConfigRequest request);
// Type of UI.
std::string display_type_;
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 71aabddcca2..eca0146a80f 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
@@ -59,7 +59,6 @@
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/system/system_clock.h"
-#include "chrome/browser/io_thread.h"
#include "chrome/browser/lifetime/browser_shutdown.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_metrics.h"
@@ -120,10 +119,14 @@ const size_t kMaxUsers = 18;
// Timeout to delay first notification about offline state for a
// current network.
-const int kOfflineTimeoutSec = 5;
+constexpr base::TimeDelta kOfflineTimeout = base::TimeDelta::FromSeconds(1);
+
+// Timeout to delay first notification about offline state when authenticating
+// to a proxy.
+constexpr base::TimeDelta kProxyAuthTimeout = base::TimeDelta::FromSeconds(5);
// Timeout used to prevent infinite connecting to a flaky network.
-const int kConnectingTimeoutSec = 60;
+constexpr base::TimeDelta kConnectingTimeout = base::TimeDelta::FromSeconds(60);
// Max number of Gaia Reload to Show Proxy Auth Dialog.
const int kMaxGaiaReloadForProxyAuthDialog = 3;
@@ -618,9 +621,8 @@ void SigninScreenHandler::UpdateStateInternal(NetworkError::ErrorReason reason,
true));
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, update_state_closure_.callback(),
- is_offline_timeout_for_test_set_
- ? offline_timeout_for_test_
- : base::TimeDelta::FromSeconds(kOfflineTimeoutSec));
+ is_offline_timeout_for_test_set_ ? offline_timeout_for_test_
+ : kOfflineTimeout);
return;
}
@@ -634,8 +636,7 @@ void SigninScreenHandler::UpdateStateInternal(NetworkError::ErrorReason reason,
reason,
true));
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
- FROM_HERE, connecting_closure_.callback(),
- base::TimeDelta::FromSeconds(kConnectingTimeoutSec));
+ FROM_HERE, connecting_closure_.callback(), kConnectingTimeout);
}
return;
}
@@ -981,7 +982,7 @@ void SigninScreenHandler::Observe(int type,
ReenableNetworkStateUpdatesAfterProxyAuth();
} else {
// Gaia is not hidden behind an error yet. Discard last cached network
- // state notification and wait for |kOfflineTimeoutSec| before
+ // state notification and wait for |kProxyAuthTimeout| before
// considering network update notifications again (hoping the network
// will become ONLINE by then).
update_state_closure_.Cancel();
@@ -990,7 +991,7 @@ void SigninScreenHandler::Observe(int type,
base::BindOnce(
&SigninScreenHandler::ReenableNetworkStateUpdatesAfterProxyAuth,
weak_factory_.GetWeakPtr()),
- base::TimeDelta::FromSeconds(kOfflineTimeoutSec));
+ kProxyAuthTimeout);
}
break;
}
@@ -1057,8 +1058,6 @@ void SigninScreenHandler::AuthenticateExistingUser(const AccountId& account_id,
user_context = UserContext(*user);
}
user_context.SetKey(Key(password));
- // Save the user's plaintext password for possible authentication to a
- // 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) {
@@ -1306,7 +1305,10 @@ void SigninScreenHandler::HandleShowLoadingTimeoutError() {
void SigninScreenHandler::HandleFocusPod(const AccountId& account_id,
bool is_large_pod) {
proximity_auth::ScreenlockBridge::Get()->SetFocusedUser(account_id);
- if (delegate_)
+ const bool is_same_pod_focused =
+ focused_pod_account_id_ && *focused_pod_account_id_ == account_id;
+
+ if (delegate_ && !is_same_pod_focused)
delegate_->CheckUserStatus(account_id);
if (!test_focus_pod_callback_.is_null())
test_focus_pod_callback_.Run();
@@ -1318,21 +1320,26 @@ void SigninScreenHandler::HandleFocusPod(const AccountId& account_id,
// |user| may be nullptr in kiosk mode or unit tests.
if (user && user->is_logged_in() && !user->is_active()) {
SessionControllerClientImpl::DoSwitchActiveUser(account_id);
- } else {
- lock_screen_utils::SetUserInputMethod(account_id.GetUserEmail(),
- ime_state_.get());
- lock_screen_utils::SetKeyboardSettings(account_id);
- if (LoginDisplayHost::default_host() && is_large_pod)
- LoginDisplayHost::default_host()->LoadWallpaper(account_id);
-
- bool use_24hour_clock = false;
- if (user_manager::known_user::GetBooleanPref(
- account_id, prefs::kUse24HourClock, &use_24hour_clock)) {
- g_browser_process->platform_part()
- ->GetSystemClock()
- ->SetLastFocusedPodHourClockType(
- use_24hour_clock ? base::k24HourClock : base::k12HourClock);
- }
+ return;
+ }
+
+ if (LoginDisplayHost::default_host() && is_large_pod)
+ LoginDisplayHost::default_host()->LoadWallpaper(account_id);
+
+ if (is_same_pod_focused)
+ return;
+
+ lock_screen_utils::SetUserInputMethod(account_id.GetUserEmail(),
+ ime_state_.get());
+ lock_screen_utils::SetKeyboardSettings(account_id);
+
+ bool use_24hour_clock = false;
+ if (user_manager::known_user::GetBooleanPref(
+ account_id, prefs::kUse24HourClock, &use_24hour_clock)) {
+ g_browser_process->platform_part()
+ ->GetSystemClock()
+ ->SetLastFocusedPodHourClockType(use_24hour_clock ? base::k24HourClock
+ : base::k12HourClock);
}
}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/supervision_onboarding_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/supervision_onboarding_screen_handler.cc
deleted file mode 100644
index 62eb8af70aa..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/login/supervision_onboarding_screen_handler.cc
+++ /dev/null
@@ -1,80 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/chromeos/login/supervision_onboarding_screen_handler.h"
-
-#include "base/bind.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chromeos/login/oobe_screen.h"
-#include "chrome/browser/chromeos/login/screens/supervision_onboarding_screen.h"
-#include "chrome/browser/profiles/profile_manager.h"
-#include "chrome/browser/ui/ash/login_screen_client.h"
-#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/login/localized_values_builder.h"
-
-namespace chromeos {
-
-constexpr StaticOobeScreenId SupervisionOnboardingScreenView::kScreenId;
-
-SupervisionOnboardingScreenHandler::SupervisionOnboardingScreenHandler(
- JSCallsContainer* js_calls_container)
- : BaseScreenHandler(kScreenId, js_calls_container) {
- set_user_acted_method_path("login.SupervisionOnboardingScreen.userActed");
-}
-
-SupervisionOnboardingScreenHandler::~SupervisionOnboardingScreenHandler() {
- if (screen_)
- screen_->OnViewDestroyed(this);
-}
-
-void SupervisionOnboardingScreenHandler::DeclareLocalizedValues(
- ::login::LocalizedValuesBuilder* builder) {
- builder->Add("supervisionOnboardingWaitMessage",
- IDS_SUPERVISION_ONBOARDING_WAIT_MESSAGE);
- builder->Add("supervisionOnboardingNextButtonLabel",
- IDS_SUPERVISION_ONBOARDING_NEXT_BUTTON);
- builder->Add("supervisionOnboardingSkipButtonLabel",
- IDS_SUPERVISION_ONBOARDING_SKIP_BUTTON);
- builder->Add("supervisionOnboardingBackButtonLabel",
- IDS_SUPERVISION_ONBOARDING_BACK_BUTTON);
-}
-
-void SupervisionOnboardingScreenHandler::Bind(
- SupervisionOnboardingScreen* screen) {
- BaseScreenHandler::SetBaseScreen(screen);
- screen_ = screen;
-}
-
-void SupervisionOnboardingScreenHandler::Unbind() {
- screen_ = nullptr;
- BaseScreenHandler::SetBaseScreen(nullptr);
-}
-
-void SupervisionOnboardingScreenHandler::Show() {
- ShowScreen(kScreenId);
-
- GetOobeUI()->AddHandlerToRegistry(base::BindRepeating(
- &SupervisionOnboardingScreenHandler::BindSupervisionOnboardingController,
- base::Unretained(this)));
-
- CallJS("login.SupervisionOnboardingScreen.setupMojo");
-}
-
-void SupervisionOnboardingScreenHandler::Hide() {}
-
-void SupervisionOnboardingScreenHandler::Initialize() {}
-
-void SupervisionOnboardingScreenHandler::BindSupervisionOnboardingController(
- supervision::mojom::OnboardingControllerRequest request) {
- if (!supervision_onboarding_controller_) {
- supervision_onboarding_controller_ =
- std::make_unique<supervision::OnboardingControllerImpl>(
- ProfileManager::GetPrimaryUserProfile());
- }
-
- supervision_onboarding_controller_->BindRequest(std::move(request));
-}
-
-} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/supervision_onboarding_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/supervision_onboarding_screen_handler.h
deleted file mode 100644
index ba8035c670e..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/login/supervision_onboarding_screen_handler.h
+++ /dev/null
@@ -1,82 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_SUPERVISION_ONBOARDING_SCREEN_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_SUPERVISION_ONBOARDING_SCREEN_HANDLER_H_
-
-#include <memory>
-#include <string>
-
-#include "base/macros.h"
-#include "base/time/time.h"
-#include "base/timer/timer.h"
-#include "chrome/browser/chromeos/supervision/mojom/onboarding_controller.mojom.h"
-#include "chrome/browser/chromeos/supervision/onboarding_controller_impl.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
-#include "components/prefs/pref_change_registrar.h"
-
-namespace chromeos {
-
-class SupervisionOnboardingScreen;
-
-// Interface for dependency injection between SupervisionOnboardingScreen
-// and its WebUI representation.
-class SupervisionOnboardingScreenView {
- public:
- constexpr static StaticOobeScreenId kScreenId{"supervision-onboarding"};
-
- virtual ~SupervisionOnboardingScreenView() {}
-
- virtual void Bind(SupervisionOnboardingScreen* screen) = 0;
- virtual void Unbind() = 0;
- virtual void Show() = 0;
- virtual void Hide() = 0;
-
- protected:
- SupervisionOnboardingScreenView() = default;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(SupervisionOnboardingScreenView);
-};
-
-class SupervisionOnboardingScreenHandler
- : public BaseScreenHandler,
- public SupervisionOnboardingScreenView {
- public:
- using TView = SupervisionOnboardingScreenView;
-
- explicit SupervisionOnboardingScreenHandler(
- JSCallsContainer* js_calls_container);
- ~SupervisionOnboardingScreenHandler() override;
-
- // BaseScreenHandler:
- void DeclareLocalizedValues(
- ::login::LocalizedValuesBuilder* builder) override;
-
- // SupervisionOnboardingScreenView:
- void Bind(SupervisionOnboardingScreen* screen) override;
- void Unbind() override;
- void Show() override;
- void Hide() override;
-
- private:
- // BaseScreenHandler:
- void Initialize() override;
-
- // Callback used to bing the mojo onboarding controller.
- void BindSupervisionOnboardingController(
- supervision::mojom::OnboardingControllerRequest request);
-
- SupervisionOnboardingScreen* screen_ = nullptr;
-
- std::unique_ptr<supervision::OnboardingControllerImpl>
- supervision_onboarding_controller_;
-
- DISALLOW_COPY_AND_ASSIGN(SupervisionOnboardingScreenHandler);
-};
-
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_SUPERVISION_ONBOARDING_SCREEN_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn b/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn
index 3adbd9c1354..f6ccee9ab2e 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn
+++ b/chromium/chrome/browser/ui/webui/chromeos/machine_learning/BUILD.gn
@@ -12,4 +12,7 @@ mojom("mojo_bindings") {
deps = [
"//chromeos/services/machine_learning/public/mojom",
]
+
+ # TODO(https://crbug.com/968369): Change to use new names.
+ use_old_js_lite_bindings_names = true
}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.cc
index 6013fe414ea..34e2447eafb 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.cc
@@ -4,17 +4,21 @@
#include "chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h"
+#include "base/feature_list.h"
#include "base/stl_util.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/chromeos/net/shill_error.h"
+#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/webui/localized_string.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/login/login_state/login_state.h"
#include "chromeos/network/network_connection_handler.h"
#include "components/login/localized_values_builder.h"
+#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_ui_data_source.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
+#include "ui/base/l10n/l10n_util.h"
namespace chromeos {
namespace network_element {
@@ -22,9 +26,10 @@ namespace network_element {
namespace {
constexpr LocalizedString kElementLocalizedStrings[] = {
- {"OncTypeCellular", IDS_NETWORK_TYPE_MOBILE_DATA},
+ {"OncTypeCellular", IDS_NETWORK_TYPE_CELLULAR},
{"OncTypeEthernet", IDS_NETWORK_TYPE_ETHERNET},
- {"OncTypeTether", IDS_NETWORK_TYPE_MOBILE_DATA},
+ {"OncTypeMobile", IDS_NETWORK_TYPE_MOBILE_DATA},
+ {"OncTypeTether", IDS_NETWORK_TYPE_TETHER},
{"OncTypeVPN", IDS_NETWORK_TYPE_VPN},
{"OncTypeWiFi", IDS_NETWORK_TYPE_WIFI},
{"OncTypeWiMAX", IDS_NETWORK_TYPE_WIMAX},
@@ -223,6 +228,16 @@ void AddDetailsLocalizedStrings(content::WebUIDataSource* html_source) {
IDS_SETTINGS_INTERNET_NETWORK_SIM_RE_ENTER_NEW_PIN},
{"networkSimReEnterNewPin",
IDS_SETTINGS_INTERNET_NETWORK_SIM_RE_ENTER_NEW_PIN},
+ {"networkSimErrorIncorrectPin",
+ IDS_SETTINGS_INTERNET_NETWORK_SIM_ERROR_INCORRECT_PIN},
+ {"networkSimErrorIncorrectPuk",
+ IDS_SETTINGS_INTERNET_NETWORK_SIM_ERROR_INCORRECT_PUK},
+ {"networkSimErrorInvalidPin",
+ IDS_SETTINGS_INTERNET_NETWORK_SIM_ERROR_INVALID_PIN},
+ {"networkSimErrorInvalidPuk",
+ IDS_SETTINGS_INTERNET_NETWORK_SIM_ERROR_INVALID_PUK},
+ {"networkSimErrorPinMismatch",
+ IDS_SETTINGS_INTERNET_NETWORK_SIM_ERROR_PIN_MISMATCH},
{"networkSimUnlock", IDS_SETTINGS_INTERNET_NETWORK_SIM_BUTTON_UNLOCK},
{"networkAccessPoint", IDS_SETTINGS_INTERNET_NETWORK_ACCESS_POINT},
{"networkChooseMobile", IDS_SETTINGS_INTERNET_NETWORK_CHOOSE_MOBILE},
@@ -244,6 +259,7 @@ void AddDetailsLocalizedStrings(content::WebUIDataSource* html_source) {
IDS_SETTINGS_INTERNET_NETWORK_NAMESERVERS_GOOGLE},
{"networkProxyWpad", IDS_SETTINGS_INTERNET_NETWORK_PROXY_WPAD},
{"networkProxyWpadNone", IDS_SETTINGS_INTERNET_NETWORK_PROXY_WPAD_NONE},
+ {"remove", IDS_REMOVE},
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings,
base::size(kLocalizedStrings));
@@ -263,12 +279,18 @@ void AddConfigLocalizedStrings(content::WebUIDataSource* html_source) {
{"networkConfigSaveCredentials",
IDS_SETTINGS_INTERNET_CONFIG_SAVE_CREDENTIALS},
{"networkConfigShare", IDS_SETTINGS_INTERNET_CONFIG_SHARE},
+ {"networkAutoConnect", IDS_SETTINGS_INTERNET_NETWORK_AUTO_CONNECT},
+ {"hiddenNetworkWarning", IDS_SETTINGS_HIDDEN_NETWORK_WARNING},
{"hidePassword", IDS_SETTINGS_PASSWORD_HIDE},
{"showPassword", IDS_SETTINGS_PASSWORD_SHOW},
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings,
base::size(kLocalizedStrings));
+ html_source->AddBoolean(
+ "showHiddenNetworkWarning",
+ base::FeatureList::IsEnabled(features::kHiddenNetworkWarning));
+
// Login screen and public account users can only create shared network
// configurations. Other users default to unshared network configurations.
// NOTE: Guest and kiosk users can only create unshared network configs.
diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc
index 1513366c2d6..4c767fef5ea 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc
@@ -16,6 +16,7 @@
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/ui/webui/chromeos/cellular_setup/cellular_setup_dialog_launcher.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/network_element_localized_strings_provider.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
@@ -26,11 +27,14 @@
#include "chromeos/network/network_state.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/onc/onc_utils.h"
+#include "chromeos/services/network_config/public/mojom/constants.mojom.h"
#include "components/device_event_log/device_event_log.h"
+#include "content/public/browser/browser_context.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
+#include "services/service_manager/public/cpp/connector.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
#include "ui/base/l10n/l10n_util.h"
@@ -42,6 +46,9 @@ constexpr char kAddNetwork[] = "addNetwork";
constexpr char kGetNetworkProperties[] = "getShillNetworkProperties";
constexpr char kGetDeviceProperties[] = "getShillDeviceProperties";
constexpr char kOpenCellularActivationUi[] = "openCellularActivationUi";
+constexpr char kShowNetworkDetails[] = "showNetworkDetails";
+constexpr char kShowNetworkConfig[] = "showNetworkConfig";
+constexpr char kShowAddNewWifiNetworkDialog[] = "showAddNewWifi";
bool GetServicePathFromGuid(const std::string& guid,
std::string* service_path) {
@@ -105,6 +112,18 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler {
base::BindRepeating(
&NetworkConfigMessageHandler::OpenCellularActivationUi,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ kShowNetworkDetails,
+ base::BindRepeating(&NetworkConfigMessageHandler::ShowNetworkDetails,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ kShowNetworkConfig,
+ base::BindRepeating(&NetworkConfigMessageHandler::ShowNetworkConfig,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ kShowAddNewWifiNetworkDialog,
+ base::BindRepeating(&NetworkConfigMessageHandler::ShowAddNewWifi,
+ base::Unretained(this)));
}
private:
@@ -186,6 +205,30 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler {
base::Value(cellular_network != nullptr));
}
+ void ShowNetworkDetails(const base::ListValue* arg_list) {
+ std::string guid;
+ if (!arg_list->GetString(0, &guid)) {
+ NOTREACHED();
+ return;
+ }
+
+ InternetDetailDialog::ShowDialog(guid);
+ }
+
+ void ShowNetworkConfig(const base::ListValue* arg_list) {
+ std::string guid;
+ if (!arg_list->GetString(0, &guid)) {
+ NOTREACHED();
+ return;
+ }
+
+ InternetConfigDialog::ShowDialogForNetworkId(guid);
+ }
+
+ void ShowAddNewWifi(const base::ListValue* arg_list) {
+ InternetConfigDialog::ShowDialogForNetworkType(::onc::network_type::kWiFi);
+ }
+
void GetShillDevicePropertiesSuccess(
const std::string& device_path,
const base::DictionaryValue& dictionary) {
@@ -295,10 +338,17 @@ void NetworkUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) {
localized_strings->SetString(
"noCellularErrorText",
l10n_util::GetStringUTF16(IDS_NETWORK_UI_NO_CELLULAR_ERROR_TEXT));
+
+ localized_strings->SetString(
+ "addNewWifiLabel",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_ADD_NEW_WIFI_LABEL));
+ localized_strings->SetString(
+ "addNewWifiButtonText",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_ADD_NEW_WIFI_BUTTON_TEXT));
}
NetworkUI::NetworkUI(content::WebUI* web_ui)
- : content::WebUIController(web_ui) {
+ : ui::MojoWebUIController(web_ui, /*enable_chrome_send=*/true) {
web_ui->AddMessageHandler(std::make_unique<NetworkConfigMessageHandler>());
// Enable extension API calls in the WebUI.
@@ -320,8 +370,17 @@ NetworkUI::NetworkUI(content::WebUI* web_ui)
content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(),
html);
+ AddHandlerToRegistry(base::BindRepeating(&NetworkUI::BindCrosNetworkConfig,
+ base::Unretained(this)));
}
NetworkUI::~NetworkUI() {}
+void NetworkUI::BindCrosNetworkConfig(
+ network_config::mojom::CrosNetworkConfigRequest request) {
+ content::BrowserContext::GetConnectorFor(
+ web_ui()->GetWebContents()->GetBrowserContext())
+ ->BindInterface(network_config::mojom::kServiceName, std::move(request));
+}
+
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_ui.h b/chromium/chrome/browser/ui/webui/chromeos/network_ui.h
index 49f9d7f6e5f..4ed87901d96 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/network_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/network_ui.h
@@ -6,7 +6,8 @@
#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_NETWORK_UI_H_
#include "base/macros.h"
-#include "content/public/browser/web_ui_controller.h"
+#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h"
+#include "ui/webui/mojo_web_ui_controller.h"
namespace base {
class DictionaryValue;
@@ -15,7 +16,7 @@ class DictionaryValue;
namespace chromeos {
// WebUI controller for chrome://network debugging page.
-class NetworkUI : public content::WebUIController {
+class NetworkUI : public ui::MojoWebUIController {
public:
explicit NetworkUI(content::WebUI* web_ui);
~NetworkUI() override;
@@ -23,6 +24,9 @@ class NetworkUI : public content::WebUIController {
static void GetLocalizedStrings(base::DictionaryValue* localized_strings);
private:
+ void BindCrosNetworkConfig(
+ network_config::mojom::CrosNetworkConfigRequest request);
+
DISALLOW_COPY_AND_ASSIGN(NetworkUI);
};
diff --git a/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc
index 2a86ba919f8..7c2890f0231 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc
@@ -8,12 +8,15 @@
#include <memory>
+#include "ash/public/cpp/login_screen.h"
+#include "ash/public/cpp/login_types.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/build_time.h"
#include "base/macros.h"
#include "base/scoped_observer.h"
#include "base/values.h"
+#include "chrome/browser/chromeos/child_accounts/parent_access_code/parent_access_service.h"
#include "chrome/browser/chromeos/set_time_dialog.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/system/timezone_util.h"
@@ -25,6 +28,7 @@
#include "chromeos/dbus/system_clock/system_clock_client.h"
#include "chromeos/settings/timezone_settings.h"
#include "components/strings/grit/components_strings.h"
+#include "components/user_manager/user_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
@@ -38,7 +42,7 @@ class SetTimeMessageHandler : public content::WebUIMessageHandler,
public chromeos::SystemClockClient::Observer,
public system::TimezoneSettings::Observer {
public:
- SetTimeMessageHandler() = default;
+ SetTimeMessageHandler() : weak_factory_(this) {}
~SetTimeMessageHandler() override = default;
// WebUIMessageHandler:
@@ -55,6 +59,9 @@ class SetTimeMessageHandler : public content::WebUIMessageHandler,
"setTimezone",
base::BindRepeating(&SetTimeMessageHandler::OnSetTimezone,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "doneClicked", base::BindRepeating(&SetTimeMessageHandler::DoneClicked,
+ base::Unretained(this)));
}
void OnJavascriptAllowed() override {
@@ -113,10 +120,38 @@ class SetTimeMessageHandler : public content::WebUIMessageHandler,
system::SetTimezoneFromUI(profile, timezone_id);
}
+ void DoneClicked(const base::ListValue* args) {
+ if (!parent_access::ParentAccessService::IsApprovalRequired(
+ parent_access::ParentAccessService::SupervisedAction::
+ kUpdateClock)) {
+ OnParentAccessValidation(true);
+ return;
+ }
+
+ AccountId account_id;
+ bool is_user_logged_in = user_manager::UserManager::Get()->IsUserLoggedIn();
+ if (is_user_logged_in) {
+ account_id =
+ user_manager::UserManager::Get()->GetActiveUser()->GetAccountId();
+ }
+ ash::LoginScreen::Get()->ShowParentAccessWidget(
+ account_id,
+ base::BindRepeating(&SetTimeMessageHandler::OnParentAccessValidation,
+ weak_factory_.GetWeakPtr()),
+ ash::ParentAccessRequestReason::kChangeTime,
+ !is_user_logged_in /* extra_dimmer */);
+ }
+
+ void OnParentAccessValidation(bool success) {
+ if (success)
+ FireWebUIListener("validation-complete");
+ }
+
ScopedObserver<SystemClockClient, SystemClockClient::Observer>
clock_observer_{this};
ScopedObserver<system::TimezoneSettings, system::TimezoneSettings::Observer>
timezone_observer_{this};
+ base::WeakPtrFactory<SetTimeMessageHandler> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SetTimeMessageHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc
index cafa6b84151..07d906c1abd 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.cc
@@ -28,7 +28,7 @@ namespace chromeos {
SlowTraceSource::SlowTraceSource() {
}
-std::string SlowTraceSource::GetSource() const {
+std::string SlowTraceSource::GetSource() {
return chrome::kChromeUISlowTraceHost;
}
@@ -51,7 +51,7 @@ void SlowTraceSource::StartDataRequest(
callback));
}
-std::string SlowTraceSource::GetMimeType(const std::string& path) const {
+std::string SlowTraceSource::GetMimeType(const std::string& path) {
return "application/zip";
}
@@ -63,7 +63,7 @@ void SlowTraceSource::OnGetTraceData(
callback.Run(trace_data.get());
}
-bool SlowTraceSource::AllowCaching() const {
+bool SlowTraceSource::AllowCaching() {
// Should not be cached to reflect dynamically-generated contents that may
// depend on current settings.
return false;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h
index 495b05c3091..77a04463b1d 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/slow_trace_ui.h
@@ -29,13 +29,13 @@ class SlowTraceSource : public content::URLDataSource {
~SlowTraceSource() override;
// content::URLDataSource implementation.
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override;
- std::string GetMimeType(const std::string& path) const override;
- bool AllowCaching() const override;
+ std::string GetMimeType(const std::string& path) override;
+ bool AllowCaching() override;
private:
void OnGetTraceData(const content::URLDataSource::GotDataCallback& callback,
diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc
index 4728bfe1844..4b224daa69c 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.cc
@@ -53,7 +53,7 @@ void SmbHandler::RegisterMessages() {
}
void SmbHandler::HandleSmbMount(const base::ListValue* args) {
- CHECK_EQ(7U, args->GetSize());
+ CHECK_EQ(8U, args->GetSize());
std::string callback_id;
CHECK(args->GetString(0, &callback_id));
@@ -63,12 +63,14 @@ void SmbHandler::HandleSmbMount(const base::ListValue* args) {
std::string password;
bool use_kerberos;
bool should_open_file_manager_after_mount;
+ bool save_credentials;
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));
CHECK(args->GetBoolean(6, &should_open_file_manager_after_mount));
+ CHECK(args->GetBoolean(7, &save_credentials));
smb_client::SmbService* const service = GetSmbService(profile_);
if (!service) {
@@ -82,10 +84,11 @@ void SmbHandler::HandleSmbMount(const base::ListValue* args) {
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, use_kerberos,
- should_open_file_manager_after_mount, std::move(mount_response));
+ auto mount_call =
+ base::BindOnce(&smb_client::SmbService::Mount, base::Unretained(service),
+ mo, base::FilePath(mount_url), username, password,
+ use_kerberos, should_open_file_manager_after_mount,
+ save_credentials, std::move(mount_response));
if (host_discovery_done_) {
std::move(mount_call).Run();
@@ -122,9 +125,11 @@ void SmbHandler::HandleDiscoveryDone() {
}
void SmbHandler::HandleGatherSharesResponse(
- const std::vector<smb_client::SmbUrl>& shares_gathered) {
+ const std::vector<smb_client::SmbUrl>& shares_gathered,
+ bool done) {
AllowJavascript();
- FireWebUIListener("on-shares-found", BuildShareList(shares_gathered));
+ FireWebUIListener("on-shares-found", BuildShareList(shares_gathered),
+ base::Value(done));
}
void SmbHandler::HandleUpdateCredentials(const base::ListValue* args) {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h
index 493b9ba3ad4..38354b5e168 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h
@@ -43,7 +43,8 @@ class SmbHandler : public content::WebUIMessageHandler {
// Callback handler for StartDiscovery.
void HandleGatherSharesResponse(
- const std::vector<smb_client::SmbUrl>& shares_gathered);
+ const std::vector<smb_client::SmbUrl>& shares_gathered,
+ bool done);
// Callback handler that indicates discovery is complete.
void HandleDiscoveryDone();
diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc
index c7cc5bffd2d..ac5be07201d 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc
@@ -19,7 +19,7 @@ namespace chromeos {
namespace smb_dialog {
namespace {
-constexpr int kSmbShareDialogHeight = 524;
+constexpr int kSmbShareDialogHeight = 564;
void AddSmbSharesStrings(content::WebUIDataSource* html_source) {
// Add strings specific to smb_dialog.
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
index 4e2a7e1b96e..4a50ff51a44 100644
--- 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
@@ -20,6 +20,8 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source) {
{"smbShareName", IDS_SETTINGS_DOWNLOADS_ADD_SHARE_NAME},
{"smbShareUsername", IDS_SETTINGS_DOWNLOADS_ADD_SHARE_USERNAME},
{"smbSharePassword", IDS_SETTINGS_DOWNLOADS_ADD_SHARE_PASSWORD},
+ {"smbShareSaveCredentials",
+ IDS_SETTINGS_DOWNLOADS_ADD_SHARE_SAVE_CREDENTIALS},
{"smbShareAuthenticationMethod",
IDS_SETTINGS_DOWNLOADS_ADD_SHARE_AUTHENTICATION_METHOD},
{"smbShareStandardAuthentication",
diff --git a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_browsertest.cc b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_browsertest.cc
index f5205f41736..ce3b17a3858 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_browsertest.cc
@@ -23,7 +23,6 @@
#include "content/public/common/web_preferences.h"
#include "services/service_manager/public/cpp/connector.h"
#include "ui/aura/client/aura_constants.h"
-#include "ui/base/ui_base_features.h"
#include "url/gurl.h"
namespace chromeos {
@@ -82,10 +81,8 @@ IN_PROC_BROWSER_TEST_F(SystemWebDialogLoginTest, NonModalTest) {
dialog->ShowSystemDialog();
EXPECT_FALSE(ash::ShellTestApi().IsSystemModalWindowOpen());
aura::Window* window_to_test = dialog->dialog_window();
- // In Mash, the AlwaysOnTop property will be set on the parent.
- if (::features::IsUsingWindowService())
- window_to_test = window_to_test->parent();
- EXPECT_TRUE(window_to_test->GetProperty(aura::client::kAlwaysOnTopKey));
+ EXPECT_NE(ui::ZOrderLevel::kNormal,
+ window_to_test->GetProperty(aura::client::kZOrderingKey));
}
using SystemWebDialogTest = InProcessBrowserTest;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc
index 8e4841b0bf3..6fcd5cd124a 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc
@@ -91,6 +91,11 @@ void SystemWebDialogDelegate::Focus() {
dialog_window()->Focus();
}
+void SystemWebDialogDelegate::Close() {
+ DCHECK(dialog_window());
+ views::Widget::GetWidgetForNativeWindow(dialog_window())->Close();
+}
+
ui::ModalType SystemWebDialogDelegate::GetDialogModalType() const {
return modal_type_;
}
@@ -149,16 +154,20 @@ bool SystemWebDialogDelegate::ShouldShowDialogTitle() const {
return !title_.empty();
}
-void SystemWebDialogDelegate::ShowSystemDialog(gfx::NativeWindow parent) {
- content::BrowserContext* browser_context =
- ProfileManager::GetActiveUserProfile();
+void SystemWebDialogDelegate::ShowSystemDialogForBrowserContext(
+ content::BrowserContext* browser_context,
+ gfx::NativeWindow parent) {
views::Widget::InitParams extra_params;
// If unparented and not modal, keep it on top (see header comment).
if (!parent && GetDialogModalType() == ui::MODAL_TYPE_NONE)
- extra_params.keep_on_top = true;
+ extra_params.z_order = ui::ZOrderLevel::kFloatingWindow;
AdjustWidgetInitParams(&extra_params);
dialog_window_ = chrome::ShowWebDialogWithParams(parent, browser_context,
this, &extra_params);
}
+void SystemWebDialogDelegate::ShowSystemDialog(gfx::NativeWindow parent) {
+ ShowSystemDialogForBrowserContext(ProfileManager::GetActiveUserProfile(),
+ parent);
+}
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h b/chromium/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h
index f18c91cbc43..e9b0e2fd4f7 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
@@ -49,6 +49,9 @@ class SystemWebDialogDelegate : public ui::WebDialogDelegate {
// implementation for details.
void Focus();
+ // Closes the dialog window.
+ void Close();
+
// ui::WebDialogDelegate
ui::ModalType GetDialogModalType() const override;
base::string16 GetDialogTitle() const override;
@@ -66,10 +69,14 @@ class SystemWebDialogDelegate : public ui::WebDialogDelegate {
bool* out_close_dialog) override;
bool ShouldShowDialogTitle() const override;
- // Shows a system dialog using the current ative profile.
+ // Shows a system dialog using the specified BrowserContext (or Profile).
// If |parent| is not null, the dialog will be parented to |parent|.
// Otherwise it will be attached to either the AlwaysOnTop container or the
// LockSystemModal container, depending on the session state at creation.
+ void ShowSystemDialogForBrowserContext(content::BrowserContext* context,
+ gfx::NativeWindow parent = nullptr);
+ // Same as previous but shows a system dialog using the current active
+ // profile.
void ShowSystemDialog(gfx::NativeWindow parent = nullptr);
content::WebUI* GetWebUIForTest() { return webui_; }
diff --git a/chromium/chrome/browser/ui/webui/chromeos/terminal/OWNERS b/chromium/chrome/browser/ui/webui/chromeos/terminal/OWNERS
new file mode 100644
index 00000000000..7cec5666d6e
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/terminal/OWNERS
@@ -0,0 +1,4 @@
+calamity@chromium.org
+joelhockey@chromium.org
+
+# COMPONENT: UI>Shell>Containers
diff --git a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc
new file mode 100644
index 00000000000..889a692e022
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.cc
@@ -0,0 +1,61 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/chromeos/terminal/terminal_source.h"
+
+#include "base/files/file_path.h"
+#include "base/files/file_util.h"
+#include "base/memory/ref_counted_memory.h"
+#include "base/strings/string_util.h"
+#include "base/task/post_task.h"
+#include "base/task/task_traits.h"
+#include "chrome/common/url_constants.h"
+#include "chrome/common/webui_url_constants.h"
+#include "net/base/mime_util.h"
+
+namespace {
+// TODO(crbug.com/846546): Initially set to load crosh, but change to
+// terminal when it is available.
+constexpr base::FilePath::CharType kTerminalRoot[] =
+ FILE_PATH_LITERAL("/usr/share/chromeos-assets/crosh_builtin");
+constexpr base::FilePath::CharType kDefaultFile[] =
+ FILE_PATH_LITERAL("html/crosh.html");
+constexpr char kDefaultMime[] = "text/html";
+
+void ReadFile(const base::FilePath& path,
+ const content::URLDataSource::GotDataCallback& callback) {
+ std::string content;
+ CHECK(base::ReadFileToString(path, &content)) << path;
+ scoped_refptr<base::RefCountedString> response =
+ base::RefCountedString::TakeString(&content);
+ callback.Run(response.get());
+}
+} // namespace
+
+std::string TerminalSource::GetSource() {
+ return chrome::kChromeUITerminalHost;
+}
+
+void TerminalSource::StartDataRequest(
+ const std::string& path,
+ const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
+ const content::URLDataSource::GotDataCallback& callback) {
+ base::FilePath file_path(kTerminalRoot);
+ if (path.empty()) {
+ file_path = file_path.Append(kDefaultFile);
+ } else {
+ file_path = file_path.Append(path);
+ }
+ base::PostTaskWithTraits(
+ FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
+ base::BindOnce(&ReadFile, file_path, callback));
+}
+
+std::string TerminalSource::GetMimeType(const std::string& path) {
+ std::string mime_type(kDefaultMime);
+ std::string ext = base::FilePath(path).Extension();
+ if (!ext.empty())
+ net::GetWellKnownMimeTypeFromExtension(ext.substr(1), &mime_type);
+ return mime_type;
+}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h
new file mode 100644
index 00000000000..dc922840e02
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_source.h
@@ -0,0 +1,32 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_TERMINAL_TERMINAL_SOURCE_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_TERMINAL_TERMINAL_SOURCE_H_
+
+#include <string>
+
+#include "base/macros.h"
+#include "content/public/browser/resource_request_info.h"
+#include "content/public/browser/url_data_source.h"
+
+class TerminalSource : public content::URLDataSource {
+ public:
+ TerminalSource() = default;
+ ~TerminalSource() override = default;
+
+ private:
+ std::string GetSource() override;
+
+ void StartDataRequest(
+ const std::string& path,
+ const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
+ const content::URLDataSource::GotDataCallback& callback) override;
+
+ std::string GetMimeType(const std::string& path) override;
+
+ DISALLOW_COPY_AND_ASSIGN(TerminalSource);
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_TERMINAL_TERMINAL_SOURCE_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_ui.cc
new file mode 100644
index 00000000000..012f4a98466
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_ui.cc
@@ -0,0 +1,16 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/chromeos/terminal/terminal_ui.h"
+
+#include <memory>
+
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/webui/chromeos/terminal/terminal_source.h"
+#include "content/public/browser/url_data_source.h"
+
+TerminalUI::TerminalUI(content::WebUI* web_ui) : WebUIController(web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+ content::URLDataSource::Add(profile, std::make_unique<TerminalSource>());
+}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_ui.h b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_ui.h
new file mode 100644
index 00000000000..d87b3f313e3
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/terminal/terminal_ui.h
@@ -0,0 +1,19 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_TERMINAL_TERMINAL_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_TERMINAL_TERMINAL_UI_H_
+
+#include "base/macros.h"
+#include "content/public/browser/web_ui_controller.h"
+
+class TerminalUI : public content::WebUIController {
+ public:
+ explicit TerminalUI(content::WebUI* web_ui);
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(TerminalUI);
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_TERMINAL_TERMINAL_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc
index 1702ebc2bef..63c867618b6 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.cc
@@ -173,7 +173,7 @@ UserImageSource::UserImageSource() {}
UserImageSource::~UserImageSource() {}
-std::string UserImageSource::GetSource() const {
+std::string UserImageSource::GetSource() {
return chrome::kChromeUIUserImageHost;
}
@@ -189,7 +189,7 @@ void UserImageSource::StartDataRequest(
callback.Run(GetUserImageInternal(account_id, frame));
}
-std::string UserImageSource::GetMimeType(const std::string& path) const {
+std::string UserImageSource::GetMimeType(const std::string& path) {
// We need to explicitly return a mime type, otherwise if the user tries to
// drag the image they get no extension.
return "image/png";
diff --git a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h
index 287a21bb130..1e73aed0637 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/user_image_source.h
@@ -30,12 +30,12 @@ class UserImageSource : public content::URLDataSource {
~UserImageSource() override;
// content::URLDataSource implementation.
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override;
- std::string GetMimeType(const std::string& path) const override;
+ std::string GetMimeType(const std::string& path) override;
// Returns PNG encoded image for user with specified |account_id|. If there's
// no user with such an id, returns the first default image. Always returns
diff --git a/chromium/chrome/browser/ui/webui/chromeos/video_source.cc b/chromium/chrome/browser/ui/webui/chromeos/video_source.cc
index c42955ad542..4db1b33388d 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/video_source.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/video_source.cc
@@ -62,7 +62,7 @@ VideoSource::VideoSource() : weak_factory_(this) {
VideoSource::~VideoSource() {}
-std::string VideoSource::GetSource() const {
+std::string VideoSource::GetSource() {
return chrome::kChromeOSAssetHost;
}
@@ -85,7 +85,7 @@ void VideoSource::StartDataRequest(
got_data_callback));
}
-std::string VideoSource::GetMimeType(const std::string& path) const {
+std::string VideoSource::GetMimeType(const std::string& path) {
std::string mime_type;
std::string ext = base::FilePath(path).Extension();
if (!ext.empty())
diff --git a/chromium/chrome/browser/ui/webui/chromeos/video_source.h b/chromium/chrome/browser/ui/webui/chromeos/video_source.h
index 12a1a884896..316509a93ec 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/video_source.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/video_source.h
@@ -28,13 +28,13 @@ class VideoSource : public content::URLDataSource {
~VideoSource() override;
// content::URLDataSource:
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& got_data_callback)
override;
- std::string GetMimeType(const std::string& path) const override;
+ std::string GetMimeType(const std::string& path) override;
private:
// Continuation from StartDataRequest().
diff --git a/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc
index 3bbd42d7a49..9ee1634110a 100644
--- a/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc
@@ -18,7 +18,6 @@
#include "chrome/browser/ui/webui/constrained_web_dialog_ui.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
-#include "components/viz/common/features.h"
#include "components/web_modal/web_contents_modal_dialog_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
@@ -109,25 +108,6 @@ class ConstrainedWebDialogBrowserTest : public InProcessBrowserTest {
}
};
-class ConstrainedWebDialogSurfaceSynchronizationBrowserTest
- : public ConstrainedWebDialogBrowserTest {
- public:
- ConstrainedWebDialogSurfaceSynchronizationBrowserTest() = default;
- ~ConstrainedWebDialogSurfaceSynchronizationBrowserTest() override = default;
-
- void SetUp() override {
- scoped_feature_list_.InitAndEnableFeature(
- features::kEnableSurfaceSynchronization);
- ConstrainedWebDialogBrowserTest::SetUp();
- }
-
- private:
- base::test::ScopedFeatureList scoped_feature_list_;
-
- DISALLOW_COPY_AND_ASSIGN(
- ConstrainedWebDialogSurfaceSynchronizationBrowserTest);
-};
-
// Tests that opening/closing the constrained window won't crash it.
IN_PROC_BROWSER_TEST_F(ConstrainedWebDialogBrowserTest, BasicTest) {
auto delegate = std::make_unique<ui::test::TestWebDialogDelegate>(
@@ -256,90 +236,6 @@ IN_PROC_BROWSER_TEST_F(ConstrainedWebDialogBrowserTest,
dialog_delegate)));
}
-// This test is equivalent to
-// ConstrainedWebDialogBrowserTest.ContentResizeInAutoResizingDialog but
-// has the surface synchronization flag turned on. Once surface synchronization
-// is on by default, this test can be deleted.
-// TODO(fsamuel): Fix this for Mac too.
-#if defined(USE_AURA)
-// Flaky on CrOS: http://crbug.com/928924
-#if defined(OS_CHROMEOS)
-#define MAYBE_ContentResizeInAutoResizingDialog \
- DISABLED_ContentResizeInAutoResizingDialog
-#else
-#define MAYBE_ContentResizeInAutoResizingDialog \
- ContentResizeInAutoResizingDialog
-#endif
-IN_PROC_BROWSER_TEST_F(ConstrainedWebDialogSurfaceSynchronizationBrowserTest,
- MAYBE_ContentResizeInAutoResizingDialog) {
- // During auto-resizing, dialogs size to (WebContents size) + 16.
- const int dialog_border_space = 16;
-
- // Expected dialog sizes after auto-resizing.
- const int initial_size = 150 + dialog_border_space;
- const int new_size = 175 + dialog_border_space;
-
- auto delegate =
- std::make_unique<AutoResizingTestWebDialogDelegate>(GURL(kTestDataURL));
- WebContents* web_contents =
- browser()->tab_strip_model()->GetActiveWebContents();
- ASSERT_TRUE(web_contents);
-
- // Observes the next created WebContents.
- content::TestNavigationObserver observer(nullptr);
- observer.StartWatchingNewWebContents();
-
- gfx::Size min_size = gfx::Size(100, 100);
- gfx::Size max_size = gfx::Size(200, 200);
- gfx::Size initial_dialog_size;
-
- delegate->GetDialogSize(&initial_dialog_size);
-
- ConstrainedWebDialogDelegate* dialog_delegate =
- ShowConstrainedWebDialogWithAutoResize(browser()->profile(),
- std::move(delegate), web_contents,
- min_size, max_size);
- ASSERT_TRUE(dialog_delegate);
- EXPECT_TRUE(dialog_delegate->GetNativeDialog());
- ASSERT_FALSE(IsShowingWebContentsModalDialog(web_contents));
- EXPECT_EQ(min_size, dialog_delegate->GetConstrainedWebDialogMinimumSize());
- EXPECT_EQ(max_size, dialog_delegate->GetConstrainedWebDialogMaximumSize());
-
- // Check for initial sizing. Dialog was created as a 400x400 dialog.
- ASSERT_EQ(initial_dialog_size,
- dialog_delegate->GetConstrainedWebDialogPreferredSize());
-
- observer.Wait();
-
- // Wait until the entire WebContents has loaded.
- WaitForLoadStop(dialog_delegate->GetWebContents());
-
- ASSERT_TRUE(IsShowingWebContentsModalDialog(web_contents));
-
- // Resize to content's originally set dimensions.
- ASSERT_TRUE(RunLoopUntil(base::Bind(
- &IsEqualSizes, gfx::Size(initial_size, initial_size), dialog_delegate)));
-
- // Resize to dimensions within expected bounds.
- EXPECT_TRUE(ExecuteScript(dialog_delegate->GetWebContents(),
- GetChangeDimensionsScript(175)));
- ASSERT_TRUE(RunLoopUntil(base::Bind(
- &IsEqualSizes, gfx::Size(new_size, new_size), dialog_delegate)));
-
- // Resize to dimensions smaller than the minimum bounds.
- EXPECT_TRUE(ExecuteScript(dialog_delegate->GetWebContents(),
- GetChangeDimensionsScript(50)));
- ASSERT_TRUE(
- RunLoopUntil(base::Bind(&IsEqualSizes, min_size, dialog_delegate)));
-
- // Resize to dimensions greater than the maximum bounds.
- EXPECT_TRUE(ExecuteScript(dialog_delegate->GetWebContents(),
- GetChangeDimensionsScript(250)));
- ASSERT_TRUE(
- RunLoopUntil(base::Bind(&IsEqualSizes, max_size, dialog_delegate)));
-}
-#endif // USE_AURA
-
// Tests that dialog does not autoresize when autoresizing is not enabled.
IN_PROC_BROWSER_TEST_F(ConstrainedWebDialogBrowserTest,
ContentResizeInNonAutoResizingDialog) {
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 9c411e462fc..1e98254cceb 100644
--- a/chromium/chrome/browser/ui/webui/cookies_tree_model_util.cc
+++ b/chromium/chrome/browser/ui/webui/cookies_tree_model_util.cc
@@ -185,13 +185,13 @@ bool CookiesTreeModelUtil::GetCookieTreeNodeDictionary(
dict->SetString(kKeyOrigin, file_system_info.origin.Serialize());
dict->SetString(
kKeyPersistent,
- base::ContainsKey(file_system_info.usage_map, kPerm)
+ base::Contains(file_system_info.usage_map, kPerm)
? base::UTF16ToUTF8(ui::FormatBytes(
file_system_info.usage_map.find(kPerm)->second))
: l10n_util::GetStringUTF8(IDS_COOKIES_FILE_SYSTEM_USAGE_NONE));
dict->SetString(
kKeyTemporary,
- base::ContainsKey(file_system_info.usage_map, kTemp)
+ base::Contains(file_system_info.usage_map, kTemp)
? base::UTF16ToUTF8(ui::FormatBytes(
file_system_info.usage_map.find(kTemp)->second))
: l10n_util::GetStringUTF8(IDS_COOKIES_FILE_SYSTEM_USAGE_NONE));
@@ -299,24 +299,21 @@ bool CookiesTreeModelUtil::GetCookieTreeNodeDictionary(
}
void CookiesTreeModelUtil::GetChildNodeDetails(const CookieTreeNode* parent,
- int start,
- int count,
bool include_quota_nodes,
base::ListValue* list) {
std::string id_path = GetTreeNodeId(parent);
- for (int i = 0; i < count; ++i) {
- const CookieTreeNode* child = parent->GetChild(start + i);
- int cookie_count = child->child_count();
- std::string cookie_id_path = id_path + "," + GetTreeNodeId(child) + ",";
- for (int k = 0; k < cookie_count; ++k) {
- const CookieTreeNode* details = child->GetChild(k);
+ for (const auto& child : parent->children()) {
+ std::string cookie_id_path =
+ id_path + "," + GetTreeNodeId(child.get()) + ",";
+ for (const auto& details : child->children()) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
if (GetCookieTreeNodeDictionary(*details, include_quota_nodes,
dict.get())) {
// TODO(dschuyler): This ID path is an artifact from using tree nodes to
// hold the cookies. Can this be changed to a dictionary with a key
// lookup (and remove use of id_map_)?
- dict->SetString("idPath", cookie_id_path + GetTreeNodeId(details));
+ dict->SetString("idPath",
+ cookie_id_path + GetTreeNodeId(details.get()));
list->Append(std::move(dict));
}
}
@@ -324,13 +321,13 @@ void CookiesTreeModelUtil::GetChildNodeDetails(const CookieTreeNode* parent,
}
void CookiesTreeModelUtil::GetChildNodeList(const CookieTreeNode* parent,
- int start,
- int count,
+ size_t start,
+ size_t count,
bool include_quota_nodes,
base::ListValue* nodes) {
- for (int i = 0; i < count; ++i) {
+ for (size_t i = 0; i < count; ++i) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
- const CookieTreeNode* child = parent->GetChild(start + i);
+ const CookieTreeNode* child = parent->children()[start + i].get();
if (GetCookieTreeNodeDictionary(*child, include_quota_nodes, dict.get()))
nodes->Append(std::move(dict));
}
@@ -364,14 +361,10 @@ const CookieTreeNode* CookiesTreeModelUtil::GetTreeNodeFromPath(
const CookieTreeNode* CookiesTreeModelUtil::GetTreeNodeFromTitle(
const CookieTreeNode* root,
const base::string16& title) {
- // TODO(dschuyler): This method reduces an old O(n^2) lookup with an O(n)
- // lookup for O(1) space, but it could be further improved to O(1) lookup if
- // desired (by trading O(n) space for the time improvement).
- int site_count = root->child_count();
- for (int i = 0; i < site_count; ++i) {
- const CookieTreeNode* child = root->GetChild(i);
- if (title == child->GetTitle())
- return child;
- }
- return nullptr;
+ // TODO(dschuyler): This is an O(n) lookup for O(1) space, but it could be
+ // improved to O(1) lookup if desired (by using O(n) space).
+ const auto i = std::find_if(
+ root->children().cbegin(), root->children().cend(),
+ [&title](const auto& child) { return title == child->GetTitle(); });
+ return (i == root->children().cend()) ? nullptr : i->get();
}
diff --git a/chromium/chrome/browser/ui/webui/cookies_tree_model_util.h b/chromium/chrome/browser/ui/webui/cookies_tree_model_util.h
index 02c30f4882d..9573508bca4 100644
--- a/chromium/chrome/browser/ui/webui/cookies_tree_model_util.h
+++ b/chromium/chrome/browser/ui/webui/cookies_tree_model_util.h
@@ -29,17 +29,15 @@ class CookiesTreeModelUtil {
// Finds or creates an ID for given |node| and returns it as string.
std::string GetTreeNodeId(const CookieTreeNode* node);
- // Append the details of the child nodes of |parent| in specified range.
+ // Append the details of the child nodes of |parent|.
void GetChildNodeDetails(const CookieTreeNode* parent,
- int start,
- int count,
bool include_quota_nodes,
base::ListValue* list);
// Append the children nodes of |parent| in specified range to |nodes| list.
void GetChildNodeList(const CookieTreeNode* parent,
- int start,
- int count,
+ size_t start,
+ size_t count,
bool include_quota_nodes,
base::ListValue* nodes);
diff --git a/chromium/chrome/browser/ui/webui/dark_mode_handler.cc b/chromium/chrome/browser/ui/webui/dark_mode_handler.cc
deleted file mode 100644
index 3569eb0c7a9..00000000000
--- a/chromium/chrome/browser/ui/webui/dark_mode_handler.cc
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
-
-#include "base/bind.h"
-#include "base/feature_list.h"
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/values.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/ui_features.h"
-#include "content/public/browser/web_ui.h"
-#include "content/public/browser/web_ui_data_source.h"
-#include "ui/native_theme/native_theme.h"
-
-DarkModeHandler::~DarkModeHandler() {}
-
-// static
-void DarkModeHandler::Initialize(content::WebUI* web_ui,
- content::WebUIDataSource* source) {
- InitializeInternal(web_ui, source, ui::NativeTheme::GetInstanceForNativeUi(),
- Profile::FromWebUI(web_ui));
-}
-
-// static
-void DarkModeHandler::InitializeInternal(content::WebUI* web_ui,
- content::WebUIDataSource* source,
- ui::NativeTheme* theme,
- Profile* profile) {
- auto handler = base::WrapUnique(new DarkModeHandler(theme, profile));
- source->AddLocalizedStrings(*handler->GetDataSourceUpdate());
- handler->source_name_ = source->GetSource();
- web_ui->AddMessageHandler(std::move(handler));
-}
-
-DarkModeHandler::DarkModeHandler(ui::NativeTheme* theme, Profile* profile)
- : profile_(profile),
- dark_mode_observer_(
- theme,
- base::BindRepeating(&DarkModeHandler::OnDarkModeChanged,
- base::Unretained(this))) {
- dark_mode_observer_.Start();
-}
-
-void DarkModeHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "observeDarkMode",
- base::BindRepeating(&DarkModeHandler::HandleObserveDarkMode,
- base::Unretained(this)));
-}
-
-void DarkModeHandler::HandleObserveDarkMode(const base::ListValue* /*args*/) {
- AllowJavascript();
-}
-
-bool DarkModeHandler::UseDarkMode() const {
- return base::FeatureList::IsEnabled(features::kWebUIDarkMode) &&
- dark_mode_observer_.InDarkMode();
-}
-
-std::unique_ptr<base::DictionaryValue> DarkModeHandler::GetDataSourceUpdate()
- const {
- auto update = std::make_unique<base::DictionaryValue>();
- bool use_dark_mode = UseDarkMode();
- update->SetKey("dark", base::Value(use_dark_mode ? "dark" : ""));
- return update;
-}
-
-void DarkModeHandler::OnDarkModeChanged(bool /*dark_mode*/) {
- content::WebUIDataSource::Update(profile_, source_name_,
- GetDataSourceUpdate());
- if (IsJavascriptAllowed())
- FireWebUIListener("dark-mode-changed", base::Value(UseDarkMode()));
-}
diff --git a/chromium/chrome/browser/ui/webui/dark_mode_handler.h b/chromium/chrome/browser/ui/webui/dark_mode_handler.h
deleted file mode 100644
index 5215589978d..00000000000
--- a/chromium/chrome/browser/ui/webui/dark_mode_handler.h
+++ /dev/null
@@ -1,81 +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_DARK_MODE_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_DARK_MODE_HANDLER_H_
-
-#include <memory>
-#include <string>
-
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/scoped_observer.h"
-#include "content/public/browser/web_ui_message_handler.h"
-#include "ui/native_theme/dark_mode_observer.h"
-#include "ui/native_theme/native_theme.h"
-
-namespace base {
-class ListValue;
-} // namespace base
-
-namespace content {
-class WebUI;
-class WebUIDataSource;
-} // namespace content
-
-namespace ui {
-class NativeTheme;
-} // namespace ui
-
-class Profile;
-
-class DarkModeHandler : public content::WebUIMessageHandler {
- public:
- ~DarkModeHandler() override;
-
- // Sets load-time constants on |source|. This handles a flicker-free initial
- // page load (i.e. $i18n{dark}, loadTimeData.getBoolean('darkMode')). Adds a
- // DarkModeHandler to |web_ui| if WebUI dark mode enhancements are enabled.
- // If enabled, continually updates |source| by name if dark mode changes. This
- // is so page refreshes will have fresh, correct data. Neither |web_ui| nor
- // |source| may be nullptr.
- static void Initialize(content::WebUI* web_ui,
- content::WebUIDataSource* source);
-
- protected:
- // Protected for testing.
- static void InitializeInternal(content::WebUI* web_ui,
- content::WebUIDataSource* source,
- ui::NativeTheme* theme,
- Profile* profile);
-
- explicit DarkModeHandler(ui::NativeTheme* theme, Profile* profile);
-
- private:
- // content::WebUIMessageHandler:
- void RegisterMessages() override;
-
- // Handles the "observeDarkMode" message. No arguments. Protected for testing.
- void HandleObserveDarkMode(const base::ListValue* args);
-
- bool UseDarkMode() const;
-
- // Generates a dictionary with "dark" i18n key based on |using_dark_|. Called
- // in Initialize() and on each change for notifications.
- std::unique_ptr<base::DictionaryValue> GetDataSourceUpdate() const;
-
- void OnDarkModeChanged(bool dark_mode);
-
- // Profile to update data sources on. Injected for testing.
- Profile* const profile_;
-
- ui::DarkModeObserver dark_mode_observer_;
-
- // Populated if feature is enabled.
- std::string source_name_;
-
- DISALLOW_COPY_AND_ASSIGN(DarkModeHandler);
-};
-
-#endif // CHROME_BROWSER_UI_WEBUI_DARK_MODE_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/dark_mode_handler_unittest.cc b/chromium/chrome/browser/ui/webui/dark_mode_handler_unittest.cc
deleted file mode 100644
index 8efcdd048ee..00000000000
--- a/chromium/chrome/browser/ui/webui/dark_mode_handler_unittest.cc
+++ /dev/null
@@ -1,212 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
-
-#include "base/test/scoped_feature_list.h"
-#include "base/token.h"
-#include "base/values.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/ui_features.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 "content/public/test/test_web_ui_data_source.h"
-#include "testing/gtest/include/gtest/gtest.h"
-#include "ui/native_theme/test_native_theme.h"
-
-class TestDarkModeHandler : public DarkModeHandler {
- public:
- using DarkModeHandler::InitializeInternal;
-};
-
-class DarkModeHandlerTest : public testing::Test {
- public:
- DarkModeHandlerTest()
- : source_(content::TestWebUIDataSource::Create(
- base::Token::CreateRandom().ToString())) {
- // We use a random source_name here as calling Add() can replace existing
- // sources with the same name (which might destroy the memory addressed by
- // |source()->GetWebUIDataSource()|.
- content::WebUIDataSource::Add(&profile_, source()->GetWebUIDataSource());
- }
-
- content::TestBrowserThreadBundle* bundle() { return &bundle_; }
- content::TestWebUI* web_ui() { return &web_ui_; }
- ui::TestNativeTheme* theme() { return &theme_; }
- base::test::ScopedFeatureList* features() { return &features_; }
- content::TestWebUIDataSource* source() { return source_.get(); }
-
- void InitializeHandler() {
- TestDarkModeHandler::InitializeInternal(
- web_ui(), source()->GetWebUIDataSource(), theme(), &profile_);
- }
-
- bool IsSourceDark() {
- const auto* replacements = source()->GetReplacements();
- const auto dark_it = replacements->find("dark");
-
- if (dark_it == replacements->end()) {
- ADD_FAILURE();
- return false;
- }
-
- return dark_it->second == "dark";
- }
-
- private:
- content::TestBrowserThreadBundle bundle_;
- TestingProfile profile_;
- base::test::ScopedFeatureList features_;
- content::TestWebUI web_ui_;
- ui::TestNativeTheme theme_;
- std::unique_ptr<content::TestWebUIDataSource> source_;
-};
-
-TEST_F(DarkModeHandlerTest, WebUIDarkModeDisabledLightMode) {
- features()->InitAndDisableFeature(features::kWebUIDarkMode);
- theme()->SetDarkMode(false);
-
- InitializeHandler();
-
- EXPECT_EQ(web_ui()->GetHandlersForTesting()->size(), 1u);
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
-
- EXPECT_FALSE(IsSourceDark());
-}
-
-TEST_F(DarkModeHandlerTest, WebUIDarkModeDisabledDarkMode) {
- features()->InitAndDisableFeature(features::kWebUIDarkMode);
- theme()->SetDarkMode(true);
-
- InitializeHandler();
-
- EXPECT_EQ(web_ui()->GetHandlersForTesting()->size(), 1u);
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
-
- // Even if in dark mode, if the feature's disabled we shouldn't be telling the
- // page to be dark.
- EXPECT_FALSE(IsSourceDark());
-}
-
-TEST_F(DarkModeHandlerTest, WebUIDarkModeDisabledNoNotifications) {
- features()->InitAndDisableFeature(features::kWebUIDarkMode);
- theme()->SetDarkMode(false);
-
- InitializeHandler();
-
- EXPECT_EQ(web_ui()->GetHandlersForTesting()->size(), 1u);
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
- EXPECT_FALSE(IsSourceDark());
-
- theme()->SetDarkMode(true);
- theme()->NotifyObservers();
-
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
- EXPECT_FALSE(IsSourceDark());
-}
-
-TEST_F(DarkModeHandlerTest, WebUIDarkModeEnabledInLightMode) {
- features()->InitAndEnableFeature(features::kWebUIDarkMode);
- theme()->SetDarkMode(false);
-
- InitializeHandler();
-
- EXPECT_EQ(web_ui()->GetHandlersForTesting()->size(), 1u);
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
-
- EXPECT_FALSE(IsSourceDark());
-}
-
-TEST_F(DarkModeHandlerTest, WebUIDarkModeEnabledInDarkMode) {
- features()->InitAndEnableFeature(features::kWebUIDarkMode);
- theme()->SetDarkMode(true);
-
- InitializeHandler();
-
- EXPECT_EQ(web_ui()->GetHandlersForTesting()->size(), 1u);
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
-
- EXPECT_TRUE(IsSourceDark());
-}
-
-TEST_F(DarkModeHandlerTest, NotifiesAndUpdatesOnChange) {
- features()->InitAndEnableFeature(features::kWebUIDarkMode);
- theme()->SetDarkMode(false);
-
- InitializeHandler();
-
- ASSERT_EQ(web_ui()->GetHandlersForTesting()->size(), 1u);
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
-
- EXPECT_FALSE(IsSourceDark());
-
- web_ui()->HandleReceivedMessage("observeDarkMode", /*args=*/nullptr);
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
-
- // Theme changes unrelated to dark mode should not notify.
- theme()->NotifyObservers();
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
-
- theme()->SetDarkMode(true);
- theme()->NotifyObservers();
- bundle()->RunUntilIdle();
-
- EXPECT_TRUE(IsSourceDark());
- ASSERT_EQ(web_ui()->call_data().size(), 1u);
-
- EXPECT_STREQ(web_ui()->call_data()[0]->function_name().c_str(),
- "cr.webUIListenerCallback");
-
- ASSERT_TRUE(web_ui()->call_data()[0]->arg1());
- ASSERT_TRUE(web_ui()->call_data()[0]->arg1()->is_string());
- EXPECT_STREQ(web_ui()->call_data()[0]->arg1()->GetString().c_str(),
- "dark-mode-changed");
-
- ASSERT_TRUE(web_ui()->call_data()[0]->arg2());
- ASSERT_TRUE(web_ui()->call_data()[0]->arg2()->is_bool());
- EXPECT_TRUE(web_ui()->call_data()[0]->arg2()->GetBool());
-}
-
-TEST_F(DarkModeHandlerTest, DarkModeChangeBeforeJsAllowed) {
- features()->InitAndEnableFeature(features::kWebUIDarkMode);
- theme()->SetDarkMode(false);
-
- InitializeHandler();
-
- EXPECT_EQ(web_ui()->GetHandlersForTesting()->size(), 1u);
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
- EXPECT_FALSE(IsSourceDark());
-
- theme()->SetDarkMode(true);
- theme()->NotifyObservers();
-
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
-
- bundle()->RunUntilIdle();
- EXPECT_TRUE(IsSourceDark());
-}
-
-TEST_F(DarkModeHandlerTest, DarkModeChangeWhileJsDisallowed) {
- features()->InitAndEnableFeature(features::kWebUIDarkMode);
- theme()->SetDarkMode(false);
-
- InitializeHandler();
-
- EXPECT_EQ(web_ui()->GetHandlersForTesting()->size(), 1u);
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
- EXPECT_FALSE(IsSourceDark());
-
- web_ui()->HandleReceivedMessage("observeDarkMode", /*args=*/nullptr);
- web_ui()->GetHandlersForTesting()->front()->DisallowJavascript();
-
- theme()->SetDarkMode(true);
- theme()->NotifyObservers();
-
- EXPECT_EQ(web_ui()->call_data().size(), 0u);
-
- bundle()->RunUntilIdle();
- EXPECT_TRUE(IsSourceDark());
-}
diff --git a/chromium/chrome/browser/ui/webui/device_log_ui.cc b/chromium/chrome/browser/ui/webui/device_log_ui.cc
index b87b5d35b9d..1eb85455185 100644
--- a/chromium/chrome/browser/ui/webui/device_log_ui.cc
+++ b/chromium/chrome/browser/ui/webui/device_log_ui.cc
@@ -36,6 +36,10 @@ class DeviceLogMessageHandler : public content::WebUIMessageHandler {
"DeviceLog.getLog",
base::BindRepeating(&DeviceLogMessageHandler::GetLog,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "DeviceLog.clearLog",
+ base::BindRepeating(&DeviceLogMessageHandler::ClearLog,
+ base::Unretained(this)));
}
private:
@@ -46,6 +50,10 @@ class DeviceLogMessageHandler : public content::WebUIMessageHandler {
web_ui()->CallJavascriptFunctionUnsafe("DeviceLogUI.getLogCallback", data);
}
+ void ClearLog(const base::ListValue* value) const {
+ device_event_log::ClearAll();
+ }
+
DISALLOW_COPY_AND_ASSIGN(DeviceLogMessageHandler);
};
@@ -62,6 +70,8 @@ DeviceLogUI::DeviceLogUI(content::WebUI* web_ui)
{"titleText", IDS_DEVICE_LOG_TITLE},
{"autoRefreshText", IDS_DEVICE_AUTO_REFRESH},
{"logRefreshText", IDS_DEVICE_LOG_REFRESH},
+ {"logClearText", IDS_DEVICE_LOG_CLEAR},
+ {"logNoEntriesText", IDS_DEVICE_LOG_NO_ENTRIES},
{"logLevelShowText", IDS_DEVICE_LOG_LEVEL_SHOW},
{"logLevelErrorText", IDS_DEVICE_LOG_LEVEL_ERROR},
{"logLevelUserText", IDS_DEVICE_LOG_LEVEL_USER},
diff --git a/chromium/chrome/browser/ui/webui/devtools_ui.cc b/chromium/chrome/browser/ui/webui/devtools_ui.cc
index 0643144e2ac..a9cc1d845e7 100644
--- a/chromium/chrome/browser/ui/webui/devtools_ui.cc
+++ b/chromium/chrome/browser/ui/webui/devtools_ui.cc
@@ -94,7 +94,7 @@ class DevToolsDataSource : public content::URLDataSource {
~DevToolsDataSource() override = default;
// content::URLDataSource implementation.
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
@@ -105,10 +105,10 @@ class DevToolsDataSource : public content::URLDataSource {
struct PendingRequest;
// content::URLDataSource overrides.
- std::string GetMimeType(const std::string& path) const override;
- bool ShouldAddContentSecurityPolicy() const override;
- bool ShouldDenyXFrameOptions() const override;
- bool ShouldServeMimeTypeAsContentTypeHeader() const override;
+ std::string GetMimeType(const std::string& path) override;
+ bool ShouldAddContentSecurityPolicy() override;
+ bool ShouldDenyXFrameOptions() override;
+ bool ShouldServeMimeTypeAsContentTypeHeader() override;
void OnLoadComplete(std::list<PendingRequest>::iterator request_iter,
std::unique_ptr<std::string> response_body);
@@ -158,7 +158,7 @@ class DevToolsDataSource : public content::URLDataSource {
DISALLOW_COPY_AND_ASSIGN(DevToolsDataSource);
};
-std::string DevToolsDataSource::GetSource() const {
+std::string DevToolsDataSource::GetSource() {
return chrome::kChromeUIDevToolsHost;
}
@@ -235,19 +235,19 @@ void DevToolsDataSource::StartDataRequest(
callback.Run(NULL);
}
-std::string DevToolsDataSource::GetMimeType(const std::string& path) const {
+std::string DevToolsDataSource::GetMimeType(const std::string& path) {
return GetMimeTypeForPath(path);
}
-bool DevToolsDataSource::ShouldAddContentSecurityPolicy() const {
+bool DevToolsDataSource::ShouldAddContentSecurityPolicy() {
return false;
}
-bool DevToolsDataSource::ShouldDenyXFrameOptions() const {
+bool DevToolsDataSource::ShouldDenyXFrameOptions() {
return false;
}
-bool DevToolsDataSource::ShouldServeMimeTypeAsContentTypeHeader() const {
+bool DevToolsDataSource::ShouldServeMimeTypeAsContentTypeHeader() {
return true;
}
diff --git a/chromium/chrome/browser/ui/webui/discards/DEPS b/chromium/chrome/browser/ui/webui/discards/DEPS
new file mode 100644
index 00000000000..f452a3a9db6
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/discards/DEPS
@@ -0,0 +1,5 @@
+specific_include_rules = {
+ "discards_ui.h": [
+ "+chrome/browser/performance_manager/webui_graph_dump.mojom.h",
+ ],
+}
diff --git a/chromium/chrome/browser/ui/webui/discards/discards.mojom b/chromium/chrome/browser/ui/webui/discards/discards.mojom
index 54935aec13d..61d5f81d1cc 100644
--- a/chromium/chrome/browser/ui/webui/discards/discards.mojom
+++ b/chromium/chrome/browser/ui/webui/discards/discards.mojom
@@ -5,6 +5,7 @@
module mojom;
import "chrome/browser/resource_coordinator/lifecycle_unit_state.mojom";
+import "mojo/public/mojom/base/time.mojom";
// Identical to content::Visibility.
enum LifecycleUnitVisibility {
@@ -127,6 +128,8 @@ struct TabDiscardsInfo {
double site_engagement_score;
// Whether or not the tab has input focus.
bool has_focus;
+ // Delta between Unix Epoch and time at which the lifecycle state has changed.
+ mojo_base.mojom.TimeDelta state_change_time;
};
// Interface for providing information about discards. Lives in the browser
diff --git a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc
index 16b79b5584d..597f062d388 100644
--- a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc
+++ b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc
@@ -26,10 +26,13 @@
#include "chrome/browser/resource_coordinator/tab_manager.h"
#include "chrome/browser/resource_coordinator/time.h"
#include "chrome/browser/ui/webui/discards/discards.mojom.h"
+#include "chrome/browser/ui/webui/favicon_source.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/browser_resources.h"
+#include "components/favicon_base/favicon_url_parser.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
+#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
@@ -227,6 +230,8 @@ class DiscardsDetailsProviderImpl : public mojom::DiscardsDetailsProvider {
if (info->has_reactivation_score)
info->reactivation_score = reactivation_score.value();
info->site_engagement_score = GetSiteEngagementScore(contents);
+ info->state_change_time =
+ lifecycle_unit->GetStateChangeTime() - base::TimeTicks::UnixEpoch();
// TODO(crbug.com/876340): The focus is used to compute the page lifecycle
// state. This should be replaced with the actual page lifecycle state
// information from Blink, but this depends on implementing the passive
@@ -432,6 +437,10 @@ DiscardsUI::DiscardsUI(content::WebUI* web_ui)
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource::Add(profile, source.release());
+ content::URLDataSource::Add(
+ profile, std::make_unique<FaviconSource>(
+ profile, chrome::FaviconUrlFormat::kFavicon2));
+
AddHandlerToRegistry(base::BindRepeating(
&DiscardsUI::BindDiscardsDetailsProvider, base::Unretained(this)));
AddHandlerToRegistry(base::BindRepeating(
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 e0976b8a67f..148a71455e2 100644
--- a/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc
@@ -16,7 +16,7 @@
DomainReliabilityInternalsUI::DomainReliabilityInternalsUI(
content::WebUI* web_ui)
- : content::WebUIController(web_ui), weak_factory_(this) {
+ : content::WebUIController(web_ui) {
content::WebUIDataSource* html_source = content::WebUIDataSource::Create(
chrome::kChromeUIDomainReliabilityInternalsHost);
html_source->OverrideContentSecurityPolicyScriptSrc(
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 62436b50896..384474ea70b 100644
--- a/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.h
+++ b/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.h
@@ -26,7 +26,7 @@ class DomainReliabilityInternalsUI : public content::WebUIController {
void UpdateData(const base::ListValue* args);
void OnDataUpdated(base::Value data) const;
- base::WeakPtrFactory<DomainReliabilityInternalsUI> weak_factory_;
+ base::WeakPtrFactory<DomainReliabilityInternalsUI> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DomainReliabilityInternalsUI);
};
diff --git a/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.cc b/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.cc
index 9988db2e568..eb6d5d61bf2 100644
--- a/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.cc
+++ b/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.cc
@@ -17,7 +17,7 @@
namespace download_internals {
DownloadInternalsUIMessageHandler::DownloadInternalsUIMessageHandler()
- : download_service_(nullptr), weak_ptr_factory_(this) {}
+ : download_service_(nullptr) {}
DownloadInternalsUIMessageHandler::~DownloadInternalsUIMessageHandler() {
if (download_service_)
@@ -42,7 +42,8 @@ void DownloadInternalsUIMessageHandler::RegisterMessages() {
weak_ptr_factory_.GetWeakPtr()));
Profile* profile = Profile::FromWebUI(web_ui());
- download_service_ = DownloadServiceFactory::GetForBrowserContext(profile);
+ download_service_ =
+ DownloadServiceFactory::GetForKey(profile->GetProfileKey());
download_service_->GetLogger()->AddObserver(this);
}
diff --git a/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.h b/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.h
index ac0a3c645b6..2fb3159cde8 100644
--- a/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.h
+++ b/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.h
@@ -44,7 +44,8 @@ class DownloadInternalsUIMessageHandler : public content::WebUIMessageHandler,
download::DownloadService* download_service_;
- base::WeakPtrFactory<DownloadInternalsUIMessageHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<DownloadInternalsUIMessageHandler> weak_ptr_factory_{
+ this};
DISALLOW_COPY_AND_ASSIGN(DownloadInternalsUIMessageHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc b/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc
index dee48d78b57..8b51693ecd6 100644
--- a/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc
+++ b/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc
@@ -23,6 +23,7 @@
#include "chrome/browser/extensions/api/downloads/downloads_api.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
+#include "components/download/public/common/download_danger_type.h"
#include "components/download/public/common/download_item.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/download_item_utils.h"
@@ -58,6 +59,10 @@ const char* GetDangerTypeString(download::DownloadDangerType danger_type) {
return "DANGEROUS_HOST";
case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED:
return "POTENTIALLY_UNWANTED";
+ case download::DOWNLOAD_DANGER_TYPE_ASYNC_SCANNING:
+ return "ASYNC_SCANNING";
+ case download::DOWNLOAD_DANGER_TYPE_BLOCKED_PASSWORD_PROTECTED:
+ return "BLOCKED_PASSWORD_PROTECTED";
case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS:
case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT:
case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED:
diff --git a/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc b/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc
index 0a90fa6ea04..b2b55ef537a 100644
--- a/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc
+++ b/chromium/chrome/browser/ui/webui/downloads/downloads_ui.cc
@@ -16,7 +16,6 @@
#include "chrome/browser/defaults.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/safe_browsing/advanced_protection_status_manager.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
#include "chrome/browser/ui/webui/downloads/downloads_dom_handler.h"
#include "chrome/browser/ui/webui/localized_string.h"
#include "chrome/browser/ui/webui/managed_ui_handler.h"
@@ -167,7 +166,6 @@ DownloadsUI::DownloadsUI(content::WebUI* web_ui)
// Set up the chrome://downloads/ source.
content::WebUIDataSource* source = CreateDownloadsUIHTMLSource(profile);
- DarkModeHandler::Initialize(web_ui, source);
ManagedUIHandler::Initialize(web_ui, source);
content::WebUIDataSource::Add(profile, source);
content::URLDataSource::Add(profile, std::make_unique<ThemeSource>(profile));
diff --git a/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.cc b/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.cc
deleted file mode 100644
index 1f11aa2d6ab..00000000000
--- a/chromium/chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.cc
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/eoc_internals/eoc_internals_ui.h"
-
-#include "base/bind.h"
-#include "build/build_config.h"
-#include "chrome/browser/ntp_snippets/contextual_content_suggestions_service_factory.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/eoc_internals/eoc_internals_page_handler.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/browser_resources.h"
-#include "content/public/browser/web_ui_data_source.h"
-
-#if defined(OS_ANDROID)
-#include "chrome/browser/android/chrome_feature_list.h"
-#endif
-
-using contextual_suggestions::ContextualContentSuggestionsService;
-
-EocInternalsUI::EocInternalsUI(content::WebUI* web_ui)
- : ui::MojoWebUIController(web_ui) {
- content::WebUIDataSource* source =
- content::WebUIDataSource::Create(chrome::kChromeUIEocInternalsHost);
-
- source->AddResourcePath("eoc_internals.css", IDR_EOC_INTERNALS_CSS);
- source->AddResourcePath("eoc_internals.js", IDR_EOC_INTERNALS_JS);
- source->AddResourcePath("eoc_internals.mojom-lite.js",
- IDR_EOC_INTERNALS_MOJOM_LITE_JS);
- source->SetDefaultResource(IDR_EOC_INTERNALS_HTML);
-
- Profile* profile = Profile::FromWebUI(web_ui);
- contextual_content_suggestions_service_ =
- ContextualContentSuggestionsServiceFactory::GetForProfile(profile);
- content::WebUIDataSource::Add(profile, source);
- // This class is the caller of the callback when an observer interface is
- // triggered. So this base::Unretained is safe.
- AddHandlerToRegistry(base::BindRepeating(
- &EocInternalsUI::BindEocInternalsPageHandler, base::Unretained(this)));
-}
-
-EocInternalsUI::~EocInternalsUI() {}
-
-void EocInternalsUI::BindEocInternalsPageHandler(
- eoc_internals::mojom::PageHandlerRequest request) {
- page_handler_.reset(new EocInternalsPageHandler(
- std::move(request), contextual_content_suggestions_service_));
-}
diff --git a/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_page_handler.cc
index d259e914d2d..b336e92d1f8 100644
--- a/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_page_handler.cc
+++ b/chromium/chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_page_handler.cc
@@ -28,8 +28,6 @@ std::string GetChromeFlagsSetupString() {
return "Experiment";
case ExploreSitesVariation::PERSONALIZED:
return "Personalized";
- case ExploreSitesVariation::CONDENSED:
- return "Condensed";
case ExploreSitesVariation::MOST_LIKELY:
return "Most Likely";
case ExploreSitesVariation::DISABLED:
@@ -59,7 +57,7 @@ void ExploreSitesInternalsPageHandler::GetProperties(
void ExploreSitesInternalsPageHandler::ClearCachedExploreSitesCatalog(
ClearCachedExploreSitesCatalogCallback callback) {
- if (ExploreSitesVariation::ENABLED != GetExploreSitesVariation()) {
+ if (ExploreSitesVariation::DISABLED == GetExploreSitesVariation()) {
std::move(callback).Run(false);
return;
}
@@ -79,7 +77,7 @@ void ExploreSitesInternalsPageHandler::ForceNetworkRequest(
void ExploreSitesInternalsPageHandler::OverrideCountryCode(
const std::string& country_code,
OverrideCountryCodeCallback callback) {
- if (ExploreSitesVariation::ENABLED != GetExploreSitesVariation()) {
+ if (ExploreSitesVariation::DISABLED == GetExploreSitesVariation()) {
std::move(callback).Run(false);
return;
}
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 eded33bb9ed..618914d559b 100644
--- a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc
+++ b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.cc
@@ -102,11 +102,11 @@ SkBitmap* ExtensionIconSource::LoadImageByResourceId(int resource_id) {
return ToBitmap(data, contents.length());
}
-std::string ExtensionIconSource::GetSource() const {
+std::string ExtensionIconSource::GetSource() {
return chrome::kChromeUIExtensionIconHost;
}
-std::string ExtensionIconSource::GetMimeType(const std::string&) const {
+std::string ExtensionIconSource::GetMimeType(const std::string&) {
// We need to explicitly return a mime type, otherwise if the user tries to
// drag the image they get no extension.
return "image/png";
@@ -139,7 +139,7 @@ void ExtensionIconSource::StartDataRequest(
}
}
-bool ExtensionIconSource::AllowCaching() const {
+bool ExtensionIconSource::AllowCaching() {
// Should not be cached to reflect the latest contents that may be updated by
// Extensions.
return false;
diff --git a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h
index 62cee4a823f..c7be8dc828f 100644
--- a/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h
+++ b/chromium/chrome/browser/ui/webui/extensions/extension_icon_source.h
@@ -68,13 +68,13 @@ class ExtensionIconSource : public content::URLDataSource,
static SkBitmap* LoadImageByResourceId(int resource_id);
// content::URLDataSource implementation.
- std::string GetSource() const override;
- std::string GetMimeType(const std::string&) const override;
+ std::string GetSource() override;
+ std::string GetMimeType(const std::string&) override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override;
- bool AllowCaching() const override;
+ bool AllowCaching() override;
private:
// Encapsulates the request parameters for |request_id|.
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 f7449ee2f38..9c1963ef46f 100644
--- a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc
+++ b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc
@@ -12,6 +12,7 @@
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/numerics/safe_conversions.h"
+#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
@@ -23,6 +24,9 @@
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/process_manager.h"
+#include "extensions/common/manifest_handlers/permissions_parser.h"
+#include "extensions/common/permissions/permission_set.h"
+#include "extensions/common/permissions/permissions_data.h"
namespace {
@@ -116,6 +120,14 @@ base::Value CreationFlagsToList(int creation_flags) {
}
// The JSON we generate looks like this:
+// Note:
+// - tab_specific permissions can have 0 or more DICT entries with each tab id
+// pointing to the api, explicit_host, manifest and scriptable_host permission
+// lists.
+// - In some cases manifest or api permissions rather than just being a STRING
+// can be a DICT with the name keying a more complex object with detailed
+// information. This is the case for subclasses of ManifestPermission and
+// APIPermission which override the ToValue function.
//
// [ {
// "creation_flags": [ "ALLOW_FILE_ACCESS", "FROM_WEBSTORE" ],
@@ -139,6 +151,33 @@ base::Value CreationFlagsToList(int creation_flags) {
// "manifest_version": 2,
// "name": "Earth View from Google Earth",
// "path": "/user/Extensions/bhloflhklmhfpedakmangadcdofhnnoh/2.18.5_0",
+// "permissions": {
+// "active": {
+// "api": [ ],
+// "explicit_hosts": [ ],
+// "manifest": [ ],
+// "scriptable_hosts": [ ]
+// },
+// "optional": {
+// "api": [ ],
+// "explicit_hosts": [ ],
+// "manifest": [ ],
+// "scriptable_hosts": [ ]
+// },
+// "tab_specific": {
+// "4": {
+// "api": [ ],
+// "explicit_hosts": [ ],
+// "manifest": [ ],
+// "scriptable_hosts": [ ]
+// }
+// },
+// "withheld": {
+// "api": [ ],
+// "explicit_hosts": [ ],
+// "manifest": [ ],
+// "scriptable_hosts": [ ]
+// },
// "type": "TYPE_EXTENSION",
// "version": "2.18.5"
// } ]
@@ -169,6 +208,37 @@ base::Value CreationFlagsToList(int creation_flags) {
// "manifest_version": INT
// "name": STRING
// "path": STRING
+// "permissions": DICT
+// "active": DICT
+// "api": LIST
+// STRING
+// (see note above for edge cases on all "api" and "manfest" entries)
+// "explicit_hosts": LIST
+// STRING
+// "manifest": LIST
+// STRING
+// "scriptable_hosts": LIST
+// STRING
+// "optional": DICT
+// "api": LIST
+// STRING
+// "explicit_hosts": LIST
+// STRING
+// "manifest": LIST
+// STRING
+// "scriptable_hosts": LIST
+// STRING
+// "tab_specific": DICT
+// (see note above for details)
+// "withheld": DICT
+// "api": LIST
+// STRING
+// "explicit_hosts": LIST
+// STRING
+// "manifest": LIST
+// STRING
+// "scriptable_hosts": LIST
+// STRING
// "type": STRING
// "version": STRING
@@ -190,6 +260,15 @@ constexpr base::StringPiece kListenerUrlKey = "url";
constexpr base::StringPiece kLocationKey = "location";
constexpr base::StringPiece kManifestVersionKey = "manifest_version";
constexpr base::StringPiece kPathKey = "path";
+constexpr base::StringPiece kPermissionsKey = "permissions";
+constexpr base::StringPiece kPermissionsActiveKey = "active";
+constexpr base::StringPiece kPermissionsOptionalKey = "optional";
+constexpr base::StringPiece kPermissionsTabSpecificKey = "tab_specific";
+constexpr base::StringPiece kPermissionsWithheldKey = "withheld";
+constexpr base::StringPiece kPermissionsApiKey = "api";
+constexpr base::StringPiece kPermissionsManifestKey = "manifest";
+constexpr base::StringPiece kPermissionsExplicitHostsKey = "explicit_hosts";
+constexpr base::StringPiece kPermissionsScriptableHostsKey = "scriptable_hosts";
constexpr base::StringPiece kTypeKey = "type";
base::Value FormatKeepaliveData(extensions::ProcessManager* process_manager,
@@ -213,6 +292,75 @@ base::Value FormatKeepaliveData(extensions::ProcessManager* process_manager,
return keepalive_data;
}
+// Formats API and Manifest permissions, which can have details that we add as a
+// dictionary rather than just the string name
+template <typename T>
+base::Value FormatDetailedPermissionSet(const T& permissions) {
+ base::Value value_list(base::Value::Type::LIST);
+ value_list.GetList().reserve(permissions.size());
+ for (const auto& permission : permissions) {
+ std::unique_ptr<base::Value> detail(permission->ToValue());
+ if (detail) {
+ base::Value tmp(base::Value::Type::DICTIONARY);
+ tmp.SetKey(permission->name(),
+ base::Value::FromUniquePtrValue(std::move(detail)));
+ value_list.GetList().push_back(std::move(tmp));
+ } else {
+ value_list.GetList().push_back(base::Value(permission->name()));
+ }
+ }
+ return value_list;
+}
+
+base::Value FormatPermissionSet(
+ const extensions::PermissionSet& permission_set) {
+ base::Value value(base::Value::Type::DICTIONARY);
+
+ value.SetKey(kPermissionsExplicitHostsKey,
+ base::Value::FromUniquePtrValue(
+ permission_set.explicit_hosts().ToValue()));
+ value.SetKey(kPermissionsScriptableHostsKey,
+ base::Value::FromUniquePtrValue(
+ permission_set.scriptable_hosts().ToValue()));
+ value.SetKey(
+ kPermissionsManifestKey,
+ FormatDetailedPermissionSet(permission_set.manifest_permissions()));
+ value.SetKey(kPermissionsApiKey,
+ FormatDetailedPermissionSet(permission_set.apis()));
+
+ return value;
+}
+
+base::Value FormatPermissionsData(const extensions::Extension& extension) {
+ const extensions::PermissionsData& permissions =
+ *extension.permissions_data();
+ base::Value permissions_data(base::Value::Type::DICTIONARY);
+
+ const extensions::PermissionSet& active_permissions =
+ permissions.active_permissions();
+ permissions_data.SetKey(kPermissionsActiveKey,
+ FormatPermissionSet(active_permissions));
+
+ const extensions::PermissionSet& withheld_permissions =
+ permissions.withheld_permissions();
+ permissions_data.SetKey(kPermissionsWithheldKey,
+ FormatPermissionSet(withheld_permissions));
+
+ base::Value tab_specific(base::Value::Type::DICTIONARY);
+ for (const auto& tab : permissions.tab_specific_permissions()) {
+ tab_specific.SetKey(base::NumberToString(tab.first),
+ FormatPermissionSet(*tab.second));
+ }
+ permissions_data.SetKey(kPermissionsTabSpecificKey, std::move(tab_specific));
+
+ const extensions::PermissionSet& optional_permissions =
+ extensions::PermissionsParser::GetOptionalPermissions(&extension);
+ permissions_data.SetKey(kPermissionsOptionalKey,
+ FormatPermissionSet(optional_permissions));
+
+ return permissions_data;
+}
+
void AddEventListenerData(extensions::EventRouter* event_router,
base::Value* data) {
CHECK(data->is_list());
@@ -277,12 +425,11 @@ ExtensionsInternalsSource::ExtensionsInternalsSource(Profile* profile)
ExtensionsInternalsSource::~ExtensionsInternalsSource() = default;
-std::string ExtensionsInternalsSource::GetSource() const {
+std::string ExtensionsInternalsSource::GetSource() {
return chrome::kChromeUIExtensionsInternalsHost;
}
-std::string ExtensionsInternalsSource::GetMimeType(
- const std::string& path) const {
+std::string ExtensionsInternalsSource::GetMimeType(const std::string& path) {
return "text/plain";
}
@@ -320,6 +467,7 @@ std::string ExtensionsInternalsSource::WriteToString() const {
base::Value(TypeToString(extension->GetType())));
extension_data.SetKey(kInternalsVersionKey,
base::Value(extension->GetVersionForDisplay()));
+ extension_data.SetKey(kPermissionsKey, FormatPermissionsData(*extension));
data.GetList().push_back(std::move(extension_data));
}
diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h
index c848a0a5041..4a8a6cabeaf 100644
--- a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h
+++ b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.h
@@ -18,8 +18,8 @@ class ExtensionsInternalsSource : public content::URLDataSource {
~ExtensionsInternalsSource() override;
// content::URLDataSource:
- std::string GetSource() const override;
- std::string GetMimeType(const std::string& path) const override;
+ std::string GetSource() override;
+ std::string GetMimeType(const std::string& path) override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_unittest.cc b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_unittest.cc
new file mode 100644
index 00000000000..170ad2c67d1
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_unittest.cc
@@ -0,0 +1,227 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/extensions/extensions_internals_source.h"
+
+#include "base/bind.h"
+#include "base/json/json_reader.h"
+#include "base/values.h"
+#include "chrome/browser/extensions/extension_service.h"
+#include "chrome/browser/extensions/extension_service_test_base.h"
+#include "chrome/browser/extensions/permissions_updater.h"
+#include "chrome/browser/extensions/scripting_permissions_modifier.h"
+#include "chrome/test/base/testing_profile.h"
+#include "components/version_info/channel.h"
+#include "extensions/browser/event_router.h"
+#include "extensions/browser/event_router_factory.h"
+#include "extensions/browser/extension_prefs.h"
+#include "extensions/browser/extension_registry.h"
+#include "extensions/common/extension_builder.h"
+#include "extensions/common/features/feature_channel.h"
+#include "extensions/common/permissions/api_permission.h"
+#include "extensions/common/permissions/api_permission_set.h"
+#include "extensions/common/permissions/manifest_permission_set.h"
+#include "extensions/common/permissions/permission_set.h"
+#include "extensions/common/permissions/permissions_data.h"
+#include "extensions/common/url_pattern_set.h"
+#include "extensions/common/user_script.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "url/gurl.h"
+
+namespace {
+
+using ExtensionsInternalsUnitTest = extensions::ExtensionServiceTestBase;
+
+std::unique_ptr<KeyedService> BuildEventRouter(
+ content::BrowserContext* profile) {
+ return std::make_unique<extensions::EventRouter>(
+ profile, extensions::ExtensionPrefs::Get(profile));
+}
+
+} // namespace
+
+// Test that active and optional permissions show up correctly in the JSON
+// returned by WriteToString.
+TEST_F(ExtensionsInternalsUnitTest, WriteToStringPermissions) {
+ // The automation manifest entry is restricted to the dev channel, so we do
+ // this so the test is fine on stable/beta.
+ extensions::ScopedCurrentChannel current_channel(version_info::Channel::DEV);
+
+ InitializeEmptyExtensionService();
+ extensions::EventRouterFactory::GetInstance()->SetTestingFactory(
+ profile(), base::BindRepeating(&BuildEventRouter));
+
+ scoped_refptr<const extensions::Extension> extension =
+ extensions::ExtensionBuilder("test")
+ .AddPermission("activeTab")
+ .SetManifestKey("automation", true)
+ .SetManifestKey("optional_permissions",
+ extensions::ListBuilder().Append("storage").Build())
+ .AddPermission("https://example.com/*")
+ .AddContentScript("not-real.js", {"https://chromium.org/foo"})
+ .Build();
+ service()->AddExtension(extension.get());
+
+ ExtensionsInternalsSource source(profile());
+ auto extensions_list = base::JSONReader::Read(source.WriteToString());
+ ASSERT_TRUE(extensions_list) << "Failed to parse extensions internals json.";
+
+ EXPECT_EQ(extensions_list->GetList().size(), 1U);
+
+ base::Value* extension_1 = &extensions_list->GetList().at(0);
+ ASSERT_TRUE(extension_1->is_dict());
+ base::Value* permissions = extension_1->FindDictKey("permissions");
+ ASSERT_TRUE(permissions);
+
+ // Permissions section should always have four elements: active, optional,
+ // tab-specific and withheld.
+ EXPECT_EQ(permissions->DictSize(), 4U);
+
+ base::Value* active = permissions->FindDictKey("active");
+ ASSERT_NE(active->FindListKey("api"), nullptr);
+ EXPECT_EQ(active->FindListKey("api")->GetList().at(0).GetString(),
+ "activeTab");
+ ASSERT_NE(active->FindListKey("manifest"), nullptr);
+ EXPECT_TRUE(active->FindListKey("manifest")
+ ->GetList()
+ .at(0)
+ .FindBoolKey("automation"));
+ ASSERT_NE(active->FindListKey("explicit_hosts"), nullptr);
+ EXPECT_EQ(active->FindListKey("explicit_hosts")->GetList().at(0).GetString(),
+ "https://example.com/*");
+ ASSERT_NE(active->FindListKey("scriptable_hosts"), nullptr);
+ EXPECT_EQ(
+ active->FindListKey("scriptable_hosts")->GetList().at(0).GetString(),
+ "https://chromium.org/foo");
+
+ base::Value* optional = permissions->FindDictKey("optional");
+ EXPECT_EQ(optional->FindListKey("api")->GetList().at(0).GetString(),
+ "storage");
+}
+
+// Test that tab-specific permissions show up correctly in the JSON returned by
+// WriteToString.
+TEST_F(ExtensionsInternalsUnitTest, WriteToStringTabSpecificPermissions) {
+ InitializeEmptyExtensionService();
+ extensions::EventRouterFactory::GetInstance()->SetTestingFactory(
+ profile(), base::BindRepeating(&BuildEventRouter));
+
+ scoped_refptr<const extensions::Extension> extension =
+ extensions::ExtensionBuilder("test").AddPermission("activeTab").Build();
+ service()->AddExtension(extension.get());
+
+ ExtensionsInternalsSource source(profile());
+ auto extensions_list = base::JSONReader::Read(source.WriteToString());
+ ASSERT_TRUE(extensions_list) << "Failed to parse extensions internals json.";
+ base::Value* permissions =
+ extensions_list->GetList().at(0).FindDictKey("permissions");
+
+ // Check that initially there is no tab-scpecific data.
+ EXPECT_EQ(permissions->FindDictKey("tab_specific")->DictSize(), 0U);
+
+ // Grant a tab specific permission to the extension.
+ extensions::APIPermissionSet tab_api_permissions;
+ tab_api_permissions.insert(extensions::APIPermission::kTab);
+ extensions::URLPatternSet tab_hosts;
+ tab_hosts.AddOrigin(extensions::UserScript::ValidUserScriptSchemes(),
+ GURL("https://google.com/*"));
+ extensions::PermissionSet tab_permissions(
+ std::move(tab_api_permissions), extensions::ManifestPermissionSet(),
+ tab_hosts.Clone(), tab_hosts.Clone());
+ extension->permissions_data()->UpdateTabSpecificPermissions(1,
+ tab_permissions);
+ extensions_list = base::JSONReader::Read(source.WriteToString());
+ permissions = extensions_list->GetList().at(0).FindDictKey("permissions");
+
+ // Check the tab specific data is present now.
+ base::Value* tab_specific = permissions->FindDictKey("tab_specific");
+ EXPECT_TRUE(tab_specific->is_dict());
+ EXPECT_EQ(tab_specific->DictSize(), 1U);
+ EXPECT_EQ(tab_specific->FindDictKey("1")
+ ->FindListKey("explicit_hosts")
+ ->GetList()
+ .at(0)
+ .GetString(),
+ "https://google.com/*");
+ EXPECT_EQ(tab_specific->FindDictKey("1")
+ ->FindListKey("scriptable_hosts")
+ ->GetList()
+ .at(0)
+ .GetString(),
+ "https://google.com/*");
+ EXPECT_EQ(tab_specific->FindDictKey("1")
+ ->FindListKey("api")
+ ->GetList()
+ .at(0)
+ .GetString(),
+ "tabs");
+}
+
+// Test that withheld permissions show up correctly in the JSON returned by
+// WriteToString.
+TEST_F(ExtensionsInternalsUnitTest, WriteToStringWithheldPermissions) {
+ InitializeEmptyExtensionService();
+ extensions::EventRouterFactory::GetInstance()->SetTestingFactory(
+ profile(), base::BindRepeating(&BuildEventRouter));
+
+ scoped_refptr<const extensions::Extension> extension =
+ extensions::ExtensionBuilder("test")
+ .AddPermission("https://example.com/*")
+ .Build();
+ service()->AddExtension(extension.get());
+
+ ExtensionsInternalsSource source(profile());
+ auto extensions_list = base::JSONReader::Read(source.WriteToString());
+ ASSERT_TRUE(extensions_list) << "Failed to parse extensions internals json.";
+ base::Value* permissions =
+ extensions_list->GetList().at(0).FindDictKey("permissions");
+
+ // Check the host is initially in active hosts and there are no withheld
+ // entries.
+ EXPECT_EQ(permissions->FindDictKey("active")
+ ->FindListKey("explicit_hosts")
+ ->GetList()
+ .at(0)
+ .GetString(),
+ "https://example.com/*");
+ EXPECT_EQ(permissions->FindDictKey("withheld")
+ ->FindListKey("api")
+ ->GetList()
+ .size(),
+ 0U);
+ EXPECT_EQ(permissions->FindDictKey("withheld")
+ ->FindListKey("manifest")
+ ->GetList()
+ .size(),
+ 0U);
+ EXPECT_EQ(permissions->FindDictKey("withheld")
+ ->FindListKey("explicit_hosts")
+ ->GetList()
+ .size(),
+ 0U);
+ EXPECT_EQ(permissions->FindDictKey("withheld")
+ ->FindListKey("scriptable_hosts")
+ ->GetList()
+ .size(),
+ 0U);
+
+ // Change an active host to be withheld.
+ extensions::ScriptingPermissionsModifier modifier(profile(), extension);
+ modifier.SetWithholdHostPermissions(true);
+ extensions_list = base::JSONReader::Read(source.WriteToString());
+ permissions = extensions_list->GetList().at(0).FindDictKey("permissions");
+
+ // Check the host that was active is now withheld.
+ EXPECT_EQ(permissions->FindDictKey("active")
+ ->FindListKey("explicit_hosts")
+ ->GetList()
+ .size(),
+ 0U);
+ EXPECT_EQ(permissions->FindDictKey("withheld")
+ ->FindListKey("explicit_hosts")
+ ->GetList()
+ .at(0)
+ .GetString(),
+ "https://example.com/*");
+}
diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc
index f98590304f6..b08cee7d5bd 100644
--- a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc
+++ b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc
@@ -10,14 +10,11 @@
#include "base/bind.h"
#include "base/command_line.h"
-#include "base/metrics/histogram_macros.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/timer/elapsed_timer.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/chrome_extension_browser_constants.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
#include "chrome/browser/ui/webui/localized_string.h"
#include "chrome/browser/ui/webui/managed_ui_handler.h"
#include "chrome/browser/ui/webui/metrics_handler.h"
@@ -34,9 +31,6 @@
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "components/strings/grit/components_strings.h"
-#include "content/public/browser/navigation_handle.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "extensions/common/extension_urls.h"
@@ -57,51 +51,6 @@ constexpr char kInDevModeKey[] = "inDevMode";
constexpr char kShowActivityLogKey[] = "showActivityLog";
constexpr char kLoadTimeClassesKey[] = "loadTimeClasses";
-class ExtensionWebUiTimer : public content::WebContentsObserver {
- public:
- explicit ExtensionWebUiTimer(content::WebContents* web_contents)
- : content::WebContentsObserver(web_contents) {}
- ~ExtensionWebUiTimer() override {}
-
- void DidStartNavigation(
- content::NavigationHandle* navigation_handle) override {
- if (navigation_handle->IsInMainFrame() &&
- !navigation_handle->IsSameDocument()) {
- timer_.reset(new base::ElapsedTimer());
- }
- }
-
- void DocumentLoadedInFrame(
- content::RenderFrameHost* render_frame_host) override {
- if (render_frame_host != web_contents()->GetMainFrame() ||
- !timer_) { // See comment in DocumentOnLoadCompletedInMainFrame()
- return;
- }
- UMA_HISTOGRAM_TIMES("Extensions.WebUi.DocumentLoadedInMainFrameTime.MD",
- timer_->Elapsed());
- }
-
- void DocumentOnLoadCompletedInMainFrame() override {
- // TODO(devlin): The usefulness of these metrics remains to be seen.
- if (!timer_) {
- // This object could have been created for a child RenderFrameHost so it
- // would never get a DidStartNavigation with the main frame. However it
- // will receive this current callback.
- return;
- }
- UMA_HISTOGRAM_TIMES("Extensions.WebUi.LoadCompletedInMainFrame.MD",
- timer_->Elapsed());
- timer_.reset();
- }
-
- void WebContentsDestroyed() override { delete this; }
-
- private:
- std::unique_ptr<base::ElapsedTimer> timer_;
-
- DISALLOW_COPY_AND_ASSIGN(ExtensionWebUiTimer);
-};
-
std::string GetLoadTimeClasses(bool in_dev_mode) {
return in_dev_mode ? "in-dev-mode" : std::string();
}
@@ -362,7 +311,11 @@ content::WebUIDataSource* CreateMdExtensionsSource(Profile* profile,
} // namespace
-ExtensionsUI::ExtensionsUI(content::WebUI* web_ui) : WebUIController(web_ui) {
+ExtensionsUI::ExtensionsUI(content::WebUI* web_ui)
+ : WebUIController(web_ui),
+ webui_load_timer_(web_ui->GetWebContents(),
+ "Extensions.WebUi.DocumentLoadedInMainFrameTime.MD",
+ "Extensions.WebUi.LoadCompletedInMainFrame.MD") {
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource* source = nullptr;
@@ -371,7 +324,6 @@ ExtensionsUI::ExtensionsUI(content::WebUI* web_ui) : WebUIController(web_ui) {
base::Bind(&ExtensionsUI::OnDevModeChanged, base::Unretained(this)));
source = CreateMdExtensionsSource(profile, *in_dev_mode_);
- DarkModeHandler::Initialize(web_ui, source);
ManagedUIHandler::Initialize(web_ui, source);
#if defined(OS_CHROMEOS)
@@ -386,9 +338,6 @@ ExtensionsUI::ExtensionsUI(content::WebUI* web_ui) : WebUIController(web_ui) {
source->OverrideContentSecurityPolicyObjectSrc("object-src 'self';");
content::WebUIDataSource::Add(profile, source);
-
- // Handles its own lifetime.
- new ExtensionWebUiTimer(web_ui->GetWebContents());
}
ExtensionsUI::~ExtensionsUI() {}
diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.h b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.h
index b16cc35454c..71e5e754f91 100644
--- a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.h
+++ b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.h
@@ -6,6 +6,7 @@
#define CHROME_BROWSER_UI_WEBUI_EXTENSIONS_EXTENSIONS_UI_H_
#include "base/macros.h"
+#include "chrome/browser/ui/webui/webui_load_timer.h"
#include "components/prefs/pref_member.h"
#include "content/public/browser/web_ui_controller.h"
#include "ui/base/layout.h"
@@ -37,6 +38,8 @@ class ExtensionsUI : public content::WebUIController {
// Tracks whether developer mode is enabled.
BooleanPrefMember in_dev_mode_;
+ WebuiLoadTimer webui_load_timer_;
+
DISALLOW_COPY_AND_ASSIGN(ExtensionsUI);
};
diff --git a/chromium/chrome/browser/ui/webui/favicon_source.cc b/chromium/chrome/browser/ui/webui/favicon_source.cc
index c93c9e6bd63..5175c36ac4d 100644
--- a/chromium/chrome/browser/ui/webui/favicon_source.cc
+++ b/chromium/chrome/browser/ui/webui/favicon_source.cc
@@ -11,17 +11,16 @@
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/favicon/favicon_service_factory.h"
-#include "chrome/browser/favicon/large_icon_service_factory.h"
+#include "chrome/browser/favicon/history_ui_favicon_request_handler_factory.h"
#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 "chrome/common/webui_url_constants.h"
+#include "components/favicon/core/history_ui_favicon_request_handler.h"
#include "components/favicon_base/favicon_url_parser.h"
#include "components/history/core/browser/top_sites.h"
-#include "components/sync/driver/sync_service_utils.h"
#include "components/sync_sessions/open_tabs_ui_delegate.h"
#include "components/sync_sessions/session_sync_service.h"
#include "content/public/browser/web_contents.h"
@@ -34,71 +33,49 @@
#include "url/gurl.h"
namespace {
-favicon::FaviconRequestOrigin ParseFaviconRequestOrigin(const GURL& url) {
- GURL history_url(chrome::kChromeUIHistoryURL);
- if (url == history_url.Resolve(chrome::kChromeUIHistorySyncedTabs))
- return favicon::FaviconRequestOrigin::HISTORY_SYNCED_TABS;
- if (url == history_url)
- return favicon::FaviconRequestOrigin::HISTORY;
- return favicon::FaviconRequestOrigin::UNKNOWN;
-}
-sync_sessions::OpenTabsUIDelegate* GetOpenTabsUIDelegate(Profile* profile) {
- sync_sessions::SessionSyncService* session_sync_service =
- SessionSyncServiceFactory::GetInstance()->GetForProfile(profile);
- DCHECK(session_sync_service);
- return session_sync_service->GetOpenTabsUIDelegate();
-}
-
-scoped_refptr<base::RefCountedMemory> GetSyncedFaviconForPageURL(
- Profile* profile,
- const GURL& page_url) {
- sync_sessions::OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(profile);
- return open_tabs ? open_tabs->GetSyncedFaviconForPageURL(page_url.spec())
- : nullptr;
+// web_contents->GetLastCommittedURL in general will not necessarily yield the
+// original URL that started the request, but we're only interested in verifying
+// if it was issued by a history page, for whom this is the case. If it is not
+// possible to obtain the URL, we return the empty GURL.
+GURL GetUnsafeRequestOrigin(
+ const content::ResourceRequestInfo::WebContentsGetter& wc_getter) {
+ content::WebContents* web_contents = wc_getter.Run();
+ return web_contents ? web_contents->GetLastCommittedURL() : GURL();
}
-// Check if user settings allow querying a Google server using history
-// information.
-bool CanSendHistoryDataToServer(Profile* profile) {
- return syncer::GetUploadToGoogleState(
- ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile),
- syncer::ModelType::HISTORY_DELETE_DIRECTIVES) ==
- syncer::UploadState::ACTIVE;
+bool ParseHistoryUiOrigin(const GURL& url,
+ favicon::HistoryUiFaviconRequestOrigin* origin) {
+ GURL history_url(chrome::kChromeUIHistoryURL);
+ if (url == history_url) {
+ *origin = favicon::HistoryUiFaviconRequestOrigin::kHistory;
+ return true;
+ }
+ if (url == history_url.Resolve(chrome::kChromeUIHistorySyncedTabs)) {
+ *origin = favicon::HistoryUiFaviconRequestOrigin::kHistorySyncedTabs;
+ return true;
+ }
+ return false;
}
} // namespace
-FaviconSource::IconRequest::IconRequest()
- : size_in_dip(gfx::kFaviconSize),
- device_scale_factor(1.0f),
- icon_request_origin(favicon::FaviconRequestOrigin::UNKNOWN) {}
-
-FaviconSource::IconRequest::IconRequest(
- const content::URLDataSource::GotDataCallback& cb,
- const GURL& path,
- int size,
- float scale,
- favicon::FaviconRequestOrigin origin)
- : callback(cb),
- request_path(path),
- size_in_dip(size),
- device_scale_factor(scale),
- icon_request_origin(origin) {}
-
-FaviconSource::IconRequest::IconRequest(const IconRequest& other) = default;
-
-FaviconSource::IconRequest::~IconRequest() {
-}
-
-FaviconSource::FaviconSource(Profile* profile)
- : profile_(profile->GetOriginalProfile()) {}
+FaviconSource::FaviconSource(Profile* profile,
+ chrome::FaviconUrlFormat url_format)
+ : profile_(profile->GetOriginalProfile()), url_format_(url_format) {}
FaviconSource::~FaviconSource() {
}
-std::string FaviconSource::GetSource() const {
- return chrome::kChromeUIFaviconHost;
+std::string FaviconSource::GetSource() {
+ switch (url_format_) {
+ case chrome::FaviconUrlFormat::kFaviconLegacy:
+ return chrome::kChromeUIFaviconHost;
+ case chrome::FaviconUrlFormat::kFavicon2:
+ return chrome::kChromeUIFavicon2Host;
+ }
+ NOTREACHED();
+ return "";
}
void FaviconSource::StartDataRequest(
@@ -114,7 +91,7 @@ void FaviconSource::StartDataRequest(
}
chrome::ParsedFaviconPath parsed;
- bool success = chrome::ParseFaviconPath(path, &parsed);
+ bool success = chrome::ParseFaviconPath(path, url_format_, &parsed);
if (!success) {
SendDefaultResponse(callback);
return;
@@ -129,22 +106,14 @@ void FaviconSource::StartDataRequest(
int desired_size_in_pixel =
std::ceil(parsed.size_in_dip * parsed.device_scale_factor);
- content::WebContents* web_contents = wc_getter.Run();
- // web_contents->GetURL will not necessarily yield the original URL that
- // started the request, but for collecting metrics for chrome://history and
- // chrome://history/syncedTabs this will be ok.
- favicon::FaviconRequestOrigin unsafe_request_origin =
- web_contents ? ParseFaviconRequestOrigin(web_contents->GetURL())
- : favicon::FaviconRequestOrigin::UNKNOWN;
if (parsed.is_icon_url) {
// TODO(michaelbai): Change GetRawFavicon to support combination of
// IconType.
favicon_service->GetRawFavicon(
url, favicon_base::IconType::kFavicon, desired_size_in_pixel,
- base::BindRepeating(
- &FaviconSource::OnFaviconDataAvailable, base::Unretained(this),
- IconRequest(callback, url, parsed.size_in_dip,
- parsed.device_scale_factor, unsafe_request_origin)),
+ base::BindRepeating(&FaviconSource::OnFaviconDataAvailable,
+ base::Unretained(this), callback,
+ parsed.size_in_dip, parsed.device_scale_factor),
&cancelable_task_tracker_);
} else {
// Intercept requests for prepopulated pages if TopSites exists.
@@ -163,35 +132,62 @@ void FaviconSource::StartDataRequest(
}
}
}
+
+ favicon::HistoryUiFaviconRequestOrigin parsed_history_ui_origin;
+ if (!parsed.allow_favicon_server_fallback ||
+ !ParseHistoryUiOrigin(GetUnsafeRequestOrigin(wc_getter),
+ &parsed_history_ui_origin)) {
+ // Request from local storage only.
+ // TODO(victorvianna): Expose fallback_to_host in FaviconRequestHandler
+ // API and move the explanatory comment for |fallback_to_host| here.
+ const bool fallback_to_host = true;
+ favicon_service->GetRawFaviconForPageURL(
+ url, {favicon_base::IconType::kFavicon}, desired_size_in_pixel,
+ fallback_to_host,
+ base::Bind(&FaviconSource::OnFaviconDataAvailable,
+ base::Unretained(this), callback, parsed.size_in_dip,
+ parsed.device_scale_factor),
+ &cancelable_task_tracker_);
+ return;
+ }
+
+ // Request from both local storage and favicon server using
+ // HistoryUiFaviconRequestHandler.
+ favicon::HistoryUiFaviconRequestHandler*
+ history_ui_favicon_request_handler =
+ HistoryUiFaviconRequestHandlerFactory::GetForBrowserContext(
+ profile_);
+ if (!history_ui_favicon_request_handler) {
+ SendDefaultResponse(callback);
+ return;
+ }
+ sync_sessions::SessionSyncService* session_sync_service =
+ SessionSyncServiceFactory::GetInstance()->GetForProfile(profile_);
sync_sessions::OpenTabsUIDelegate* open_tabs =
- GetOpenTabsUIDelegate(profile_);
- favicon_request_handler_.GetRawFaviconForPageURL(
+ session_sync_service->GetOpenTabsUIDelegate();
+ history_ui_favicon_request_handler->GetRawFaviconForPageURL(
url, desired_size_in_pixel,
- base::BindOnce(
- &FaviconSource::OnFaviconDataAvailable, base::Unretained(this),
- IconRequest(callback, url, parsed.size_in_dip,
- parsed.device_scale_factor, unsafe_request_origin)),
- unsafe_request_origin, favicon::FaviconRequestPlatform::kDesktop,
- favicon_service,
- LargeIconServiceFactory::GetForBrowserContext(profile_),
+ base::BindOnce(&FaviconSource::OnFaviconDataAvailable,
+ base::Unretained(this), callback, parsed.size_in_dip,
+ parsed.device_scale_factor),
+ favicon::FaviconRequestPlatform::kDesktop, parsed_history_ui_origin,
/*icon_url_for_uma=*/
open_tabs ? open_tabs->GetIconUrlForPageUrl(url) : GURL(),
- base::BindOnce(&GetSyncedFaviconForPageURL, base::Unretained(profile_)),
- CanSendHistoryDataToServer(profile_), &cancelable_task_tracker_);
+ &cancelable_task_tracker_);
}
}
-std::string FaviconSource::GetMimeType(const std::string&) const {
+std::string FaviconSource::GetMimeType(const std::string&) {
// We need to explicitly return a mime type, otherwise if the user tries to
// drag the image they get no extension.
return "image/png";
}
-bool FaviconSource::AllowCaching() const {
+bool FaviconSource::AllowCaching() {
return false;
}
-bool FaviconSource::ShouldReplaceExistingSource() const {
+bool FaviconSource::ShouldReplaceExistingSource() {
// Leave the existing DataSource in place, otherwise we'll drop any pending
// requests on the floor.
return false;
@@ -200,7 +196,7 @@ bool FaviconSource::ShouldReplaceExistingSource() const {
bool FaviconSource::ShouldServiceRequest(
const GURL& url,
content::ResourceContext* resource_context,
- int render_process_id) const {
+ int render_process_id) {
if (url.SchemeIs(chrome::kChromeSearchScheme)) {
return InstantIOContext::ShouldServiceRequest(url, resource_context,
render_process_id);
@@ -214,26 +210,30 @@ ui::NativeTheme* FaviconSource::GetNativeTheme() {
}
void FaviconSource::OnFaviconDataAvailable(
- const IconRequest& request,
+ const content::URLDataSource::GotDataCallback& callback,
+ int size_in_dip,
+ float scale_factor,
const favicon_base::FaviconRawBitmapResult& bitmap_result) {
if (bitmap_result.is_valid()) {
// Forward the data along to the networking system.
- request.callback.Run(bitmap_result.bitmap_data.get());
+ callback.Run(bitmap_result.bitmap_data.get());
} else {
- SendDefaultResponse(request);
+ SendDefaultResponse(callback, size_in_dip, scale_factor);
}
}
void FaviconSource::SendDefaultResponse(
const content::URLDataSource::GotDataCallback& callback) {
- SendDefaultResponse(IconRequest(callback, GURL(), 16, 1.0f,
- favicon::FaviconRequestOrigin::UNKNOWN));
+ SendDefaultResponse(callback, 16, 1.0f);
}
-void FaviconSource::SendDefaultResponse(const IconRequest& icon_request) {
+void FaviconSource::SendDefaultResponse(
+ const content::URLDataSource::GotDataCallback& callback,
+ int size_in_dip,
+ float scale_factor) {
const bool dark = GetNativeTheme()->SystemDarkModeEnabled();
int resource_id;
- switch (icon_request.size_in_dip) {
+ switch (size_in_dip) {
case 64:
resource_id = dark ? IDR_DEFAULT_FAVICON_DARK_64 : IDR_DEFAULT_FAVICON_64;
break;
@@ -244,11 +244,11 @@ void FaviconSource::SendDefaultResponse(const IconRequest& icon_request) {
resource_id = dark ? IDR_DEFAULT_FAVICON_DARK : IDR_DEFAULT_FAVICON;
break;
}
- icon_request.callback.Run(LoadIconBytes(icon_request, resource_id));
+ callback.Run(LoadIconBytes(scale_factor, resource_id));
}
-base::RefCountedMemory* FaviconSource::LoadIconBytes(const IconRequest& request,
+base::RefCountedMemory* FaviconSource::LoadIconBytes(float scale_factor,
int resource_id) {
return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale(
- resource_id, ui::GetSupportedScaleFactor(request.device_scale_factor));
+ resource_id, ui::GetSupportedScaleFactor(scale_factor));
}
diff --git a/chromium/chrome/browser/ui/webui/favicon_source.h b/chromium/chrome/browser/ui/webui/favicon_source.h
index 2c725b75148..d07df2fed51 100644
--- a/chromium/chrome/browser/ui/webui/favicon_source.h
+++ b/chromium/chrome/browser/ui/webui/favicon_source.h
@@ -11,7 +11,6 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/task/cancelable_task_tracker.h"
-#include "components/favicon/core/favicon_request_handler.h"
#include "components/favicon/core/favicon_service.h"
#include "content/public/browser/url_data_source.h"
#include "ui/gfx/favicon_size.h"
@@ -22,78 +21,43 @@ namespace base {
class RefCountedMemory;
}
+namespace chrome {
+enum class FaviconUrlFormat;
+}
+
namespace ui {
class NativeTheme;
}
// FaviconSource is the gateway between network-level chrome:
// requests for favicons and the history backend that serves these.
-//
-// Format:
-// chrome://favicon/size&scalefactor/iconurl/url
-// Some parameters are optional as described below. However, the order of the
-// parameters is not interchangeable.
-//
-// Parameter:
-// 'url' Required
-// Specifies the page URL of the requested favicon. If the 'iconurl'
-// parameter is specified, the URL refers to the URL of the favicon image
-// instead.
-// 'size&scalefactor' Optional
-// Values: ['size/aa@bx/']
-// Specifies the requested favicon's size in DIP (aa) and the requested
-// favicon's scale factor. (b).
-// The supported requested DIP sizes are: 16x16, 32x32 and 64x64.
-// If the parameter is unspecified, the requested favicon's size defaults
-// to 16 and the requested scale factor defaults to 1x.
-// Example: chrome://favicon/size/16@2x/https://www.google.com/
-// 'iconurl' Optional
-// Values: ['iconurl']
-// 'iconurl': Specifies that the url parameter refers to the URL of
-// the favicon image as opposed to the URL of the page that the favicon is
-// on.
-// Example: chrome://favicon/iconurl/https://www.google.com/favicon.ico
+// Two possible formats are allowed: chrome://favicon, kept only for backwards
+// compatibility for extensions, and chrome://favicon2. Formats are described in
+// favicon_url_parser.h.
class FaviconSource : public content::URLDataSource {
public:
// |type| is the type of icon this FaviconSource will provide.
- explicit FaviconSource(Profile* profile);
+ explicit FaviconSource(Profile* profile, chrome::FaviconUrlFormat format);
~FaviconSource() override;
// content::URLDataSource implementation.
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override;
- std::string GetMimeType(const std::string&) const override;
- bool AllowCaching() const override;
- bool ShouldReplaceExistingSource() const override;
+ std::string GetMimeType(const std::string&) override;
+ bool AllowCaching() override;
+ bool ShouldReplaceExistingSource() override;
bool ShouldServiceRequest(const GURL& url,
content::ResourceContext* resource_context,
- int render_process_id) const override;
+ int render_process_id) override;
protected:
- struct IconRequest {
- IconRequest();
- IconRequest(const content::URLDataSource::GotDataCallback& cb,
- const GURL& path,
- int size,
- float scale,
- favicon::FaviconRequestOrigin origin);
- IconRequest(const IconRequest& other);
- ~IconRequest();
-
- content::URLDataSource::GotDataCallback callback;
- GURL request_path;
- int size_in_dip;
- float device_scale_factor;
- favicon::FaviconRequestOrigin icon_request_origin;
- };
-
// Exposed for testing.
virtual ui::NativeTheme* GetNativeTheme();
- virtual base::RefCountedMemory* LoadIconBytes(const IconRequest& request,
+ virtual base::RefCountedMemory* LoadIconBytes(float scale_factor,
int resource_id);
Profile* profile_;
@@ -107,9 +71,13 @@ class FaviconSource : public content::URLDataSource {
NUM_SIZES
};
- // Called when favicon data is available from the history backend.
+ // Called when favicon data is available from the history backend. If
+ // |bitmap_result| is valid, returns it to caller using |callback|. Otherwise
+ // will send appropriate default icon for |size_in_dip| and |scale_factor|.
void OnFaviconDataAvailable(
- const IconRequest& request,
+ const content::URLDataSource::GotDataCallback& callback,
+ int size_in_dip,
+ float scale_factor,
const favicon_base::FaviconRawBitmapResult& bitmap_result);
// Sends the 16x16 DIP 1x default favicon.
@@ -117,10 +85,14 @@ class FaviconSource : public content::URLDataSource {
const content::URLDataSource::GotDataCallback& callback);
// Sends the default favicon.
- void SendDefaultResponse(const IconRequest& request);
+ void SendDefaultResponse(
+ const content::URLDataSource::GotDataCallback& callback,
+ int size_in_dip,
+ float scale_factor);
+
+ chrome::FaviconUrlFormat url_format_;
base::CancelableTaskTracker cancelable_task_tracker_;
- favicon::FaviconRequestHandler favicon_request_handler_;
DISALLOW_COPY_AND_ASSIGN(FaviconSource);
};
diff --git a/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc b/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc
index d0d1b146cdc..5639be31fb3 100644
--- a/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/favicon_source_unittest.cc
@@ -4,10 +4,23 @@
#include "chrome/browser/ui/webui/favicon_source.h"
+#include <memory>
+#include <utility>
+
+#include "base/test/bind_test_util.h"
+#include "chrome/browser/favicon/favicon_service_factory.h"
+#include "chrome/browser/favicon/history_ui_favicon_request_handler_factory.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/testing_profile.h"
+#include "components/favicon/core/history_ui_favicon_request_handler.h"
+#include "components/favicon/core/test/mock_favicon_service.h"
+#include "components/favicon_base/favicon_url_parser.h"
+#include "content/public/browser/browser_context.h"
#include "content/public/browser/resource_request_info.h"
+#include "content/public/browser/web_contents.h"
#include "content/public/test/test_browser_thread_bundle.h"
+#include "content/public/test/web_contents_tester.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/native_theme/test_native_theme.h"
@@ -19,16 +32,49 @@ using testing::_;
using testing::Return;
using testing::ReturnArg;
+namespace {
+
+const int kDummyTaskId = 1;
+
+} // namespace
+
void Noop(scoped_refptr<base::RefCountedMemory>) {}
+class MockHistoryUiFaviconRequestHandler
+ : public favicon::HistoryUiFaviconRequestHandler {
+ public:
+ MockHistoryUiFaviconRequestHandler() = default;
+ ~MockHistoryUiFaviconRequestHandler() override = default;
+
+ MOCK_METHOD7(
+ GetRawFaviconForPageURL,
+ void(const GURL& page_url,
+ int desired_size_in_pixel,
+ favicon_base::FaviconRawBitmapCallback callback,
+ favicon::FaviconRequestPlatform request_platform,
+ favicon::HistoryUiFaviconRequestOrigin request_origin_for_uma,
+ const GURL& icon_url_for_uma,
+ base::CancelableTaskTracker* tracker));
+
+ MOCK_METHOD5(
+ GetFaviconImageForPageURL,
+ void(const GURL& page_url,
+ favicon_base::FaviconImageCallback callback,
+ favicon::HistoryUiFaviconRequestOrigin request_origin_for_uma,
+ const GURL& icon_url_for_uma,
+ base::CancelableTaskTracker* tracker));
+};
+
class TestFaviconSource : public FaviconSource {
public:
- TestFaviconSource(Profile* profile, ui::NativeTheme* theme)
- : FaviconSource(profile), theme_(theme) {}
+ TestFaviconSource(chrome::FaviconUrlFormat format,
+ Profile* profile,
+ ui::NativeTheme* theme)
+ : FaviconSource(profile, format), theme_(theme) {}
~TestFaviconSource() override {}
- MOCK_METHOD2(LoadIconBytes, base::RefCountedMemory*(const IconRequest&, int));
+ MOCK_METHOD2(LoadIconBytes, base::RefCountedMemory*(float, int));
protected:
ui::NativeTheme* GetNativeTheme() override { return theme_; }
@@ -37,37 +83,171 @@ class TestFaviconSource : public FaviconSource {
ui::NativeTheme* const theme_;
};
-class FaviconSourceTest : public testing::Test {
+class FaviconSourceTestBase : public testing::Test {
public:
- FaviconSourceTest() : source_(&profile_, &theme_) {}
+ explicit FaviconSourceTestBase(chrome::FaviconUrlFormat format)
+ : source_(format, &profile_, &theme_) {
+ // Setup testing factories for main dependencies.
+ BrowserContextKeyedServiceFactory::TestingFactory
+ history_ui_favicon_request_handler_factory =
+ base::BindRepeating([](content::BrowserContext*) {
+ return base::WrapUnique<KeyedService>(
+ new MockHistoryUiFaviconRequestHandler());
+ });
+ mock_history_ui_favicon_request_handler_ =
+ static_cast<MockHistoryUiFaviconRequestHandler*>(
+ HistoryUiFaviconRequestHandlerFactory::GetInstance()
+ ->SetTestingFactoryAndUse(
+ &profile_, history_ui_favicon_request_handler_factory));
+ BrowserContextKeyedServiceFactory::TestingFactory favicon_service_factory =
+ base::BindRepeating([](content::BrowserContext*) {
+ return static_cast<std::unique_ptr<KeyedService>>(
+ std::make_unique<favicon::MockFaviconService>());
+ });
+ mock_favicon_service_ = static_cast<favicon::MockFaviconService*>(
+ FaviconServiceFactory::GetInstance()->SetTestingFactoryAndUse(
+ &profile_, favicon_service_factory));
+
+ // Setup TestWebContents.
+ test_web_contents_ =
+ content::WebContentsTester::CreateTestWebContents(&profile_, nullptr);
+ test_web_contents_getter_ = base::BindLambdaForTesting(
+ [&] { return (content::WebContents*)test_web_contents_.get(); });
+
+ // On call, dependencies will return empty favicon by default.
+ ON_CALL(*mock_favicon_service_, GetRawFaviconForPageURL(_, _, _, _, _, _))
+ .WillByDefault([](auto, auto, auto, auto,
+ favicon_base::FaviconRawBitmapCallback callback,
+ auto) {
+ std::move(callback).Run(favicon_base::FaviconRawBitmapResult());
+ return kDummyTaskId;
+ });
+ ON_CALL(*mock_history_ui_favicon_request_handler_,
+ GetRawFaviconForPageURL(_, _, _, _, _, _, _))
+ .WillByDefault([](auto, auto,
+ favicon_base::FaviconRawBitmapCallback callback, auto,
+ auto, auto, auto) {
+ std::move(callback).Run(favicon_base::FaviconRawBitmapResult());
+ });
+
+ // Mock default icon loading.
+ ON_CALL(*source(), LoadIconBytes(_, _))
+ .WillByDefault(Return(kDummyIconBytes.get()));
+ }
void SetDarkMode(bool dark_mode) { theme_.SetDarkMode(dark_mode); }
TestFaviconSource* source() { return &source_; }
- private:
+ protected:
+ const scoped_refptr<base::RefCountedBytes> kDummyIconBytes;
content::TestBrowserThreadBundle thread_bundle_;
ui::TestNativeTheme theme_;
TestingProfile profile_;
+ MockHistoryUiFaviconRequestHandler* mock_history_ui_favicon_request_handler_;
+ favicon::MockFaviconService* mock_favicon_service_;
+ std::unique_ptr<content::WebContents> test_web_contents_;
+ WebContentsGetter test_web_contents_getter_;
TestFaviconSource source_;
};
-TEST_F(FaviconSourceTest, DarkDefault) {
- SetDarkMode(true);
+class FaviconSourceTestWithLegacyFormat : public FaviconSourceTestBase {
+ public:
+ FaviconSourceTestWithLegacyFormat()
+ : FaviconSourceTestBase(chrome::FaviconUrlFormat::kFaviconLegacy) {}
+};
+
+class FaviconSourceTestWithFavicon2Format : public FaviconSourceTestBase {
+ public:
+ FaviconSourceTestWithFavicon2Format()
+ : FaviconSourceTestBase(chrome::FaviconUrlFormat::kFavicon2) {}
+};
- auto bytes = base::MakeRefCounted<base::RefCountedBytes>(1);
- EXPECT_CALL(*source(), LoadIconBytes(_, IDR_DEFAULT_FAVICON_DARK))
- .WillOnce(Return(bytes.get()));
- source()->StartDataRequest(std::string(), WebContentsGetter(),
+TEST_F(FaviconSourceTestWithLegacyFormat, DarkDefault) {
+ SetDarkMode(true);
+ EXPECT_CALL(*source(), LoadIconBytes(_, IDR_DEFAULT_FAVICON_DARK));
+ source()->StartDataRequest(std::string(), test_web_contents_getter_,
base::BindRepeating(&Noop));
}
-TEST_F(FaviconSourceTest, LightDefault) {
+TEST_F(FaviconSourceTestWithLegacyFormat, LightDefault) {
SetDarkMode(false);
+ EXPECT_CALL(*source(), LoadIconBytes(_, IDR_DEFAULT_FAVICON));
+ source()->StartDataRequest(std::string(), test_web_contents_getter_,
+ base::BindRepeating(&Noop));
+}
+
+TEST_F(FaviconSourceTestWithLegacyFormat,
+ ShouldNotQueryHistoryUiFaviconRequestHandler) {
+ content::WebContentsTester::For(test_web_contents_.get())
+ ->SetLastCommittedURL(GURL(chrome::kChromeUIHistoryURL));
- auto bytes = base::MakeRefCounted<base::RefCountedBytes>(1);
- EXPECT_CALL(*source(), LoadIconBytes(_, IDR_DEFAULT_FAVICON))
- .WillOnce(Return(bytes.get()));
- source()->StartDataRequest(std::string(), WebContentsGetter(),
+ EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
+ GetRawFaviconForPageURL)
+ .Times(0);
+
+ source()->StartDataRequest("size/16@1x/https://www.google.com",
+ test_web_contents_getter_,
+ base::BindRepeating(&Noop));
+}
+
+TEST_F(FaviconSourceTestWithFavicon2Format, DarkDefault) {
+ SetDarkMode(true);
+ EXPECT_CALL(*source(), LoadIconBytes(_, IDR_DEFAULT_FAVICON_DARK));
+ source()->StartDataRequest(std::string(), test_web_contents_getter_,
base::BindRepeating(&Noop));
}
+
+TEST_F(FaviconSourceTestWithFavicon2Format, LightDefault) {
+ SetDarkMode(false);
+ EXPECT_CALL(*source(), LoadIconBytes(_, IDR_DEFAULT_FAVICON));
+ source()->StartDataRequest(std::string(), test_web_contents_getter_,
+ base::BindRepeating(&Noop));
+}
+
+TEST_F(FaviconSourceTestWithFavicon2Format,
+ ShouldNotQueryHistoryUiFaviconRequestHandlerIfNotAllowed) {
+ content::WebContentsTester::For(test_web_contents_.get())
+ ->SetLastCommittedURL(GURL(chrome::kChromeUIHistoryURL));
+
+ EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
+ GetRawFaviconForPageURL)
+ .Times(0);
+
+ source()->StartDataRequest(
+ "?size=16&scale_factor=1x&url_type=page_url&url=https%3A%2F%2Fwww.google."
+ "com&allow_google_server_fallback=0",
+ test_web_contents_getter_, base::BindRepeating(&Noop));
+}
+
+TEST_F(FaviconSourceTestWithFavicon2Format,
+ ShouldNotQueryHistoryUiFaviconRequestHandlerIfHasNotHistoryUiOrigin) {
+ content::WebContentsTester::For(test_web_contents_.get())
+ ->SetLastCommittedURL(GURL("chrome://non-history-url"));
+
+ EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
+ GetRawFaviconForPageURL)
+ .Times(0);
+
+ source()->StartDataRequest(
+ "?size=16&scale_factor=1x&url_type=page_url&url=https%3A%2F%2Fwww.google."
+ "com&allow_google_server_fallback=1",
+ test_web_contents_getter_, base::BindRepeating(&Noop));
+}
+
+TEST_F(
+ FaviconSourceTestWithFavicon2Format,
+ ShouldQueryHistoryUiFaviconRequestHandlerIfHasHistoryUiOriginAndAllowed) {
+ content::WebContentsTester::For(test_web_contents_.get())
+ ->SetLastCommittedURL(GURL(chrome::kChromeUIHistoryURL));
+
+ EXPECT_CALL(
+ *mock_history_ui_favicon_request_handler_,
+ GetRawFaviconForPageURL(GURL("https://www.google.com"), _, _, _, _, _, _))
+ .Times(1);
+
+ source()->StartDataRequest(
+ "?size=16&scale_factor=1x&url_type=page_url&url=https%3A%2F%2Fwww.google."
+ "com&allow_google_server_fallback=1",
+ test_web_contents_getter_, base::BindRepeating(&Noop));
+}
diff --git a/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc
index 51c01b6e21d..77f5faedee6 100644
--- a/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc
+++ b/chromium/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc
@@ -31,8 +31,10 @@ feed_internals::mojom::TimePtr ToMojoTime(base::Time time) {
: feed_internals::mojom::Time::New(time.ToJsTime());
}
-std::string TriggerTypeToString(feed::FeedSchedulerHost::TriggerType trigger) {
- switch (trigger) {
+std::string TriggerTypeToString(feed::FeedSchedulerHost::TriggerType* trigger) {
+ if (trigger == nullptr)
+ return "Not set";
+ switch (*trigger) {
case feed::FeedSchedulerHost::TriggerType::kNtpShown:
return "NTP Shown";
case feed::FeedSchedulerHost::TriggerType::kForegrounded:
diff --git a/chromium/chrome/browser/ui/webui/fileicon_source.cc b/chromium/chrome/browser/ui/webui/fileicon_source.cc
index b38de38bc39..7706c0fffd1 100644
--- a/chromium/chrome/browser/ui/webui/fileicon_source.cc
+++ b/chromium/chrome/browser/ui/webui/fileicon_source.cc
@@ -108,7 +108,7 @@ void FileIconSource::FetchFileIcon(
}
}
-std::string FileIconSource::GetSource() const {
+std::string FileIconSource::GetSource() {
return kFileIconPath;
}
@@ -123,12 +123,12 @@ void FileIconSource::StartDataRequest(
FetchFileIcon(file_path, scale_factor, icon_size, callback);
}
-std::string FileIconSource::GetMimeType(const std::string&) const {
+std::string FileIconSource::GetMimeType(const std::string&) {
// Rely on image decoder inferring the correct type.
return std::string();
}
-bool FileIconSource::AllowCaching() const {
+bool FileIconSource::AllowCaching() {
return false;
}
diff --git a/chromium/chrome/browser/ui/webui/fileicon_source.h b/chromium/chrome/browser/ui/webui/fileicon_source.h
index b8c093c105a..38fd7797a60 100644
--- a/chromium/chrome/browser/ui/webui/fileicon_source.h
+++ b/chromium/chrome/browser/ui/webui/fileicon_source.h
@@ -25,13 +25,13 @@ class FileIconSource : public content::URLDataSource {
~FileIconSource() override;
// content::URLDataSource implementation.
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override;
- std::string GetMimeType(const std::string&) const override;
- bool AllowCaching() const override;
+ std::string GetMimeType(const std::string&) override;
+ bool AllowCaching() override;
protected:
// Once the |path| and |icon_size| has been determined from the request, this
diff --git a/chromium/chrome/browser/ui/webui/flags_ui.cc b/chromium/chrome/browser/ui/webui/flags_ui.cc
index ad3e0322e50..cdf598ea4d3 100644
--- a/chromium/chrome/browser/ui/webui/flags_ui.cc
+++ b/chromium/chrome/browser/ui/webui/flags_ui.cc
@@ -14,12 +14,9 @@
#include "base/memory/ref_counted_memory.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
-#include "build/build_config.h"
-#include "chrome/browser/about_flags.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/common/channel_info.h"
+#include "chrome/browser/ui/webui/flags_ui_handler.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "components/flags_ui/flags_ui_constants.h"
@@ -51,10 +48,6 @@
#include "components/user_manager/user_manager.h"
#endif
-#if !defined(OS_ANDROID)
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
-#endif
-
using content::WebContents;
using content::WebUIMessageHandler;
@@ -89,195 +82,6 @@ content::WebUIDataSource* CreateFlagsUIHTMLSource() {
return source;
}
-////////////////////////////////////////////////////////////////////////////////
-//
-// FlagsDOMHandler
-//
-////////////////////////////////////////////////////////////////////////////////
-
-// The handler for Javascript messages for the about:flags page.
-class FlagsDOMHandler : public WebUIMessageHandler {
- public:
- FlagsDOMHandler() : access_(flags_ui::kGeneralAccessFlagsOnly),
- experimental_features_requested_(false) {
- }
- ~FlagsDOMHandler() override {}
-
- // Initializes the DOM handler with the provided flags storage and flags
- // access. If there were flags experiments requested from javascript before
- // this was called, it calls |HandleRequestExperimentalFeatures| again.
- void Init(flags_ui::FlagsStorage* flags_storage,
- flags_ui::FlagAccess access);
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- // Callback for the "requestExperimentFeatures" message.
- void HandleRequestExperimentalFeatures(const base::ListValue* args);
-
- // Callback for the "enableExperimentalFeature" message.
- void HandleEnableExperimentalFeatureMessage(const base::ListValue* args);
-
- // Callback for the "setOriginListFlag" message.
- void HandleSetOriginListFlagMessage(const base::ListValue* args);
-
- // Callback for the "restartBrowser" message. Restores all tabs on restart.
- void HandleRestartBrowser(const base::ListValue* args);
-
- // Callback for the "resetAllFlags" message.
- void HandleResetAllFlags(const base::ListValue* args);
-
- private:
- std::unique_ptr<flags_ui::FlagsStorage> flags_storage_;
- flags_ui::FlagAccess access_;
- bool experimental_features_requested_;
-
- DISALLOW_COPY_AND_ASSIGN(FlagsDOMHandler);
-};
-
-void FlagsDOMHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- flags_ui::kRequestExperimentalFeatures,
- base::BindRepeating(&FlagsDOMHandler::HandleRequestExperimentalFeatures,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- flags_ui::kEnableExperimentalFeature,
- base::BindRepeating(
- &FlagsDOMHandler::HandleEnableExperimentalFeatureMessage,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- flags_ui::kSetOriginListFlag,
- base::BindRepeating(&FlagsDOMHandler::HandleSetOriginListFlagMessage,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- flags_ui::kRestartBrowser,
- base::BindRepeating(&FlagsDOMHandler::HandleRestartBrowser,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- flags_ui::kResetAllFlags,
- base::BindRepeating(&FlagsDOMHandler::HandleResetAllFlags,
- base::Unretained(this)));
-}
-
-void FlagsDOMHandler::Init(flags_ui::FlagsStorage* flags_storage,
- flags_ui::FlagAccess access) {
- flags_storage_.reset(flags_storage);
- access_ = access;
-
- if (experimental_features_requested_)
- HandleRequestExperimentalFeatures(nullptr);
-}
-
-void FlagsDOMHandler::HandleRequestExperimentalFeatures(
- const base::ListValue* args) {
- experimental_features_requested_ = true;
- // Bail out if the handler hasn't been initialized yet. The request will be
- // handled after the initialization.
- if (!flags_storage_)
- return;
-
- base::DictionaryValue results;
-
- std::unique_ptr<base::ListValue> supported_features(new base::ListValue);
- std::unique_ptr<base::ListValue> unsupported_features(new base::ListValue);
- about_flags::GetFlagFeatureEntries(flags_storage_.get(),
- access_,
- supported_features.get(),
- unsupported_features.get());
- results.Set(flags_ui::kSupportedFeatures, std::move(supported_features));
- results.Set(flags_ui::kUnsupportedFeatures, std::move(unsupported_features));
- results.SetBoolean(flags_ui::kNeedsRestart,
- about_flags::IsRestartNeededToCommitChanges());
- results.SetBoolean(flags_ui::kShowOwnerWarning,
- access_ == flags_ui::kGeneralAccessFlagsOnly);
-
-#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
- version_info::Channel channel = chrome::GetChannel();
- results.SetBoolean(flags_ui::kShowBetaChannelPromotion,
- channel == version_info::Channel::STABLE);
- results.SetBoolean(flags_ui::kShowDevChannelPromotion,
- channel == version_info::Channel::BETA);
-#else
- results.SetBoolean(flags_ui::kShowBetaChannelPromotion, false);
- results.SetBoolean(flags_ui::kShowDevChannelPromotion, false);
-#endif
- web_ui()->CallJavascriptFunctionUnsafe(flags_ui::kReturnExperimentalFeatures,
- results);
-}
-
-void FlagsDOMHandler::HandleEnableExperimentalFeatureMessage(
- const base::ListValue* args) {
- DCHECK(flags_storage_);
- DCHECK_EQ(2u, args->GetSize());
- if (args->GetSize() != 2)
- return;
-
- std::string entry_internal_name;
- std::string enable_str;
- if (!args->GetString(0, &entry_internal_name) ||
- !args->GetString(1, &enable_str))
- return;
-
- about_flags::SetFeatureEntryEnabled(flags_storage_.get(), entry_internal_name,
- enable_str == "true");
-}
-
-void FlagsDOMHandler::HandleSetOriginListFlagMessage(
- const base::ListValue* args) {
- DCHECK(flags_storage_);
- if (args->GetSize() != 2) {
- NOTREACHED();
- return;
- }
-
- std::string entry_internal_name;
- std::string value_str;
- if (!args->GetString(0, &entry_internal_name) ||
- !args->GetString(1, &value_str) || entry_internal_name.empty()) {
- NOTREACHED();
- return;
- }
-
- about_flags::SetOriginListFlag(entry_internal_name, value_str,
- flags_storage_.get());
-}
-
-void FlagsDOMHandler::HandleRestartBrowser(const base::ListValue* args) {
- DCHECK(flags_storage_);
-#if defined(OS_CHROMEOS)
- // On ChromeOS be less intrusive and restart inside the user session after
- // we apply the newly selected flags.
- base::CommandLine user_flags(base::CommandLine::NO_PROGRAM);
- about_flags::ConvertFlagsToSwitches(flags_storage_.get(),
- &user_flags,
- flags_ui::kAddSentinels);
-
- // Apply additional switches from policy that should not be dropped when
- // applying flags..
- chromeos::UserSessionManager::MaybeAppendPolicySwitches(
- Profile::FromWebUI(web_ui())->GetPrefs(), &user_flags);
-
- base::CommandLine::StringVector flags;
- // argv[0] is the program name |base::CommandLine::NO_PROGRAM|.
- flags.assign(user_flags.argv().begin() + 1, user_flags.argv().end());
- VLOG(1) << "Restarting to apply per-session flags...";
- AccountId account_id =
- user_manager::UserManager::Get()->GetActiveUser()->GetAccountId();
- chromeos::UserSessionManager::GetInstance()->SetSwitchesForUser(
- account_id,
- chromeos::UserSessionManager::CommandLineSwitchesType::
- kPolicyAndFlagsAndKioskControl,
- flags);
-#endif
- chrome::AttemptRestart();
-}
-
-void FlagsDOMHandler::HandleResetAllFlags(const base::ListValue* args) {
- DCHECK(flags_storage_);
- about_flags::ResetAllFlags(flags_storage_.get());
-}
-
-
#if defined(OS_CHROMEOS)
// On ChromeOS verifying if the owner is signed in is async operation and only
// after finishing it the UI can be properly populated. This function is the
@@ -285,7 +89,7 @@ void FlagsDOMHandler::HandleResetAllFlags(const base::ListValue* args) {
// proper PrefService for the flags interface.
void FinishInitialization(base::WeakPtr<FlagsUI> flags_ui,
Profile* profile,
- FlagsDOMHandler* dom_handler,
+ FlagsUIHandler* dom_handler,
bool current_user_is_owner) {
DCHECK(!profile->IsOffTheRecord());
// If the flags_ui has gone away, there's nothing to do.
@@ -313,19 +117,11 @@ void FinishInitialization(base::WeakPtr<FlagsUI> flags_ui,
} // namespace
-///////////////////////////////////////////////////////////////////////////////
-//
-// FlagsUI
-//
-///////////////////////////////////////////////////////////////////////////////
-
-FlagsUI::FlagsUI(content::WebUI* web_ui)
- : WebUIController(web_ui),
- weak_factory_(this) {
+FlagsUI::FlagsUI(content::WebUI* web_ui) : WebUIController(web_ui) {
Profile* profile = Profile::FromWebUI(web_ui);
- auto handler_owner = std::make_unique<FlagsDOMHandler>();
- FlagsDOMHandler* handler = handler_owner.get();
+ auto handler_owner = std::make_unique<FlagsUIHandler>();
+ FlagsUIHandler* handler = handler_owner.get();
web_ui->AddMessageHandler(std::move(handler_owner));
#if defined(OS_CHROMEOS)
@@ -351,13 +147,7 @@ FlagsUI::FlagsUI(content::WebUI* web_ui)
#endif
// Set up the about:flags source.
- auto* source = CreateFlagsUIHTMLSource();
-#if !defined(OS_ANDROID)
- // Android hasn't implemented NativeTheme::SystemDarkModeEnabled() yet, which
- // DarkModeHandler relies on to determine "darkness".
- DarkModeHandler::Initialize(web_ui, source);
-#endif
- content::WebUIDataSource::Add(profile, source);
+ content::WebUIDataSource::Add(profile, CreateFlagsUIHTMLSource());
}
FlagsUI::~FlagsUI() {
diff --git a/chromium/chrome/browser/ui/webui/flags_ui.h b/chromium/chrome/browser/ui/webui/flags_ui.h
index f28cbaf3757..c41991b2f88 100644
--- a/chromium/chrome/browser/ui/webui/flags_ui.h
+++ b/chromium/chrome/browser/ui/webui/flags_ui.h
@@ -28,7 +28,7 @@ class FlagsUI : public content::WebUIController {
ui::ScaleFactor scale_factor);
private:
- base::WeakPtrFactory<FlagsUI> weak_factory_;
+ base::WeakPtrFactory<FlagsUI> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(FlagsUI);
};
diff --git a/chromium/chrome/browser/ui/webui/flags_ui_handler.cc b/chromium/chrome/browser/ui/webui/flags_ui_handler.cc
new file mode 100644
index 00000000000..0c03c7a56fa
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/flags_ui_handler.cc
@@ -0,0 +1,169 @@
+// Copyright (c) 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/flags_ui_handler.h"
+
+#include "base/bind.h"
+#include "chrome/browser/about_flags.h"
+#include "chrome/browser/lifetime/application_lifetime.h"
+#include "chrome/common/channel_info.h"
+#include "components/flags_ui/flags_storage.h"
+#include "components/flags_ui/flags_ui_constants.h"
+#include "components/version_info/channel.h"
+
+#if defined(OS_CHROMEOS)
+#include "base/system/sys_info.h"
+#include "chrome/browser/chromeos/login/session/user_session_manager.h"
+#include "components/account_id/account_id.h"
+#include "components/pref_registry/pref_registry_syncable.h"
+#include "components/user_manager/user_manager.h"
+#endif
+
+FlagsUIHandler::FlagsUIHandler()
+ : access_(flags_ui::kGeneralAccessFlagsOnly),
+ experimental_features_requested_(false) {}
+
+FlagsUIHandler::~FlagsUIHandler() {}
+
+void FlagsUIHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ flags_ui::kRequestExperimentalFeatures,
+ base::BindRepeating(&FlagsUIHandler::HandleRequestExperimentalFeatures,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ flags_ui::kEnableExperimentalFeature,
+ base::BindRepeating(
+ &FlagsUIHandler::HandleEnableExperimentalFeatureMessage,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ flags_ui::kSetOriginListFlag,
+ base::BindRepeating(&FlagsUIHandler::HandleSetOriginListFlagMessage,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ flags_ui::kRestartBrowser,
+ base::BindRepeating(&FlagsUIHandler::HandleRestartBrowser,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ flags_ui::kResetAllFlags,
+ base::BindRepeating(&FlagsUIHandler::HandleResetAllFlags,
+ base::Unretained(this)));
+}
+
+void FlagsUIHandler::Init(flags_ui::FlagsStorage* flags_storage,
+ flags_ui::FlagAccess access) {
+ flags_storage_.reset(flags_storage);
+ access_ = access;
+
+ if (experimental_features_requested_)
+ HandleRequestExperimentalFeatures(nullptr);
+}
+
+void FlagsUIHandler::HandleRequestExperimentalFeatures(
+ const base::ListValue* args) {
+ experimental_features_requested_ = true;
+ // Bail out if the handler hasn't been initialized yet. The request will be
+ // handled after the initialization.
+ if (!flags_storage_)
+ return;
+
+ base::DictionaryValue results;
+
+ std::unique_ptr<base::ListValue> supported_features(new base::ListValue);
+ std::unique_ptr<base::ListValue> unsupported_features(new base::ListValue);
+
+ about_flags::GetFlagFeatureEntries(flags_storage_.get(), access_,
+ supported_features.get(),
+ unsupported_features.get());
+
+ results.Set(flags_ui::kSupportedFeatures, std::move(supported_features));
+ results.Set(flags_ui::kUnsupportedFeatures, std::move(unsupported_features));
+ results.SetBoolean(flags_ui::kNeedsRestart,
+ about_flags::IsRestartNeededToCommitChanges());
+ results.SetBoolean(flags_ui::kShowOwnerWarning,
+ access_ == flags_ui::kGeneralAccessFlagsOnly);
+
+#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
+ version_info::Channel channel = chrome::GetChannel();
+ results.SetBoolean(flags_ui::kShowBetaChannelPromotion,
+ channel == version_info::Channel::STABLE);
+ results.SetBoolean(flags_ui::kShowDevChannelPromotion,
+ channel == version_info::Channel::BETA);
+#else
+ results.SetBoolean(flags_ui::kShowBetaChannelPromotion, false);
+ results.SetBoolean(flags_ui::kShowDevChannelPromotion, false);
+#endif
+ web_ui()->CallJavascriptFunctionUnsafe(flags_ui::kReturnExperimentalFeatures,
+ results);
+}
+
+void FlagsUIHandler::HandleEnableExperimentalFeatureMessage(
+ const base::ListValue* args) {
+ DCHECK(flags_storage_);
+ DCHECK_EQ(2u, args->GetSize());
+ if (args->GetSize() != 2)
+ return;
+
+ std::string entry_internal_name;
+ std::string enable_str;
+ if (!args->GetString(0, &entry_internal_name) ||
+ !args->GetString(1, &enable_str))
+ return;
+
+ about_flags::SetFeatureEntryEnabled(flags_storage_.get(), entry_internal_name,
+ enable_str == "true");
+}
+
+void FlagsUIHandler::HandleSetOriginListFlagMessage(
+ const base::ListValue* args) {
+ DCHECK(flags_storage_);
+ if (args->GetSize() != 2) {
+ NOTREACHED();
+ return;
+ }
+
+ std::string entry_internal_name;
+ std::string value_str;
+ if (!args->GetString(0, &entry_internal_name) ||
+ !args->GetString(1, &value_str) || entry_internal_name.empty()) {
+ NOTREACHED();
+ return;
+ }
+
+ about_flags::SetOriginListFlag(entry_internal_name, value_str,
+ flags_storage_.get());
+}
+
+void FlagsUIHandler::HandleRestartBrowser(const base::ListValue* args) {
+ DCHECK(flags_storage_);
+#if defined(OS_CHROMEOS)
+ // On ChromeOS be less intrusive and restart inside the user session after
+ // we apply the newly selected flags.
+ base::CommandLine user_flags(base::CommandLine::NO_PROGRAM);
+ about_flags::ConvertFlagsToSwitches(flags_storage_.get(), &user_flags,
+ flags_ui::kAddSentinels);
+
+ // Adhere to policy-enforced command-line switch handling when
+ // applying modified flags..
+ chromeos::UserSessionManager::ApplyUserPolicyToSwitches(
+ Profile::FromWebUI(web_ui())->GetPrefs(), &user_flags);
+
+ base::CommandLine::StringVector flags;
+ // argv[0] is the program name |base::CommandLine::NO_PROGRAM|.
+ flags.assign(user_flags.argv().begin() + 1, user_flags.argv().end());
+ VLOG(1) << "Restarting to apply per-session flags...";
+ AccountId account_id =
+ user_manager::UserManager::Get()->GetActiveUser()->GetAccountId();
+ chromeos::UserSessionManager::GetInstance()->SetSwitchesForUser(
+ account_id,
+ chromeos::UserSessionManager::CommandLineSwitchesType::
+ kPolicyAndFlagsAndKioskControl,
+ flags);
+#endif
+ chrome::AttemptRestart();
+}
+
+void FlagsUIHandler::HandleResetAllFlags(const base::ListValue* args) {
+ DCHECK(flags_storage_);
+ about_flags::ResetAllFlags(flags_storage_.get());
+}
diff --git a/chromium/chrome/browser/ui/webui/flags_ui_handler.h b/chromium/chrome/browser/ui/webui/flags_ui_handler.h
new file mode 100644
index 00000000000..05c6bfd343b
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/flags_ui_handler.h
@@ -0,0 +1,55 @@
+// Copyright (c) 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/flags_ui.h"
+
+#include "build/build_config.h"
+#include "components/flags_ui/feature_entry.h"
+#include "components/flags_ui/flags_state.h"
+#include "content/public/browser/web_ui_message_handler.h"
+
+#ifndef CHROME_BROWSER_UI_WEBUI_FLAGS_UI_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_FLAGS_UI_HANDLER_H_
+
+namespace flags_ui {
+class FlagsStorage;
+}
+
+class FlagsUIHandler : public content::WebUIMessageHandler {
+ public:
+ FlagsUIHandler();
+ ~FlagsUIHandler() override;
+
+ // Initializes the UI handler with the provided flags storage and flags
+ // access. If there were flags experiments requested from javascript before
+ // this was called, it calls |HandleRequestExperimentalFeatures| again.
+ void Init(flags_ui::FlagsStorage* flags_storage, flags_ui::FlagAccess access);
+
+ // WebUIMessageHandler implementation.
+ void RegisterMessages() override;
+
+ // Callback for the "requestExperimentFeatures" message.
+ void HandleRequestExperimentalFeatures(const base::ListValue* args);
+
+ // Callback for the "enableExperimentalFeature" message.
+ void HandleEnableExperimentalFeatureMessage(const base::ListValue* args);
+
+ // Callback for the "setOriginListFlag" message.
+ void HandleSetOriginListFlagMessage(const base::ListValue* args);
+
+ // Callback for the "restartBrowser" message. Restores all tabs on restart.
+ void HandleRestartBrowser(const base::ListValue* args);
+
+ // Callback for the "resetAllFlags" message.
+ void HandleResetAllFlags(const base::ListValue* args);
+
+ private:
+ std::unique_ptr<flags_ui::FlagsStorage> flags_storage_;
+ flags_ui::FlagAccess access_;
+ bool experimental_features_requested_;
+
+ DISALLOW_COPY_AND_ASSIGN(FlagsUIHandler);
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_FLAGS_UI_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc b/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc
index 79bf8d2c8fb..b1e16e87001 100644
--- a/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/gcm_internals_ui.cc
@@ -55,13 +55,12 @@ class GcmInternalsUIMessageHandler : public content::WebUIMessageHandler {
const gcm::GCMClient::GCMStatistics& args) const;
// Factory for creating references in callbacks.
- base::WeakPtrFactory<GcmInternalsUIMessageHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<GcmInternalsUIMessageHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(GcmInternalsUIMessageHandler);
};
-GcmInternalsUIMessageHandler::GcmInternalsUIMessageHandler()
- : weak_ptr_factory_(this) {}
+GcmInternalsUIMessageHandler::GcmInternalsUIMessageHandler() {}
GcmInternalsUIMessageHandler::~GcmInternalsUIMessageHandler() {}
diff --git a/chromium/chrome/browser/ui/webui/hats/hats_handler.cc b/chromium/chrome/browser/ui/webui/hats/hats_handler.cc
deleted file mode 100644
index 0b36869b9ce..00000000000
--- a/chromium/chrome/browser/ui/webui/hats/hats_handler.cc
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/hats/hats_handler.h"
-
-#include "base/bind.h"
-#include "base/metrics/histogram_macros.h"
-
-HatsHandler::HatsHandler() {}
-
-HatsHandler::~HatsHandler() {}
-
-void HatsHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "afterShow", base::BindRepeating(&HatsHandler::HandleAfterShow,
- base::Unretained(this)));
-}
-
-// Callback for the "afterShow" message.
-void HatsHandler::HandleAfterShow(const base::ListValue* args) {
- UMA_HISTOGRAM_ENUMERATION("Feedback.HappinessTrackingSurvey.DesktopResponse",
- HappinessTrackingSurveyDesktopResponse::kShown);
-}
diff --git a/chromium/chrome/browser/ui/webui/hats/hats_handler.h b/chromium/chrome/browser/ui/webui/hats/hats_handler.h
deleted file mode 100644
index 24ecd1c1336..00000000000
--- a/chromium/chrome/browser/ui/webui/hats/hats_handler.h
+++ /dev/null
@@ -1,39 +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_HATS_HATS_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_HATS_HATS_HANDLER_H_
-
-#include "base/macros.h"
-#include "content/public/browser/web_ui_message_handler.h"
-
-namespace base {
-class ListValue;
-}
-
-// Used by UMA histogram, so entries shouldn't be reordered or removed.
-enum class HappinessTrackingSurveyDesktopResponse {
- kShown = 0,
- kCompleted = 1,
- kDimsissed = 2,
- kMaxValue = kDimsissed,
-};
-
-// The handler for Javascript messages for the about:flags page.
-class HatsHandler : public content::WebUIMessageHandler {
- public:
- HatsHandler();
- ~HatsHandler() override;
-
- private:
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- // Callback for the "afterShow" message.
- void HandleAfterShow(const base::ListValue* args);
-
- DISALLOW_COPY_AND_ASSIGN(HatsHandler);
-};
-
-#endif // CHROME_BROWSER_UI_WEBUI_HATS_HATS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/hats/hats_ui.cc b/chromium/chrome/browser/ui/webui/hats/hats_ui.cc
deleted file mode 100644
index 20f9089c91b..00000000000
--- a/chromium/chrome/browser/ui/webui/hats/hats_ui.cc
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/hats/hats_ui.h"
-
-#include <utility>
-
-#include "base/optional.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/hats/hats_handler.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/browser_resources.h"
-#include "content/public/browser/web_ui.h"
-#include "content/public/browser/web_ui_controller.h"
-#include "content/public/browser/web_ui_data_source.h"
-
-HatsUI::HatsUI(content::WebUI* web_ui) : content::WebUIController(web_ui) {
- // Set up the chrome://hats/ source.
- content::WebUIDataSource* source =
- content::WebUIDataSource::Create(chrome::kChromeUIHatsHost);
-
- // TODO(jeffreycohen) The Site ID for the current survey will need to be
- // passed into the JS with code similar to this :
- // source->AddString("trigger", "z4cctguzopq5x2ftal6vdgjrui");
- source->SetJsonPath("strings.js");
-
- source->AddResourcePath("hats.js", IDR_DESKTOP_HATS_JS);
- source->SetDefaultResource(IDR_DESKTOP_HATS_HTML);
-
- Profile* profile = Profile::FromWebUI(web_ui);
- content::WebUIDataSource::Add(profile, source);
-
- auto handler = std::make_unique<HatsHandler>();
- web_ui->AddMessageHandler(std::move(handler));
-}
-
-HatsUI::~HatsUI() {}
diff --git a/chromium/chrome/browser/ui/webui/hats/hats_ui.h b/chromium/chrome/browser/ui/webui/hats/hats_ui.h
deleted file mode 100644
index 3673a514995..00000000000
--- a/chromium/chrome/browser/ui/webui/hats/hats_ui.h
+++ /dev/null
@@ -1,25 +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_HATS_HATS_UI_H_
-#define CHROME_BROWSER_UI_WEBUI_HATS_HATS_UI_H_
-
-#include "base/macros.h"
-#include "content/public/browser/web_ui_controller.h"
-
-namespace content {
-class WebUI;
-}
-
-// The WebUI for chrome://hats
-class HatsUI : public content::WebUIController {
- public:
- explicit HatsUI(content::WebUI* web_ui);
- ~HatsUI() override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(HatsUI);
-};
-
-#endif // CHROME_BROWSER_UI_WEBUI_HATS_HATS_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc
index fb31dea54af..fd278d7d6c2 100644
--- a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc
+++ b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc
@@ -80,21 +80,19 @@ bool IsAutoUpdateDisabled() {
}
base::string16 GetConnectionTypeAsUTF16(const chromeos::NetworkState* network) {
- const std::string type =
- network->IsUsingMobileData() ? shill::kTypeCellular : network->type();
+ const std::string type = network->type();
+ if (chromeos::NetworkTypePattern::WiFi().MatchesType(type)) {
+ if (network->IsUsingMobileData())
+ return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_METERED_WIFI);
+ return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_WIFI);
+ }
if (chromeos::NetworkTypePattern::Ethernet().MatchesType(type))
return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_ETHERNET);
- if (type == shill::kTypeWifi)
- return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_WIFI);
- if (type == shill::kTypeWimax)
+ if (chromeos::NetworkTypePattern::Wimax().MatchesType(type))
return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_WIMAX);
- if (type == shill::kTypeBluetooth)
- return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_BLUETOOTH);
- if (type == shill::kTypeCellular ||
- chromeos::NetworkTypePattern::Tether().MatchesType(type)) {
+ if (chromeos::NetworkTypePattern::Mobile().MatchesType(type))
return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_MOBILE_DATA);
- }
- if (type == shill::kTypeVPN)
+ if (chromeos::NetworkTypePattern::VPN().MatchesType(type))
return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_VPN);
NOTREACHED();
return base::string16();
diff --git a/chromium/chrome/browser/ui/webui/history_login_handler.cc b/chromium/chrome/browser/ui/webui/history_login_handler.cc
index 5fe265fd7ae..f8db85e08e6 100644
--- a/chromium/chrome/browser/ui/webui/history_login_handler.cc
+++ b/chromium/chrome/browser/ui/webui/history_login_handler.cc
@@ -13,7 +13,7 @@
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/webui/profile_info_watcher.h"
-#include "components/signin/core/browser/signin_metrics.h"
+#include "components/signin/public/base/signin_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
diff --git a/chromium/chrome/browser/ui/webui/history_ui.cc b/chromium/chrome/browser/ui/webui/history_ui.cc
index 215689d34df..368b995af9a 100644
--- a/chromium/chrome/browser/ui/webui/history_ui.cc
+++ b/chromium/chrome/browser/ui/webui/history_ui.cc
@@ -18,7 +18,6 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/ui/webui/browsing_history_handler.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
#include "chrome/browser/ui/webui/foreign_session_handler.h"
#include "chrome/browser/ui/webui/history_login_handler.h"
#include "chrome/browser/ui/webui/localized_string.h"
@@ -31,10 +30,10 @@
#include "chrome/grit/locale_settings.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
-#include "services/identity/public/cpp/identity_manager.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
@@ -43,7 +42,7 @@ constexpr char kIsUserSignedInKey[] = "isUserSignedIn";
constexpr char kShowMenuPromoKey[] = "showMenuPromo";
bool IsUserSignedIn(Profile* profile) {
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
return identity_manager && identity_manager->HasPrimaryAccount();
}
@@ -178,7 +177,6 @@ content::WebUIDataSource* CreateHistoryUIHTMLSource(Profile* profile) {
HistoryUI::HistoryUI(content::WebUI* web_ui) : WebUIController(web_ui) {
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource* data_source = CreateHistoryUIHTMLSource(profile);
- DarkModeHandler::Initialize(web_ui, data_source);
ManagedUIHandler::Initialize(web_ui, data_source);
content::WebUIDataSource::Add(profile, data_source);
diff --git a/chromium/chrome/browser/ui/webui/identity_internals_ui.cc b/chromium/chrome/browser/ui/webui/identity_internals_ui.cc
index 0d7a333a2d0..1c4bfa947ea 100644
--- a/chromium/chrome/browser/ui/webui/identity_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/identity_internals_ui.cc
@@ -11,6 +11,7 @@
#include "base/bind.h"
#include "base/i18n/time_formatting.h"
#include "base/macros.h"
+#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/identity/identity_api.h"
@@ -25,18 +26,9 @@
#include "content/public/browser/web_ui_message_handler.h"
#include "extensions/browser/extension_registry.h"
#include "google_apis/gaia/gaia_auth_fetcher.h"
-#include "ui/base/l10n/l10n_util.h"
namespace {
-// Properties of the Javascript object representing a token.
-const char kExtensionId[] = "extensionId";
-const char kExtensionName[] = "extensionName";
-const char kScopes[] = "scopes";
-const char kStatus[] = "status";
-const char kTokenExpirationTime[] = "expirationTime";
-const char kAccessToken[] = "accessToken";
-
// RevokeToken message parameter offsets.
const int kRevokeTokenExtensionOffset = 0;
const int kRevokeTokenTokenOffset = 1;
@@ -68,18 +60,17 @@ class IdentityInternalsUIMessageHandler : public content::WebUIMessageHandler {
std::unique_ptr<base::ListValue> GetScopes(
const extensions::ExtensionTokenKey& token_cache_key);
- // Gets a localized status of the access token in |token_cache_value|.
- const base::string16 GetStatus(
+ // Gets a status of the access token in |token_cache_value|.
+ std::string GetStatus(
const extensions::IdentityTokenCacheValue& token_cache_value);
// Gets a string representation of an expiration time of the access token in
// |token_cache_value|.
- const std::string GetExpirationTime(
+ base::string16 GetExpirationTime(
const extensions::IdentityTokenCacheValue& token_cache_value);
// Converts a pair of |token_cache_key| and |token_cache_value| to a
- // DictionaryValue object with corresponding information in a localized and
- // readable form and returns a pointer to created object.
+ // DictionaryValue object with corresponding information.
std::unique_ptr<base::DictionaryValue> GetInfoForToken(
const extensions::ExtensionTokenKey& token_cache_key,
const extensions::IdentityTokenCacheValue& token_cache_value);
@@ -191,41 +182,37 @@ std::unique_ptr<base::ListValue> IdentityInternalsUIMessageHandler::GetScopes(
return scopes_value;
}
-const base::string16 IdentityInternalsUIMessageHandler::GetStatus(
+std::string IdentityInternalsUIMessageHandler::GetStatus(
const extensions::IdentityTokenCacheValue& token_cache_value) {
switch (token_cache_value.status()) {
case extensions::IdentityTokenCacheValue::CACHE_STATUS_ADVICE:
// Fallthrough to NOT FOUND case, as ADVICE is short lived.
case extensions::IdentityTokenCacheValue::CACHE_STATUS_NOTFOUND:
- return l10n_util::GetStringUTF16(
- IDS_IDENTITY_INTERNALS_TOKEN_NOT_FOUND);
+ return "Not Found";
case extensions::IdentityTokenCacheValue::CACHE_STATUS_TOKEN:
- return l10n_util::GetStringUTF16(
- IDS_IDENTITY_INTERNALS_TOKEN_PRESENT);
+ return "Token Present";
}
NOTREACHED();
- return base::string16();
+ return std::string();
}
-const std::string IdentityInternalsUIMessageHandler::GetExpirationTime(
+base::string16 IdentityInternalsUIMessageHandler::GetExpirationTime(
const extensions::IdentityTokenCacheValue& token_cache_value) {
- return base::UTF16ToUTF8(base::TimeFormatFriendlyDateAndTime(
- token_cache_value.expiration_time()));
+ return base::TimeFormatFriendlyDateAndTime(
+ token_cache_value.expiration_time());
}
std::unique_ptr<base::DictionaryValue>
IdentityInternalsUIMessageHandler::GetInfoForToken(
const extensions::ExtensionTokenKey& token_cache_key,
const extensions::IdentityTokenCacheValue& token_cache_value) {
- std::unique_ptr<base::DictionaryValue> token_data(
- new base::DictionaryValue());
- token_data->SetString(kExtensionId, token_cache_key.extension_id);
- token_data->SetString(kExtensionName, GetExtensionName(token_cache_key));
- token_data->Set(kScopes, GetScopes(token_cache_key));
- token_data->SetString(kStatus, GetStatus(token_cache_value));
- token_data->SetString(kAccessToken, token_cache_value.token());
- token_data->SetString(kTokenExpirationTime,
- GetExpirationTime(token_cache_value));
+ auto token_data = std::make_unique<base::DictionaryValue>();
+ token_data->SetString("extensionId", token_cache_key.extension_id);
+ token_data->SetString("extensionName", GetExtensionName(token_cache_key));
+ token_data->Set("scopes", GetScopes(token_cache_key));
+ token_data->SetString("status", GetStatus(token_cache_value));
+ token_data->SetString("accessToken", token_cache_value.token());
+ token_data->SetString("expirationTime", GetExpirationTime(token_cache_value));
return token_data;
}
@@ -296,22 +283,7 @@ IdentityInternalsUI::IdentityInternalsUI(content::WebUI* web_ui)
: content::WebUIController(web_ui) {
// chrome://identity-internals source.
content::WebUIDataSource* html_source =
- content::WebUIDataSource::Create(chrome::kChromeUIIdentityInternalsHost);
-
- // Localized strings
- static constexpr LocalizedString kStrings[] = {
- {"tokenCacheHeader", IDS_IDENTITY_INTERNALS_TOKEN_CACHE_TEXT},
- {"accessToken", IDS_IDENTITY_INTERNALS_ACCESS_TOKEN},
- {"extensionName", IDS_IDENTITY_INTERNALS_EXTENSION_NAME},
- {"extensionId", IDS_IDENTITY_INTERNALS_EXTENSION_ID},
- {"tokenStatus", IDS_IDENTITY_INTERNALS_TOKEN_STATUS},
- {"expirationTime", IDS_IDENTITY_INTERNALS_EXPIRATION_TIME},
- {"scopes", IDS_IDENTITY_INTERNALS_SCOPES},
- {"revoke", IDS_IDENTITY_INTERNALS_REVOKE},
- };
- AddLocalizedStringsBulk(html_source, kStrings, base::size(kStrings));
-
- html_source->SetJsonPath("strings.js");
+ content::WebUIDataSource::Create(chrome::kChromeUIIdentityInternalsHost);
// Required resources
html_source->AddResourcePath("identity_internals.css",
diff --git a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc
index d21cebf18f2..1a5607b50c2 100644
--- a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc
+++ b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc
@@ -21,7 +21,6 @@
#include "chrome/browser/ssl/bad_clock_blocking_page.h"
#include "chrome/browser/ssl/mitm_software_blocking_page.h"
#include "chrome/browser/ssl/ssl_blocking_page.h"
-#include "chrome/browser/supervised_user/supervised_user_interstitial.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/url_constants.h"
#include "components/grit/components_resources.h"
@@ -30,7 +29,6 @@
#include "components/security_interstitials/core/ssl_error_ui.h"
#include "components/supervised_user_error_page/supervised_user_error_page.h"
#include "content/public/browser/interstitial_page_delegate.h"
-#include "content/public/browser/origin_policy_error_reason.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/url_data_source.h"
@@ -84,11 +82,11 @@ class InterstitialHTMLSource : public content::URLDataSource {
~InterstitialHTMLSource() override = default;
// content::URLDataSource:
- std::string GetMimeType(const std::string& mime_type) const override;
- std::string GetSource() const override;
- std::string GetContentSecurityPolicyScriptSrc() const override;
- std::string GetContentSecurityPolicyStyleSrc() const override;
- std::string GetContentSecurityPolicyImgSrc() const override;
+ std::string GetMimeType(const std::string& mime_type) override;
+ std::string GetSource() override;
+ std::string GetContentSecurityPolicyScriptSrc() override;
+ std::string GetContentSecurityPolicyStyleSrc() override;
+ std::string GetContentSecurityPolicyImgSrc() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
@@ -424,7 +422,7 @@ CaptivePortalBlockingPage* CreateCaptivePortalBlockingPage(
security_interstitials::SecurityInterstitialPage*
CreateOriginPolicyInterstitialPage(content::WebContents* web_contents) {
return security_interstitials::OriginPolicyUI::GetBlockingPage(
- content::OriginPolicyErrorReason::kCannotLoadPolicy, web_contents,
+ network::OriginPolicyState::kCannotLoadPolicy, web_contents,
GURL("https://example.com/broken/origin/policy"));
}
@@ -441,25 +439,24 @@ InterstitialUI::~InterstitialUI() {
// InterstitialHTMLSource
-std::string InterstitialHTMLSource::GetMimeType(
- const std::string& mime_type) const {
+std::string InterstitialHTMLSource::GetMimeType(const std::string& mime_type) {
return "text/html";
}
-std::string InterstitialHTMLSource::GetSource() const {
+std::string InterstitialHTMLSource::GetSource() {
return chrome::kChromeUIInterstitialHost;
}
-std::string InterstitialHTMLSource::GetContentSecurityPolicyScriptSrc() const {
+std::string InterstitialHTMLSource::GetContentSecurityPolicyScriptSrc() {
// 'unsafe-inline' is added to script-src.
return "script-src chrome://resources 'self' 'unsafe-inline';";
}
-std::string InterstitialHTMLSource::GetContentSecurityPolicyStyleSrc() const {
+std::string InterstitialHTMLSource::GetContentSecurityPolicyStyleSrc() {
return "style-src 'self' 'unsafe-inline';";
}
-std::string InterstitialHTMLSource::GetContentSecurityPolicyImgSrc() const {
+std::string InterstitialHTMLSource::GetContentSecurityPolicyImgSrc() {
return "img-src data:;";
}
@@ -509,9 +506,8 @@ void InterstitialHTMLSource::StartDataRequest(
} else if (interstitial_delegate.get()) {
html = interstitial_delegate.get()->GetHTMLContents();
} else {
- html = ui::ResourceBundle::GetSharedInstance()
- .GetRawDataResource(IDR_SECURITY_INTERSTITIAL_UI_HTML)
- .as_string();
+ html = ui::ResourceBundle::GetSharedInstance().DecompressDataResource(
+ IDR_SECURITY_INTERSTITIAL_UI_HTML);
}
scoped_refptr<base::RefCountedString> html_bytes = new base::RefCountedString;
html_bytes->data().assign(html.begin(), html.end());
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 ad7d7c63d0f..2becb485ab2 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
@@ -28,19 +28,19 @@ namespace {
// 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 kPreviewsAllowedHtmlId[] = "previews-allowed-status";
-const char kClientLoFiPreviewsHtmlId[] = "client-lofi-preview-status";
const char kLitePageRedirectHtmlId[] = "lite-page-redirect-status";
const char kNoScriptPreviewsHtmlId[] = "noscript-preview-status";
const char kResourceLoadingHintsHtmlId[] = "resource-loading-hints-status";
const char kOfflinePreviewsHtmlId[] = "offline-preview-status";
+const char kDeferAllScriptPreviewsHtmlId[] = "defer-all-script-preview-status";
// Descriptions for previews.
const char kPreviewsAllowedDescription[] = "Previews Allowed";
-const char kClientLoFiDescription[] = "Client LoFi Previews";
const char kLitePageRedirectDescription[] =
"Lite Page Redirect / Server Previews";
const char kNoScriptDescription[] = "NoScript Previews";
const char kResourceLoadingHintsDescription[] = "ResourceLoadingHints Previews";
+const char kDeferAllScriptPreviewsDescription[] = "DeferAllScript Previews";
const char kOfflineDesciption[] = "Offline Previews";
// Flag feature name.
@@ -48,6 +48,7 @@ const char kPreviewsAllowedFeatureName[] = "Previews";
const char kLitePageRedirectFeatureName[] = "LitePageServerPreviews";
const char kNoScriptFeatureName[] = "NoScriptPreviews";
const char kResourceLoadingHintsFeatureName[] = "ResourceLoadingHints";
+const char kDeferAllScriptFeatureName[] = "DeferAllScript";
#if defined(OS_ANDROID)
const char kOfflinePageFeatureName[] = "OfflinePreviews";
#endif // OS_ANDROID
@@ -58,6 +59,7 @@ const char kPreviewsAllowedFlagHtmlId[] = "previews-flag";
const char kOfflinePageFlagHtmlId[] = "offline-page-flag";
const char kLitePageRedirectFlagHtmlId[] = "lite-page-redirect-flag";
const char kResourceLoadingHintsFlagHtmlId[] = "resource-loading-hints-flag";
+const char kDeferAllScriptFlagHtmlId[] = "defer-all-script-flag";
const char kNoScriptFlagHtmlId[] = "noscript-flag";
const char kEctFlagHtmlId[] = "ect-flag";
const char kIgnorePreviewsBlacklistFlagHtmlId[] = "ignore-previews-blacklist";
@@ -72,6 +74,8 @@ const char kLitePageRedirectFlagLink[] =
"chrome://flags/#enable-lite-page-server-previews";
const char kResourceLoadingHintsFlagLink[] =
"chrome://flags/#enable-resource-loading-hints";
+const char kDeferAllScriptFlagLink[] =
+ "chrome://flags/#enable-defer-all-script";
const char kNoScriptFlagLink[] = "chrome://flags/#enable-noscript-previews";
const char kEctFlagLink[] = "chrome://flags/#force-effective-connection-type";
const char kIgnorePreviewsBlacklistLink[] =
@@ -243,18 +247,20 @@ void InterventionsInternalsPageHandler::GetPreviewsEnabled(
resource_loading_hints_status->htmlId = kResourceLoadingHintsHtmlId;
statuses.push_back(std::move(resource_loading_hints_status));
+ auto defer_all_script_preview_status = mojom::PreviewsStatus::New();
+ defer_all_script_preview_status->description =
+ kDeferAllScriptPreviewsDescription;
+ defer_all_script_preview_status->enabled =
+ previews::params::IsDeferAllScriptPreviewsEnabled();
+ defer_all_script_preview_status->htmlId = kDeferAllScriptPreviewsHtmlId;
+ statuses.push_back(std::move(defer_all_script_preview_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));
}
@@ -302,6 +308,15 @@ void InterventionsInternalsPageHandler::GetPreviewsFlagsDetails(
resource_loading_hints_status->htmlId = kResourceLoadingHintsFlagHtmlId;
flags.push_back(std::move(resource_loading_hints_status));
+ auto defer_all_script_status = mojom::PreviewsFlag::New();
+ defer_all_script_status->description =
+ flag_descriptions::kEnableDeferAllScriptName;
+ defer_all_script_status->link = kDeferAllScriptFlagLink;
+ defer_all_script_status->value =
+ GetFeatureFlagStatus(kDeferAllScriptFeatureName);
+ defer_all_script_status->htmlId = kDeferAllScriptFlagHtmlId;
+ flags.push_back(std::move(defer_all_script_status));
+
auto noscript_status = mojom::PreviewsFlag::New();
noscript_status->description = flag_descriptions::kEnableNoScriptPreviewsName;
noscript_status->link = kNoScriptFlagLink;
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 53e7db108d3..3f8998adb52 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
@@ -54,8 +54,9 @@ constexpr char kPreviewsAllowedHtmlId[] = "previews-allowed-status";
constexpr char kOfflinePreviewsHtmlId[] = "offline-preview-status";
constexpr char kLitePageRedirectHtmlId[] = "lite-page-redirect-status";
constexpr char kResourceLoadingHintsHtmlId[] = "resource-loading-hints-status";
+constexpr char kDeferAllScriptPreviewsHtmlId[] =
+ "defer-all-script-preview-status";
constexpr char kNoScriptPreviewsHtmlId[] = "noscript-preview-status";
-constexpr char kClientLoFiPreviewsHtmlId[] = "client-lofi-preview-status";
// Descriptions for previews.
constexpr char kPreviewsAllowedDescription[] = "Previews Allowed";
@@ -64,14 +65,15 @@ constexpr char kLitePageRedirectDescription[] =
"Lite Page Redirect / Server Previews";
constexpr char kResourceLoadingHintsDescription[] =
"ResourceLoadingHints Previews";
+constexpr char kDeferAllScriptPreviewsDescription[] = "DeferAllScript 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 kLitePageRedirectFlagHtmlId[] = "lite-page-redirect-flag";
constexpr char kResourceLoadingHintsFlagHtmlId[] =
"resource-loading-hints-flag";
+constexpr char kDeferAllScriptFlagHtmlId[] = "defer-all-script-flag";
constexpr char kNoScriptFlagHtmlId[] = "noscript-flag";
constexpr char kEctFlagHtmlId[] = "ect-flag";
constexpr char kIgnorePreviewsBlacklistFlagHtmlId[] =
@@ -86,6 +88,8 @@ constexpr char kLitePageRedirectFlagLink[] =
"chrome://flags/#enable-lite-page-server-previews";
constexpr char kResourceLoadingHintsFlagLink[] =
"chrome://flags/#enable-resource-loading-hints";
+constexpr char kDeferAllScriptFlagLink[] =
+ "chrome://flags/#enable-defer-all-script";
constexpr char kNoScriptFlagLink[] = "chrome://flags/#enable-noscript-previews";
constexpr char kEctFlagLink[] =
"chrome://flags/#force-effective-connection-type";
@@ -98,6 +102,7 @@ constexpr char kDataSaverAltConfigLink[] =
constexpr char kOfflinePageFeatureName[] = "OfflinePreviews";
constexpr char kLitePageRedirectFeatureName[] = "LitePageServerPreviews";
constexpr char kResourceLoadingHintsFeatureName[] = "ResourceLoadingHints";
+constexpr char kDeferAllScriptFeatureName[] = "DeferAllScriptPreviews";
constexpr char kNoScriptFeatureName[] = "NoScriptPreviews";
constexpr char kDefaultFlagValue[] = "Default";
@@ -355,30 +360,6 @@ TEST_F(InterventionsInternalsPageHandlerTest, PreviewsAllowedEnabled) {
EXPECT_TRUE(previews_allowed->second->enabled);
}
-TEST_F(InterventionsInternalsPageHandlerTest, ClientLoFiDisabled) {
- // Init with kClientLoFi disabled.
- scoped_feature_list_->InitWithFeatures({}, {previews::features::kClientLoFi});
-
- page_handler_->GetPreviewsEnabled(
- base::BindOnce(&MockGetPreviewsEnabledCallback));
- auto client_lofi = passed_in_modes.find(kClientLoFiPreviewsHtmlId);
- ASSERT_NE(passed_in_modes.end(), client_lofi);
- EXPECT_EQ(kClientLoFiDescription, client_lofi->second->description);
- EXPECT_FALSE(client_lofi->second->enabled);
-}
-
-TEST_F(InterventionsInternalsPageHandlerTest, ClientLoFiEnabled) {
- // Init with kClientLoFi enabled.
- scoped_feature_list_->InitWithFeatures({previews::features::kClientLoFi}, {});
-
- page_handler_->GetPreviewsEnabled(
- base::BindOnce(&MockGetPreviewsEnabledCallback));
- auto client_lofi = passed_in_modes.find(kClientLoFiPreviewsHtmlId);
- ASSERT_NE(passed_in_modes.end(), client_lofi);
- EXPECT_EQ(kClientLoFiDescription, client_lofi->second->description);
- EXPECT_TRUE(client_lofi->second->enabled);
-}
-
TEST_F(InterventionsInternalsPageHandlerTest, NoScriptDisabled) {
// Init with kNoScript disabled.
scoped_feature_list_->InitWithFeatures(
@@ -490,11 +471,39 @@ TEST_F(InterventionsInternalsPageHandlerTest, LitePageRedirectEnabled) {
EXPECT_TRUE(resource_loading_hints->second->enabled);
}
+TEST_F(InterventionsInternalsPageHandlerTest, DeferAllScriptPreviewsDisabled) {
+ // Init with kDeferAllScriptPreviews disabled.
+ scoped_feature_list_->InitWithFeatures(
+ {}, {previews::features::kDeferAllScriptPreviews});
+
+ page_handler_->GetPreviewsEnabled(
+ base::BindOnce(&MockGetPreviewsEnabledCallback));
+ auto defer_all_script = passed_in_modes.find(kDeferAllScriptPreviewsHtmlId);
+ ASSERT_NE(passed_in_modes.end(), defer_all_script);
+ EXPECT_EQ(kDeferAllScriptPreviewsDescription,
+ defer_all_script->second->description);
+ EXPECT_FALSE(defer_all_script->second->enabled);
+}
+
+TEST_F(InterventionsInternalsPageHandlerTest, DeferAllScriptPreviewsEnabled) {
+ // Init with kDeferAllScriptPreviews enabled.
+ scoped_feature_list_->InitWithFeatures(
+ {previews::features::kDeferAllScriptPreviews}, {});
+
+ page_handler_->GetPreviewsEnabled(
+ base::BindOnce(&MockGetPreviewsEnabledCallback));
+ auto defer_all_script = passed_in_modes.find(kDeferAllScriptPreviewsHtmlId);
+ ASSERT_NE(passed_in_modes.end(), defer_all_script);
+ EXPECT_EQ(kDeferAllScriptPreviewsDescription,
+ defer_all_script->second->description);
+ EXPECT_TRUE(defer_all_script->second->enabled);
+}
+
TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsCount) {
page_handler_->GetPreviewsFlagsDetails(
base::BindOnce(&MockGetPreviewsFlagsCallback));
- constexpr size_t expected = 8;
+ constexpr size_t expected = 9;
EXPECT_EQ(expected, passed_in_flags.size());
}
@@ -537,7 +546,6 @@ TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsForceEctValue) {
}
TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsEctForceFieldtrialValue) {
- base::FieldTrialList field_trial_list_(nullptr);
const std::string trial_name = "NetworkQualityEstimator";
const std::string group_name = "Enabled";
const std::string expected_ect = "Slow-2G";
@@ -690,6 +698,53 @@ TEST_F(InterventionsInternalsPageHandlerTest,
}
TEST_F(InterventionsInternalsPageHandlerTest,
+ GetFlagsDeferAllScriptDefaultValue) {
+ page_handler_->GetPreviewsFlagsDetails(
+ base::BindOnce(&MockGetPreviewsFlagsCallback));
+ auto defer_all_script_flag = passed_in_flags.find(kDeferAllScriptFlagHtmlId);
+
+ ASSERT_NE(passed_in_flags.end(), defer_all_script_flag);
+ EXPECT_EQ(flag_descriptions::kEnableDeferAllScriptName,
+ defer_all_script_flag->second->description);
+ EXPECT_EQ(kDefaultFlagValue, defer_all_script_flag->second->value);
+ EXPECT_EQ(kDeferAllScriptFlagLink, defer_all_script_flag->second->link);
+}
+
+TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsDeferAllScriptEnabled) {
+ base::test::ScopedCommandLine scoped_command_line;
+ base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine();
+ command_line->AppendSwitchASCII(switches::kEnableFeatures,
+ kDeferAllScriptFeatureName);
+
+ page_handler_->GetPreviewsFlagsDetails(
+ base::BindOnce(&MockGetPreviewsFlagsCallback));
+ auto defer_all_script_flag = passed_in_flags.find(kDeferAllScriptFlagHtmlId);
+
+ ASSERT_NE(passed_in_flags.end(), defer_all_script_flag);
+ EXPECT_EQ(flag_descriptions::kEnableDeferAllScriptName,
+ defer_all_script_flag->second->description);
+ EXPECT_EQ(kEnabledFlagValue, defer_all_script_flag->second->value);
+ EXPECT_EQ(kDeferAllScriptFlagLink, defer_all_script_flag->second->link);
+}
+
+TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsDeferAllScriptDisabled) {
+ base::test::ScopedCommandLine scoped_command_line;
+ base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine();
+ command_line->AppendSwitchASCII(switches::kDisableFeatures,
+ kDeferAllScriptFeatureName);
+
+ page_handler_->GetPreviewsFlagsDetails(
+ base::BindOnce(&MockGetPreviewsFlagsCallback));
+ auto defer_all_script_flag = passed_in_flags.find(kDeferAllScriptFlagHtmlId);
+
+ ASSERT_NE(passed_in_flags.end(), defer_all_script_flag);
+ EXPECT_EQ(flag_descriptions::kEnableDeferAllScriptName,
+ defer_all_script_flag->second->description);
+ EXPECT_EQ(kDisabledFlagValue, defer_all_script_flag->second->value);
+ EXPECT_EQ(kDeferAllScriptFlagLink, defer_all_script_flag->second->link);
+}
+
+TEST_F(InterventionsInternalsPageHandlerTest,
GetFlagsLitePageRedirectDefaultValue) {
page_handler_->GetPreviewsFlagsDetails(
base::BindOnce(&MockGetPreviewsFlagsCallback));
diff --git a/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc b/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc
index 7b21427b89f..858391be7b1 100644
--- a/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc
+++ b/chromium/chrome/browser/ui/webui/invalidations_message_handler.cc
@@ -40,8 +40,7 @@ invalidation::ProfileInvalidationProvider* GetInvalidationProvider(
} // namespace
-InvalidationsMessageHandler::InvalidationsMessageHandler()
- : logger_(NULL), weak_ptr_factory_(this) {}
+InvalidationsMessageHandler::InvalidationsMessageHandler() : logger_(nullptr) {}
InvalidationsMessageHandler::~InvalidationsMessageHandler() {
if (logger_)
diff --git a/chromium/chrome/browser/ui/webui/invalidations_message_handler.h b/chromium/chrome/browser/ui/webui/invalidations_message_handler.h
index 8d94440be97..f357963065c 100644
--- a/chromium/chrome/browser/ui/webui/invalidations_message_handler.h
+++ b/chromium/chrome/browser/ui/webui/invalidations_message_handler.h
@@ -57,7 +57,7 @@ class InvalidationsMessageHandler
// register ourselves as Observers for any notifications.
invalidation::InvalidationLogger* logger_;
- base::WeakPtrFactory<InvalidationsMessageHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<InvalidationsMessageHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(InvalidationsMessageHandler);
};
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 fe9a0f776c4..94f7f790bb2 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
@@ -35,9 +35,9 @@
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/base/web_ui_browser_test.h"
+#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/http/http_status_code.h"
-#include "services/identity/public/cpp/identity_test_utils.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
@@ -390,7 +390,7 @@ class LocalDiscoveryUITest : public WebUIBrowserTest {
test_url_loader_factory_.AddResponse(kURLRegisterComplete,
kResponseRegisterComplete);
- identity::MakePrimaryAccountAvailable(
+ signin::MakePrimaryAccountAvailable(
IdentityManagerFactory::GetForProfile(browser()->profile()),
kSampleUser);
@@ -501,9 +501,9 @@ IN_PROC_BROWSER_TEST_F(LocalDiscoveryUITest, RegisterTest) {
}));
EXPECT_TRUE(WebUIBrowserTest::RunJavascriptTest("registerBegin"));
run_loop.Run();
- EXPECT_TRUE(base::ContainsKey(served_urls, GURL(kURLInfo)));
- EXPECT_TRUE(base::ContainsKey(served_urls, GURL(kURLRegisterStart)));
- EXPECT_TRUE(base::ContainsKey(served_urls, GURL(kURLRegisterClaimToken)));
+ EXPECT_TRUE(base::Contains(served_urls, GURL(kURLInfo)));
+ EXPECT_TRUE(base::Contains(served_urls, GURL(kURLRegisterStart)));
+ EXPECT_TRUE(base::Contains(served_urls, GURL(kURLRegisterClaimToken)));
test_url_loader_factory()->SetInterceptor(base::NullCallback());
}
@@ -523,10 +523,10 @@ IN_PROC_BROWSER_TEST_F(LocalDiscoveryUITest, RegisterTest) {
run_loop.Quit();
}));
run_loop.Run();
- EXPECT_TRUE(base::ContainsKey(served_urls, GURL(kURLRegisterClaimToken)));
- EXPECT_TRUE(base::ContainsKey(served_urls, GURL(kURLCloudPrintConfirm)));
- EXPECT_TRUE(base::ContainsKey(served_urls, GURL(kURLRegisterComplete)));
- EXPECT_TRUE(base::ContainsKey(served_urls, GURL(kURLInfo)));
+ EXPECT_TRUE(base::Contains(served_urls, GURL(kURLRegisterClaimToken)));
+ EXPECT_TRUE(base::Contains(served_urls, GURL(kURLCloudPrintConfirm)));
+ EXPECT_TRUE(base::Contains(served_urls, GURL(kURLRegisterComplete)));
+ EXPECT_TRUE(base::Contains(served_urls, GURL(kURLInfo)));
test_url_loader_factory()->SetInterceptor(base::NullCallback());
}
diff --git a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc
index ae9fae44529..1a905066c73 100644
--- a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc
+++ b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.cc
@@ -79,13 +79,13 @@ void ReadDevicesList(const CloudPrintPrinterList::DeviceList& devices,
const std::set<std::string>& local_ids,
base::ListValue* devices_list) {
for (const auto& i : devices) {
- if (base::ContainsKey(local_ids, i.id)) {
+ if (base::Contains(local_ids, i.id)) {
devices_list->Append(CreateDeviceInfo(i));
}
}
for (const auto& i : devices) {
- if (!base::ContainsKey(local_ids, i.id)) {
+ if (!base::Contains(local_ids, i.id)) {
devices_list->Append(CreateDeviceInfo(i));
}
}
@@ -119,7 +119,7 @@ LocalDiscoveryUIHandler::LocalDiscoveryUIHandler()
LocalDiscoveryUIHandler::~LocalDiscoveryUIHandler() {
Profile* profile = Profile::FromWebUI(web_ui());
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
if (identity_manager)
identity_manager->RemoveObserver(this);
@@ -193,7 +193,7 @@ void LocalDiscoveryUIHandler::HandleStart(const base::ListValue* args) {
cloud_print::PrivetHTTPAsynchronousFactory::CreateInstance(
url_loader_factory);
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
if (identity_manager)
identity_manager->AddObserver(this);
@@ -300,8 +300,7 @@ void LocalDiscoveryUIHandler::OnPrivetRegisterClaimToken(
const GURL& url) {
web_ui()->CallJavascriptFunctionUnsafe(
"local_discovery.onRegistrationConfirmedOnPrinter");
- if (!base::ContainsKey(device_descriptions_,
- current_http_client_->GetName())) {
+ if (!base::Contains(device_descriptions_, current_http_client_->GetName())) {
SendRegisterError();
return;
}
@@ -459,7 +458,7 @@ void LocalDiscoveryUIHandler::SendRegisterDone(
std::string LocalDiscoveryUIHandler::GetSyncAccount() const {
Profile* profile = Profile::FromWebUI(web_ui());
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
std::string email;
@@ -516,7 +515,7 @@ std::unique_ptr<GCDApiFlow> LocalDiscoveryUIHandler::CreateApiFlow() {
if (!profile)
return std::unique_ptr<GCDApiFlow>();
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
if (!(identity_manager && identity_manager->HasPrimaryAccount()))
return std::unique_ptr<GCDApiFlow>();
diff --git a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h
index 0844fb69ddc..caf5a5b870d 100644
--- a/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h
+++ b/chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h
@@ -15,9 +15,10 @@
#include "chrome/browser/printing/cloud_print/cloud_print_printer_list.h"
#include "chrome/browser/printing/cloud_print/privet_device_lister.h"
#include "chrome/browser/printing/cloud_print/privet_http.h"
+#include "components/prefs/pref_member.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "printing/buildflags/buildflags.h"
-#include "services/identity/public/cpp/identity_manager.h"
#if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_CHROMEOS)
#define CLOUD_PRINT_CONNECTOR_UI_AVAILABLE
@@ -44,7 +45,7 @@ class LocalDiscoveryUIHandler
public cloud_print::PrivetRegisterOperation::Delegate,
public cloud_print::PrivetDeviceLister::Delegate,
public cloud_print::CloudPrintPrinterList::Delegate,
- public identity::IdentityManager::Observer {
+ public signin::IdentityManager::Observer {
public:
// Class used to set a URLLoaderFactory that should be used when making
// network requests. Create one instance of this object with the
@@ -90,7 +91,7 @@ class LocalDiscoveryUIHandler
const cloud_print::CloudPrintPrinterList::DeviceList& devices) override;
void OnDeviceListUnavailable() override;
- // identity::IdentityManager::Observer implementation.
+ // signin::IdentityManager::Observer implementation.
void OnPrimaryAccountSet(
const CoreAccountInfo& primary_account_info) override;
void OnPrimaryAccountCleared(
diff --git a/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc b/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc
index 06fd62ceb7a..f9a4b1b0c37 100644
--- a/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/managed_ui_handler_unittest.cc
@@ -4,12 +4,10 @@
#include "chrome/browser/ui/webui/managed_ui_handler.h"
-#include "base/test/scoped_feature_list.h"
#include "base/token.h"
#include "base/values.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/common/chrome_features.h"
#include "chrome/test/base/testing_profile.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/core/common/policy_service_impl.h"
@@ -35,8 +33,6 @@ class ManagedUIHandlerTest : public testing::Test {
ManagedUIHandlerTest()
: source_(content::TestWebUIDataSource::Create(
base::Token::CreateRandom().ToString())) {
- features_.InitAndEnableFeature(features::kShowManagedUi);
-
// Create a TestingProfile that uses our MockConfigurationPolicyProvider.
policy_provider()->Init();
policy::PolicyServiceImpl::Providers providers = {policy_provider()};
@@ -80,7 +76,6 @@ class ManagedUIHandlerTest : public testing::Test {
private:
content::TestBrowserThreadBundle bundle_;
- base::test::ScopedFeatureList features_;
testing::NiceMock<policy::MockConfigurationPolicyProvider> policy_provider_;
std::unique_ptr<TestingProfile> profile_;
diff --git a/chromium/chrome/browser/ui/webui/management_ui.cc b/chromium/chrome/browser/ui/webui/management_ui.cc
index 8801658e631..fd0d3cbdde4 100644
--- a/chromium/chrome/browser/ui/webui/management_ui.cc
+++ b/chromium/chrome/browser/ui/webui/management_ui.cc
@@ -10,7 +10,6 @@
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
#include "chrome/browser/ui/webui/localized_string.h"
#include "chrome/browser/ui/webui/management_ui_handler.h"
#include "chrome/common/url_constants.h"
@@ -59,6 +58,7 @@ content::WebUIDataSource* CreateManagementUIHtmlSource(Profile* profile) {
IDS_MANAGEMENT_REPORT_DEVICE_NETWORK_INTERFACES},
{kManagementReportUsers, IDS_MANAGEMENT_REPORT_DEVICE_USERS},
{kManagementPrinting, IDS_MANAGEMENT_REPORT_PRINTING},
+ {kManagementCrostini, IDS_MANAGEMENT_CROSTINI},
#endif // defined(OS_CHROMEOS)
{"browserReporting", IDS_MANAGEMENT_BROWSER_REPORTING},
{"browserReportingExplanation",
@@ -72,7 +72,6 @@ content::WebUIDataSource* CreateManagementUIHtmlSource(Profile* profile) {
{"searchPrompt", IDS_SETTINGS_SEARCH_PROMPT},
{"clearSearch", IDS_DOWNLOAD_CLEAR_SEARCH},
{"backButton", IDS_ACCNAME_BACK},
-#if BUILDFLAG(ENABLE_EXTENSIONS)
{kManagementExtensionReportMachineName,
IDS_MANAGEMENT_EXTENSION_REPORT_MACHINE_NAME},
{kManagementExtensionReportMachineNameAddress,
@@ -87,7 +86,6 @@ content::WebUIDataSource* CreateManagementUIHtmlSource(Profile* profile) {
IDS_MANAGEMENT_EXTENSION_REPORT_PERF_CRASH},
{kManagementExtensionReportUserBrowsingData,
IDS_MANAGEMENT_EXTENSION_REPORT_USER_BROWSING_DATA},
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
};
AddLocalizedStringsBulk(source, kLocalizedStrings,
@@ -173,7 +171,6 @@ ManagementUI::ManagementUI(content::WebUI* web_ui) : WebUIController(web_ui) {
content::WebUIDataSource* source =
CreateManagementUIHtmlSource(Profile::FromWebUI(web_ui));
ManagementUIHandler::Initialize(web_ui, source);
- DarkModeHandler::Initialize(web_ui, source);
content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source);
}
diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler.cc b/chromium/chrome/browser/ui/webui/management_ui_handler.cc
index e6cdb78a74d..329d86573be 100644
--- a/chromium/chrome/browser/ui/webui/management_ui_handler.cc
+++ b/chromium/chrome/browser/ui/webui/management_ui_handler.cc
@@ -36,6 +36,7 @@
#include "ui/base/webui/web_ui_util.h"
#if defined(OS_CHROMEOS)
+#include "chrome/browser/chromeos/crostini/crostini_pref_names.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h"
#include "chrome/browser/chromeos/policy/policy_cert_service.h"
@@ -50,7 +51,6 @@
#include "ui/chromeos/devicetype_utils.h"
#endif // defined(OS_CHROMEOS)
-#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/common/extensions/permissions/chrome_permission_message_provider.h"
#include "components/policy/core/common/policy_map.h"
@@ -109,8 +109,6 @@ enum class ReportingType {
kUserActivity
};
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
-
#if defined(OS_CHROMEOS)
const char kManagementLogUploadEnabled[] = "managementLogUploadEnabled";
const char kManagementReportActivityTimes[] = "managementReportActivityTimes";
@@ -119,6 +117,7 @@ const char kManagementReportNetworkInterfaces[] =
"managementReportNetworkInterfaces";
const char kManagementReportUsers[] = "managementReportUsers";
const char kManagementPrinting[] = "managementPrinting";
+const char kManagementCrostini[] = "managementCrostini";
const char kAccountManagedInfo[] = "accountManagedInfo";
const char kDeviceManagedInfo[] = "deviceManagedInfo";
const char kOverview[] = "overview";
@@ -155,7 +154,8 @@ enum class DeviceReportingType {
kDeviceStatistics,
kDevice,
kLogs,
- kPrint
+ kPrint,
+ kCrostini
};
// Corresponds to DeviceReportingType in management_browser_proxy.js
@@ -173,6 +173,8 @@ std::string ToJSDeviceReportingType(const DeviceReportingType& type) {
return "logs";
case DeviceReportingType::kPrint:
return "print";
+ case DeviceReportingType::kCrostini:
+ return "crostini";
default:
NOTREACHED() << "Unknown device reporting type";
return "device";
@@ -234,10 +236,15 @@ void AddDeviceReportingInfo(base::Value* report_sources, Profile* profile) {
AddDeviceReportingElement(report_sources, kManagementPrinting,
DeviceReportingType::kPrint);
}
+
+ if (profile->GetPrefs()->GetBoolean(
+ crostini::prefs::kReportCrostiniUsageEnabled)) {
+ AddDeviceReportingElement(report_sources, kManagementCrostini,
+ DeviceReportingType::kCrostini);
+ }
}
#endif // defined(OS_CHROMEOS)
-#if BUILDFLAG(ENABLE_EXTENSIONS)
std::vector<base::Value> GetPermissionsForExtension(
scoped_refptr<const extensions::Extension> extension) {
std::vector<base::Value> permission_messages;
@@ -298,8 +305,6 @@ const char* GetReportingTypeValue(ReportingType reportingType) {
}
}
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
-
} // namespace
// TODO(raleksandov) Move to util class or smth similar.
@@ -323,11 +328,9 @@ std::string ManagementUIHandler::GetAccountDomain(Profile* profile) {
}
ManagementUIHandler::ManagementUIHandler() {
-#if BUILDFLAG(ENABLE_EXTENSIONS)
reporting_extension_ids_ = {kOnPremReportingExtensionStableId,
kOnPremReportingExtensionBetaId,
kCloudReportingExtensionId};
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
}
ManagementUIHandler::~ManagementUIHandler() {
@@ -379,7 +382,6 @@ void ManagementUIHandler::RegisterMessages() {
base::Unretained(this)));
}
-#if BUILDFLAG(ENABLE_EXTENSIONS)
void ManagementUIHandler::OnJavascriptAllowed() {
AddObservers();
}
@@ -570,7 +572,6 @@ const extensions::Extension* ManagementUIHandler::GetEnabledExtension(
->GetExtensionById(kCloudReportingExtensionId,
extensions::ExtensionRegistry::ENABLED);
}
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
void ManagementUIHandler::AsyncUpdateLogo() {
#if defined(OS_CHROMEOS)
@@ -701,7 +702,6 @@ void ManagementUIHandler::GetManagementStatus(Profile* profile,
void ManagementUIHandler::HandleGetExtensions(const base::ListValue* args) {
AllowJavascript();
-#if BUILDFLAG(ENABLE_EXTENSIONS)
// List of all enabled extensions
const extensions::ExtensionSet& extensions =
extensions::ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))
@@ -711,10 +711,6 @@ void ManagementUIHandler::HandleGetExtensions(const base::ListValue* args) {
ResolveJavascriptCallback(args->GetList()[0] /* callback_id */,
powerful_extensions);
-#else
- ResolveJavascriptCallback(args->GetList()[0] /* callback_id */,
- base::Value(base::Value::Type::LIST));
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
}
#if defined(OS_CHROMEOS)
@@ -758,14 +754,11 @@ void ManagementUIHandler::HandleInitBrowserReportingInfo(
const base::ListValue* args) {
base::Value report_sources(base::Value::Type::LIST);
AllowJavascript();
-#if BUILDFLAG(ENABLE_EXTENSIONS)
AddExtensionReportingInfo(&report_sources);
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
ResolveJavascriptCallback(args->GetList()[0] /* callback_id */,
report_sources);
}
-#if BUILDFLAG(ENABLE_EXTENSIONS)
void ManagementUIHandler::NotifyBrowserReportingInfoUpdated() {
base::Value report_sources(base::Value::Type::LIST);
AddExtensionReportingInfo(&report_sources);
@@ -854,4 +847,3 @@ void ManagementUIHandler::RemoveObservers() {
pref_registrar_.RemoveAll();
}
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler.h b/chromium/chrome/browser/ui/webui/management_ui_handler.h
index 2247b4bab72..1d40707ca7c 100644
--- a/chromium/chrome/browser/ui/webui/management_ui_handler.h
+++ b/chromium/chrome/browser/ui/webui/management_ui_handler.h
@@ -14,18 +14,15 @@
#include "base/strings/string16.h"
#include "chrome/browser/bitmap_fetcher/bitmap_fetcher.h"
#include "chrome/common/url_constants.h"
+#include "components/policy/core/common/policy_service.h"
#include "components/prefs/pref_change_registrar.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 "extensions/browser/extension_registry_observer.h"
#include "extensions/buildflags/buildflags.h"
#include "url/gurl.h"
-#if BUILDFLAG(ENABLE_EXTENSIONS)
-#include "components/policy/core/common/policy_service.h"
-#include "extensions/browser/extension_registry_observer.h"
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
-
#if defined(OS_CHROMEOS)
// Constants defining the IDs for the localized strings sent to the page as
// load time data.
@@ -35,9 +32,9 @@ extern const char kManagementReportHardwareStatus[];
extern const char kManagementReportNetworkInterfaces[];
extern const char kManagementReportUsers[];
extern const char kManagementPrinting[];
+extern const char kManagementCrostini[];
#endif // defined(OS_CHROMEOS)
-#if BUILDFLAG(ENABLE_EXTENSIONS)
extern const char kCloudReportingExtensionId[];
extern const char kOnPremReportingExtensionStableId[];
extern const char kOnPremReportingExtensionBetaId[];
@@ -66,8 +63,6 @@ extern const char kReportingTypeSecurity[];
extern const char kReportingTypeUser[];
extern const char kReportingTypeUserActivity[];
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
-
namespace base {
class ListValue;
} // namespace base
@@ -83,15 +78,10 @@ class PolicyService;
class Profile;
// The JavaScript message handler for the chrome://management page.
-#if BUILDFLAG(ENABLE_EXTENSIONS)
class ManagementUIHandler : public content::WebUIMessageHandler,
public extensions::ExtensionRegistryObserver,
public policy::PolicyService::Observer,
public BitmapFetcherDelegate {
-#else
-class ManagementUIHandler : public content::WebUIMessageHandler,
- public BitmapFetcherDelegate {
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
public:
ManagementUIHandler();
~ManagementUIHandler() override;
@@ -107,13 +97,10 @@ class ManagementUIHandler : public content::WebUIMessageHandler,
static std::string GetAccountDomain(Profile* profile);
-#if BUILDFLAG(ENABLE_EXTENSIONS)
void OnJavascriptAllowed() override;
void OnJavascriptDisallowed() override;
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
protected:
-#if BUILDFLAG(ENABLE_EXTENSIONS)
// Protected for testing.
static void InitializeInternal(content::WebUI* web_ui,
content::WebUIDataSource* source,
@@ -124,7 +111,6 @@ class ManagementUIHandler : public content::WebUIMessageHandler,
virtual policy::PolicyService* GetPolicyService() const;
virtual const extensions::Extension* GetEnabledExtension(
const std::string& extensionId) const;
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
#if defined(OS_CHROMEOS)
// Protected for testing.
@@ -151,7 +137,6 @@ class ManagementUIHandler : public content::WebUIMessageHandler,
// BitmapFetcherDelegate
void OnFetchComplete(const GURL& url, const SkBitmap* bitmap) override;
-#if BUILDFLAG(ENABLE_EXTENSIONS)
void NotifyBrowserReportingInfoUpdated();
// extensions::ExtensionRegistryObserver implementation.
@@ -182,7 +167,6 @@ class ManagementUIHandler : public content::WebUIMessageHandler,
PrefChangeRegistrar pref_registrar_;
std::set<extensions::ExtensionId> reporting_extension_ids_;
-#endif // BUILDFLAG(ENABLE_EXTENSIONS)
GURL logo_url_;
std::string fetched_image_;
std::unique_ptr<BitmapFetcher> icon_fetcher_;
diff --git a/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc b/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc
index f49bed13d29..c4172e96053 100644
--- a/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc
+++ b/chromium/chrome/browser/ui/webui/media/webrtc_logs_ui.cc
@@ -160,7 +160,7 @@ class WebRtcLogsDOMHandler final : public WebUIMessageHandler {
std::vector<UploadList::UploadInfo> event_logs_;
// Factory for creating weak references to instances of this class.
- base::WeakPtrFactory<WebRtcLogsDOMHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<WebRtcLogsDOMHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(WebRtcLogsDOMHandler);
};
@@ -174,8 +174,7 @@ WebRtcLogsDOMHandler::WebRtcLogsDOMHandler(Profile* profile)
original_browser_context_id_(webrtc_event_logging::GetBrowserContextId(
profile->GetOriginalProfile())),
text_log_upload_list_(
- webrtc_logging::TextLogList::CreateWebRtcLogList(profile)),
- weak_ptr_factory_(this) {
+ webrtc_logging::TextLogList::CreateWebRtcLogList(profile)) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.cc
deleted file mode 100644
index 6ca08d656c7..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.cc
+++ /dev/null
@@ -1,321 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h"
-
-#include <memory>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "base/trace_event/trace_event.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/browser_window.h"
-#include "chrome/browser/ui/webui/constrained_web_dialog_ui.h"
-#include "chrome/browser/ui/webui/media_router/media_router_ui.h"
-#include "chrome/common/url_constants.h"
-#include "components/guest_view/browser/guest_view_base.h"
-#include "components/web_modal/web_contents_modal_dialog_host.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/host_zoom_map.h"
-#include "content/public/browser/navigation_controller.h"
-#include "content/public/browser/navigation_details.h"
-#include "content/public/browser/navigation_entry.h"
-#include "content/public/browser/render_frame_host.h"
-#include "content/public/browser/render_process_host.h"
-#include "content/public/browser/render_view_host.h"
-#include "ui/web_dialogs/web_dialog_delegate.h"
-#include "ui/web_dialogs/web_dialog_web_contents_delegate.h"
-#include "url/gurl.h"
-
-using content::LoadCommittedDetails;
-using content::NavigationController;
-using content::WebContents;
-using content::WebUIMessageHandler;
-using ui::WebDialogDelegate;
-
-namespace media_router {
-
-namespace {
-
-constexpr const int kMaxHeight = 2000;
-constexpr const int kMinHeight = 80;
-constexpr const int kWidth = 340;
-
-// WebDialogDelegate that specifies what the Media Router dialog
-// will look like.
-class MediaRouterDialogDelegate : public WebDialogDelegate {
- public:
- explicit MediaRouterDialogDelegate(
- const base::WeakPtr<MediaRouterDialogControllerWebUIImpl>& controller)
- : controller_(controller) {}
- ~MediaRouterDialogDelegate() override {}
-
- // WebDialogDelegate implementation.
- ui::ModalType GetDialogModalType() const override {
- // Not used, returning dummy value.
- return ui::MODAL_TYPE_WINDOW;
- }
-
- base::string16 GetDialogTitle() const override { return base::string16(); }
-
- GURL GetDialogContentURL() const override {
- return GURL(chrome::kChromeUIMediaRouterURL);
- }
-
- void GetWebUIMessageHandlers(
- std::vector<WebUIMessageHandler*>* handlers) const override {
- // MediaRouterUI adds its own message handlers.
- }
-
- void GetDialogSize(gfx::Size* size) const override {
- DCHECK(size);
- // We set the dialog width if it's not set, so that the dialog is
- // center-aligned horizontally when it appears.
- if (size->width() != kWidth)
- size->set_width(kWidth);
- // GetDialogSize() is called when the browser window resizes. We may want to
- // update the maximum height of the dialog and scale the WebUI to the new
- // height. |size| is not set because the dialog is auto-resizeable.
- controller_->UpdateMaxDialogSize();
- }
-
- std::string GetDialogArgs() const override { return std::string(); }
-
- void OnDialogClosed(const std::string& json_retval) override {
- // We don't delete |this| here because this class is owned
- // by ConstrainedWebDialogDelegate.
- }
-
- void OnCloseContents(WebContents* source, bool* out_close_dialog) override {
- if (out_close_dialog)
- *out_close_dialog = true;
- }
-
- bool ShouldShowDialogTitle() const override { return false; }
-
- private:
- base::WeakPtr<MediaRouterDialogControllerWebUIImpl> controller_;
-
- DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogDelegate);
-};
-
-} // namespace
-
-#if !defined(TOOLKIT_VIEWS)
-// static
-MediaRouterDialogControllerImplBase*
-MediaRouterDialogControllerImplBase::GetOrCreateForWebContents(
- content::WebContents* web_contents) {
- return MediaRouterDialogControllerWebUIImpl::GetOrCreateForWebContents(
- web_contents);
-}
-
-// static
-MediaRouterDialogControllerImplBase*
-MediaRouterDialogControllerImplBase::FromWebContents(
- content::WebContents* web_contents) {
- return MediaRouterDialogControllerWebUIImpl::FromWebContents(web_contents);
-}
-#endif // !defined(TOOLKIT_VIEWS)
-
-class MediaRouterDialogControllerWebUIImpl::DialogWebContentsObserver
- : public content::WebContentsObserver {
- public:
- DialogWebContentsObserver(
- WebContents* web_contents,
- MediaRouterDialogControllerWebUIImpl* dialog_controller)
- : content::WebContentsObserver(web_contents),
- dialog_controller_(dialog_controller) {}
-
- private:
- void WebContentsDestroyed() override {
- // The dialog is already closed. No need to call Close() again.
- // NOTE: |this| is deleted after Reset() returns.
- dialog_controller_->Reset();
- }
-
- void NavigationEntryCommitted(
- const LoadCommittedDetails& load_details) override {
- dialog_controller_->OnDialogNavigated(load_details);
- }
-
- void RenderProcessGone(base::TerminationStatus status) override {
- // NOTE: |this| is deleted after CloseMediaRouterDialog() returns.
- dialog_controller_->CloseMediaRouterDialog();
- }
-
- MediaRouterDialogControllerWebUIImpl* const dialog_controller_;
-};
-
-// static
-MediaRouterDialogControllerWebUIImpl*
-MediaRouterDialogControllerWebUIImpl::GetOrCreateForWebContents(
- content::WebContents* web_contents) {
- DCHECK(web_contents);
- // This call does nothing if the controller already exists.
- CreateForWebContents(web_contents);
- return FromWebContents(web_contents);
-}
-
-MediaRouterDialogControllerWebUIImpl::~MediaRouterDialogControllerWebUIImpl() {
- Reset();
-}
-
-WebContents* MediaRouterDialogControllerWebUIImpl::GetMediaRouterDialog()
- const {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- return dialog_observer_.get() ? dialog_observer_->web_contents() : nullptr;
-}
-
-void MediaRouterDialogControllerWebUIImpl::CreateMediaRouterDialog() {
- MediaRouterDialogControllerImplBase::CreateMediaRouterDialog();
-
- DCHECK(!dialog_observer_.get());
-
- base::Time dialog_creation_time = base::Time::Now();
- TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("media_router", "UI", initiator());
-
- Profile* profile =
- Profile::FromBrowserContext(initiator()->GetBrowserContext());
- DCHECK(profile);
-
- auto web_dialog_delegate = std::make_unique<MediaRouterDialogDelegate>(
- weak_ptr_factory_.GetWeakPtr());
- WebDialogDelegate* web_dialog_delegate_ptr = web_dialog_delegate.get();
-
- // |ShowConstrainedWebDialogWithAutoResize()| will end up creating
- // ConstrainedWebDialogDelegateViewViews containing a WebContents containing
- // the MediaRouterUI, using the provided |web_dialog_delegate|. Then, the
- // view is shown as a modal dialog constrained to the |initiator| WebContents.
- // The dialog will resize between the given minimum and maximum size bounds
- // based on the currently rendered contents.
- // |constrained_delegate| is owned by the parent |views::View|.
- ConstrainedWebDialogDelegate* constrained_delegate =
- ShowConstrainedWebDialogWithAutoResize(
- profile, std::move(web_dialog_delegate), initiator(),
- gfx::Size(kWidth, kMinHeight), gfx::Size(kWidth, kMaxHeight));
-
- WebContents* media_router_dialog = constrained_delegate->GetWebContents();
- TRACE_EVENT_NESTABLE_ASYNC_INSTANT1("media_router", "UI", initiator(),
- "WebContents created",
- media_router_dialog);
-
- // Clear the zoom level for the dialog so that it is not affected by the page
- // zoom setting.
- const GURL dialog_url = web_dialog_delegate_ptr->GetDialogContentURL();
- content::HostZoomMap::Get(media_router_dialog->GetSiteInstance())
- ->SetZoomLevelForHostAndScheme(dialog_url.scheme(), dialog_url.host(), 0);
-
- // |media_router_ui| is created when |constrained_delegate| is created.
- // For tests, GetWebUI() returns a nullptr.
- if (media_router_dialog->GetWebUI()) {
- MediaRouterUI* media_router_ui = static_cast<MediaRouterUI*>(
- media_router_dialog->GetWebUI()->GetController());
- DCHECK(media_router_ui);
- media_router_ui->SetUIInitializationTimer(dialog_creation_time);
- }
-
- media_router_dialog_pending_ = true;
-
- dialog_observer_ =
- std::make_unique<DialogWebContentsObserver>(media_router_dialog, this);
-}
-
-void MediaRouterDialogControllerWebUIImpl::CloseMediaRouterDialog() {
- WebContents* media_router_dialog = GetMediaRouterDialog();
- if (!media_router_dialog)
- return;
-
- content::WebUI* web_ui = media_router_dialog->GetWebUI();
- if (web_ui) {
- MediaRouterUI* media_router_ui =
- static_cast<MediaRouterUI*>(web_ui->GetController());
- if (media_router_ui)
- media_router_ui->Close();
- }
-}
-
-bool MediaRouterDialogControllerWebUIImpl::IsShowingMediaRouterDialog() const {
- return GetMediaRouterDialog() != nullptr;
-}
-
-void MediaRouterDialogControllerWebUIImpl::Reset() {
- MediaRouterDialogControllerImplBase::Reset();
- dialog_observer_.reset();
-}
-
-void MediaRouterDialogControllerWebUIImpl::UpdateMaxDialogSize() {
- WebContents* media_router_dialog = GetMediaRouterDialog();
- if (!media_router_dialog)
- return;
-
- content::WebUI* web_ui = media_router_dialog->GetWebUI();
- if (web_ui) {
- MediaRouterUI* media_router_ui =
- static_cast<MediaRouterUI*>(web_ui->GetController());
- if (media_router_ui) {
- Browser* browser = chrome::FindBrowserWithWebContents(initiator());
- web_modal::WebContentsModalDialogHost* host = nullptr;
- if (browser)
- host = browser->window()->GetWebContentsModalDialogHost();
-
- gfx::Size maxSize = host ? host->GetMaximumDialogSize()
- : initiator()->GetContainerBounds().size();
-
- // The max height of the dialog should be 90% of the browser window
- // height. The width stays fixed.
- maxSize.Enlarge(0, -0.1 * maxSize.height());
- media_router_ui->UpdateMaxDialogHeight(maxSize.height());
- }
- }
-}
-
-MediaRouterDialogControllerWebUIImpl::MediaRouterDialogControllerWebUIImpl(
- WebContents* web_contents)
- : MediaRouterDialogControllerImplBase(web_contents),
- media_router_dialog_pending_(false),
- weak_ptr_factory_(this) {}
-
-void MediaRouterDialogControllerWebUIImpl::OnDialogNavigated(
- const content::LoadCommittedDetails& details) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- WebContents* media_router_dialog = GetMediaRouterDialog();
- CHECK(media_router_dialog);
- ui::PageTransition transition_type = details.entry->GetTransitionType();
- content::NavigationType nav_type = details.type;
-
- // New |media_router_dialog| is created.
- DCHECK(media_router_dialog_pending_);
- DCHECK(ui::PageTransitionCoreTypeIs(transition_type,
- ui::PAGE_TRANSITION_AUTO_TOPLEVEL) &&
- nav_type == content::NAVIGATION_TYPE_NEW_PAGE)
- << "transition_type: " << transition_type << ", "
- << "nav_type: " << nav_type;
-
- media_router_dialog_pending_ = false;
-
- PopulateDialog(media_router_dialog);
-}
-
-void MediaRouterDialogControllerWebUIImpl::PopulateDialog(
- content::WebContents* media_router_dialog) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- DCHECK(media_router_dialog);
- if (!initiator() || !media_router_dialog->GetWebUI()) {
- Reset();
- return;
- }
-
- MediaRouterUI* media_router_ui = static_cast<MediaRouterUI*>(
- media_router_dialog->GetWebUI()->GetController());
- DCHECK(media_router_ui);
-
- InitializeMediaRouterUI(media_router_ui);
-}
-
-WEB_CONTENTS_USER_DATA_KEY_IMPL(MediaRouterDialogControllerWebUIImpl)
-
-} // namespace media_router
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h
deleted file mode 100644
index da50fd97a82..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_WEBUI_IMPL_H_
-#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_WEBUI_IMPL_H_
-
-#include <memory>
-
-#include "base/gtest_prod_util.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "chrome/browser/ui/media_router/media_router_dialog_controller_impl_base.h"
-#include "content/public/browser/web_contents_observer.h"
-#include "content/public/browser/web_contents_user_data.h"
-
-FORWARD_DECLARE_TEST(MediaRouterActionUnitTest, IconPressedState);
-
-namespace media_router {
-
-// A WebUI implementation of MediaRouterDialogController.
-// This class is not thread safe and must be called on the UI thread.
-class MediaRouterDialogControllerWebUIImpl
- : public content::WebContentsUserData<MediaRouterDialogControllerWebUIImpl>,
- public MediaRouterDialogControllerImplBase {
- public:
- static MediaRouterDialogControllerWebUIImpl* GetOrCreateForWebContents(
- content::WebContents* web_contents);
- using content::WebContentsUserData<
- MediaRouterDialogControllerWebUIImpl>::FromWebContents;
-
- ~MediaRouterDialogControllerWebUIImpl() override;
-
- // Returns the media router dialog WebContents.
- // Returns nullptr if there is no dialog.
- content::WebContents* GetMediaRouterDialog() const;
-
- // MediaRouterDialogController:
- void CreateMediaRouterDialog() override;
- void CloseMediaRouterDialog() override;
- bool IsShowingMediaRouterDialog() const override;
- void Reset() override;
-
- void UpdateMaxDialogSize();
-
- private:
- class DialogWebContentsObserver;
- friend class content::WebContentsUserData<
- MediaRouterDialogControllerWebUIImpl>;
- FRIEND_TEST_ALL_PREFIXES(::MediaRouterActionUnitTest, IconPressedState);
-
- // Use MediaRouterDialogControllerWebUIImpl::CreateForWebContents() to create
- // an instance.
- explicit MediaRouterDialogControllerWebUIImpl(
- content::WebContents* web_contents);
-
- // Invoked when the dialog WebContents has navigated.
- void OnDialogNavigated(const content::LoadCommittedDetails& details);
-
- void PopulateDialog(content::WebContents* media_router_dialog);
-
- std::unique_ptr<DialogWebContentsObserver> dialog_observer_;
-
- // True if the controller is waiting for a new media router dialog to be
- // created.
- bool media_router_dialog_pending_;
-
- base::WeakPtrFactory<MediaRouterDialogControllerWebUIImpl> weak_ptr_factory_;
-
- WEB_CONTENTS_USER_DATA_KEY_DECL();
-
- DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogControllerWebUIImpl);
-};
-
-} // namespace media_router
-
-#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_DIALOG_CONTROLLER_WEBUI_IMPL_H_
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_browsertest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_browsertest.cc
deleted file mode 100644
index 85a1ce528d0..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_browsertest.cc
+++ /dev/null
@@ -1,142 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/macros.h"
-#include "chrome/browser/ui/browser_commands.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/tabs/tab_strip_model.h"
-#include "chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h"
-#include "chrome/browser/ui/webui/media_router/media_router_ui.h"
-#include "chrome/test/base/in_process_browser_test.h"
-#include "chrome/test/base/ui_test_utils.h"
-#include "content/public/common/url_constants.h"
-#include "content/public/test/browser_test_utils.h"
-#include "content/public/test/test_navigation_observer.h"
-
-using content::WebContents;
-using content::TestNavigationObserver;
-
-namespace media_router {
-
-class MediaRouterDialogControllerWebUIBrowserTest
- : public InProcessBrowserTest {
- public:
- MediaRouterDialogControllerWebUIBrowserTest()
- : dialog_controller_(nullptr),
- initiator_(nullptr),
- media_router_dialog_(nullptr) {}
- ~MediaRouterDialogControllerWebUIBrowserTest() override {}
-
- protected:
- void SetUpOnMainThread() override {
- // Start with one window with one tab.
- EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
- EXPECT_EQ(1, browser()->tab_strip_model()->count());
-
- initiator_ = browser()->tab_strip_model()->GetActiveWebContents();
- ASSERT_TRUE(initiator_);
- MediaRouterDialogControllerWebUIImpl::CreateForWebContents(initiator_);
- dialog_controller_ =
- MediaRouterDialogControllerWebUIImpl::FromWebContents(initiator_);
- ASSERT_TRUE(dialog_controller_);
-
- // Get the media router dialog for the initiator.
- dialog_controller_->ShowMediaRouterDialog();
- media_router_dialog_ = dialog_controller_->GetMediaRouterDialog();
- ASSERT_TRUE(media_router_dialog_);
- }
-
- MediaRouterDialogControllerWebUIImpl* dialog_controller_;
- WebContents* initiator_;
- WebContents* media_router_dialog_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogControllerWebUIBrowserTest);
-};
-
-IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerWebUIBrowserTest,
- ShowDialog) {
- // Waits for the dialog to initialize.
- TestNavigationObserver nav_observer(media_router_dialog_);
- nav_observer.Wait();
-
- // New media router dialog is a constrained window, so the number of
- // tabs is still 1.
- EXPECT_EQ(1, browser()->tab_strip_model()->count());
- EXPECT_NE(initiator_, media_router_dialog_);
- EXPECT_EQ(media_router_dialog_, dialog_controller_->GetMediaRouterDialog());
-
- content::WebUI* web_ui = media_router_dialog_->GetWebUI();
- ASSERT_TRUE(web_ui);
- MediaRouterUI* media_router_ui =
- static_cast<MediaRouterUI*>(web_ui->GetController());
- ASSERT_TRUE(media_router_ui);
-}
-
-IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerWebUIBrowserTest, Navigate) {
- {
- // Wait for the dialog to initialize.
- TestNavigationObserver nav_observer(media_router_dialog_);
- nav_observer.Wait();
- }
-
- // New media router dialog is a constrained window, so the number of
- // tabs is still 1.
- EXPECT_EQ(1, browser()->tab_strip_model()->count());
- EXPECT_EQ(media_router_dialog_, dialog_controller_->GetMediaRouterDialog());
-
- {
- // Navigate to another URL and block until the dialog WebContents has been
- // destroyed.
- content::WebContentsDestroyedWatcher dialog_watcher(media_router_dialog_);
- ui_test_utils::NavigateToURL(browser(), GURL("about:blank"));
- dialog_watcher.Wait();
- }
-
- // Verify that dialog has been removed.
- EXPECT_FALSE(dialog_controller_->GetMediaRouterDialog());
-
- // Open the dialog again.
- EXPECT_TRUE(dialog_controller_->ShowMediaRouterDialog());
- media_router_dialog_ = dialog_controller_->GetMediaRouterDialog();
- ASSERT_TRUE(media_router_dialog_);
-
- {
- // Wait for the dialog to initialize.
- TestNavigationObserver nav_observer(media_router_dialog_);
- nav_observer.Wait();
-
- // Refresh and block until dialog WebContents has been destroyed.
- content::WebContentsDestroyedWatcher dialog_watcher(media_router_dialog_);
- chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB);
- dialog_watcher.Wait();
- }
-
- // Verify that dialog has been removed again.
- EXPECT_FALSE(dialog_controller_->GetMediaRouterDialog());
-}
-
-IN_PROC_BROWSER_TEST_F(MediaRouterDialogControllerWebUIBrowserTest,
- RenderProcessHost) {
- // New media router dialog is a constrained window, so the number of
- // tabs is still 1.
- EXPECT_EQ(1, browser()->tab_strip_model()->count());
- EXPECT_EQ(media_router_dialog_, dialog_controller_->GetMediaRouterDialog());
-
- // Crash initiator_'s renderer process.
- content::WebContentsDestroyedWatcher dialog_watcher(media_router_dialog_);
- content::RenderProcessHostWatcher rph_watcher(
- initiator_, content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
-
- ui_test_utils::NavigateToURL(browser(), GURL(content::kChromeUICrashURL));
-
- // Blocks until the dialog WebContents has been destroyed.
- rph_watcher.Wait();
- dialog_watcher.Wait();
-
- // Entry has been removed.
- EXPECT_FALSE(dialog_controller_->GetMediaRouterDialog());
-}
-
-} // namespace media_router
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_unittest.cc
deleted file mode 100644
index 57907741c55..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl_unittest.cc
+++ /dev/null
@@ -1,278 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <vector>
-
-#include "base/bind.h"
-#include "base/macros.h"
-#include "chrome/browser/media/router/test/test_helper.h"
-#include "chrome/browser/ui/browser_commands.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/media_router/media_router_ui_service.h"
-#include "chrome/browser/ui/tabs/tab_strip_model.h"
-#include "chrome/browser/ui/toolbar/mock_media_router_action_controller.h"
-#include "chrome/browser/ui/webui/media_router/media_router_dialog_controller_webui_impl.h"
-#include "chrome/browser/ui/webui/media_router/media_router_ui.h"
-#include "chrome/browser/ui/webui/media_router/media_router_web_ui_test.h"
-#include "content/public/test/test_utils.h"
-#include "testing/gmock/include/gmock/gmock.h"
-
-using blink::mojom::PresentationInfo;
-using content::WebContents;
-
-namespace media_router {
-
-class MediaRouterDialogControllerWebUIImplTest : public MediaRouterWebUITest {
- public:
- MediaRouterDialogControllerWebUIImplTest() : MediaRouterWebUITest(true) {}
- ~MediaRouterDialogControllerWebUIImplTest() override {}
-
- void OpenMediaRouterDialog();
-
- MOCK_METHOD3(PresentationSuccessCallback,
- void(const blink::mojom::PresentationInfo&,
- mojom::RoutePresentationConnectionPtr,
- const MediaRoute&));
- MOCK_METHOD1(PresentationErrorCallback,
- void(const blink::mojom::PresentationError& error));
-
- protected:
- WebContents* initiator_ = nullptr;
- MediaRouterDialogControllerWebUIImpl* dialog_controller_ = nullptr;
- WebContents* media_router_dialog_ = nullptr;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(MediaRouterDialogControllerWebUIImplTest);
-};
-
-void MediaRouterDialogControllerWebUIImplTest::OpenMediaRouterDialog() {
- // Start with one window with one tab.
- EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
- EXPECT_EQ(0, browser()->tab_strip_model()->count());
- chrome::NewTab(browser());
- EXPECT_EQ(1, browser()->tab_strip_model()->count());
-
- // Create a reference to initiator contents.
- initiator_ = browser()->tab_strip_model()->GetActiveWebContents();
-
- dialog_controller_ =
- MediaRouterDialogControllerWebUIImpl::GetOrCreateForWebContents(
- initiator_);
- ASSERT_TRUE(dialog_controller_);
-
- // Get the media router dialog for the initiator.
- dialog_controller_->ShowMediaRouterDialog();
- media_router_dialog_ = dialog_controller_->GetMediaRouterDialog();
- ASSERT_TRUE(media_router_dialog_);
-
- // New media router dialog is a constrained window, so the number of
- // tabs is still 1.
- EXPECT_EQ(1, browser()->tab_strip_model()->count());
- EXPECT_NE(initiator_, media_router_dialog_);
- EXPECT_EQ(media_router_dialog_, dialog_controller_->GetMediaRouterDialog());
-}
-
-// Create/Get a media router dialog for initiator.
-TEST_F(MediaRouterDialogControllerWebUIImplTest, ShowMediaRouterDialog) {
- OpenMediaRouterDialog();
-
- // Show media router dialog for the same initiator again.
- dialog_controller_->ShowMediaRouterDialog();
- WebContents* same_media_router_dialog =
- dialog_controller_->GetMediaRouterDialog();
-
- // Tab count remains the same.
- EXPECT_EQ(1, browser()->tab_strip_model()->count());
-
- // Media router dialog already exists. Calling |ShowMediaRouterDialog| again
- // should not have created a new media router dialog.
- EXPECT_EQ(media_router_dialog_, same_media_router_dialog);
-}
-
-// Tests multiple media router dialogs exist in the same browser for different
-// initiators. If a dialog already exists for an initiator, that initiator
-// gets focused.
-TEST_F(MediaRouterDialogControllerWebUIImplTest, MultipleMediaRouterDialogs) {
- // Let's start with one window and two tabs.
- EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
- TabStripModel* tab_strip_model = browser()->tab_strip_model();
- ASSERT_TRUE(tab_strip_model);
-
- EXPECT_EQ(0, tab_strip_model->count());
-
- // Create some new initiators.
- chrome::NewTab(browser());
- WebContents* web_contents_1 = tab_strip_model->GetActiveWebContents();
- ASSERT_TRUE(web_contents_1);
-
- chrome::NewTab(browser());
- WebContents* web_contents_2 = tab_strip_model->GetActiveWebContents();
- ASSERT_TRUE(web_contents_2);
- EXPECT_EQ(2, tab_strip_model->count());
-
- // Create media router dialog for |web_contents_1|.
- MediaRouterDialogControllerWebUIImpl* dialog_controller_1 =
- MediaRouterDialogControllerWebUIImpl::GetOrCreateForWebContents(
- web_contents_1);
- ASSERT_TRUE(dialog_controller_1);
-
- dialog_controller_1->ShowMediaRouterDialog();
- WebContents* media_router_dialog_1 =
- dialog_controller_1->GetMediaRouterDialog();
-
- ASSERT_TRUE(media_router_dialog_1);
-
- EXPECT_NE(web_contents_1, media_router_dialog_1);
- EXPECT_EQ(2, tab_strip_model->count());
-
- // Create media router dialog for |web_contents_2|.
- MediaRouterDialogControllerWebUIImpl* dialog_controller_2 =
- MediaRouterDialogControllerWebUIImpl::GetOrCreateForWebContents(
- web_contents_2);
- ASSERT_TRUE(dialog_controller_2);
-
- dialog_controller_2->ShowMediaRouterDialog();
- WebContents* media_router_dialog_2 =
- dialog_controller_2->GetMediaRouterDialog();
- ASSERT_TRUE(media_router_dialog_2);
-
- EXPECT_NE(web_contents_2, media_router_dialog_2);
- EXPECT_NE(media_router_dialog_1, media_router_dialog_2);
-
- // 2 initiators and 2 dialogs exist in the same browser. The dialogs are
- // constrained in their respective initiators.
- EXPECT_EQ(2, tab_strip_model->count());
-
- int tab_1_index = tab_strip_model->GetIndexOfWebContents(web_contents_1);
- int tab_2_index = tab_strip_model->GetIndexOfWebContents(web_contents_2);
- int media_router_dialog_1_index =
- tab_strip_model->GetIndexOfWebContents(media_router_dialog_1);
- int media_router_dialog_2_index =
- tab_strip_model->GetIndexOfWebContents(media_router_dialog_2);
-
- // Constrained dialogs are not in the TabStripModel.
- EXPECT_EQ(-1, media_router_dialog_1_index);
- EXPECT_EQ(-1, media_router_dialog_2_index);
-
- // Since |media_router_dialog_2_index| was the most recently created dialog,
- // its initiator should have focus.
- EXPECT_EQ(tab_2_index, tab_strip_model->active_index());
-
- // When we get the media router dialog for |web_contents_1|,
- // |media_router_dialog_1| is activated and focused.
- dialog_controller_1->ShowMediaRouterDialog();
- EXPECT_EQ(tab_1_index, tab_strip_model->active_index());
-
- // When we get the media router dialog for |web_contents_2|,
- // |media_router_dialog_2| is activated and focused.
- dialog_controller_2->ShowMediaRouterDialog();
- EXPECT_EQ(tab_2_index, tab_strip_model->active_index());
-}
-
-TEST_F(MediaRouterDialogControllerWebUIImplTest, CloseDialogFromWebUI) {
- OpenMediaRouterDialog();
-
- // Close the dialog.
- content::WebContentsDestroyedWatcher watcher(media_router_dialog_);
-
- content::WebUI* web_ui = media_router_dialog_->GetWebUI();
- ASSERT_TRUE(web_ui);
- MediaRouterUI* media_router_ui =
- static_cast<MediaRouterUI*>(web_ui->GetController());
- ASSERT_TRUE(media_router_ui);
- media_router_ui->Close();
-
- // Blocks until the media router dialog WebContents has been destroyed.
- watcher.Wait();
-
- // Still 1 tab in the browser.
- EXPECT_EQ(1, browser()->tab_strip_model()->count());
-
- // Entry has been removed.
- EXPECT_FALSE(dialog_controller_->GetMediaRouterDialog());
-
- // Show the media router dialog again, creating a new one.
- dialog_controller_->ShowMediaRouterDialog();
- WebContents* media_router_dialog_2 =
- dialog_controller_->GetMediaRouterDialog();
-
- // Still 1 tab in the browser.
- EXPECT_EQ(1, browser()->tab_strip_model()->count());
-
- EXPECT_EQ(media_router_dialog_2, dialog_controller_->GetMediaRouterDialog());
-}
-
-TEST_F(MediaRouterDialogControllerWebUIImplTest,
- CloseDialogFromDialogController) {
- OpenMediaRouterDialog();
-
- // Close the dialog.
- content::WebContentsDestroyedWatcher watcher(media_router_dialog_);
-
- dialog_controller_->HideMediaRouterDialog();
-
- // Blocks until the media router dialog WebContents has been destroyed.
- watcher.Wait();
-
- // Still 1 tab in the browser.
- EXPECT_EQ(1, browser()->tab_strip_model()->count());
-
- // Entry has been removed.
- EXPECT_FALSE(dialog_controller_->GetMediaRouterDialog());
-}
-
-TEST_F(MediaRouterDialogControllerWebUIImplTest, CloseInitiator) {
- OpenMediaRouterDialog();
-
- // Close the initiator. This should also close the dialog WebContents.
- content::WebContentsDestroyedWatcher initiator_watcher(initiator_);
- content::WebContentsDestroyedWatcher dialog_watcher(media_router_dialog_);
-
- int initiator_index =
- browser()->tab_strip_model()->GetIndexOfWebContents(initiator_);
- EXPECT_NE(-1, initiator_index);
- EXPECT_TRUE(browser()->tab_strip_model()->CloseWebContentsAt(
- initiator_index, TabStripModel::CLOSE_NONE));
-
- // Blocks until the initiator WebContents has been destroyed.
- initiator_watcher.Wait();
- dialog_watcher.Wait();
-
- // No tabs in the browser.
- EXPECT_EQ(0, browser()->tab_strip_model()->count());
-
- // The dialog controller is deleted when the WebContents is closed/destroyed.
-}
-
-TEST_F(MediaRouterDialogControllerWebUIImplTest, NotifyActionController) {
- MockMediaRouterActionController* action_controller =
- static_cast<MockMediaRouterActionController*>(
- MediaRouterUIService::Get(browser()->profile())->action_controller());
- ASSERT_TRUE(action_controller);
-
- EXPECT_CALL(*action_controller, OnDialogShown());
- OpenMediaRouterDialog();
- EXPECT_CALL(*action_controller, OnDialogHidden());
- dialog_controller_->HideMediaRouterDialog();
-
- EXPECT_CALL(*action_controller, OnDialogShown());
- EXPECT_TRUE(dialog_controller_->ShowMediaRouterDialogForPresentation(
- std::make_unique<StartPresentationContext>(
- content::PresentationRequest(
- {1, 2}, {GURL("http://test.com"), GURL("http://test2.com")},
- url::Origin::Create(GURL("http://example.com"))),
- base::BindOnce(&MediaRouterDialogControllerWebUIImplTest::
- PresentationSuccessCallback,
- base::Unretained(this)),
- base::BindOnce(&MediaRouterDialogControllerWebUIImplTest::
- PresentationErrorCallback,
- base::Unretained(this)))));
-
- // When |dialog_controller_| is destroyed with its dialog open,
- // |action_controller| should be notified.
- EXPECT_CALL(*action_controller, OnDialogHidden());
- EXPECT_CALL(*this, PresentationErrorCallback(testing::_));
-}
-
-} // namespace media_router
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_internals_ui.h b/chromium/chrome/browser/ui/webui/media_router/media_router_internals_ui.h
index 40cf3f15915..65dd590d7ee 100644
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_internals_ui.h
+++ b/chromium/chrome/browser/ui/webui/media_router/media_router_internals_ui.h
@@ -12,7 +12,7 @@
namespace media_router {
-// Implements the chrome://media-router user interface.
+// Implements the chrome://media-router-internals/ user interface.
class MediaRouterInternalsUI : public content::WebUIController {
public:
// |web_ui| owns this object and is used to initialize the base class.
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.cc
deleted file mode 100644
index ab626b1cf44..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.cc
+++ /dev/null
@@ -1,109 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.h"
-
-#include "base/stl_util.h"
-#include "chrome/browser/ui/webui/localized_string.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/strings/grit/components_strings.h"
-#include "content/public/browser/web_ui_data_source.h"
-
-namespace {
-
-// Note that media_router.html contains a <script> tag which imports a script
-// of the following name. These names must be kept in sync.
-const char kLocalizedStringsFile[] = "strings.js";
-
-void AddMediaRouterStrings(content::WebUIDataSource* html_source) {
- static constexpr LocalizedString kLocalizedStrings[] = {
- {"mediaRouterTitle", IDS_MEDIA_ROUTER_TITLE},
- {"learnMoreText", IDS_LEARN_MORE},
- {"backButtonTitle", IDS_MEDIA_ROUTER_BACK_BUTTON_TITLE},
- {"closeButtonTitle", IDS_MEDIA_ROUTER_CLOSE_BUTTON_TITLE},
- {"searchButtonTitle", IDS_MEDIA_ROUTER_SEARCH_BUTTON_TITLE},
- {"viewCastModeListButtonTitle",
- IDS_MEDIA_ROUTER_VIEW_CAST_MODE_LIST_BUTTON_TITLE},
- {"viewDeviceListButtonTitle",
- IDS_MEDIA_ROUTER_VIEW_DEVICE_LIST_BUTTON_TITLE},
- };
- AddLocalizedStringsBulk(html_source, kLocalizedStrings,
- base::size(kLocalizedStrings));
-}
-
-void AddRouteDetailsStrings(content::WebUIDataSource* html_source) {
- static constexpr LocalizedString kLocalizedStrings[] = {
- {"castingActivityStatus", IDS_MEDIA_ROUTER_CASTING_ACTIVITY_STATUS},
- {"stopCastingButtonText", IDS_MEDIA_ROUTER_STOP_CASTING_BUTTON},
- {"startCastingButtonText", IDS_MEDIA_ROUTER_START_CASTING_BUTTON},
- {"playTitle", IDS_MEDIA_ROUTER_ROUTE_DETAILS_PLAY_TITLE},
- {"pauseTitle", IDS_MEDIA_ROUTER_ROUTE_DETAILS_PAUSE_TITLE},
- {"muteTitle", IDS_MEDIA_ROUTER_ROUTE_DETAILS_MUTE_TITLE},
- {"unmuteTitle", IDS_MEDIA_ROUTER_ROUTE_DETAILS_UNMUTE_TITLE},
- {"seekTitle", IDS_MEDIA_ROUTER_ROUTE_DETAILS_SEEK_TITLE},
- {"volumeTitle", IDS_MEDIA_ROUTER_ROUTE_DETAILS_VOLUME_TITLE},
- {"currentTimeLabel", IDS_MEDIA_ROUTER_ROUTE_DETAILS_CURRENT_TIME_LABEL},
- {"durationLabel", IDS_MEDIA_ROUTER_ROUTE_DETAILS_DURATION_LABEL},
- {"hangoutsLocalPresentTitle",
- IDS_MEDIA_ROUTER_ROUTE_DETAILS_HANGOUTS_LOCAL_PRESENT_TITLE},
- {"hangoutsLocalPresentSubtitle",
- IDS_MEDIA_ROUTER_ROUTE_DETAILS_HANGOUTS_LOCAL_PRESENT_SUBTITLE},
- {"alwaysUseMirroringTitle",
- IDS_MEDIA_ROUTER_ROUTE_DETAILS_ALWAYS_USE_MIRRORING_TITLE},
- {"fullscreenVideosDropdownTitle",
- IDS_MEDIA_ROUTER_ROUTE_DETAILS_FULLSCREEN_VIDEOS_DROPDOWN_TITLE},
- {"fullscreenVideosRemoteScreen",
- IDS_MEDIA_ROUTER_ROUTE_DETAILS_FULLSCREEN_VIDEOS_REMOTE_SCREEN},
- {"fullscreenVideosBothScreens",
- IDS_MEDIA_ROUTER_ROUTE_DETAILS_FULLSCREEN_VIDEOS_BOTH_SCREENS},
- };
- AddLocalizedStringsBulk(html_source, kLocalizedStrings,
- base::size(kLocalizedStrings));
-}
-
-void AddIssuesStrings(content::WebUIDataSource* html_source) {
- static constexpr LocalizedString kLocalizedStrings[] = {
- {"dismissButton", IDS_MEDIA_ROUTER_DISMISS_BUTTON},
- {"issueHeaderText", IDS_MEDIA_ROUTER_ISSUE_HEADER},
- };
- AddLocalizedStringsBulk(html_source, kLocalizedStrings,
- base::size(kLocalizedStrings));
-}
-
-void AddMediaRouterContainerStrings(content::WebUIDataSource* html_source) {
- static constexpr LocalizedString kLocalizedStrings[] = {
- {"castLocalMediaSubheadingText",
- IDS_MEDIA_ROUTER_CAST_LOCAL_MEDIA_SUBHEADING},
- {"castLocalMediaSelectedFileTitle",
- IDS_MEDIA_ROUTER_CAST_LOCAL_MEDIA_TITLE},
- {"firstRunFlowButtonText", IDS_MEDIA_ROUTER_FIRST_RUN_FLOW_BUTTON},
- {"firstRunFlowText", IDS_MEDIA_ROUTER_FIRST_RUN_FLOW_TEXT},
- {"firstRunFlowTitle", IDS_MEDIA_ROUTER_FIRST_RUN_FLOW_TITLE},
- {"firstRunFlowCloudPrefText",
- IDS_MEDIA_ROUTER_FIRST_RUN_FLOW_CLOUD_PREF_TEXT},
- {"autoCastMode", IDS_MEDIA_ROUTER_AUTO_CAST_MODE},
- {"destinationMissingText", IDS_MEDIA_ROUTER_DESTINATION_MISSING},
- {"searchInputLabel", IDS_MEDIA_ROUTER_SEARCH_LABEL},
- {"searchNoMatchesText", IDS_MEDIA_ROUTER_SEARCH_NO_MATCHES},
- {"selectCastModeHeaderText", IDS_MEDIA_ROUTER_SELECT_CAST_MODE_HEADER},
- {"shareYourScreenSubheadingText",
- IDS_MEDIA_ROUTER_SHARE_YOUR_SCREEN_SUBHEADING},
- };
- AddLocalizedStringsBulk(html_source, kLocalizedStrings,
- base::size(kLocalizedStrings));
-}
-
-} // namespace
-
-namespace media_router {
-
-void AddLocalizedStrings(content::WebUIDataSource* html_source) {
- AddMediaRouterStrings(html_source);
- AddRouteDetailsStrings(html_source);
- AddIssuesStrings(html_source);
- AddMediaRouterContainerStrings(html_source);
- html_source->SetJsonPath(kLocalizedStringsFile);
-}
-
-} // namespace media_router
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.h b/chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.h
deleted file mode 100644
index e700a0ed6e3..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.h
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_LOCALIZED_STRINGS_PROVIDER_H_
-#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_LOCALIZED_STRINGS_PROVIDER_H_
-
-namespace content {
-class WebUIDataSource;
-}
-
-namespace media_router {
-
-// Adds the strings needed by Media Router to |html_source|. This function
-// causes |html_source| to expose a strings.js file from its source which
-// contains a mapping from string's name to its translated value.
-void AddLocalizedStrings(content::WebUIDataSource* html_source);
-
-} // namespace media_router
-
-#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_LOCALIZED_STRINGS_PROVIDER_H_
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_resources_provider.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_resources_provider.cc
deleted file mode 100644
index bd29d2360c1..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_resources_provider.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/media_router/media_router_resources_provider.h"
-
-#include "chrome/grit/browser_resources.h"
-#include "content/public/browser/web_ui_data_source.h"
-
-namespace {
-
-void AddMainWebResources(content::WebUIDataSource* html_source) {
- html_source->AddResourcePath("media_router.js", IDR_MEDIA_ROUTER_JS);
- html_source->AddResourcePath("media_router_common.css",
- IDR_MEDIA_ROUTER_COMMON_CSS);
- html_source->AddResourcePath("media_router.css",
- IDR_MEDIA_ROUTER_CSS);
- html_source->AddResourcePath("media_router_data.js",
- IDR_MEDIA_ROUTER_DATA_JS);
- html_source->AddResourcePath("media_router_ui_interface.js",
- IDR_MEDIA_ROUTER_UI_INTERFACE_JS);
-}
-
-void AddPolymerElements(content::WebUIDataSource* html_source) {
- html_source->AddResourcePath(
- "icons/media_router_icons.html",
- IDR_MEDIA_ROUTER_ICONS_HTML);
- html_source->AddResourcePath(
- "elements/issue_banner/issue_banner.css",
- IDR_ISSUE_BANNER_CSS);
- html_source->AddResourcePath(
- "elements/issue_banner/issue_banner.html",
- IDR_ISSUE_BANNER_HTML);
- html_source->AddResourcePath(
- "elements/issue_banner/issue_banner.js",
- IDR_ISSUE_BANNER_JS);
- html_source->AddResourcePath(
- "elements/media_router_container/media_router_container.css",
- IDR_MEDIA_ROUTER_CONTAINER_CSS);
- html_source->AddResourcePath(
- "elements/media_router_container/media_router_container.html",
- IDR_MEDIA_ROUTER_CONTAINER_HTML);
- html_source->AddResourcePath(
- "elements/media_router_container/media_router_container.js",
- IDR_MEDIA_ROUTER_CONTAINER_JS);
- html_source->AddResourcePath(
- "elements/media_router_header/media_router_header.css",
- IDR_MEDIA_ROUTER_HEADER_CSS);
- html_source->AddResourcePath(
- "elements/media_router_header/media_router_header.html",
- IDR_MEDIA_ROUTER_HEADER_HTML);
- html_source->AddResourcePath(
- "elements/media_router_header/media_router_header.js",
- IDR_MEDIA_ROUTER_HEADER_JS);
- html_source->AddResourcePath(
- "elements/media_router_search_highlighter/"
- "media_router_search_highlighter.css",
- IDR_MEDIA_ROUTER_SEARCH_HIGHLIGHTER_CSS);
- html_source->AddResourcePath(
- "elements/media_router_search_highlighter/"
- "media_router_search_highlighter.html",
- IDR_MEDIA_ROUTER_SEARCH_HIGHLIGHTER_HTML);
- html_source->AddResourcePath(
- "elements/media_router_search_highlighter/"
- "media_router_search_highlighter.js",
- IDR_MEDIA_ROUTER_SEARCH_HIGHLIGHTER_JS);
- html_source->AddResourcePath("elements/route_controls/route_controls.css",
- IDR_ROUTE_CONTROLS_CSS);
- html_source->AddResourcePath("elements/route_controls/route_controls.html",
- IDR_ROUTE_CONTROLS_HTML);
- html_source->AddResourcePath("elements/route_controls/route_controls.js",
- IDR_ROUTE_CONTROLS_JS);
- html_source->AddResourcePath("elements/route_details/route_details.css",
- IDR_ROUTE_DETAILS_CSS);
- html_source->AddResourcePath(
- "elements/route_details/route_details.html",
- IDR_ROUTE_DETAILS_HTML);
- html_source->AddResourcePath(
- "elements/route_details/route_details.js",
- IDR_ROUTE_DETAILS_JS);
- html_source->AddResourcePath(
- "elements/media_router_container/pseudo_sink_search_state.js",
- IDR_PSEUDO_SINK_SEARCH_STATE_JS);
-}
-
-} // namespace
-
-namespace media_router {
-
-void AddMediaRouterUIResources(content::WebUIDataSource* html_source) {
- AddMainWebResources(html_source);
- AddPolymerElements(html_source);
- html_source->SetDefaultResource(IDR_MEDIA_ROUTER_HTML);
-}
-
-} // namespace media_router
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_resources_provider.h b/chromium/chrome/browser/ui/webui/media_router/media_router_resources_provider.h
deleted file mode 100644
index 1c62084f4c4..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_resources_provider.h
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_RESOURCES_PROVIDER_H_
-#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_RESOURCES_PROVIDER_H_
-
-namespace content {
-class WebUIDataSource;
-}
-
-namespace media_router {
-
-// Adds the resources needed by Media Router to |html_source|.
-void AddMediaRouterUIResources(content::WebUIDataSource* html_source);
-
-} // namespace media_router
-
-#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_RESOURCES_PROVIDER_H_
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc
deleted file mode 100644
index 11d65b67de4..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.cc
+++ /dev/null
@@ -1,411 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/media_router/media_router_ui.h"
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/guid.h"
-#include "base/macros.h"
-#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/trace_event/trace_event.h"
-#include "build/build_config.h"
-#include "chrome/browser/media/router/issue_manager.h"
-#include "chrome/browser/media/router/media_router.h"
-#include "chrome/browser/media/router/media_router_factory.h"
-#include "chrome/browser/media/router/media_router_metrics.h"
-#include "chrome/browser/media/router/media_sinks_observer.h"
-#include "chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/sessions/session_tab_helper.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/browser_navigator.h"
-#include "chrome/browser/ui/browser_navigator_params.h"
-#include "chrome/browser/ui/browser_tabstrip.h"
-#include "chrome/browser/ui/media_router/media_router_ui_helper.h"
-#include "chrome/browser/ui/webui/media_router/media_router_localized_strings_provider.h"
-#include "chrome/browser/ui/webui/media_router/media_router_resources_provider.h"
-#include "chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h"
-#include "chrome/common/chrome_features.h"
-#include "chrome/common/media_router/issue.h"
-#include "chrome/common/media_router/media_route.h"
-#include "chrome/common/media_router/media_sink.h"
-#include "chrome/common/media_router/media_source.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/prefs/pref_service.h"
-#include "components/prefs/scoped_user_pref_update.h"
-#include "content/public/browser/navigation_handle.h"
-#include "content/public/browser/render_frame_host.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/browser/web_ui.h"
-#include "content/public/browser/web_ui_data_source.h"
-#include "content/public/common/fullscreen_video_element.mojom.h"
-#include "extensions/browser/extension_registry.h"
-#include "extensions/common/constants.h"
-#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
-#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/display/display.h"
-#include "ui/web_dialogs/web_dialog_delegate.h"
-#include "url/origin.h"
-
-namespace media_router {
-
-MediaRouterUI::MediaRouterUI(content::WebUI* web_ui)
- : ConstrainedWebDialogUI(web_ui), weak_factory_(this) {
- auto handler = std::make_unique<MediaRouterWebUIMessageHandler>(this);
- handler_ = handler.get();
-
- // Create a WebUIDataSource containing the chrome://media-router page's
- // content.
- std::unique_ptr<content::WebUIDataSource> html_source(
- content::WebUIDataSource::Create(chrome::kChromeUIMediaRouterHost));
-
- AddLocalizedStrings(html_source.get());
- AddMediaRouterUIResources(html_source.get());
- // Ownership of |html_source| is transferred to the BrowserContext.
- content::WebUIDataSource::Add(Profile::FromWebUI(web_ui),
- html_source.release());
-
- web_ui->AddMessageHandler(std::move(handler));
-}
-
-MediaRouterUI::~MediaRouterUI() = default;
-
-void MediaRouterUI::Close() {
- ConstrainedWebDialogDelegate* delegate = GetConstrainedDelegate();
- if (delegate) {
- delegate->GetWebDialogDelegate()->OnDialogClosed(std::string());
- delegate->OnDialogCloseFromWebUI();
- }
-}
-
-void MediaRouterUI::OnUIInitialized() {
- TRACE_EVENT_NESTABLE_ASYNC_END0("media_router", "UI", initiator());
-
- ui_initialized_ = true;
-
- // TODO(imcheng): We should be able to instantiate |issue_observer_| during
- // InitCommon by storing an initial Issue in this class.
- // Register for Issue updates.
- StartObservingIssues();
-}
-
-bool MediaRouterUI::ConnectRoute(const MediaSink::Id& sink_id,
- const MediaRoute::Id& route_id) {
- base::Optional<RouteParameters> params =
- GetRouteParameters(sink_id, MediaCastMode::PRESENTATION);
- if (!params) {
- SendIssueForUnableToCast(MediaCastMode::PRESENTATION, sink_id);
- return false;
- }
- GetIssueManager()->ClearNonBlockingIssues();
- GetMediaRouter()->ConnectRouteByRouteId(
- params->source_id, route_id, params->origin, initiator(),
- base::BindOnce(&MediaRouterUIBase::RunRouteResponseCallbacks,
- std::move(params->presentation_callback),
- std::move(params->route_result_callbacks)),
- params->timeout, params->incognito);
- return true;
-}
-
-void MediaRouterUI::SearchSinksAndCreateRoute(
- const MediaSink::Id& sink_id,
- const std::string& search_criteria,
- const std::string& domain,
- MediaCastMode cast_mode) {
- std::unique_ptr<MediaSource> source =
- query_result_manager()->GetSourceForCastModeAndSink(cast_mode, sink_id);
- const std::string source_id = source ? source->id() : "";
-
- // The CreateRoute() part of the function is accomplished in the callback
- // OnSearchSinkResponseReceived().
- GetMediaRouter()->SearchSinks(
- sink_id, source_id, search_criteria, domain,
- base::BindRepeating(&MediaRouterUI::OnSearchSinkResponseReceived,
- weak_factory_.GetWeakPtr(), cast_mode));
-}
-
-bool MediaRouterUI::UserSelectedTabMirroringForCurrentOrigin() const {
- const base::ListValue* origins =
- Profile::FromWebUI(web_ui())->GetPrefs()->GetList(
- ::prefs::kMediaRouterTabMirroringSources);
- return origins->Find(base::Value(GetSerializedInitiatorOrigin())) !=
- origins->end();
-}
-
-void MediaRouterUI::RecordCastModeSelection(MediaCastMode cast_mode) {
- ListPrefUpdate update(Profile::FromWebUI(web_ui())->GetPrefs(),
- ::prefs::kMediaRouterTabMirroringSources);
-
- switch (cast_mode) {
- case MediaCastMode::PRESENTATION:
- update->Remove(base::Value(GetSerializedInitiatorOrigin()), nullptr);
- break;
- case MediaCastMode::TAB_MIRROR:
- update->AppendIfNotPresent(
- std::make_unique<base::Value>(GetSerializedInitiatorOrigin()));
- break;
- case MediaCastMode::DESKTOP_MIRROR:
- // Desktop mirroring isn't domain-specific, so we don't record the
- // selection.
- break;
- case MediaCastMode::LOCAL_FILE:
- // Local media isn't domain-specific, so we don't record the selection.
- break;
- default:
- NOTREACHED();
- break;
- }
-}
-
-std::string MediaRouterUI::GetPresentationRequestSourceName() const {
- GURL gurl = GetFrameURL();
- return gurl.SchemeIs(extensions::kExtensionScheme)
- ? GetExtensionName(gurl, extensions::ExtensionRegistry::Get(
- Profile::FromWebUI(web_ui())))
- : GetHostFromURL(gurl);
-}
-
-const std::set<MediaCastMode>& MediaRouterUI::GetCastModes() const {
- return cast_modes_;
-}
-
-void MediaRouterUI::SetUIInitializationTimer(const base::Time& start_time) {
- DCHECK(!start_time.is_null());
- start_time_ = start_time;
-}
-
-void MediaRouterUI::OnUIInitiallyLoaded() {
- if (!start_time_.is_null()) {
- MediaRouterMetrics::RecordMediaRouterDialogPaint(base::Time::Now() -
- start_time_);
- }
-}
-
-void MediaRouterUI::OnUIInitialDataReceived() {
- if (!start_time_.is_null()) {
- MediaRouterMetrics::RecordMediaRouterDialogLoaded(base::Time::Now() -
- start_time_);
- start_time_ = base::Time();
- }
-}
-
-void MediaRouterUI::UpdateMaxDialogHeight(int height) {
- if (ui_initialized_) {
- handler_->UpdateMaxDialogHeight(height);
- }
-}
-
-MediaRouteController* MediaRouterUI::GetMediaRouteController() const {
- return route_controller_observer_
- ? route_controller_observer_->controller().get()
- : nullptr;
-}
-
-void MediaRouterUI::OnMediaControllerUIAvailable(
- const MediaRoute::Id& route_id) {
- scoped_refptr<MediaRouteController> controller =
- GetMediaRouter()->GetRouteController(route_id);
- if (!controller) {
- DVLOG(1) << "Requested a route controller with an invalid route ID.";
- return;
- }
- DVLOG_IF(1, route_controller_observer_)
- << "Route controller observer unexpectedly exists.";
- route_controller_observer_ =
- std::make_unique<UIMediaRouteControllerObserver>(this, controller);
-}
-
-void MediaRouterUI::OnMediaControllerUIClosed() {
- route_controller_observer_.reset();
-}
-
-void MediaRouterUI::InitForTest(
- MediaRouter* router,
- content::WebContents* initiator,
- MediaRouterWebUIMessageHandler* handler,
- std::unique_ptr<StartPresentationContext> context,
- std::unique_ptr<MediaRouterFileDialog> file_dialog) {
- handler_ = handler;
- set_start_presentation_context_for_test(std::move(context));
- InitForTest(std::move(file_dialog));
- InitCommon(initiator);
- if (start_presentation_context()) {
- OnDefaultPresentationChanged(
- start_presentation_context()->presentation_request());
- }
-
- OnUIInitialized();
-}
-
-void MediaRouterUI::InitForTest(
- std::unique_ptr<MediaRouterFileDialog> file_dialog) {
- set_media_router_file_dialog_for_test(std::move(file_dialog));
-}
-
-MediaRouterUI::UIMediaRouteControllerObserver::UIMediaRouteControllerObserver(
- MediaRouterUI* ui,
- scoped_refptr<MediaRouteController> controller)
- : MediaRouteController::Observer(std::move(controller)), ui_(ui) {
- if (controller_->current_media_status())
- OnMediaStatusUpdated(controller_->current_media_status().value());
-}
-
-MediaRouterUI::UIMediaRouteControllerObserver::
- ~UIMediaRouteControllerObserver() {}
-
-void MediaRouterUI::UIMediaRouteControllerObserver::OnMediaStatusUpdated(
- const MediaStatus& status) {
- ui_->UpdateMediaRouteStatus(status);
-}
-
-void MediaRouterUI::UIMediaRouteControllerObserver::OnControllerInvalidated() {
- ui_->OnRouteControllerInvalidated();
-}
-
-void MediaRouterUI::FileDialogFileSelected(
- const ui::SelectedFileInfo& file_info) {
- handler_->UserSelectedLocalMediaFile(file_info.display_name);
-}
-
-void MediaRouterUI::OnIssue(const Issue& issue) {
- if (ui_initialized_)
- handler_->UpdateIssue(issue);
-}
-
-void MediaRouterUI::OnIssueCleared() {
- if (ui_initialized_)
- handler_->ClearIssue();
-}
-
-void MediaRouterUI::OnRoutesUpdated(
- const std::vector<MediaRoute>& routes,
- const std::vector<MediaRoute::Id>& joinable_route_ids) {
- MediaRouterUIBase::OnRoutesUpdated(routes, joinable_route_ids);
- joinable_route_ids_.clear();
-
- for (const MediaRoute& route : routes) {
- if (route.for_display() &&
- base::ContainsValue(joinable_route_ids, route.media_route_id())) {
- joinable_route_ids_.push_back(route.media_route_id());
- }
- }
-
- if (ui_initialized_) {
- handler_->UpdateRoutes(MediaRouterUIBase::routes(), joinable_route_ids_,
- routes_and_cast_modes());
- }
- UpdateRoutesToCastModesMapping();
-}
-
-void MediaRouterUI::OnRouteResponseReceived(
- int route_request_id,
- const MediaSink::Id& sink_id,
- MediaCastMode cast_mode,
- const base::string16& presentation_request_source_name,
- const RouteRequestResult& result) {
- MediaRouterUIBase::OnRouteResponseReceived(
- route_request_id, sink_id, cast_mode, presentation_request_source_name,
- result);
- handler_->OnCreateRouteResponseReceived(sink_id, result.route());
-}
-
-void MediaRouterUI::HandleCreateSessionRequestRouteResponse(
- const RouteRequestResult&) {
- Close();
-}
-
-void MediaRouterUI::OnSearchSinkResponseReceived(
- MediaCastMode cast_mode,
- const MediaSink::Id& found_sink_id) {
- DVLOG(1) << "OnSearchSinkResponseReceived";
- handler_->ReturnSearchResult(found_sink_id);
-
- CreateRoute(found_sink_id, cast_mode);
- MediaRouterMetrics::RecordSearchSinkOutcome(!found_sink_id.empty());
-}
-
-void MediaRouterUI::InitCommon(content::WebContents* initiator) {
- MediaRouterUIBase::InitCommon(initiator);
- UpdateCastModes();
- // Presentation requests from content must show the origin requesting
- // presentation: crbug.com/704964
- if (start_presentation_context())
- forced_cast_mode_ = MediaCastMode::PRESENTATION;
-}
-
-void MediaRouterUI::OnDefaultPresentationChanged(
- const content::PresentationRequest& presentation_request) {
- MediaRouterUIBase::OnDefaultPresentationChanged(presentation_request);
- UpdateCastModes();
-}
-
-void MediaRouterUI::OnDefaultPresentationRemoved() {
- MediaRouterUIBase::OnDefaultPresentationRemoved();
-
- // This should not be set if the dialog was initiated with a default
- // presentation request from the top level frame. However, clear it just to
- // be safe.
- forced_cast_mode_ = base::nullopt;
- UpdateCastModes();
-}
-
-void MediaRouterUI::UpdateCastModes() {
- // Gets updated cast modes from |query_result_manager()| and forwards it to
- // UI.
- cast_modes_ = query_result_manager()->GetSupportedCastModes();
- if (ui_initialized_) {
- handler_->UpdateCastModes(
- GetCastModes(), GetPresentationRequestSourceName(), forced_cast_mode());
- }
-}
-
-void MediaRouterUI::UpdateRoutesToCastModesMapping() {
- std::unordered_map<MediaSource::Id, MediaCastMode> available_source_map;
- for (const auto& cast_mode : GetCastModes()) {
- for (const auto& source : GetSourcesForCastMode(cast_mode))
- available_source_map.insert(std::make_pair(source.id(), cast_mode));
- }
-
- routes_and_cast_modes_.clear();
- for (const auto& route : routes()) {
- auto source_entry = available_source_map.find(route.media_source().id());
- if (source_entry != available_source_map.end()) {
- routes_and_cast_modes_.insert(
- std::make_pair(route.media_route_id(), source_entry->second));
- }
- }
-}
-
-std::string MediaRouterUI::GetSerializedInitiatorOrigin() const {
- url::Origin origin =
- initiator() ? url::Origin::Create(initiator()->GetLastCommittedURL())
- : url::Origin();
- return origin.Serialize();
-}
-
-void MediaRouterUI::OnRouteControllerInvalidated() {
- route_controller_observer_.reset();
- handler_->OnRouteControllerInvalidated();
-}
-void MediaRouterUI::UpdateMediaRouteStatus(const MediaStatus& status) {
- handler_->UpdateMediaRouteStatus(status);
-}
-
-void MediaRouterUI::UpdateSinks() {
- if (ui_initialized_)
- handler_->UpdateSinks(GetEnabledSinks());
-}
-
-MediaRouter* MediaRouterUI::GetMediaRouter() const {
- return MediaRouterFactory::GetApiForBrowserContext(
- web_ui()->GetWebContents()->GetBrowserContext());
-}
-
-} // namespace media_router
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
deleted file mode 100644
index 531fdf243f2..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui.h
+++ /dev/null
@@ -1,237 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_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"
-#include "chrome/browser/ui/media_router/media_cast_mode.h"
-#include "chrome/browser/ui/media_router/media_router_ui_base.h"
-#include "chrome/browser/ui/webui/constrained_web_dialog_ui.h"
-#include "chrome/common/media_router/media_route.h"
-#include "chrome/common/media_router/media_sink.h"
-
-namespace media_router {
-
-struct MediaStatus;
-class MediaRouterWebUIMessageHandler;
-class RouteRequestResult;
-
-// Functions as an intermediary between MediaRouter and WebUI Cast dialog.
-class MediaRouterUI : public MediaRouterUIBase, public ConstrainedWebDialogUI {
- public:
- // |web_ui| owns this object and is used to initialize the base class.
- explicit MediaRouterUI(content::WebUI* web_ui);
- ~MediaRouterUI() override;
-
- // Closes the media router UI.
- void Close();
-
- // Notifies this instance that the UI has been initialized.
- virtual void OnUIInitialized();
-
- // Calls MediaRouter to join the given route.
- bool ConnectRoute(const MediaSink::Id& sink_id,
- const MediaRoute::Id& route_id);
-
- // Calls MediaRouter to search route providers for sinks matching
- // |search_criteria| with the source that is currently associated with
- // |cast_mode|. The user's domain |domain| is also used.
- void SearchSinksAndCreateRoute(const MediaSink::Id& sink_id,
- const std::string& search_criteria,
- const std::string& domain,
- MediaCastMode cast_mode);
-
- // Returns true if the cast mode last chosen for the current origin is tab
- // mirroring.
- virtual bool UserSelectedTabMirroringForCurrentOrigin() const;
-
- // Records the cast mode selection for the current origin, unless the cast
- // mode is MediaCastMode::DESKTOP_MIRROR.
- virtual void RecordCastModeSelection(MediaCastMode cast_mode);
-
- // Returns the hostname of the PresentationRequest's parent frame URL.
- virtual std::string GetPresentationRequestSourceName() const;
- bool HasPendingRouteRequest() const {
- return current_route_request().has_value();
- }
- const std::vector<MediaRoute::Id>& joinable_route_ids() const {
- return joinable_route_ids_;
- }
- virtual const std::set<MediaCastMode>& GetCastModes() const;
- const std::unordered_map<MediaRoute::Id, MediaCastMode>&
- routes_and_cast_modes() const {
- return routes_and_cast_modes_;
- }
- const base::Optional<MediaCastMode>& forced_cast_mode() const {
- return forced_cast_mode_;
- }
-
- // Called to track UI metrics.
- void SetUIInitializationTimer(const base::Time& start_time);
- void OnUIInitiallyLoaded();
- void OnUIInitialDataReceived();
-
- void UpdateMaxDialogHeight(int height);
-
- // Gets the route controller currently in use by the UI. Returns a nullptr if
- // none is in use.
- virtual MediaRouteController* GetMediaRouteController() const;
-
- // Called when a media controller UI surface is created. Creates an observer
- // for the MediaRouteController for |route_id| to listen for media status
- // updates.
- virtual void OnMediaControllerUIAvailable(const MediaRoute::Id& route_id);
- // Called when a media controller UI surface is closed. Resets the observer
- // for MediaRouteController.
- virtual void OnMediaControllerUIClosed();
-
- void InitForTest(MediaRouter* router,
- content::WebContents* initiator,
- MediaRouterWebUIMessageHandler* handler,
- std::unique_ptr<StartPresentationContext> context,
- std::unique_ptr<MediaRouterFileDialog> file_dialog);
-
- void InitForTest(std::unique_ptr<MediaRouterFileDialog> file_dialog);
-
- private:
- friend class MediaRouterUITest;
-
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, SortedSinks);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, SortSinksByIconType);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, FilterNonDisplayRoutes);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, FilterNonDisplayJoinableRoutes);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest,
- UIMediaRoutesObserverAssignsCurrentCastModes);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest,
- UIMediaRoutesObserverSkipsUnavailableCastModes);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, GetExtensionNameExtensionPresent);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest,
- GetExtensionNameEmptyWhenNotInstalled);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest,
- GetExtensionNameEmptyWhenNotExtensionURL);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest,
- RouteCreationTimeoutForPresentation);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUIIncognitoTest,
- RouteRequestFromIncognito);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, OpenAndCloseUIDetailsView);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, SendMediaCommands);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, SendMediaStatusUpdate);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, SendInitialMediaStatusUpdate);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest,
- UpdateSinksWhenDialogMovesToAnotherDisplay);
-
- class UIIssuesObserver;
-
- class UIMediaRouteControllerObserver : public MediaRouteController::Observer {
- public:
- UIMediaRouteControllerObserver(
- MediaRouterUI* ui,
- scoped_refptr<MediaRouteController> controller);
- ~UIMediaRouteControllerObserver() override;
-
- // MediaRouteController::Observer:
- void OnMediaStatusUpdated(const MediaStatus& status) override;
- void OnControllerInvalidated() override;
-
- private:
- MediaRouterUI* const ui_;
-
- DISALLOW_COPY_AND_ASSIGN(UIMediaRouteControllerObserver);
- };
-
- // MediaRouterFileDialogDelegate:
- void FileDialogFileSelected(const ui::SelectedFileInfo& file_info) override;
-
- void OnIssue(const Issue& issue) override;
- void OnIssueCleared() override;
-
- void OnRoutesUpdated(
- const std::vector<MediaRoute>& routes,
- const std::vector<MediaRoute::Id>& joinable_route_ids) override;
-
- void OnRouteResponseReceived(
- int route_request_id,
- const MediaSink::Id& sink_id,
- MediaCastMode cast_mode,
- const base::string16& presentation_request_source_name,
- const RouteRequestResult& result) override;
-
- void HandleCreateSessionRequestRouteResponse(
- const RouteRequestResult&) override;
-
- // Callback passed to MediaRouter to receive the sink ID of the sink found by
- // SearchSinksAndCreateRoute().
- void OnSearchSinkResponseReceived(MediaCastMode cast_mode,
- const MediaSink::Id& found_sink_id);
-
- void InitCommon(content::WebContents* initiator) override;
-
- // PresentationServiceDelegateImpl::DefaultPresentationObserver:
- void OnDefaultPresentationChanged(
- const content::PresentationRequest& presentation_request) override;
- void OnDefaultPresentationRemoved() override;
-
- // Updates the set of supported cast modes and sends the updated set to
- // |handler_|.
- void UpdateCastModes();
-
- // Updates the routes-to-cast-modes mapping in |routes_and_cast_modes_| to
- // match the value of |routes_|.
- void UpdateRoutesToCastModesMapping();
-
- // Returns the serialized origin for |initiator_|, or the serialization of an
- // opaque origin ("null") if |initiator_| is not set.
- std::string GetSerializedInitiatorOrigin() const;
-
- // Destroys the route controller observer. Called when the route controller is
- // invalidated.
- void OnRouteControllerInvalidated();
-
- // Called by the internal route controller observer. Notifies the message
- // handler of a media status update for the route currently shown in the UI.
- void UpdateMediaRouteStatus(const MediaStatus& status);
-
- void UpdateSinks() override;
-
- MediaRouter* GetMediaRouter() const override;
-
- // Owned by the |web_ui| passed in the ctor, and guaranteed to be deleted
- // only after it has deleted |this|.
- MediaRouterWebUIMessageHandler* handler_ = nullptr;
-
- // Set to true by |handler_| when the UI has been initialized.
- bool ui_initialized_ = false;
-
- std::vector<MediaRoute::Id> joinable_route_ids_;
- CastModeSet cast_modes_;
- std::unordered_map<MediaRoute::Id, MediaCastMode> routes_and_cast_modes_;
-
- // The start time for UI initialization metrics timer. When a dialog has been
- // been painted and initialized with initial data, this should be cleared.
- base::Time start_time_;
-
- // The observer for the route controller. Notifies |handler_| of media status
- // updates.
- std::unique_ptr<UIMediaRouteControllerObserver> route_controller_observer_;
-
- // If set, a cast mode that is required to be shown first.
- base::Optional<MediaCastMode> forced_cast_mode_;
-
- base::WeakPtrFactory<MediaRouterUI> weak_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(MediaRouterUI);
-};
-
-} // namespace media_router
-
-#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_UI_H_
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
deleted file mode 100644
index 771ebe53416..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_ui_unittest.cc
+++ /dev/null
@@ -1,852 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/media_router/media_router_ui.h"
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/strings/utf_string_conversions.h"
-#include "build/build_config.h"
-#include "chrome/browser/media/router/media_router_factory.h"
-#include "chrome/browser/media/router/providers/wired_display/wired_display_media_route_provider.h"
-#include "chrome/browser/media/router/test/media_router_mojo_test.h"
-#include "chrome/browser/media/router/test/mock_media_router.h"
-#include "chrome/browser/media/router/test/test_helper.h"
-#include "chrome/browser/sessions/session_tab_helper.h"
-#include "chrome/browser/ui/media_router/media_router_ui_helper.h"
-#include "chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h"
-#include "chrome/browser/ui/webui/media_router/web_contents_display_observer.h"
-#include "chrome/common/media_router/media_route.h"
-#include "chrome/common/media_router/media_source.h"
-#include "chrome/common/media_router/mojo/media_router.mojom.h"
-#include "chrome/common/media_router/route_request_result.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/generated_resources.h"
-#include "chrome/test/base/chrome_render_view_host_test_harness.h"
-#include "chrome/test/base/testing_profile.h"
-#include "content/public/test/test_web_ui.h"
-#include "extensions/browser/extension_registry.h"
-#include "extensions/common/extension.h"
-#include "extensions/common/extension_builder.h"
-#include "extensions/common/value_builder.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
-#include "ui/base/l10n/l10n_util.h"
-#include "ui/display/display.h"
-
-using content::WebContents;
-using testing::_;
-using testing::AnyNumber;
-using testing::Invoke;
-using testing::Mock;
-using testing::Return;
-
-namespace media_router {
-
-ACTION_TEMPLATE(SaveArgWithMove,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_1_VALUE_PARAMS(pointer)) {
- *pointer = std::move(::testing::get<k>(args));
-}
-
-class MockMediaRouterWebUIMessageHandler
- : public MediaRouterWebUIMessageHandler {
- public:
- explicit MockMediaRouterWebUIMessageHandler(MediaRouterUI* media_router_ui)
- : MediaRouterWebUIMessageHandler(media_router_ui) {}
- ~MockMediaRouterWebUIMessageHandler() override {}
-
- MOCK_METHOD1(UpdateSinks,
- void(const std::vector<MediaSinkWithCastModes>& sinks));
- MOCK_METHOD1(UpdateIssue, void(const Issue& issue));
- MOCK_METHOD1(UpdateMediaRouteStatus, void(const MediaStatus& status));
- MOCK_METHOD3(UpdateCastModes,
- void(const CastModeSet& cast_modes,
- const std::string& source_host,
- base::Optional<MediaCastMode> forced_cast_mode));
-};
-
-class MockMediaRouterFileDialog : public MediaRouterFileDialog {
- public:
- MockMediaRouterFileDialog() : MediaRouterFileDialog(nullptr) {}
- ~MockMediaRouterFileDialog() override {}
-
- MOCK_METHOD0(GetLastSelectedFileUrl, GURL());
- MOCK_METHOD0(GetLastSelectedFileName, base::string16());
- MOCK_METHOD1(OpenFileDialog, void(Browser* browser));
-};
-
-class TestWebContentsDisplayObserver : public WebContentsDisplayObserver {
- public:
- explicit TestWebContentsDisplayObserver(const display::Display& display)
- : display_(display) {}
- ~TestWebContentsDisplayObserver() override {}
-
- const display::Display& GetCurrentDisplay() const override {
- return display_;
- }
-
- void set_display(const display::Display& display) { display_ = display; }
-
- private:
- display::Display display_;
-};
-
-class PresentationRequestCallbacks {
- public:
- PresentationRequestCallbacks() {}
-
- explicit PresentationRequestCallbacks(
- const blink::mojom::PresentationError& expected_error)
- : expected_error_(expected_error) {}
-
- void Success(const blink::mojom::PresentationInfo&,
- mojom::RoutePresentationConnectionPtr,
- const MediaRoute&) {}
-
- void Error(const blink::mojom::PresentationError& error) {
- EXPECT_EQ(expected_error_.error_type, error.error_type);
- EXPECT_EQ(expected_error_.message, error.message);
- }
-
- private:
- blink::mojom::PresentationError expected_error_;
-};
-
-class TestMediaRouterUI : public MediaRouterUI {
- public:
- TestMediaRouterUI(content::WebUI* web_ui, MediaRouter* router)
- : MediaRouterUI(web_ui), router_(router) {}
- ~TestMediaRouterUI() override = default;
-
- private:
- MediaRouter* GetMediaRouter() const override { return router_; }
-
- MediaRouter* router_;
- DISALLOW_COPY_AND_ASSIGN(TestMediaRouterUI);
-};
-
-class MediaRouterUITest : public ChromeRenderViewHostTestHarness {
- public:
- MediaRouterUITest()
- : presentation_request_({0, 0},
- {GURL("https://google.com/presentation")},
- url::Origin::Create(GURL("http://google.com"))) {}
-
- void SetUp() override {
- ChromeRenderViewHostTestHarness::SetUp();
- EXPECT_CALL(mock_router_, OnUserGesture()).Times(AnyNumber());
- EXPECT_CALL(mock_router_, GetCurrentRoutes())
- .Times(AnyNumber())
- .WillRepeatedly(Return(std::vector<MediaRoute>()));
- }
-
- void TearDown() override {
- EXPECT_CALL(mock_router_, UnregisterMediaSinksObserver(_))
- .Times(AnyNumber());
- EXPECT_CALL(mock_router_, UnregisterMediaRoutesObserver(_))
- .Times(AnyNumber());
- web_ui_contents_.reset();
- start_presentation_context_.reset();
- media_router_ui_.reset();
- message_handler_.reset();
- ChromeRenderViewHostTestHarness::TearDown();
- }
-
- void CreateMediaRouterUIForURL(Profile* profile, const GURL& url) {
- web_contents()->GetController().LoadURL(url, content::Referrer(),
- ui::PAGE_TRANSITION_LINK, "");
- content::RenderFrameHostTester::CommitPendingLoad(
- &web_contents()->GetController());
- CreateMediaRouterUI(profile);
- }
-
- void CreateMediaRouterUI(Profile* profile) {
- SessionTabHelper::CreateForWebContents(web_contents());
- web_ui_contents_ = WebContents::Create(WebContents::CreateParams(profile));
- web_ui_.set_web_contents(web_ui_contents_.get());
- media_router_ui_ =
- std::make_unique<TestMediaRouterUI>(&web_ui_, &mock_router_);
- message_handler_ = std::make_unique<MockMediaRouterWebUIMessageHandler>(
- media_router_ui_.get());
-
- auto file_dialog = std::make_unique<MockMediaRouterFileDialog>();
- mock_file_dialog_ = file_dialog.get();
-
- EXPECT_CALL(mock_router_, RegisterMediaSinksObserver(_))
- .WillRepeatedly(Invoke([this](MediaSinksObserver* observer) {
- this->media_sinks_observers_.push_back(observer);
- return true;
- }));
- EXPECT_CALL(mock_router_, RegisterMediaRoutesObserver(_))
- .Times(AnyNumber());
- media_router_ui_->InitForTest(
- &mock_router_, web_contents(), message_handler_.get(),
- std::move(start_presentation_context_), std::move(file_dialog));
- message_handler_->SetWebUIForTest(&web_ui_);
- }
-
- MediaSink CreateSinkCompatibleWithAllSources() {
- MediaSink sink("sinkId", "sinkName", SinkIconType::GENERIC);
- for (auto* observer : media_sinks_observers_)
- observer->OnSinksUpdated({sink}, std::vector<url::Origin>());
- return sink;
- }
-
- // Notifies MediaRouterUI that a route details view has been opened. Expects
- // MediaRouterUI to request a MediaRouteController, and gives it a mock
- // controller. Returns a reference to the mock controller.
- scoped_refptr<MockMediaRouteController> OpenUIDetailsView(
- const MediaRoute::Id& route_id) {
- auto controller = base::MakeRefCounted<MockMediaRouteController>(
- route_id, profile(), &mock_router_);
- MediaSource media_source("mediaSource");
- MediaRoute route(route_id, media_source, "sinkId", "", true, true);
-
- media_router_ui_->OnRoutesUpdated({route}, std::vector<MediaRoute::Id>());
- EXPECT_CALL(mock_router_, GetRouteController(route_id))
- .WillOnce(Return(controller));
- media_router_ui_->OnMediaControllerUIAvailable(route_id);
-
- return controller;
- }
-
- protected:
- MockMediaRouter mock_router_;
- content::PresentationRequest presentation_request_;
- content::TestWebUI web_ui_;
- std::unique_ptr<WebContents> web_ui_contents_;
- std::unique_ptr<StartPresentationContext> start_presentation_context_;
- std::unique_ptr<TestMediaRouterUI> media_router_ui_;
- std::unique_ptr<MockMediaRouterWebUIMessageHandler> message_handler_;
- MockMediaRouterFileDialog* mock_file_dialog_ = nullptr;
- std::vector<MediaSinksObserver*> media_sinks_observers_;
-};
-
-class MediaRouterUIIncognitoTest : public MediaRouterUITest {
- protected:
- content::BrowserContext* GetBrowserContext() override {
- return static_cast<Profile*>(MediaRouterUITest::GetBrowserContext())
- ->GetOffTheRecordProfile();
- }
-};
-
-TEST_F(MediaRouterUITest, RouteCreationTimeoutForTab) {
- CreateMediaRouterUI(profile());
- MediaRouteResponseCallback callback;
- EXPECT_CALL(mock_router_,
- CreateRouteInternal(_, _, _, _, _,
- base::TimeDelta::FromSeconds(60), false))
- .WillOnce(SaveArgWithMove<4>(&callback));
- media_router_ui_->CreateRoute(CreateSinkCompatibleWithAllSources().id(),
- MediaCastMode::TAB_MIRROR);
-
- std::string expected_title = l10n_util::GetStringUTF8(
- IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT_FOR_TAB);
- EXPECT_CALL(*message_handler_, UpdateIssue(IssueTitleEquals(expected_title)));
- std::unique_ptr<RouteRequestResult> result =
- RouteRequestResult::FromError("Timed out", RouteRequestResult::TIMED_OUT);
- std::move(callback).Run(nullptr, *result);
-}
-
-TEST_F(MediaRouterUITest, RouteCreationTimeoutForDesktop) {
- CreateMediaRouterUI(profile());
- MediaRouteResponseCallback callback;
- EXPECT_CALL(mock_router_,
- CreateRouteInternal(_, _, _, _, _,
- base::TimeDelta::FromSeconds(120), false))
- .WillOnce(SaveArgWithMove<4>(&callback));
- media_router_ui_->CreateRoute(CreateSinkCompatibleWithAllSources().id(),
- MediaCastMode::DESKTOP_MIRROR);
-
- std::string expected_title = l10n_util::GetStringUTF8(
- IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT_FOR_DESKTOP);
- EXPECT_CALL(*message_handler_, UpdateIssue(IssueTitleEquals(expected_title)));
- std::unique_ptr<RouteRequestResult> result =
- RouteRequestResult::FromError("Timed out", RouteRequestResult::TIMED_OUT);
- std::move(callback).Run(nullptr, *result);
-}
-
-TEST_F(MediaRouterUITest, RouteCreationTimeoutForPresentation) {
- CreateMediaRouterUI(profile());
- content::PresentationRequest presentation_request(
- {0, 0}, {GURL("https://presentationurl.com")},
- url::Origin::Create(GURL("https://frameurl.fakeurl")));
- media_router_ui_->OnDefaultPresentationChanged(presentation_request);
- MediaRouteResponseCallback callback;
- EXPECT_CALL(mock_router_,
- CreateRouteInternal(_, _, _, _, _,
- base::TimeDelta::FromSeconds(20), false))
- .WillOnce(SaveArgWithMove<4>(&callback));
- media_router_ui_->CreateRoute(CreateSinkCompatibleWithAllSources().id(),
- MediaCastMode::PRESENTATION);
-
- std::string expected_title =
- l10n_util::GetStringFUTF8(IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT,
- base::UTF8ToUTF16("frameurl.fakeurl"));
- EXPECT_CALL(*message_handler_, UpdateIssue(IssueTitleEquals(expected_title)));
- std::unique_ptr<RouteRequestResult> result =
- RouteRequestResult::FromError("Timed out", RouteRequestResult::TIMED_OUT);
- std::move(callback).Run(nullptr, *result);
-}
-
-// Tests that if a local file CreateRoute call is made from a new tab, the
-// file will be opened in the new tab.
-TEST_F(MediaRouterUITest, RouteCreationLocalFileModeInTab) {
- const GURL empty_tab = GURL(chrome::kChromeUINewTabURL);
- const std::string file_url = "file:///some/url/for/a/file.mp3";
-
- // Setup the UI
- CreateMediaRouterUIForURL(profile(), empty_tab);
-
- EXPECT_CALL(*mock_file_dialog_, GetLastSelectedFileUrl())
- .WillOnce(Return(GURL(file_url)));
-
- content::WebContents* location_file_opened = nullptr;
-
- // Expect that the media_router_ will make a call to the mock_router
- // then we will want to check that it made the call with.
- EXPECT_CALL(mock_router_, CreateRouteInternal(_, _, _, _, _, _, _))
- .WillOnce(SaveArgWithMove<3>(&location_file_opened));
-
- media_router_ui_->CreateRoute(CreateSinkCompatibleWithAllSources().id(),
- MediaCastMode::LOCAL_FILE);
-
- ASSERT_EQ(location_file_opened, web_contents());
- ASSERT_EQ(location_file_opened->GetVisibleURL(), file_url);
-}
-
-TEST_F(MediaRouterUITest, RouteCreationParametersCantBeCreated) {
- CreateMediaRouterUI(profile());
- MediaSinkSearchResponseCallback sink_callback;
- EXPECT_CALL(mock_router_, SearchSinksInternal(_, _, _, _, _))
- .WillOnce(SaveArgWithMove<4>(&sink_callback));
-
- // Use PRESENTATION mode without setting a PresentationRequest.
- media_router_ui_->SearchSinksAndCreateRoute(
- "sinkId", "search input", "domain", MediaCastMode::PRESENTATION);
- std::string expected_title = l10n_util::GetStringUTF8(
- IDS_MEDIA_ROUTER_ISSUE_CREATE_ROUTE_TIMEOUT_FOR_TAB);
- EXPECT_CALL(*message_handler_, UpdateIssue(IssueTitleEquals(expected_title)));
- std::move(sink_callback).Run("foundSinkId");
-}
-
-TEST_F(MediaRouterUIIncognitoTest, RouteRequestFromIncognito) {
- CreateMediaRouterUI(profile());
- media_router_ui_->OnDefaultPresentationChanged(presentation_request_);
-
- EXPECT_CALL(mock_router_,
- CreateRouteInternal(_, _, _, _, _,
- base::TimeDelta::FromSeconds(20), true));
- media_router_ui_->CreateRoute(CreateSinkCompatibleWithAllSources().id(),
- MediaCastMode::PRESENTATION);
-}
-
-TEST_F(MediaRouterUITest, SortedSinks) {
- CreateMediaRouterUI(profile());
- std::vector<MediaSinkWithCastModes> unsorted_sinks;
- std::string sink_id1("sink3");
- std::string sink_name1("B sink");
- MediaSinkWithCastModes sink1(
- MediaSink(sink_id1, sink_name1, SinkIconType::CAST));
- unsorted_sinks.push_back(sink1);
-
- std::string sink_id2("sink1");
- std::string sink_name2("A sink");
- MediaSinkWithCastModes sink2(
- MediaSink(sink_id2, sink_name2, SinkIconType::CAST));
- unsorted_sinks.push_back(sink2);
-
- std::string sink_id3("sink2");
- std::string sink_name3("B sink");
- MediaSinkWithCastModes sink3(
- MediaSink(sink_id3, sink_name3, SinkIconType::CAST));
- unsorted_sinks.push_back(sink3);
-
- // Sorted order is 2, 3, 1.
- media_router_ui_->OnResultsUpdated(unsorted_sinks);
- const auto& sorted_sinks = media_router_ui_->GetEnabledSinks();
- EXPECT_EQ(sink_name2, sorted_sinks[0].sink.name());
- EXPECT_EQ(sink_id3, sorted_sinks[1].sink.id());
- EXPECT_EQ(sink_id1, sorted_sinks[2].sink.id());
-}
-
-TEST_F(MediaRouterUITest, SortSinksByIconType) {
- CreateMediaRouterUI(profile());
- std::vector<MediaSinkWithCastModes> unsorted_sinks;
-
- MediaSinkWithCastModes sink1(MediaSink("id1", "sink", SinkIconType::HANGOUT));
- unsorted_sinks.push_back(sink1);
- MediaSinkWithCastModes sink2(
- MediaSink("id2", "B sink", SinkIconType::CAST_AUDIO_GROUP));
- unsorted_sinks.push_back(sink2);
- MediaSinkWithCastModes sink3(MediaSink("id3", "sink", SinkIconType::GENERIC));
- unsorted_sinks.push_back(sink3);
- MediaSinkWithCastModes sink4(
- MediaSink("id4", "A sink", SinkIconType::CAST_AUDIO_GROUP));
- unsorted_sinks.push_back(sink4);
- MediaSinkWithCastModes sink5(
- MediaSink("id5", "sink", SinkIconType::CAST_AUDIO));
- unsorted_sinks.push_back(sink5);
- MediaSinkWithCastModes sink6(MediaSink("id6", "sink", SinkIconType::CAST));
- unsorted_sinks.push_back(sink6);
-
- // Sorted order is CAST, CAST_AUDIO_GROUP "A", CAST_AUDIO_GROUP "B",
- // CAST_AUDIO, HANGOUT, GENERIC.
- media_router_ui_->OnResultsUpdated(unsorted_sinks);
- const auto& sorted_sinks = media_router_ui_->GetEnabledSinks();
- EXPECT_EQ(sink6.sink.id(), sorted_sinks[0].sink.id());
- EXPECT_EQ(sink4.sink.id(), sorted_sinks[1].sink.id());
- EXPECT_EQ(sink2.sink.id(), sorted_sinks[2].sink.id());
- EXPECT_EQ(sink5.sink.id(), sorted_sinks[3].sink.id());
- EXPECT_EQ(sink1.sink.id(), sorted_sinks[4].sink.id());
- EXPECT_EQ(sink3.sink.id(), sorted_sinks[5].sink.id());
-}
-
-TEST_F(MediaRouterUITest, FilterNonDisplayRoutes) {
- CreateMediaRouterUI(profile());
-
- MediaSource media_source("mediaSource");
- MediaRoute display_route_1("routeId1", media_source, "sinkId1", "desc 1",
- true, true);
- MediaRoute non_display_route_1("routeId2", media_source, "sinkId2", "desc 2",
- true, false);
- MediaRoute display_route_2("routeId3", media_source, "sinkId2", "desc 2",
- true, true);
- std::vector<MediaRoute> routes;
- routes.push_back(display_route_1);
- routes.push_back(non_display_route_1);
- routes.push_back(display_route_2);
-
- media_router_ui_->OnRoutesUpdated(routes, std::vector<MediaRoute::Id>());
- ASSERT_EQ(2u, media_router_ui_->routes().size());
- EXPECT_EQ(display_route_1, media_router_ui_->routes()[0]);
- EXPECT_TRUE(media_router_ui_->routes()[0].for_display());
- EXPECT_EQ(display_route_2, media_router_ui_->routes()[1]);
- EXPECT_TRUE(media_router_ui_->routes()[1].for_display());
-}
-
-TEST_F(MediaRouterUITest, FilterNonDisplayJoinableRoutes) {
- CreateMediaRouterUI(profile());
-
- MediaSource media_source("mediaSource");
- MediaRoute display_route_1("routeId1", media_source, "sinkId1", "desc 1",
- true, true);
- MediaRoute non_display_route_1("routeId2", media_source, "sinkId2", "desc 2",
- true, false);
- MediaRoute display_route_2("routeId3", media_source, "sinkId2", "desc 2",
- true, true);
- std::vector<MediaRoute> routes;
- routes.push_back(display_route_1);
- routes.push_back(non_display_route_1);
- routes.push_back(display_route_2);
-
- std::vector<MediaRoute::Id> joinable_route_ids;
- joinable_route_ids.push_back("routeId1");
- joinable_route_ids.push_back("routeId2");
- joinable_route_ids.push_back("routeId3");
-
- media_router_ui_->OnRoutesUpdated(routes, joinable_route_ids);
- ASSERT_EQ(2u, media_router_ui_->joinable_route_ids().size());
- EXPECT_EQ(display_route_1.media_route_id(),
- media_router_ui_->joinable_route_ids()[0]);
- EXPECT_EQ(display_route_2.media_route_id(),
- media_router_ui_->joinable_route_ids()[1]);
-}
-
-TEST_F(MediaRouterUITest, UIMediaRoutesObserverAssignsCurrentCastModes) {
- CreateMediaRouterUI(profile());
- SessionID tab_id = SessionTabHelper::IdForTab(web_contents());
- MediaSource media_source_1(MediaSource::ForTab(tab_id.id()));
- MediaSource media_source_2("mediaSource");
- MediaSource media_source_3(MediaSource::ForDesktop());
- std::unique_ptr<MediaRouterUI::UIMediaRoutesObserver> observer(
- new MediaRouterUI::UIMediaRoutesObserver(
- &mock_router_, MediaSource::Id(),
- base::Bind(&MediaRouterUI::OnRoutesUpdated,
- base::Unretained(media_router_ui_.get()))));
-
- MediaRoute display_route_1("routeId1", media_source_1, "sinkId1", "desc 1",
- true, true);
- MediaRoute non_display_route_1("routeId2", media_source_2, "sinkId2",
- "desc 2", true, false);
- MediaRoute display_route_2("routeId3", media_source_3, "sinkId2", "desc 2",
- true, true);
- std::vector<MediaRoute> routes;
- routes.push_back(display_route_1);
- routes.push_back(non_display_route_1);
- routes.push_back(display_route_2);
-
- observer->OnRoutesUpdated(routes, std::vector<MediaRoute::Id>());
-
- const auto& filtered_routes = media_router_ui_->routes();
- ASSERT_EQ(2u, filtered_routes.size());
- EXPECT_EQ(display_route_1, filtered_routes[0]);
- EXPECT_TRUE(filtered_routes[0].for_display());
- EXPECT_EQ(display_route_2, filtered_routes[1]);
- EXPECT_TRUE(filtered_routes[1].for_display());
-
- const auto& current_cast_modes = media_router_ui_->routes_and_cast_modes();
- ASSERT_EQ(2u, current_cast_modes.size());
- auto cast_mode_entry =
- current_cast_modes.find(display_route_1.media_route_id());
- EXPECT_NE(end(current_cast_modes), cast_mode_entry);
- EXPECT_EQ(MediaCastMode::TAB_MIRROR, cast_mode_entry->second);
- cast_mode_entry =
- current_cast_modes.find(non_display_route_1.media_route_id());
- EXPECT_EQ(end(current_cast_modes), cast_mode_entry);
- cast_mode_entry = current_cast_modes.find(display_route_2.media_route_id());
- EXPECT_NE(end(current_cast_modes), cast_mode_entry);
- EXPECT_EQ(MediaCastMode::DESKTOP_MIRROR, cast_mode_entry->second);
-
- EXPECT_CALL(mock_router_, UnregisterMediaRoutesObserver(_)).Times(1);
- observer.reset();
-}
-
-TEST_F(MediaRouterUITest, UIMediaRoutesObserverSkipsUnavailableCastModes) {
- CreateMediaRouterUI(profile());
- MediaSource media_source_1("mediaSource1");
- MediaSource media_source_2("mediaSource2");
- MediaSource media_source_3(MediaSource::ForDesktop());
- std::unique_ptr<MediaRouterUI::UIMediaRoutesObserver> observer(
- new MediaRouterUI::UIMediaRoutesObserver(
- &mock_router_, MediaSource::Id(),
- base::Bind(&MediaRouterUI::OnRoutesUpdated,
- base::Unretained(media_router_ui_.get()))));
-
- MediaRoute display_route_1("routeId1", media_source_1, "sinkId1", "desc 1",
- true, true);
- MediaRoute non_display_route_1("routeId2", media_source_2, "sinkId2",
- "desc 2", true, false);
- MediaRoute display_route_2("routeId3", media_source_3, "sinkId2", "desc 2",
- true, true);
- std::vector<MediaRoute> routes;
- routes.push_back(display_route_1);
- routes.push_back(non_display_route_1);
- routes.push_back(display_route_2);
-
- observer->OnRoutesUpdated(routes, std::vector<MediaRoute::Id>());
-
- const auto& filtered_routes = media_router_ui_->routes();
- ASSERT_EQ(2u, filtered_routes.size());
- EXPECT_EQ(display_route_1, filtered_routes[0]);
- EXPECT_TRUE(filtered_routes[0].for_display());
- EXPECT_EQ(display_route_2, filtered_routes[1]);
- EXPECT_TRUE(filtered_routes[1].for_display());
-
- const auto& current_cast_modes = media_router_ui_->routes_and_cast_modes();
- ASSERT_EQ(1u, current_cast_modes.size());
- auto cast_mode_entry =
- current_cast_modes.find(display_route_1.media_route_id());
- // No observer for source "mediaSource1" means no cast mode for this route.
- EXPECT_EQ(end(current_cast_modes), cast_mode_entry);
- cast_mode_entry =
- current_cast_modes.find(non_display_route_1.media_route_id());
- EXPECT_EQ(end(current_cast_modes), cast_mode_entry);
- cast_mode_entry = current_cast_modes.find(display_route_2.media_route_id());
- EXPECT_NE(end(current_cast_modes), cast_mode_entry);
- EXPECT_EQ(MediaCastMode::DESKTOP_MIRROR, cast_mode_entry->second);
-
- EXPECT_CALL(mock_router_, UnregisterMediaRoutesObserver(_)).Times(1);
- observer.reset();
-}
-
-TEST_F(MediaRouterUITest, NotFoundErrorOnCloseWithNoSinks) {
- blink::mojom::PresentationError expected_error(
- blink::mojom::PresentationErrorType::NO_AVAILABLE_SCREENS,
- "No screens found.");
- PresentationRequestCallbacks request_callbacks(expected_error);
- start_presentation_context_ = std::make_unique<StartPresentationContext>(
- presentation_request_,
- base::Bind(&PresentationRequestCallbacks::Success,
- base::Unretained(&request_callbacks)),
- base::Bind(&PresentationRequestCallbacks::Error,
- base::Unretained(&request_callbacks)));
- CreateMediaRouterUI(profile());
- // Destroying the UI should return the expected error from above to the error
- // callback.
- media_router_ui_.reset();
-}
-
-TEST_F(MediaRouterUITest, NotFoundErrorOnCloseWithNoCompatibleSinks) {
- blink::mojom::PresentationError expected_error(
- blink::mojom::PresentationErrorType::NO_AVAILABLE_SCREENS,
- "No screens found.");
- PresentationRequestCallbacks request_callbacks(expected_error);
- start_presentation_context_ = std::make_unique<StartPresentationContext>(
- presentation_request_,
- base::Bind(&PresentationRequestCallbacks::Success,
- base::Unretained(&request_callbacks)),
- base::Bind(&PresentationRequestCallbacks::Error,
- base::Unretained(&request_callbacks)));
- CreateMediaRouterUI(profile());
-
- // Send a sink to the UI that is compatible with sources other than the
- // presentation url to cause a NotFoundError.
- std::vector<MediaSink> sinks;
- sinks.emplace_back("sink id", "sink name", SinkIconType::GENERIC);
- std::vector<url::Origin> origins;
- auto presentation_source = MediaSource::ForPresentationUrl(
- presentation_request_.presentation_urls[0]);
- for (auto* observer : media_sinks_observers_) {
- if (!(observer->source() == presentation_source)) {
- observer->OnSinksUpdated(sinks, origins);
- }
- }
- // Destroying the UI should return the expected error from above to the error
- // callback.
- media_router_ui_.reset();
-}
-
-TEST_F(MediaRouterUITest, AbortErrorOnClose) {
- blink::mojom::PresentationError expected_error(
- blink::mojom::PresentationErrorType::PRESENTATION_REQUEST_CANCELLED,
- "Dialog closed.");
- PresentationRequestCallbacks request_callbacks(expected_error);
- start_presentation_context_ = std::make_unique<StartPresentationContext>(
- presentation_request_,
- base::Bind(&PresentationRequestCallbacks::Success,
- base::Unretained(&request_callbacks)),
- base::Bind(&PresentationRequestCallbacks::Error,
- base::Unretained(&request_callbacks)));
- CreateMediaRouterUI(profile());
-
- // Send a sink to the UI that is compatible with the presentation url to avoid
- // a NotFoundError.
- std::vector<MediaSink> sinks;
- sinks.emplace_back("sink id", "sink name", SinkIconType::GENERIC);
- std::vector<url::Origin> origins;
- auto presentation_source = MediaSource::ForPresentationUrl(
- presentation_request_.presentation_urls[0]);
- for (auto* observer : media_sinks_observers_) {
- if (observer->source() == presentation_source) {
- observer->OnSinksUpdated(sinks, origins);
- }
- }
- // Destroying the UI should return the expected error from above to the error
- // callback.
- media_router_ui_.reset();
-}
-
-TEST_F(MediaRouterUITest, RecordCastModeSelections) {
- const GURL url_1a = GURL("https://www.example.com/watch?v=AAAA");
- const GURL url_1b = GURL("https://www.example.com/watch?v=BBBB");
- const GURL url_2 = GURL("https://example2.com/0000");
- const GURL url_3 = GURL("https://www3.example.com/index.html");
-
- CreateMediaRouterUIForURL(profile(), url_1a);
- EXPECT_FALSE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
- media_router_ui_->RecordCastModeSelection(MediaCastMode::TAB_MIRROR);
- EXPECT_TRUE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
-
- CreateMediaRouterUIForURL(profile(), url_2);
- EXPECT_FALSE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
-
- CreateMediaRouterUIForURL(profile(), url_1b);
- // |url_1a| and |url_1b| have the same origin, so the selection made for
- // |url_1a| should be retrieved.
- EXPECT_TRUE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
- media_router_ui_->RecordCastModeSelection(MediaCastMode::PRESENTATION);
- EXPECT_FALSE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
-
- media_router_ui_->RecordCastModeSelection(MediaCastMode::TAB_MIRROR);
- CreateMediaRouterUIForURL(profile(), url_3);
- // |url_1a| and |url_3| have the same domain "example.com" but different
- // origins, so their preferences should be separate.
- EXPECT_FALSE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
-}
-
-TEST_F(MediaRouterUITest, RecordCastModeSelectionsInIncognito) {
- const GURL url = GURL("https://www.example.com/watch?v=AAAA");
-
- CreateMediaRouterUIForURL(profile()->GetOffTheRecordProfile(), url);
- EXPECT_FALSE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
- media_router_ui_->RecordCastModeSelection(MediaCastMode::TAB_MIRROR);
- EXPECT_TRUE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
-
- // Selections recorded in incognito shouldn't be retrieved in the regular
- // profile.
- CreateMediaRouterUIForURL(profile(), url);
- EXPECT_FALSE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
-}
-
-TEST_F(MediaRouterUITest, RecordDesktopMirroringCastModeSelection) {
- const GURL url = GURL("https://www.example.com/watch?v=AAAA");
- CreateMediaRouterUIForURL(profile(), url);
-
- EXPECT_FALSE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
- media_router_ui_->RecordCastModeSelection(MediaCastMode::DESKTOP_MIRROR);
- // Selecting desktop mirroring should not change the recorded preferences.
- EXPECT_FALSE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
-
- media_router_ui_->RecordCastModeSelection(MediaCastMode::TAB_MIRROR);
- EXPECT_TRUE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
- media_router_ui_->RecordCastModeSelection(MediaCastMode::DESKTOP_MIRROR);
- // Selecting desktop mirroring should not change the recorded preferences.
- EXPECT_TRUE(media_router_ui_->UserSelectedTabMirroringForCurrentOrigin());
-}
-
-TEST_F(MediaRouterUITest, OpenAndCloseUIDetailsView) {
- const std::string route_id = "routeId";
- CreateMediaRouterUI(profile());
- OpenUIDetailsView(route_id);
-
- // When the route details view is closed, the route controller observer should
- // be destroyed, also triggering the destruction of the controller.
- EXPECT_CALL(mock_router_, DetachRouteController(route_id, _));
- media_router_ui_->OnMediaControllerUIClosed();
-
- EXPECT_TRUE(Mock::VerifyAndClearExpectations(&mock_router_));
-}
-
-TEST_F(MediaRouterUITest, SendMediaStatusUpdate) {
- MediaStatus status;
- status.title = "test title";
- CreateMediaRouterUI(profile());
- scoped_refptr<MockMediaRouteController> controller =
- OpenUIDetailsView("routeId");
-
- // The route controller observer held by MediaRouterUI should send the status
- // update to the message handler.
- EXPECT_CALL(*message_handler_, UpdateMediaRouteStatus(status));
- controller->OnMediaStatusUpdated(status);
-
- // |controller| will outlive |mock_router_| because we passed it into
- // testing::Return(). Invalidate it so that it doesn't reference
- // |mock_router_| in its dtor.
- controller->Invalidate();
-}
-
-TEST_F(MediaRouterUITest, SendInitialMediaStatusUpdate) {
- MediaStatus status;
- status.title = "test title";
- std::string route_id = "routeId";
- auto controller = base::MakeRefCounted<MockMediaRouteController>(
- route_id, profile(), &mock_router_);
- controller->OnMediaStatusUpdated(status);
-
- CreateMediaRouterUI(profile());
- MediaSource media_source("mediaSource");
- MediaRoute route(route_id, media_source, "sinkId", "", true, true);
- media_router_ui_->OnRoutesUpdated({route}, std::vector<MediaRoute::Id>());
-
- // If the controller has already received a media status update, MediaRouterUI
- // should be notified with it when it starts observing the controller.
- EXPECT_CALL(mock_router_, GetRouteController(route_id))
- .WillOnce(Return(controller));
- EXPECT_CALL(*message_handler_, UpdateMediaRouteStatus(status));
- media_router_ui_->OnMediaControllerUIAvailable(route_id);
-
- // |controller| will outlive |mock_router_| because we passed it into
- // testing::Return(). Invalidate it so that it doesn't reference
- // |mock_router_| in its dtor.
- controller->Invalidate();
-}
-
-TEST_F(MediaRouterUITest, SetsForcedCastModeWithPresentationURLs) {
- presentation_request_.presentation_urls.push_back(
- GURL("https://google.com/presentation2"));
- blink::mojom::PresentationError expected_error(
- blink::mojom::PresentationErrorType::NO_AVAILABLE_SCREENS,
- "No screens found.");
- PresentationRequestCallbacks request_callbacks(expected_error);
- start_presentation_context_ = std::make_unique<StartPresentationContext>(
- presentation_request_,
- base::Bind(&PresentationRequestCallbacks::Success,
- base::Unretained(&request_callbacks)),
- base::Bind(&PresentationRequestCallbacks::Error,
- base::Unretained(&request_callbacks)));
-
- SessionTabHelper::CreateForWebContents(web_contents());
- web_ui_contents_ = WebContents::Create(WebContents::CreateParams(profile()));
- web_ui_.set_web_contents(web_ui_contents_.get());
- media_router_ui_ =
- std::make_unique<TestMediaRouterUI>(&web_ui_, &mock_router_);
- message_handler_ = std::make_unique<MockMediaRouterWebUIMessageHandler>(
- media_router_ui_.get());
- message_handler_->SetWebUIForTest(&web_ui_);
- EXPECT_CALL(mock_router_, RegisterMediaSinksObserver(_))
- .WillRepeatedly(Invoke([this](MediaSinksObserver* observer) {
- this->media_sinks_observers_.push_back(observer);
- return true;
- }));
- EXPECT_CALL(mock_router_, RegisterMediaRoutesObserver(_)).Times(AnyNumber());
-
- CastModeSet expected_modes(
- {MediaCastMode::TAB_MIRROR, MediaCastMode::DESKTOP_MIRROR,
- MediaCastMode::LOCAL_FILE, MediaCastMode::PRESENTATION});
- media_router_ui_->InitForTest(
- &mock_router_, web_contents(), message_handler_.get(),
- std::move(start_presentation_context_), nullptr);
- 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());
-
- // |media_router_ui_| takes ownership of |request_callbacks|.
- media_router_ui_.reset();
-}
-
-// A wired display sink should not be on the sinks list when the dialog is on
-// that display, to prevent showing a fullscreen presentation window over the
-// controlling window.
-TEST_F(MediaRouterUITest, UpdateSinksWhenDialogMovesToAnotherDisplay) {
- const display::Display display1(1000001);
- const display::Display display2(1000002);
- const std::string display_sink_id1 =
- WiredDisplayMediaRouteProvider::GetSinkIdForDisplay(display1);
- const std::string display_sink_id2 =
- WiredDisplayMediaRouteProvider::GetSinkIdForDisplay(display2);
-
- CreateMediaRouterUI(profile());
-
- auto display_observer_unique =
- std::make_unique<TestWebContentsDisplayObserver>(display1);
- TestWebContentsDisplayObserver* display_observer =
- display_observer_unique.get();
- media_router_ui_->display_observer_ = std::move(display_observer_unique);
-
- std::vector<MediaSinkWithCastModes> sinks;
- MediaSinkWithCastModes display_sink1(
- MediaSink(display_sink_id1, "sink", SinkIconType::GENERIC));
- sinks.push_back(display_sink1);
- MediaSinkWithCastModes display_sink2(
- MediaSink(display_sink_id2, "sink", SinkIconType::GENERIC));
- sinks.push_back(display_sink2);
- MediaSinkWithCastModes sink3(MediaSink("id3", "sink", SinkIconType::GENERIC));
- sinks.push_back(sink3);
- media_router_ui_->OnResultsUpdated(sinks);
-
- // Initially |display_sink1| should not be on the sinks list because we are on
- // |display1|.
- EXPECT_CALL(*message_handler_, UpdateSinks(_))
- .WillOnce(Invoke([&display_sink_id1](
- const std::vector<MediaSinkWithCastModes>& sinks) {
- EXPECT_EQ(2u, sinks.size());
- EXPECT_TRUE(std::find_if(sinks.begin(), sinks.end(),
- [&display_sink_id1](
- const MediaSinkWithCastModes& sink) {
- return sink.sink.id() == display_sink_id1;
- }) == sinks.end());
- }));
- media_router_ui_->UpdateSinks();
-
- // Change the display to |display2|. Now |display_sink2| should be removed
- // from the list of sinks.
- EXPECT_CALL(*message_handler_, UpdateSinks(_))
- .WillOnce(Invoke([&display_sink_id2](
- const std::vector<MediaSinkWithCastModes>& sinks) {
- EXPECT_EQ(2u, sinks.size());
- EXPECT_TRUE(std::find_if(sinks.begin(), sinks.end(),
- [&display_sink_id2](
- const MediaSinkWithCastModes& sink) {
- return sink.sink.id() == display_sink_id2;
- }) == sinks.end());
- }));
- display_observer->set_display(display2);
- media_router_ui_->UpdateSinks();
-}
-
-} // namespace media_router
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_web_ui_test.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_web_ui_test.cc
deleted file mode 100644
index 75c75604250..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_web_ui_test.cc
+++ /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.
-
-#include "chrome/browser/ui/webui/media_router/media_router_web_ui_test.h"
-
-#include "base/bind.h"
-#include "chrome/browser/media/router/media_router_factory.h"
-#include "chrome/browser/media/router/test/mock_media_router.h"
-#include "chrome/browser/ui/media_router/media_router_ui_service.h"
-#include "chrome/browser/ui/media_router/media_router_ui_service_factory.h"
-#include "chrome/browser/ui/toolbar/mock_media_router_action_controller.h"
-#include "chrome/browser/ui/toolbar/toolbar_actions_model.h"
-#include "chrome/browser/ui/toolbar/toolbar_actions_model_factory.h"
-#include "chrome/test/base/dialog_test_browser_window.h"
-
-class MockMediaRouterUIService : public media_router::MediaRouterUIService {
- public:
- explicit MockMediaRouterUIService(Profile* profile)
- : media_router::MediaRouterUIService(profile),
- action_controller_(profile) {}
- ~MockMediaRouterUIService() override {}
-
- MediaRouterActionController* action_controller() override {
- return &action_controller_;
- }
-
- private:
- MockMediaRouterActionController action_controller_;
-};
-
-std::unique_ptr<KeyedService> BuildMockMediaRouterUIService(
- content::BrowserContext* context) {
- return std::make_unique<MockMediaRouterUIService>(
- static_cast<Profile*>(context));
-}
-
-std::unique_ptr<KeyedService> BuildToolbarActionsModel(
- content::BrowserContext* context) {
- return std::make_unique<ToolbarActionsModel>(static_cast<Profile*>(context),
- nullptr);
-}
-
-MediaRouterWebUITest::MediaRouterWebUITest() : MediaRouterWebUITest(false) {}
-MediaRouterWebUITest::MediaRouterWebUITest(bool require_mock_ui_service)
- : require_mock_ui_service_(require_mock_ui_service) {}
-
-MediaRouterWebUITest::~MediaRouterWebUITest() {}
-
-TestingProfile::TestingFactories MediaRouterWebUITest::GetTestingFactories() {
- TestingProfile::TestingFactories factories = {
- {media_router::MediaRouterFactory::GetInstance(),
- base::BindRepeating(&media_router::MockMediaRouter::Create)}};
- if (require_mock_ui_service_) {
- factories.emplace_back(
- media_router::MediaRouterUIServiceFactory::GetInstance(),
- base::BindRepeating(&BuildMockMediaRouterUIService));
- factories.emplace_back(ToolbarActionsModelFactory::GetInstance(),
- base::BindRepeating(&BuildToolbarActionsModel));
- }
-
- return factories;
-}
-
-std::unique_ptr<BrowserWindow> MediaRouterWebUITest::CreateBrowserWindow() {
- return std::make_unique<DialogTestBrowserWindow>();
-}
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_web_ui_test.h b/chromium/chrome/browser/ui/webui/media_router/media_router_web_ui_test.h
deleted file mode 100644
index b52ae525fc6..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_web_ui_test.h
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2016 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_WEB_UI_TEST_H_
-#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_WEB_UI_TEST_H_
-
-#include "chrome/test/base/browser_with_test_window_test.h"
-
-class MediaRouterWebUITest : public BrowserWithTestWindowTest {
- public:
- // |require_mock_ui_service_| defaults to false in the default ctor.
- MediaRouterWebUITest();
- explicit MediaRouterWebUITest(bool require_mock_ui_service);
- ~MediaRouterWebUITest() override;
-
- protected:
- // BrowserWithTestWindowTest:
- TestingProfile::TestingFactories GetTestingFactories() override;
- std::unique_ptr<BrowserWindow> CreateBrowserWindow() override;
-
- private:
- // When this is set to true, MockMediaRouterUIService is instantiated.
- // Otherwise, no MediaRouterUIService is instantiated.
- bool require_mock_ui_service_;
-
- DISALLOW_COPY_AND_ASSIGN(MediaRouterWebUITest);
-};
-
-#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_WEB_UI_TEST_H_
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
deleted file mode 100644
index b6b9fe2eda5..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc
+++ /dev/null
@@ -1,1165 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h"
-
-#include <algorithm>
-#include <memory>
-#include <set>
-#include <string>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/metrics/histogram_functions.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/metrics/user_metrics.h"
-#include "base/strings/string_util.h"
-#include "base/strings/stringprintf.h"
-#include "base/values.h"
-#include "chrome/browser/media/router/media_router_metrics.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/signin/identity_manager_factory.h"
-#include "chrome/browser/sync/profile_sync_service_factory.h"
-#include "chrome/browser/ui/webui/media_router/media_router_ui.h"
-#include "chrome/common/chrome_features.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/account_info.h"
-#include "components/sync/driver/sync_service.h"
-#include "content/public/browser/web_ui.h"
-#include "extensions/common/constants.h"
-#include "services/identity/public/cpp/identity_manager.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace media_router {
-
-namespace {
-
-const char kCastLearnMorePageUrl[] =
- "https://www.google.com/chrome/devices/chromecast/learn.html";
-const char kHelpPageUrlPrefix[] =
- "https://support.google.com/chromecast/answer/%d";
-
-// Message names.
-const char kRequestInitialData[] = "requestInitialData";
-const char kCreateRoute[] = "requestRoute";
-const char kAcknowledgeFirstRunFlow[] = "acknowledgeFirstRunFlow";
-const char kActOnIssue[] = "actOnIssue";
-const char kCloseRoute[] = "closeRoute";
-const char kJoinRoute[] = "joinRoute";
-const char kCloseDialog[] = "closeDialog";
-const char kReportBlur[] = "reportBlur";
-const char kReportClickedSinkIndex[] = "reportClickedSinkIndex";
-const char kReportFilter[] = "reportFilter";
-const char kReportInitialAction[] = "reportInitialAction";
-const char kReportInitialState[] = "reportInitialState";
-const char kReportNavigateToView[] = "reportNavigateToView";
-const char kReportRouteCreationOutcome[] = "reportRouteCreationOutcome";
-const char kReportRouteCreation[] = "reportRouteCreation";
-const char kReportSelectedCastMode[] = "reportSelectedCastMode";
-const char kReportSinkCount[] = "reportSinkCount";
-const char kReportTimeToClickSink[] = "reportTimeToClickSink";
-const char kReportTimeToInitialActionClose[] = "reportTimeToInitialActionClose";
-const char kReportWebUIRouteControllerLoaded[] =
- "reportWebUIRouteControllerLoaded";
-const char kSearchSinksAndCreateRoute[] = "searchSinksAndCreateRoute";
-const char kOnInitialDataReceived[] = "onInitialDataReceived";
-const char kOnMediaControllerAvailable[] = "onMediaControllerAvailable";
-const char kOnMediaControllerClosed[] = "onMediaControllerClosed";
-const char kPauseCurrentMedia[] = "pauseCurrentMedia";
-const char kPlayCurrentMedia[] = "playCurrentMedia";
-const char kSeekCurrentMedia[] = "seekCurrentMedia";
-const char kSelectLocalMediaFile[] = "selectLocalMediaFile";
-const char kSetCurrentMediaMute[] = "setCurrentMediaMute";
-const char kSetCurrentMediaVolume[] = "setCurrentMediaVolume";
-const char kSetMediaRemotingEnabled[] = "setMediaRemotingEnabled";
-const char kHangoutsSetLocalPresent[] = "hangouts.setLocalPresent";
-
-// JS function names.
-const char kSetInitialData[] = "media_router.ui.setInitialData";
-const char kOnCreateRouteResponseReceived[] =
- "media_router.ui.onCreateRouteResponseReceived";
-const char kOnRouteControllerInvalidated[] =
- "media_router.ui.onRouteControllerInvalidated";
-const char kReceiveSearchResult[] = "media_router.ui.receiveSearchResult";
-const char kSetFirstRunFlowData[] = "media_router.ui.setFirstRunFlowData";
-const char kSetIssue[] = "media_router.ui.setIssue";
-const char kSetSinkListAndIdentity[] = "media_router.ui.setSinkListAndIdentity";
-const char kSetRouteList[] = "media_router.ui.setRouteList";
-const char kSetCastModeList[] = "media_router.ui.setCastModeList";
-const char kUpdateMaxHeight[] = "media_router.ui.updateMaxHeight";
-const char kUpdateRouteStatus[] = "media_router.ui.updateRouteStatus";
-const char kUserSelectedLocalMediaFile[] =
- "media_router.ui.userSelectedLocalMediaFile";
-const char kWindowOpen[] = "window.open";
-
-std::unique_ptr<base::DictionaryValue> SinksAndIdentityToValue(
- const std::vector<MediaSinkWithCastModes>& sinks,
- const AccountInfo& account_info) {
- auto sink_list_and_identity = std::make_unique<base::DictionaryValue>();
- bool show_email = false;
- bool show_domain = false;
- std::string user_domain;
- if (account_info.IsValid()) {
- user_domain = account_info.hosted_domain;
- sink_list_and_identity->SetString("userEmail", account_info.email);
- }
-
- auto sinks_val = std::make_unique<base::ListValue>();
-
- for (const MediaSinkWithCastModes& sink_with_cast_modes : sinks) {
- auto sink_val = std::make_unique<base::DictionaryValue>();
-
- const MediaSink& sink = sink_with_cast_modes.sink;
- sink_val->SetString("id", sink.id());
- sink_val->SetString("name", sink.name());
- sink_val->SetInteger("iconType", static_cast<int>(sink.icon_type()));
- if (sink.description())
- sink_val->SetString("description", *sink.description());
-
- bool is_pseudo_sink =
- base::StartsWith(sink.id(), "pseudo:", base::CompareCase::SENSITIVE);
- if (!user_domain.empty() && sink.domain() && !sink.domain()->empty()) {
- std::string domain = *sink.domain();
- // Convert default domains to user domain
- if (domain == "default") {
- domain = user_domain;
- if (domain == kNoHostedDomainFound) {
- // Default domain will be empty for non-dasher accounts.
- domain.clear();
- }
- }
-
- sink_val->SetString("domain", domain);
-
- show_email = show_email || !is_pseudo_sink;
- if (!domain.empty() && domain != user_domain) {
- show_domain = true;
- }
- }
-
- int cast_mode_bits = 0;
- for (MediaCastMode cast_mode : sink_with_cast_modes.cast_modes)
- cast_mode_bits |= cast_mode;
-
- sink_val->SetInteger("castModes", cast_mode_bits);
- sink_val->SetBoolean("isPseudoSink", is_pseudo_sink);
- sinks_val->Append(std::move(sink_val));
- }
-
- sink_list_and_identity->Set("sinks", std::move(sinks_val));
- sink_list_and_identity->SetBoolean("showEmail", show_email);
- sink_list_and_identity->SetBoolean("showDomain", show_domain);
- return sink_list_and_identity;
-}
-
-std::unique_ptr<base::DictionaryValue> RouteToValue(
- const MediaRoute& route,
- bool can_join,
- bool incognito,
- int current_cast_mode) {
- auto dictionary = std::make_unique<base::DictionaryValue>();
- dictionary->SetString("id", route.media_route_id());
- dictionary->SetString("sinkId", route.media_sink_id());
- dictionary->SetString("description", route.description());
- dictionary->SetBoolean("isLocal", route.is_local());
- dictionary->SetBoolean("supportsWebUiController",
- route.controller_type() != RouteControllerType::kNone);
- dictionary->SetBoolean("canJoin", can_join);
- if (current_cast_mode > 0) {
- dictionary->SetInteger("currentCastMode", current_cast_mode);
- }
-
- return dictionary;
-}
-
-std::unique_ptr<base::ListValue> CastModesToValue(
- const CastModeSet& cast_modes,
- const std::string& source_host,
- base::Optional<MediaCastMode> forced_cast_mode) {
- auto value = std::make_unique<base::ListValue>();
-
- for (const MediaCastMode& cast_mode : cast_modes) {
- auto cast_mode_val = std::make_unique<base::DictionaryValue>();
- cast_mode_val->SetInteger("type", cast_mode);
- cast_mode_val->SetString(
- "description", MediaCastModeToDescription(cast_mode, source_host));
- cast_mode_val->SetString("host", source_host);
- cast_mode_val->SetBoolean(
- "isForced", forced_cast_mode && forced_cast_mode == cast_mode);
- value->Append(std::move(cast_mode_val));
- }
-
- return value;
-}
-
-// Returns an Issue dictionary created from |issue| that can be used in WebUI.
-std::unique_ptr<base::DictionaryValue> IssueToValue(const Issue& issue) {
- const IssueInfo& issue_info = issue.info();
- auto dictionary = std::make_unique<base::DictionaryValue>();
- dictionary->SetInteger("id", issue.id());
- dictionary->SetString("title", issue_info.title);
- dictionary->SetString("message", issue_info.message);
- dictionary->SetInteger("defaultActionType",
- static_cast<int>(issue_info.default_action));
- if (!issue_info.secondary_actions.empty()) {
- DCHECK_EQ(1u, issue_info.secondary_actions.size());
- dictionary->SetInteger("secondaryActionType",
- static_cast<int>(issue_info.secondary_actions[0]));
- }
- if (!issue_info.route_id.empty())
- dictionary->SetString("routeId", issue_info.route_id);
- dictionary->SetBoolean("isBlocking", issue_info.is_blocking);
- if (issue_info.help_page_id > 0)
- dictionary->SetInteger("helpPageId", issue_info.help_page_id);
-
- return dictionary;
-}
-
-bool IsValidIssueActionTypeNum(int issue_action_type_num) {
- return issue_action_type_num >= 0 &&
- issue_action_type_num <=
- static_cast<int>(IssueInfo::Action::NUM_VALUES);
-}
-
-// Composes a "learn more" URL. The URL depends on template arguments in |args|.
-// Returns an empty string if |args| is invalid.
-std::string GetLearnMoreUrl(const base::DictionaryValue* args) {
- // TODO(imcheng): The template arguments for determining the learn more URL
- // should come from the Issue object in the browser, not from WebUI.
- int help_page_id = -1;
- if (!args->GetInteger("helpPageId", &help_page_id) || help_page_id < 0) {
- DVLOG(1) << "Invalid help page id.";
- return std::string();
- }
-
- std::string help_url = base::StringPrintf(kHelpPageUrlPrefix, help_page_id);
- if (!GURL(help_url).is_valid()) {
- DVLOG(1) << "Error: URL is invalid and cannot be opened.";
- return std::string();
- }
- return help_url;
-}
-
-} // namespace
-
-MediaRouterWebUIMessageHandler::MediaRouterWebUIMessageHandler(
- MediaRouterUI* media_router_ui)
- : incognito_(
- Profile::FromWebUI(media_router_ui->web_ui())->IsOffTheRecord()),
- dialog_closing_(false),
- media_router_ui_(media_router_ui) {}
-
-MediaRouterWebUIMessageHandler::~MediaRouterWebUIMessageHandler() {}
-
-void MediaRouterWebUIMessageHandler::UpdateSinks(
- const std::vector<MediaSinkWithCastModes>& sinks) {
- DVLOG(2) << "UpdateSinks";
- std::unique_ptr<base::DictionaryValue> sinks_and_identity_val(
- SinksAndIdentityToValue(sinks, GetAccountInfo()));
- web_ui()->CallJavascriptFunctionUnsafe(kSetSinkListAndIdentity,
- *sinks_and_identity_val);
-}
-
-void MediaRouterWebUIMessageHandler::UpdateRoutes(
- const std::vector<MediaRoute>& routes,
- const std::vector<MediaRoute::Id>& joinable_route_ids,
- const std::unordered_map<MediaRoute::Id, MediaCastMode>&
- current_cast_modes) {
- std::unique_ptr<base::ListValue> routes_val(
- RoutesToValue(routes, joinable_route_ids, current_cast_modes));
-
- web_ui()->CallJavascriptFunctionUnsafe(kSetRouteList, *routes_val);
-}
-
-void MediaRouterWebUIMessageHandler::UpdateCastModes(
- const CastModeSet& cast_modes,
- const std::string& source_host,
- base::Optional<MediaCastMode> forced_cast_mode) {
- DVLOG(2) << "UpdateCastModes";
- std::unique_ptr<base::ListValue> cast_modes_val(
- CastModesToValue(cast_modes, source_host, forced_cast_mode));
- web_ui()->CallJavascriptFunctionUnsafe(kSetCastModeList, *cast_modes_val);
-}
-
-void MediaRouterWebUIMessageHandler::OnCreateRouteResponseReceived(
- const MediaSink::Id& sink_id,
- const MediaRoute* route) {
- DVLOG(2) << "OnCreateRouteResponseReceived";
- if (route) {
- int current_cast_mode = CurrentCastModeForRouteId(
- route->media_route_id(), media_router_ui_->routes_and_cast_modes());
- std::unique_ptr<base::DictionaryValue> route_value(
- RouteToValue(*route, false, incognito_, current_cast_mode));
- web_ui()->CallJavascriptFunctionUnsafe(kOnCreateRouteResponseReceived,
- base::Value(sink_id), *route_value,
- base::Value(route->for_display()));
- } else {
- web_ui()->CallJavascriptFunctionUnsafe(kOnCreateRouteResponseReceived,
- base::Value(sink_id), base::Value(),
- base::Value(false));
- }
-}
-
-void MediaRouterWebUIMessageHandler::ReturnSearchResult(
- const std::string& sink_id) {
- DVLOG(2) << "ReturnSearchResult";
- web_ui()->CallJavascriptFunctionUnsafe(kReceiveSearchResult,
- base::Value(sink_id));
-}
-
-void MediaRouterWebUIMessageHandler::UpdateIssue(const Issue& issue) {
- DVLOG(2) << "UpdateIssue";
- web_ui()->CallJavascriptFunctionUnsafe(kSetIssue, *IssueToValue(issue));
-}
-
-void MediaRouterWebUIMessageHandler::ClearIssue() {
- DVLOG(2) << "ClearIssue";
- web_ui()->CallJavascriptFunctionUnsafe(kSetIssue, base::Value());
-}
-
-void MediaRouterWebUIMessageHandler::UpdateMaxDialogHeight(int height) {
- DVLOG(2) << "UpdateMaxDialogHeight";
- web_ui()->CallJavascriptFunctionUnsafe(kUpdateMaxHeight, base::Value(height));
-}
-
-void MediaRouterWebUIMessageHandler::UpdateMediaRouteStatus(
- const MediaStatus& status) {
- current_media_status_ = base::make_optional<MediaStatus>(MediaStatus(status));
-
- base::DictionaryValue status_value;
- status_value.SetString("title", status.title);
- status_value.SetBoolean("canPlayPause", status.can_play_pause);
- status_value.SetBoolean("canMute", status.can_mute);
- status_value.SetBoolean("canSetVolume", status.can_set_volume);
- status_value.SetBoolean("canSeek", status.can_seek);
- status_value.SetInteger("playState", static_cast<int>(status.play_state));
- status_value.SetBoolean("isMuted", status.is_muted);
- status_value.SetInteger("duration", status.duration.InSeconds());
- status_value.SetInteger("currentTime", status.current_time.InSeconds());
- status_value.SetDouble("volume", status.volume);
-
- if (status.hangouts_extra_data) {
- base::Value hangouts_extra_data(base::Value::Type::DICTIONARY);
- hangouts_extra_data.SetKey(
- "localPresent", base::Value(status.hangouts_extra_data->local_present));
- status_value.SetKey("hangoutsExtraData", std::move(hangouts_extra_data));
- }
-
- if (status.mirroring_extra_data) {
- base::Value mirroring_extra_data(base::Value::Type::DICTIONARY);
- mirroring_extra_data.SetKey(
- "mediaRemotingEnabled",
- base::Value(status.mirroring_extra_data->media_remoting_enabled));
- status_value.SetKey("mirroringExtraData", std::move(mirroring_extra_data));
- }
-
- web_ui()->CallJavascriptFunctionUnsafe(kUpdateRouteStatus,
- std::move(status_value));
-}
-
-void MediaRouterWebUIMessageHandler::OnRouteControllerInvalidated() {
- web_ui()->CallJavascriptFunctionUnsafe(kOnRouteControllerInvalidated);
-}
-
-void MediaRouterWebUIMessageHandler::UserSelectedLocalMediaFile(
- base::FilePath::StringType file_name) {
- DVLOG(2) << "UserSelectedLocalMediaFile";
- web_ui()->CallJavascriptFunctionUnsafe(kUserSelectedLocalMediaFile,
- base::Value(file_name));
-}
-
-void MediaRouterWebUIMessageHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- kRequestInitialData,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnRequestInitialData,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kCreateRoute,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnCreateRoute,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kAcknowledgeFirstRunFlow,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnAcknowledgeFirstRunFlow,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kActOnIssue,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnActOnIssue,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kCloseRoute,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnCloseRoute,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kJoinRoute,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnJoinRoute,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kCloseDialog,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnCloseDialog,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportBlur,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnReportBlur,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportClickedSinkIndex,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnReportClickedSinkIndex,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportFilter,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnReportFilter,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportInitialState,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnReportInitialState,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportInitialAction,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnReportInitialAction,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportRouteCreation,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnReportRouteCreation,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportRouteCreationOutcome,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnReportRouteCreationOutcome,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportSelectedCastMode,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnReportSelectedCastMode,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportNavigateToView,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnReportNavigateToView,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportSinkCount,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnReportSinkCount,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportTimeToClickSink,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnReportTimeToClickSink,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportTimeToInitialActionClose,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnReportTimeToInitialActionClose,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReportWebUIRouteControllerLoaded,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnReportWebUIRouteControllerLoaded,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kSearchSinksAndCreateRoute,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnSearchSinksAndCreateRoute,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kOnInitialDataReceived,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnInitialDataReceived,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kOnMediaControllerAvailable,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnMediaControllerAvailable,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kOnMediaControllerClosed,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnMediaControllerClosed,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kPauseCurrentMedia,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnPauseCurrentMedia,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kPlayCurrentMedia,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnPlayCurrentMedia,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kSeekCurrentMedia,
- base::BindRepeating(&MediaRouterWebUIMessageHandler::OnSeekCurrentMedia,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kSelectLocalMediaFile,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnSelectLocalMediaFile,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kSetCurrentMediaMute,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnSetCurrentMediaMute,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kSetCurrentMediaVolume,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnSetCurrentMediaVolume,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kSetMediaRemotingEnabled,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnSetMediaRemotingEnabled,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kHangoutsSetLocalPresent,
- base::BindRepeating(
- &MediaRouterWebUIMessageHandler::OnSetHangoutsLocalPresent,
- base::Unretained(this)));
-}
-
-void MediaRouterWebUIMessageHandler::OnRequestInitialData(
- const base::ListValue* args) {
- DVLOG(1) << "OnRequestInitialData";
- media_router_ui_->OnUIInitiallyLoaded();
- base::DictionaryValue initial_data;
-
- // "No Cast devices found?" Chromecast help center page.
- initial_data.SetString("deviceMissingUrl",
- base::StringPrintf(kHelpPageUrlPrefix, 3249268));
-
- std::unique_ptr<base::DictionaryValue> sinks_and_identity(
- SinksAndIdentityToValue(media_router_ui_->GetEnabledSinks(),
- GetAccountInfo()));
- initial_data.Set("sinksAndIdentity", std::move(sinks_and_identity));
-
- std::unique_ptr<base::ListValue> routes(RoutesToValue(
- media_router_ui_->routes(), media_router_ui_->joinable_route_ids(),
- media_router_ui_->routes_and_cast_modes()));
- initial_data.Set("routes", std::move(routes));
-
- 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()));
- initial_data.Set("castModes", std::move(cast_modes_list));
-
- // If the cast mode last chosen for the current origin is tab mirroring,
- // that should be the cast mode initially selected in the dialog. Otherwise
- // the initial cast mode should be chosen automatically by the dialog.
- bool use_tab_mirroring =
- base::ContainsKey(cast_modes, MediaCastMode::TAB_MIRROR) &&
- media_router_ui_->UserSelectedTabMirroringForCurrentOrigin();
- initial_data.SetBoolean("useTabMirroring", use_tab_mirroring);
-
- web_ui()->CallJavascriptFunctionUnsafe(kSetInitialData, initial_data);
- media_router_ui_->OnUIInitialized();
-}
-
-void MediaRouterWebUIMessageHandler::OnCreateRoute(
- const base::ListValue* args) {
- DVLOG(1) << "OnCreateRoute";
- const base::DictionaryValue* args_dict = nullptr;
- std::string sink_id;
- int cast_mode_num = -1;
- if (!args->GetDictionary(0, &args_dict) ||
- !args_dict->GetString("sinkId", &sink_id) ||
- !args_dict->GetInteger("selectedCastMode", &cast_mode_num)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
-
- if (sink_id.empty()) {
- DVLOG(1) << "Media Route UI did not respond with a "
- << "valid sink ID. Aborting.";
- return;
- }
-
- if (!IsValidCastModeNum(cast_mode_num)) {
- // TODO(imcheng): Record error condition with UMA.
- DVLOG(1) << "Invalid cast mode: " << cast_mode_num << ". Aborting.";
- return;
- }
-
- MediaRouterUI* media_router_ui =
- static_cast<MediaRouterUI*>(web_ui()->GetController());
- if (media_router_ui->HasPendingRouteRequest()) {
- DVLOG(1) << "UI already has pending route request. Ignoring.";
- IssueInfo issue(
- l10n_util::GetStringUTF8(IDS_MEDIA_ROUTER_ISSUE_PENDING_ROUTE),
- IssueInfo::Action::DISMISS, IssueInfo::Severity::NOTIFICATION);
- media_router_ui_->AddIssue(issue);
- return;
- }
-
- DVLOG(2) << __func__ << ": sink id: " << sink_id
- << ", cast mode: " << cast_mode_num;
-
- // TODO(haibinlu): Pass additional parameters into the CreateRoute request,
- // e.g. low-fps-mirror, user-override. (crbug.com/490364)
- if (!media_router_ui->CreateRoute(
- sink_id, static_cast<MediaCastMode>(cast_mode_num))) {
- DVLOG(1) << "Error initiating route request.";
- }
-}
-
-void MediaRouterWebUIMessageHandler::OnAcknowledgeFirstRunFlow(
- const base::ListValue* args) {
- DVLOG(1) << "OnAcknowledgeFirstRunFlow";
- Profile::FromWebUI(web_ui())->GetPrefs()->SetBoolean(
- ::prefs::kMediaRouterFirstRunFlowAcknowledged, true);
-
- bool enabled_cloud_services = false;
- // Do not set the relevant cloud services prefs if the user was not shown
- // the cloud services prompt.
- if (!args->GetBoolean(0, &enabled_cloud_services)) {
- DVLOG(1) << "User was not shown the enable cloud services prompt.";
- return;
- }
-
- PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
- pref_service->SetBoolean(::prefs::kMediaRouterEnableCloudServices,
- enabled_cloud_services);
- pref_service->SetBoolean(::prefs::kMediaRouterCloudServicesPrefSet, true);
-}
-
-void MediaRouterWebUIMessageHandler::OnActOnIssue(const base::ListValue* args) {
- DVLOG(1) << "OnActOnIssue";
- const base::DictionaryValue* args_dict = nullptr;
- Issue::Id issue_id;
- int action_type_num = -1;
- if (!args->GetDictionary(0, &args_dict) ||
- !args_dict->GetInteger("issueId", &issue_id) ||
- !args_dict->GetInteger("actionType", &action_type_num)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
- if (!IsValidIssueActionTypeNum(action_type_num)) {
- DVLOG(1) << "Invalid action type: " << action_type_num;
- return;
- }
- IssueInfo::Action action_type =
- static_cast<IssueInfo::Action>(action_type_num);
- if (ActOnIssueType(action_type, args_dict))
- DVLOG(1) << "ActOnIssueType failed for Issue ID " << issue_id;
- media_router_ui_->RemoveIssue(issue_id);
-}
-
-void MediaRouterWebUIMessageHandler::OnJoinRoute(const base::ListValue* args) {
- DVLOG(1) << "OnJoinRoute";
- const base::DictionaryValue* args_dict = nullptr;
- std::string route_id;
- std::string sink_id;
- if (!args->GetDictionary(0, &args_dict) ||
- !args_dict->GetString("sinkId", &sink_id) ||
- !args_dict->GetString("routeId", &route_id)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
-
- if (sink_id.empty()) {
- DVLOG(1) << "Media Route UI did not respond with a "
- << "valid sink ID. Aborting.";
- return;
- }
-
- if (route_id.empty()) {
- DVLOG(1) << "Media Route UI did not respond with a "
- << "valid route ID. Aborting.";
- return;
- }
-
- MediaRouterUI* media_router_ui =
- static_cast<MediaRouterUI*>(web_ui()->GetController());
- if (media_router_ui->HasPendingRouteRequest()) {
- DVLOG(1) << "UI already has pending route request. Ignoring.";
- IssueInfo issue(
- l10n_util::GetStringUTF8(IDS_MEDIA_ROUTER_ISSUE_PENDING_ROUTE),
- IssueInfo::Action::DISMISS, IssueInfo::Severity::NOTIFICATION);
- media_router_ui_->AddIssue(issue);
- return;
- }
-
- if (!media_router_ui_->ConnectRoute(sink_id, route_id)) {
- DVLOG(1) << "Error initiating route join request.";
- }
-}
-
-void MediaRouterWebUIMessageHandler::OnCloseRoute(const base::ListValue* args) {
- DVLOG(1) << "OnCloseRoute";
- const base::DictionaryValue* args_dict = nullptr;
- std::string route_id;
- bool is_local = false;
- if (!args->GetDictionary(0, &args_dict) ||
- !args_dict->GetString("routeId", &route_id) ||
- !args_dict->GetBoolean("isLocal", &is_local)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
- media_router_ui_->TerminateRoute(route_id);
- if (is_local) {
- MediaRouterMetrics::RecordStopLocalRoute();
- } else {
- MediaRouterMetrics::RecordStopRemoteRoute();
- }
-}
-
-void MediaRouterWebUIMessageHandler::OnCloseDialog(
- const base::ListValue* args) {
- DVLOG(1) << "OnCloseDialog";
- if (dialog_closing_)
- return;
-
- bool used_esc_to_close_dialog = false;
- if (!args->GetBoolean(0, &used_esc_to_close_dialog)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
-
- if (used_esc_to_close_dialog) {
- base::RecordAction(
- base::UserMetricsAction("MediaRouter_Ui_Dialog_ESCToClose"));
- }
-
- dialog_closing_ = true;
- media_router_ui_->Close();
-}
-
-void MediaRouterWebUIMessageHandler::OnReportBlur(const base::ListValue* args) {
- DVLOG(1) << "OnReportBlur";
- base::RecordAction(base::UserMetricsAction("MediaRouter_Ui_Dialog_Blur"));
-}
-
-void MediaRouterWebUIMessageHandler::OnReportClickedSinkIndex(
- const base::ListValue* args) {
- DVLOG(1) << "OnReportClickedSinkIndex";
- int index;
- if (!args->GetInteger(0, &index)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
- MediaRouterMetrics::RecordStartRouteDeviceIndex(index);
-}
-
-void MediaRouterWebUIMessageHandler::OnReportFilter(const base::ListValue*) {
- DVLOG(1) << "OnReportFilter";
- base::RecordAction(base::UserMetricsAction("MediaRouter_Ui_Action_Filter"));
-}
-
-void MediaRouterWebUIMessageHandler::OnReportInitialAction(
- const base::ListValue* args) {
- DVLOG(1) << "OnReportInitialAction";
- int action;
- if (!args->GetInteger(0, &action)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
- media_router::MediaRouterMetrics::RecordMediaRouterInitialUserAction(
- static_cast<MediaRouterUserAction>(action));
-}
-
-void MediaRouterWebUIMessageHandler::OnReportInitialState(
- const base::ListValue* args) {
- DVLOG(1) << "OnReportInitialState";
- std::string initial_view;
- if (!args->GetString(0, &initial_view)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
- bool sink_list_state = initial_view == "sink-list";
- DCHECK(sink_list_state || (initial_view == "route-details"));
- UMA_HISTOGRAM_BOOLEAN("MediaRouter.Ui.InitialState", sink_list_state);
-}
-
-void MediaRouterWebUIMessageHandler::OnReportNavigateToView(
- const base::ListValue* args) {
- DVLOG(1) << "OnReportNavigateToView";
- std::string view;
- if (!args->GetString(0, &view)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
-
- if (view == "cast-mode-list") {
- base::RecordAction(
- base::UserMetricsAction("MediaRouter_Ui_Navigate_SinkListToSource"));
- } else if (view == "route-details") {
- base::RecordAction(base::UserMetricsAction(
- "MediaRouter_Ui_Navigate_SinkListToRouteDetails"));
- } else if (view == "sink-list") {
- base::RecordAction(base::UserMetricsAction(
- "MediaRouter_Ui_Navigate_RouteDetailsToSinkList"));
- }
-}
-
-void MediaRouterWebUIMessageHandler::OnReportRouteCreation(
- const base::ListValue* args) {
- DVLOG(1) << "OnReportRouteCreation";
- bool route_created_successfully;
- if (!args->GetBoolean(0, &route_created_successfully)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
- MediaRouterMetrics::RecordStartLocalSessionSuccessful(
- route_created_successfully);
-}
-
-void MediaRouterWebUIMessageHandler::OnReportRouteCreationOutcome(
- const base::ListValue* args) {
- DVLOG(1) << "OnReportRouteCreationOutcome";
- int outcome;
- if (!args->GetInteger(0, &outcome)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
-
- media_router::MediaRouterMetrics::RecordRouteCreationOutcome(
- static_cast<MediaRouterRouteCreationOutcome>(outcome));
-}
-
-void MediaRouterWebUIMessageHandler::OnReportSelectedCastMode(
- const base::ListValue* args) {
- DVLOG(1) << "OnReportSelectedCastMode";
- int cast_mode_type;
- if (!args->GetInteger(0, &cast_mode_type)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
- DCHECK(IsValidCastModeNum(cast_mode_type));
- base::UmaHistogramSparse("MediaRouter.Ui.Navigate.SourceSelection",
- cast_mode_type);
- media_router_ui_->RecordCastModeSelection(
- static_cast<MediaCastMode>(cast_mode_type));
-}
-
-void MediaRouterWebUIMessageHandler::OnReportSinkCount(
- const base::ListValue* args) {
- DVLOG(1) << "OnReportSinkCount";
- int sink_count;
- if (!args->GetInteger(0, &sink_count)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
- MediaRouterMetrics::RecordDeviceCount(sink_count);
-}
-
-void MediaRouterWebUIMessageHandler::OnReportTimeToClickSink(
- const base::ListValue* args) {
- DVLOG(1) << "OnReportTimeToClickSink";
- double time_to_click;
- if (!args->GetDouble(0, &time_to_click)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
- MediaRouterMetrics::RecordStartLocalSessionLatency(
- base::TimeDelta::FromMillisecondsD(time_to_click));
-}
-
-void MediaRouterWebUIMessageHandler::OnReportWebUIRouteControllerLoaded(
- const base::ListValue* args) {
- DVLOG(1) << "OnReportWebUIRouteControllerLoaded";
- double load_time;
- if (!args->GetDouble(0, &load_time)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
- UMA_HISTOGRAM_TIMES("MediaRouter.Ui.Dialog.LoadedWebUiRouteController",
- base::TimeDelta::FromMillisecondsD(load_time));
-}
-
-void MediaRouterWebUIMessageHandler::OnReportTimeToInitialActionClose(
- const base::ListValue* args) {
- DVLOG(1) << "OnReportTimeToInitialActionClose";
- double time_to_close;
- if (!args->GetDouble(0, &time_to_close)) {
- DVLOG(1) << "Unable to extract args.";
- return;
- }
- MediaRouterMetrics::RecordCloseDialogLatency(
- base::TimeDelta::FromMillisecondsD(time_to_close));
-}
-
-void MediaRouterWebUIMessageHandler::OnSearchSinksAndCreateRoute(
- const base::ListValue* args) {
- DVLOG(1) << "OnSearchSinksAndCreateRoute";
- const base::DictionaryValue* args_dict = nullptr;
- std::string sink_id;
- std::string search_criteria;
- std::string domain;
- int cast_mode_num = -1;
- if (!args->GetDictionary(0, &args_dict) ||
- !args_dict->GetString("sinkId", &sink_id) ||
- !args_dict->GetString("searchCriteria", &search_criteria) ||
- !args_dict->GetString("domain", &domain) ||
- !args_dict->GetInteger("selectedCastMode", &cast_mode_num)) {
- DVLOG(1) << "Unable to extract args";
- return;
- }
-
- if (search_criteria.empty()) {
- DVLOG(1) << "Media Router UI did not provide valid search criteria. "
- "Aborting.";
- return;
- }
-
- if (!IsValidCastModeNum(cast_mode_num)) {
- DVLOG(1) << "Invalid cast mode: " << cast_mode_num << ". Aborting.";
- return;
- }
-
- media_router_ui_->SearchSinksAndCreateRoute(
- sink_id, search_criteria, domain,
- static_cast<MediaCastMode>(cast_mode_num));
-}
-
-void MediaRouterWebUIMessageHandler::OnSelectLocalMediaFile(
- const base::ListValue* args) {
- media_router_ui_->OpenFileDialog();
-}
-
-void MediaRouterWebUIMessageHandler::OnInitialDataReceived(
- const base::ListValue* args) {
- DVLOG(1) << "OnInitialDataReceived";
- media_router_ui_->OnUIInitialDataReceived();
- MaybeUpdateFirstRunFlowData();
-}
-
-void MediaRouterWebUIMessageHandler::OnMediaControllerAvailable(
- const base::ListValue* args) {
- const base::DictionaryValue* args_dict = nullptr;
- std::string route_id;
- if (!args->GetDictionary(0, &args_dict) ||
- !args_dict->GetString("routeId", &route_id)) {
- DVLOG(1) << "Unable to extract media route ID";
- return;
- }
- media_router_ui_->OnMediaControllerUIAvailable(route_id);
-}
-
-void MediaRouterWebUIMessageHandler::OnMediaControllerClosed(
- const base::ListValue* args) {
- current_media_status_.reset();
- media_router_ui_->OnMediaControllerUIClosed();
-}
-
-void MediaRouterWebUIMessageHandler::OnPauseCurrentMedia(
- const base::ListValue* args) {
- MediaRouteController* route_controller =
- media_router_ui_->GetMediaRouteController();
- if (route_controller)
- route_controller->Pause();
-}
-
-void MediaRouterWebUIMessageHandler::OnPlayCurrentMedia(
- const base::ListValue* args) {
- MediaRouteController* route_controller =
- media_router_ui_->GetMediaRouteController();
- if (route_controller)
- route_controller->Play();
-}
-
-void MediaRouterWebUIMessageHandler::OnSeekCurrentMedia(
- const base::ListValue* args) {
- const base::DictionaryValue* args_dict = nullptr;
- double time;
- if (!args->GetDictionary(0, &args_dict) ||
- !args_dict->GetDouble("time", &time)) {
- DVLOG(1) << "Unable to extract time";
- return;
- }
- base::TimeDelta time_delta = base::TimeDelta::FromSecondsD(time);
- MediaRouteController* route_controller =
- media_router_ui_->GetMediaRouteController();
- if (route_controller && current_media_status_ &&
- time_delta >= base::TimeDelta() &&
- time_delta <= current_media_status_->duration) {
- route_controller->Seek(time_delta);
- }
-}
-
-void MediaRouterWebUIMessageHandler::OnSetCurrentMediaMute(
- const base::ListValue* args) {
- const base::DictionaryValue* args_dict = nullptr;
- bool mute;
- if (!args->GetDictionary(0, &args_dict) ||
- !args_dict->GetBoolean("mute", &mute)) {
- DVLOG(1) << "Unable to extract mute";
- return;
- }
- MediaRouteController* route_controller =
- media_router_ui_->GetMediaRouteController();
- if (route_controller)
- route_controller->SetMute(mute);
-}
-
-void MediaRouterWebUIMessageHandler::OnSetCurrentMediaVolume(
- const base::ListValue* args) {
- const base::DictionaryValue* args_dict = nullptr;
- double volume;
- if (!args->GetDictionary(0, &args_dict) ||
- !args_dict->GetDouble("volume", &volume)) {
- DVLOG(1) << "Unable to extract volume";
- return;
- }
- MediaRouteController* route_controller =
- media_router_ui_->GetMediaRouteController();
- if (route_controller && volume >= 0 && volume <= 1)
- route_controller->SetVolume(volume);
-}
-
-void MediaRouterWebUIMessageHandler::OnSetMediaRemotingEnabled(
- const base::ListValue* args) {
- bool media_remoting_enabled;
- if (!args->GetBoolean(0, &media_remoting_enabled)) {
- DVLOG(1) << "Unable to extract media remoting value";
- return;
- }
- MirroringMediaRouteController* mirroring_controller =
- MirroringMediaRouteController::From(
- media_router_ui_->GetMediaRouteController());
- if (!mirroring_controller) {
- DVLOG(1) << "Unable to get mirroring controller";
- return;
- }
-
- mirroring_controller->SetMediaRemotingEnabled(media_remoting_enabled);
-}
-
-void MediaRouterWebUIMessageHandler::OnSetHangoutsLocalPresent(
- const base::ListValue* args) {
- bool local_present;
- if (!args->GetBoolean(0, &local_present)) {
- DVLOG(1) << "Unable to extract local present";
- return;
- }
- HangoutsMediaRouteController* hangouts_controller =
- HangoutsMediaRouteController::From(
- media_router_ui_->GetMediaRouteController());
- if (!hangouts_controller) {
- DVLOG(1) << "Unable to get hangouts controller";
- return;
- }
-
- hangouts_controller->SetLocalPresent(local_present);
-}
-
-bool MediaRouterWebUIMessageHandler::ActOnIssueType(
- IssueInfo::Action action_type,
- const base::DictionaryValue* args) {
- if (action_type == IssueInfo::Action::LEARN_MORE) {
- std::string learn_more_url = GetLearnMoreUrl(args);
- if (learn_more_url.empty())
- return false;
- auto open_args = std::make_unique<base::ListValue>();
- open_args->AppendString(learn_more_url);
- web_ui()->CallJavascriptFunctionUnsafe(kWindowOpen, *open_args);
- return true;
- } else {
- // Do nothing; no other issue action types require any other action.
- return true;
- }
-}
-
-void MediaRouterWebUIMessageHandler::MaybeUpdateFirstRunFlowData() {
- base::DictionaryValue first_run_flow_data;
-
- Profile* profile = Profile::FromWebUI(web_ui());
- PrefService* pref_service = profile->GetPrefs();
-
- bool first_run_flow_acknowledged =
- pref_service->GetBoolean(::prefs::kMediaRouterFirstRunFlowAcknowledged);
- bool show_cloud_pref = false;
- // Cloud services preference is shown if user is logged in. If the user
- // enables sync after acknowledging the first run flow, this is treated as
- // the user opting into Google services, including cloud services, if the
- // browser is a Chrome branded build.
- if (!pref_service->GetBoolean(::prefs::kMediaRouterCloudServicesPrefSet)) {
- identity::IdentityManager* identity_manager =
- IdentityManagerFactory::GetForProfile(profile);
- if (identity_manager && identity_manager->HasPrimaryAccount()) {
- // If the user had previously acknowledged the first run flow without
- // being shown the cloud services option, and is now logged in with sync
- // enabled, turn on cloud services.
- if (first_run_flow_acknowledged &&
- ProfileSyncServiceFactory::GetForProfile(profile)
- ->IsSyncFeatureActive()) {
- pref_service->SetBoolean(::prefs::kMediaRouterEnableCloudServices,
- true);
- pref_service->SetBoolean(::prefs::kMediaRouterCloudServicesPrefSet,
- true);
- // Return early since the first run flow won't be surfaced.
- return;
- }
-
- show_cloud_pref = true;
- // "Casting to a Hangout from Chrome" Chromecast help center page.
- first_run_flow_data.SetString(
- "firstRunFlowCloudPrefLearnMoreUrl",
- base::StringPrintf(kHelpPageUrlPrefix, 6320939));
- }
- }
-
- // Return early if the first run flow won't be surfaced.
- if (first_run_flow_acknowledged && !show_cloud_pref)
- return;
-
- // General Chromecast learn more page.
- first_run_flow_data.SetString("firstRunFlowLearnMoreUrl",
- kCastLearnMorePageUrl);
- first_run_flow_data.SetBoolean("wasFirstRunFlowAcknowledged",
- first_run_flow_acknowledged);
- first_run_flow_data.SetBoolean("showFirstRunFlowCloudPref", show_cloud_pref);
- web_ui()->CallJavascriptFunctionUnsafe(kSetFirstRunFlowData,
- first_run_flow_data);
-}
-
-AccountInfo MediaRouterWebUIMessageHandler::GetAccountInfo() {
- identity::IdentityManager* identity_manager =
- IdentityManagerFactory::GetForProfile(Profile::FromWebUI(web_ui()));
- if (!identity_manager)
- return AccountInfo();
- base::Optional<AccountInfo> primary_account_info =
- identity_manager->FindExtendedAccountInfoForAccount(
- identity_manager->GetPrimaryAccountInfo());
- return primary_account_info.value_or(AccountInfo{});
-}
-
-int MediaRouterWebUIMessageHandler::CurrentCastModeForRouteId(
- const MediaRoute::Id& route_id,
- const std::unordered_map<MediaRoute::Id, MediaCastMode>& current_cast_modes)
- const {
- auto current_cast_mode_entry = current_cast_modes.find(route_id);
- int current_cast_mode = current_cast_mode_entry != current_cast_modes.end()
- ? current_cast_mode_entry->second
- : -1;
- return current_cast_mode;
-}
-
-std::unique_ptr<base::ListValue> MediaRouterWebUIMessageHandler::RoutesToValue(
- const std::vector<MediaRoute>& routes,
- const std::vector<MediaRoute::Id>& joinable_route_ids,
- const std::unordered_map<MediaRoute::Id, MediaCastMode>& current_cast_modes)
- const {
- auto value = std::make_unique<base::ListValue>();
-
- for (const MediaRoute& route : routes) {
- bool can_join =
- base::ContainsValue(joinable_route_ids, route.media_route_id());
- int current_cast_mode =
- CurrentCastModeForRouteId(route.media_route_id(), current_cast_modes);
- std::unique_ptr<base::DictionaryValue> route_val(
- RouteToValue(route, can_join, incognito_, current_cast_mode));
- value->Append(std::move(route_val));
- }
-
- return value;
-}
-
-void MediaRouterWebUIMessageHandler::SetWebUIForTest(content::WebUI* web_ui) {
- set_web_ui(web_ui);
-}
-
-} // namespace media_router
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h
deleted file mode 100644
index 85d555942c5..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h
+++ /dev/null
@@ -1,181 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_WEBUI_MESSAGE_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_WEBUI_MESSAGE_HANDLER_H_
-
-#include <memory>
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-#include "base/files/file_path.h"
-#include "base/macros.h"
-#include "base/optional.h"
-#include "chrome/browser/ui/media_router/media_cast_mode.h"
-#include "chrome/browser/ui/media_router/media_sink_with_cast_modes.h"
-#include "chrome/common/media_router/issue.h"
-#include "chrome/common/media_router/media_status.h"
-#include "components/signin/core/browser/account_info.h"
-#include "content/public/browser/web_ui_message_handler.h"
-#include "ui/gfx/geometry/size.h"
-
-namespace base {
-class DictionaryValue;
-class ListValue;
-} // namespace base
-
-namespace content {
-class WebUI;
-}
-
-namespace media_router {
-
-class Issue;
-class MediaRoute;
-class MediaRouterUI;
-
-// The handler for Javascript messages related to the media router dialog.
-class MediaRouterWebUIMessageHandler : public content::WebUIMessageHandler {
- public:
- explicit MediaRouterWebUIMessageHandler(MediaRouterUI* media_router_ui);
- ~MediaRouterWebUIMessageHandler() override;
-
- // Methods to update the status displayed by the dialog.
- virtual void UpdateSinks(const std::vector<MediaSinkWithCastModes>& sinks);
- void UpdateRoutes(const std::vector<MediaRoute>& routes,
- const std::vector<MediaRoute::Id>& joinable_route_ids,
- const std::unordered_map<MediaRoute::Id, MediaCastMode>&
- current_cast_modes);
- // Overridden in tests.
- virtual void UpdateCastModes(const CastModeSet& cast_modes,
- const std::string& source_host,
- base::Optional<MediaCastMode> forced_cast_mode);
- void OnCreateRouteResponseReceived(const MediaSink::Id& sink_id,
- const MediaRoute* route);
- void ReturnSearchResult(const std::string& sink_id);
-
- virtual void UpdateIssue(const Issue& issue);
- void ClearIssue();
-
- // Updates the maximum dialog height to allow the WebUI properly scale when
- // the browser window changes.
- void UpdateMaxDialogHeight(int height);
-
- // Notifies the WebUI with an updated MediaStatus. Overridden in tests.
- virtual void UpdateMediaRouteStatus(const MediaStatus& status);
-
- // Notifies the WebUI that the controller for the selected route has been
- // invalidated.
- void OnRouteControllerInvalidated();
-
- // Called when the user has selected a file and the name should be relayed to
- // the UI.
- void UserSelectedLocalMediaFile(base::FilePath::StringType file_name);
-
- void SetWebUIForTest(content::WebUI* webui);
- void set_incognito_for_test(bool incognito) { incognito_ = incognito; }
-
- private:
- FRIEND_TEST_ALL_PREFIXES(MediaRouterWebUIMessageHandlerTest,
- RecordCastModeSelection);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterWebUIMessageHandlerTest,
- RetrieveCastModeSelection);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterWebUIMessageHandlerTest,
- OnRouteDetailsOpenedAndClosed);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterWebUIMessageHandlerTest,
- OnMediaCommandsReceived);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterWebUIMessageHandlerTest,
- OnInvalidMediaCommandsReceived);
- FRIEND_TEST_ALL_PREFIXES(MediaRouterWebUIMessageHandlerTest,
- OnSetMediaRemotingEnabled);
-
- // WebUIMessageHandler implementation.
- void RegisterMessages() override;
-
- // Handlers for JavaScript messages.
- // See media_router_ui_interface.js for documentation on parameters.
- void OnRequestInitialData(const base::ListValue* args);
- void OnCreateRoute(const base::ListValue* args);
- void OnAcknowledgeFirstRunFlow(const base::ListValue* args);
- void OnActOnIssue(const base::ListValue* args);
- void OnCloseRoute(const base::ListValue* args);
- void OnJoinRoute(const base::ListValue* args);
- void OnCloseDialog(const base::ListValue* args);
- void OnReportBlur(const base::ListValue* args);
- void OnReportClickedSinkIndex(const base::ListValue* args);
- void OnReportFilter(const base::ListValue* args);
- void OnReportInitialAction(const base::ListValue* args);
- void OnReportInitialState(const base::ListValue* args);
- void OnReportNavigateToView(const base::ListValue* args);
- void OnReportRouteCreation(const base::ListValue* args);
- void OnReportRouteCreationOutcome(const base::ListValue* args);
- void OnReportSelectedCastMode(const base::ListValue* args);
- void OnReportSinkCount(const base::ListValue* args);
- void OnReportTimeToClickSink(const base::ListValue* args);
- void OnReportWebUIRouteControllerLoaded(const base::ListValue* args);
- void OnReportTimeToInitialActionClose(const base::ListValue* args);
- void OnMediaControllerAvailable(const base::ListValue* args);
- void OnMediaControllerClosed(const base::ListValue* args);
- void OnSearchSinksAndCreateRoute(const base::ListValue* args);
- void OnSelectLocalMediaFile(const base::ListValue* args);
- void OnInitialDataReceived(const base::ListValue* args);
-
- // Handlers for JavaScript messages to control the media.
- void OnPlayCurrentMedia(const base::ListValue* args);
- void OnPauseCurrentMedia(const base::ListValue* args);
- void OnSeekCurrentMedia(const base::ListValue* args);
- void OnSetCurrentMediaMute(const base::ListValue* args);
- void OnSetCurrentMediaVolume(const base::ListValue* args);
- void OnSetHangoutsLocalPresent(const base::ListValue* args);
- void OnSetMediaRemotingEnabled(const base::ListValue* args);
-
- // Performs an action for an Issue of |type|.
- // |args| contains additional parameter that varies based on |type|.
- // Returns |true| if the action was successfully performed.
- bool ActOnIssueType(IssueInfo::Action type,
- const base::DictionaryValue* args);
-
- // May update the first run flow related properties in the WebUI. This is
- // called after the initial data is received to avoid unnecessary work when
- // initializing the WebUI.
- void MaybeUpdateFirstRunFlowData();
-
- // Returns the current cast mode for the route with ID |route_id| or -1 if the
- // route has no current cast mode.
- int CurrentCastModeForRouteId(
- const MediaRoute::Id& route_id,
- const std::unordered_map<MediaRoute::Id, MediaCastMode>&
- current_cast_modes) const;
-
- // Converts |routes| and |joinable_route_ids| into base::ListValue that can be
- // passed to WebUI.
- std::unique_ptr<base::ListValue> RoutesToValue(
- const std::vector<MediaRoute>& routes,
- const std::vector<MediaRoute::Id>& joinable_route_ids,
- const std::unordered_map<MediaRoute::Id, MediaCastMode>&
- current_cast_modes) const;
-
- // Retrieve the account info for email and domain of signed in users. This is
- // used when updating sinks to determine if identity should be displayed.
- // Marked virtual for tests.
- virtual AccountInfo GetAccountInfo();
-
- // |true| if the associated Profile is incognito.
- bool incognito_;
-
- // Keeps track of whether a command to close the dialog has been issued.
- bool dialog_closing_;
-
- // The media status currently shown in the UI.
- base::Optional<MediaStatus> current_media_status_;
-
- MediaRouterUI* media_router_ui_;
-
- DISALLOW_COPY_AND_ASSIGN(MediaRouterWebUIMessageHandler);
-};
-
-} // namespace media_router
-
-#endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_ROUTER_WEBUI_MESSAGE_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc b/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc
deleted file mode 100644
index 57df58579c7..00000000000
--- a/chromium/chrome/browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc
+++ /dev/null
@@ -1,691 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/ui/webui/media_router/media_router_webui_message_handler.h"
-
-#include <memory>
-#include <set>
-#include <utility>
-
-#include "base/macros.h"
-#include "base/strings/stringprintf.h"
-#include "chrome/browser/media/router/test/media_router_mojo_test.h"
-#include "chrome/browser/media/router/test/mock_media_router.h"
-#include "chrome/browser/ui/browser_commands.h"
-#include "chrome/browser/ui/tabs/tab_strip_model.h"
-#include "chrome/browser/ui/webui/media_router/media_router_ui.h"
-#include "chrome/browser/ui/webui/media_router/media_router_web_ui_test.h"
-#include "content/public/browser/browser_context.h"
-#include "content/public/test/test_web_ui.h"
-#include "extensions/common/constants.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-using testing::_;
-using testing::Return;
-using testing::ReturnRef;
-
-namespace media_router {
-
-namespace {
-
-const char kUserEmailForTesting[] = "nobody@example.com";
-const char kUserDomainForTesting[] = "example.com";
-
-bool GetBooleanFromDict(const base::DictionaryValue* dict,
- const std::string& key) {
- bool value = false;
- EXPECT_TRUE(dict->GetBoolean(key, &value));
- return value;
-}
-
-double GetDoubleFromDict(const base::DictionaryValue* dict,
- const std::string& key) {
- double value = 0;
- EXPECT_TRUE(dict->GetDouble(key, &value));
- return value;
-}
-
-int GetIntegerFromDict(const base::DictionaryValue* dict,
- const std::string& key) {
- int value = 0;
- EXPECT_TRUE(dict->GetInteger(key, &value));
- return value;
-}
-
-std::string GetStringFromDict(const base::DictionaryValue* dict,
- const std::string& key) {
- std::string value;
- EXPECT_TRUE(dict->GetString(key, &value));
- return value;
-}
-
-// Creates a local route for display.
-MediaRoute CreateRoute() {
- MediaRoute::Id route_id("routeId123");
- MediaSink::Id sink_id("sinkId123");
- MediaSink sink(sink_id, "The sink", SinkIconType::CAST);
- std::string description("This is a route");
- bool is_local = true;
- bool is_for_display = true;
- MediaRoute route(route_id, MediaSource("mediaSource"), sink_id, description,
- is_local, is_for_display);
-
- return route;
-}
-
-MediaSinkWithCastModes CreateMediaSinkWithCastMode(const std::string& sink_id,
- MediaCastMode cast_mode) {
- std::string sink_name("The sink");
- MediaSinkWithCastModes media_sink_with_cast_modes(
- MediaSink(sink_id, sink_name, SinkIconType::CAST));
- media_sink_with_cast_modes.cast_modes.insert(cast_mode);
-
- return media_sink_with_cast_modes;
-}
-
-} // namespace
-
-class MockMediaRouterUI : public MediaRouterUI {
- public:
- explicit MockMediaRouterUI(content::WebUI* web_ui)
- : MediaRouterUI(web_ui) {}
- ~MockMediaRouterUI() override {}
-
- MOCK_METHOD0(OnUIInitialized, void());
- MOCK_CONST_METHOD0(UserSelectedTabMirroringForCurrentOrigin, bool());
- MOCK_METHOD1(RecordCastModeSelection, void(MediaCastMode cast_mode));
- MOCK_CONST_METHOD0(GetPresentationRequestSourceName, std::string());
- MOCK_CONST_METHOD0(GetCastModes, const std::set<MediaCastMode>&());
- MOCK_METHOD1(OnMediaControllerUIAvailable,
- void(const MediaRoute::Id& route_id));
- MOCK_METHOD0(OnMediaControllerUIClosed, void());
- MOCK_METHOD0(PlayRoute, void());
- MOCK_METHOD0(PauseRoute, void());
- MOCK_METHOD1(SeekRoute, void(base::TimeDelta time));
- MOCK_METHOD1(SetRouteMute, void(bool mute));
- MOCK_METHOD1(SetRouteVolume, void(float volume));
- MOCK_CONST_METHOD0(GetMediaRouteController, MediaRouteController*());
-};
-
-class TestMediaRouterWebUIMessageHandler
- : public MediaRouterWebUIMessageHandler {
- public:
- explicit TestMediaRouterWebUIMessageHandler(MediaRouterUI* media_router_ui)
- : MediaRouterWebUIMessageHandler(media_router_ui),
- email_(kUserEmailForTesting),
- domain_(kUserDomainForTesting) {}
- ~TestMediaRouterWebUIMessageHandler() override = default;
-
- AccountInfo GetAccountInfo() override {
- AccountInfo info = AccountInfo();
- info.account_id = info.gaia = info.email = email_;
- info.hosted_domain = domain_;
- info.full_name = info.given_name = "name";
- info.locale = "locale";
- info.picture_url = "picture";
-
- return info;
- }
-
- void SetEmailAndDomain(const std::string& email, const std::string& domain) {
- email_ = email;
- domain_ = domain;
- }
-
- private:
- std::string email_;
- std::string domain_;
-};
-
-class MediaRouterWebUIMessageHandlerTest : public MediaRouterWebUITest {
- public:
- MediaRouterWebUIMessageHandlerTest()
- : web_ui_(std::make_unique<content::TestWebUI>()) {}
- ~MediaRouterWebUIMessageHandlerTest() override {}
-
- // BrowserWithTestWindowTest:
- void SetUp() override {
- BrowserWithTestWindowTest::SetUp();
- chrome::NewTab(browser());
- web_ui_->set_web_contents(
- browser()->tab_strip_model()->GetActiveWebContents());
- mock_media_router_ui_ = std::make_unique<MockMediaRouterUI>(web_ui_.get());
- handler_ = std::make_unique<TestMediaRouterWebUIMessageHandler>(
- mock_media_router_ui_.get());
- handler_->SetWebUIForTest(web_ui_.get());
- }
-
- void TearDown() override {
- handler_.reset();
- mock_media_router_ui_.reset();
- web_ui_.reset();
- BrowserWithTestWindowTest::TearDown();
- }
-
- const std::string& provider_extension_id() const {
- return provider_extension_id_;
- }
-
- // 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_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();
- }
-
- // Gets the dictionary passed into a call to the |web_ui_| as the argument.
- // There needs to be one call made, and its function name must be
- // |function_name|.
- const base::DictionaryValue* ExtractDictFromCallArg(
- const std::string& function_name) {
- const base::DictionaryValue* dict_value = nullptr;
- CHECK(GetCallData(function_name)->GetAsDictionary(&dict_value));
- return dict_value;
- }
-
- // Gets the list passed into a call to the |web_ui_| as the argument.
- // There needs to be one call made, and its function name must be
- // |function_name|.
- const base::ListValue* ExtractListFromCallArg(
- const std::string& function_name) {
- const base::ListValue* list_value = nullptr;
- CHECK(GetCallData(function_name)->GetAsList(&list_value));
- return list_value;
- }
-
- // Gets the first element of the list passed in as the argument to a call to
- // the |web_ui_| as a dictionary. There needs to be one call made, and its
- // function name must be |function_name|.
- const base::DictionaryValue* ExtractDictFromListFromCallArg(
- const std::string& function_name) {
- const base::ListValue* list_value = nullptr;
- CHECK(GetCallData(function_name)->GetAsList(&list_value));
- const base::DictionaryValue* dict_value = nullptr;
- CHECK(list_value->GetDictionary(0, &dict_value));
- return dict_value;
- }
-
- MockMediaRouter* router() { return &router_; }
-
- protected:
- std::unique_ptr<content::TestWebUI> web_ui_;
- MockMediaRouter router_;
- std::unique_ptr<MockMediaRouterUI> mock_media_router_ui_;
- std::unique_ptr<TestMediaRouterWebUIMessageHandler> handler_;
- const std::string provider_extension_id_;
-};
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateSinks) {
- MediaSink::Id sink_id("sinkId123");
- MediaSinkWithCastModes media_sink_with_cast_modes =
- CreateMediaSinkWithCastMode(sink_id, MediaCastMode::TAB_MIRROR);
-
- handler_->UpdateSinks({media_sink_with_cast_modes});
- const base::DictionaryValue* sinks_with_identity_value =
- ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
-
- // Email is not displayed if there is no sinks with domain.
- EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showEmail"));
-
- // Domain is not displayed if there is no sinks with domain.
- EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showDomain"));
-
- const base::ListValue* sinks_list_value = nullptr;
- ASSERT_TRUE(sinks_with_identity_value->GetList("sinks", &sinks_list_value));
- const base::DictionaryValue* sink_value = nullptr;
- ASSERT_TRUE(sinks_list_value->GetDictionary(0, &sink_value));
-
- EXPECT_EQ(sink_id, GetStringFromDict(sink_value, "id"));
- EXPECT_EQ(media_sink_with_cast_modes.sink.name(),
- GetStringFromDict(sink_value, "name"));
- EXPECT_EQ(static_cast<int>(MediaCastMode::TAB_MIRROR),
- GetIntegerFromDict(sink_value, "castModes"));
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateSinksWithIdentity) {
- MediaSinkWithCastModes media_sink_with_cast_modes =
- CreateMediaSinkWithCastMode("sinkId123", MediaCastMode::TAB_MIRROR);
- media_sink_with_cast_modes.sink.set_domain(kUserDomainForTesting);
-
- handler_->UpdateSinks({media_sink_with_cast_modes});
- const base::DictionaryValue* sinks_with_identity_value =
- ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
-
- EXPECT_TRUE(GetBooleanFromDict(sinks_with_identity_value, "showEmail"));
- // Sink domain is not displayed if it matches user domain.
- EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showDomain"));
- EXPECT_EQ(kUserEmailForTesting,
- GetStringFromDict(sinks_with_identity_value, "userEmail"));
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest,
- UpdateSinksWithIdentityAndPseudoSink) {
- MediaSinkWithCastModes media_sink_with_cast_modes =
- CreateMediaSinkWithCastMode("pseudo:sinkId1", MediaCastMode::TAB_MIRROR);
- media_sink_with_cast_modes.sink.set_domain(kUserDomainForTesting);
-
- handler_->UpdateSinks({media_sink_with_cast_modes});
- const base::DictionaryValue* sinks_with_identity_value =
- ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
-
- EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showEmail"));
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateSinksWithIdentityAndDomain) {
- MediaSinkWithCastModes media_sink_with_cast_modes =
- CreateMediaSinkWithCastMode("sinkId123", MediaCastMode::TAB_MIRROR);
- std::string domain_name("google.com");
- media_sink_with_cast_modes.sink.set_domain(domain_name);
-
- handler_->UpdateSinks({media_sink_with_cast_modes});
- const base::DictionaryValue* sinks_with_identity_value =
- ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
-
- // Domain is displayed for sinks with domains that are not the user domain.
- EXPECT_TRUE(GetBooleanFromDict(sinks_with_identity_value, "showDomain"));
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateSinksWithNoDomain) {
- MediaSinkWithCastModes media_sink_with_cast_modes =
- CreateMediaSinkWithCastMode("sinkId123", MediaCastMode::TAB_MIRROR);
- std::string user_email("nobody@gmail.com");
- std::string user_domain("NO_HOSTED_DOMAIN");
- std::string domain_name("default");
- media_sink_with_cast_modes.sink.set_domain(domain_name);
-
- handler_->SetEmailAndDomain(user_email, user_domain);
- handler_->UpdateSinks({media_sink_with_cast_modes});
- const base::DictionaryValue* sinks_with_identity_value =
- ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
-
- const base::ListValue* sinks_list_value = nullptr;
- ASSERT_TRUE(sinks_with_identity_value->GetList("sinks", &sinks_list_value));
- const base::DictionaryValue* sink_value = nullptr;
- ASSERT_TRUE(sinks_list_value->GetDictionary(0, &sink_value));
-
- // Domain should not be shown if there were only default sink domains.
- EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showDomain"));
-
- // Sink domain should be empty if user has no hosted domain.
- EXPECT_EQ(std::string(), GetStringFromDict(sink_value, "domain"));
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateSinksWithDefaultDomain) {
- MediaSinkWithCastModes media_sink_with_cast_modes =
- CreateMediaSinkWithCastMode("sinkId123", MediaCastMode::TAB_MIRROR);
- std::string domain_name("default");
- media_sink_with_cast_modes.sink.set_domain(domain_name);
-
- handler_->UpdateSinks({media_sink_with_cast_modes});
- const base::DictionaryValue* sinks_with_identity_value =
- ExtractDictFromCallArg("media_router.ui.setSinkListAndIdentity");
-
- const base::ListValue* sinks_list_value = nullptr;
- ASSERT_TRUE(sinks_with_identity_value->GetList("sinks", &sinks_list_value));
- const base::DictionaryValue* sink_value = nullptr;
- ASSERT_TRUE(sinks_list_value->GetDictionary(0, &sink_value));
-
- // Domain should not be shown if there were only default sink domains.
- EXPECT_FALSE(GetBooleanFromDict(sinks_with_identity_value, "showDomain"));
-
- // Sink domain should be updated from 'default' to user domain.
- EXPECT_EQ(kUserDomainForTesting, GetStringFromDict(sink_value, "domain"));
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateRoutes) {
- const MediaRoute route = CreateRoute();
- std::vector<MediaRoute::Id> joinable_route_ids = {route.media_route_id()};
- std::unordered_map<MediaRoute::Id, MediaCastMode> current_cast_modes;
- current_cast_modes.insert(
- std::make_pair(route.media_route_id(), MediaCastMode::PRESENTATION));
-
- handler_->UpdateRoutes({route}, joinable_route_ids, current_cast_modes);
- const base::DictionaryValue* route_value =
- ExtractDictFromListFromCallArg("media_router.ui.setRouteList");
-
- EXPECT_EQ(route.media_route_id(), GetStringFromDict(route_value, "id"));
- EXPECT_EQ(route.media_sink_id(), GetStringFromDict(route_value, "sinkId"));
- EXPECT_EQ(route.description(), GetStringFromDict(route_value, "description"));
- EXPECT_EQ(route.is_local(), GetBooleanFromDict(route_value, "isLocal"));
- EXPECT_TRUE(GetBooleanFromDict(route_value, "canJoin"));
- EXPECT_EQ(MediaCastMode::PRESENTATION,
- GetIntegerFromDict(route_value, "currentCastMode"));
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateRoutesIncognito) {
- handler_->set_incognito_for_test(true);
- const MediaRoute route = CreateRoute();
-
- handler_->UpdateRoutes({route}, std::vector<MediaRoute::Id>(),
- std::unordered_map<MediaRoute::Id, MediaCastMode>());
- const base::DictionaryValue* route_value =
- ExtractDictFromListFromCallArg("media_router.ui.setRouteList");
-
- EXPECT_EQ(route.media_route_id(), GetStringFromDict(route_value, "id"));
- EXPECT_EQ(route.media_sink_id(), GetStringFromDict(route_value, "sinkId"));
- EXPECT_EQ(route.description(), GetStringFromDict(route_value, "description"));
- EXPECT_EQ(route.is_local(), GetBooleanFromDict(route_value, "isLocal"));
- EXPECT_FALSE(GetBooleanFromDict(route_value, "canJoin"));
-
- int actual_current_cast_mode = -1;
- EXPECT_FALSE(
- route_value->GetInteger("currentCastMode", &actual_current_cast_mode));
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, SetCastModesList) {
- CastModeSet cast_modes({MediaCastMode::PRESENTATION,
- MediaCastMode::TAB_MIRROR,
- MediaCastMode::DESKTOP_MIRROR});
- handler_->UpdateCastModes(cast_modes, "www.host.com",
- MediaCastMode::PRESENTATION);
- const base::ListValue* set_cast_mode_list =
- ExtractListFromCallArg("media_router.ui.setCastModeList");
-
- const base::DictionaryValue* cast_mode = nullptr;
- size_t index = 0;
- for (auto i = cast_modes.begin(); i != cast_modes.end(); i++) {
- CHECK(set_cast_mode_list->GetDictionary(index++, &cast_mode));
- EXPECT_EQ(static_cast<int>(*i), GetIntegerFromDict(cast_mode, "type"));
- EXPECT_EQ(MediaCastModeToDescription(*i, "www.host.com"),
- GetStringFromDict(cast_mode, "description"));
- EXPECT_EQ("www.host.com", GetStringFromDict(cast_mode, "host"));
- EXPECT_EQ(*i == MediaCastMode::PRESENTATION,
- GetBooleanFromDict(cast_mode, "isForced"));
- }
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateMediaRouteStatus) {
- MediaStatus status;
- status.title = "test title";
- status.can_play_pause = true;
- status.can_set_volume = true;
- status.play_state = MediaStatus::PlayState::BUFFERING;
- status.duration = base::TimeDelta::FromSeconds(90);
- status.current_time = base::TimeDelta::FromSeconds(80);
- status.volume = 0.9;
- // |status.hangouts_extra_data->local_present| defaults to |false|.
- status.hangouts_extra_data.emplace();
- status.mirroring_extra_data.emplace(true);
-
- handler_->UpdateMediaRouteStatus(status);
- const base::DictionaryValue* status_value =
- ExtractDictFromCallArg("media_router.ui.updateRouteStatus");
-
- EXPECT_EQ(status.title, GetStringFromDict(status_value, "title"));
- EXPECT_EQ(status.can_play_pause,
- GetBooleanFromDict(status_value, "canPlayPause"));
- EXPECT_EQ(status.can_mute, GetBooleanFromDict(status_value, "canMute"));
- EXPECT_EQ(status.can_set_volume,
- GetBooleanFromDict(status_value, "canSetVolume"));
- EXPECT_EQ(status.can_seek, GetBooleanFromDict(status_value, "canSeek"));
- EXPECT_EQ(static_cast<int>(status.play_state),
- GetIntegerFromDict(status_value, "playState"));
- EXPECT_EQ(status.is_muted, GetBooleanFromDict(status_value, "isMuted"));
- EXPECT_EQ(status.duration.InSeconds(),
- GetIntegerFromDict(status_value, "duration"));
- EXPECT_EQ(status.current_time.InSeconds(),
- GetIntegerFromDict(status_value, "currentTime"));
- EXPECT_EQ(status.volume, GetDoubleFromDict(status_value, "volume"));
-
- const base::Value* hangouts_extra_data = status_value->FindKeyOfType(
- "hangoutsExtraData", base::Value::Type::DICTIONARY);
- ASSERT_TRUE(hangouts_extra_data);
- const base::Value* local_present_value = hangouts_extra_data->FindKeyOfType(
- "localPresent", base::Value::Type::BOOLEAN);
- ASSERT_TRUE(local_present_value);
- EXPECT_FALSE(local_present_value->GetBool());
-
- const base::Value* mirroring_extra_data = status_value->FindKeyOfType(
- "mirroringExtraData", base::Value::Type::DICTIONARY);
- ASSERT_TRUE(mirroring_extra_data);
- const base::Value* media_remoting_value = mirroring_extra_data->FindKeyOfType(
- "mediaRemotingEnabled", base::Value::Type::BOOLEAN);
- ASSERT_TRUE(media_remoting_value);
- EXPECT_TRUE(media_remoting_value->GetBool());
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, OnCreateRouteResponseReceived) {
- MediaRoute route = CreateRoute();
- bool incognito = false;
- route.set_incognito(incognito);
-
- handler_->OnCreateRouteResponseReceived(route.media_sink_id(), &route);
-
- const content::TestWebUI::CallData& call_data = *web_ui_->call_data()[0];
- EXPECT_EQ("media_router.ui.onCreateRouteResponseReceived",
- call_data.function_name());
- std::string sink_id_value;
- ASSERT_TRUE(call_data.arg1()->GetAsString(&sink_id_value));
- EXPECT_EQ(route.media_sink_id(), sink_id_value);
-
- const base::DictionaryValue* route_value = nullptr;
- ASSERT_TRUE(call_data.arg2()->GetAsDictionary(&route_value));
- EXPECT_EQ(route.media_route_id(), GetStringFromDict(route_value, "id"));
- EXPECT_EQ(route.media_sink_id(), GetStringFromDict(route_value, "sinkId"));
- EXPECT_EQ(route.description(), GetStringFromDict(route_value, "description"));
- EXPECT_EQ(route.is_local(), GetBooleanFromDict(route_value, "isLocal"));
-
- bool route_for_display = false;
- ASSERT_TRUE(call_data.arg3()->GetAsBoolean(&route_for_display));
- EXPECT_TRUE(route_for_display);
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest,
- OnCreateRouteResponseReceivedIncognito) {
- handler_->set_incognito_for_test(true);
- MediaRoute route = CreateRoute();
- bool incognito = true;
- route.set_incognito(incognito);
-
- handler_->OnCreateRouteResponseReceived(route.media_sink_id(), &route);
-
- const content::TestWebUI::CallData& call_data = *web_ui_->call_data()[0];
- EXPECT_EQ("media_router.ui.onCreateRouteResponseReceived",
- call_data.function_name());
- std::string sink_id_value;
- ASSERT_TRUE(call_data.arg1()->GetAsString(&sink_id_value));
- EXPECT_EQ(route.media_sink_id(), sink_id_value);
-
- const base::DictionaryValue* route_value = nullptr;
- ASSERT_TRUE(call_data.arg2()->GetAsDictionary(&route_value));
- EXPECT_EQ(route.media_route_id(), GetStringFromDict(route_value, "id"));
- EXPECT_EQ(route.media_sink_id(), GetStringFromDict(route_value, "sinkId"));
- EXPECT_EQ(route.description(), GetStringFromDict(route_value, "description"));
- EXPECT_EQ(route.is_local(), GetBooleanFromDict(route_value, "isLocal"));
-
- bool route_for_display = false;
- ASSERT_TRUE(call_data.arg3()->GetAsBoolean(&route_for_display));
- EXPECT_TRUE(route_for_display);
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, UpdateIssue) {
- std::string issue_title("An issue");
- std::string issue_message("This is an issue");
- IssueInfo::Action default_action = IssueInfo::Action::LEARN_MORE;
- std::vector<IssueInfo::Action> secondary_actions;
- secondary_actions.push_back(IssueInfo::Action::DISMISS);
- MediaRoute::Id route_id("routeId123");
- IssueInfo info(issue_title, default_action, IssueInfo::Severity::FATAL);
- info.message = issue_message;
- info.secondary_actions = secondary_actions;
- info.route_id = route_id;
- Issue issue(info);
- const Issue::Id& issue_id = issue.id();
-
- handler_->UpdateIssue(issue);
- const base::DictionaryValue* issue_value =
- ExtractDictFromCallArg("media_router.ui.setIssue");
-
- // Initialized to invalid issue id.
- EXPECT_EQ(issue_id, GetIntegerFromDict(issue_value, "id"));
- EXPECT_EQ(issue_title, GetStringFromDict(issue_value, "title"));
- EXPECT_EQ(issue_message, GetStringFromDict(issue_value, "message"));
-
- // Initialized to invalid action type.
- EXPECT_EQ(static_cast<int>(default_action),
- GetIntegerFromDict(issue_value, "defaultActionType"));
- EXPECT_EQ(static_cast<int>(secondary_actions[0]),
- GetIntegerFromDict(issue_value, "secondaryActionType"));
- EXPECT_EQ(route_id, GetStringFromDict(issue_value, "routeId"));
-
- // The issue is blocking since it is FATAL.
- EXPECT_TRUE(GetBooleanFromDict(issue_value, "isBlocking"));
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, RecordCastModeSelection) {
- base::ListValue args;
- args.AppendInteger(MediaCastMode::PRESENTATION);
- EXPECT_CALL(*mock_media_router_ui_,
- RecordCastModeSelection(MediaCastMode::PRESENTATION))
- .Times(1);
- handler_->OnReportSelectedCastMode(&args);
-
- args.Clear();
- args.AppendInteger(MediaCastMode::TAB_MIRROR);
- EXPECT_CALL(*mock_media_router_ui_,
- RecordCastModeSelection(MediaCastMode::TAB_MIRROR))
- .Times(1);
- handler_->OnReportSelectedCastMode(&args);
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, RetrieveCastModeSelection) {
- base::ListValue args;
- std::set<MediaCastMode> cast_modes = {MediaCastMode::TAB_MIRROR};
- EXPECT_CALL(*mock_media_router_ui_, GetCastModes())
- .WillRepeatedly(ReturnRef(cast_modes));
-
- EXPECT_CALL(*mock_media_router_ui_, GetPresentationRequestSourceName())
- .WillRepeatedly(Return("source"));
- EXPECT_CALL(*mock_media_router_ui_,
- UserSelectedTabMirroringForCurrentOrigin())
- .WillOnce(Return(true));
- handler_->OnRequestInitialData(&args);
- const content::TestWebUI::CallData& call_data1 = *web_ui_->call_data()[0];
- ASSERT_EQ("media_router.ui.setInitialData", call_data1.function_name());
- const base::DictionaryValue* initial_data = nullptr;
- ASSERT_TRUE(call_data1.arg1()->GetAsDictionary(&initial_data));
- EXPECT_TRUE(GetBooleanFromDict(initial_data, "useTabMirroring"));
-
- EXPECT_CALL(*mock_media_router_ui_,
- UserSelectedTabMirroringForCurrentOrigin())
- .WillOnce(Return(false));
- handler_->OnRequestInitialData(&args);
- const content::TestWebUI::CallData& call_data2 = *web_ui_->call_data()[1];
- ASSERT_EQ("media_router.ui.setInitialData", call_data2.function_name());
- ASSERT_TRUE(call_data2.arg1()->GetAsDictionary(&initial_data));
- EXPECT_FALSE(GetBooleanFromDict(initial_data, "useTabMirroring"));
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, OnRouteDetailsOpenedAndClosed) {
- const std::string route_id = "routeId123";
- base::ListValue args_list;
- base::DictionaryValue* args;
- args_list.Append(std::make_unique<base::DictionaryValue>());
- args_list.GetDictionary(0, &args);
- args->SetString("routeId", route_id);
-
- EXPECT_CALL(*mock_media_router_ui_, OnMediaControllerUIAvailable(route_id));
- handler_->OnMediaControllerAvailable(&args_list);
-
- args_list.Clear();
- EXPECT_CALL(*mock_media_router_ui_, OnMediaControllerUIClosed());
- handler_->OnMediaControllerClosed(&args_list);
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, OnMediaCommandsReceived) {
- auto controller = base::MakeRefCounted<MockMediaRouteController>(
- "routeId", profile(), router());
- EXPECT_CALL(*mock_media_router_ui_, GetMediaRouteController())
- .WillRepeatedly(Return(controller.get()));
- MediaStatus status;
- status.duration = base::TimeDelta::FromSeconds(100);
- handler_->UpdateMediaRouteStatus(status);
-
- base::ListValue args_list;
-
- EXPECT_CALL(*controller, Play());
- handler_->OnPlayCurrentMedia(&args_list);
-
- EXPECT_CALL(*controller, Pause());
- handler_->OnPauseCurrentMedia(&args_list);
-
- base::DictionaryValue* args;
- args_list.Append(std::make_unique<base::DictionaryValue>());
- args_list.GetDictionary(0, &args);
-
- const double time = 50.1;
- args->SetDouble("time", time);
- EXPECT_CALL(*controller, Seek(base::TimeDelta::FromSecondsD(time)));
- handler_->OnSeekCurrentMedia(&args_list);
-
- args->Clear();
- args->SetBoolean("mute", true);
- EXPECT_CALL(*controller, SetMute(true));
- handler_->OnSetCurrentMediaMute(&args_list);
-
- const double volume = 0.4;
- args->Clear();
- args->SetDouble("volume", volume);
- EXPECT_CALL(*controller, SetVolume(volume));
- handler_->OnSetCurrentMediaVolume(&args_list);
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, OnSetMediaRemotingEnabled) {
- auto controller = base::MakeRefCounted<MirroringMediaRouteController>(
- "routeId", profile(), router());
- EXPECT_CALL(*mock_media_router_ui_, GetMediaRouteController())
- .WillRepeatedly(Return(controller.get()));
-
- base::ListValue args_list;
- args_list.GetList().emplace_back(false);
- handler_->OnSetMediaRemotingEnabled(&args_list);
- EXPECT_FALSE(controller->media_remoting_enabled());
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, OnInvalidMediaCommandsReceived) {
- auto controller = base::MakeRefCounted<MockMediaRouteController>(
- "routeId", profile(), router());
- EXPECT_CALL(*mock_media_router_ui_, GetMediaRouteController())
- .WillRepeatedly(Return(controller.get()));
-
- MediaStatus status;
- status.duration = base::TimeDelta::FromSeconds(100);
- handler_->UpdateMediaRouteStatus(status);
-
- EXPECT_CALL(*controller, Seek(_)).Times(0);
- EXPECT_CALL(*controller, SetVolume(_)).Times(0);
-
- base::ListValue args_list;
-
- base::DictionaryValue* args;
- args_list.Append(std::make_unique<base::DictionaryValue>());
- args_list.GetDictionary(0, &args);
-
- // Seek positions greater than the duration or negative should be ignored.
- args->SetDouble("time", 101);
- handler_->OnSeekCurrentMedia(&args_list);
- args->SetDouble("time", -10);
- handler_->OnSeekCurrentMedia(&args_list);
-
- args->Clear();
-
- // Volumes outside of the [0, 1] range should be ignored.
- args->SetDouble("volume", 1.5);
- handler_->OnSetCurrentMediaVolume(&args_list);
- args->SetDouble("volume", 1.5);
- handler_->OnSetCurrentMediaVolume(&args_list);
-}
-
-TEST_F(MediaRouterWebUIMessageHandlerTest, OnRouteControllerInvalidated) {
- handler_->OnRouteControllerInvalidated();
- EXPECT_EQ(1u, web_ui_->call_data().size());
- const content::TestWebUI::CallData& call_data = *web_ui_->call_data()[0];
- EXPECT_EQ("media_router.ui.onRouteControllerInvalidated",
- call_data.function_name());
-}
-
-} // namespace media_router
diff --git a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc
index 91ec91781ed..30482e50366 100644
--- a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc
@@ -33,12 +33,12 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/render_process_host.h"
+#include "content/public/browser/system_connector.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "content/public/common/process_type.h"
-#include "content/public/common/service_manager_connection.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "services/service_manager/public/cpp/connector.h"
#include "ui/shell_dialogs/select_file_dialog.h"
@@ -167,13 +167,13 @@ class MemoryInternalsDOMHandler : public content::WebUIMessageHandler,
scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
content::WebUI* web_ui_; // The WebUI that owns us.
- base::WeakPtrFactory<MemoryInternalsDOMHandler> weak_factory_;
+ base::WeakPtrFactory<MemoryInternalsDOMHandler> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(MemoryInternalsDOMHandler);
};
MemoryInternalsDOMHandler::MemoryInternalsDOMHandler(content::WebUI* web_ui)
- : web_ui_(web_ui), weak_factory_(this) {}
+ : web_ui_(web_ui) {}
MemoryInternalsDOMHandler::~MemoryInternalsDOMHandler() {
if (select_file_dialog_)
@@ -269,7 +269,7 @@ void MemoryInternalsDOMHandler::HandleStartProfiling(
supervisor->StartManualProfiling(pid);
} else {
supervisor->Start(
- content::ServiceManagerConnection::GetForProcess(),
+ content::GetSystemConnector(),
base::BindOnce(&heap_profiling::Supervisor::StartManualProfiling,
base::Unretained(supervisor), pid));
}
diff --git a/chromium/chrome/browser/ui/webui/nacl_ui.cc b/chromium/chrome/browser/ui/webui/nacl_ui.cc
index e818ddd346d..89228f3b232 100644
--- a/chromium/chrome/browser/ui/webui/nacl_ui.cc
+++ b/chromium/chrome/browser/ui/webui/nacl_ui.cc
@@ -133,7 +133,7 @@ class NaClDomHandler : public WebUIMessageHandler {
std::string pnacl_version_string_;
// Factory for the creating refs in callbacks.
- base::WeakPtrFactory<NaClDomHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<NaClDomHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(NaClDomHandler);
};
@@ -141,8 +141,7 @@ class NaClDomHandler : public WebUIMessageHandler {
NaClDomHandler::NaClDomHandler()
: has_plugin_info_(false),
pnacl_path_validated_(false),
- pnacl_path_exists_(false),
- weak_ptr_factory_(this) {
+ pnacl_path_exists_(false) {
PluginService::GetInstance()->GetPlugins(base::Bind(
&NaClDomHandler::OnGotPlugins, weak_ptr_factory_.GetWeakPtr()));
}
diff --git a/chromium/chrome/browser/ui/webui/net_export_ui.cc b/chromium/chrome/browser/ui/webui/net_export_ui.cc
index 1b9b3d857f4..c50cd8b8f77 100644
--- a/chromium/chrome/browser/ui/webui/net_export_ui.cc
+++ b/chromium/chrome/browser/ui/webui/net_export_ui.cc
@@ -22,7 +22,6 @@
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_prefs.h"
-#include "chrome/browser/io_thread.h"
#include "chrome/browser/net/net_export_helper.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/platform_util.h"
@@ -152,7 +151,7 @@ class NetExportMessageHandler
scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
- base::WeakPtrFactory<NetExportMessageHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<NetExportMessageHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(NetExportMessageHandler);
};
@@ -160,8 +159,7 @@ class NetExportMessageHandler
NetExportMessageHandler::NetExportMessageHandler()
: file_writer_(g_browser_process->system_network_context_manager()
->GetNetExportFileWriter()),
- state_observer_manager_(this),
- weak_ptr_factory_(this) {
+ state_observer_manager_(this) {
file_writer_->Initialize();
}
@@ -217,7 +215,7 @@ void NetExportMessageHandler::OnStartNetLog(const base::ListValue* list) {
const base::Value::ListStorage& params = list->GetList();
// Determine the capture mode.
- capture_mode_ = net::NetLogCaptureMode::Default();
+ capture_mode_ = net::NetLogCaptureMode::kDefault;
if (!params.empty() && params[0].is_string()) {
capture_mode_ = net_log::NetExportFileWriter::CaptureModeFromString(
params[0].GetString());
diff --git a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui.cc b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui.cc
index a99d5b78ca9..5cc53f9c7d0 100644
--- a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui.cc
@@ -83,7 +83,7 @@ class NetInternalsMessageHandler
void RegisterMessages() override;
private:
- network::mojom::NetworkContext* GetNetworkContext() const;
+ network::mojom::NetworkContext* GetNetworkContext();
// Calls g_browser.receive in the renderer, passing in |command| and |arg|.
// If the renderer is displaying a log file, the message will be ignored.
@@ -137,7 +137,7 @@ class NetInternalsMessageHandler
bool succeeded);
#endif
- const content::WebUI* web_ui_;
+ content::WebUI* web_ui_;
DISALLOW_COPY_AND_ASSIGN(NetInternalsMessageHandler);
};
@@ -503,8 +503,8 @@ void NetInternalsMessageHandler::OnSetNetworkDebugModeCompleted(
}
#endif // defined(OS_CHROMEOS)
-network::mojom::NetworkContext* NetInternalsMessageHandler::GetNetworkContext()
- const {
+network::mojom::NetworkContext*
+NetInternalsMessageHandler::GetNetworkContext() {
return content::BrowserContext::GetDefaultStoragePartition(
web_ui_->GetWebContents()->GetBrowserContext())
->GetNetworkContext();
diff --git a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc
index 92f899d74cb..4b93e834575 100644
--- a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc
@@ -13,6 +13,7 @@
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/macros.h"
+#include "base/memory/weak_ptr.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
@@ -20,7 +21,7 @@
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/io_thread.h"
+#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
@@ -31,24 +32,18 @@
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
+#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "net/base/address_list.h"
#include "net/base/net_errors.h"
-#include "net/dns/host_cache.h"
-#include "net/dns/host_resolver.h"
+#include "net/dns/host_resolver_source.h"
#include "net/dns/mock_host_resolver.h"
-#include "net/http/http_network_session.h"
-#include "net/http/http_transaction_factory.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/request_handler_util.h"
-#include "net/url_request/url_request_context.h"
-#include "net/url_request/url_request_context_getter.h"
-#include "services/network/public/cpp/features.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
-using content::BrowserThread;
using content::WebUIMessageHandler;
namespace {
@@ -65,37 +60,44 @@ std::unique_ptr<net::test_server::HttpResponse> HandleExpectCTReportPreflight(
return http_response;
}
-// Called on IO thread. Adds an entry to the cache for the specified hostname.
-// Either |net_error| must be net::OK, or |address| must be NULL.
-void AddCacheEntryOnIOThread(net::URLRequestContextGetter* context_getter,
- const std::string& hostname,
- const std::string& ip_literal,
- int net_error,
- int expire_days_from_now) {
- ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO));
- net::URLRequestContext* context = context_getter->GetURLRequestContext();
- net::HostCache* cache = context->host_resolver()->GetHostCache();
- ASSERT_TRUE(cache);
-
- net::HostCache::Key key(hostname, net::ADDRESS_FAMILY_UNSPECIFIED, 0);
- base::TimeDelta ttl = base::TimeDelta::FromDays(expire_days_from_now);
-
- net::AddressList address_list;
- if (net_error == net::OK) {
- // If |net_error| does not indicate an error, convert |ip_literal| to a
- // net::AddressList, so it can be used with the cache.
- int rv = net::ParseAddressList(ip_literal, hostname, &address_list);
- ASSERT_EQ(net::OK, rv);
- } else {
- ASSERT_TRUE(ip_literal.empty());
+// Notifies the NetInternalsTest.Task JS object of the DNS lookup result once
+// it's complete. Owns itself.
+class DnsLookupClient : public network::mojom::ResolveHostClient {
+ public:
+ using Callback = base::OnceCallback<void(base::Value*)>;
+
+ DnsLookupClient(network::mojom::ResolveHostClientRequest request,
+ Callback callback)
+ : binding_(this, std::move(request)), callback_(std::move(callback)) {
+ binding_.set_connection_error_handler(
+ base::BindOnce(&DnsLookupClient::OnComplete, base::Unretained(this),
+ net::ERR_FAILED, base::nullopt));
+ }
+ ~DnsLookupClient() override {}
+
+ // network::mojom::ResolveHostClient:
+ void OnComplete(
+ int32_t error,
+ const base::Optional<net::AddressList>& resolved_addresses) override {
+ std::string result;
+ if (error == net::OK) {
+ CHECK(resolved_addresses->size() == 1);
+ result = resolved_addresses.value()[0].ToStringWithoutPort();
+ } else {
+ result = net::ErrorToString(error);
+ }
+ base::Value value(result);
+ std::move(callback_).Run(&value);
+ delete this;
+ }
+ void OnTextResults(const std::vector<std::string>& text_results) override {}
+ void OnHostnameResults(const std::vector<net::HostPortPair>& hosts) override {
}
- // Add entry to the cache.
- cache->Set(net::HostCache::Key(hostname, net::ADDRESS_FAMILY_UNSPECIFIED, 0),
- net::HostCache::Entry(net_error, address_list,
- net::HostCache::Entry::SOURCE_UNKNOWN),
- base::TimeTicks::Now(), ttl);
-}
+ private:
+ mojo::Binding<network::mojom::ResolveHostClient> binding_;
+ Callback callback_;
+};
} // namespace
@@ -124,21 +126,20 @@ class NetInternalsTest::MessageHandler : public content::WebUIMessageHandler {
// which must already have been started.
void GetTestServerURL(const base::ListValue* list_value);
- // Called on UI thread. Adds an entry to the cache for the specified
- // hostname by posting a task to the IO thread. Takes the host name,
- // ip address, net error code, and expiration time in days from now
- // as parameters. If the error code indicates failure, the ip address
- // must be an empty string.
- void AddCacheEntry(const base::ListValue* list_value);
-
// Sets up the test server to receive test Expect-CT reports. Calls the
// Javascript callback to return the test server URI.
void SetUpTestReportURI(const base::ListValue* list_value);
+ // Performs a DNS lookup. Calls the Javascript callback with the host's IP
+ // address or an error string.
+ void DnsLookup(const base::ListValue* list_value);
+
Browser* browser() { return net_internals_test_->browser(); }
NetInternalsTest* net_internals_test_;
+ base::WeakPtrFactory<MessageHandler> weak_factory_{this};
+
DISALLOW_COPY_AND_ASSIGN(MessageHandler);
};
@@ -150,15 +151,14 @@ void NetInternalsTest::MessageHandler::RegisterMessages() {
RegisterMessage(
"getTestServerURL",
base::BindRepeating(&NetInternalsTest::MessageHandler::GetTestServerURL,
- base::Unretained(this)));
- RegisterMessage(
- "addCacheEntry",
- base::BindRepeating(&NetInternalsTest::MessageHandler::AddCacheEntry,
- base::Unretained(this)));
+ weak_factory_.GetWeakPtr()));
RegisterMessage(
"setUpTestReportURI",
base::BindRepeating(&NetInternalsTest::MessageHandler::SetUpTestReportURI,
- base::Unretained(this)));
+ weak_factory_.GetWeakPtr()));
+ RegisterMessage("dnsLookup", base::BindRepeating(
+ &NetInternalsTest::MessageHandler::DnsLookup,
+ weak_factory_.GetWeakPtr()));
}
void NetInternalsTest::MessageHandler::RegisterMessage(
@@ -167,7 +167,7 @@ void NetInternalsTest::MessageHandler::RegisterMessage(
web_ui()->RegisterMessageCallback(
message,
base::BindRepeating(&NetInternalsTest::MessageHandler::HandleMessage,
- base::Unretained(this), handler));
+ weak_factory_.GetWeakPtr(), handler));
}
void NetInternalsTest::MessageHandler::HandleMessage(
@@ -193,33 +193,6 @@ void NetInternalsTest::MessageHandler::GetTestServerURL(
RunJavascriptCallback(url_value.get());
}
-void NetInternalsTest::MessageHandler::AddCacheEntry(
- const base::ListValue* list_value) {
- std::string hostname;
- std::string ip_literal;
- double net_error;
- double expire_days_from_now;
- ASSERT_TRUE(list_value->GetString(0, &hostname));
- ASSERT_TRUE(list_value->GetString(1, &ip_literal));
- ASSERT_TRUE(list_value->GetDouble(2, &net_error));
- ASSERT_TRUE(list_value->GetDouble(3, &expire_days_from_now));
- ASSERT_TRUE(browser());
-
- if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
- // TODO(mattm): implement this with a ForTesting method on NetworkContext
- // when it's needed.
- return;
- }
-
- base::PostTaskWithTraits(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(
- &AddCacheEntryOnIOThread,
- base::RetainedRef(browser()->profile()->GetRequestContext()),
- hostname, ip_literal, static_cast<int>(net_error),
- static_cast<int>(expire_days_from_now)));
-}
-
void NetInternalsTest::MessageHandler::SetUpTestReportURI(
const base::ListValue* list_value) {
net_internals_test_->embedded_test_server()->RegisterRequestHandler(
@@ -230,6 +203,28 @@ void NetInternalsTest::MessageHandler::SetUpTestReportURI(
RunJavascriptCallback(&report_uri_value);
}
+void NetInternalsTest::MessageHandler::DnsLookup(
+ const base::ListValue* list_value) {
+ std::string hostname;
+ bool local;
+ ASSERT_TRUE(list_value->GetString(0, &hostname));
+ ASSERT_TRUE(list_value->GetBoolean(1, &local));
+ ASSERT_TRUE(browser());
+
+ auto resolve_host_parameters = network::mojom::ResolveHostParameters::New();
+ if (local)
+ resolve_host_parameters->source = net::HostResolverSource::LOCAL_ONLY;
+ network::mojom::ResolveHostClientPtr client_ptr;
+ // DnsLookupClient owns itself.
+ new DnsLookupClient(mojo::MakeRequest(&client_ptr),
+ base::BindOnce(&MessageHandler::RunJavascriptCallback,
+ weak_factory_.GetWeakPtr()));
+ content::BrowserContext::GetDefaultStoragePartition(browser()->profile())
+ ->GetNetworkContext()
+ ->ResolveHost(net::HostPortPair(hostname, 80),
+ std::move(resolve_host_parameters), std::move(client_ptr));
+}
+
////////////////////////////////////////////////////////////////////////////////
// NetInternalsTest
////////////////////////////////////////////////////////////////////////////////
@@ -242,6 +237,11 @@ NetInternalsTest::NetInternalsTest()
NetInternalsTest::~NetInternalsTest() {
}
+void NetInternalsTest::SetUpOnMainThread() {
+ WebUIBrowserTest::SetUpOnMainThread();
+ host_resolver()->AddRule("*", "127.0.0.1");
+}
+
content::WebUIMessageHandler* NetInternalsTest::GetMockMessageHandler() {
return message_handler_.get();
}
diff --git a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.h b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.h
index 86d996e6b8e..a3d2845b98c 100644
--- a/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.h
+++ b/chromium/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.h
@@ -15,6 +15,8 @@ class NetInternalsTest : public WebUIBrowserTest {
NetInternalsTest();
~NetInternalsTest() override;
+ void SetUpOnMainThread() override;
+
private:
class MessageHandler;
diff --git a/chromium/chrome/browser/ui/webui/notifications_internals/OWNERS b/chromium/chrome/browser/ui/webui/notifications_internals/OWNERS
new file mode 100644
index 00000000000..1ce49a53d68
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/notifications_internals/OWNERS
@@ -0,0 +1,2 @@
+file://chrome/browser/notifications/OWNERS
+file://chrome/browser/notifications/scheduler/OWNERS
diff --git a/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.cc b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.cc
new file mode 100644
index 00000000000..596be278024
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.cc
@@ -0,0 +1,36 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.h"
+
+#include <memory>
+
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.h"
+#include "chrome/common/url_constants.h"
+#include "chrome/grit/browser_resources.h"
+#include "content/public/browser/web_ui.h"
+#include "content/public/browser/web_ui_controller.h"
+#include "content/public/browser/web_ui_data_source.h"
+
+NotificationsInternalsUI::NotificationsInternalsUI(content::WebUI* web_ui)
+ : content::WebUIController(web_ui) {
+ content::WebUIDataSource* html_source = content::WebUIDataSource::Create(
+ chrome::kChromeUINotificationsInternalsHost);
+ html_source->AddResourcePath("notifications_internals.css",
+ IDR_NOTIFICATIONS_INTERNALS_CSS);
+ html_source->AddResourcePath("notifications_internals.js",
+ IDR_NOTIFICATIONS_INTERNALS_JS);
+ html_source->AddResourcePath("notifications_internals_browser_proxy.js",
+ IDR_NOTIFICATIONS_INTERNALS_BROWSER_PROXY_JS);
+ html_source->SetDefaultResource(IDR_NOTIFICATIONS_INTERNALS_HTML);
+
+ Profile* profile = Profile::FromWebUI(web_ui);
+ content::WebUIDataSource::Add(profile, html_source);
+
+ web_ui->AddMessageHandler(
+ std::make_unique<NotificationsInternalsUIMessageHandler>(profile));
+}
+
+NotificationsInternalsUI::~NotificationsInternalsUI() = default;
diff --git a/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.h b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.h
new file mode 100644
index 00000000000..7507bcf1036
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui.h
@@ -0,0 +1,25 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_NOTIFICATIONS_INTERNALS_NOTIFICATIONS_INTERNALS_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_NOTIFICATIONS_INTERNALS_NOTIFICATIONS_INTERNALS_UI_H_
+
+#include "base/macros.h"
+#include "content/public/browser/web_ui_controller.h"
+
+namespace content {
+class WebUI;
+} // namespace content
+
+// The WebUI for chrome://notifications-internals.
+class NotificationsInternalsUI : public content::WebUIController {
+ public:
+ explicit NotificationsInternalsUI(content::WebUI* web_ui);
+ ~NotificationsInternalsUI() override;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(NotificationsInternalsUI);
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_NOTIFICATIONS_INTERNALS_NOTIFICATIONS_INTERNALS_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc
new file mode 100644
index 00000000000..9cca6cc57da
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.cc
@@ -0,0 +1,48 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.h"
+
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "base/bind.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/values.h"
+#include "chrome/browser/notifications/scheduler/notification_schedule_service_factory.h"
+#include "chrome/browser/notifications/scheduler/public/notification_params.h"
+#include "chrome/browser/notifications/scheduler/public/notification_schedule_service.h"
+#include "chrome/browser/profiles/profile.h"
+#include "content/public/browser/web_ui.h"
+
+NotificationsInternalsUIMessageHandler::NotificationsInternalsUIMessageHandler(
+ Profile* profile)
+ : schedule_service_(
+ NotificationScheduleServiceFactory::GetForBrowserContext(profile)) {}
+
+NotificationsInternalsUIMessageHandler::
+ ~NotificationsInternalsUIMessageHandler() = default;
+
+void NotificationsInternalsUIMessageHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "scheduleNotification",
+ base::BindRepeating(
+ &NotificationsInternalsUIMessageHandler::HandleScheduleNotification,
+ base::Unretained(this)));
+}
+
+void NotificationsInternalsUIMessageHandler::HandleScheduleNotification(
+ const base::ListValue* args) {
+ CHECK_EQ(args->GetList().size(), 4u);
+ notifications::ScheduleParams schedule_params;
+ notifications::NotificationData data;
+ data.custom_data.emplace("url", args->GetList()[1].GetString());
+ data.title = base::UTF8ToUTF16(args->GetList()[2].GetString());
+ data.message = base::UTF8ToUTF16(args->GetList()[3].GetString());
+ auto params = std::make_unique<notifications::NotificationParams>(
+ notifications::SchedulerClientType::kWebUI, std::move(data),
+ std::move(schedule_params));
+ schedule_service_->Schedule(std::move(params));
+}
diff --git a/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.h b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.h
new file mode 100644
index 00000000000..35fe4eab48d
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/notifications_internals/notifications_internals_ui_message_handler.h
@@ -0,0 +1,41 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_NOTIFICATIONS_INTERNALS_NOTIFICATIONS_INTERNALS_UI_MESSAGE_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_NOTIFICATIONS_INTERNALS_NOTIFICATIONS_INTERNALS_UI_MESSAGE_HANDLER_H_
+
+#include "base/macros.h"
+#include "base/memory/weak_ptr.h"
+#include "content/public/browser/web_ui_message_handler.h"
+
+namespace base {
+class ListValue;
+} // namespace base
+
+namespace notifications {
+class NotificationScheduleService;
+} // namespace notifications
+
+class Profile;
+
+// Routes html events to native notification systems in
+// chrome://notifications-internals.
+class NotificationsInternalsUIMessageHandler
+ : public content::WebUIMessageHandler {
+ public:
+ explicit NotificationsInternalsUIMessageHandler(Profile* profile);
+ ~NotificationsInternalsUIMessageHandler() override;
+
+ // content::WebUIMessageHandler implementation.
+ void RegisterMessages() override;
+
+ private:
+ void HandleScheduleNotification(const base::ListValue* args);
+
+ notifications::NotificationScheduleService* schedule_service_;
+
+ DISALLOW_COPY_AND_ASSIGN(NotificationsInternalsUIMessageHandler);
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_NOTIFICATIONS_INTERNALS_NOTIFICATIONS_INTERNALS_UI_MESSAGE_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc
index d52d5c7d397..eb64fce1c92 100644
--- a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc
+++ b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc
@@ -182,8 +182,10 @@ void AppLauncherHandler::CreateAppInfo(const Extension* extension,
value->SetString("icon_small", small_icon.spec());
value->SetBoolean("icon_small_exists", has_non_default_small_icon);
- value->SetInteger("launch_container",
- extensions::AppLaunchInfo::GetLaunchContainer(extension));
+ value->SetInteger(
+ "launch_container",
+ static_cast<int>(
+ extensions::AppLaunchInfo::GetLaunchContainer(extension)));
ExtensionPrefs* prefs = ExtensionPrefs::Get(service->profile());
value->SetInteger("launch_type", extensions::GetLaunchType(prefs, extension));
value->SetBoolean("is_component",
@@ -521,11 +523,12 @@ void AppLauncherHandler::HandleLaunchApp(const base::ListValue* args) {
disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB ||
disposition == WindowOpenDisposition::NEW_WINDOW) {
// TODO(jamescook): Proper support for background tabs.
- AppLaunchParams params(profile, extension,
- disposition == WindowOpenDisposition::NEW_WINDOW
- ? extensions::LAUNCH_CONTAINER_WINDOW
- : extensions::LAUNCH_CONTAINER_TAB,
- disposition, extensions::SOURCE_NEW_TAB_PAGE);
+ AppLaunchParams params(
+ profile, extension_id,
+ disposition == WindowOpenDisposition::NEW_WINDOW
+ ? extensions::LaunchContainer::kLaunchContainerWindow
+ : extensions::LaunchContainer::kLaunchContainerTab,
+ disposition, extensions::AppLaunchSource::kSourceNewTabPage);
params.override_url = override_url;
OpenApplication(params);
} else {
@@ -541,7 +544,7 @@ void AppLauncherHandler::HandleLaunchApp(const base::ListValue* args) {
profile, extension,
old_contents ? WindowOpenDisposition::CURRENT_TAB
: WindowOpenDisposition::NEW_FOREGROUND_TAB,
- extensions::SOURCE_NEW_TAB_PAGE);
+ extensions::AppLaunchSource::kSourceNewTabPage);
params.override_url = override_url;
WebContents* new_contents = OpenApplication(params);
diff --git a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc
index f565648b2d4..9102ea06af4 100644
--- a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc
+++ b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc
@@ -14,13 +14,12 @@
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/webui/ntp/app_launcher_handler.h"
#include "chrome/browser/ui/webui/ntp/core_app_launcher_handler.h"
#include "chrome/browser/ui/webui/ntp/ntp_resource_cache.h"
#include "chrome/browser/ui/webui/ntp/ntp_resource_cache_factory.h"
#include "chrome/browser/ui/webui/theme_handler.h"
-#include "chrome/common/pref_names.h"
+#include "chrome/common/chrome_features.h"
#include "chrome/common/url_constants.h"
#include "components/bookmarks/common/bookmark_pref_names.h"
#include "components/prefs/pref_service.h"
@@ -44,8 +43,7 @@ const char kLTRHtmlTextDirection[] = "ltr";
const char* GetHtmlTextDirection(const base::string16& text) {
if (base::i18n::IsRTL() && base::i18n::StringContainsStrongRTLChars(text))
return kRTLHtmlTextDirection;
- else
- return kLTRHtmlTextDirection;
+ return kLTRHtmlTextDirection;
}
} // namespace
@@ -53,11 +51,7 @@ const char* GetHtmlTextDirection(const base::string16& text) {
///////////////////////////////////////////////////////////////////////////////
// NewTabUI
-NewTabUI::NewTabUI(content::WebUI* web_ui)
- : content::WebUIController(web_ui),
- dark_mode_observer_(ui::NativeTheme::GetInstanceForNativeUi(),
- base::BindRepeating(&NewTabUI::OnDarkModeChanged,
- base::Unretained(this))) {
+NewTabUI::NewTabUI(content::WebUI* web_ui) : content::WebUIController(web_ui) {
web_ui->OverrideTitle(l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE));
Profile* profile = GetProfile();
@@ -73,11 +67,6 @@ NewTabUI::NewTabUI(content::WebUI* web_ui)
pref_change_registrar_.Add(bookmarks::prefs::kShowBookmarkBar,
base::Bind(&NewTabUI::OnShowBookmarkBarChanged,
base::Unretained(this)));
- pref_change_registrar_.Add(
- prefs::kWebKitDefaultFontSize,
- base::Bind(&NewTabUI::OnDefaultFontSizeChanged, base::Unretained(this)));
-
- dark_mode_observer_.Start();
}
NewTabUI::~NewTabUI() {}
@@ -91,20 +80,6 @@ void NewTabUI::OnShowBookmarkBarChanged() {
attached);
}
-void NewTabUI::OnDarkModeChanged(bool /*dark_mode*/) {
- if (!web_ui() || !web_ui()->CanCallJavascript())
- return;
-
- bool enabled = base::FeatureList::IsEnabled(features::kWebUIDarkMode);
- web_ui()->CallJavascriptFunctionUnsafe(
- "document.documentElement.toggleAttribute", base::Value("dark"),
- base::Value(enabled && dark_mode_observer_.InDarkMode()));
-}
-
-void NewTabUI::OnDefaultFontSizeChanged() {
- web_ui()->CallJavascriptFunctionUnsafe("ntp.defaultFontSizeChanged");
-}
-
// static
void NewTabUI::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
@@ -169,7 +144,7 @@ NewTabUI::NewTabHTMLSource::NewTabHTMLSource(Profile* profile)
: profile_(profile) {
}
-std::string NewTabUI::NewTabHTMLSource::GetSource() const {
+std::string NewTabUI::NewTabHTMLSource::GetSource() {
return chrome::kChromeUINewTabHost;
}
@@ -199,35 +174,31 @@ void NewTabUI::NewTabHTMLSource::StartDataRequest(
callback.Run(html_bytes.get());
}
-std::string NewTabUI::NewTabHTMLSource::GetMimeType(const std::string& resource)
- const {
+std::string NewTabUI::NewTabHTMLSource::GetMimeType(
+ const std::string& resource) {
return "text/html";
}
-bool NewTabUI::NewTabHTMLSource::ShouldReplaceExistingSource() const {
+bool NewTabUI::NewTabHTMLSource::ShouldReplaceExistingSource() {
return false;
}
-std::string NewTabUI::NewTabHTMLSource::GetContentSecurityPolicyScriptSrc()
- const {
+std::string NewTabUI::NewTabHTMLSource::GetContentSecurityPolicyScriptSrc() {
// 'unsafe-inline' and google resources are added to script-src.
return "script-src chrome://resources 'self' 'unsafe-eval' 'unsafe-inline' "
"*.google.com *.gstatic.com;";
}
-std::string NewTabUI::NewTabHTMLSource::GetContentSecurityPolicyStyleSrc()
- const {
+std::string NewTabUI::NewTabHTMLSource::GetContentSecurityPolicyStyleSrc() {
return "style-src 'self' chrome://resources 'unsafe-inline' chrome://theme;";
}
-std::string NewTabUI::NewTabHTMLSource::GetContentSecurityPolicyImgSrc()
- const {
+std::string NewTabUI::NewTabHTMLSource::GetContentSecurityPolicyImgSrc() {
return "img-src chrome-search://thumb chrome-search://thumb2 "
"chrome-search://theme chrome://theme data:;";
}
-std::string NewTabUI::NewTabHTMLSource::GetContentSecurityPolicyChildSrc()
- const {
+std::string NewTabUI::NewTabHTMLSource::GetContentSecurityPolicyChildSrc() {
return "child-src chrome-search://most-visited;";
}
diff --git a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h
index 53f6473e449..61e2451c3db 100644
--- a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h
+++ b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h
@@ -10,7 +10,6 @@
#include "components/prefs/pref_change_registrar.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_ui_controller.h"
-#include "ui/native_theme/dark_mode_observer.h"
class GURL;
class Profile;
@@ -55,17 +54,17 @@ class NewTabUI : public content::WebUIController {
~NewTabHTMLSource() override;
// content::URLDataSource implementation.
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override;
- std::string GetMimeType(const std::string&) const override;
- bool ShouldReplaceExistingSource() const override;
- std::string GetContentSecurityPolicyScriptSrc() const override;
- std::string GetContentSecurityPolicyStyleSrc() const override;
- std::string GetContentSecurityPolicyImgSrc() const override;
- std::string GetContentSecurityPolicyChildSrc() const override;
+ std::string GetMimeType(const std::string&) override;
+ bool ShouldReplaceExistingSource() override;
+ std::string GetContentSecurityPolicyScriptSrc() override;
+ std::string GetContentSecurityPolicyStyleSrc() override;
+ std::string GetContentSecurityPolicyImgSrc() override;
+ std::string GetContentSecurityPolicyChildSrc() override;
private:
// Pointer back to the original profile.
@@ -74,14 +73,10 @@ class NewTabUI : public content::WebUIController {
DISALLOW_COPY_AND_ASSIGN(NewTabHTMLSource);
};
- void OnDarkModeChanged(bool dark_mode);
- void OnDefaultFontSizeChanged();
void OnShowBookmarkBarChanged();
Profile* GetProfile() const;
- ui::DarkModeObserver dark_mode_observer_;
-
PrefChangeRegistrar pref_change_registrar_;
DISALLOW_COPY_AND_ASSIGN(NewTabUI);
diff --git a/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc b/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc
index c5531d9c5f9..2dcf1f8771c 100644
--- a/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc
+++ b/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc
@@ -23,10 +23,10 @@
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/apps/app_info_dialog.h"
#include "chrome/browser/ui/layout_constants.h"
-#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/webui/app_launcher_login_handler.h"
#include "chrome/browser/ui/webui/ntp/app_launcher_handler.h"
#include "chrome/common/buildflags.h"
+#include "chrome/common/chrome_features.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
@@ -36,13 +36,13 @@
#include "components/bookmarks/common/bookmark_pref_names.h"
#include "components/google/core/common/google_util.h"
#include "components/prefs/pref_service.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_process_host.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_urls.h"
-#include "services/identity/public/cpp/identity_manager.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/template_expressions.h"
@@ -347,8 +347,6 @@ void NTPResourceCache::CreateNewTabGuestHTML() {
l10n_util::GetStringUTF16(guest_tab_link_ids));
localized_strings.SetString("learnMoreLink", guest_tab_link);
- SetDarkKey(&localized_strings);
-
const std::string& app_locale = g_browser_process->GetApplicationLocale();
webui::SetLoadTimeDataDefaults(app_locale, &localized_strings);
@@ -467,8 +465,6 @@ void NTPResourceCache::CreateNewTabHTML() {
"isUserSignedIn",
IdentityManagerFactory::GetForProfile(profile_)->HasPrimaryAccount());
- SetDarkKey(&load_time_data);
-
// Load the new tab page appropriate for this build.
base::StringPiece new_tab_html(
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
@@ -584,11 +580,3 @@ void NTPResourceCache::CreateNewTabCSS() {
ui::ReplaceTemplateExpressions(new_tab_theme_css, substitutions);
new_tab_css_ = base::RefCountedString::TakeString(&css_string);
}
-
-void NTPResourceCache::SetDarkKey(base::Value* dict) {
- DCHECK(dict && dict->is_dict());
- bool use_dark =
- base::FeatureList::IsEnabled(features::kWebUIDarkMode) &&
- ui::NativeTheme::GetInstanceForNativeUi()->SystemDarkModeEnabled();
- dict->SetKey("dark", base::Value(use_dark ? "dark" : ""));
-}
diff --git a/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc b/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc
index 44d7fd3988c..8f72bc23a7b 100644
--- a/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc
@@ -88,7 +88,6 @@ bool ChromeNTPTilesInternalsMessageHandlerClient::DoesSourceExist(
return false;
#endif
case ntp_tiles::TileSource::CUSTOM_LINKS:
- case ntp_tiles::TileSource::SEARCH_PAGE:
#if !defined(OS_ANDROID)
return true;
#else
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 c5e4553ca0f..d8eadc545f5 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
@@ -34,7 +34,6 @@
#include "components/offline_pages/core/prefetch/prefetch_background_task_handler.h"
#include "components/offline_pages/core/prefetch/prefetch_dispatcher.h"
#include "components/offline_pages/core/prefetch/prefetch_downloader.h"
-#include "components/offline_pages/core/prefetch/prefetch_gcm_handler.h"
#include "components/offline_pages/core/prefetch/prefetch_prefs.h"
#include "components/offline_pages/core/prefetch/prefetch_service.h"
#include "components/offline_pages/core/prefetch/prefetch_types.h"
@@ -261,28 +260,20 @@ void OfflineInternalsUIMessageHandler::HandleGetNetworkStatus(
void OfflineInternalsUIMessageHandler::HandleScheduleNwake(
const base::ListValue* args) {
AllowJavascript();
- CHECK(!args->GetList().empty());
- base::Value callback_id = args->GetList()[0].Clone();
+ const base::Value* callback_id;
+ CHECK(args->Get(0, &callback_id));
if (prefetch_service_) {
- prefetch_service_->GetGCMToken(base::BindOnce(
- &OfflineInternalsUIMessageHandler::ScheduleNwakeWithGCMToken,
- weak_ptr_factory_.GetWeakPtr(), std::move(callback_id)));
+ prefetch_service_->ForceRefreshSuggestions();
+ prefetch_service_->GetPrefetchBackgroundTaskHandler()
+ ->EnsureTaskScheduled();
+ ResolveJavascriptCallback(*callback_id, base::Value("Scheduled."));
} else {
- RejectJavascriptCallback(callback_id,
+ RejectJavascriptCallback(*callback_id,
base::Value("No prefetch service available."));
}
}
-void OfflineInternalsUIMessageHandler::ScheduleNwakeWithGCMToken(
- base::Value callback_id,
- const std::string& gcm_token) {
- prefetch_service_->ForceRefreshSuggestions();
- prefetch_service_->GetPrefetchBackgroundTaskHandler()->EnsureTaskScheduled(
- gcm_token);
- ResolveJavascriptCallback(callback_id, base::Value("Scheduled."));
-}
-
void OfflineInternalsUIMessageHandler::HandleCancelNwake(
const base::ListValue* args) {
AllowJavascript();
diff --git a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h
index 61e06e47c1d..09a718680fa 100644
--- a/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h
+++ b/chromium/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h
@@ -85,8 +85,6 @@ class OfflineInternalsUIMessageHandler : public content::WebUIMessageHandler {
// Schedules an NWake signal.
void HandleScheduleNwake(const base::ListValue* args);
- void ScheduleNwakeWithGCMToken(base::Value callback_id,
- const std::string& gcm_token);
// Cancels an NWake signal.
void HandleCancelNwake(const base::ListValue* args);
diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom b/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom
index 3427d037a6d..de8253d461c 100644
--- a/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom
+++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox.mojom
@@ -43,7 +43,6 @@ struct AutocompleteMatch {
int32 duplicates;
bool from_previous;
array<AutocompleteAdditionalInfo> additional_info;
- string document_type;
};
struct AutocompleteResultsForProvider {
diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc b/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc
index 4554907ab18..97def4ae86d 100644
--- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc
+++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc
@@ -198,8 +198,6 @@ struct TypeConverter<mojom::AutocompleteMatchPtr, AutocompleteMatch> {
result->additional_info =
mojo::ConvertTo<std::vector<mojom::AutocompleteAdditionalInfoPtr>>(
input.additional_info);
- result->document_type =
- AutocompleteMatch::DocumentTypeString(input.document_type);
return result;
}
};
diff --git a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc
index 7ad3bb95e96..af3ee72c3cd 100644
--- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc
+++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_ui.cc
@@ -9,6 +9,7 @@
#include "base/bind.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/omnibox/omnibox_page_handler.h"
+#include "chrome/browser/ui/webui/version_ui.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
#include "content/public/browser/web_ui.h"
@@ -19,6 +20,11 @@ OmniboxUI::OmniboxUI(content::WebUI* web_ui) : ui::MojoWebUIController(web_ui) {
// Set up the chrome://omnibox/ source.
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIOmniboxHost);
+
+ // Expose version information to client because it is useful in output.
+ VersionUI::AddVersionDetailStrings(source);
+ source->SetJsonPath("strings.js");
+
source->AddResourcePath("omnibox.css", IDR_OMNIBOX_CSS);
source->AddResourcePath("omnibox_input.css", IDR_OMNIBOX_INPUT_CSS);
source->AddResourcePath("output_results_group.css",
diff --git a/chromium/chrome/browser/ui/webui/page_not_available_for_guest/page_not_available_for_guest_ui.cc b/chromium/chrome/browser/ui/webui/page_not_available_for_guest/page_not_available_for_guest_ui.cc
index 1cf3620d094..b33b6ad17af 100644
--- a/chromium/chrome/browser/ui/webui/page_not_available_for_guest/page_not_available_for_guest_ui.cc
+++ b/chromium/chrome/browser/ui/webui/page_not_available_for_guest/page_not_available_for_guest_ui.cc
@@ -6,7 +6,6 @@
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/generated_resources.h"
@@ -49,7 +48,5 @@ PageNotAvailableForGuestUI::PageNotAvailableForGuestUI(
const std::string& host_name)
: WebUIController(web_ui) {
Profile* profile = Profile::FromWebUI(web_ui);
- auto* source = CreateHTMLSource(profile, host_name);
- DarkModeHandler::Initialize(web_ui, source);
- content::WebUIDataSource::Add(profile, source);
+ content::WebUIDataSource::Add(profile, CreateHTMLSource(profile, host_name));
}
diff --git a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.cc b/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.cc
index 64c6734a0eb..5e92515c354 100644
--- a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.cc
@@ -4,26 +4,21 @@
#include "chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h"
-#include <algorithm>
-#include <set>
-
-#include "base/stl_util.h"
-#include "base/strings/string_split.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/url_constants.h"
+#include "components/autofill/core/browser/logging/log_receiver.h"
+#include "components/autofill/core/browser/logging/log_router.h"
#include "components/grit/components_resources.h"
-#include "components/password_manager/content/browser/password_manager_internals_service_factory.h"
-#include "components/password_manager/core/browser/password_manager_internals_service.h"
-#include "components/password_manager/core/common/password_manager_pref_names.h"
-#include "components/prefs/pref_service.h"
+#include "components/password_manager/content/browser/password_manager_log_router_factory.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "content/public/browser/web_ui_message_handler.h"
#include "net/base/escape.h"
-using password_manager::PasswordManagerInternalsService;
-using password_manager::PasswordManagerInternalsServiceFactory;
+using autofill::LogRouter;
+using password_manager::PasswordManagerLogRouterFactory;
namespace {
@@ -38,88 +33,102 @@ content::WebUIDataSource* CreatePasswordManagerInternalsHTMLSource() {
return source;
}
-} // namespace
+// chrome://password-manager-internals specific UI handler that takes care of
+// subscribing to the autofill logging instance.
+class PasswordManagerInternalsUIHandler : public content::WebUIMessageHandler,
+ public autofill::LogReceiver {
+ public:
+ PasswordManagerInternalsUIHandler() = default;
+ ~PasswordManagerInternalsUIHandler() override;
-PasswordManagerInternalsUI::PasswordManagerInternalsUI(content::WebUI* web_ui)
- : WebUIController(web_ui),
- WebContentsObserver(web_ui->GetWebContents()),
- registered_with_logging_service_(false) {
- // Set up the chrome://password-manager-internals/ source.
- content::WebUIDataSource::Add(Profile::FromWebUI(web_ui),
- CreatePasswordManagerInternalsHTMLSource());
+ private:
+ // content::WebUIMessageHandler:
+ void RegisterMessages() override;
+
+ // Implements content::WebUIMessageHandler.
+ void OnJavascriptAllowed() override;
+ void OnJavascriptDisallowed() override;
+
+ // LogReceiver implementation.
+ void LogEntry(const base::Value& entry) override;
+
+ void StartSubscription();
+ void EndSubscription();
+
+ // JavaScript call handler.
+ void OnLoaded(const base::ListValue* args);
+
+ // Whether |this| is registered as a log receiver with the LogRouter.
+ bool registered_with_log_router_ = false;
+
+ DISALLOW_COPY_AND_ASSIGN(PasswordManagerInternalsUIHandler);
+};
+
+PasswordManagerInternalsUIHandler::~PasswordManagerInternalsUIHandler() {
+ EndSubscription();
}
-PasswordManagerInternalsUI::~PasswordManagerInternalsUI() {
- UnregisterFromLoggingServiceIfNecessary();
+void PasswordManagerInternalsUIHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "loaded",
+ base::BindRepeating(&PasswordManagerInternalsUIHandler::OnLoaded,
+ base::Unretained(this)));
}
-void PasswordManagerInternalsUI::DidStartLoading() {
- // In case this tab is being reloaded, unregister itself until the reload is
- // completed.
- UnregisterFromLoggingServiceIfNecessary();
+void PasswordManagerInternalsUIHandler::OnJavascriptAllowed() {
+ StartSubscription();
}
-void PasswordManagerInternalsUI::DidStopLoading() {
- web_ui()->CallJavascriptFunctionUnsafe("setUpPasswordManagerInternals");
- DCHECK(!registered_with_logging_service_);
- PasswordManagerInternalsService* service =
- PasswordManagerInternalsServiceFactory::GetForBrowserContext(
- Profile::FromWebUI(web_ui()));
- // No service means the WebUI is displayed in Incognito.
- base::Value is_incognito(!service);
- web_ui()->CallJavascriptFunctionUnsafe("notifyAboutIncognito", is_incognito);
-
- if (service) {
- registered_with_logging_service_ = true;
-
- std::string past_logs(service->RegisterReceiver(this));
- LogSavePasswordProgress(past_logs);
- }
-
- // Reset the first run experience for auto sign-in if the user opened
- // chrome://password-manager-internals/?reset_fre .
- // TODO(crbug.com/599454) This may be removed in M53, when the credential
- // manager API has been launched to stable.
- GURL url = web_ui()->GetWebContents()->GetVisibleURL();
- if (url.is_valid() && url.has_query()) {
- std::vector<std::string> query_parameters = base::SplitString(
- url.query(), "&", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
- if (base::ContainsValue(query_parameters, "reset_fre"))
- ResetAutoSignInFirstRunExperience();
- }
+void PasswordManagerInternalsUIHandler::OnJavascriptDisallowed() {
+ EndSubscription();
}
-void PasswordManagerInternalsUI::LogSavePasswordProgress(
- const std::string& text) {
- if (!registered_with_logging_service_ || text.empty())
+void PasswordManagerInternalsUIHandler::OnLoaded(const base::ListValue* args) {
+ AllowJavascript();
+ CallJavascriptFunction("setUpPasswordManagerInternals");
+ CallJavascriptFunction(
+ "notifyAboutIncognito",
+ base::Value(Profile::FromWebUI(web_ui())->IsIncognitoProfile()));
+}
+
+void PasswordManagerInternalsUIHandler::StartSubscription() {
+ LogRouter* log_router = PasswordManagerLogRouterFactory::GetForBrowserContext(
+ Profile::FromWebUI(web_ui()));
+ if (!log_router)
return;
- std::string no_quotes(text);
- std::replace(no_quotes.begin(), no_quotes.end(), '"', ' ');
- base::Value text_string_value(net::EscapeForHTML(no_quotes));
- web_ui()->CallJavascriptFunctionUnsafe("addLog", text_string_value);
+
+ registered_with_log_router_ = true;
+
+ const auto& past_logs = log_router->RegisterReceiver(this);
+ for (const auto& entry : past_logs)
+ LogEntry(entry);
}
-void PasswordManagerInternalsUI::UnregisterFromLoggingServiceIfNecessary() {
- if (!registered_with_logging_service_)
+void PasswordManagerInternalsUIHandler::EndSubscription() {
+ if (!registered_with_log_router_)
return;
- registered_with_logging_service_ = false;
- PasswordManagerInternalsService* service =
- PasswordManagerInternalsServiceFactory::GetForBrowserContext(
- Profile::FromWebUI(web_ui()));
- if (service)
- service->UnregisterReceiver(this);
+ registered_with_log_router_ = false;
+ LogRouter* log_router = PasswordManagerLogRouterFactory::GetForBrowserContext(
+ Profile::FromWebUI(web_ui()));
+ if (log_router)
+ log_router->UnregisterReceiver(this);
}
-void PasswordManagerInternalsUI::ResetAutoSignInFirstRunExperience() {
- Profile* profile = Profile::FromWebUI(web_ui());
- if (profile->IsRegularProfile()) {
- profile->GetPrefs()->SetBoolean(
- password_manager::prefs::kWasAutoSignInFirstRunExperienceShown, false);
-
- PasswordManagerInternalsService* service =
- PasswordManagerInternalsServiceFactory::GetForBrowserContext(
- Profile::FromWebUI(web_ui()));
- if (service)
- service->ProcessLog("Reset auto sign-in first run experience: yes");
- }
+void PasswordManagerInternalsUIHandler::LogEntry(const base::Value& entry) {
+ if (!registered_with_log_router_ || entry.is_none())
+ return;
+ CallJavascriptFunction("addRawLog", entry);
}
+
+} // namespace
+
+PasswordManagerInternalsUI::PasswordManagerInternalsUI(content::WebUI* web_ui)
+ : WebUIController(web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+ content::WebUIDataSource::Add(profile,
+ CreatePasswordManagerInternalsHTMLSource());
+ web_ui->AddMessageHandler(
+ std::make_unique<PasswordManagerInternalsUIHandler>());
+}
+
+PasswordManagerInternalsUI::~PasswordManagerInternalsUI() = default;
diff --git a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h b/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h
index 510408b44df..586ce8e2940 100644
--- a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h
+++ b/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui.h
@@ -6,35 +6,15 @@
#define CHROME_BROWSER_UI_WEBUI_PASSWORD_MANAGER_INTERNALS_PASSWORD_MANAGER_INTERNALS_UI_H_
#include "base/macros.h"
-#include "components/password_manager/core/browser/log_receiver.h"
-#include "content/public/browser/web_contents_observer.h"
+#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_controller.h"
-class PasswordManagerInternalsUI : public content::WebUIController,
- public content::WebContentsObserver,
- public password_manager::LogReceiver {
+class PasswordManagerInternalsUI : public content::WebUIController {
public:
explicit PasswordManagerInternalsUI(content::WebUI* web_ui);
~PasswordManagerInternalsUI() override;
- // WebContentsObserver implementation.
- void DidStartLoading() override;
- void DidStopLoading() override;
-
- // LogReceiver implementation.
- void LogSavePasswordProgress(const std::string& text) override;
-
private:
- // If currently registered with PasswordManagerInternalsService, unregisters
- // |this|. Otherwise this is a no-op.
- void UnregisterFromLoggingServiceIfNecessary();
-
- void ResetAutoSignInFirstRunExperience();
-
- // Whether |this| registered as a log receiver with the
- // PasswordManagerInternalsService.
- bool registered_with_logging_service_;
-
DISALLOW_COPY_AND_ASSIGN(PasswordManagerInternalsUI);
};
diff --git a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui_browsertest.cc
index a2d08b5ed6b..5d84d3044ff 100644
--- a/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/password_manager_internals/password_manager_internals_ui_browsertest.cc
@@ -9,8 +9,8 @@
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/base/web_ui_browser_test.h"
-#include "components/password_manager/content/browser/password_manager_internals_service_factory.h"
-#include "components/password_manager/core/browser/password_manager_internals_service.h"
+#include "components/autofill/core/browser/logging/log_router.h"
+#include "components/password_manager/content/browser/password_manager_log_router_factory.h"
#include "content/public/browser/web_contents.h"
class PasswordManagerInternalsWebUIBrowserTest : public WebUIBrowserTest {
@@ -72,34 +72,33 @@ void PasswordManagerInternalsWebUIBrowserTest::OpenInternalsPageWithBrowser(
GetWebContents()->GetWebUI()->GetController());
}
-IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
- LogSavePasswordProgress) {
- password_manager::PasswordManagerInternalsService* service =
- password_manager::PasswordManagerInternalsServiceFactory::
- GetForBrowserContext(browser()->profile());
- ASSERT_TRUE(service);
- service->ProcessLog("<script> text for testing");
+IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest, LogEntry) {
+ autofill::LogRouter* log_router =
+ password_manager::PasswordManagerLogRouterFactory::GetForBrowserContext(
+ browser()->profile());
+ ASSERT_TRUE(log_router);
+ log_router->ProcessLog("<script> text for testing");
ASSERT_TRUE(RunJavascriptTest("testLogText"));
}
// Test that a single internals page is empty on load.
IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
- LogSavePasswordProgress_EmptyOnLoad) {
- password_manager::PasswordManagerInternalsService* service =
- password_manager::PasswordManagerInternalsServiceFactory::
- GetForBrowserContext(browser()->profile());
- ASSERT_TRUE(service);
+ LogEntry_EmptyOnLoad) {
+ autofill::LogRouter* log_router =
+ password_manager::PasswordManagerLogRouterFactory::GetForBrowserContext(
+ browser()->profile());
+ ASSERT_TRUE(log_router);
ASSERT_TRUE(RunJavascriptTest("testLogEmpty"));
}
// Test that a single internals page is flushed on reload.
IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
- LogSavePasswordProgress_FlushedOnReload) {
- password_manager::PasswordManagerInternalsService* service =
- password_manager::PasswordManagerInternalsServiceFactory::
- GetForBrowserContext(browser()->profile());
- ASSERT_TRUE(service);
- service->ProcessLog("<script> text for testing");
+ LogEntry_FlushedOnReload) {
+ autofill::LogRouter* log_router =
+ password_manager::PasswordManagerLogRouterFactory::GetForBrowserContext(
+ browser()->profile());
+ ASSERT_TRUE(log_router);
+ log_router->ProcessLog("<script> text for testing");
OpenInternalsPage(WindowOpenDisposition::CURRENT_TAB); // Reload.
ASSERT_TRUE(RunJavascriptTest("testLogEmpty"));
}
@@ -110,13 +109,13 @@ IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
// waits with displaying until the internals page is ready (trying to display
// the old logs just on construction time would fail).
IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
- LogSavePasswordProgress_MultipleTabsIdentical) {
+ LogEntry_MultipleTabsIdentical) {
// First, open one tab with the internals page, and log something.
- password_manager::PasswordManagerInternalsService* service =
- password_manager::PasswordManagerInternalsServiceFactory::
- GetForBrowserContext(browser()->profile());
- ASSERT_TRUE(service);
- service->ProcessLog("<script> text for testing");
+ autofill::LogRouter* log_router =
+ password_manager::PasswordManagerLogRouterFactory::GetForBrowserContext(
+ browser()->profile());
+ ASSERT_TRUE(log_router);
+ log_router->ProcessLog("<script> text for testing");
ASSERT_TRUE(RunJavascriptTest("testLogText"));
// Now open a second tab with the internals page, but do not log anything.
OpenInternalsPage(WindowOpenDisposition::NEW_FOREGROUND_TAB);
@@ -127,15 +126,15 @@ IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
// Test that in the presence of more internals pages, reload does not cause
// flushing the logs.
IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
- LogSavePasswordProgress_NotFlushedOnReloadIfMultiple) {
+ LogEntry_NotFlushedOnReloadIfMultiple) {
// Open one more tab with the internals page.
OpenInternalsPage(WindowOpenDisposition::NEW_FOREGROUND_TAB);
// Now log something.
- password_manager::PasswordManagerInternalsService* service =
- password_manager::PasswordManagerInternalsServiceFactory::
- GetForBrowserContext(browser()->profile());
- ASSERT_TRUE(service);
- service->ProcessLog("<script> text for testing");
+ autofill::LogRouter* log_router =
+ password_manager::PasswordManagerLogRouterFactory::GetForBrowserContext(
+ browser()->profile());
+ ASSERT_TRUE(log_router);
+ log_router->ProcessLog("<script> text for testing");
// Reload.
OpenInternalsPage(WindowOpenDisposition::CURRENT_TAB);
// The text should still be there.
@@ -144,22 +143,22 @@ IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
// Test that navigation away from the internals page works OK.
IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
- LogSavePasswordProgress_NavigateAway) {
- password_manager::PasswordManagerInternalsService* service =
- password_manager::PasswordManagerInternalsServiceFactory::
- GetForBrowserContext(browser()->profile());
- ASSERT_TRUE(service);
- service->ProcessLog("<script> text for testing");
+ LogEntry_NavigateAway) {
+ autofill::LogRouter* log_router =
+ password_manager::PasswordManagerLogRouterFactory::GetForBrowserContext(
+ browser()->profile());
+ ASSERT_TRUE(log_router);
+ log_router->ProcessLog("<script> text for testing");
ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIVersionURL));
}
// Test that the description is correct in a non-Incognito tab.
IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
NonIncognitoMessage) {
- password_manager::PasswordManagerInternalsService* service =
- password_manager::PasswordManagerInternalsServiceFactory::
- GetForBrowserContext(browser()->profile());
- ASSERT_TRUE(service);
+ autofill::LogRouter* log_router =
+ password_manager::PasswordManagerLogRouterFactory::GetForBrowserContext(
+ browser()->profile());
+ ASSERT_TRUE(log_router);
ASSERT_TRUE(RunJavascriptTest("testNonIncognitoDescription"));
}
@@ -167,10 +166,10 @@ IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
IN_PROC_BROWSER_TEST_F(PasswordManagerInternalsWebUIBrowserTest,
IncognitoMessage) {
Browser* incognito = CreateIncognitoBrowser();
- password_manager::PasswordManagerInternalsService* service =
- password_manager::PasswordManagerInternalsServiceFactory::
- GetForBrowserContext(incognito->profile()->GetOffTheRecordProfile());
- EXPECT_FALSE(service); // There should be no service for Incognito.
+ autofill::LogRouter* log_router =
+ password_manager::PasswordManagerLogRouterFactory::GetForBrowserContext(
+ incognito->profile()->GetOffTheRecordProfile());
+ EXPECT_FALSE(log_router); // There should be no log_router for Incognito.
OpenInternalsPageWithBrowser(incognito, WindowOpenDisposition::CURRENT_TAB);
SetWebUIInstance(
incognito->tab_strip_model()->GetActiveWebContents()->GetWebUI());
diff --git a/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc
index cc28e91c1c8..f2194caae69 100644
--- a/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc
+++ b/chromium/chrome/browser/ui/webui/policy_indicator_localized_strings_provider.cc
@@ -35,6 +35,8 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source) {
{"controlledSettingWithOwner", IDS_CONTROLLED_SETTING_WITH_OWNER},
{"controlledSettingNoOwner", IDS_CONTROLLED_SETTING_NO_OWNER},
{"controlledSettingParent", IDS_CONTROLLED_SETTING_PARENT},
+ {"controlledSettingChildRestriction",
+ IDS_CONTROLLED_SETTING_CHILD_RESTRICTION},
#endif
};
AddLocalizedStringsBulk(html_source, localized_strings,
diff --git a/chromium/chrome/browser/ui/webui/policy_ui.cc b/chromium/chrome/browser/ui/webui/policy_ui.cc
index d06ccd10656..81efd814b86 100644
--- a/chromium/chrome/browser/ui/webui/policy_ui.cc
+++ b/chromium/chrome/browser/ui/webui/policy_ui.cc
@@ -27,6 +27,8 @@ content::WebUIDataSource* CreatePolicyUIHtmlSource() {
{"exportPoliciesJSON", IDS_EXPORT_POLICIES_JSON},
{"filterPlaceholder", IDS_POLICY_FILTER_PLACEHOLDER},
{"hideExpandedStatus", IDS_POLICY_HIDE_EXPANDED_STATUS},
+ {"isAffiliatedYes", IDS_POLICY_IS_AFFILIATED_YES},
+ {"isAffiliatedNo", IDS_POLICY_IS_AFFILIATED_NO},
{"labelAssetId", IDS_POLICY_LABEL_ASSET_ID},
{"labelClientId", IDS_POLICY_LABEL_CLIENT_ID},
{"labelDirectoryApiId", IDS_POLICY_LABEL_DIRECTORY_API_ID},
@@ -35,6 +37,7 @@ content::WebUIDataSource* CreatePolicyUIHtmlSource() {
{"labelEnterpriseEnrollmentDomain",
IDS_POLICY_LABEL_ENTERPRISE_ENROLLMENT_DOMAIN},
{"labelGaiaId", IDS_POLICY_LABEL_GAIA_ID},
+ {"labelIsAffiliated", IDS_POLICY_LABEL_IS_AFFILIATED},
{"labelLocation", IDS_POLICY_LABEL_LOCATION},
{"labelMachineEnrollmentDomain",
IDS_POLICY_LABEL_MACHINE_ENROLLMENT_DOMAIN},
@@ -44,12 +47,15 @@ content::WebUIDataSource* CreatePolicyUIHtmlSource() {
IDS_POLICY_LABEL_MACHINE_ENROLLMENT_TOKEN},
{"labelMachineEntrollmentDeviceId",
IDS_POLICY_LABEL_MACHINE_ENROLLMENT_DEVICE_ID},
+ {"labelIsOffHoursActive", IDS_POLICY_LABEL_IS_OFFHOURS_ACTIVE},
{"labelPoliciesPush", IDS_POLICY_LABEL_PUSH_POLICIES},
{"labelRefreshInterval", IDS_POLICY_LABEL_REFRESH_INTERVAL},
{"labelStatus", IDS_POLICY_LABEL_STATUS},
{"labelTimeSinceLastRefresh", IDS_POLICY_LABEL_TIME_SINCE_LAST_REFRESH},
{"labelUsername", IDS_POLICY_LABEL_USERNAME},
{"noPoliciesSet", IDS_POLICY_NO_POLICIES_SET},
+ {"offHoursActive", IDS_POLICY_OFFHOURS_ACTIVE},
+ {"offHoursNotActive", IDS_POLICY_OFFHOURS_NOT_ACTIVE},
{"policiesPushOff", IDS_POLICY_PUSH_POLICIES_OFF},
{"policiesPushOn", IDS_POLICY_PUSH_POLICIES_ON},
{"policyLearnMore", IDS_POLICY_LEARN_MORE},
diff --git a/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc
index f06534a9171..e4ac4cf3d0b 100644
--- a/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/policy_ui_browsertest.cc
@@ -47,8 +47,8 @@
#include "ui/shell_dialogs/select_file_policy.h"
#include "url/gurl.h"
-using testing::Return;
using testing::_;
+using testing::Return;
namespace {
@@ -142,6 +142,21 @@ std::vector<std::string> PopulateExpectedPolicy(
return expected_policy;
}
+void SetChromeMetaData(base::DictionaryValue* expected) {
+ // Only set the expected keys and types and not the values since
+ // these can vary greatly on the platform, OS, architecture
+ // that is running.
+ constexpr char prefix[] = "chromeMetadata";
+ expected->SetPath({prefix, "application"}, base::Value(""));
+ expected->SetPath({prefix, "version"}, base::Value(""));
+ expected->SetPath({prefix, "revision"}, base::Value(""));
+#if defined(OS_CHROMEOS)
+ expected->SetPath({prefix, "platform"}, base::Value(""));
+#else
+ expected->SetPath({prefix, "OS"}, base::Value(""));
+#endif
+}
+
void SetExpectedPolicy(base::DictionaryValue* expected,
const std::string& name,
const std::string& level,
@@ -185,7 +200,7 @@ class PolicyUITest : public InProcessBrowserTest {
const policy::PolicyNamespace& policy_namespace,
const policy::PolicyMap& policy);
- void VerifyPolicies(const std::vector<std::vector<std::string> >& expected);
+ void VerifyPolicies(const std::vector<std::vector<std::string>>& expected);
void VerifyExportingPolicies(const base::DictionaryValue& expected);
@@ -237,11 +252,9 @@ class TestSelectFileDialogFactory : public ui::SelectFileDialogFactory {
}
};
-PolicyUITest::PolicyUITest() {
-}
+PolicyUITest::PolicyUITest() {}
-PolicyUITest::~PolicyUITest() {
-}
+PolicyUITest::~PolicyUITest() {}
void PolicyUITest::SetUpInProcessBrowserTestFixture() {
EXPECT_CALL(provider_, IsInitializationComplete(_))
@@ -266,7 +279,7 @@ void PolicyUITest::UpdateProviderPolicyForNamespace(
}
void PolicyUITest::VerifyPolicies(
- const std::vector<std::vector<std::string> >& expected_policies) {
+ const std::vector<std::vector<std::string>>& expected_policies) {
ui_test_utils::NavigateToURL(browser(), GURL("chrome://policy"));
// Retrieve the text contents of the policy table cells for all policies.
@@ -289,8 +302,8 @@ void PolicyUITest::VerifyPolicies(
content::WebContents* contents =
browser()->tab_strip_model()->GetActiveWebContents();
std::string json;
- ASSERT_TRUE(content::ExecuteScriptAndExtractString(contents, javascript,
- &json));
+ ASSERT_TRUE(
+ content::ExecuteScriptAndExtractString(contents, javascript, &json));
std::unique_ptr<base::Value> value_ptr =
base::JSONReader::ReadDeprecated(json);
const base::ListValue* actual_policies = NULL;
@@ -344,6 +357,24 @@ void PolicyUITest::VerifyExportingPolicies(
base::DictionaryValue* actual_policies = nullptr;
EXPECT_TRUE(value_ptr->GetAsDictionary(&actual_policies));
+ // Since Chrome Metadata has a lot of variations based on platform, OS,
+ // architecture and version, it is difficult to test for exact values. Test
+ // instead that the same keys exist in the meta data and also that the type of
+ // all the keys is a string. The incoming |expected| value should already be
+ // filled with the expected keys.
+ base::Value* chrome_metadata = actual_policies->FindKeyOfType(
+ "chromeMetadata", base::Value::Type::DICTIONARY);
+ EXPECT_NE(chrome_metadata, nullptr);
+
+ base::DictionaryValue* chrome_metadata_dict = nullptr;
+ EXPECT_TRUE(chrome_metadata->GetAsDictionary(&chrome_metadata_dict));
+
+ // The |chrome_metadata| we compare against will have the actual values so
+ // those will be cleared to empty values so that the equals comparison below
+ // will just compare key existence and value types.
+ for (auto& key_value : *chrome_metadata_dict)
+ *(key_value.second) = base::Value(key_value.second->type());
+
// Check that this dictionary is the same as expected.
EXPECT_EQ(expected, *actual_policies);
}
@@ -353,6 +384,8 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, WritePoliciesToJSONFile) {
policy::PolicyMap values;
base::DictionaryValue expected_values;
+ SetChromeMetaData(&expected_values);
+
base::ListValue popups_blocked_for_urls;
popups_blocked_for_urls.AppendString("aaa");
popups_blocked_for_urls.AppendString("bbb");
@@ -361,14 +394,14 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, WritePoliciesToJSONFile) {
policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_PLATFORM,
popups_blocked_for_urls.CreateDeepCopy(), nullptr);
SetExpectedPolicy(&expected_values, policy::key::kPopupsBlockedForUrls,
- "mandatory", "machine", "sourcePlatform", std::string(),
+ "mandatory", "machine", "platform", std::string(),
std::string(), false, popups_blocked_for_urls);
values.Set(policy::key::kDefaultImagesSetting, policy::POLICY_LEVEL_MANDATORY,
policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD,
std::make_unique<base::Value>(2), nullptr);
SetExpectedPolicy(&expected_values, policy::key::kDefaultImagesSetting,
- "mandatory", "machine", "sourceCloud", std::string(),
+ "mandatory", "machine", "cloud", std::string(),
std::string(), false, base::Value(2));
// This also checks that we save complex policies correctly.
@@ -383,7 +416,7 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, WritePoliciesToJSONFile) {
policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
unknown_policy.CreateDeepCopy(), nullptr);
SetExpectedPolicy(&expected_values, kUnknownPolicy, "recommended", "user",
- "sourceCloud", l10n_util::GetStringUTF8(IDS_POLICY_UNKNOWN),
+ "cloud", l10n_util::GetStringUTF8(IDS_POLICY_UNKNOWN),
std::string(), false, unknown_policy);
// Set the extension policies to an empty dictionary as we haven't added any
@@ -415,7 +448,7 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, WritePoliciesToJSONFile) {
policy::POLICY_SOURCE_PLATFORM,
std::make_unique<base::Value>(false), nullptr);
SetExpectedPolicy(&expected_values, policy::key::kAllowFileSelectionDialogs,
- "mandatory", "machine", "sourcePlatform", std::string(),
+ "mandatory", "machine", "platform", std::string(),
std::string(), false, base::Value(false));
#endif
@@ -424,7 +457,7 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, WritePoliciesToJSONFile) {
policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_PLATFORM,
popups_blocked_for_urls.CreateDeepCopy(), nullptr);
SetExpectedPolicy(&expected_values, policy::key::kPopupsBlockedForUrls,
- "mandatory", "machine", "sourcePlatform", std::string(),
+ "mandatory", "machine", "platform", std::string(),
std::string(), false, popups_blocked_for_urls);
provider_.UpdateChromePolicy(values);
@@ -441,15 +474,14 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, SendPolicyNames) {
// Expect that the policy table contains all known policies in alphabetical
// order and none of the policies have a set value.
- std::vector<std::vector<std::string> > expected_policies;
+ std::vector<std::vector<std::string>> expected_policies;
policy::Schema chrome_schema =
policy::Schema::Wrap(policy::GetChromeSchemaData());
ASSERT_TRUE(chrome_schema.valid());
for (policy::Schema::Iterator it = chrome_schema.GetPropertiesIterator();
!it.IsAtEnd(); it.Advance()) {
- expected_policies.push_back(
- PopulateExpectedPolicy(
- it.key(), std::string(), std::string(), nullptr, false));
+ expected_policies.push_back(PopulateExpectedPolicy(
+ it.key(), std::string(), std::string(), nullptr, false));
}
// Retrieve the contents of the policy table from the UI and verify that it
@@ -504,7 +536,7 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, SendPolicyValues) {
// * All known policies whose value has been set, in alphabetical order.
// * The unknown policy.
// * All known policies whose value has not been set, in alphabetical order.
- std::vector<std::vector<std::string> > expected_policies;
+ std::vector<std::vector<std::string>> expected_policies;
size_t first_unset_position = 0;
policy::Schema chrome_schema =
policy::Schema::Wrap(policy::GetChromeSchemaData());
@@ -519,17 +551,14 @@ IN_PROC_BROWSER_TEST_F(PolicyUITest, SendPolicyValues) {
it == expected_values.end() ? std::string() : "Cloud";
const policy::PolicyMap::Entry* metadata = values.Get(props.key());
expected_policies.insert(
- metadata ? expected_policies.begin() + first_unset_position++ :
- expected_policies.end(),
+ metadata ? expected_policies.begin() + first_unset_position++
+ : expected_policies.end(),
PopulateExpectedPolicy(props.key(), value, source, metadata, false));
}
expected_policies.insert(
expected_policies.begin() + first_unset_position++,
- PopulateExpectedPolicy(kUnknownPolicy,
- expected_values[kUnknownPolicy],
- "Platform",
- values.Get(kUnknownPolicy),
- true));
+ PopulateExpectedPolicy(kUnknownPolicy, expected_values[kUnknownPolicy],
+ "Platform", values.Get(kUnknownPolicy), true));
expected_policies.insert(
expected_policies.begin() + first_unset_position++,
PopulateExpectedPolicy(
diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc
index 33b1ba64e8c..85b71b8f5ea 100644
--- a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc
+++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc
@@ -18,6 +18,8 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string16.h"
+#include "base/strings/stringprintf.h"
+#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "base/task/task_traits.h"
#include "base/time/time.h"
@@ -32,6 +34,8 @@
#include "chrome/browser/policy/schema_registry_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/localized_string.h"
+#include "chrome/common/channel_info.h"
+#include "chrome/grit/chromium_strings.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/browser/cloud/message_util.h"
#include "components/policy/core/browser/configuration_policy_handler_list.h"
@@ -54,6 +58,7 @@
#include "components/policy/policy_constants.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "components/strings/grit/components_strings.h"
+#include "components/version_info/version_info.h"
#include "content/public/browser/web_contents.h"
#include "extensions/buildflags/buildflags.h"
#include "google_apis/gaia/gaia_auth_util.h"
@@ -61,18 +66,33 @@
#include "ui/base/l10n/time_format.h"
#include "ui/shell_dialogs/select_file_policy.h"
+#if defined(OS_ANDROID)
+#include "chrome/browser/ui/android/android_about_app_info.h"
+#endif
+
#if defined(OS_CHROMEOS)
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/chromeos/policy/active_directory_policy_manager.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h"
#include "chrome/browser/chromeos/policy/device_local_account_policy_service.h"
+#include "chrome/browser/chromeos/policy/off_hours/device_off_hours_controller.h"
#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#include "chromeos/dbus/util/version_loader.h"
#include "components/user_manager/user_manager.h"
#else
#include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
#endif
+#if defined(OS_MACOSX)
+#include "base/mac/mac_util.h"
+#endif
+
+#if defined(OS_WIN)
+#include "chrome/browser/ui/webui/version_util_win.h"
+#endif
+
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
@@ -144,33 +164,58 @@ void GetStatusFromCore(const policy::CloudPolicyCore* core,
if (policy && policy->has_gaia_id())
dict->SetString("gaiaId", policy->gaia_id());
- base::TimeDelta refresh_interval =
- base::TimeDelta::FromMilliseconds(refresh_scheduler ?
- refresh_scheduler->GetActualRefreshDelay() :
- policy::CloudPolicyRefreshScheduler::kDefaultRefreshDelayMs);
- base::Time last_refresh_time = refresh_scheduler ?
- refresh_scheduler->last_refresh() : base::Time();
+ base::TimeDelta refresh_interval = base::TimeDelta::FromMilliseconds(
+ refresh_scheduler
+ ? refresh_scheduler->GetActualRefreshDelay()
+ : policy::CloudPolicyRefreshScheduler::kDefaultRefreshDelayMs);
+ base::Time last_refresh_time =
+ refresh_scheduler ? refresh_scheduler->last_refresh() : base::Time();
bool no_error = store->status() == policy::CloudPolicyStore::STATUS_OK &&
client && client->status() == policy::DM_STATUS_SUCCESS;
dict->SetBoolean("error", !no_error);
- dict->SetBoolean("policiesPushAvailable",
- refresh_scheduler->invalidations_available());
+ dict->SetBoolean(
+ "policiesPushAvailable",
+ refresh_scheduler ? refresh_scheduler->invalidations_available() : false);
dict->SetString("status", status);
dict->SetString("clientId", client_id);
dict->SetString("username", username);
- dict->SetString("refreshInterval",
- ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_DURATION,
- ui::TimeFormat::LENGTH_SHORT,
- refresh_interval));
- dict->SetString("timeSinceLastRefresh", last_refresh_time.is_null() ?
- l10n_util::GetStringUTF16(IDS_POLICY_NEVER_FETCHED) :
- ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED,
- ui::TimeFormat::LENGTH_SHORT,
- base::Time::NowFromSystemTime() -
- last_refresh_time));
+ dict->SetString(
+ "refreshInterval",
+ ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_DURATION,
+ ui::TimeFormat::LENGTH_SHORT, refresh_interval));
+ dict->SetString(
+ "timeSinceLastRefresh",
+ last_refresh_time.is_null()
+ ? l10n_util::GetStringUTF16(IDS_POLICY_NEVER_FETCHED)
+ : ui::TimeFormat::Simple(
+ ui::TimeFormat::FORMAT_ELAPSED, ui::TimeFormat::LENGTH_SHORT,
+ base::Time::NowFromSystemTime() - last_refresh_time));
+}
+
+#if defined(OS_CHROMEOS)
+// Adds a new entry to |dict| with the affiliation status of the user associated
+// with |profile|. Device scope policy status providers call this method with
+// nullptr |profile|. In this case no entry is added as affiliation status only
+// makes sense for user scope policy status providers.
+void GetUserAffiliationStatus(base::DictionaryValue* dict, Profile* profile) {
+ if (!profile)
+ return;
+ const user_manager::User* user =
+ chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
+ if (!user)
+ return;
+ dict->SetBoolean("isAffiliated", user->IsAffiliated());
}
+void GetOffHoursStatus(base::DictionaryValue* dict) {
+ policy::off_hours::DeviceOffHoursController* off_hours_controller =
+ chromeos::DeviceSettingsService::Get()->device_off_hours_controller();
+ if (off_hours_controller)
+ dict->SetBoolean("isOffHoursActive", off_hours_controller->is_off_hours_mode());
+}
+#endif // defined(OS_CHROMEOS)
+
void ExtractDomainFromUsername(base::DictionaryValue* dict) {
std::string username;
dict->GetString("username", &username);
@@ -239,6 +284,24 @@ class UserCloudPolicyStatusProvider : public CloudPolicyCoreStatusProvider {
DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyStatusProvider);
};
+#if defined(OS_CHROMEOS)
+// A cloud policy status provider for user policy on Chrome OS.
+class UserCloudPolicyStatusProviderChromeOS
+ : public UserCloudPolicyStatusProvider {
+ public:
+ explicit UserCloudPolicyStatusProviderChromeOS(policy::CloudPolicyCore* core,
+ Profile* profile);
+ ~UserCloudPolicyStatusProviderChromeOS() override;
+
+ // CloudPolicyCoreStatusProvider implementation.
+ void GetStatus(base::DictionaryValue* dict) override;
+
+ private:
+ Profile* profile_;
+ DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyStatusProviderChromeOS);
+};
+#endif // defined(OS_CHROMEOS)
+
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
class MachineLevelUserCloudPolicyStatusProvider
: public PolicyStatusProvider,
@@ -263,11 +326,12 @@ class MachineLevelUserCloudPolicyStatusProvider
#if defined(OS_CHROMEOS)
// A cloud policy status provider for device policy.
-class DeviceCloudPolicyStatusProvider : public CloudPolicyCoreStatusProvider {
+class DeviceCloudPolicyStatusProviderChromeOS
+ : public CloudPolicyCoreStatusProvider {
public:
- explicit DeviceCloudPolicyStatusProvider(
+ explicit DeviceCloudPolicyStatusProviderChromeOS(
policy::BrowserPolicyConnectorChromeOS* connector);
- ~DeviceCloudPolicyStatusProvider() override;
+ ~DeviceCloudPolicyStatusProviderChromeOS() override;
// CloudPolicyCoreStatusProvider implementation.
void GetStatus(base::DictionaryValue* dict) override;
@@ -276,7 +340,7 @@ class DeviceCloudPolicyStatusProvider : public CloudPolicyCoreStatusProvider {
std::string enterprise_enrollment_domain_;
std::string enterprise_display_domain_;
- DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyStatusProvider);
+ DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyStatusProviderChromeOS);
};
// A cloud policy status provider that reads policy status from the policy core
@@ -314,7 +378,8 @@ class UserActiveDirectoryPolicyStatusProvider
public policy::CloudPolicyStore::Observer {
public:
explicit UserActiveDirectoryPolicyStatusProvider(
- policy::ActiveDirectoryPolicyManager* policy_manager);
+ policy::ActiveDirectoryPolicyManager* policy_manager,
+ Profile* profile);
~UserActiveDirectoryPolicyStatusProvider() override;
@@ -327,7 +392,7 @@ class UserActiveDirectoryPolicyStatusProvider
private:
policy::ActiveDirectoryPolicyManager* const policy_manager_; // not owned.
-
+ Profile* profile_;
DISALLOW_COPY_AND_ASSIGN(UserActiveDirectoryPolicyStatusProvider);
};
@@ -370,7 +435,8 @@ void PolicyStatusProvider::NotifyStatusChange() {
}
CloudPolicyCoreStatusProvider::CloudPolicyCoreStatusProvider(
- policy::CloudPolicyCore* core) : core_(core) {
+ policy::CloudPolicyCore* core)
+ : core_(core) {
core_->store()->AddObserver(this);
// TODO(bartfab): Add an observer that watches for client errors. Observing
// core_->client() directly is not safe as the client may be destroyed and
@@ -404,6 +470,26 @@ void UserCloudPolicyStatusProvider::GetStatus(base::DictionaryValue* dict) {
ExtractDomainFromUsername(dict);
}
+#if defined(OS_CHROMEOS)
+UserCloudPolicyStatusProviderChromeOS::UserCloudPolicyStatusProviderChromeOS(
+ policy::CloudPolicyCore* core,
+ Profile* profile)
+ : UserCloudPolicyStatusProvider(core) {
+ profile_ = profile;
+}
+
+UserCloudPolicyStatusProviderChromeOS::
+ ~UserCloudPolicyStatusProviderChromeOS() {}
+
+void UserCloudPolicyStatusProviderChromeOS::GetStatus(
+ base::DictionaryValue* dict) {
+ if (!core_->store()->is_managed())
+ return;
+ UserCloudPolicyStatusProvider::GetStatus(dict);
+ GetUserAffiliationStatus(dict, profile_);
+}
+#endif // defined(OS_CHROMEOS)
+
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
MachineLevelUserCloudPolicyStatusProvider::
@@ -472,27 +558,30 @@ void MachineLevelUserCloudPolicyStatusProvider::OnStoreError(
#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
#if defined(OS_CHROMEOS)
-DeviceCloudPolicyStatusProvider::DeviceCloudPolicyStatusProvider(
- policy::BrowserPolicyConnectorChromeOS* connector)
+DeviceCloudPolicyStatusProviderChromeOS::
+ DeviceCloudPolicyStatusProviderChromeOS(
+ policy::BrowserPolicyConnectorChromeOS* connector)
: CloudPolicyCoreStatusProvider(
connector->GetDeviceCloudPolicyManager()->core()) {
enterprise_enrollment_domain_ = connector->GetEnterpriseEnrollmentDomain();
enterprise_display_domain_ = connector->GetEnterpriseDisplayDomain();
}
-DeviceCloudPolicyStatusProvider::~DeviceCloudPolicyStatusProvider() = default;
+DeviceCloudPolicyStatusProviderChromeOS::
+ ~DeviceCloudPolicyStatusProviderChromeOS() = default;
-void DeviceCloudPolicyStatusProvider::GetStatus(base::DictionaryValue* dict) {
+void DeviceCloudPolicyStatusProviderChromeOS::GetStatus(
+ base::DictionaryValue* dict) {
GetStatusFromCore(core_, dict);
dict->SetString("enterpriseEnrollmentDomain", enterprise_enrollment_domain_);
dict->SetString("enterpriseDisplayDomain", enterprise_display_domain_);
+ GetOffHoursStatus(dict);
}
DeviceLocalAccountPolicyStatusProvider::DeviceLocalAccountPolicyStatusProvider(
const std::string& user_id,
policy::DeviceLocalAccountPolicyService* service)
- : user_id_(user_id),
- service_(service) {
+ : user_id_(user_id), service_(service) {
service_->AddObserver(this);
}
@@ -531,9 +620,11 @@ void DeviceLocalAccountPolicyStatusProvider::OnDeviceLocalAccountsChanged() {
UserActiveDirectoryPolicyStatusProvider::
UserActiveDirectoryPolicyStatusProvider(
- policy::ActiveDirectoryPolicyManager* policy_manager)
+ policy::ActiveDirectoryPolicyManager* policy_manager,
+ Profile* profile)
: policy_manager_(policy_manager) {
policy_manager_->store()->AddObserver(this);
+ profile_ = profile;
}
UserActiveDirectoryPolicyStatusProvider::
@@ -571,6 +662,7 @@ void UserActiveDirectoryPolicyStatusProvider::GetStatus(
: ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED,
ui::TimeFormat::LENGTH_SHORT,
base::Time::Now() - last_refresh_time));
+ GetUserAffiliationStatus(dict, profile_);
}
void UserActiveDirectoryPolicyStatusProvider::OnStoreLoaded(
@@ -588,7 +680,7 @@ DeviceActiveDirectoryPolicyStatusProvider::
policy::ActiveDirectoryPolicyManager* policy_manager,
const std::string& enterprise_realm,
const std::string& enterprise_display_domain)
- : UserActiveDirectoryPolicyStatusProvider(policy_manager),
+ : UserActiveDirectoryPolicyStatusProvider(policy_manager, nullptr),
enterprise_realm_(enterprise_realm),
enterprise_display_domain_(enterprise_display_domain) {}
@@ -601,9 +693,7 @@ void DeviceActiveDirectoryPolicyStatusProvider::GetStatus(
#endif // defined(OS_CHROMEOS)
-PolicyUIHandler::PolicyUIHandler()
- : weak_factory_(this) {
-}
+PolicyUIHandler::PolicyUIHandler() {}
PolicyUIHandler::~PolicyUIHandler() {
GetPolicyService()->RemoveObserver(policy::POLICY_DOMAIN_CHROME, this);
@@ -621,7 +711,7 @@ PolicyUIHandler::~PolicyUIHandler() {
}
void PolicyUIHandler::AddCommonLocalizedStringsToSource(
- content::WebUIDataSource* source) {
+ content::WebUIDataSource* source) {
AddLocalizedStringsBulk(source, policy::kPolicySources,
policy::POLICY_SOURCE_COUNT);
@@ -665,7 +755,7 @@ void PolicyUIHandler::RegisterMessages() {
connector->GetRealm(), connector->GetEnterpriseDisplayDomain());
} else {
device_status_provider_ =
- std::make_unique<DeviceCloudPolicyStatusProvider>(connector);
+ std::make_unique<DeviceCloudPolicyStatusProviderChromeOS>(connector);
}
}
@@ -685,12 +775,13 @@ void PolicyUIHandler::RegisterMessages() {
user_manager->GetActiveUser()->GetAccountId().GetUserEmail(),
local_account_service);
} else if (user_cloud_policy) {
- user_status_provider_ = std::make_unique<UserCloudPolicyStatusProvider>(
- user_cloud_policy->core());
+ user_status_provider_ =
+ std::make_unique<UserCloudPolicyStatusProviderChromeOS>(
+ user_cloud_policy->core(), profile);
} else if (active_directory_policy) {
user_status_provider_ =
std::make_unique<UserActiveDirectoryPolicyStatusProvider>(
- active_directory_policy);
+ active_directory_policy, profile);
}
#else
policy::UserCloudPolicyManager* user_cloud_policy_manager =
@@ -807,7 +898,7 @@ base::Value PolicyUIHandler::GetPolicyNames() const {
extensions::ExtensionRegistry::Get(profile)->enabled_extensions()) {
// Skip this extension if it's not an enterprise extension.
if (!extension->manifest()->HasPath(
- extensions::manifest_keys::kStorageManagedSchema))
+ extensions::manifest_keys::kStorageManagedSchema))
continue;
auto extension_value = std::make_unique<base::DictionaryValue>();
extension_value->SetString("name", extension->name());
@@ -835,7 +926,8 @@ base::Value PolicyUIHandler::GetPolicyValues() const {
return policy::GetAllPolicyValuesAsArray(
web_ui()->GetWebContents()->GetBrowserContext(),
true /* with_user_policies */, true /* convert_values */,
- false /* with_device_data */, true /* is_pretty_print */);
+ false /* with_device_data */, true /* is_pretty_print */,
+ true /* convert_types */);
}
void PolicyUIHandler::SendStatus() {
@@ -938,10 +1030,63 @@ void DoWritePoliciesToJSONFile(const base::FilePath& path,
void PolicyUIHandler::WritePoliciesToJSONFile(
const base::FilePath& path) const {
- std::string json_policies = policy::GetAllPolicyValuesAsJSON(
+ constexpr bool is_pretty_print = true;
+ base::Value dict = policy::GetAllPolicyValuesAsDictionary(
web_ui()->GetWebContents()->GetBrowserContext(),
- true /* with_user_policies */, false /* with_device_data */,
- true /* is_pretty_print */);
+ true /* with_user_policies */, false /* convert_values */,
+ false /* with_device_data */, is_pretty_print, true /* convert_types */);
+
+ base::Value chrome_metadata(base::Value::Type::DICTIONARY);
+
+ chrome_metadata.SetKey(
+ "application", base::Value(l10n_util::GetStringUTF8(IDS_PRODUCT_NAME)));
+ std::string cohort_name;
+#if defined(OS_WIN)
+ base::string16 cohort_version_info =
+ version_utils::win::GetCohortVersionInfo();
+ if (!cohort_version_info.empty()) {
+ cohort_name = base::StringPrintf(
+ " %s", base::UTF16ToUTF8(cohort_version_info).c_str());
+ }
+#endif
+ std::string channel_name = chrome::GetChannelName();
+ std::string version = base::StringPrintf(
+ "%s (%s)%s %s%s", version_info::GetVersionNumber().c_str(),
+ l10n_util::GetStringUTF8(version_info::IsOfficialBuild()
+ ? IDS_VERSION_UI_OFFICIAL
+ : IDS_VERSION_UI_UNOFFICIAL)
+ .c_str(),
+ (channel_name.empty() ? "" : " " + channel_name).c_str(),
+ l10n_util::GetStringUTF8(sizeof(void*) == 8 ? IDS_VERSION_UI_64BIT
+ : IDS_VERSION_UI_32BIT)
+ .c_str(),
+ cohort_name.c_str());
+ chrome_metadata.SetKey("version", base::Value(version));
+
+#if defined(OS_CHROMEOS)
+ chrome_metadata.SetKey("platform",
+ base::Value(chromeos::version_loader::GetVersion(
+ chromeos::version_loader::VERSION_FULL)));
+#elif defined(OS_MACOSX)
+ chrome_metadata.SetKey("OS", base::Value(base::mac::GetOSDisplayName()));
+#else
+ std::string os = version_info::GetOSType();
+#if defined(OS_WIN)
+ os += " " + version_utils::win::GetFullWindowsVersion();
+#elif defined(OS_ANDROID)
+ os += " " + AndroidAboutAppInfo::GetOsInfo();
+#endif
+ chrome_metadata.SetKey("OS", base::Value(os));
+#endif
+ chrome_metadata.SetKey("revision",
+ base::Value(version_info::GetLastChange()));
+
+ dict.SetKey("chromeMetadata", std::move(chrome_metadata));
+
+ std::string json_policies;
+ base::JSONWriter::WriteWithOptions(
+ dict, (is_pretty_print ? base::JSONWriter::OPTIONS_PRETTY_PRINT : 0),
+ &json_policies);
base::PostTaskWithTraits(
FROM_HERE,
diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.h b/chromium/chrome/browser/ui/webui/policy_ui_handler.h
index 368f2048c7a..3d0b89d3ac0 100644
--- a/chromium/chrome/browser/ui/webui/policy_ui_handler.h
+++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.h
@@ -107,7 +107,7 @@ class PolicyUIHandler : public content::WebUIMessageHandler,
std::unique_ptr<PolicyStatusProvider> device_status_provider_;
std::unique_ptr<PolicyStatusProvider> machine_status_provider_;
- base::WeakPtrFactory<PolicyUIHandler> weak_factory_;
+ base::WeakPtrFactory<PolicyUIHandler> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(PolicyUIHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/prefs_internals_source.cc b/chromium/chrome/browser/ui/webui/prefs_internals_source.cc
index 9d30d1190c5..382f02f3391 100644
--- a/chromium/chrome/browser/ui/webui/prefs_internals_source.cc
+++ b/chromium/chrome/browser/ui/webui/prefs_internals_source.cc
@@ -19,11 +19,11 @@ PrefsInternalsSource::PrefsInternalsSource(Profile* profile)
PrefsInternalsSource::~PrefsInternalsSource() = default;
-std::string PrefsInternalsSource::GetSource() const {
+std::string PrefsInternalsSource::GetSource() {
return chrome::kChromeUIPrefsInternalsHost;
}
-std::string PrefsInternalsSource::GetMimeType(const std::string& path) const {
+std::string PrefsInternalsSource::GetMimeType(const std::string& path) {
return "text/plain";
}
diff --git a/chromium/chrome/browser/ui/webui/prefs_internals_source.h b/chromium/chrome/browser/ui/webui/prefs_internals_source.h
index 471c05d09e6..d20af558b90 100644
--- a/chromium/chrome/browser/ui/webui/prefs_internals_source.h
+++ b/chromium/chrome/browser/ui/webui/prefs_internals_source.h
@@ -17,8 +17,8 @@ class PrefsInternalsSource : public content::URLDataSource {
~PrefsInternalsSource() override;
// content::URLDataSource:
- std::string GetSource() const override;
- std::string GetMimeType(const std::string& path) const override;
+ std::string GetSource() override;
+ std::string GetMimeType(const std::string& path) override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
diff --git a/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.cc
index 3a54ee701f8..c8d5070a3d6 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.cc
@@ -19,7 +19,7 @@ CloudPrinterHandler::~CloudPrinterHandler() {}
void CloudPrinterHandler::Reset() {}
void CloudPrinterHandler::StartGetPrinters(
- const AddedPrintersCallback& added_printers_callback,
+ AddedPrintersCallback added_printers_callback,
GetPrintersDoneCallback done_callback) {
// TODO(https://crbug.com/829414): Actually retrieve the printers
std::move(done_callback).Run();
diff --git a/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.h
index f6c198fbeee..8d8dbb8c7bd 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/cloud_printer_handler.h
@@ -22,7 +22,7 @@ class CloudPrinterHandler : public PrinterHandler {
// PrinterHandler implementation:
void Reset() override;
- void StartGetPrinters(const AddedPrintersCallback& added_printers_callback,
+ void StartGetPrinters(AddedPrintersCallback added_printers_callback,
GetPrintersDoneCallback done_callback) override;
void StartGetCapability(const std::string& destination_id,
GetCapabilityCallback calback) override;
diff --git a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc
index 731191984e1..38c8cd00de4 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.cc
@@ -107,7 +107,7 @@ extensions::PrinterProviderAPI* GetPrinterProviderAPI(Profile* profile) {
} // namespace
ExtensionPrinterHandler::ExtensionPrinterHandler(Profile* profile)
- : profile_(profile), weak_ptr_factory_(this) {}
+ : profile_(profile) {}
ExtensionPrinterHandler::~ExtensionPrinterHandler() {
}
@@ -120,7 +120,7 @@ void ExtensionPrinterHandler::Reset() {
}
void ExtensionPrinterHandler::StartGetPrinters(
- const AddedPrintersCallback& callback,
+ AddedPrintersCallback callback,
GetPrintersDoneCallback done_callback) {
// Assume that there can only be one printer enumeration occuring at once.
DCHECK_EQ(pending_enumeration_count_, 0);
@@ -142,13 +142,13 @@ void ExtensionPrinterHandler::StartGetPrinters(
UsbDeviceManager* usb_manager = UsbDeviceManager::Get(profile_);
DCHECK(usb_manager);
usb_manager->GetDevices(
- base::Bind(&ExtensionPrinterHandler::OnUsbDevicesEnumerated,
- weak_ptr_factory_.GetWeakPtr(), callback));
+ base::BindOnce(&ExtensionPrinterHandler::OnUsbDevicesEnumerated,
+ weak_ptr_factory_.GetWeakPtr(), callback));
}
GetPrinterProviderAPI(profile_)->DispatchGetPrintersRequested(
base::BindRepeating(&ExtensionPrinterHandler::WrapGetPrintersCallback,
- weak_ptr_factory_.GetWeakPtr(), callback));
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void ExtensionPrinterHandler::StartGetCapability(
@@ -280,7 +280,7 @@ void ExtensionPrinterHandler::DispatchPrintJob(
}
void ExtensionPrinterHandler::WrapGetPrintersCallback(
- const AddedPrintersCallback& callback,
+ AddedPrintersCallback callback,
const base::ListValue& printers,
bool done) {
DCHECK_GT(pending_enumeration_count_, 0);
@@ -317,7 +317,7 @@ void ExtensionPrinterHandler::WrapGetPrinterInfoCallback(
}
void ExtensionPrinterHandler::OnUsbDevicesEnumerated(
- const AddedPrintersCallback& callback,
+ AddedPrintersCallback callback,
std::vector<device::mojom::UsbDeviceInfoPtr> devices) {
ExtensionRegistry* registry = ExtensionRegistry::Get(profile_);
DevicePermissionsManager* permissions_manager =
diff --git a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h
index 2dacc08b396..2f88ff82df4 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler.h
@@ -48,7 +48,7 @@ class ExtensionPrinterHandler : public PrinterHandler {
// PrinterHandler implementation:
void Reset() override;
- void StartGetPrinters(const AddedPrintersCallback& added_printers_callback,
+ void StartGetPrinters(AddedPrintersCallback added_printers_callback,
GetPrintersDoneCallback done_callback) override;
void StartGetCapability(const std::string& destination_id,
GetCapabilityCallback callback) override;
@@ -83,7 +83,7 @@ class ExtensionPrinterHandler : public PrinterHandler {
// Methods used as wrappers to callbacks for extensions::PrinterProviderAPI
// methods, primarily so the callbacks can be bound to this class' weak ptr.
// They just propagate results to callbacks passed to them.
- void WrapGetPrintersCallback(const AddedPrintersCallback& callback,
+ void WrapGetPrintersCallback(AddedPrintersCallback callback,
const base::ListValue& printers,
bool done);
void WrapGetCapabilityCallback(GetCapabilityCallback callback,
@@ -93,7 +93,7 @@ class ExtensionPrinterHandler : public PrinterHandler {
const base::DictionaryValue& printer_info);
void OnUsbDevicesEnumerated(
- const AddedPrintersCallback& callback,
+ AddedPrintersCallback callback,
std::vector<device::mojom::UsbDeviceInfoPtr> devices);
Profile* const profile_;
@@ -102,7 +102,7 @@ class ExtensionPrinterHandler : public PrinterHandler {
std::unique_ptr<PwgRasterConverter> pwg_raster_converter_;
int pending_enumeration_count_ = 0;
- base::WeakPtrFactory<ExtensionPrinterHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<ExtensionPrinterHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ExtensionPrinterHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc
index 7d19304d092..13276fa5968 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/extension_printer_handler_unittest.cc
@@ -538,8 +538,8 @@ TEST_F(ExtensionPrinterHandlerTest, GetPrinters) {
bool is_done = false;
extension_printer_handler_->StartGetPrinters(
- base::Bind(&RecordPrinterList, &call_count, &printers),
- base::Bind(&RecordPrintersDone, &is_done));
+ base::BindRepeating(&RecordPrinterList, &call_count, &printers),
+ base::BindOnce(&RecordPrintersDone, &is_done));
EXPECT_FALSE(printers.get());
FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
@@ -566,8 +566,8 @@ TEST_F(ExtensionPrinterHandlerTest, GetPrinters_Reset) {
bool is_done = false;
extension_printer_handler_->StartGetPrinters(
- base::Bind(&RecordPrinterList, &call_count, &printers),
- base::Bind(&RecordPrintersDone, &is_done));
+ base::BindRepeating(&RecordPrinterList, &call_count, &printers),
+ base::BindOnce(&RecordPrintersDone, &is_done));
EXPECT_FALSE(printers.get());
FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
@@ -608,8 +608,8 @@ TEST_F(ExtensionPrinterHandlerTest, GetUsbPrinters) {
std::unique_ptr<base::ListValue> printers;
bool is_done = false;
extension_printer_handler_->StartGetPrinters(
- base::Bind(&RecordPrinterList, &call_count, &printers),
- base::Bind(&RecordPrintersDone, &is_done));
+ base::BindRepeating(&RecordPrinterList, &call_count, &printers),
+ base::BindOnce(&RecordPrintersDone, &is_done));
base::RunLoop().RunUntilIdle();
@@ -656,7 +656,7 @@ TEST_F(ExtensionPrinterHandlerTest, GetCapability) {
std::unique_ptr<base::DictionaryValue> capability;
extension_printer_handler_->StartGetCapability(
- kPrinterId, base::Bind(&RecordCapability, &call_count, &capability));
+ kPrinterId, base::BindOnce(&RecordCapability, &call_count, &capability));
EXPECT_EQ(0u, call_count);
@@ -683,7 +683,7 @@ TEST_F(ExtensionPrinterHandlerTest, GetCapability_Reset) {
std::unique_ptr<base::DictionaryValue> capability;
extension_printer_handler_->StartGetCapability(
- kPrinterId, base::Bind(&RecordCapability, &call_count, &capability));
+ kPrinterId, base::BindOnce(&RecordCapability, &call_count, &capability));
EXPECT_EQ(0u, call_count);
@@ -715,7 +715,7 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pdf) {
extension_printer_handler_->StartPrint(
title, *base::JSONReader::Read(kPdfSettings), print_data,
- base::Bind(&RecordPrintResult, &call_count, &success, &status));
+ base::BindOnce(&RecordPrintResult, &call_count, &success, &status));
EXPECT_EQ(0u, call_count);
FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
@@ -751,7 +751,7 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pdf_Reset) {
extension_printer_handler_->StartPrint(
title, *base::JSONReader::Read(kPdfSettings), print_data,
- base::Bind(&RecordPrintResult, &call_count, &success, &status));
+ base::BindOnce(&RecordPrintResult, &call_count, &success, &status));
EXPECT_EQ(0u, call_count);
FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
@@ -776,7 +776,7 @@ TEST_F(ExtensionPrinterHandlerTest, Print_All) {
extension_printer_handler_->StartPrint(
title, *base::JSONReader::Read(kAllTypesSettings), print_data,
- base::Bind(&RecordPrintResult, &call_count, &success, &status));
+ base::BindOnce(&RecordPrintResult, &call_count, &success, &status));
EXPECT_EQ(0u, call_count);
@@ -813,7 +813,7 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pwg) {
extension_printer_handler_->StartPrint(
title, *base::JSONReader::Read(kSimpleRasterSettings), print_data,
- base::Bind(&RecordPrintResult, &call_count, &success, &status));
+ base::BindOnce(&RecordPrintResult, &call_count, &success, &status));
EXPECT_EQ(0u, call_count);
@@ -866,7 +866,7 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_NonDefaultSettings) {
extension_printer_handler_->StartPrint(
title, *base::JSONReader::Read(kDuplexSettings), print_data,
- base::Bind(&RecordPrintResult, &call_count, &success, &status));
+ base::BindOnce(&RecordPrintResult, &call_count, &success, &status));
EXPECT_EQ(0u, call_count);
@@ -919,7 +919,7 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_Reset) {
extension_printer_handler_->StartPrint(
title, *base::JSONReader::Read(kSimpleRasterSettings), print_data,
- base::Bind(&RecordPrintResult, &call_count, &success, &status));
+ base::BindOnce(&RecordPrintResult, &call_count, &success, &status));
EXPECT_EQ(0u, call_count);
@@ -947,7 +947,7 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_InvalidTicket) {
extension_printer_handler_->StartPrint(
title, *base::JSONReader::Read(kInvalidSettings), print_data,
- base::Bind(&RecordPrintResult, &call_count, &success, &status));
+ base::BindOnce(&RecordPrintResult, &call_count, &success, &status));
EXPECT_EQ(1u, call_count);
@@ -968,7 +968,7 @@ TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_FailedConversion) {
extension_printer_handler_->StartPrint(
title, *base::JSONReader::Read(kSimpleRasterSettings), print_data,
- base::Bind(&RecordPrintResult, &call_count, &success, &status));
+ base::BindOnce(&RecordPrintResult, &call_count, &success, &status));
EXPECT_EQ(1u, call_count);
@@ -987,7 +987,8 @@ TEST_F(ExtensionPrinterHandlerTest, GrantUsbPrinterAccess) {
std::string printer_id = base::StringPrintf(
"provisional-usb:fake extension id:%s", device->guid.c_str());
extension_printer_handler_->StartGrantPrinterAccess(
- printer_id, base::Bind(&RecordPrinterInfo, &call_count, &printer_info));
+ printer_id,
+ base::BindOnce(&RecordPrinterInfo, &call_count, &printer_info));
EXPECT_FALSE(printer_info.get());
FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
@@ -1019,7 +1020,7 @@ TEST_F(ExtensionPrinterHandlerTest, GrantUsbPrinterAccess_Reset) {
extension_printer_handler_->StartGrantPrinterAccess(
base::StringPrintf("provisional-usb:fake extension id:%s",
device->guid.c_str()),
- base::Bind(&RecordPrinterInfo, &call_count, &printer_info));
+ base::BindOnce(&RecordPrinterInfo, &call_count, &printer_info));
EXPECT_FALSE(printer_info.get());
FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
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 65229b67491..9534da45d8d 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
@@ -152,7 +152,7 @@ void LocalPrinterHandlerChromeos::GetDefaultPrinter(DefaultPrinterCallback cb) {
}
void LocalPrinterHandlerChromeos::StartGetPrinters(
- const AddedPrintersCallback& added_printers_callback,
+ AddedPrintersCallback added_printers_callback,
GetPrintersDoneCallback done_callback) {
// SyncedPrintersManager is not thread safe and must be called from the UI
// thread.
@@ -172,7 +172,7 @@ void LocalPrinterHandlerChromeos::StartGetPrinters(
AddPrintersToList(printers_manager_->GetPrinters(PrinterClass::kAutomatic),
&printer_list);
- ConvertPrinterListForCallback(added_printers_callback,
+ ConvertPrinterListForCallback(std::move(added_printers_callback),
std::move(done_callback), printer_list);
}
@@ -288,7 +288,6 @@ void LocalPrinterHandlerChromeos::StartPrint(
settings.SetKey(
kSettingUsername,
base::Value(username.empty() ? kUsernamePlaceholder : username));
- settings.SetKey(kSettingJobTitle, base::Value(job_title));
settings.SetKey(kSettingSendUserInfo, base::Value(true));
}
StartLocalPrint(std::move(settings), std::move(print_data),
diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h
index 5a124f88f92..7136f4e03a9 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.h
@@ -42,7 +42,7 @@ class LocalPrinterHandlerChromeos : public PrinterHandler {
// PrinterHandler implementation
void Reset() override;
void GetDefaultPrinter(DefaultPrinterCallback cb) override;
- void StartGetPrinters(const AddedPrintersCallback& added_printers_callback,
+ void StartGetPrinters(AddedPrintersCallback added_printers_callback,
GetPrintersDoneCallback done_callback) override;
void StartGetCapability(const std::string& printer_name,
GetCapabilityCallback cb) override;
diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc
index 03bd08a9b71..0074a2f8b68 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc
@@ -112,14 +112,14 @@ void LocalPrinterHandlerDefault::GetDefaultPrinter(DefaultPrinterCallback cb) {
}
void LocalPrinterHandlerDefault::StartGetPrinters(
- const AddedPrintersCallback& callback,
+ AddedPrintersCallback callback,
GetPrintersDoneCallback done_callback) {
VLOG(1) << "Enumerate printers start";
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
base::PostTaskAndReplyWithResult(
task_runner_.get(), FROM_HERE, base::BindOnce(&EnumeratePrintersAsync),
- base::BindOnce(&ConvertPrinterListForCallback, callback,
+ base::BindOnce(&ConvertPrinterListForCallback, std::move(callback),
std::move(done_callback)));
}
diff --git a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.h b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.h
index 25659249abb..1f6d48aae7c 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.h
@@ -34,7 +34,7 @@ class LocalPrinterHandlerDefault : public PrinterHandler {
// PrinterHandler implementation.
void Reset() override;
void GetDefaultPrinter(DefaultPrinterCallback cb) override;
- void StartGetPrinters(const AddedPrintersCallback& added_printers_callback,
+ void StartGetPrinters(AddedPrintersCallback added_printers_callback,
GetPrintersDoneCallback done_callback) override;
void StartGetCapability(const std::string& destination_id,
GetCapabilityCallback callback) override;
diff --git a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc
index e0d6a903433..6147b07f6da 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.cc
@@ -97,7 +97,7 @@ base::Value GetPdfCapabilities(const std::string& locale) {
Media default_media("", "", default_media_size.width(),
default_media_size.height());
if (!default_media.MatchBySize() ||
- !base::ContainsValue(kPdfMedia, default_media.type)) {
+ !base::Contains(kPdfMedia, default_media.type)) {
default_media =
Media(locale == "en-US" ? MediaType::NA_LETTER : MediaType::ISO_A4);
}
@@ -115,13 +115,13 @@ base::Value GetPdfCapabilities(const std::string& locale) {
// Callback that stores a PDF file on disk.
void PrintToPdfCallback(scoped_refptr<base::RefCountedMemory> data,
const base::FilePath& path,
- const base::Closure& pdf_file_saved_closure) {
+ base::OnceClosure pdf_file_saved_closure) {
base::File file(path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
file.WriteAtCurrentPos(reinterpret_cast<const char*>(data->front()),
base::checked_cast<int>(data->size()));
if (!pdf_file_saved_closure.is_null())
- pdf_file_saved_closure.Run();
+ std::move(pdf_file_saved_closure).Run();
}
base::FilePath SelectSaveDirectory(const base::FilePath& path,
@@ -140,8 +140,7 @@ PdfPrinterHandler::PdfPrinterHandler(Profile* profile,
StickySettings* sticky_settings)
: preview_web_contents_(preview_web_contents),
profile_(profile),
- sticky_settings_(sticky_settings),
- weak_ptr_factory_(this) {}
+ sticky_settings_(sticky_settings) {}
PdfPrinterHandler::~PdfPrinterHandler() {
if (select_file_dialog_.get())
@@ -153,7 +152,7 @@ void PdfPrinterHandler::Reset() {
}
void PdfPrinterHandler::StartGetPrinters(
- const AddedPrintersCallback& added_printers_callback,
+ AddedPrintersCallback added_printers_callback,
GetPrintersDoneCallback done_callback) {
NOTREACHED();
}
@@ -226,8 +225,8 @@ void PdfPrinterHandler::FileSelectionCanceled(void* params) {
}
void PdfPrinterHandler::SetPdfSavedClosureForTesting(
- const base::Closure& closure) {
- pdf_file_saved_closure_ = closure;
+ base::OnceClosure closure) {
+ pdf_file_saved_closure_ = std::move(closure);
}
// static
@@ -315,9 +314,9 @@ void PdfPrinterHandler::SelectFile(const base::FilePath& default_filename,
if (!prompt_user) {
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
- base::Bind(&base::GetUniquePath, path.Append(default_filename)),
- base::Bind(&PdfPrinterHandler::OnGotUniqueFileName,
- weak_ptr_factory_.GetWeakPtr()));
+ base::BindOnce(&base::GetUniquePath, path.Append(default_filename)),
+ base::BindOnce(&PdfPrinterHandler::OnGotUniqueFileName,
+ weak_ptr_factory_.GetWeakPtr()));
return;
}
@@ -342,7 +341,7 @@ void PdfPrinterHandler::PostPrintToPdfTask() {
base::PostTaskWithTraits(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
base::BindOnce(&PrintToPdfCallback, print_data_, print_to_pdf_path_,
- pdf_file_saved_closure_));
+ std::move(pdf_file_saved_closure_)));
print_to_pdf_path_.clear();
std::move(print_callback_).Run(base::Value());
}
diff --git a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h
index eae9098f213..06f5799efbb 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/pdf_printer_handler.h
@@ -44,7 +44,7 @@ class PdfPrinterHandler : public PrinterHandler,
// PrinterHandler implementation
void Reset() override;
// Required by PrinterHandler implementation but should never be called.
- void StartGetPrinters(const AddedPrintersCallback& added_printers_callback,
+ void StartGetPrinters(AddedPrintersCallback added_printers_callback,
GetPrintersDoneCallback done_callback) override;
void StartGetCapability(const std::string& destination_id,
GetCapabilityCallback callback) override;
@@ -60,7 +60,7 @@ class PdfPrinterHandler : public PrinterHandler,
void FileSelectionCanceled(void* params) override;
// Sets |pdf_file_saved_closure_| to |closure|.
- void SetPdfSavedClosureForTesting(const base::Closure& closure);
+ void SetPdfSavedClosureForTesting(base::OnceClosure closure);
// Exposed for testing.
static base::FilePath GetFileNameForPrintJobTitle(
@@ -99,7 +99,7 @@ class PdfPrinterHandler : public PrinterHandler,
// Notifies tests that want to know if the PDF has been saved. This doesn't
// notify the test if it was a successful save, only that it was attempted.
- base::Closure pdf_file_saved_closure_;
+ base::OnceClosure pdf_file_saved_closure_;
// The data to print
scoped_refptr<base::RefCountedMemory> print_data_;
@@ -107,7 +107,7 @@ class PdfPrinterHandler : public PrinterHandler,
// The callback to call when complete.
PrintCallback print_callback_;
- base::WeakPtrFactory<PdfPrinterHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<PdfPrinterHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(PdfPrinterHandler);
};
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 a1ff2e4d1da..e3d7c5f14cd 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
@@ -62,20 +62,20 @@
#include "components/printing/browser/printer_capabilities.h"
#include "components/printing/common/cloud_print_cdd_conversion.h"
#include "components/printing/common/print_messages.h"
-#include "components/signin/core/browser/account_consistency_method.h"
+#include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h"
+#include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h"
#include "components/url_formatter/url_formatter.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
-#include "google_apis/gaia/oauth2_token_service.h"
+#include "google_apis/gaia/gaia_auth_util.h"
#include "net/base/url_util.h"
#include "printing/backend/print_backend.h"
#include "printing/backend/print_backend_consts.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_settings.h"
-#include "services/identity/public/cpp/primary_account_access_token_fetcher.h"
#include "third_party/icu/source/i18n/unicode/ulocdata.h"
#if defined(OS_CHROMEOS)
@@ -144,6 +144,7 @@ enum PrintSettingsBuckets {
FIT_TO_PAGE,
DEFAULT_DPI,
NON_DEFAULT_DPI,
+ PIN,
PRINT_SETTINGS_BUCKET_BOUNDARY
};
@@ -184,44 +185,6 @@ void ReportPrintDocumentTypeAndSizeHistograms(PrintDocumentTypeBuckets doctype,
}
}
-bool ReportPageCountHistogram(UserActionBuckets user_action, int page_count) {
- switch (user_action) {
- case PRINT_TO_PRINTER:
- UMA_HISTOGRAM_COUNTS_1M("PrintPreview.PageCount.PrintToPrinter",
- page_count);
- return true;
- case PRINT_TO_PDF:
- UMA_HISTOGRAM_COUNTS_1M("PrintPreview.PageCount.PrintToPDF", page_count);
- return true;
- case FALLBACK_TO_ADVANCED_SETTINGS_DIALOG:
- UMA_HISTOGRAM_COUNTS_1M("PrintPreview.PageCount.SystemDialog",
- page_count);
- return true;
- case PRINT_WITH_CLOUD_PRINT:
- UMA_HISTOGRAM_COUNTS_1M("PrintPreview.PageCount.PrintToCloudPrint",
- page_count);
- return true;
- case PRINT_WITH_PRIVET:
- UMA_HISTOGRAM_COUNTS_1M("PrintPreview.PageCount.PrintWithPrivet",
- page_count);
- return true;
- case PRINT_WITH_EXTENSION:
- UMA_HISTOGRAM_COUNTS_1M("PrintPreview.PageCount.PrintWithExtension",
- page_count);
- return true;
- case OPEN_IN_MAC_PREVIEW:
- UMA_HISTOGRAM_COUNTS_1M("PrintPreview.PageCount.OpenInMacPreview",
- page_count);
- return true;
- case PRINT_TO_GOOGLE_DRIVE:
- UMA_HISTOGRAM_COUNTS_1M("PrintPreview.PageCount.PrintToGoogleDrive",
- page_count);
- return true;
- default:
- return false;
- }
-}
-
PrinterType GetPrinterTypeForUserAction(UserActionBuckets user_action) {
switch (user_action) {
case PRINT_WITH_PRIVET:
@@ -256,6 +219,8 @@ const char kIsInKioskAutoPrintMode[] = "isInKioskAutoPrintMode";
// Dictionary field to indicate whether Chrome is running in forced app (app
// kiosk) mode. It's not the same as desktop Chrome kiosk (the one above).
const char kIsInAppKioskMode[] = "isInAppKioskMode";
+// Name of a dictionary field holding the UI locale.
+const char kUiLocale[] = "uiLocale";
// Name of a dictionary field holding the thousands delimeter according to the
// locale.
const char kThousandsDelimeter[] = "thousandsDelimeter";
@@ -401,6 +366,11 @@ void ReportPrintSettingsStats(const base::Value& print_settings,
: NON_DEFAULT_DPI);
}
}
+
+#if defined(OS_CHROMEOS)
+ if (print_settings.FindStringKey(kSettingPinValue))
+ ReportPrintSettingHistogram(PIN);
+#endif // defined(OS_CHROMEOS)
}
UserActionBuckets DetermineUserAction(const base::Value& settings) {
@@ -436,9 +406,9 @@ StickySettings* GetStickySettings() {
#if defined(OS_CHROMEOS)
class PrintPreviewHandler::AccessTokenService
- : public OAuth2TokenService::Consumer {
+ : public OAuth2AccessTokenManager::Consumer {
public:
- AccessTokenService() : OAuth2TokenService::Consumer("print_preview") {}
+ AccessTokenService() : OAuth2AccessTokenManager::Consumer("print_preview") {}
void RequestToken(base::OnceCallback<void(const std::string&)> callback) {
// There can only be one pending request at a time. See
@@ -450,30 +420,31 @@ class PrintPreviewHandler::AccessTokenService
chromeos::DeviceOAuth2TokenServiceFactory::Get();
std::string account_id = token_service->GetRobotAccountId();
- device_request_ = token_service->StartRequest(account_id, scopes, this);
+ device_request_ =
+ token_service->StartAccessTokenRequest(account_id, scopes, this);
device_request_callback_ = std::move(callback);
}
void OnGetTokenSuccess(
- const OAuth2TokenService::Request* request,
+ const OAuth2AccessTokenManager::Request* request,
const OAuth2AccessTokenConsumer::TokenResponse& token_response) override {
OnServiceResponse(request, token_response.access_token);
}
- void OnGetTokenFailure(const OAuth2TokenService::Request* request,
+ void OnGetTokenFailure(const OAuth2AccessTokenManager::Request* request,
const GoogleServiceAuthError& error) override {
OnServiceResponse(request, std::string());
}
private:
- void OnServiceResponse(const OAuth2TokenService::Request* request,
+ void OnServiceResponse(const OAuth2AccessTokenManager::Request* request,
const std::string& access_token) {
DCHECK_EQ(request, device_request_.get());
std::move(device_request_callback_).Run(access_token);
device_request_.reset();
}
- std::unique_ptr<OAuth2TokenService::Request> device_request_;
+ std::unique_ptr<OAuth2AccessTokenManager::Request> device_request_;
base::OnceCallback<void(const std::string&)> device_request_callback_;
DISALLOW_COPY_AND_ASSIGN(AccessTokenService);
@@ -485,8 +456,7 @@ PrintPreviewHandler::PrintPreviewHandler()
manage_printers_dialog_request_count_(0),
reported_failed_preview_(false),
has_logged_printers_count_(false),
- identity_manager_(nullptr),
- weak_factory_(this) {
+ identity_manager_(nullptr) {
ReportUserActionHistogram(PREVIEW_STARTED);
}
@@ -600,7 +570,7 @@ bool PrintPreviewHandler::ShouldReceiveRendererMessage(int request_id) {
return false;
}
- if (!base::ContainsKey(preview_callbacks_, request_id)) {
+ if (!base::Contains(preview_callbacks_, request_id)) {
BadMessageReceived();
return false;
}
@@ -642,10 +612,10 @@ void PrintPreviewHandler::HandleGetPrinters(const base::ListValue* args) {
// starts.
handler->Reset();
handler->StartGetPrinters(
- base::Bind(&PrintPreviewHandler::OnAddedPrinters,
- weak_factory_.GetWeakPtr(), printer_type),
- base::Bind(&PrintPreviewHandler::OnGetPrintersDone,
- weak_factory_.GetWeakPtr(), callback_id));
+ base::BindRepeating(&PrintPreviewHandler::OnAddedPrinters,
+ weak_factory_.GetWeakPtr(), printer_type),
+ base::BindOnce(&PrintPreviewHandler::OnGetPrintersDone,
+ weak_factory_.GetWeakPtr(), callback_id));
}
void PrintPreviewHandler::HandleGrantExtensionPrinterAccess(
@@ -659,8 +629,8 @@ void PrintPreviewHandler::HandleGrantExtensionPrinterAccess(
GetPrinterHandler(PrinterType::kExtensionPrinter)
->StartGrantPrinterAccess(
printer_id,
- base::Bind(&PrintPreviewHandler::OnGotExtensionPrinterInfo,
- weak_factory_.GetWeakPtr(), callback_id));
+ base::BindOnce(&PrintPreviewHandler::OnGotExtensionPrinterInfo,
+ weak_factory_.GetWeakPtr(), callback_id));
}
void PrintPreviewHandler::HandleGetPrinterCapabilities(
@@ -703,7 +673,7 @@ void PrintPreviewHandler::HandleGetPreview(const base::ListValue* args) {
int request_id = settings.FindIntKey(kPreviewRequestID).value();
CHECK_GT(request_id, -1);
- CHECK(!base::ContainsKey(preview_callbacks_, request_id));
+ CHECK(!base::Contains(preview_callbacks_, request_id));
preview_callbacks_[request_id] = callback_id;
print_preview_ui()->OnPrintPreviewRequest(request_id);
// Add an additional key in order to identify |print_preview_ui| later on
@@ -800,10 +770,6 @@ void PrintPreviewHandler::HandlePrint(const base::ListValue* args) {
ReportPrintDocumentTypeAndSizeHistograms(doc_type, average_page_size_in_kb);
}
ReportUserActionHistogram(user_action);
- if (!ReportPageCountHistogram(user_action, page_count)) {
- NOTREACHED();
- return;
- }
if (user_action == PRINT_WITH_CLOUD_PRINT ||
user_action == PRINT_TO_GOOGLE_DRIVE) {
@@ -927,18 +893,16 @@ void PrintPreviewHandler::HandleClosePreviewDialog(
#if defined(OS_CHROMEOS)
void PrintPreviewHandler::HandleOpenPrinterSettings(
const base::ListValue* args) {
- auto* const settings_manager = chrome::SettingsWindowManager::GetInstance();
- settings_manager->ShowChromePageForProfile(
- Profile::FromWebUI(web_ui()),
- chrome::GetSettingsUrl(chrome::kPrintingSettingsSubPage));
+ chrome::SettingsWindowManager::GetInstance()->ShowOSSettings(
+ Profile::FromWebUI(web_ui()), chrome::kPrintingSettingsSubPage);
}
#endif
-void PrintPreviewHandler::GetNumberFormatAndMeasurementSystem(
- base::Value* settings) {
+void PrintPreviewHandler::GetLocaleInformation(base::Value* settings) {
// Getting the measurement system based on the locale.
UErrorCode errorCode = U_ZERO_ERROR;
const char* locale = g_browser_process->GetApplicationLocale().c_str();
+ settings->SetStringKey(kUiLocale, std::string(locale));
UMeasurementSystem system = ulocdata_getMeasurementSystem(locale, &errorCode);
// On error, assume the units are SI.
// Since the only measurement units print preview's WebUI cares about are
@@ -963,8 +927,9 @@ void PrintPreviewHandler::HandleGetInitialSettings(
AllowJavascript();
GetPrinterHandler(PrinterType::kLocalPrinter)
- ->GetDefaultPrinter(base::Bind(&PrintPreviewHandler::SendInitialSettings,
- weak_factory_.GetWeakPtr(), callback_id));
+ ->GetDefaultPrinter(
+ base::BindOnce(&PrintPreviewHandler::SendInitialSettings,
+ weak_factory_.GetWeakPtr(), callback_id));
}
void PrintPreviewHandler::GetUserAccountList(base::Value* settings) {
@@ -1033,7 +998,7 @@ void PrintPreviewHandler::SendInitialSettings(
initial_settings.SetStringKey(kDefaultDestinationSelectionRules, rules_str);
}
- GetNumberFormatAndMeasurementSystem(&initial_settings);
+ GetLocaleInformation(&initial_settings);
if (IsCloudPrintEnabled()) {
GetUserAccountList(&initial_settings);
}
@@ -1124,7 +1089,7 @@ WebContents* PrintPreviewHandler::GetInitiator() const {
}
void PrintPreviewHandler::OnAccountsInCookieUpdated(
- const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
+ const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
const GoogleServiceAuthError& error) {
base::Value account_list(base::Value::Type::LIST);
const std::vector<gaia::ListedAccount>& accounts =
@@ -1208,7 +1173,7 @@ void PrintPreviewHandler::SendPagePreviewReady(int page_index,
// gets called, the print preview may have failed. Since the failure message
// may have arrived first, check for this case and bail out instead of
// thinking this may be a bad IPC message.
- if (base::ContainsKey(preview_failures_, preview_request_id))
+ if (base::Contains(preview_failures_, preview_request_id))
return;
if (!ShouldReceiveRendererMessage(preview_request_id))
@@ -1386,8 +1351,8 @@ void PrintPreviewHandler::FileSelectedForTesting(const base::FilePath& path,
}
void PrintPreviewHandler::SetPdfSavedClosureForTesting(
- const base::Closure& closure) {
- GetPdfPrinterHandler()->SetPdfSavedClosureForTesting(closure);
+ base::OnceClosure closure) {
+ GetPdfPrinterHandler()->SetPdfSavedClosureForTesting(std::move(closure));
}
void PrintPreviewHandler::SendEnableManipulateSettingsForTest() {
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 1b34ac7694f..305ba9357f5 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
@@ -17,10 +17,11 @@
#include "base/memory/weak_ptr.h"
#include "base/timer/timer.h"
#include "chrome/common/buildflags.h"
+#include "components/prefs/pref_service.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "printing/backend/print_backend.h"
#include "printing/buildflags/buildflags.h"
-#include "services/identity/public/cpp/identity_manager.h"
namespace base {
class DictionaryValue;
@@ -49,7 +50,7 @@ enum PrinterType {
// The handler for Javascript messages related to the print preview dialog.
class PrintPreviewHandler : public content::WebUIMessageHandler,
- public identity::IdentityManager::Observer {
+ public signin::IdentityManager::Observer {
public:
PrintPreviewHandler();
~PrintPreviewHandler() override;
@@ -61,7 +62,7 @@ class PrintPreviewHandler : public content::WebUIMessageHandler,
// IdentityManager::Observer implementation.
void OnAccountsInCookieUpdated(
- const identity::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
+ const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
const GoogleServiceAuthError& error) override;
// Called when print preview failed. |request_id| identifies the request that
@@ -113,7 +114,7 @@ class PrintPreviewHandler : public content::WebUIMessageHandler,
void* params);
// Sets |pdf_file_saved_closure_| to |closure|.
- void SetPdfSavedClosureForTesting(const base::Closure& closure);
+ void SetPdfSavedClosureForTesting(base::OnceClosure closure);
// Fires the 'enable-manipulate-settings-for-test' WebUI event.
void SendEnableManipulateSettingsForTest();
@@ -278,7 +279,7 @@ class PrintPreviewHandler : public content::WebUIMessageHandler,
void ClearInitiatorDetails();
// Populates |settings| according to the current locale.
- void GetNumberFormatAndMeasurementSystem(base::Value* settings);
+ void GetLocaleInformation(base::Value* settings);
// Populates |settings| with the list of logged in accounts.
void GetUserAccountList(base::Value* settings);
@@ -336,7 +337,7 @@ class PrintPreviewHandler : public content::WebUIMessageHandler,
// Pointer to the identity manager service so that print preview can listen
// for GAIA cookie changes.
- identity::IdentityManager* identity_manager_;
+ signin::IdentityManager* identity_manager_;
// Handles requests for cloud printers. Created lazily by calling
// GetPrinterHandler().
@@ -364,7 +365,7 @@ class PrintPreviewHandler : public content::WebUIMessageHandler,
// Set of preview request ids for failed previews.
std::set<int> preview_failures_;
- base::WeakPtrFactory<PrintPreviewHandler> weak_factory_;
+ base::WeakPtrFactory<PrintPreviewHandler> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(PrintPreviewHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc
index 64af66f7500..004dec28a15 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_handler_unittest.cc
@@ -128,7 +128,7 @@ class TestPrinterHandler : public PrinterHandler {
std::move(cb).Run(default_printer_);
}
- void StartGetPrinters(const AddedPrintersCallback& added_printers_callback,
+ void StartGetPrinters(AddedPrintersCallback added_printers_callback,
GetPrintersDoneCallback done_callback) override {
if (!printers_.empty())
added_printers_callback.Run(printers_);
@@ -340,6 +340,10 @@ class PrintPreviewHandlerTest : public testing::Test {
ASSERT_TRUE(settings->FindKeyOfType("isInAppKioskMode",
base::Value::Type::BOOLEAN));
+ const base::Value* locale =
+ settings->FindKeyOfType("uiLocale", base::Value::Type::STRING);
+ ASSERT_TRUE(locale);
+ EXPECT_EQ("en", locale->GetString());
const base::Value* thousands_delimeter = settings->FindKeyOfType(
"thousandsDelimeter", base::Value::Type::STRING);
ASSERT_TRUE(thousands_delimeter);
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 f90198efcf2..2dfc91469b8 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
@@ -30,7 +30,6 @@
#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/dark_mode_handler.h"
#include "chrome/browser/ui/webui/localized_string.h"
#include "chrome/browser/ui/webui/metrics_handler.h"
#include "chrome/browser/ui/webui/print_preview/print_preview_handler.h"
@@ -293,9 +292,6 @@ void AddPrintPreviewStrings(content::WebUIDataSource* source) {
AddLocalizedStringsBulk(source, kLocalizedStrings,
base::size(kLocalizedStrings));
- source->AddString(
- "settingsPrintingPage",
- chrome::GetSettingsUrl(chrome::kPrintingSettingsSubPage).spec());
source->AddString("gcpCertificateErrorLearnMoreURL",
chrome::kCloudPrintCertificateErrorLearnMoreURL);
@@ -479,9 +475,7 @@ PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui)
handler_(CreatePrintPreviewHandlers(web_ui)) {
// Set up the chrome://print/ data source.
Profile* profile = Profile::FromWebUI(web_ui);
- content::WebUIDataSource* source = CreatePrintPreviewUISource(profile);
- DarkModeHandler::Initialize(web_ui, source);
- content::WebUIDataSource::Add(profile, source);
+ content::WebUIDataSource::Add(profile, CreatePrintPreviewUISource(profile));
// Set up the chrome://theme/ source.
content::URLDataSource::Add(profile, std::make_unique<ThemeSource>(profile));
@@ -788,9 +782,8 @@ void PrintPreviewUI::SetSelectedFileForTesting(const base::FilePath& path) {
handler_->FileSelectedForTesting(path, 0, nullptr);
}
-void PrintPreviewUI::SetPdfSavedClosureForTesting(
- const base::Closure& closure) {
- handler_->SetPdfSavedClosureForTesting(closure);
+void PrintPreviewUI::SetPdfSavedClosureForTesting(base::OnceClosure closure) {
+ handler_->SetPdfSavedClosureForTesting(std::move(closure));
}
void PrintPreviewUI::SendEnableManipulateSettingsForTest() {
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 2958b36ecef..2aca55e7bc1 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
@@ -202,7 +202,7 @@ class PrintPreviewUI : public ConstrainedWebDialogUI {
void SetSelectedFileForTesting(const base::FilePath& path);
// Passes |closure| to PrintPreviewHandler::SetPdfSavedClosureForTesting().
- void SetPdfSavedClosureForTesting(const base::Closure& closure);
+ void SetPdfSavedClosureForTesting(base::OnceClosure closure);
// Tell the handler to send the enable-manipulate-settings-for-test WebUI
// event.
diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.cc b/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.cc
index b5bbf3818cf..e9d21dc1c15 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.cc
@@ -58,7 +58,7 @@ void PrintersToValues(const PrinterList& printer_list,
printer_info->SetBoolean(
kCUPSEnterprisePrinter,
- base::ContainsKey(printer.options, kCUPSEnterprisePrinter) &&
+ base::Contains(printer.options, kCUPSEnterprisePrinter) &&
printer.options.at(kCUPSEnterprisePrinter) == kValueTrue);
printer_info->Set(kSettingPrinterOptions, std::move(options));
@@ -165,7 +165,7 @@ base::Value ValidateCddForPrintPreview(base::Value cdd) {
}
void ConvertPrinterListForCallback(
- const PrinterHandler::AddedPrintersCallback& callback,
+ PrinterHandler::AddedPrintersCallback callback,
PrinterHandler::GetPrintersDoneCallback done_callback,
const PrinterList& printer_list) {
base::ListValue printers;
diff --git a/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.h b/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.h
index b7c00de671e..d678ae7f3c6 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/print_preview_utils.h
@@ -30,7 +30,7 @@ extern const char kVendorCapabilityKey[];
// Converts |printer_list| to a base::ListValue form, runs |callback| with the
// converted list as the argument if it is not empty, and runs |done_callback|.
void ConvertPrinterListForCallback(
- const PrinterHandler::AddedPrintersCallback& callback,
+ PrinterHandler::AddedPrintersCallback callback,
PrinterHandler::GetPrintersDoneCallback done_callback,
const PrinterList& printer_list);
diff --git a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h
index 4d6a47646b7..2ccef52c2b4 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/printer_handler.h
@@ -88,9 +88,8 @@ class PrinterHandler {
// are found. May be called multiple times, or never if there are no printers
// to add.
// |done_callback| must be called exactly once when the search is complete.
- virtual void StartGetPrinters(
- const AddedPrintersCallback& added_printers_callback,
- GetPrintersDoneCallback done_callback) = 0;
+ virtual void StartGetPrinters(AddedPrintersCallback added_printers_callback,
+ GetPrintersDoneCallback done_callback) = 0;
// Starts getting printing capability of the printer with the provided
// destination ID.
diff --git a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc
index 0d695cfac47..88a2448b5b4 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.cc
@@ -20,7 +20,7 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/ui/webui/print_preview/print_preview_utils.h"
-#include "services/identity/public/cpp/identity_manager.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "ui/gfx/geometry/size.h"
@@ -42,7 +42,7 @@ void FillPrinterDescription(const std::string& name,
} // namespace
PrivetPrinterHandler::PrivetPrinterHandler(Profile* profile)
- : profile_(profile), weak_ptr_factory_(this) {}
+ : profile_(profile) {}
PrivetPrinterHandler::~PrivetPrinterHandler() {}
@@ -54,7 +54,7 @@ void PrivetPrinterHandler::Reset() {
}
void PrivetPrinterHandler::StartGetPrinters(
- const AddedPrintersCallback& added_printers_callback,
+ AddedPrintersCallback added_printers_callback,
GetPrintersDoneCallback done_callback) {
using local_discovery::ServiceDiscoverySharedClient;
scoped_refptr<ServiceDiscoverySharedClient> service_discovery =
@@ -71,8 +71,8 @@ void PrivetPrinterHandler::StartGetCapability(const std::string& destination_id,
DCHECK(!capabilities_callback_);
capabilities_callback_ = std::move(callback);
CreateHTTP(destination_id,
- base::Bind(&PrivetPrinterHandler::CapabilitiesUpdateClient,
- weak_ptr_factory_.GetWeakPtr()));
+ base::BindOnce(&PrivetPrinterHandler::CapabilitiesUpdateClient,
+ weak_ptr_factory_.GetWeakPtr()));
}
void PrivetPrinterHandler::StartPrint(
@@ -132,8 +132,7 @@ void PrivetPrinterHandler::OnPrivetPrintingError(
}
void PrivetPrinterHandler::StartLister(
- const scoped_refptr<local_discovery::ServiceDiscoverySharedClient>&
- client) {
+ scoped_refptr<local_discovery::ServiceDiscoverySharedClient> client) {
DCHECK(!service_discovery_client_.get() ||
service_discovery_client_.get() == client.get());
service_discovery_client_ = client;
@@ -164,8 +163,8 @@ void PrivetPrinterHandler::CapabilitiesUpdateClient(
privet_capabilities_operation_ =
privet_http_client_->CreateCapabilitiesOperation(
- base::Bind(&PrivetPrinterHandler::OnGotCapabilities,
- weak_ptr_factory_.GetWeakPtr()));
+ base::BindOnce(&PrivetPrinterHandler::OnGotCapabilities,
+ weak_ptr_factory_.GetWeakPtr()));
privet_capabilities_operation_->Start();
}
@@ -250,7 +249,7 @@ void PrivetPrinterHandler::StartPrint(
privet_local_print_operation_->SetPageSize(page_size);
privet_local_print_operation_->SetData(print_data);
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfileIfExists(profile_);
if (identity_manager) {
privet_local_print_operation_->SetUsername(
diff --git a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h
index 5d0e7a541e6..37b9f3d10ce 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/privet_printer_handler.h
@@ -40,7 +40,7 @@ class PrivetPrinterHandler
// PrinterHandler implementation:
void Reset() override;
- void StartGetPrinters(const AddedPrintersCallback& added_printers_callback,
+ void StartGetPrinters(AddedPrintersCallback added_printers_callback,
GetPrintersDoneCallback done_callback) override;
void StartGetCapability(const std::string& destination_id,
GetCapabilityCallback calback) override;
@@ -66,8 +66,7 @@ class PrivetPrinterHandler
private:
void StartLister(
- const scoped_refptr<local_discovery::ServiceDiscoverySharedClient>&
- client);
+ scoped_refptr<local_discovery::ServiceDiscoverySharedClient> client);
void StopLister();
void CapabilitiesUpdateClient(
std::unique_ptr<cloud_print::PrivetHTTPClient> http_client);
@@ -107,7 +106,7 @@ class PrivetPrinterHandler
PrintCallback print_callback_;
GetCapabilityCallback capabilities_callback_;
- base::WeakPtrFactory<PrivetPrinterHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<PrivetPrinterHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(PrivetPrinterHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/profile_helper_browsertest.cc b/chromium/chrome/browser/ui/webui/profile_helper_browsertest.cc
index 935f0292d4e..5e9302e517b 100644
--- a/chromium/chrome/browser/ui/webui/profile_helper_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/profile_helper_browsertest.cc
@@ -6,7 +6,6 @@
#include "base/run_loop.h"
#include "base/scoped_observer.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
@@ -14,8 +13,8 @@
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/browser/ui/webui/profile_helper.h"
#include "chrome/test/base/in_process_browser_test.h"
+#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/browsing_data_remover.h"
-#include "content/public/browser/notification_service.h"
#include "content/public/test/browsing_data_remover_test_util.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/test_web_ui.h"
@@ -80,7 +79,7 @@ IN_PROC_BROWSER_TEST_F(ProfileHelperTest, OpenNewWindowForProfile) {
// Sanity checks.
EXPECT_EQ(1u, browser_list->size());
- EXPECT_TRUE(base::ContainsValue(*browser_list, original_browser));
+ EXPECT_TRUE(base::Contains(*browser_list, original_browser));
// Opening existing browser profile shouldn't open additional browser windows.
webui::OpenNewWindowForProfile(original_profile);
@@ -120,22 +119,16 @@ IN_PROC_BROWSER_TEST_F(ProfileHelperTest, DeleteSoleProfile) {
BrowserList* browser_list = BrowserList::GetInstance();
EXPECT_EQ(1u, browser_list->size());
- EXPECT_TRUE(base::ContainsValue(*browser_list, original_browser));
+ EXPECT_TRUE(base::Contains(*browser_list, original_browser));
EXPECT_EQ(1u, storage.GetNumberOfProfiles());
// Original browser will be closed, and browser with the new profile created.
- content::WindowedNotificationObserver open_observer(
- chrome::NOTIFICATION_BROWSER_OPENED,
- content::NotificationService::AllSources());
- content::WindowedNotificationObserver close_observer(
- chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(browser()));
webui::DeleteProfileAtPath(original_browser->profile()->GetPath(),
ProfileMetrics::DELETE_PROFILE_SETTINGS);
- open_observer.Wait();
- close_observer.Wait();
+ ui_test_utils::WaitForBrowserToClose(original_browser);
EXPECT_EQ(1u, browser_list->size());
- EXPECT_FALSE(base::ContainsValue(*browser_list, original_browser));
+ EXPECT_FALSE(base::Contains(*browser_list, original_browser));
EXPECT_EQ(1u, storage.GetNumberOfProfiles());
}
@@ -147,22 +140,16 @@ IN_PROC_BROWSER_TEST_F(ProfileHelperTest, DeleteActiveProfile) {
BrowserList* browser_list = BrowserList::GetInstance();
EXPECT_EQ(1u, browser_list->size());
- EXPECT_TRUE(base::ContainsValue(*browser_list, original_browser));
+ EXPECT_TRUE(base::Contains(*browser_list, original_browser));
EXPECT_EQ(1u, storage.GetNumberOfProfiles());
Profile* additional_profile = CreateProfile();
EXPECT_EQ(2u, storage.GetNumberOfProfiles());
// Original browser will be closed, and browser with the new profile created.
- content::WindowedNotificationObserver open_observer(
- chrome::NOTIFICATION_BROWSER_OPENED,
- content::NotificationService::AllSources());
- content::WindowedNotificationObserver close_observer(
- chrome::NOTIFICATION_BROWSER_CLOSED, content::Source<Browser>(browser()));
webui::DeleteProfileAtPath(original_browser->profile()->GetPath(),
ProfileMetrics::DELETE_PROFILE_SETTINGS);
- open_observer.Wait();
- close_observer.Wait();
+ ui_test_utils::WaitForBrowserToClose(original_browser);
EXPECT_EQ(1u, browser_list->size());
EXPECT_EQ(additional_profile, browser_list->get(0)->profile());
@@ -177,7 +164,7 @@ IN_PROC_BROWSER_TEST_F(ProfileHelperTest, DeleteInactiveProfile) {
BrowserList* browser_list = BrowserList::GetInstance();
EXPECT_EQ(1u, browser_list->size());
- EXPECT_TRUE(base::ContainsValue(*browser_list, original_browser));
+ EXPECT_TRUE(base::Contains(*browser_list, original_browser));
EXPECT_EQ(1u, storage.GetNumberOfProfiles());
Profile* additional_profile = CreateProfile();
@@ -191,6 +178,6 @@ IN_PROC_BROWSER_TEST_F(ProfileHelperTest, DeleteInactiveProfile) {
inhibitor.ContinueToCompletion();
EXPECT_EQ(1u, browser_list->size());
- EXPECT_TRUE(base::ContainsValue(*browser_list, original_browser));
+ EXPECT_TRUE(base::Contains(*browser_list, original_browser));
EXPECT_EQ(1u, storage.GetNumberOfProfiles());
}
diff --git a/chromium/chrome/browser/ui/webui/profile_info_watcher.cc b/chromium/chrome/browser/ui/webui/profile_info_watcher.cc
index a4f62d805c8..4767226339b 100644
--- a/chromium/chrome/browser/ui/webui/profile_info_watcher.cc
+++ b/chromium/chrome/browser/ui/webui/profile_info_watcher.cc
@@ -12,8 +12,8 @@
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/signin_pref_names.h"
-#include "services/identity/public/cpp/identity_manager.h"
+#include "components/signin/public/base/signin_pref_names.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
ProfileInfoWatcher::ProfileInfoWatcher(
Profile* profile, const base::Closure& callback)
@@ -50,7 +50,7 @@ std::string ProfileInfoWatcher::GetAuthenticatedUsername() const {
return username;
}
-identity::IdentityManager* ProfileInfoWatcher::GetIdentityManager() const {
+signin::IdentityManager* ProfileInfoWatcher::GetIdentityManager() const {
return IdentityManagerFactory::GetForProfile(profile_);
}
diff --git a/chromium/chrome/browser/ui/webui/profile_info_watcher.h b/chromium/chrome/browser/ui/webui/profile_info_watcher.h
index 98493150379..315c68281af 100644
--- a/chromium/chrome/browser/ui/webui/profile_info_watcher.h
+++ b/chromium/chrome/browser/ui/webui/profile_info_watcher.h
@@ -14,7 +14,7 @@
class Profile;
-namespace identity {
+namespace signin {
class IdentityManager;
}
@@ -33,7 +33,7 @@ class ProfileInfoWatcher : public ProfileAttributesStorage::Observer {
void OnProfileAuthInfoChanged(const base::FilePath& profile_path) override;
// Gets the IdentityManager for |profile_|.
- identity::IdentityManager* GetIdentityManager() const;
+ signin::IdentityManager* GetIdentityManager() const;
// Runs |callback_| when a profile changes. No-ops if |GetIdentityManager()|
// returns nullptr.
diff --git a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc
index 4e6b381086d..fd564930748 100644
--- a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc
+++ b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc
@@ -9,7 +9,6 @@
#include "base/bind.h"
#include "base/task/post_task.h"
-#include "base/trace_event/trace_event.h"
#include "chrome/browser/ui/webui/quota_internals/quota_internals_handler.h"
#include "chrome/browser/ui/webui/quota_internals/quota_internals_types.h"
#include "content/public/browser/browser_task_traits.h"
@@ -22,9 +21,7 @@ using content::BrowserThread;
namespace quota_internals {
QuotaInternalsProxy::QuotaInternalsProxy(QuotaInternalsHandler* handler)
- : handler_(handler),
- weak_factory_(this) {
-}
+ : handler_(handler) {}
void QuotaInternalsProxy::RequestInfo(
scoped_refptr<storage::QuotaManager> quota_manager) {
diff --git a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h
index f5c38a3a65a..0f562f5d428 100644
--- a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h
+++ b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h
@@ -82,7 +82,7 @@ class QuotaInternalsProxy
std::set<std::pair<std::string, blink::mojom::StorageType>> hosts_visited_,
hosts_pending_;
std::vector<PerHostStorageInfo> report_pending_;
- base::WeakPtrFactory<QuotaInternalsProxy> weak_factory_;
+ base::WeakPtrFactory<QuotaInternalsProxy> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(QuotaInternalsProxy);
};
diff --git a/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn b/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn
index 46529aa8ccb..bf4768bf16e 100644
--- a/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn
+++ b/chromium/chrome/browser/ui/webui/reset_password/BUILD.gn
@@ -8,4 +8,7 @@ mojom("mojo_bindings") {
sources = [
"reset_password.mojom",
]
+
+ # TODO(https://crbug.com/968369): Change to use new names.
+ use_old_js_lite_bindings_names = true
}
diff --git a/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc b/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc
index fc424d93b1a..739a6f401c3 100644
--- a/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc
+++ b/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.cc
@@ -10,6 +10,7 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
+#include "components/password_manager/core/browser/password_manager_metrics_util.h"
#include "components/safe_browsing/common/safe_browsing_prefs.h"
#include "components/safe_browsing/password_protection/password_protection_service.h"
#include "components/strings/grit/components_strings.h"
@@ -22,11 +23,6 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "ui/base/l10n/l10n_util.h"
-namespace safe_browsing {
-using PasswordReuseEvent =
- safe_browsing::LoginReputationClientRequest::PasswordReuseEvent;
-}
-
namespace {
constexpr char kStringTypeUMAName[] = "PasswordProtection.InterstitialString";
@@ -46,7 +42,7 @@ class ResetPasswordHandlerImpl : public mojom::ResetPasswordHandler {
public:
ResetPasswordHandlerImpl(
content::WebContents* web_contents,
- safe_browsing::ReusedPasswordType password_type,
+ PasswordType password_type,
mojo::InterfaceRequest<mojom::ResetPasswordHandler> request)
: web_contents_(web_contents),
password_type_(password_type),
@@ -71,28 +67,27 @@ class ResetPasswordHandlerImpl : public mojom::ResetPasswordHandler {
private:
content::WebContents* web_contents_;
- safe_browsing::ReusedPasswordType password_type_;
+ PasswordType password_type_;
mojo::Binding<mojom::ResetPasswordHandler> binding_;
DISALLOW_COPY_AND_ASSIGN(ResetPasswordHandlerImpl);
};
// Gets the reused password type from post data, or returns
-// REUSED_PASSWORD_TYPE_UNKNOWN if post data is not available.
-safe_browsing::ReusedPasswordType GetPasswordType(
- content::WebContents* web_contents) {
+// PASSWORD_TYPE_UNKNOWN if post data is not available.
+PasswordType GetPasswordType(content::WebContents* web_contents) {
content::NavigationEntry* nav_entry =
web_contents->GetController().GetPendingEntry();
if (!nav_entry || !nav_entry->GetHasPostData())
- return safe_browsing::PasswordReuseEvent::REUSED_PASSWORD_TYPE_UNKNOWN;
+ return PasswordType::PASSWORD_TYPE_UNKNOWN;
auto& post_data = nav_entry->GetPostData()->elements()->at(0);
int post_data_int = -1;
if (base::StringToInt(std::string(post_data.bytes(), post_data.length()),
&post_data_int)) {
- return static_cast<safe_browsing::ReusedPasswordType>(post_data_int);
+ return static_cast<PasswordType>(post_data_int);
}
- return safe_browsing::PasswordReuseEvent::REUSED_PASSWORD_TYPE_UNKNOWN;
+ return PasswordType::PASSWORD_TYPE_UNKNOWN;
}
// Properly format host name based on text direction.
@@ -137,8 +132,7 @@ base::DictionaryValue ResetPasswordUI::PopulateStrings() const {
GetPasswordProtectionService(Profile::FromWebUI(web_ui()))
->GetOrganizationName(password_type_);
bool known_password_type =
- password_type_ !=
- safe_browsing::PasswordReuseEvent::REUSED_PASSWORD_TYPE_UNKNOWN;
+ password_type_ != PasswordType::PASSWORD_TYPE_UNKNOWN;
int heading_string_id = known_password_type
? IDS_RESET_PASSWORD_WARNING_HEADING
diff --git a/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.h b/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.h
index 3f299695d7d..8712c13c91d 100644
--- a/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.h
+++ b/chromium/chrome/browser/ui/webui/reset_password/reset_password_ui.h
@@ -8,12 +8,15 @@
#include "base/macros.h"
#include "chrome/browser/safe_browsing/chrome_password_protection_service.h"
#include "chrome/browser/ui/webui/reset_password/reset_password.mojom.h"
+#include "components/password_manager/core/browser/password_manager_metrics_util.h"
#include "ui/webui/mojo_web_ui_controller.h"
namespace base {
class DictionaryValue;
}
+using password_manager::metrics_util::PasswordType;
+
// The WebUI for chrome://reset-password/.
class ResetPasswordUI : public ui::MojoWebUIController {
public:
@@ -26,7 +29,7 @@ class ResetPasswordUI : public ui::MojoWebUIController {
base::DictionaryValue PopulateStrings() const;
std::unique_ptr<mojom::ResetPasswordHandler> ui_handler_;
- const safe_browsing::ReusedPasswordType password_type_;
+ const PasswordType password_type_;
DISALLOW_COPY_AND_ASSIGN(ResetPasswordUI);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.cc b/chromium/chrome/browser/ui/webui/settings/about_handler.cc
index 37c62926b35..517f2c413cb 100644
--- a/chromium/chrome/browser/ui/webui/settings/about_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/about_handler.cc
@@ -16,6 +16,8 @@
#include "base/i18n/message_formatter.h"
#include "base/location.h"
#include "base/macros.h"
+#include "base/metrics/user_metrics.h"
+#include "base/metrics/user_metrics_action.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
@@ -60,9 +62,11 @@
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/tpm_firmware_update.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/webui/chromeos/image_source.h"
#include "chrome/browser/ui/webui/help/help_utils_chromeos.h"
#include "chrome/browser/ui/webui/help/version_updater_chromeos.h"
+#include "chromeos/constants/chromeos_features.h"
#include "chromeos/constants/chromeos_switches.h"
#include "chromeos/dbus/power/power_manager_client.h"
#include "chromeos/dbus/util/version_loader.h"
@@ -142,28 +146,20 @@ bool IsEnterpriseManaged() {
// Returns true if current user can change channel, false otherwise.
bool CanChangeChannel(Profile* profile) {
- // On a managed machine we delegate this setting to the users of the same
- // domain only if the policy value is "domain".
if (IsEnterpriseManaged()) {
bool value = false;
+ // On a managed machine we delegate this setting to the affiliated users
+ // only if the policy value is true.
chromeos::CrosSettings::Get()->GetBoolean(
chromeos::kReleaseChannelDelegated, &value);
if (!value)
return false;
- // Get the currently logged-in user and strip the domain part only.
- std::string domain = "";
+ // Get the currently logged-in user and check if it is affiliated.
const user_manager::User* user =
profile ? chromeos::ProfileHelper::Get()->GetUserByProfile(profile)
: nullptr;
- std::string email =
- user ? user->GetAccountId().GetUserEmail() : std::string();
- size_t at_pos = email.find('@');
- if (at_pos != std::string::npos && at_pos + 1 < email.length())
- domain = email.substr(email.find('@') + 1);
- policy::BrowserPolicyConnectorChromeOS* connector =
- g_browser_process->platform_part()->browser_policy_connector_chromeos();
- return domain == connector->GetEnterpriseEnrollmentDomain();
+ return user && user->IsAffiliated();
}
// On non-managed machines, only the local owner can change the channel.
@@ -285,8 +281,7 @@ std::string UpdateStatusToString(VersionUpdater::Status status) {
namespace settings {
-AboutHandler::AboutHandler()
- : apply_changes_from_upgrade_observer_(false), weak_factory_(this) {
+AboutHandler::AboutHandler() : apply_changes_from_upgrade_observer_(false) {
UpgradeDetector::GetInstance()->AddObserver(this);
}
@@ -396,6 +391,9 @@ void AboutHandler::RegisterMessages() {
base::Unretained(this)));
#if defined(OS_CHROMEOS)
web_ui()->RegisterMessageCallback(
+ "openOsHelpPage", base::BindRepeating(&AboutHandler::HandleOpenOsHelpPage,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
"setChannel", base::BindRepeating(&AboutHandler::HandleSetChannel,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
@@ -423,6 +421,18 @@ void AboutHandler::RegisterMessages() {
"getHasEndOfLife",
base::BindRepeating(&AboutHandler::HandleGetHasEndOfLife,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "getEnabledReleaseNotes",
+ base::BindRepeating(&AboutHandler::HandleGetEnabledReleaseNotes,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "launchReleaseNotes",
+ base::BindRepeating(&AboutHandler::HandleLaunchReleaseNotes,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "checkInternetConnection",
+ base::BindRepeating(&AboutHandler::HandleCheckInternetConnection,
+ base::Unretained(this)));
#endif
#if defined(OS_MACOSX)
web_ui()->RegisterMessageCallback(
@@ -521,6 +531,47 @@ void AboutHandler::HandleOpenHelpPage(const base::ListValue* args) {
}
#if defined(OS_CHROMEOS)
+void AboutHandler::HandleGetEnabledReleaseNotes(const base::ListValue* args) {
+ CHECK_EQ(1U, args->GetSize());
+ std::string callback_id;
+ CHECK(args->GetString(0, &callback_id));
+ ResolveJavascriptCallback(base::Value(callback_id),
+ base::Value(base::FeatureList::IsEnabled(
+ chromeos::features::kReleaseNotes)));
+}
+
+void AboutHandler::HandleCheckInternetConnection(const base::ListValue* args) {
+ CHECK_EQ(1U, args->GetSize());
+ std::string callback_id;
+ CHECK(args->GetString(0, &callback_id));
+
+ chromeos::NetworkStateHandler* network_state_handler =
+ chromeos::NetworkHandler::Get()->network_state_handler();
+ const chromeos::NetworkState* network =
+ network_state_handler->DefaultNetwork();
+ ResolveJavascriptCallback(base::Value(callback_id),
+ base::Value(network && network->IsOnline()));
+}
+
+void AboutHandler::HandleLaunchReleaseNotes(const base::ListValue* args) {
+ DCHECK(args->empty());
+ chromeos::NetworkStateHandler* network_state_handler =
+ chromeos::NetworkHandler::Get()->network_state_handler();
+ const chromeos::NetworkState* network =
+ network_state_handler->DefaultNetwork();
+ if (network && network->IsOnline()) {
+ base::RecordAction(
+ base::UserMetricsAction("ReleaseNotes.LaunchedAboutPage"));
+ chrome::LaunchReleaseNotes(Profile::FromWebUI(web_ui()));
+ }
+}
+
+void AboutHandler::HandleOpenOsHelpPage(const base::ListValue* args) {
+ DCHECK(args->empty());
+ Browser* browser =
+ chrome::FindBrowserWithWebContents(web_ui()->GetWebContents());
+ chrome::ShowHelp(browser, chrome::HELP_SOURCE_WEBUI_CHROME_OS);
+}
void AboutHandler::HandleSetChannel(const base::ListValue* args) {
DCHECK(args->GetSize() == 2);
diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.h b/chromium/chrome/browser/ui/webui/settings/about_handler.h
index 6395f3060ef..0c9d0b82c4e 100644
--- a/chromium/chrome/browser/ui/webui/settings/about_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/about_handler.h
@@ -85,6 +85,18 @@ class AboutHandler : public settings::SettingsPageUIHandler,
void HandleOpenHelpPage(const base::ListValue* args);
#if defined(OS_CHROMEOS)
+ // Checks if ReleaseNotes is enabled.
+ void HandleGetEnabledReleaseNotes(const base::ListValue* args);
+
+ // Checks if system is connected to internet.
+ void HandleCheckInternetConnection(const base::ListValue* args);
+
+ // Opens the release notes app. |args| must be empty.
+ void HandleLaunchReleaseNotes(const base::ListValue* args);
+
+ // Opens the help page. |args| must be empty.
+ void HandleOpenOsHelpPage(const base::ListValue* args);
+
// Sets the release track version.
void HandleSetChannel(const base::ListValue* args);
@@ -171,7 +183,7 @@ class AboutHandler : public settings::SettingsPageUIHandler,
bool apply_changes_from_upgrade_observer_;
// Used for callbacks.
- base::WeakPtrFactory<AboutHandler> weak_factory_;
+ base::WeakPtrFactory<AboutHandler> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(AboutHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc b/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc
index 435767b8b82..86695044727 100644
--- a/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/appearance_handler.cc
@@ -19,7 +19,7 @@
namespace settings {
AppearanceHandler::AppearanceHandler(content::WebUI* webui)
- : profile_(Profile::FromWebUI(webui)), weak_ptr_factory_(this) {}
+ : profile_(Profile::FromWebUI(webui)) {}
AppearanceHandler::~AppearanceHandler() {}
diff --git a/chromium/chrome/browser/ui/webui/settings/appearance_handler.h b/chromium/chrome/browser/ui/webui/settings/appearance_handler.h
index 3acb6d567f4..dabbd53601d 100644
--- a/chromium/chrome/browser/ui/webui/settings/appearance_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/appearance_handler.h
@@ -57,7 +57,7 @@ class AppearanceHandler : public SettingsPageUIHandler {
Profile* profile_; // Weak pointer.
- base::WeakPtrFactory<AppearanceHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<AppearanceHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(AppearanceHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/captions_handler.cc b/chromium/chrome/browser/ui/webui/settings/captions_handler.cc
new file mode 100644
index 00000000000..f91f2fdd3a1
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/captions_handler.cc
@@ -0,0 +1,34 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/settings/captions_handler.h"
+
+#include "base/bind.h"
+#include "base/bind_helpers.h"
+#include "chrome/browser/accessibility/caption_settings_dialog.h"
+#include "content/public/browser/web_ui.h"
+
+namespace settings {
+
+CaptionsHandler::CaptionsHandler() {}
+
+CaptionsHandler::~CaptionsHandler() {}
+
+void CaptionsHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "openSystemCaptionsDialog",
+ base::BindRepeating(&CaptionsHandler::HandleOpenSystemCaptionsDialog,
+ base::Unretained(this)));
+}
+
+void CaptionsHandler::OnJavascriptAllowed() {}
+
+void CaptionsHandler::OnJavascriptDisallowed() {}
+
+void CaptionsHandler::HandleOpenSystemCaptionsDialog(
+ const base::ListValue* args) {
+ captions::CaptionSettingsDialog::ShowCaptionSettingsDialog();
+}
+
+} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/captions_handler.h b/chromium/chrome/browser/ui/webui/settings/captions_handler.h
new file mode 100644
index 00000000000..28ea30dc334
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/captions_handler.h
@@ -0,0 +1,34 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CAPTIONS_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CAPTIONS_HANDLER_H_
+
+#include "base/macros.h"
+#include "build/build_config.h"
+#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
+
+namespace settings {
+
+// UI handler for Chrome caption settings subpage on operating systems other
+// than Chrome OS and Linux.
+class CaptionsHandler : public SettingsPageUIHandler {
+ public:
+ CaptionsHandler();
+ ~CaptionsHandler() override;
+
+ // SettingsPageUIHandler overrides:
+ void RegisterMessages() override;
+ void OnJavascriptAllowed() override;
+ void OnJavascriptDisallowed() override;
+
+ private:
+ void HandleOpenSystemCaptionsDialog(const base::ListValue* args);
+
+ DISALLOW_COPY_AND_ASSIGN(CaptionsHandler);
+};
+
+} // namespace settings
+
+#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CAPTIONS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc b/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc
index a768aa185c9..7047d2983da 100644
--- a/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/change_password_handler.cc
@@ -7,12 +7,14 @@
#include "base/bind.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/safe_browsing/chrome_password_protection_service.h"
+#include "components/password_manager/core/browser/password_manager_metrics_util.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
namespace settings {
+using password_manager::metrics_util::PasswordType;
using safe_browsing::ChromePasswordProtectionService;
ChangePasswordHandler::ChangePasswordHandler(
@@ -54,8 +56,7 @@ void ChangePasswordHandler::HandleInitialize(const base::ListValue* args) {
void ChangePasswordHandler::HandleChangePassword(const base::ListValue* args) {
service_->OnUserAction(web_ui()->GetWebContents(),
- safe_browsing::LoginReputationClientRequest::
- PasswordReuseEvent::SIGN_IN_PASSWORD,
+ PasswordType::PRIMARY_ACCOUNT_PASSWORD,
safe_browsing::WarningUIType::CHROME_SETTINGS,
safe_browsing::WarningAction::CHANGE_PASSWORD);
}
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc
index 8cba903e7f6..e06d7205e11 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc
@@ -6,10 +6,13 @@
#include <utility>
+#include "ash/public/cpp/toast_data.h"
+#include "ash/public/cpp/toast_manager.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
#include "base/macros.h"
+#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/policy/profile_policy_connector.h"
@@ -18,10 +21,13 @@
#include "chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h"
+#include "chrome/grit/generated_resources.h"
#include "chromeos/components/account_manager/account_manager_factory.h"
#include "components/user_manager/user.h"
+#include "google_apis/gaia/gaia_auth_util.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "third_party/skia/include/core/SkBitmap.h"
+#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/chromeos/resources/grit/ui_chromeos_resources.h"
@@ -33,6 +39,9 @@ namespace settings {
namespace {
constexpr char kFamilyLink[] = "Family Link";
+constexpr int kToastDurationMs = 2500;
+constexpr char kAccountRemovedToastId[] =
+ "settings_account_manager_account_removed";
std::string GetEnterpriseDomainFromUsername(const std::string& username) {
size_t email_separator_pos = username.find('@');
@@ -79,11 +88,16 @@ bool IsSameAccount(const AccountManager::AccountKey& account_key,
}
}
+void ShowToast(const std::string& id, const base::string16& message) {
+ ash::ToastManager::Get()->Show(ash::ToastData(
+ id, message, kToastDurationMs, /*dismiss_text=*/base::nullopt));
+}
+
} // namespace
AccountManagerUIHandler::AccountManagerUIHandler(
AccountManager* account_manager,
- identity::IdentityManager* identity_manager)
+ signin::IdentityManager* identity_manager)
: account_manager_(account_manager),
identity_manager_(identity_manager),
account_manager_observer_(this),
@@ -126,16 +140,22 @@ void AccountManagerUIHandler::RegisterMessages() {
void AccountManagerUIHandler::HandleGetAccounts(const base::ListValue* args) {
AllowJavascript();
- CHECK(!args->GetList().empty());
- base::Value callback_id = args->GetList()[0].Clone();
+ const auto& args_list = args->GetList();
+ CHECK_EQ(args_list.size(), 2u);
+ CHECK(args_list[0].is_string());
+ CHECK(args_list[1].is_bool());
+
+ base::Value callback_id = args_list[0].Clone();
+ bool include_images = args_list[1].GetBool();
- account_manager_->GetAccounts(
- base::BindOnce(&AccountManagerUIHandler::OnGetAccounts,
- weak_factory_.GetWeakPtr(), std::move(callback_id)));
+ account_manager_->GetAccounts(base::BindOnce(
+ &AccountManagerUIHandler::OnGetAccounts, weak_factory_.GetWeakPtr(),
+ std::move(callback_id), include_images));
}
void AccountManagerUIHandler::OnGetAccounts(
base::Value callback_id,
+ bool include_images,
const std::vector<AccountManager::Account>& stored_accounts) {
base::ListValue accounts;
@@ -169,17 +189,20 @@ void AccountManagerUIHandler::OnGetAccounts(
maybe_account_info->account_id));
account.SetString("fullName", maybe_account_info->full_name);
account.SetString("email", stored_account.raw_email);
- if (!maybe_account_info->account_image.IsEmpty()) {
- account.SetString("pic",
- webui::GetBitmapDataUrl(
- maybe_account_info->account_image.AsBitmap()));
- } else {
- gfx::ImageSkia default_icon =
- *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
- IDR_LOGIN_DEFAULT_USER);
- account.SetString("pic",
- webui::GetBitmapDataUrl(
- default_icon.GetRepresentation(1.0f).GetBitmap()));
+ // Images can be large, so only send them if requested.
+ if (include_images) {
+ if (!maybe_account_info->account_image.IsEmpty()) {
+ account.SetString("pic",
+ webui::GetBitmapDataUrl(
+ maybe_account_info->account_image.AsBitmap()));
+ } else {
+ gfx::ImageSkia default_icon =
+ *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
+ IDR_LOGIN_DEFAULT_USER);
+ account.SetString(
+ "pic", webui::GetBitmapDataUrl(
+ default_icon.GetRepresentation(1.0f).GetBitmap()));
+ }
}
account.SetBoolean("unmigrated",
account_manager_->HasDummyGaiaToken(account_key));
@@ -258,6 +281,16 @@ void AccountManagerUIHandler::HandleRemoveAccount(const base::ListValue* args) {
}
account_manager_->RemoveAccount(account_key);
+
+ // Show toast with removal message.
+ const base::Value* email_value = dictionary->FindKey("email");
+ const std::string email = email_value->GetString();
+ DCHECK(!email.empty());
+
+ ShowToast(kAccountRemovedToastId,
+ l10n_util::GetStringFUTF16(
+ IDS_SETTINGS_ACCOUNT_MANAGER_ACCOUNT_REMOVED_MESSAGE,
+ base::UTF8ToUTF16(email)));
}
void AccountManagerUIHandler::HandleShowWelcomeDialogIfRequired(
@@ -289,11 +322,11 @@ void AccountManagerUIHandler::OnAccountRemoved(
RefreshUI();
}
-// |identity::IdentityManager::Observer| overrides. For newly added accounts,
-// |identity::IdentityManager| may take some time to fetch user's full name and
+// |signin::IdentityManager::Observer| overrides. For newly added accounts,
+// |signin::IdentityManager| may take some time to fetch user's full name and
// account image. Whenever that is completed, we may need to update the UI with
// this new set of information. Note that we may be listening to
-// |identity::IdentityManager| but we still consider |AccountManager| to be the
+// |signin::IdentityManager| but we still consider |AccountManager| to be the
// source of truth for account list.
void AccountManagerUIHandler::OnExtendedAccountInfoUpdated(
const AccountInfo& info) {
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h
index c6acb8939b7..071c7cf9b22 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h
@@ -13,19 +13,19 @@
#include "base/scoped_observer.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "chromeos/components/account_manager/account_manager.h"
-#include "services/identity/public/cpp/identity_manager.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
namespace chromeos {
namespace settings {
class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler,
public AccountManager::Observer,
- public identity::IdentityManager::Observer {
+ public signin::IdentityManager::Observer {
public:
// Accepts non-owning pointers to |AccountManager|, |AccountTrackerService|
// and |IdentityManager|. Both of these must outlive |this| instance.
AccountManagerUIHandler(AccountManager* account_manager,
- identity::IdentityManager* identity_manager);
+ signin::IdentityManager* identity_manager);
~AccountManagerUIHandler() override;
// WebUIMessageHandler implementation.
@@ -39,7 +39,7 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler,
void OnTokenUpserted(const AccountManager::Account& account) override;
void OnAccountRemoved(const AccountManager::Account& account) override;
- // |identity::IdentityManager::Observer| overrides.
+ // |signin::IdentityManager::Observer| overrides.
void OnExtendedAccountInfoUpdated(const AccountInfo& info) override;
private:
@@ -64,6 +64,7 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler,
// |AccountManager::GetAccounts| callback.
void OnGetAccounts(
base::Value callback_id,
+ bool include_images,
const std::vector<AccountManager::Account>& stored_accounts);
// Refreshes the UI.
@@ -73,16 +74,16 @@ class AccountManagerUIHandler : public ::settings::SettingsPageUIHandler,
AccountManager* const account_manager_;
// A non-owning pointer to |IdentityManager|.
- identity::IdentityManager* const identity_manager_;
+ signin::IdentityManager* const identity_manager_;
// An observer for |AccountManager|. Automatically deregisters when |this| is
// destructed.
ScopedObserver<AccountManager, AccountManager::Observer>
account_manager_observer_;
- // An observer for |identity::IdentityManager|. Automatically deregisters when
+ // An observer for |signin::IdentityManager|. Automatically deregisters when
// |this| is destructed.
- ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer>
+ ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer>
identity_manager_observer_;
base::WeakPtrFactory<AccountManagerUIHandler> weak_factory_;
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 7559e034ef9..3a2b3bc5b12 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc
@@ -12,9 +12,9 @@
#include "base/bind_helpers.h"
#include "chrome/browser/chromeos/crostini/crostini_export_import.h"
#include "chrome/browser/chromeos/crostini/crostini_manager.h"
-#include "chrome/browser/chromeos/crostini/crostini_share_path.h"
#include "chrome/browser/chromeos/crostini/crostini_util.h"
#include "chrome/browser/chromeos/file_manager/path_util.h"
+#include "chrome/browser/chromeos/guest_os/guest_os_share_path.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_thread.h"
@@ -73,7 +73,7 @@ void CrostiniHandler::OnJavascriptAllowed() {
crostini::CrostiniManager::GetForProfile(profile_)
->AddInstallerViewStatusObserver(this);
if (chromeos::CrosUsbDetector::Get()) {
- chromeos::CrosUsbDetector::Get()->AddSharedUsbDeviceObserver(this);
+ chromeos::CrosUsbDetector::Get()->AddUsbDeviceObserver(this);
}
}
@@ -84,7 +84,7 @@ void CrostiniHandler::OnJavascriptDisallowed() {
->RemoveInstallerViewStatusObserver(this);
}
if (chromeos::CrosUsbDetector::Get()) {
- chromeos::CrosUsbDetector::Get()->RemoveSharedUsbDeviceObserver(this);
+ chromeos::CrosUsbDetector::Get()->RemoveUsbDeviceObserver(this);
}
}
@@ -126,7 +126,7 @@ void CrostiniHandler::HandleRemoveCrostiniSharedPath(
std::string path;
CHECK(args->GetString(1, &path));
- crostini::CrostiniSharePath::GetForProfile(profile_)->UnsharePath(
+ guest_os::GuestOsSharePath::GetForProfile(profile_)->UnsharePath(
vm_name, base::FilePath(path),
/*unpersist=*/true,
base::BindOnce(
@@ -141,13 +141,15 @@ void CrostiniHandler::HandleRemoveCrostiniSharedPath(
namespace {
base::ListValue UsbDevicesToListValue(
- const std::vector<SharedUsbDeviceInfo> shared_usbs) {
+ const std::vector<CrosUsbDeviceInfo> shared_usbs) {
base::ListValue usb_devices_list;
for (auto device : shared_usbs) {
base::Value device_info(base::Value::Type::DICTIONARY);
device_info.SetKey("guid", base::Value(device.guid));
device_info.SetKey("label", base::Value(device.label));
- device_info.SetKey("shared", base::Value(device.shared));
+ const bool shared_in_crostini =
+ device.vm_sharing_info[crostini::kCrostiniDefaultVmName].shared;
+ device_info.SetKey("shared", base::Value(shared_in_crostini));
usb_devices_list.GetList().push_back(std::move(device_info));
}
return usb_devices_list;
@@ -169,7 +171,7 @@ void CrostiniHandler::HandleGetCrostiniSharedUsbDevices(
ResolveJavascriptCallback(
base::Value(callback_id),
- UsbDevicesToListValue(detector->GetSharedUsbDevices()));
+ UsbDevicesToListValue(detector->GetDevicesSharableWithCrostini()));
}
void CrostiniHandler::HandleSetCrostiniUsbDeviceShared(
@@ -192,10 +194,12 @@ void CrostiniHandler::HandleSetCrostiniUsbDeviceShared(
base::DoNothing());
}
-void CrostiniHandler::OnSharedUsbDevicesChanged(
- const std::vector<SharedUsbDeviceInfo> shared_usbs) {
- FireWebUIListener("crostini-shared-usb-devices-changed",
- UsbDevicesToListValue(shared_usbs));
+void CrostiniHandler::OnUsbDevicesChanged() {
+ chromeos::CrosUsbDetector* detector = chromeos::CrosUsbDetector::Get();
+ DCHECK(detector); // This callback is called by the detector.
+ FireWebUIListener(
+ "crostini-shared-usb-devices-changed",
+ UsbDevicesToListValue(detector->GetDevicesSharableWithCrostini()));
}
void CrostiniHandler::HandleExportCrostiniContainer(
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 cda0346383e..97f4605f475 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h
@@ -23,7 +23,7 @@ namespace settings {
class CrostiniHandler : public ::settings::SettingsPageUIHandler,
public crostini::InstallerViewStatusObserver,
- public chromeos::SharedUsbDeviceObserver {
+ public chromeos::CrosUsbDeviceObserver {
public:
explicit CrostiniHandler(Profile* profile);
~CrostiniHandler() override;
@@ -47,8 +47,7 @@ class CrostiniHandler : public ::settings::SettingsPageUIHandler,
// Set the share state of a USB device.
void HandleSetCrostiniUsbDeviceShared(const base::ListValue* args);
// chromeos::SharedUsbDeviceObserver.
- void OnSharedUsbDevicesChanged(
- const std::vector<SharedUsbDeviceInfo> shared_usbs) override;
+ void OnUsbDevicesChanged() override;
// Export the crostini container.
void HandleExportCrostiniContainer(const base::ListValue* args);
// Import the crostini container.
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc
index 218e5bb79bc..b6021b75156 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc
@@ -59,16 +59,10 @@ namespace settings {
namespace {
-// These values are written to logs. New enum values can be added, but existing
-// enums must never be renumbered or deleted and reused.
-enum PpdSourceForHistogram { kUser = 0, kScs = 1, kPpdSourceMax };
+using printing::PrinterQueryResult;
constexpr int kPpdMaxLineLength = 255;
-void RecordPpdSource(const PpdSourceForHistogram& source) {
- UMA_HISTOGRAM_ENUMERATION("Printing.CUPS.PpdSource", source, kPpdSourceMax);
-}
-
void OnRemovedPrinter(const Printer::PrinterProtocol& protocol, bool success) {
if (success) {
PRINTER_LOG(DEBUG) << "Printer removal succeeded.";
@@ -101,18 +95,19 @@ bool IsIppUri(base::StringPiece printer_uri) {
// located at |printer_uri|. Results are reported through |callback|. It is an
// error to attempt this with a non-IPP printer.
void QueryAutoconf(const std::string& printer_uri,
- const PrinterInfoCallback& callback) {
+ PrinterInfoCallback callback) {
auto optional = ParseUri(printer_uri);
// Behavior for querying a non-IPP uri is undefined and disallowed.
if (!IsIppUri(printer_uri) || !optional.has_value()) {
PRINTER_LOG(ERROR) << "Printer uri is invalid: " << printer_uri;
- callback.Run(false, "", "", "", {}, false);
+ std::move(callback).Run(PrinterQueryResult::UNKNOWN_FAILURE, "", "", "", {},
+ false);
return;
}
UriComponents uri = optional.value();
QueryIppPrinter(uri.host(), uri.port(), uri.path(), uri.encrypted(),
- callback);
+ std::move(callback));
}
// Returns the list of |printers| formatted as a CupsPrintersList.
@@ -388,10 +383,13 @@ void CupsPrintersHandler::HandleGetCupsPrintersList(
}
void CupsPrintersHandler::HandleUpdateCupsPrinter(const base::ListValue* args) {
+ std::string callback_id;
std::string printer_id;
std::string printer_name;
- CHECK(args->GetString(0, &printer_id));
- CHECK(args->GetString(1, &printer_name));
+ CHECK_EQ(3U, args->GetSize());
+ CHECK(args->GetString(0, &callback_id));
+ CHECK(args->GetString(1, &printer_id));
+ CHECK(args->GetString(2, &printer_name));
Printer printer(printer_id);
printer.set_display_name(printer_name);
@@ -402,12 +400,14 @@ void CupsPrintersHandler::HandleUpdateCupsPrinter(const base::ListValue* args) {
OnAddedOrEditedPrinterCommon(printer,
PrinterSetupResult::kNativePrintersNotAllowed,
false /* is_automatic */);
- // Used to fire the web UI listener.
- OnAddOrEditPrinterError(PrinterSetupResult::kNativePrintersNotAllowed);
+ // Logs the error and runs the callback.
+ OnAddOrEditPrinterError(callback_id,
+ PrinterSetupResult::kNativePrintersNotAllowed);
return;
}
- OnAddedOrEditedSpecifiedPrinter(printer, true /* is_printer_edit */,
+ OnAddedOrEditedSpecifiedPrinter(callback_id, printer,
+ true /* is_printer_edit */,
PrinterSetupResult::kEditSuccess);
}
@@ -459,7 +459,8 @@ void CupsPrintersHandler::HandleGetPrinterInfo(const base::ListValue* args) {
if (printer_address.empty()) {
// Run the failure callback.
- OnAutoconfQueried(callback_id, false, "", "", "", {}, false);
+ OnAutoconfQueried(callback_id, PrinterQueryResult::UNKNOWN_FAILURE, "", "",
+ "", {}, false);
return;
}
@@ -478,18 +479,20 @@ void CupsPrintersHandler::HandleGetPrinterInfo(const base::ListValue* args) {
base::StringPrintf("%s://%s/%s", printer_protocol.c_str(),
printer_address.c_str(), printer_queue.c_str());
QueryAutoconf(printer_uri,
- base::Bind(&CupsPrintersHandler::OnAutoconfQueried,
- weak_factory_.GetWeakPtr(), callback_id));
+ base::BindOnce(&CupsPrintersHandler::OnAutoconfQueried,
+ weak_factory_.GetWeakPtr(), callback_id));
}
void CupsPrintersHandler::OnAutoconfQueriedDiscovered(
+ const std::string& callback_id,
Printer printer,
- bool success,
+ PrinterQueryResult result,
const std::string& make,
const std::string& model,
const std::string& make_and_model,
const std::vector<std::string>& document_formats,
bool ipp_everywhere) {
+ const bool success = result == PrinterQueryResult::SUCCESS;
RecordIppQuerySuccess(success);
if (success) {
@@ -514,7 +517,7 @@ void CupsPrintersHandler::OnAutoconfQueriedDiscovered(
printer_configurer_->SetUpPrinter(
printer,
base::BindOnce(&CupsPrintersHandler::OnAddedDiscoveredPrinter,
- weak_factory_.GetWeakPtr(), printer));
+ weak_factory_.GetWeakPtr(), callback_id, printer));
return;
}
}
@@ -523,24 +526,35 @@ void CupsPrintersHandler::OnAutoconfQueriedDiscovered(
// much information as we can about the printer, and ask the user to supply
// the rest.
PRINTER_LOG(EVENT) << "Could not query printer. Fallback to asking the user";
- FireManuallyAddDiscoveredPrinter(printer);
+ RejectJavascriptCallback(base::Value(callback_id),
+ *GetCupsPrinterInfo(printer));
}
void CupsPrintersHandler::OnAutoconfQueried(
const std::string& callback_id,
- bool success,
+ PrinterQueryResult result,
const std::string& make,
const std::string& model,
const std::string& make_and_model,
const std::vector<std::string>& document_formats,
bool ipp_everywhere) {
+ const bool success = result == PrinterQueryResult::SUCCESS;
RecordIppQuerySuccess(success);
+ if (result == PrinterQueryResult::UNREACHABLE) {
+ PRINTER_LOG(DEBUG) << "Could not reach printer";
+ RejectJavascriptCallback(
+ base::Value(callback_id),
+ base::Value(PrinterSetupResult::kPrinterUnreachable));
+ return;
+ }
+
if (!success) {
PRINTER_LOG(DEBUG) << "Could not query printer";
base::DictionaryValue reject;
reject.SetString("message", "Querying printer failed");
- RejectJavascriptCallback(base::Value(callback_id), reject);
+ RejectJavascriptCallback(base::Value(callback_id),
+ base::Value(PrinterSetupResult::kFatalError));
return;
}
@@ -603,13 +617,16 @@ void CupsPrintersHandler::HandleReconfigureCupsPrinter(
void CupsPrintersHandler::AddOrReconfigurePrinter(const base::ListValue* args,
bool is_printer_edit) {
+ std::string callback_id;
const base::DictionaryValue* printer_dict = nullptr;
- CHECK(args->GetDictionary(0, &printer_dict));
+ CHECK_EQ(2U, args->GetSize());
+ CHECK(args->GetString(0, &callback_id));
+ CHECK(args->GetDictionary(1, &printer_dict));
std::unique_ptr<Printer> printer = DictToPrinter(*printer_dict);
if (!printer) {
PRINTER_LOG(ERROR) << "Failed to parse printer URI";
- OnAddOrEditPrinterError(PrinterSetupResult::kFatalError);
+ OnAddOrEditPrinterError(callback_id, PrinterSetupResult::kFatalError);
return;
}
@@ -620,7 +637,8 @@ void CupsPrintersHandler::AddOrReconfigurePrinter(const base::ListValue* args,
PrinterSetupResult::kNativePrintersNotAllowed,
false /* is_automatic */);
// Used to fire the web UI listener.
- OnAddOrEditPrinterError(PrinterSetupResult::kNativePrintersNotAllowed);
+ OnAddOrEditPrinterError(callback_id,
+ PrinterSetupResult::kNativePrintersNotAllowed);
return;
}
@@ -628,7 +646,7 @@ void CupsPrintersHandler::AddOrReconfigurePrinter(const base::ListValue* args,
// If the returned optional does not contain a value then it means that the
// printer's uri was not able to be parsed successfully.
PRINTER_LOG(ERROR) << "Failed to parse printer URI";
- OnAddOrEditPrinterError(PrinterSetupResult::kFatalError);
+ OnAddOrEditPrinterError(callback_id, PrinterSetupResult::kFatalError);
return;
}
@@ -638,7 +656,7 @@ void CupsPrintersHandler::AddOrReconfigurePrinter(const base::ListValue* args,
// If the printer object has not already been created, error out since this
// is not a valid case.
PRINTER_LOG(ERROR) << "Failed to parse printer ID";
- OnAddOrEditPrinterError(PrinterSetupResult::kFatalError);
+ OnAddOrEditPrinterError(callback_id, PrinterSetupResult::kFatalError);
return;
}
@@ -646,7 +664,8 @@ void CupsPrintersHandler::AddOrReconfigurePrinter(const base::ListValue* args,
printers_manager_->GetPrinter(printer->id());
if (existing_printer_object) {
if (!IsValidUriChange(*existing_printer_object, *printer)) {
- OnAddOrEditPrinterError(PrinterSetupResult::kInvalidPrinterUpdate);
+ OnAddOrEditPrinterError(callback_id,
+ PrinterSetupResult::kInvalidPrinterUpdate);
return;
}
}
@@ -669,16 +688,14 @@ void CupsPrintersHandler::AddOrReconfigurePrinter(const base::ListValue* args,
if (ppd_ref_resolved) {
*printer->mutable_ppd_reference() = GetPpdReference(printer_dict);
} else if (!printer_ppd_path.empty()) {
- RecordPpdSource(kUser);
GURL tmp = net::FilePathToFileURL(base::FilePath(printer_ppd_path));
if (!tmp.is_valid()) {
LOG(ERROR) << "Invalid ppd path: " << printer_ppd_path;
- OnAddOrEditPrinterError(PrinterSetupResult::kInvalidPpd);
+ OnAddOrEditPrinterError(callback_id, PrinterSetupResult::kInvalidPpd);
return;
}
printer->mutable_ppd_reference()->user_supplied_ppd_url = tmp.spec();
} else if (!ppd_manufacturer.empty() && !ppd_model.empty()) {
- RecordPpdSource(kScs);
// Pull out the ppd reference associated with the selected manufacturer and
// model.
bool found = false;
@@ -691,7 +708,7 @@ void CupsPrintersHandler::AddOrReconfigurePrinter(const base::ListValue* args,
}
if (!found) {
LOG(ERROR) << "Failed to get ppd reference";
- OnAddOrEditPrinterError(PrinterSetupResult::kPpdNotFound);
+ OnAddOrEditPrinterError(callback_id, PrinterSetupResult::kPpdNotFound);
return;
}
@@ -713,7 +730,8 @@ void CupsPrintersHandler::AddOrReconfigurePrinter(const base::ListValue* args,
printer_configurer_->SetUpPrinter(
*printer,
base::BindOnce(&CupsPrintersHandler::OnAddedOrEditedSpecifiedPrinter,
- weak_factory_.GetWeakPtr(), *printer, is_printer_edit));
+ weak_factory_.GetWeakPtr(), callback_id, *printer,
+ is_printer_edit));
}
void CupsPrintersHandler::OnAddedOrEditedPrinterCommon(
@@ -785,21 +803,24 @@ void CupsPrintersHandler::OnAddedOrEditedPrinterCommon(
}
void CupsPrintersHandler::OnAddedDiscoveredPrinter(
+ const std::string& callback_id,
const Printer& printer,
PrinterSetupResult result_code) {
OnAddedOrEditedPrinterCommon(printer, result_code, /*is_automatic=*/true);
if (result_code == PrinterSetupResult::kSuccess) {
- FireWebUIListener("on-add-or-edit-cups-printer", base::Value(result_code),
- base::Value(printer.display_name()));
+ ResolveJavascriptCallback(base::Value(callback_id),
+ base::Value(result_code));
} else {
PRINTER_LOG(EVENT) << "Automatic setup failed for discovered printer. "
"Fall back to manual.";
// Could not set up printer. Asking user for manufacturer data.
- FireManuallyAddDiscoveredPrinter(printer);
+ RejectJavascriptCallback(base::Value(callback_id),
+ *GetCupsPrinterInfo(printer));
}
}
void CupsPrintersHandler::OnAddedOrEditedSpecifiedPrinter(
+ const std::string& callback_id,
const Printer& printer,
bool is_printer_edit,
PrinterSetupResult result_code) {
@@ -808,35 +829,42 @@ void CupsPrintersHandler::OnAddedOrEditedSpecifiedPrinter(
}
PRINTER_LOG(EVENT) << "Add/Update manual printer: " << result_code;
OnAddedOrEditedPrinterCommon(printer, result_code, /*is_automatic=*/false);
- FireWebUIListener("on-add-or-edit-cups-printer", base::Value(result_code),
- base::Value(printer.display_name()));
+
+ if (result_code != PrinterSetupResult::kSuccess &&
+ result_code != PrinterSetupResult::kEditSuccess) {
+ RejectJavascriptCallback(base::Value(callback_id),
+ base::Value(result_code));
+ return;
+ }
+
+ ResolveJavascriptCallback(base::Value(callback_id), base::Value(result_code));
}
void CupsPrintersHandler::OnAddOrEditPrinterError(
+ const std::string& callback_id,
PrinterSetupResult result_code) {
PRINTER_LOG(EVENT) << "Add printer error: " << result_code;
- FireWebUIListener("on-add-or-edit-cups-printer", base::Value(result_code),
- base::Value(""));
+ RejectJavascriptCallback(base::Value(callback_id), base::Value(result_code));
}
void CupsPrintersHandler::HandleGetCupsPrinterManufacturers(
const base::ListValue* args) {
AllowJavascript();
- std::string js_callback;
+ std::string callback_id;
CHECK_EQ(1U, args->GetSize());
- CHECK(args->GetString(0, &js_callback));
+ CHECK(args->GetString(0, &callback_id));
ppd_provider_->ResolveManufacturers(
- base::Bind(&CupsPrintersHandler::ResolveManufacturersDone,
- weak_factory_.GetWeakPtr(), js_callback));
+ base::BindOnce(&CupsPrintersHandler::ResolveManufacturersDone,
+ weak_factory_.GetWeakPtr(), callback_id));
}
void CupsPrintersHandler::HandleGetCupsPrinterModels(
const base::ListValue* args) {
AllowJavascript();
- std::string js_callback;
+ std::string callback_id;
std::string manufacturer;
CHECK_EQ(2U, args->GetSize());
- CHECK(args->GetString(0, &js_callback));
+ CHECK(args->GetString(0, &callback_id));
CHECK(args->GetString(1, &manufacturer));
// Empty manufacturer queries may be triggered as a part of the ui
@@ -845,14 +873,14 @@ void CupsPrintersHandler::HandleGetCupsPrinterModels(
base::DictionaryValue response;
response.SetBoolean("success", true);
response.Set("models", std::make_unique<base::ListValue>());
- ResolveJavascriptCallback(base::Value(js_callback), response);
+ ResolveJavascriptCallback(base::Value(callback_id), response);
return;
}
ppd_provider_->ResolvePrinters(
manufacturer,
- base::Bind(&CupsPrintersHandler::ResolvePrintersDone,
- weak_factory_.GetWeakPtr(), manufacturer, js_callback));
+ base::BindOnce(&CupsPrintersHandler::ResolvePrintersDone,
+ weak_factory_.GetWeakPtr(), manufacturer, callback_id));
}
void CupsPrintersHandler::HandleSelectPPDFile(const base::ListValue* args) {
@@ -877,7 +905,7 @@ void CupsPrintersHandler::HandleSelectPPDFile(const base::ListValue* args) {
}
void CupsPrintersHandler::ResolveManufacturersDone(
- const std::string& js_callback,
+ const std::string& callback_id,
PpdProvider::CallbackResultCode result_code,
const std::vector<std::string>& manufacturers) {
auto manufacturers_value = std::make_unique<base::ListValue>();
@@ -887,12 +915,12 @@ void CupsPrintersHandler::ResolveManufacturersDone(
base::DictionaryValue response;
response.SetBoolean("success", result_code == PpdProvider::SUCCESS);
response.Set("manufacturers", std::move(manufacturers_value));
- ResolveJavascriptCallback(base::Value(js_callback), response);
+ ResolveJavascriptCallback(base::Value(callback_id), response);
}
void CupsPrintersHandler::ResolvePrintersDone(
const std::string& manufacturer,
- const std::string& js_callback,
+ const std::string& callback_id,
PpdProvider::CallbackResultCode result_code,
const PpdProvider::ResolvedPrintersList& printers) {
auto printers_value = std::make_unique<base::ListValue>();
@@ -905,7 +933,7 @@ void CupsPrintersHandler::ResolvePrintersDone(
base::DictionaryValue response;
response.SetBoolean("success", result_code == PpdProvider::SUCCESS);
response.Set("models", std::move(printers_value));
- ResolveJavascriptCallback(base::Value(js_callback), response);
+ ResolveJavascriptCallback(base::Value(callback_id), response);
}
void CupsPrintersHandler::FileSelected(const base::FilePath& path,
@@ -999,24 +1027,30 @@ void CupsPrintersHandler::UpdateDiscoveredPrinters() {
return;
}
- std::unique_ptr<base::ListValue> printers_list =
+ std::unique_ptr<base::ListValue> automatic_printers_list =
std::make_unique<base::ListValue>();
for (const Printer& printer : automatic_printers_) {
- printers_list->Append(GetCupsPrinterInfo(printer));
+ automatic_printers_list->Append(GetCupsPrinterInfo(printer));
}
+
+ std::unique_ptr<base::ListValue> discovered_printers_list =
+ std::make_unique<base::ListValue>();
for (const Printer& printer : discovered_printers_) {
- printers_list->Append(GetCupsPrinterInfo(printer));
+ discovered_printers_list->Append(GetCupsPrinterInfo(printer));
}
- FireWebUIListener("on-printer-discovered", *printers_list);
+ FireWebUIListener("on-nearby-printers-changed", *automatic_printers_list,
+ *discovered_printers_list);
}
void CupsPrintersHandler::HandleAddDiscoveredPrinter(
const base::ListValue* args) {
AllowJavascript();
- CHECK_EQ(1U, args->GetSize());
+ CHECK_EQ(2U, args->GetSize());
+ std::string callback_id;
std::string printer_id;
- CHECK(args->GetString(0, &printer_id));
+ CHECK(args->GetString(0, &callback_id));
+ CHECK(args->GetString(1, &printer_id));
PRINTER_LOG(USER) << "Adding discovered printer";
base::Optional<Printer> printer = printers_manager_->GetPrinter(printer_id);
@@ -1024,16 +1058,18 @@ void CupsPrintersHandler::HandleAddDiscoveredPrinter(
PRINTER_LOG(ERROR) << "Discovered printer disappeared";
// Printer disappeared, so we don't have information about it anymore and
// can't really do much. Fail the add.
- FireWebUIListener("on-add-or-edit-cups-printer", base::Value(false),
- base::Value(printer_id));
+ ResolveJavascriptCallback(
+ base::Value(callback_id),
+ base::Value(PrinterSetupResult::kPrinterUnreachable));
return;
}
if (!printer->GetUriComponents().has_value()) {
PRINTER_LOG(DEBUG) << "Could not parse uri";
// The printer uri was not parsed successfully. Fail the add.
- FireWebUIListener("on-add-or-edit-cups-printer", base::Value(false),
- base::Value(printer_id));
+ ResolveJavascriptCallback(
+ base::Value(callback_id),
+ base::Value(PrinterSetupResult::kPrinterUnreachable));
return;
}
@@ -1044,8 +1080,9 @@ void CupsPrintersHandler::HandleAddDiscoveredPrinter(
// If we have something that looks like a ppd reference for this printer,
// try to configure it.
printer_configurer_->SetUpPrinter(
- *printer, base::Bind(&CupsPrintersHandler::OnAddedDiscoveredPrinter,
- weak_factory_.GetWeakPtr(), *printer));
+ *printer,
+ base::BindOnce(&CupsPrintersHandler::OnAddedDiscoveredPrinter,
+ weak_factory_.GetWeakPtr(), callback_id, *printer));
return;
}
@@ -1054,12 +1091,14 @@ void CupsPrintersHandler::HandleAddDiscoveredPrinter(
auto address = printer->GetHostAndPort();
if (address.IsEmpty()) {
PRINTER_LOG(ERROR) << "Address is invalid";
- OnAddedDiscoveredPrinter(*printer, PrinterSetupResult::kPrinterUnreachable);
+ OnAddedDiscoveredPrinter(callback_id, *printer,
+ PrinterSetupResult::kPrinterUnreachable);
return;
}
endpoint_resolver_->Start(
address, base::BindOnce(&CupsPrintersHandler::OnIpResolved,
- weak_factory_.GetWeakPtr(), std::move(*printer)));
+ weak_factory_.GetWeakPtr(), callback_id,
+ std::move(*printer)));
}
void CupsPrintersHandler::HandleGetPrinterPpdManufacturerAndModel(
@@ -1079,8 +1118,8 @@ void CupsPrintersHandler::HandleGetPrinterPpdManufacturerAndModel(
ppd_provider_->ReverseLookup(
printer->ppd_reference().effective_make_and_model,
- base::Bind(&CupsPrintersHandler::OnGetPrinterPpdManufacturerAndModel,
- weak_factory_.GetWeakPtr(), callback_id));
+ base::BindOnce(&CupsPrintersHandler::OnGetPrinterPpdManufacturerAndModel,
+ weak_factory_.GetWeakPtr(), callback_id));
}
void CupsPrintersHandler::OnGetPrinterPpdManufacturerAndModel(
@@ -1113,20 +1152,16 @@ void CupsPrintersHandler::HandleGetEulaUrl(const base::ListValue* args) {
base::Value("" /* eulaUrl */));
}
-void CupsPrintersHandler::FireManuallyAddDiscoveredPrinter(
- const Printer& printer) {
- FireWebUIListener("on-manually-add-discovered-printer",
- *GetCupsPrinterInfo(printer));
-}
-
-void CupsPrintersHandler::OnIpResolved(const Printer& printer,
+void CupsPrintersHandler::OnIpResolved(const std::string& callback_id,
+ const Printer& printer,
const net::IPEndPoint& endpoint) {
bool address_resolved = endpoint.address().IsValid();
UMA_HISTOGRAM_BOOLEAN("Printing.CUPS.AddressResolutionResult",
address_resolved);
if (!address_resolved) {
PRINTER_LOG(ERROR) << printer.make_and_model() << " IP Resolution failed";
- OnAddedDiscoveredPrinter(printer, PrinterSetupResult::kPrinterUnreachable);
+ OnAddedDiscoveredPrinter(callback_id, printer,
+ PrinterSetupResult::kPrinterUnreachable);
return;
}
@@ -1137,14 +1172,15 @@ void CupsPrintersHandler::OnIpResolved(const Printer& printer,
PRINTER_LOG(EVENT) << "Query printer for IPP attributes";
QueryAutoconf(
resolved_uri,
- base::BindRepeating(&CupsPrintersHandler::OnAutoconfQueriedDiscovered,
- weak_factory_.GetWeakPtr(), printer));
+ base::BindOnce(&CupsPrintersHandler::OnAutoconfQueriedDiscovered,
+ weak_factory_.GetWeakPtr(), callback_id, printer));
return;
}
PRINTER_LOG(EVENT) << "Request make and model from user";
// If it's not an IPP printer, the user must choose a PPD.
- FireManuallyAddDiscoveredPrinter(printer);
+ RejectJavascriptCallback(base::Value(callback_id),
+ *GetCupsPrinterInfo(printer));
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h
index f790bfcaee2..d2b16b0ec44 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h
@@ -20,6 +20,7 @@
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "chromeos/printing/ppd_provider.h"
#include "chromeos/printing/printer_configuration.h"
+#include "printing/printer_query_result_chromeos.h"
#include "ui/shell_dialogs/select_file_dialog.h"
namespace base {
@@ -79,7 +80,7 @@ class CupsPrintersHandler : public ::settings::SettingsPageUIHandler,
// Everywhere driver should be attempted. If |success| is false, the values of
// |make|, |model|, |make_and_model|, and |ipp_everywhere| are not specified.
void OnAutoconfQueried(const std::string& callback_id,
- bool success,
+ printing::PrinterQueryResult result,
const std::string& make,
const std::string& model,
const std::string& make_and_model,
@@ -88,8 +89,9 @@ class CupsPrintersHandler : public ::settings::SettingsPageUIHandler,
// Handles the callback for HandleGetPrinterInfo for a discovered printer.
void OnAutoconfQueriedDiscovered(
+ const std::string& callback_id,
Printer printer,
- bool success,
+ printing::PrinterQueryResult result,
const std::string& make,
const std::string& model,
const std::string& make_and_model,
@@ -112,13 +114,15 @@ class CupsPrintersHandler : public ::settings::SettingsPageUIHandler,
// Handles the result of adding a printer which the user specified the
// location of (i.e. a printer that was not 'discovered' automatically).
- void OnAddedOrEditedSpecifiedPrinter(const Printer& printer,
+ void OnAddedOrEditedSpecifiedPrinter(const std::string& callback_id,
+ const Printer& printer,
bool is_printer_edit,
PrinterSetupResult result);
// Handles the result of failure to add a printer. |result_code| is used to
// determine the reason for the failure.
- void OnAddOrEditPrinterError(PrinterSetupResult result_code);
+ void OnAddOrEditPrinterError(const std::string& callback_id,
+ PrinterSetupResult result_code);
// Get a list of all manufacturers for which we have at least one model of
// printer supported. Takes one argument, the callback id for the result.
@@ -135,11 +139,11 @@ class CupsPrintersHandler : public ::settings::SettingsPageUIHandler,
void HandleSelectPPDFile(const base::ListValue* args);
// PpdProvider callback handlers.
- void ResolveManufacturersDone(const std::string& js_callback,
+ void ResolveManufacturersDone(const std::string& callback_id,
PpdProvider::CallbackResultCode result_code,
const std::vector<std::string>& available);
void ResolvePrintersDone(const std::string& manufacturer,
- const std::string& js_callback,
+ const std::string& callback_id,
PpdProvider::CallbackResultCode result_code,
const PpdProvider::ResolvedPrintersList& printers);
@@ -164,7 +168,8 @@ class CupsPrintersHandler : public ::settings::SettingsPageUIHandler,
void HandleAddDiscoveredPrinter(const base::ListValue* args);
// Post printer setup callback.
- void OnAddedDiscoveredPrinter(const Printer& printer,
+ void OnAddedDiscoveredPrinter(const std::string& callback_id,
+ const Printer& printer,
PrinterSetupResult result_code);
// Code common between the discovered and manual add printer code paths.
@@ -195,7 +200,9 @@ class CupsPrintersHandler : public ::settings::SettingsPageUIHandler,
// parameters. See https://crbug.com/835476
void FireManuallyAddDiscoveredPrinter(const Printer& printer);
- void OnIpResolved(const Printer& printer, const net::IPEndPoint& endpoint);
+ void OnIpResolved(const std::string& callback_id,
+ const Printer& printer,
+ const net::IPEndPoint& endpoint);
Profile* profile_;
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc
index c3a3202bb1d..812cffcf10f 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc
@@ -4,10 +4,14 @@
#include "chrome/browser/ui/webui/settings/chromeos/date_time_handler.h"
+#include "ash/public/cpp/login_screen.h"
+#include "ash/public/cpp/login_types.h"
#include "base/bind.h"
#include "base/command_line.h"
+#include "base/logging.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
+#include "chrome/browser/chromeos/child_accounts/parent_access_code/parent_access_service.h"
#include "chrome/browser/chromeos/set_time_dialog.h"
#include "chrome/browser/chromeos/system/timezone_resolver_manager.h"
#include "chrome/browser/chromeos/system/timezone_util.h"
@@ -17,6 +21,7 @@
#include "chromeos/settings/timezone_settings.h"
#include "components/policy/proto/chrome_device_policy.pb.h"
#include "components/prefs/pref_service.h"
+#include "components/user_manager/user_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
@@ -87,6 +92,10 @@ void DateTimeHandler::RegisterMessages() {
"showSetDateTimeUI",
base::BindRepeating(&DateTimeHandler::HandleShowSetDateTimeUI,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "handleShowParentAccessForTimeZone",
+ base::BindRepeating(&DateTimeHandler::HandleShowParentAccessForTimeZone,
+ base::Unretained(this)));
}
void DateTimeHandler::OnJavascriptAllowed() {
@@ -141,6 +150,29 @@ void DateTimeHandler::HandleShowSetDateTimeUI(const base::ListValue* args) {
web_ui()->GetWebContents()->GetTopLevelNativeWindow());
}
+void DateTimeHandler::HandleShowParentAccessForTimeZone(
+ const base::ListValue* args) {
+ DCHECK(user_manager::UserManager::Get()->GetActiveUser()->IsChild());
+
+ if (!parent_access::ParentAccessService::IsApprovalRequired(
+ parent_access::ParentAccessService::SupervisedAction::
+ kUpdateTimezone)) {
+ OnParentAccessValidation(true);
+ return;
+ }
+
+ ash::LoginScreen::Get()->ShowParentAccessWidget(
+ user_manager::UserManager::Get()->GetActiveUser()->GetAccountId(),
+ base::BindRepeating(&DateTimeHandler::OnParentAccessValidation,
+ weak_ptr_factory_.GetWeakPtr()),
+ ash::ParentAccessRequestReason::kChangeTimezone);
+}
+
+void DateTimeHandler::OnParentAccessValidation(bool success) {
+ if (success)
+ FireWebUIListener("access-code-validation-complete");
+}
+
void DateTimeHandler::NotifyTimezoneAutomaticDetectionPolicy() {
bool managed = !IsTimezoneAutomaticDetectionUserEditable();
bool force_enabled = managed &&
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h
index c4f2a32f874..bd69d936bc8 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.h
@@ -55,6 +55,14 @@ class DateTimeHandler : public ::settings::SettingsPageUIHandler,
// Called to show the Set Time UI.
void HandleShowSetDateTimeUI(const base::ListValue* args);
+ // Handles clicks on the timezone row on the settings page. This should only
+ // be called when the current user is a child.
+ void HandleShowParentAccessForTimeZone(const base::ListValue* args);
+
+ // Called when the parent access code was validated with result equals
+ // |success|.
+ void OnParentAccessValidation(bool success);
+
// Updates the UI, enabling or disabling the time zone automatic detection
// setting according to policy.
void NotifyTimezoneAutomaticDetectionPolicy();
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 11a2cc23cfb..de342d5a55e 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
@@ -11,13 +11,12 @@
#include "base/values.h"
#include "chrome/browser/ui/ash/tablet_mode_client.h"
#include "chromeos/constants/chromeos_switches.h"
-#include "chromeos/services/assistant/public/features.h"
#include "content/public/browser/web_ui.h"
#include "content/public/common/service_manager_connection.h"
#include "services/service_manager/public/cpp/connector.h"
#include "ui/chromeos/events/event_rewriter_chromeos.h"
#include "ui/chromeos/events/keyboard_layout_util.h"
-#include "ui/events/devices/input_device_manager.h"
+#include "ui/events/devices/device_data_manager.h"
namespace {
@@ -30,7 +29,7 @@ struct KeyboardsStateResult {
KeyboardsStateResult GetKeyboardsState() {
KeyboardsStateResult result;
for (const ui::InputDevice& keyboard :
- ui::InputDeviceManager::GetInstance()->GetKeyboardDevices()) {
+ ui::DeviceDataManager::GetInstance()->GetKeyboardDevices()) {
result.has_internal_keyboard |=
(keyboard.type == ui::INPUT_DEVICE_INTERNAL);
@@ -80,7 +79,7 @@ void KeyboardHandler::RegisterMessages() {
}
void KeyboardHandler::OnJavascriptAllowed() {
- observer_.Add(ui::InputDeviceManager::GetInstance());
+ observer_.Add(ui::DeviceDataManager::GetInstance());
}
void KeyboardHandler::OnJavascriptDisallowed() {
@@ -121,7 +120,7 @@ void KeyboardHandler::UpdateKeyboards() {
}
if (!physical_keyboard) {
for (const ui::InputDevice& keyboard :
- ui::InputDeviceManager::GetInstance()->GetKeyboardDevices()) {
+ ui::DeviceDataManager::GetInstance()->GetKeyboardDevices()) {
if (keyboard.type != ui::InputDeviceType::INPUT_DEVICE_INTERNAL) {
physical_keyboard = true;
break;
@@ -150,9 +149,7 @@ void KeyboardHandler::UpdateShowKeys() {
keyboard_params.SetKey("hasInternalKeyboard",
base::Value(keyboards_state.has_internal_keyboard));
- const bool show_assistant_key_settings =
- chromeos::assistant::features::IsKeyRemappingEnabled() &&
- ui::DeviceKeyboardHasAssistantKey();
+ const bool show_assistant_key_settings = ui::DeviceKeyboardHasAssistantKey();
keyboard_params.SetKey("hasAssistantKey",
base::Value(show_assistant_key_settings));
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 84b01082a20..89e70bb56cf 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
@@ -15,7 +15,7 @@ class ListValue;
}
namespace ui {
-class InputDeviceManager;
+class DeviceDataManager;
}
namespace chromeos {
@@ -71,7 +71,7 @@ class KeyboardHandler
// Sends the UI a message about whether hardware keyboard are attached.
void UpdateKeyboards();
- ScopedObserver<ui::InputDeviceManager, KeyboardHandler> observer_;
+ ScopedObserver<ui::DeviceDataManager, KeyboardHandler> observer_;
DISALLOW_COPY_AND_ASSIGN(KeyboardHandler);
};
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 21bf646a62e..8f4f6318a50 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
@@ -15,11 +15,9 @@
#include "base/observer_list.h"
#include "chromeos/constants/chromeos_switches.h"
#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/device_data_manager_test_api.h"
#include "ui/events/devices/input_device.h"
-#include "ui/events/devices/input_device_manager.h"
namespace chromeos {
namespace settings {
@@ -37,14 +35,12 @@ 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();
// Make sure that we start out without any keyboards reported.
- input_device_client_test_api_.SetKeyboardDevices({});
+ device_data_manager_test_api_.SetKeyboardDevices({});
}
protected:
@@ -164,8 +160,7 @@ class KeyboardHandlerTest : public testing::Test {
return has_assistant_key;
}
- std::unique_ptr<ui::InputDeviceManager> input_device_manager_;
- ws::InputDeviceClientTestApi input_device_client_test_api_;
+ ui::DeviceDataManagerTestApi device_data_manager_test_api_;
content::TestWebUI web_ui_;
TestKeyboardHandler handler_;
KeyboardHandler::TestAPI handler_test_api_;
@@ -200,7 +195,7 @@ TEST_F(KeyboardHandlerTest, ExternalKeyboard) {
// An internal keyboard shouldn't change the defaults.
base::CommandLine::ForCurrentProcess()->AppendSwitch(
chromeos::switches::kHasChromeOSKeyboard);
- input_device_client_test_api_.SetKeyboardDevices(std::vector<ui::InputDevice>{
+ device_data_manager_test_api_.SetKeyboardDevices(std::vector<ui::InputDevice>{
{1, ui::INPUT_DEVICE_INTERNAL, "internal keyboard"}});
handler_test_api_.Initialize();
EXPECT_TRUE(HasInternalSearchKey());
@@ -211,7 +206,7 @@ TEST_F(KeyboardHandlerTest, ExternalKeyboard) {
// Simulate an external keyboard being connected. We should assume there's a
// Caps Lock and Meta keys now.
- input_device_client_test_api_.SetKeyboardDevices(std::vector<ui::InputDevice>{
+ device_data_manager_test_api_.SetKeyboardDevices(std::vector<ui::InputDevice>{
{1, ui::INPUT_DEVICE_INTERNAL, "internal keyboard"},
{2, ui::INPUT_DEVICE_USB, "external keyboard"}});
EXPECT_TRUE(HasInternalSearchKey());
@@ -222,7 +217,7 @@ TEST_F(KeyboardHandlerTest, ExternalKeyboard) {
// Simulate an external Apple keyboard being connected. Now users can remap
// the command key.
- input_device_client_test_api_.SetKeyboardDevices(std::vector<ui::InputDevice>{
+ device_data_manager_test_api_.SetKeyboardDevices(std::vector<ui::InputDevice>{
{1, ui::INPUT_DEVICE_INTERNAL, "internal keyboard"},
{3, ui::INPUT_DEVICE_USB, "Apple Inc. Apple Keyboard"}});
EXPECT_TRUE(HasInternalSearchKey());
@@ -233,7 +228,7 @@ TEST_F(KeyboardHandlerTest, ExternalKeyboard) {
// Simulate two external keyboards (Apple and non-Apple) are connected at the
// same time.
- input_device_client_test_api_.SetKeyboardDevices(std::vector<ui::InputDevice>{
+ device_data_manager_test_api_.SetKeyboardDevices(std::vector<ui::InputDevice>{
{2, ui::INPUT_DEVICE_USB, "external keyboard"},
{3, ui::INPUT_DEVICE_USB, "Apple Inc. Apple Keyboard"}});
EXPECT_FALSE(HasInternalSearchKey());
@@ -246,7 +241,7 @@ TEST_F(KeyboardHandlerTest, ExternalKeyboard) {
// device names. Those should also be detected as external keyboards, and
// should show the capslock and external meta remapping.
// https://crbug.com/834594.
- input_device_client_test_api_.SetKeyboardDevices(std::vector<ui::InputDevice>{
+ device_data_manager_test_api_.SetKeyboardDevices(std::vector<ui::InputDevice>{
{4, ui::INPUT_DEVICE_USB, "Topre Corporation Realforce 87"}});
EXPECT_FALSE(HasInternalSearchKey());
EXPECT_TRUE(HasCapsLock());
@@ -255,7 +250,7 @@ TEST_F(KeyboardHandlerTest, ExternalKeyboard) {
EXPECT_FALSE(HasAssistantKey());
// Disconnect the external keyboard and check that the key goes away.
- input_device_client_test_api_.SetKeyboardDevices({});
+ device_data_manager_test_api_.SetKeyboardDevices({});
EXPECT_FALSE(HasInternalSearchKey());
EXPECT_FALSE(HasCapsLock());
EXPECT_FALSE(HasExternalMetaKey());
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.cc
index e2891671dcb..202fcf856f8 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.cc
@@ -14,7 +14,7 @@
#include "chrome/browser/chromeos/arc/arc_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
-#include "ui/events/devices/input_device_manager.h"
+#include "ui/events/devices/device_data_manager.h"
namespace chromeos {
namespace settings {
@@ -63,7 +63,7 @@ void StylusHandler::RegisterMessages() {
void StylusHandler::OnJavascriptAllowed() {
note_observer_.Add(NoteTakingHelper::Get());
- input_observer_.Add(ui::InputDeviceManager::GetInstance());
+ input_observer_.Add(ui::DeviceDataManager::GetInstance());
}
void StylusHandler::OnJavascriptDisallowed() {
@@ -146,12 +146,12 @@ void StylusHandler::HandleSetPreferredNoteTakingAppEnabledOnLockScreen(
void StylusHandler::HandleInitialize(const base::ListValue* args) {
AllowJavascript();
- if (ui::InputDeviceManager::GetInstance()->AreDeviceListsComplete())
+ if (ui::DeviceDataManager::GetInstance()->AreDeviceListsComplete())
SendHasStylus();
}
void StylusHandler::SendHasStylus() {
- DCHECK(ui::InputDeviceManager::GetInstance()->AreDeviceListsComplete());
+ DCHECK(ui::DeviceDataManager::GetInstance()->AreDeviceListsComplete());
FireWebUIListener("has-stylus-changed",
base::Value(ash::stylus_utils::HasStylusInput()));
}
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.h
index 676d9393c88..a1be49b471f 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_stylus_handler.h
@@ -19,7 +19,7 @@ class ListValue;
}
namespace ui {
-class InputDeviceManager;
+class DeviceDataManager;
}
namespace chromeos {
@@ -64,7 +64,7 @@ class StylusHandler : public ::settings::SettingsPageUIHandler,
// Observer registration.
ScopedObserver<NoteTakingHelper, NoteTakingHelper::Observer> note_observer_;
- ScopedObserver<ui::InputDeviceManager, ui::InputDeviceEventObserver>
+ ScopedObserver<ui::DeviceDataManager, ui::InputDeviceEventObserver>
input_observer_;
DISALLOW_COPY_AND_ASSIGN(StylusHandler);
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc
index 3a383f4c89c..8af7cb25dac 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fingerprint_handler.cc
@@ -21,7 +21,7 @@
#include "chrome/grit/generated_resources.h"
#include "components/prefs/pref_service.h"
#include "components/session_manager/core/session_manager.h"
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "ui/base/l10n/l10n_util.h"
@@ -62,9 +62,8 @@ FingerprintHandler::FingerprintHandler(Profile* profile)
binding_(this),
session_observer_(this),
weak_ptr_factory_(this) {
- service_manager::Connector* connector =
- content::ServiceManagerConnection::GetForProcess()->GetConnector();
- connector->BindInterface(device::mojom::kServiceName, &fp_service_);
+ content::GetSystemConnector()->BindInterface(device::mojom::kServiceName,
+ &fp_service_);
user_id_ = ProfileHelper::Get()->GetUserIdHashFromProfile(profile);
}
@@ -248,7 +247,7 @@ void FingerprintHandler::HandleStartEnroll(const base::ListValue* args) {
std::string fingerprint_name = l10n_util::GetStringFUTF8(
IDS_SETTINGS_PEOPLE_LOCK_SCREEN_NEW_FINGERPRINT_DEFAULT_NAME,
base::NumberToString16(i));
- if (!base::ContainsValue(fingerprints_labels_, fingerprint_name)) {
+ if (!base::Contains(fingerprints_labels_, fingerprint_name)) {
fp_service_->StartEnrollSession(user_id_, fingerprint_name);
break;
}
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc
index cbbc7f0faef..25814f623e6 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc
@@ -6,14 +6,14 @@
#include <utility>
+#include "ash/public/cpp/assistant/assistant_settings.h"
#include "ash/public/cpp/assistant/assistant_setup.h"
-#include "ash/public/interfaces/assistant_controller.mojom.h"
-#include "ash/public/interfaces/constants.mojom.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.h"
+#include "chromeos/audio/cras_audio_handler.h"
#include "chromeos/constants/chromeos_switches.h"
#include "chromeos/services/assistant/public/mojom/constants.mojom.h"
#include "components/arc/arc_prefs.h"
@@ -26,13 +26,34 @@ namespace chromeos {
namespace settings {
GoogleAssistantHandler::GoogleAssistantHandler(Profile* profile)
- : profile_(profile), weak_factory_(this) {}
+ : profile_(profile), weak_factory_(this) {
+ chromeos::CrasAudioHandler::Get()->AddAudioObserver(this);
+}
+
+GoogleAssistantHandler::~GoogleAssistantHandler() {
+ chromeos::CrasAudioHandler::Get()->RemoveAudioObserver(this);
+}
-GoogleAssistantHandler::~GoogleAssistantHandler() {}
+void GoogleAssistantHandler::OnJavascriptAllowed() {
+ if (pending_hotword_update_) {
+ OnAudioNodesChanged();
+ }
+}
-void GoogleAssistantHandler::OnJavascriptAllowed() {}
void GoogleAssistantHandler::OnJavascriptDisallowed() {}
+void GoogleAssistantHandler::OnAudioNodesChanged() {
+ if (!IsJavascriptAllowed()) {
+ pending_hotword_update_ = true;
+ return;
+ }
+
+ pending_hotword_update_ = false;
+ FireWebUIListener(
+ "hotwordDeviceUpdated",
+ base::Value(chromeos::CrasAudioHandler::Get()->HasHotwordDevice()));
+}
+
void GoogleAssistantHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(
"showGoogleAssistantSettings",
@@ -47,19 +68,17 @@ void GoogleAssistantHandler::RegisterMessages() {
"syncVoiceModelStatus",
base::BindRepeating(&GoogleAssistantHandler::HandleSyncVoiceModelStatus,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "initializeGoogleAssistantPage",
+ base::BindRepeating(&GoogleAssistantHandler::HandleInitialized,
+ base::Unretained(this)));
}
void GoogleAssistantHandler::HandleShowGoogleAssistantSettings(
const base::ListValue* args) {
CHECK_EQ(0U, args->GetSize());
- if (chromeos::switches::IsAssistantEnabled()) {
- // Opens Google Assistant settings.
- service_manager::Connector* connector =
- content::BrowserContext::GetConnectorFor(profile_);
- ash::mojom::AssistantControllerPtr assistant_controller;
- connector->BindInterface(ash::mojom::kServiceName, &assistant_controller);
- assistant_controller->OpenAssistantSettings();
- }
+ if (chromeos::switches::IsAssistantEnabled())
+ ash::OpenAssistantSettings();
}
void GoogleAssistantHandler::HandleRetrainVoiceModel(
@@ -78,6 +97,11 @@ void GoogleAssistantHandler::HandleSyncVoiceModelStatus(
settings_manager_->SyncSpeakerIdEnrollmentStatus();
}
+void GoogleAssistantHandler::HandleInitialized(const base::ListValue* args) {
+ CHECK_EQ(0U, args->GetSize());
+ AllowJavascript();
+}
+
void GoogleAssistantHandler::BindAssistantSettingsManager() {
DCHECK(!settings_manager_.is_bound());
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h
index 87d09bc8304..8891f4e53d7 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.h
@@ -6,7 +6,9 @@
#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_GOOGLE_ASSISTANT_HANDLER_H_
#include "base/macros.h"
+#include "base/optional.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
+#include "chromeos/audio/cras_audio_handler.h"
#include "chromeos/services/assistant/public/mojom/settings.mojom.h"
#include "mojo/public/cpp/bindings/binding.h"
@@ -15,7 +17,8 @@ class Profile;
namespace chromeos {
namespace settings {
-class GoogleAssistantHandler : public ::settings::SettingsPageUIHandler {
+class GoogleAssistantHandler : public ::settings::SettingsPageUIHandler,
+ chromeos::CrasAudioHandler::AudioObserver {
public:
explicit GoogleAssistantHandler(Profile* profile);
~GoogleAssistantHandler() override;
@@ -24,6 +27,9 @@ class GoogleAssistantHandler : public ::settings::SettingsPageUIHandler {
void OnJavascriptAllowed() override;
void OnJavascriptDisallowed() override;
+ // chromeos::CrasAudioHandler::AudioObserver overrides
+ void OnAudioNodesChanged() override;
+
private:
// WebUI call to launch into the Google Assistant app settings.
void HandleShowGoogleAssistantSettings(const base::ListValue* args);
@@ -31,6 +37,8 @@ class GoogleAssistantHandler : public ::settings::SettingsPageUIHandler {
void HandleRetrainVoiceModel(const base::ListValue* args);
// WebUI call to sync Assistant voice model status.
void HandleSyncVoiceModelStatus(const base::ListValue* args);
+ // WebUI call to signal js side is ready.
+ void HandleInitialized(const base::ListValue* args);
// Bind to assistant settings manager.
void BindAssistantSettingsManager();
@@ -39,6 +47,8 @@ class GoogleAssistantHandler : public ::settings::SettingsPageUIHandler {
assistant::mojom::AssistantSettingsManagerPtr settings_manager_;
+ bool pending_hotword_update_ = false;
+
base::WeakPtrFactory<GoogleAssistantHandler> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(GoogleAssistantHandler);
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc
index 16074ee814d..fdf98ee2cf5 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc
@@ -7,10 +7,12 @@
#include <utility>
#include "base/bind.h"
+#include "base/strings/string16.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/chromeos/kerberos/kerberos_credentials_manager.h"
#include "third_party/skia/include/core/SkBitmap.h"
+#include "ui/base/l10n/time_format.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/chromeos/resources/grit/ui_chromeos_resources.h"
@@ -19,16 +21,6 @@
namespace chromeos {
namespace settings {
-namespace {
-
-KerberosCredentialsManager::ResultCallback EmptyResultCallback() {
- return base::BindOnce([](kerberos::ErrorType error) {
- // Do nothing.
- });
-}
-
-} // namespace
-
KerberosAccountsHandler::KerberosAccountsHandler()
: credentials_manager_observer_(this), weak_factory_(this) {}
@@ -47,44 +39,76 @@ void KerberosAccountsHandler::RegisterMessages() {
"removeKerberosAccount",
base::BindRepeating(&KerberosAccountsHandler::HandleRemoveKerberosAccount,
weak_factory_.GetWeakPtr()));
+ web_ui()->RegisterMessageCallback(
+ "validateKerberosConfig",
+ base::BindRepeating(
+ &KerberosAccountsHandler::HandleValidateKerberosConfig,
+ weak_factory_.GetWeakPtr()));
+ web_ui()->RegisterMessageCallback(
+ "setAsActiveKerberosAccount",
+ base::BindRepeating(
+ &KerberosAccountsHandler::HandleSetAsActiveKerberosAccount,
+ weak_factory_.GetWeakPtr()));
}
void KerberosAccountsHandler::HandleGetKerberosAccounts(
const base::ListValue* args) {
AllowJavascript();
- CHECK(!args->GetList().empty());
- base::Value callback_id = args->GetList()[0].Clone();
+ CHECK_EQ(1U, args->GetSize());
+ const std::string& callback_id = args->GetList()[0].GetString();
+
+ if (!KerberosCredentialsManager::Get().IsKerberosEnabled()) {
+ ResolveJavascriptCallback(base::Value(callback_id), base::Value());
+ return;
+ }
KerberosCredentialsManager::Get().ListAccounts(
base::BindOnce(&KerberosAccountsHandler::OnListAccounts,
- weak_factory_.GetWeakPtr(), std::move(callback_id)));
+ weak_factory_.GetWeakPtr(), callback_id));
}
void KerberosAccountsHandler::OnListAccounts(
- base::Value callback_id,
+ const std::string& callback_id,
const kerberos::ListAccountsResponse& response) {
base::ListValue accounts;
- // Default icon is a briefcase.
- gfx::ImageSkia skia_default_icon =
+ // Ticket icon is a key.
+ gfx::ImageSkia skia_ticket_icon =
*ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
- IDR_LOGIN_DEFAULT_USER_2);
- std::string default_icon = webui::GetBitmapDataUrl(
- skia_default_icon.GetRepresentation(1.0f).GetBitmap());
+ IDR_KERBEROS_ICON_KEY);
+ std::string ticket_icon = webui::GetBitmapDataUrl(
+ skia_ticket_icon.GetRepresentation(1.0f).GetBitmap());
+
+ const std::string& active_principal =
+ KerberosCredentialsManager::Get().GetActiveAccount();
for (int n = 0; n < response.accounts_size(); ++n) {
const kerberos::Account& account = response.accounts(n);
+ // Format validity time as 'xx hours yy minutes' for validity < 1 day and
+ // 'nn days' otherwise.
+ base::TimeDelta tgt_validity =
+ base::TimeDelta::FromSeconds(account.tgt_validity_seconds());
+ const base::string16 valid_for_duration = ui::TimeFormat::Detailed(
+ ui::TimeFormat::FORMAT_DURATION, ui::TimeFormat::LENGTH_LONG,
+ tgt_validity < base::TimeDelta::FromDays(1) ? -1 : 0, tgt_validity);
+
base::DictionaryValue account_dict;
account_dict.SetString("principalName", account.principal_name());
- account_dict.SetString("krb5conf", account.krb5conf());
+ account_dict.SetString("config", account.krb5conf());
account_dict.SetBoolean("isSignedIn", account.tgt_validity_seconds() > 0);
- account_dict.SetString("pic", default_icon);
+ account_dict.SetString("validForDuration", valid_for_duration);
+ account_dict.SetBoolean("isActive",
+ account.principal_name() == active_principal);
+ account_dict.SetBoolean("isManaged", account.is_managed());
+ account_dict.SetBoolean("passwordWasRemembered",
+ account.password_was_remembered());
+ account_dict.SetString("pic", ticket_icon);
accounts.GetList().push_back(std::move(account_dict));
}
- ResolveJavascriptCallback(callback_id, accounts);
+ ResolveJavascriptCallback(base::Value(callback_id), std::move(accounts));
}
void KerberosAccountsHandler::HandleAddKerberosAccount(
@@ -95,19 +119,23 @@ void KerberosAccountsHandler::HandleAddKerberosAccount(
// - Prevent account changes when Kerberos is disabled.
// - Remove all accounts when Kerberos is disabled.
- CHECK_EQ(3U, args->GetSize());
-
- std::string callback_id;
- CHECK(args->GetString(0, &callback_id));
-
- std::string principal_name;
- CHECK(args->GetString(1, &principal_name));
-
- std::string password;
- CHECK(args->GetString(2, &password));
+ CHECK_EQ(6U, args->GetSize());
+ const std::string& callback_id = args->GetList()[0].GetString();
+ const std::string& principal_name = args->GetList()[1].GetString();
+ const std::string& password = args->GetList()[2].GetString();
+ const bool remember_password = args->GetList()[3].GetBool();
+ const std::string& config = args->GetList()[4].GetString();
+ const bool allow_existing = args->GetList()[5].GetBool();
+
+ if (!KerberosCredentialsManager::Get().IsKerberosEnabled()) {
+ ResolveJavascriptCallback(base::Value(callback_id),
+ base::Value(kerberos::ERROR_KERBEROS_DISABLED));
+ return;
+ }
KerberosCredentialsManager::Get().AddAccountAndAuthenticate(
- std::move(principal_name), password,
+ principal_name, false /* is_managed */, password, remember_password,
+ config, allow_existing,
base::BindOnce(&KerberosAccountsHandler::OnAddAccountAndAuthenticate,
weak_factory_.GetWeakPtr(), callback_id));
}
@@ -123,15 +151,70 @@ void KerberosAccountsHandler::HandleRemoveKerberosAccount(
const base::ListValue* args) {
AllowJavascript();
- CHECK(!args->GetList().empty());
+ CHECK_EQ(2U, args->GetSize());
+ const std::string& callback_id = args->GetList()[0].GetString();
+ const std::string& principal_name = args->GetList()[1].GetString();
+
+ if (!KerberosCredentialsManager::Get().IsKerberosEnabled()) {
+ ResolveJavascriptCallback(base::Value(callback_id),
+ base::Value(kerberos::ERROR_KERBEROS_DISABLED));
+ return;
+ }
+
+ KerberosCredentialsManager::Get().RemoveAccount(
+ principal_name, base::BindOnce(&KerberosAccountsHandler::OnRemoveAccount,
+ weak_factory_.GetWeakPtr(), callback_id));
+}
+
+void KerberosAccountsHandler::OnRemoveAccount(const std::string& callback_id,
+ kerberos::ErrorType error) {
+ ResolveJavascriptCallback(base::Value(callback_id),
+ base::Value(static_cast<int>(error)));
+}
+
+void KerberosAccountsHandler::HandleValidateKerberosConfig(
+ const base::ListValue* args) {
+ AllowJavascript();
+
+ CHECK_EQ(2U, args->GetSize());
+ const std::string& callback_id = args->GetList()[0].GetString();
+ const std::string& krb5conf = args->GetList()[1].GetString();
+
+ if (!KerberosCredentialsManager::Get().IsKerberosEnabled()) {
+ ResolveJavascriptCallback(base::Value(callback_id),
+ base::Value(kerberos::ERROR_KERBEROS_DISABLED));
+ return;
+ }
+
+ KerberosCredentialsManager::Get().ValidateConfig(
+ krb5conf, base::BindOnce(&KerberosAccountsHandler::OnValidateConfig,
+ weak_factory_.GetWeakPtr(), callback_id));
+}
+
+void KerberosAccountsHandler::OnValidateConfig(
+ const std::string& callback_id,
+ const kerberos::ValidateConfigResponse& response) {
+ base::Value error_info(base::Value::Type::DICTIONARY);
+ error_info.SetKey("code", base::Value(response.error_info().code()));
+ if (response.error_info().has_line_index()) {
+ error_info.SetKey("lineIndex",
+ base::Value(response.error_info().line_index()));
+ }
+
+ base::Value value(base::Value::Type::DICTIONARY);
+ value.SetKey("error", base::Value(static_cast<int>(response.error())));
+ value.SetKey("errorInfo", std::move(error_info));
+ ResolveJavascriptCallback(base::Value(callback_id), std::move(value));
+}
+
+void KerberosAccountsHandler::HandleSetAsActiveKerberosAccount(
+ const base::ListValue* args) {
+ AllowJavascript();
+
+ CHECK_EQ(1U, args->GetSize());
const std::string& principal_name = args->GetList()[0].GetString();
- // Note that we're observing the credentials manager, so OnAccountsChanged()
- // is called when an account is removed, which calls RefreshUI(). Thus, it's
- // fine to pass an EmptyResultCallback() in here and not something that calls
- // RefreshUI().
- KerberosCredentialsManager::Get().RemoveAccount(principal_name,
- EmptyResultCallback());
+ KerberosCredentialsManager::Get().SetActiveAccount(principal_name);
}
void KerberosAccountsHandler::OnJavascriptAllowed() {
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h
index c15457fadb8..78493fb26a9 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h
@@ -14,7 +14,7 @@
#include "chrome/browser/chromeos/kerberos/kerberos_credentials_manager.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "chromeos/dbus/kerberos/kerberos_service.pb.h"
-#include "services/identity/public/cpp/identity_manager.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
namespace kerberos {
class ListAccountsResponse;
@@ -51,8 +51,22 @@ class KerberosAccountsHandler : public ::settings::SettingsPageUIHandler,
// WebUI "removeKerberosAccount" message callback.
void HandleRemoveKerberosAccount(const base::ListValue* args);
+ // Callback for the credential manager's RemoveAccount method.
+ void OnRemoveAccount(const std::string& callback_id,
+ kerberos::ErrorType error);
+
+ // WebUI "validateKerberosConfig" message callback.
+ void HandleValidateKerberosConfig(const base::ListValue* args);
+
+ // Callback for the credential manager's ValidateConfig method.
+ void OnValidateConfig(const std::string& callback_id,
+ const kerberos::ValidateConfigResponse& response);
+
+ // WebUI "setAsActiveKerberosAccount" message callback.
+ void HandleSetAsActiveKerberosAccount(const base::ListValue* args);
+
// Callback for the credential manager's ListAccounts method.
- void OnListAccounts(base::Value callback_id,
+ void OnListAccounts(const std::string& callback_id,
const kerberos::ListAccountsResponse& response);
// Fires the "kerberos-accounts-changed" event, which refreshes the Kerberos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc
index 7f801e17315..d01be34282e 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc
@@ -12,18 +12,16 @@
#include <vector>
#include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h"
-#include "base/metrics/histogram_macros.h"
#include "build/build_config.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
#include "chrome/browser/ui/webui/managed_ui_handler.h"
#include "chrome/browser/ui/webui/metrics_handler.h"
+#include "chrome/browser/ui/webui/plural_string_handler.h"
#include "chrome/browser/ui/webui/settings/about_handler.h"
#include "chrome/browser/ui/webui/settings/accessibility_main_handler.h"
#include "chrome/browser/ui/webui/settings/appearance_handler.h"
#include "chrome/browser/ui/webui/settings/browser_lifetime_handler.h"
#include "chrome/browser/ui/webui/settings/downloads_handler.h"
#include "chrome/browser/ui/webui/settings/extension_control_handler.h"
-#include "chrome/browser/ui/webui/settings/font_handler.h"
#include "chrome/browser/ui/webui/settings/languages_handler.h"
#include "chrome/browser/ui/webui/settings/people_handler.h"
#include "chrome/browser/ui/webui/settings/profile_info_handler.h"
@@ -31,38 +29,37 @@
#include "chrome/browser/ui/webui/settings/reset_settings_handler.h"
#include "chrome/browser/ui/webui/settings/search_engines_handler.h"
#include "chrome/browser/ui/webui/settings/settings_cookies_view_handler.h"
-#include "chrome/browser/ui/webui/settings/settings_import_data_handler.h"
#include "chrome/browser/ui/webui/settings/settings_localized_strings_provider.h"
#include "chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.h"
#include "chrome/browser/ui/webui/settings/settings_ui.h"
#include "chrome/browser/web_applications/system_web_app_manager.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/browser_resources.h"
+#include "chrome/grit/generated_resources.h"
#include "chrome/grit/os_settings_resources.h"
#include "chrome/grit/os_settings_resources_map.h"
+#include "chromeos/services/network_config/public/mojom/constants.mojom.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "components/unified_consent/feature.h"
-#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_ui_data_source.h"
-
-#if defined(FULL_SAFE_BROWSING)
-#include "chrome/browser/safe_browsing/chrome_password_protection_service.h"
-#include "chrome/browser/ui/webui/settings/change_password_handler.h"
-#endif
+#include "services/service_manager/public/cpp/connector.h"
namespace chromeos {
namespace settings {
OSSettingsUI::OSSettingsUI(content::WebUI* web_ui)
- : content::WebUIController(web_ui),
- WebContentsObserver(web_ui->GetWebContents()) {
+ : ui::MojoWebUIController(web_ui, /*enable_chrome_send =*/true) {
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource* html_source =
content::WebUIDataSource::Create(chrome::kChromeUIOSSettingsHost);
::settings::SettingsUI::InitOSWebUIHandlers(profile, web_ui, html_source);
- // TODO(jamescook): Remove after basic_page.html is forked for OS settings.
+ // This handler is for chrome://os-settings.
+ html_source->AddBoolean("isOSSettings", true);
+
+ // Needed for JS code shared between browser and OS settings (for example,
+ // page_visibility.js).
html_source->AddBoolean("showOSSettings", true);
AddSettingsPageUIHandler(
@@ -77,8 +74,6 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui)
std::make_unique<::settings::DownloadsHandler>(profile));
AddSettingsPageUIHandler(
std::make_unique<::settings::ExtensionControlHandler>());
- AddSettingsPageUIHandler(std::make_unique<::settings::FontHandler>(web_ui));
- AddSettingsPageUIHandler(std::make_unique<::settings::ImportDataHandler>());
AddSettingsPageUIHandler(
std::make_unique<::settings::LanguagesHandler>(web_ui));
AddSettingsPageUIHandler(
@@ -92,22 +87,6 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui)
AddSettingsPageUIHandler(
std::make_unique<::settings::SearchEnginesHandler>(profile));
- bool password_protection_available = false;
-#if defined(FULL_SAFE_BROWSING)
- safe_browsing::ChromePasswordProtectionService* password_protection =
- safe_browsing::ChromePasswordProtectionService::
- GetPasswordProtectionService(profile);
- password_protection_available = !!password_protection;
- if (password_protection) {
- AddSettingsPageUIHandler(
- std::make_unique<::settings::ChangePasswordHandler>(
- profile, password_protection));
- }
-#endif
-
- html_source->AddBoolean("passwordProtectionAvailable",
- password_protection_available);
-
html_source->AddBoolean("unifiedConsentEnabled",
unified_consent::IsUnifiedConsentFeatureEnabled());
@@ -124,6 +103,7 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui)
if (web_app::SystemWebAppManager::IsEnabled()) {
html_source->AddResourcePath("icon-192.png", IDR_SETTINGS_LOGO_192);
html_source->AddResourcePath("pwa.html", IDR_PWA_HTML);
+ html_source->AddResourcePath("manifest.json", IDR_OS_SETTINGS_MANIFEST);
}
#if BUILDFLAG(OPTIMIZE_WEBUI)
@@ -133,7 +113,6 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui)
html_source->AddResourcePath("chromeos/lazy_load.html",
IDR_OS_SETTINGS_LAZY_LOAD_VULCANIZED_HTML);
html_source->SetDefaultResource(IDR_OS_SETTINGS_VULCANIZED_HTML);
- html_source->AddResourcePath("manifest.json", IDR_OS_SETTINGS_MANIFEST);
#else
// Add all settings resources.
for (size_t i = 0; i < kOsSettingsResourcesSize; ++i) {
@@ -145,14 +124,21 @@ OSSettingsUI::OSSettingsUI(content::WebUI* web_ui)
::settings::AddLocalizedStrings(html_source, profile);
- DarkModeHandler::Initialize(web_ui, html_source);
+ auto plural_string_handler = std::make_unique<PluralStringHandler>();
+ plural_string_handler->AddLocalizedString("profileLabel",
+ IDS_OS_SETTINGS_PROFILE_LABEL);
+ web_ui->AddMessageHandler(std::move(plural_string_handler));
+
ManagedUIHandler::Initialize(web_ui, html_source);
content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(),
html_source);
+
+ AddHandlerToRegistry(base::BindRepeating(&OSSettingsUI::BindCrosNetworkConfig,
+ base::Unretained(this)));
}
-OSSettingsUI::~OSSettingsUI() {}
+OSSettingsUI::~OSSettingsUI() = default;
void OSSettingsUI::AddSettingsPageUIHandler(
std::unique_ptr<content::WebUIMessageHandler> handler) {
@@ -160,21 +146,11 @@ void OSSettingsUI::AddSettingsPageUIHandler(
web_ui()->AddMessageHandler(std::move(handler));
}
-void OSSettingsUI::DidStartNavigation(
- content::NavigationHandle* navigation_handle) {
- if (navigation_handle->IsSameDocument())
- return;
-
- load_start_time_ = base::Time::Now();
-}
-
-void OSSettingsUI::DocumentLoadedInFrame(
- content::RenderFrameHost* render_frame_host) {
- // TODO(crbug/950007): Create new load histograms
-}
-
-void OSSettingsUI::DocumentOnLoadCompletedInMainFrame() {
- // TODO(crbug/950007): Create new load histograms
+void OSSettingsUI::BindCrosNetworkConfig(
+ network_config::mojom::CrosNetworkConfigRequest request) {
+ content::BrowserContext::GetConnectorFor(
+ web_ui()->GetWebContents()->GetBrowserContext())
+ ->BindInterface(network_config::mojom::kServiceName, std::move(request));
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h
index 6cc0ee27624..4e600afc38b 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h
@@ -8,9 +8,9 @@
#include <memory>
#include "base/macros.h"
-#include "base/time/time.h"
-#include "content/public/browser/web_contents_observer.h"
+#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h"
#include "content/public/browser/web_ui_controller.h"
+#include "ui/webui/mojo_web_ui_controller.h"
namespace content {
class WebUIMessageHandler;
@@ -19,25 +19,19 @@ class WebUIMessageHandler;
namespace chromeos {
namespace settings {
-// The WebUI handler for chrome://settings.
-class OSSettingsUI : public content::WebUIController,
- public content::WebContentsObserver {
+// The WebUI handler for chrome://os-settings.
+class OSSettingsUI : public ui::MojoWebUIController {
public:
explicit OSSettingsUI(content::WebUI* web_ui);
~OSSettingsUI() override;
- // content::WebContentsObserver:
- void DidStartNavigation(
- content::NavigationHandle* navigation_handle) override;
- void DocumentLoadedInFrame(
- content::RenderFrameHost* render_frame_host) override;
- void DocumentOnLoadCompletedInMainFrame() override;
-
private:
void AddSettingsPageUIHandler(
std::unique_ptr<content::WebUIMessageHandler> handler);
+ void BindCrosNetworkConfig(
+ network_config::mojom::CrosNetworkConfigRequest request);
- base::Time load_start_time_;
+ // TODO(crbug/950007): Create load histograms and embed WebuiLoadTimer.
DISALLOW_COPY_AND_ASSIGN(OSSettingsUI);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc
new file mode 100644
index 00000000000..b76ceac4ab6
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc
@@ -0,0 +1,100 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h"
+
+#include "base/bind.h"
+#include "base/bind_helpers.h"
+#include "base/values.h"
+#include "chrome/browser/apps/app_service/app_service_proxy.h"
+#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
+#include "chrome/browser/chromeos/arc/arc_session_manager.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
+#include "chrome/browser/ui/browser_navigator.h"
+#include "chrome/browser/ui/browser_navigator_params.h"
+#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui.h"
+#include "chrome/services/app_service/public/cpp/app_registry_cache.h"
+#include "chrome/services/app_service/public/cpp/app_update.h"
+#include "chrome/services/app_service/public/mojom/types.mojom.h"
+#include "components/arc/arc_util.h"
+#include "ui/base/page_transition_types.h"
+#include "ui/base/window_open_disposition.h"
+#include "ui/display/types/display_constants.h"
+#include "ui/events/event_constants.h"
+#include "url/gurl.h"
+
+namespace chromeos {
+namespace settings {
+
+const char kFamilyLinkHelperAppPackageName[] =
+ "com.google.android.apps.kids.familylinkhelper";
+
+const char kFamilyLinkChildHelperAppPlayStoreURL[] =
+ "https://play.google.com/store/apps/"
+ "details?id=com.google.android.apps.kids.familylinkhelper";
+
+const char kFamilyLinkSiteURL[] = "https://families.google.com/families";
+
+ParentalControlsHandler::ParentalControlsHandler(Profile* profile)
+ : profile_(profile) {}
+
+ParentalControlsHandler::~ParentalControlsHandler() = default;
+
+void ParentalControlsHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "showAddSupervisionDialog",
+ base::BindRepeating(
+ &ParentalControlsHandler::HandleShowAddSupervisionDialog,
+ base::Unretained(this)));
+
+ web_ui()->RegisterMessageCallback(
+ "launchFamilyLinkSettings",
+ base::BindRepeating(
+ &ParentalControlsHandler::HandleLaunchFamilyLinkSettings,
+ base::Unretained(this)));
+}
+
+void ParentalControlsHandler::OnJavascriptAllowed() {}
+void ParentalControlsHandler::OnJavascriptDisallowed() {}
+
+void ParentalControlsHandler::HandleShowAddSupervisionDialog(
+ const base::ListValue* args) {
+ DCHECK(args->empty());
+ AddSupervisionDialog::Show(
+ web_ui()->GetWebContents()->GetTopLevelNativeWindow());
+}
+
+void ParentalControlsHandler::HandleLaunchFamilyLinkSettings(
+ const base::ListValue* args) {
+ DCHECK(args->empty());
+
+ apps::AppServiceProxy* proxy =
+ apps::AppServiceProxyFactory::GetForProfile(profile_);
+
+ apps::AppRegistryCache& registry = proxy->AppRegistryCache();
+ const std::string app_id =
+ arc::ArcPackageNameToAppId(kFamilyLinkHelperAppPackageName, profile_);
+ if (registry.GetAppType(app_id) != apps::mojom::AppType::kUnknown) {
+ // Launch FLH app since it is available.
+ proxy->Launch(app_id, ui::EventFlags::EF_NONE,
+ apps::mojom::LaunchSource::kFromParentalControls,
+ display::kDefaultDisplayId);
+ } else if (arc::IsArcAvailable() &&
+ arc::ArcSessionManager::Get()->IsAllowed()) {
+ // No FLH app installed, but ARC is enabled so launch Play Store
+ // to FLH app install page.
+ arc::LaunchPlayStoreWithUrl(kFamilyLinkChildHelperAppPlayStoreURL);
+ } else {
+ // As a last resort, launch browser to the family link site.
+ NavigateParams params(profile_, GURL(kFamilyLinkSiteURL),
+ ui::PAGE_TRANSITION_FROM_API);
+ params.disposition = WindowOpenDisposition::NEW_WINDOW;
+ params.window_action = NavigateParams::SHOW_WINDOW;
+ Navigate(&params);
+ }
+}
+
+} // namespace settings
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h
new file mode 100644
index 00000000000..cb498d3db33
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h
@@ -0,0 +1,43 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_PARENTAL_CONTROLS_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_PARENTAL_CONTROLS_HANDLER_H_
+
+#include "base/macros.h"
+#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
+
+class Profile;
+
+namespace chromeos {
+namespace settings {
+
+// Chrome "Parental Controls" settings page UI handler.
+class ParentalControlsHandler : public ::settings::SettingsPageUIHandler {
+ public:
+ explicit ParentalControlsHandler(Profile* profile);
+ ~ParentalControlsHandler() override;
+
+ protected:
+ // content::WebUIMessageHandler:
+ void RegisterMessages() override;
+
+ private:
+ // ::settings::SettingsPageUIHandler:
+ void OnJavascriptAllowed() override;
+ void OnJavascriptDisallowed() override;
+
+ // Callbacks for handling chrome.send() events.
+ void HandleShowAddSupervisionDialog(const base::ListValue* args);
+ void HandleLaunchFamilyLinkSettings(const base::ListValue* args);
+
+ Profile* profile_;
+
+ DISALLOW_COPY_AND_ASSIGN(ParentalControlsHandler);
+};
+
+} // namespace settings
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_PARENTAL_CONTROLS_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc
index c45f87966d4..09518e994a3 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc
@@ -10,8 +10,8 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
-#include "chrome/browser/chromeos/crostini/crostini_share_path.h"
#include "chrome/browser/chromeos/file_manager/path_util.h"
+#include "chrome/browser/chromeos/guest_os/guest_os_share_path.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_thread.h"
@@ -55,7 +55,7 @@ void PluginVmHandler::HandleRemovePluginVmSharedPath(
std::string vm_name = args->GetList()[0].GetString();
std::string path = args->GetList()[1].GetString();
- crostini::CrostiniSharePath::GetForProfile(profile_)->UnsharePath(
+ guest_os::GuestOsSharePath::GetForProfile(profile_)->UnsharePath(
vm_name, base::FilePath(path),
/*unpersist=*/true,
base::BindOnce(
diff --git a/chromium/chrome/browser/ui/webui/settings/font_handler.cc b/chromium/chrome/browser/ui/webui/settings/font_handler.cc
index 7053f743452..2c25ebed0da 100644
--- a/chromium/chrome/browser/ui/webui/settings/font_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/font_handler.cc
@@ -39,9 +39,7 @@ const char kAdvancedFontSettingsExtensionId[] =
namespace settings {
FontHandler::FontHandler(content::WebUI* webui)
- : extension_registry_observer_(this),
- profile_(Profile::FromWebUI(webui)),
- weak_ptr_factory_(this) {
+ : extension_registry_observer_(this), profile_(Profile::FromWebUI(webui)) {
#if defined(OS_MACOSX)
// Perform validation for saved fonts.
settings_utils::ValidateSavedFonts(profile_->GetPrefs());
diff --git a/chromium/chrome/browser/ui/webui/settings/font_handler.h b/chromium/chrome/browser/ui/webui/settings/font_handler.h
index d7c58c2285f..f88659d654a 100644
--- a/chromium/chrome/browser/ui/webui/settings/font_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/font_handler.h
@@ -75,7 +75,7 @@ class FontHandler : public SettingsPageUIHandler,
Profile* profile_; // Weak pointer.
- base::WeakPtrFactory<FontHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<FontHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(FontHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.cc b/chromium/chrome/browser/ui/webui/settings/people_handler.cc
index 69625bc5e88..3ea106d0157 100644
--- a/chromium/chrome/browser/ui/webui/settings/people_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/people_handler.cc
@@ -35,11 +35,13 @@
#include "chrome/grit/generated_resources.h"
#include "components/autofill/core/common/autofill_prefs.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/account_consistency_method.h"
#include "components/signin/core/browser/signin_error_controller.h"
#include "components/signin/core/browser/signin_header_helper.h"
-#include "components/signin/core/browser/signin_metrics.h"
-#include "components/signin/core/browser/signin_pref_names.h"
+#include "components/signin/public/base/signin_metrics.h"
+#include "components/signin/public/base/signin_pref_names.h"
+#include "components/signin/public/identity_manager/accounts_mutator.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "components/signin/public/identity_manager/primary_account_mutator.h"
#include "components/strings/grit/components_strings.h"
#include "components/sync/base/passphrase_enums.h"
#include "components/sync/base/user_selectable_type.h"
@@ -52,9 +54,6 @@
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "google_apis/gaia/gaia_auth_util.h"
-#include "services/identity/public/cpp/accounts_mutator.h"
-#include "services/identity/public/cpp/identity_manager.h"
-#include "services/identity/public/cpp/primary_account_mutator.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
@@ -91,6 +90,14 @@ struct SyncConfigInfo {
bool set_new_passphrase;
};
+bool IsSyncSubpage(const GURL& current_url) {
+ return (current_url == chrome::GetSettingsUrl(chrome::kSyncSetupSubPage)
+#if defined(OS_CHROMEOS)
+ || current_url == chrome::GetOSSettingsUrl(chrome::kSyncSetupSubPage)
+#endif // defined(OS_CHROMEOS)
+ );
+}
+
SyncConfigInfo::SyncConfigInfo()
: encrypt_all(false),
sync_everything(false),
@@ -336,7 +343,7 @@ void PeopleHandler::OnJavascriptAllowed() {
prefs::kSigninAllowed,
base::Bind(&PeopleHandler::UpdateSyncStatus, base::Unretained(this)));
- identity::IdentityManager* identity_manager(
+ signin::IdentityManager* identity_manager(
IdentityManagerFactory::GetInstance()->GetForProfile(profile_));
if (identity_manager)
identity_manager_observer_.Add(identity_manager);
@@ -381,12 +388,12 @@ void PeopleHandler::DisplayGaiaLoginInNewTabOrWindow(
// then sign in again.
identity_manager->GetPrimaryAccountMutator()->ClearPrimaryAccount(
- identity::PrimaryAccountMutator::ClearAccountsAction::kDefault,
+ signin::PrimaryAccountMutator::ClearAccountsAction::kDefault,
signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS,
signin_metrics::SignoutDelete::IGNORE_METRIC);
}
- // If the signin manager already has an authenticated username, this is a
+ // If the identity manager already has a primary account, this is a
// re-auth scenario, and we need to ensure that the user signs in with the
// same email address.
if (identity_manager->HasPrimaryAccount()) {
@@ -805,7 +812,7 @@ void PeopleHandler::HandleSignout(const base::ListValue* args) {
: signin_metrics::SignoutDelete::KEEPING;
identity_manager->GetPrimaryAccountMutator()->ClearPrimaryAccount(
- identity::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll,
+ signin::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll,
signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric);
} else {
DCHECK(!delete_profile)
@@ -882,7 +889,7 @@ void PeopleHandler::CloseSyncSetup() {
IdentityManagerFactory::GetForProfile(profile_)
->GetPrimaryAccountMutator()
->ClearPrimaryAccount(
- identity::PrimaryAccountMutator::ClearAccountsAction::
+ signin::PrimaryAccountMutator::ClearAccountsAction::
kDefault,
signin_metrics::ABORT_SIGNIN,
signin_metrics::SignoutDelete::IGNORE_METRIC);
@@ -909,13 +916,15 @@ void PeopleHandler::CloseSyncSetup() {
void PeopleHandler::InitializeSyncBlocker() {
DCHECK(web_ui());
WebContents* web_contents = web_ui()->GetWebContents();
- if (web_contents) {
- syncer::SyncService* service = GetSyncService();
- const GURL current_url = web_contents->GetVisibleURL();
- if (service &&
- current_url == chrome::GetSettingsUrl(chrome::kSyncSetupSubPage)) {
- sync_blocker_ = service->GetSetupInProgressHandle();
- }
+ if (!web_contents)
+ return;
+
+ syncer::SyncService* service = GetSyncService();
+ if (!service)
+ return;
+
+ if (IsSyncSubpage(web_contents->GetVisibleURL())) {
+ sync_blocker_ = service->GetSetupInProgressHandle();
}
}
@@ -971,7 +980,7 @@ std::unique_ptr<base::DictionaryValue> PeopleHandler::GetSyncStatusDictionary()
std::unique_ptr<base::DictionaryValue> sync_status(new base::DictionaryValue);
if (profile_->IsGuestSession()) {
// Cannot display signin status when running in guest mode on chromeos
- // because there is no SigninManager.
+ // because there is no IdentityManager.
sync_status->SetBoolean("signinAllowed", false);
return sync_status;
}
diff --git a/chromium/chrome/browser/ui/webui/settings/people_handler.h b/chromium/chrome/browser/ui/webui/settings/people_handler.h
index 010e9ed345f..83cd8916760 100644
--- a/chromium/chrome/browser/ui/webui/settings/people_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/people_handler.h
@@ -20,10 +20,10 @@
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "chrome/browser/ui/webui/signin/login_ui_service.h"
#include "components/prefs/pref_change_registrar.h"
-#include "components/signin/core/browser/signin_buildflags.h"
+#include "components/signin/public/base/signin_buildflags.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/sync/driver/sync_service_observer.h"
#include "content/public/browser/web_contents_observer.h"
-#include "services/identity/public/cpp/identity_manager.h"
class LoginUIService;
@@ -43,7 +43,7 @@ class SyncSetupInProgressHandle;
namespace settings {
class PeopleHandler : public SettingsPageUIHandler,
- public identity::IdentityManager::Observer,
+ public signin::IdentityManager::Observer,
public SyncStartupTracker::Observer,
public LoginUIService::LoginUI,
public syncer::SyncServiceObserver,
@@ -261,7 +261,7 @@ class PeopleHandler : public SettingsPageUIHandler,
PrefChangeRegistrar profile_pref_registrar_;
// Manages observer lifetimes.
- ScopedObserver<identity::IdentityManager, PeopleHandler>
+ ScopedObserver<signin::IdentityManager, PeopleHandler>
identity_manager_observer_;
ScopedObserver<syncer::SyncService, 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 7090d96872d..87b349ecacc 100644
--- a/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/people_handler_unittest.cc
@@ -35,6 +35,9 @@
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "components/prefs/pref_service.h"
+#include "components/signin/public/identity_manager/accounts_mutator.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/sync/base/passphrase_enums.h"
#include "components/sync/driver/mock_sync_service.h"
#include "components/sync/driver/sync_user_settings_impl.h"
@@ -47,9 +50,6 @@
#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 "services/identity/public/cpp/accounts_mutator.h"
-#include "services/identity/public/cpp/identity_manager.h"
-#include "services/identity/public/cpp/identity_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
@@ -66,7 +66,7 @@ MATCHER_P(UserSelectableTypeSetMatches, value, "") {
return arg == value;
}
-const char kTestUser[] = "chrome.p13n.test@gmail.com";
+const char kTestUser[] = "chrome_p13n_test@gmail.com";
const char kTestCallbackId[] = "test-callback-id";
// Returns a UserSelectableTypeSet with all types set.
@@ -363,7 +363,7 @@ class PeopleHandlerTest : public ChromeRenderViewHostTestHarness {
return std::string(kTestUser);
}
- identity::IdentityTestEnvironment* identity_test_env() {
+ signin::IdentityTestEnvironment* identity_test_env() {
return identity_test_env_adaptor_->identity_test_env();
}
@@ -1049,7 +1049,7 @@ TEST_F(PeopleHandlerTest_UnifiedConsentDisabled, ShowSigninOnAuthError) {
primary_account_info.is_under_advanced_protection,
signin_metrics::SourceForRefreshTokenOperation::kUnknown);
- identity::UpdatePersistentErrorOfRefreshTokenForAccount(
+ signin::UpdatePersistentErrorOfRefreshTokenForAccount(
identity_manager, primary_account_info.account_id,
GoogleServiceAuthError(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));
@@ -1392,6 +1392,8 @@ class PeopleHandlerDiceUnifiedConsentTest
: public ::testing::TestWithParam<std::tuple<bool, bool>> {};
TEST_P(PeopleHandlerDiceUnifiedConsentTest, StoredAccountsList) {
+ ScopedTestingLocalState local_state(TestingBrowserProcess::GetGlobal());
+
// Do not be in first run, so that the profiles are not created as "new
// profiles" and automatically migrated to Dice.
first_run::ResetCachedSentinelDataForTesting();
diff --git a/chromium/chrome/browser/ui/webui/settings/printing_handler.cc b/chromium/chrome/browser/ui/webui/settings/printing_handler.cc
index 8647b2daf9e..deaa3ab5352 100644
--- a/chromium/chrome/browser/ui/webui/settings/printing_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/printing_handler.cc
@@ -7,6 +7,7 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "chrome/browser/printing/printer_manager_dialog.h"
+#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/web_ui.h"
namespace settings {
@@ -27,7 +28,8 @@ void PrintingHandler::OnJavascriptAllowed() {}
void PrintingHandler::OnJavascriptDisallowed() {}
void PrintingHandler::HandleOpenSystemPrintDialog(const base::ListValue* args) {
- printing::PrinterManagerDialog::ShowPrinterManagerDialog();
+ printing::PrinterManagerDialog::ShowPrinterManagerDialog(
+ Profile::FromWebUI(web_ui()));
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/profile_info_handler.cc b/chromium/chrome/browser/ui/webui/settings/profile_info_handler.cc
index 0d63bac8567..f99ba773f67 100644
--- a/chromium/chrome/browser/ui/webui/settings/profile_info_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/profile_info_handler.cc
@@ -40,8 +40,7 @@ ProfileInfoHandler::ProfileInfoHandler(Profile* profile)
#if defined(OS_CHROMEOS)
user_manager_observer_(this),
#endif
- profile_observer_(this),
- callback_weak_ptr_factory_(this) {
+ profile_observer_(this) {
#if defined(OS_CHROMEOS)
// Set up the chrome://userimage/ source.
content::URLDataSource::Add(profile,
diff --git a/chromium/chrome/browser/ui/webui/settings/profile_info_handler.h b/chromium/chrome/browser/ui/webui/settings/profile_info_handler.h
index 0d7d986709c..1c40211b89a 100644
--- a/chromium/chrome/browser/ui/webui/settings/profile_info_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/profile_info_handler.h
@@ -82,7 +82,7 @@ class ProfileInfoHandler : public SettingsPageUIHandler,
profile_observer_;
// Used to cancel callbacks when JavaScript becomes disallowed.
- base::WeakPtrFactory<ProfileInfoHandler> callback_weak_ptr_factory_;
+ base::WeakPtrFactory<ProfileInfoHandler> callback_weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ProfileInfoHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc b/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc
index b5adcb26fb4..2c4329668b1 100644
--- a/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.cc
@@ -13,7 +13,6 @@
#include "base/macros.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
-#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/url_constants.h"
@@ -23,20 +22,37 @@
namespace settings {
-ProtocolHandlersHandler::ProtocolHandlersHandler() {
-}
+namespace {
-ProtocolHandlersHandler::~ProtocolHandlersHandler() {
+void GetHandlersAsListValue(
+ const ProtocolHandlerRegistry& registry,
+ const ProtocolHandlerRegistry::ProtocolHandlerList& handlers,
+ base::ListValue* handler_list) {
+ ProtocolHandlerRegistry::ProtocolHandlerList::const_iterator handler;
+ for (handler = handlers.begin(); handler != handlers.end(); ++handler) {
+ std::unique_ptr<base::DictionaryValue> handler_value(
+ new base::DictionaryValue());
+ handler_value->SetString("protocol_display_name",
+ handler->GetProtocolDisplayName());
+ handler_value->SetString("protocol", handler->protocol());
+ handler_value->SetString("spec", handler->url().spec());
+ handler_value->SetString("host", handler->url().host());
+ handler_value->SetBoolean("is_default", registry.IsDefault(*handler));
+ handler_list->Append(std::move(handler_value));
+ }
}
+} // namespace
+
+ProtocolHandlersHandler::ProtocolHandlersHandler() = default;
+ProtocolHandlersHandler::~ProtocolHandlersHandler() = default;
+
void ProtocolHandlersHandler::OnJavascriptAllowed() {
- notification_registrar_.Add(
- this, chrome::NOTIFICATION_PROTOCOL_HANDLER_REGISTRY_CHANGED,
- content::Source<Profile>(Profile::FromWebUI(web_ui())));
+ registry_observer_.Add(GetProtocolHandlerRegistry());
}
void ProtocolHandlersHandler::OnJavascriptDisallowed() {
- notification_registrar_.RemoveAll();
+ registry_observer_.RemoveAll();
}
void ProtocolHandlersHandler::RegisterMessages() {
@@ -64,27 +80,9 @@ void ProtocolHandlersHandler::RegisterMessages() {
base::Unretained(this)));
}
-ProtocolHandlerRegistry* ProtocolHandlersHandler::GetProtocolHandlerRegistry() {
- return ProtocolHandlerRegistryFactory::GetForBrowserContext(
- Profile::FromWebUI(web_ui()));
-}
-
-static void GetHandlersAsListValue(
- const ProtocolHandlerRegistry& registry,
- const ProtocolHandlerRegistry::ProtocolHandlerList& handlers,
- base::ListValue* handler_list) {
- ProtocolHandlerRegistry::ProtocolHandlerList::const_iterator handler;
- for (handler = handlers.begin(); handler != handlers.end(); ++handler) {
- std::unique_ptr<base::DictionaryValue> handler_value(
- new base::DictionaryValue());
- handler_value->SetString("protocol_display_name",
- handler->GetProtocolDisplayName());
- handler_value->SetString("protocol", handler->protocol());
- handler_value->SetString("spec", handler->url().spec());
- handler_value->SetString("host", handler->url().host());
- handler_value->SetBoolean("is_default", registry.IsDefault(*handler));
- handler_list->Append(std::move(handler_value));
- }
+void ProtocolHandlersHandler::OnProtocolHandlerRegistryChanged() {
+ SendHandlersEnabledValue();
+ UpdateHandlerList();
}
void ProtocolHandlersHandler::GetHandlersForProtocol(
@@ -183,13 +181,9 @@ ProtocolHandler ProtocolHandlersHandler::ParseHandlerFromArgs(
GURL(base::UTF16ToUTF8(url)));
}
-void ProtocolHandlersHandler::Observe(
- int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) {
- DCHECK_EQ(chrome::NOTIFICATION_PROTOCOL_HANDLER_REGISTRY_CHANGED, type);
- SendHandlersEnabledValue();
- UpdateHandlerList();
+ProtocolHandlerRegistry* ProtocolHandlersHandler::GetProtocolHandlerRegistry() {
+ return ProtocolHandlerRegistryFactory::GetForBrowserContext(
+ Profile::FromWebUI(web_ui()));
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.h b/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.h
index cf5094ad895..0b5b5767e7c 100644
--- a/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/protocol_handlers_handler.h
@@ -8,11 +8,10 @@
#include <string>
#include "base/macros.h"
+#include "base/scoped_observer.h"
#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "chrome/common/custom_handlers/protocol_handler.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
////////////////////////////////////////////////////////////////////////////////
// ProtocolHandlersHandler
@@ -28,7 +27,7 @@ class DictionaryValue;
namespace settings {
class ProtocolHandlersHandler : public SettingsPageUIHandler,
- public content::NotificationObserver {
+ public ProtocolHandlerRegistry::Observer {
public:
ProtocolHandlersHandler();
~ProtocolHandlersHandler() override;
@@ -38,10 +37,8 @@ class ProtocolHandlersHandler : public SettingsPageUIHandler,
void OnJavascriptDisallowed() override;
void RegisterMessages() override;
- // content::NotificationObserver:
- void Observe(int type,
- const content::NotificationSource& source,
- const content::NotificationDetails& details) override;
+ // ProtocolHandlerRegistry::Observer:
+ void OnProtocolHandlerRegistryChanged() override;
private:
// Called to fetch the state of the protocol handlers. If the full list of
@@ -84,7 +81,8 @@ class ProtocolHandlersHandler : public SettingsPageUIHandler,
ProtocolHandlerRegistry* GetProtocolHandlerRegistry();
- content::NotificationRegistrar notification_registrar_;
+ ScopedObserver<ProtocolHandlerRegistry, ProtocolHandlerRegistry::Observer>
+ registry_observer_{this};
DISALLOW_COPY_AND_ASSIGN(ProtocolHandlersHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc
index 6350f23f7af..a1ef45f40ef 100644
--- a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.cc
@@ -73,7 +73,7 @@ ResetRequestOriginFromString(const std::string& request_origin) {
const char ResetSettingsHandler::kCctResetSettingsHash[] = "cct";
ResetSettingsHandler::ResetSettingsHandler(Profile* profile)
- : profile_(profile), callback_weak_ptr_factory_(this) {
+ : profile_(profile) {
google_brand::GetBrand(&brandcode_);
}
@@ -268,7 +268,6 @@ void ResetSettingsHandler::ResetProfile(
callback_weak_ptr_factory_.GetWeakPtr(), callback_id,
send_settings, request_origin));
base::RecordAction(base::UserMetricsAction("ResetProfile"));
- UMA_HISTOGRAM_BOOLEAN("ProfileReset.SendFeedback", send_settings);
UMA_HISTOGRAM_ENUMERATION(
"ProfileReset.ResetRequestOrigin", request_origin,
reset_report::ChromeResetReport::ResetRequestOrigin_MAX + 1);
diff --git a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.h b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.h
index 1a9458c43b3..db6f082298e 100644
--- a/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/reset_settings_handler.h
@@ -111,7 +111,7 @@ class ResetSettingsHandler : public SettingsPageUIHandler {
std::string brandcode_;
// Used to cancel callbacks when JavaScript becomes disallowed.
- base::WeakPtrFactory<ResetSettingsHandler> callback_weak_ptr_factory_;
+ base::WeakPtrFactory<ResetSettingsHandler> callback_weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ResetSettingsHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc b/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc
index be2b79caa67..24247be5a14 100644
--- a/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/search_engines_handler.cc
@@ -46,7 +46,7 @@ const int kNewSearchEngineIndex = -1;
namespace settings {
SearchEnginesHandler::SearchEnginesHandler(Profile* profile)
- : profile_(profile), list_controller_(profile), weak_ptr_factory_(this) {
+ : profile_(profile), list_controller_(profile) {
pref_change_registrar_.Init(profile_->GetPrefs());
}
diff --git a/chromium/chrome/browser/ui/webui/settings/search_engines_handler.h b/chromium/chrome/browser/ui/webui/settings/search_engines_handler.h
index b764a280ba4..5452f1ee59e 100644
--- a/chromium/chrome/browser/ui/webui/settings/search_engines_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/search_engines_handler.h
@@ -101,7 +101,7 @@ class SearchEnginesHandler : public SettingsPageUIHandler,
KeywordEditorController list_controller_;
std::unique_ptr<EditSearchEngineController> edit_controller_;
PrefChangeRegistrar pref_change_registrar_;
- base::WeakPtrFactory<SearchEnginesHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<SearchEnginesHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SearchEnginesHandler);
};
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 c108af6d6a1..ed1e4d58c0b 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
@@ -31,14 +31,14 @@
#include "components/feature_engagement/buildflags.h"
#include "components/prefs/pref_member.h"
#include "components/prefs/pref_service.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/browsing_data_filter_builder.h"
#include "content/public/browser/storage_partition.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/text/bytes_formatting.h"
-#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP)
+#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP)
#include "chrome/browser/feature_engagement/incognito_window/incognito_window_tracker.h"
#include "chrome/browser/feature_engagement/incognito_window/incognito_window_tracker_factory.h"
#endif
@@ -76,8 +76,7 @@ ClearBrowsingDataHandler::ClearBrowsingDataHandler(content::WebUI* webui)
: profile_(Profile::FromWebUI(webui)),
sync_service_(ProfileSyncServiceFactory::GetForProfile(profile_)),
sync_service_observer_(this),
- show_history_deletion_dialog_(false),
- weak_ptr_factory_(this) {}
+ show_history_deletion_dialog_(false) {}
ClearBrowsingDataHandler::~ClearBrowsingDataHandler() {
}
@@ -278,7 +277,7 @@ void ClearBrowsingDataHandler::HandleClearBrowsingData(
content::BrowsingDataFilterBuilder::BLACKLIST),
remover, std::move(callback));
-#if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP)
+#if BUILDFLAG(ENABLE_LEGACY_DESKTOP_IN_PRODUCT_HELP)
feature_engagement::IncognitoWindowTrackerFactory::GetInstance()
->GetForProfile(profile_)
->OnBrowsingDataCleared();
@@ -340,7 +339,7 @@ void ClearBrowsingDataHandler::OnStateChanged(syncer::SyncService* sync) {
}
void ClearBrowsingDataHandler::UpdateSyncState() {
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile_);
FireWebUIListener(
"update-sync-state",
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h
index 76d27cb783f..9434c788871 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h
@@ -108,7 +108,7 @@ class ClearBrowsingDataHandler : public SettingsPageUIHandler,
// A weak pointer factory for asynchronous calls referencing this class.
// The weak pointers are invalidated in |OnJavascriptDisallowed()| and
// |HandleInitialize()| to cancel previously initiated tasks.
- base::WeakPtrFactory<ClearBrowsingDataHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<ClearBrowsingDataHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ClearBrowsingDataHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc
index 47dd46f0888..d9c05922474 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.cc
@@ -171,8 +171,8 @@ void CookiesViewHandler::RegisterMessages() {
void CookiesViewHandler::TreeNodesAdded(ui::TreeModel* model,
ui::TreeModelNode* parent,
- int start,
- int count) {
+ size_t start,
+ size_t count) {
// Skip if there is a batch update in progress.
if (batch_update_)
return;
@@ -192,15 +192,15 @@ void CookiesViewHandler::TreeNodesAdded(ui::TreeModel* model,
args.Set(kId, std::make_unique<base::Value>());
else
args.SetString(kId, model_util_->GetTreeNodeId(parent_node));
- args.SetInteger(kStart, start);
+ args.SetInteger(kStart, int{start});
args.Set(kChildren, std::move(children));
FireWebUIListener("on-tree-item-added", args);
}
void CookiesViewHandler::TreeNodesRemoved(ui::TreeModel* model,
ui::TreeModelNode* parent,
- int start,
- int count) {
+ size_t start,
+ size_t count) {
// Skip if there is a batch update in progress.
if (batch_update_)
return;
@@ -212,8 +212,8 @@ void CookiesViewHandler::TreeNodesRemoved(ui::TreeModel* model,
args.Set(kId, std::make_unique<base::Value>());
else
args.SetString(kId, model_util_->GetTreeNodeId(tree_model->AsNode(parent)));
- args.SetInteger(kStart, start);
- args.SetInteger(kCount, count);
+ args.SetInteger(kStart, int{start});
+ args.SetInteger(kCount, int{count});
FireWebUIListener("on-tree-item-removed", args);
}
@@ -340,9 +340,8 @@ void CookiesViewHandler::HandleRemoveShownItems(const base::ListValue* args) {
AllowJavascript();
CookieTreeNode* parent = cookies_tree_model_->GetRoot();
- while (parent->child_count()) {
- cookies_tree_model_->DeleteCookieNode(parent->GetChild(0));
- }
+ while (!parent->children().empty())
+ cookies_tree_model_->DeleteCookieNode(parent->children().front().get());
}
void CookiesViewHandler::HandleRemoveItem(const base::ListValue* args) {
@@ -353,32 +352,29 @@ void CookiesViewHandler::HandleRemoveItem(const base::ListValue* args) {
AllowJavascript();
CookieTreeNode* parent = cookies_tree_model_->GetRoot();
- int parent_child_count = parent->child_count();
- for (int i = 0; i < parent_child_count; ++i) {
- CookieTreeNode* node = parent->GetChild(i);
- if (node->GetTitle() == site) {
- cookies_tree_model_->DeleteCookieNode(node);
- sorted_sites_.clear();
- return;
- }
+ const auto i = std::find_if(
+ parent->children().cbegin(), parent->children().cend(),
+ [&site](const auto& node) { return node->GetTitle() == site; });
+ if (i != parent->children().cend()) {
+ cookies_tree_model_->DeleteCookieNode(i->get());
+ sorted_sites_.clear();
}
}
void CookiesViewHandler::SendLocalDataList(const CookieTreeNode* parent) {
CHECK(cookies_tree_model_.get());
CHECK(request_.should_send_list);
- const int parent_child_count = parent->child_count();
+ const size_t parent_child_count = parent->children().size();
if (sorted_sites_.empty()) {
// Sort the list by site.
sorted_sites_.reserve(parent_child_count); // Optimization, hint size.
- for (int i = 0; i < parent_child_count; ++i) {
- const base::string16& title = parent->GetChild(i)->GetTitle();
+ for (size_t i = 0; i < parent_child_count; ++i) {
+ const base::string16& title = parent->children()[i]->GetTitle();
sorted_sites_.push_back(LabelAndIndex(title, i));
}
std::sort(sorted_sites_.begin(), sorted_sites_.end());
}
- const int list_item_count = sorted_sites_.size();
// The layers in the CookieTree are:
// root - Top level.
// site - www.google.com, example.com, etc.
@@ -386,27 +382,25 @@ void CookiesViewHandler::SendLocalDataList(const CookieTreeNode* parent) {
// item - Info on the actual thing.
// Gather list of sites with some highlights of the categories and items.
std::unique_ptr<base::ListValue> site_list(new base::ListValue);
- for (int i = 0; i < list_item_count; ++i) {
- const CookieTreeNode* site = parent->GetChild(sorted_sites_[i].second);
+ for (const auto& sorted_site : sorted_sites_) {
+ const CookieTreeNode* site = parent->children()[sorted_site.second].get();
base::string16 description;
- for (int k = 0; k < site->child_count(); ++k) {
- if (!description.empty()) {
+ for (const auto& category : site->children()) {
+ if (!description.empty())
description += base::ASCIIToUTF16(", ");
- }
- const CookieTreeNode* category = site->GetChild(k);
const auto node_type = category->GetDetailedInfo().node_type;
- int item_count = category->child_count();
+ size_t item_count = category->children().size();
switch (node_type) {
case CookieTreeNode::DetailedInfo::TYPE_QUOTA:
// TODO(crbug.com/642955): Omit quota values until bug is addressed.
continue;
case CookieTreeNode::DetailedInfo::TYPE_COOKIE:
- DCHECK_EQ(0, item_count);
+ DCHECK_EQ(0u, item_count);
item_count = 1;
FALLTHROUGH;
case CookieTreeNode::DetailedInfo::TYPE_COOKIES:
description += l10n_util::GetPluralStringFUTF16(
- IDS_SETTINGS_SITE_SETTINGS_NUM_COOKIES, item_count);
+ IDS_SETTINGS_SITE_SETTINGS_NUM_COOKIES, int{item_count});
break;
default:
int ids_value = GetCategoryLabelID(node_type);
@@ -428,7 +422,8 @@ void CookiesViewHandler::SendLocalDataList(const CookieTreeNode* parent) {
base::DictionaryValue response;
response.Set(kItems, std::move(site_list));
- response.Set(kTotal, std::make_unique<base::Value>(list_item_count));
+ response.Set(kTotal,
+ std::make_unique<base::Value>(int{sorted_sites_.size()}));
ResolveJavascriptCallback(base::Value(request_.callback_id_), response);
request_.Clear();
@@ -439,8 +434,8 @@ void CookiesViewHandler::SendChildren(const CookieTreeNode* parent) {
// Passing false for |include_quota_nodes| since they don't reflect reality
// until bug http://crbug.com/642955 is fixed and local/session storage is
// counted against the total.
- model_util_->GetChildNodeList(parent, /*start=*/0, parent->child_count(),
- /*include_quota_nodes=*/false, children.get());
+ model_util_->GetChildNodeList(parent, /*start=*/0, parent->children().size(),
+ /*include_quota_nodes=*/false, children.get());
base::DictionaryValue args;
if (parent == cookies_tree_model_->GetRoot())
@@ -458,9 +453,7 @@ void CookiesViewHandler::SendCookieDetails(const CookieTreeNode* parent) {
// Passing false for |include_quota_nodes| since they don't reflect reality
// until bug http://crbug.com/642955 is fixed and local/session storage is
// counted against the total.
- model_util_->GetChildNodeDetails(parent, /*start=*/0, parent->child_count(),
- /*include_quota_nodes=*/false,
- children.get());
+ model_util_->GetChildNodeDetails(parent, false, children.get());
base::DictionaryValue args;
if (parent == cookies_tree_model_->GetRoot())
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h
index d8debac00fa..574978c9b97 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/settings_cookies_view_handler.h
@@ -34,12 +34,12 @@ class CookiesViewHandler : public SettingsPageUIHandler,
// CookiesTreeModel::Observer:
void TreeNodesAdded(ui::TreeModel* model,
ui::TreeModelNode* parent,
- int start,
- int count) override;
+ size_t start,
+ size_t count) override;
void TreeNodesRemoved(ui::TreeModel* model,
ui::TreeModelNode* parent,
- int start,
- int count) override;
+ size_t start,
+ size_t count) override;
void TreeNodeChanged(ui::TreeModel* model, ui::TreeModelNode* node) override {
}
void TreeModelBeginBatch(CookiesTreeModel* model) override;
@@ -106,7 +106,7 @@ class CookiesViewHandler : public SettingsPageUIHandler,
Request request_;
// Sorted index list, by site. Indexes refer to |model->GetRoot()| children.
- typedef std::pair<base::string16, int> LabelAndIndex;
+ typedef std::pair<base::string16, size_t> LabelAndIndex;
std::vector<LabelAndIndex> sorted_sites_;
std::unique_ptr<CookiesTreeModelUtil> model_util_;
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.cc
index f46e5ef15f1..ef43d9631ac 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.cc
@@ -30,7 +30,7 @@ bool DefaultBrowserIsDisabledByPolicy() {
} // namespace
-DefaultBrowserHandler::DefaultBrowserHandler() : weak_ptr_factory_(this) {}
+DefaultBrowserHandler::DefaultBrowserHandler() {}
DefaultBrowserHandler::~DefaultBrowserHandler() {}
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.h
index fe71f6526bf..92f83a28a9c 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/settings_default_browser_handler.h
@@ -61,7 +61,7 @@ class DefaultBrowserHandler : public SettingsPageUIHandler {
PrefChangeRegistrar local_state_pref_registrar_;
// Used to invalidate the DefaultBrowserWorker callback.
- base::WeakPtrFactory<DefaultBrowserHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<DefaultBrowserHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DefaultBrowserHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
index fcb5f807835..9dc2fca39cb 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
+++ b/chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
@@ -12,6 +12,7 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
+#include "base/win/windows_version.h"
#include "build/build_config.h"
#include "build/buildflag.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
@@ -44,7 +45,7 @@
#include "components/password_manager/core/browser/manage_passwords_referrer.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "components/safe_browsing/common/safe_browsing_prefs.h"
-#include "components/signin/core/browser/signin_buildflags.h"
+#include "components/signin/public/base/signin_buildflags.h"
#include "components/strings/grit/components_strings.h"
#include "components/subresource_filter/core/browser/subresource_filter_features.h"
#include "components/sync/driver/sync_service.h"
@@ -56,6 +57,7 @@
#include "content/public/common/content_switches.h"
#include "device/fido/features.h"
#include "media/base/media_switches.h"
+#include "net/base/url_util.h"
#include "services/device/public/cpp/device_features.h"
#include "ui/accessibility/accessibility_switches.h"
#include "ui/base/l10n/l10n_util.h"
@@ -68,6 +70,8 @@
#include "chrome/browser/chromeos/arc/arc_util.h"
#include "chrome/browser/chromeos/assistant/assistant_util.h"
#include "chrome/browser/chromeos/crostini/crostini_util.h"
+#include "chrome/browser/chromeos/kerberos/kerberos_credentials_manager.h"
+#include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_utils.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"
@@ -136,6 +140,7 @@ void AddCommonStrings(content::WebUIDataSource* html_source, Profile* profile) {
{"clear", IDS_SETTINGS_CLEAR},
{"close", IDS_CLOSE},
{"confirm", IDS_CONFIRM},
+ {"continue", IDS_SETTINGS_CONTINUE},
{"controlledByExtension", IDS_SETTINGS_CONTROLLED_BY_EXTENSION},
#if defined(OS_CHROMEOS)
{"deviceOff", IDS_SETTINGS_DEVICE_OFF},
@@ -189,6 +194,32 @@ void AddA11yStrings(content::WebUIDataSource* html_source) {
{"moreFeaturesLink", IDS_SETTINGS_MORE_FEATURES_LINK},
{"moreFeaturesLinkDescription",
IDS_SETTINGS_MORE_FEATURES_LINK_DESCRIPTION},
+ {"captionsTitle", IDS_SETTINGS_CAPTIONS},
+ {"captionsTextSize", IDS_SETTINGS_CAPTIONS_TEXT_SIZE},
+ {"captionsTextFont", IDS_SETTINGS_CAPTIONS_TEXT_FONT},
+ {"captionsTextColor", IDS_SETTINGS_CAPTIONS_TEXT_COLOR},
+ {"captionsTextOpacity", IDS_SETTINGS_CAPTIONS_TEXT_OPACITY},
+ {"captionsBackgroundOpacity", IDS_SETTINGS_CAPTIONS_BACKGROUND_OPACITY},
+ {"captionsOpacityMin", IDS_SETTINGS_CAPTIONS_OPACITY_MIN},
+ {"captionsOpacityMax", IDS_SETTINGS_CAPTIONS_OPACITY_MAX},
+ {"captionsTextShadow", IDS_SETTINGS_CAPTIONS_TEXT_SHADOW},
+ {"captionsTextShadowNone", IDS_SETTINGS_CAPTIONS_TEXT_SHADOW_NONE},
+ {"captionsTextShadowRaised", IDS_SETTINGS_CAPTIONS_TEXT_SHADOW_RAISED},
+ {"captionsTextShadowDepressed",
+ IDS_SETTINGS_CAPTIONS_TEXT_SHADOW_DEPRESSED},
+ {"captionsTextShadowUniform", IDS_SETTINGS_CAPTIONS_TEXT_SHADOW_UNIFORM},
+ {"captionsTextShadowDropShadow",
+ IDS_SETTINGS_CAPTIONS_TEXT_SHADOW_DROP_SHADOW},
+ {"captionsBackgroundColor", IDS_SETTINGS_CAPTIONS_BACKGROUND_COLOR},
+ {"captionsColorBlack", IDS_SETTINGS_CAPTIONS_COLOR_BLACK},
+ {"captionsColorWhite", IDS_SETTINGS_CAPTIONS_COLOR_WHITE},
+ {"captionsColorRed", IDS_SETTINGS_CAPTIONS_COLOR_RED},
+ {"captionsColorGreen", IDS_SETTINGS_CAPTIONS_COLOR_GREEN},
+ {"captionsColorBlue", IDS_SETTINGS_CAPTIONS_COLOR_BLUE},
+ {"captionsColorYellow", IDS_SETTINGS_CAPTIONS_COLOR_YELLOW},
+ {"captionsColorCyan", IDS_SETTINGS_CAPTIONS_COLOR_CYAN},
+ {"captionsColorMagenta", IDS_SETTINGS_CAPTIONS_COLOR_MAGENTA},
+ {"captionsDefaultSetting", IDS_SETTINGS_CAPTIONS_DEFAULT_SETTING},
#if defined(OS_CHROMEOS)
{"optionsInMenuLabel", IDS_SETTINGS_OPTIONS_IN_MENU_LABEL},
{"largeMouseCursorLabel", IDS_SETTINGS_LARGE_MOUSE_CURSOR_LABEL},
@@ -263,6 +294,20 @@ void AddA11yStrings(content::WebUIDataSource* html_source) {
{"switchAccessLabel", IDS_SETTINGS_ACCESSIBILITY_SWITCH_ACCESS_DESCRIPTION},
{"switchAccessOptionsLabel",
IDS_SETTINGS_ACCESSIBILITY_SWITCH_ACCESS_OPTIONS_LABEL},
+ {"manageSwitchAccessSettings", IDS_SETTINGS_MANAGE_SWITCH_ACCESS_SETTINGS},
+ {"switchAssignmentHeading", IDS_SETTINGS_SWITCH_ASSIGNMENT_HEADING},
+ {"switchAssignOptionNone", IDS_SETTINGS_SWITCH_ASSIGN_OPTION_NONE},
+ {"switchAssignOptionSpace", IDS_SETTINGS_SWITCH_ASSIGN_OPTION_SPACE},
+ {"switchAssignOptionEnter", IDS_SETTINGS_SWITCH_ASSIGN_OPTION_ENTER},
+ {"assignSelectSwitchLabel", IDS_SETTINGS_ASSIGN_SELECT_SWITCH_LABEL},
+ {"assignNextSwitchLabel", IDS_SETTINGS_ASSIGN_NEXT_SWITCH_LABEL},
+ {"assignPreviousSwitchLabel", IDS_SETTINGS_ASSIGN_PREVIOUS_SWITCH_LABEL},
+ {"switchAccessAutoScanHeading",
+ IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_HEADING},
+ {"switchAccessAutoScanLabel", IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_LABEL},
+ {"switchAccessAutoScanSpeedLabel",
+ IDS_SETTINGS_SWITCH_ACCESS_AUTO_SCAN_SPEED_LABEL},
+ {"durationInSeconds", IDS_SETTINGS_DURATION_IN_SECONDS},
{"manageAccessibilityFeatures",
IDS_SETTINGS_ACCESSIBILITY_MANAGE_ACCESSIBILITY_FEATURES},
{"textToSpeechHeading", IDS_SETTINGS_ACCESSIBILITY_TEXT_TO_SPEECH_HEADING},
@@ -328,6 +373,15 @@ void AddA11yStrings(content::WebUIDataSource* html_source) {
"showExperimentalA11yLabels",
base::FeatureList::IsEnabled(features::kExperimentalAccessibilityLabels));
+ html_source->AddBoolean(
+ "enableCaptionSettings",
+ base::FeatureList::IsEnabled(features::kCaptionSettings));
+
+#if defined(OS_WIN)
+ html_source->AddBoolean("isWindows10OrNewer",
+ base::win::GetVersion() >= base::win::Version::WIN10);
+#endif
+
#if defined(OS_CHROMEOS)
html_source->AddString("accountManagerLearnMoreUrl",
chrome::kAccountManagerLearnMoreURL);
@@ -348,13 +402,6 @@ void AddA11yStrings(content::WebUIDataSource* html_source) {
void AddAboutStrings(content::WebUIDataSource* html_source) {
static constexpr LocalizedString kLocalizedStrings[] = {
{"aboutProductLogoAlt", IDS_SHORT_PRODUCT_LOGO_ALT_TEXT},
- {"aboutPageTitle", IDS_SETTINGS_ABOUT_PROGRAM},
-#if defined(OS_CHROMEOS)
- {"aboutProductTitle", IDS_PRODUCT_OS_NAME},
-#else
- {"aboutProductTitle", IDS_PRODUCT_NAME},
-#endif
- {"aboutGetHelpUsingChrome", IDS_SETTINGS_GET_HELP_USING_CHROME},
#if defined(GOOGLE_CHROME_BUILD)
{"aboutReportAnIssue", IDS_SETTINGS_ABOUT_PAGE_REPORT_AN_ISSUE},
@@ -417,13 +464,39 @@ void AddAboutStrings(content::WebUIDataSource* html_source) {
{"aboutUpdateWarningMessage",
IDS_SETTINGS_ABOUT_PAGE_UPDATE_WARNING_MESSAGE},
{"aboutUpdateWarningTitle", IDS_SETTINGS_ABOUT_PAGE_UPDATE_WARNING_TITLE},
- {"aboutUpdateWarningContinue",
- IDS_SETTINGS_ABOUT_PAGE_UPDATE_WARNING_CONTINUE_BUTTON},
#endif // defined(OS_CHROMEOS)
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings,
base::size(kLocalizedStrings));
+#if defined(OS_CHROMEOS)
+ html_source->AddLocalizedString("aboutOsPageTitle", IDS_SETTINGS_ABOUT_OS);
+ html_source->AddLocalizedString("aboutGetHelpUsingChromeOs",
+ IDS_SETTINGS_GET_HELP_USING_CHROME_OS);
+ html_source->AddLocalizedString("aboutOsProductTitle", IDS_PRODUCT_OS_NAME);
+ html_source->AddLocalizedString("aboutReleaseNotesOffline",
+ IDS_SETTINGS_ABOUT_PAGE_RELEASE_NOTES);
+ html_source->AddLocalizedString("aboutShowReleaseNotes",
+ IDS_SETTINGS_ABOUT_PAGE_SHOW_RELEASE_NOTES);
+ if (base::FeatureList::IsEnabled(chromeos::features::kSplitSettings)) {
+ html_source->AddLocalizedString("aboutGetHelpUsingChrome",
+ IDS_SETTINGS_GET_HELP_USING_CHROME);
+ html_source->AddLocalizedString("aboutPageTitle",
+ IDS_SETTINGS_ABOUT_PROGRAM);
+ html_source->AddLocalizedString("aboutProductTitle", IDS_PRODUCT_NAME);
+ } else {
+ html_source->AddLocalizedString("aboutGetHelpUsingChrome",
+ IDS_SETTINGS_GET_HELP_USING_CHROME_OS);
+ html_source->AddLocalizedString("aboutPageTitle", IDS_SETTINGS_ABOUT_OS);
+ html_source->AddLocalizedString("aboutProductTitle", IDS_PRODUCT_OS_NAME);
+ }
+#else
+ html_source->AddLocalizedString("aboutGetHelpUsingChrome",
+ IDS_SETTINGS_GET_HELP_USING_CHROME);
+ html_source->AddLocalizedString("aboutPageTitle", IDS_SETTINGS_ABOUT_PROGRAM);
+ html_source->AddLocalizedString("aboutProductTitle", IDS_PRODUCT_NAME);
+#endif
+
html_source->AddString(
"aboutUpgradeUpToDate",
#if defined(OS_CHROMEOS)
@@ -459,6 +532,12 @@ void AddCrostiniStrings(content::WebUIDataSource* html_source,
{"crostiniExportLabel", IDS_SETTINGS_CROSTINI_EXPORT_LABEL},
{"crostiniImport", IDS_SETTINGS_CROSTINI_IMPORT},
{"crostiniImportLabel", IDS_SETTINGS_CROSTINI_IMPORT_LABEL},
+ {"crostiniImportConfirmationDialogTitle",
+ IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_TITLE},
+ {"crostiniImportConfirmationDialogMessage",
+ IDS_SETTINGS_CROSTINI_CONFIRM_IMPORT_DIALOG_WINDOW_MESSAGE},
+ {"crostiniImportConfirmationDialogConfirmationButton",
+ IDS_SETTINGS_CROSTINI_IMPORT},
{"crostiniRemoveButton", IDS_SETTINGS_CROSTINI_REMOVE_BUTTON},
{"crostiniSharedUsbDevicesLabel",
IDS_SETTINGS_CROSTINI_SHARED_USB_DEVICES_LABEL},
@@ -498,6 +577,7 @@ void AddPluginVmStrings(content::WebUIDataSource* html_source,
static constexpr LocalizedString kLocalizedStrings[] = {
{"pluginVmPageTitle", IDS_SETTINGS_PLUGIN_VM_PAGE_TITLE},
{"pluginVmPageLabel", IDS_SETTINGS_PLUGIN_VM_PAGE_LABEL},
+ {"pluginVmPageSubtext", IDS_SETTINGS_PLUGIN_VM_PAGE_SUBTEXT},
{"pluginVmPrinterAccess", IDS_SETTINGS_PLUGIN_VM_PRINTER_ACCESS},
{"pluginVmSharedPaths", IDS_SETTINGS_PLUGIN_VM_SHARED_PATHS},
{"pluginVmSharedPathsListHeading",
@@ -511,33 +591,6 @@ void AddPluginVmStrings(content::WebUIDataSource* html_source,
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings,
base::size(kLocalizedStrings));
- html_source->AddString(
- "pluginVmPageSubtext",
- l10n_util::GetStringFUTF16(IDS_SETTINGS_PLUGIN_VM_PAGE_SUBTEXT,
- ui::GetChromeOSDeviceName()));
-}
-
-void AddKioskNextShellStrings(content::WebUIDataSource* html_source) {
- static constexpr LocalizedString kLocalizedStrings[] = {
- {"kioskNextShellPageTitle", IDS_SETTINGS_KIOSK_NEXT_SHELL_TITLE},
- {"kioskNextShellPageLabel", IDS_SETTINGS_KIOSK_NEXT_SHELL_LABEL},
- {"kioskNextShellPageSubtextEnable",
- IDS_SETTINGS_KIOSK_NEXT_SHELL_SUBTEXT_ENABLE},
- {"kioskNextShellPageSubtextDisable",
- IDS_SETTINGS_KIOSK_NEXT_SHELL_SUBTEXT_DISABLE},
- {"kioskNextShellTurnOn", IDS_SETTINGS_TURN_ON},
- {"kioskNextShellTurnOff", IDS_SETTINGS_KIOSK_NEXT_SHELL_TURN_OFF},
- {"kioskNextShellEnabledDialogTitle",
- IDS_SETTINGS_KIOSK_NEXT_SHELL_ENABLED_DIALOG_TITLE},
- {"kioskNextShellDisabledDialogTitle",
- IDS_SETTINGS_KIOSK_NEXT_SHELL_DISABLED_DIALOG_TITLE},
- {"kioskNextShellEnabledDialogBody",
- IDS_SETTINGS_KIOSK_NEXT_SHELL_ENABLED_DIALOG_BODY},
- {"kioskNextShellDisabledDialogBody",
- IDS_SETTINGS_KIOSK_NEXT_SHELL_DISABLED_DIALOG_BODY},
- };
- AddLocalizedStringsBulk(html_source, kLocalizedStrings,
- base::size(kLocalizedStrings));
}
void AddAndroidAppStrings(content::WebUIDataSource* html_source) {
@@ -562,7 +615,7 @@ void AddAndroidAppStrings(content::WebUIDataSource* html_source) {
html_source->AddString(
"androidAppsSubtext",
l10n_util::GetStringFUTF16(
- IDS_SETTINGS_ANDROID_APPS_SUBTEXT,
+ IDS_SETTINGS_ANDROID_APPS_SUBTEXT, ui::GetChromeOSDeviceName(),
GetHelpUrlWithBoard(chrome::kAndroidAppsLearnMoreURL)));
}
@@ -570,6 +623,7 @@ void AddAppsStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
{"appsPageTitle", IDS_SETTINGS_APPS_TITLE},
{"manageYourApps", IDS_SETTINGS_APPS_LINK_TEXT},
+ {"manageYourAppsSublabel", IDS_SETTINGS_APPS_LINK_SUBLABEL_TEXT},
};
AddLocalizedStringsBulk(html_source, localized_strings,
@@ -577,6 +631,26 @@ void AddAppsStrings(content::WebUIDataSource* html_source) {
}
#endif
+#if defined(OS_CHROMEOS)
+void AddParentalControlStrings(content::WebUIDataSource* html_source) {
+ html_source->AddBoolean(
+ "isChild", user_manager::UserManager::Get()->IsLoggedInAsChildUser());
+ static constexpr LocalizedString kLocalizedStrings[] = {
+ {"parentalControlsPageTitle", IDS_SETTINGS_PARENTAL_CONTROLS_PAGE_TITLE},
+ {"parentalControlsPageSetUpLabel",
+ IDS_SETTINGS_PARENTAL_CONTROLS_PAGE_SET_UP_LABEL},
+ {"parentalControlsPageViewSettingsLabel",
+ IDS_SETTINGS_PARENTAL_CONTROLS_PAGE_VIEW_SETTINGS_LABEL},
+ {"parentalControlsPageConnectToInternetLabel",
+ IDS_SETTINGS_PARENTAL_CONTROLS_PAGE_CONNECT_TO_INTERNET_LABEL},
+ {"parentalControlsSetUpButtonLabel",
+ IDS_SETTINGS_PARENTAL_CONTROLS_SET_UP_BUTTON_LABEL},
+ };
+ AddLocalizedStringsBulk(html_source, kLocalizedStrings,
+ base::size(kLocalizedStrings));
+}
+#endif
+
void AddAppearanceStrings(content::WebUIDataSource* html_source,
Profile* profile) {
static constexpr LocalizedString kLocalizedStrings[] = {
@@ -604,6 +678,7 @@ void AddAppearanceStrings(content::WebUIDataSource* html_source,
{"personalizationPageTitle", IDS_OS_SETTINGS_PERSONALIZATION},
{"openWallpaperApp", IDS_OS_SETTINGS_OPEN_WALLPAPER_APP},
{"setWallpaper", IDS_OS_SETTINGS_SET_WALLPAPER},
+ {"osLanguagesPageTitle", IDS_OS_SETTINGS_LANGUAGES_AND_INPUT_PAGE_TITLE},
#endif
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
{"showWindowDecorations", IDS_SHOW_WINDOW_DECORATIONS},
@@ -615,12 +690,24 @@ void AddAppearanceStrings(content::WebUIDataSource* html_source,
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings,
base::size(kLocalizedStrings));
+
+#if defined(OS_CHROMEOS)
+ if (base::FeatureList::IsEnabled(chromeos::features::kSplitSettings)) {
+ html_source->AddLocalizedString("changePictureTitle",
+ IDS_OS_SETTINGS_CHANGE_PICTURE_TITLE);
+ } else {
+ html_source->AddLocalizedString("changePictureTitle",
+ IDS_SETTINGS_CHANGE_PICTURE_DIALOG_TITLE);
+ }
+#endif
}
#if defined(OS_CHROMEOS)
void AddBluetoothStrings(content::WebUIDataSource* html_source) {
static constexpr LocalizedString kLocalizedStrings[] = {
{"bluetoothConnected", IDS_SETTINGS_BLUETOOTH_CONNECTED},
+ {"bluetoothConnectedWithBattery",
+ IDS_SETTINGS_BLUETOOTH_CONNECTED_WITH_BATTERY},
{"bluetoothConnecting", IDS_SETTINGS_BLUETOOTH_CONNECTING},
{"bluetoothDeviceListPaired", IDS_SETTINGS_BLUETOOTH_DEVICE_LIST_PAIRED},
{"bluetoothDeviceListUnpaired",
@@ -962,48 +1049,53 @@ void AddDeviceStrings(content::WebUIDataSource* html_source) {
html_source->AddString("naturalScrollLearnMoreLink",
GetHelpUrlWithBoard(chrome::kNaturalScrollHelpURL));
}
-#endif
-void AddDownloadsStrings(content::WebUIDataSource* html_source) {
+void AddFilesStrings(content::WebUIDataSource* html_source) {
static constexpr LocalizedString kLocalizedStrings[] = {
- {"downloadsPageTitle", IDS_SETTINGS_DOWNLOADS},
- {"downloadLocation", IDS_SETTINGS_DOWNLOAD_LOCATION},
- {"changeDownloadLocation", IDS_SETTINGS_CHANGE_DOWNLOAD_LOCATION},
- {"promptForDownload", IDS_SETTINGS_PROMPT_FOR_DOWNLOAD},
- {"disconnectGoogleDriveAccount", IDS_SETTINGS_DISCONNECT_GOOGLE_DRIVE},
- {"openFileTypesAutomatically", IDS_SETTINGS_OPEN_FILE_TYPES_AUTOMATICALLY},
-#if defined(OS_CHROMEOS)
- {"smbSharesTitle", IDS_SETTINGS_DOWNLOADS_SMB_SHARES},
- {"smbSharesLearnMoreLabel",
- IDS_SETTINGS_DOWNLOADS_SMB_SHARES_LEARN_MORE_LABEL},
- {"addSmbShare", IDS_SETTINGS_DOWNLOADS_SMB_SHARES_ADD_SHARE},
- {"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},
- {"smbShareAddedInvalidSSOURLMessage",
- IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_MOUNT_INVALID_SSO_URL_MESSAGE},
-#endif
+ {"filesPageTitle", IDS_OS_SETTINGS_FILES},
+ {"smbSharesTitle", IDS_SETTINGS_DOWNLOADS_SMB_SHARES},
+ {"smbSharesLearnMoreLabel",
+ IDS_SETTINGS_DOWNLOADS_SMB_SHARES_LEARN_MORE_LABEL},
+ {"addSmbShare", IDS_SETTINGS_DOWNLOADS_SMB_SHARES_ADD_SHARE},
+ {"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},
+ {"smbShareAddedInvalidSSOURLMessage",
+ IDS_SETTINGS_DOWNLOADS_SHARE_ADDED_MOUNT_INVALID_SSO_URL_MESSAGE},
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings,
base::size(kLocalizedStrings));
-#if defined(OS_CHROMEOS)
chromeos::smb_dialog::AddLocalizedStrings(html_source);
html_source->AddString("smbSharesLearnMoreURL",
GetHelpUrlWithBoard(chrome::kSmbSharesLearnMoreURL));
-#endif
+}
+#endif // defined(OS_CHROMEOS)
+
+void AddDownloadsStrings(content::WebUIDataSource* html_source) {
+ static constexpr LocalizedString kLocalizedStrings[] = {
+ {"downloadsPageTitle", IDS_SETTINGS_DOWNLOADS},
+ {"downloadLocation", IDS_SETTINGS_DOWNLOAD_LOCATION},
+ {"changeDownloadLocation", IDS_SETTINGS_CHANGE_DOWNLOAD_LOCATION},
+ {"promptForDownload", IDS_SETTINGS_PROMPT_FOR_DOWNLOAD},
+ {"disconnectGoogleDriveAccount", IDS_SETTINGS_DISCONNECT_GOOGLE_DRIVE},
+ {"openFileTypesAutomatically",
+ IDS_SETTINGS_OPEN_FILE_TYPES_AUTOMATICALLY},
+ };
+ AddLocalizedStringsBulk(html_source, kLocalizedStrings,
+ base::size(kLocalizedStrings));
}
#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
@@ -1251,6 +1343,35 @@ void AddEasyUnlockStrings(content::WebUIDataSource* html_source) {
base::size(kLocalizedStrings));
}
+void AddFingerprintStrings(content::WebUIDataSource* html_source) {
+ int instruction_id, aria_label_id;
+ using FingerprintLocation = chromeos::quick_unlock::FingerprintLocation;
+ switch (chromeos::quick_unlock::GetFingerprintLocation()) {
+ case FingerprintLocation::TABLET_POWER_BUTTON:
+ instruction_id =
+ IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_LOCATE_SCANNER_POWER_BUTTON;
+ aria_label_id =
+ IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_LOCATE_SCANNER_POWER_BUTTON_ARIA_LABEL;
+ break;
+ case FingerprintLocation::KEYBOARD_TOP_RIGHT:
+ instruction_id =
+ IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_LOCATE_SCANNER_KEYBOARD;
+ aria_label_id =
+ IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_LOCATE_SCANNER_KEYBOARD_TOP_RIGHT_ARIA_LABEL;
+ break;
+ case FingerprintLocation::KEYBOARD_BOTTOM_RIGHT:
+ instruction_id =
+ IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_LOCATE_SCANNER_KEYBOARD;
+ aria_label_id =
+ IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_LOCATE_SCANNER_KEYBOARD_BOTTOM_RIGHT_ARIA_LABEL;
+ break;
+ }
+ html_source->AddLocalizedString(
+ "configureFingerprintInstructionLocateScannerStep", instruction_id);
+ html_source->AddLocalizedString("configureFingerprintScannerStepAriaLabel",
+ aria_label_id);
+}
+
void AddInternetStrings(content::WebUIDataSource* html_source) {
static constexpr LocalizedString kLocalizedStrings[] = {
{"internetAddConnection", IDS_SETTINGS_INTERNET_ADD_CONNECTION},
@@ -1294,6 +1415,12 @@ void AddInternetStrings(content::WebUIDataSource* html_source) {
IDS_SETTINGS_INTERNET_KNOWN_NETWORKS_MENU_FORGET},
{"networkAllowDataRoaming",
IDS_SETTINGS_SETTINGS_NETWORK_ALLOW_DATA_ROAMING},
+ {"networkAllowDataRoamingEnabledHome",
+ IDS_SETTINGS_SETTINGS_NETWORK_ALLOW_DATA_ROAMING_ENABLED_HOME},
+ {"networkAllowDataRoamingEnabledRoaming",
+ IDS_SETTINGS_SETTINGS_NETWORK_ALLOW_DATA_ROAMING_ENABLED_ROAMING},
+ {"networkAllowDataRoamingDisabled",
+ IDS_SETTINGS_SETTINGS_NETWORK_ALLOW_DATA_ROAMING_DISABLED},
{"networkAlwaysOnVpn", IDS_SETTINGS_INTERNET_NETWORK_ALWAYS_ON_VPN},
{"networkAutoConnect", IDS_SETTINGS_INTERNET_NETWORK_AUTO_CONNECT},
{"networkAutoConnectCellular",
@@ -1311,6 +1438,7 @@ void AddInternetStrings(content::WebUIDataSource* html_source) {
{"networkPrefer", IDS_SETTINGS_INTERNET_NETWORK_PREFER},
{"networkPrimaryUserControlled",
IDS_SETTINGS_INTERNET_NETWORK_PRIMARY_USER_CONTROLLED},
+ {"networkScanningLabel", IDS_NETWORK_SCANNING_MESSAGE},
{"networkSectionAdvanced",
IDS_SETTINGS_INTERNET_NETWORK_SECTION_ADVANCED},
{"networkSectionAdvancedA11yLabel",
@@ -1381,7 +1509,6 @@ void AddInternetStrings(content::WebUIDataSource* html_source) {
void AddLanguagesStrings(content::WebUIDataSource* html_source) {
static constexpr LocalizedString kLocalizedStrings[] = {
- {"languagesPageTitle", IDS_SETTINGS_LANGUAGES_PAGE_TITLE},
{"languagesListTitle", IDS_SETTINGS_LANGUAGES_LANGUAGES_LIST_TITLE},
{"searchLanguages", IDS_SETTINGS_LANGUAGE_SEARCH},
{"languagesExpandA11yLabel",
@@ -1454,6 +1581,17 @@ void AddLanguagesStrings(content::WebUIDataSource* html_source) {
html_source->AddString(
"languagesLearnMoreURL",
base::ASCIIToUTF16(chrome::kLanguageSettingsLearnMoreUrl));
+ // TODO(hsuregan): Remove once OS Browser split settings is complete.
+ html_source->AddString(
+ "languagesPageTitle",
+ l10n_util::GetStringUTF16(
+ base::FeatureList::IsEnabled(chromeos::features::kSplitSettings)
+ ? IDS_SETTINGS_LANGUAGES_PAGE_TITLE
+ : IDS_OS_SETTINGS_LANGUAGES_AND_INPUT_PAGE_TITLE));
+#else
+ html_source->AddString(
+ "languagesPageTitle",
+ l10n_util::GetStringUTF16(IDS_SETTINGS_LANGUAGES_PAGE_TITLE));
#endif
}
@@ -1625,7 +1763,8 @@ void AddAutofillStrings(content::WebUIDataSource* html_source,
autofill::PersonalDataManagerFactory::GetForProfile(profile),
profile->GetPrefs(),
ProfileSyncServiceFactory::GetForProfile(profile),
- /*is_test_mode=*/false));
+ /*is_test_mode=*/false,
+ /*log_manager=*/nullptr));
AddLocalizedStringsBulk(html_source, kLocalizedStrings,
base::size(kLocalizedStrings));
@@ -1652,15 +1791,17 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) {
IDS_SETTINGS_ACCOUNT_MANAGER_MIGRATION_LABEL},
{"accountManagerReauthenticationLabel",
IDS_SETTINGS_ACCOUNT_MANAGER_REAUTHENTICATION_LABEL},
+ {"accountManagerMigrationTooltip",
+ IDS_SETTINGS_ACCOUNT_MANAGER_MIGRATION_TOOLTIP},
+ {"accountManagerReauthenticationTooltip",
+ IDS_SETTINGS_ACCOUNT_MANAGER_REAUTHENTICATION_TOOLTIP},
+ {"accountManagerMoreActionsTooltip",
+ IDS_SETTINGS_ACCOUNT_MANAGER_MORE_ACTIONS_TOOLTIP},
{"accountManagerManagedLabel",
IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS_MANAGED_ACCOUNT},
{"accountManagerUnmanagedLabel",
IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS_UNMANAGED_ACCOUNT},
{"configureFingerprintTitle", IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_TITLE},
- {"configureFingerprintInstructionLocateScannerStep",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_LOCATE_SCANNER},
- {"configureFingerprintScannerStepAriaLabel",
- IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_LOCATE_SCANNER_ARIA_LABEL},
{"configureFingerprintInstructionReadyStep",
IDS_SETTINGS_ADD_FINGERPRINT_DIALOG_INSTRUCTION_READY},
{"configureFingerprintLiftFinger",
@@ -1675,8 +1816,6 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) {
IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_CHOOSE_PIN_TITLE},
{"configurePinConfirmPinTitle",
IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_CONFIRM_PIN_TITLE},
- {"configurePinContinueButton",
- IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_CONTINUE_BUTTON},
{"configurePinMismatched", IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_MISMATCHED},
{"configurePinTooShort", IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_TOO_SHORT},
{"configurePinTooLong", IDS_SETTINGS_PEOPLE_CONFIGURE_PIN_TOO_LONG},
@@ -1685,25 +1824,46 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) {
{"kerberosAccountsSubMenuLabel",
IDS_SETTINGS_KERBEROS_ACCOUNTS_SUBMENU_LABEL},
{"kerberosAccountsPageTitle", IDS_SETTINGS_KERBEROS_ACCOUNTS_PAGE_TITLE},
- {"kerberosAccountsDescription", IDS_SETTINGS_KERBEROS_ACCOUNTS_DESCRIPTION},
{"kerberosAccountsListHeader", IDS_SETTINGS_KERBEROS_ACCOUNTS_LIST_HEADER},
{"kerberosAccountsAddAccountLabel",
IDS_SETTINGS_KERBEROS_ACCOUNTS_ADD_ACCOUNT_LABEL},
+ {"kerberosAccountsRefreshNowLabel",
+ IDS_SETTINGS_KERBEROS_ACCOUNTS_REFRESH_NOW_LABEL},
+ {"kerberosAccountsSetAsActiveAccountLabel",
+ IDS_SETTINGS_KERBEROS_ACCOUNTS_SET_AS_ACTIVE_ACCOUNT_LABEL},
{"kerberosAccountsRemoveAccountLabel",
IDS_SETTINGS_KERBEROS_ACCOUNTS_REMOVE_ACCOUNT_LABEL},
+ {"kerberosAccountsAccountRemovedTip",
+ IDS_SETTINGS_KERBEROS_ACCOUNTS_ACCOUNT_REMOVED_TIP},
{"kerberosAccountsSignedIn", IDS_SETTINGS_KERBEROS_ACCOUNTS_SIGNED_IN},
{"kerberosAccountsSignedOut", IDS_SETTINGS_KERBEROS_ACCOUNTS_SIGNED_OUT},
{"kerberosAccountsReauthenticationLabel",
IDS_SETTINGS_KERBEROS_ACCOUNTS_REAUTHENTICATION_LABEL},
+ {"kerberosAccountsTicketActive",
+ IDS_SETTINGS_KERBEROS_ACCOUNTS_TICKET_ACTIVE},
{"addKerberosAccount", IDS_SETTINGS_ADD_KERBEROS_ACCOUNT},
+ {"refreshKerberosAccount", IDS_SETTINGS_REFRESH_KERBEROS_ACCOUNT},
+ {"addKerberosAccountDescription",
+ IDS_SETTINGS_ADD_KERBEROS_ACCOUNT_DESCRIPTION},
+ {"addKerberosAccountRememberPassword",
+ IDS_SETTINGS_ADD_KERBEROS_ACCOUNT_REMEMBER_PASSWORD},
+ {"addKerberosAccountRefreshButtonLabel",
+ IDS_SETTINGS_ADD_KERBEROS_ACCOUNT_REFRESH_BUTTON_LABEL},
{"kerberosUsername", IDS_SETTINGS_KERBEROS_USERNAME},
{"kerberosPassword", IDS_SETTINGS_KERBEROS_PASSWORD},
+ {"kerberosAccountsAdvancedConfigLabel",
+ IDS_SETTINGS_KERBEROS_ACCOUNTS_ADVANCED_CONFIG_LABEL},
+ {"kerberosAdvancedConfigTitle",
+ IDS_SETTINGS_KERBEROS_ADVANCED_CONFIG_TITLE},
+ {"kerberosAdvancedConfigDesc", IDS_SETTINGS_KERBEROS_ADVANCED_CONFIG_DESC},
{"kerberosErrorNetworkProblem",
IDS_SETTINGS_KERBEROS_ERROR_NETWORK_PROBLEM},
{"kerberosErrorUsernameInvalid",
IDS_SETTINGS_KERBEROS_ERROR_USERNAME_INVALID},
{"kerberosErrorUsernameUnknown",
IDS_SETTINGS_KERBEROS_ERROR_USERNAME_UNKNOWN},
+ {"kerberosErrorDuplicatePrincipalName",
+ IDS_SETTINGS_KERBEROS_ERROR_DUPLICATE_PRINCIPAL_NAME},
{"kerberosErrorContactingServer",
IDS_SETTINGS_KERBEROS_ERROR_CONTACTING_SERVER},
{"kerberosErrorPasswordInvalid",
@@ -1712,6 +1872,22 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) {
IDS_SETTINGS_KERBEROS_ERROR_PASSWORD_EXPIRED},
{"kerberosErrorKdcEncType", IDS_SETTINGS_KERBEROS_ERROR_KDC_ENC_TYPE},
{"kerberosErrorGeneral", IDS_SETTINGS_KERBEROS_ERROR_GENERAL},
+ {"kerberosConfigErrorSectionNestedInGroup",
+ IDS_SETTINGS_KERBEROS_CONFIG_ERROR_SECTION_NESTED_IN_GROUP},
+ {"kerberosConfigErrorSectionSyntax",
+ IDS_SETTINGS_KERBEROS_CONFIG_ERROR_SECTION_SYNTAX},
+ {"kerberosConfigErrorExpectedOpeningCurlyBrace",
+ IDS_SETTINGS_KERBEROS_CONFIG_ERROR_EXPECTED_OPENING_CURLY_BRACE},
+ {"kerberosConfigErrorExtraCurlyBrace",
+ IDS_SETTINGS_KERBEROS_CONFIG_ERROR_EXTRA_CURLY_BRACE},
+ {"kerberosConfigErrorRelationSyntax",
+ IDS_SETTINGS_KERBEROS_CONFIG_ERROR_RELATION_SYNTAX_ERROR},
+ {"kerberosConfigErrorKeyNotSupported",
+ IDS_SETTINGS_KERBEROS_CONFIG_ERROR_KEY_NOT_SUPPORTED},
+ {"kerberosConfigErrorSectionNotSupported",
+ IDS_SETTINGS_KERBEROS_CONFIG_ERROR_SECTION_NOT_SUPPORTED},
+ {"kerberosConfigErrorKrb5FailedToParse",
+ IDS_SETTINGS_KERBEROS_CONFIG_ERROR_KRB5_FAILED_TO_PARSE},
{"lockScreenAddFingerprint",
IDS_SETTINGS_PEOPLE_LOCK_SCREEN_ADD_FINGERPRINT_BUTTON},
{"lockScreenChangePinButton",
@@ -1733,6 +1909,7 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) {
IDS_SETTINGS_PEOPLE_LOCK_SCREEN_FINGERPRINT_LESS_SECURE},
{"lockScreenDeleteFingerprintLabel",
IDS_SETTINGS_PEOPLE_LOCK_SCREEN_DELETE_FINGERPRINT_ARIA_LABEL},
+ {"lockScreenMediaKeys", IDS_SETTINGS_PEOPLE_LOCK_SCREEN_MEDIA_KEYS},
{"lockScreenNotificationHide",
IDS_ASH_SETTINGS_LOCK_SCREEN_NOTIFICATION_HIDE},
{"lockScreenNotificationHideSensitive",
@@ -1768,7 +1945,6 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) {
IDS_PIN_KEYBOARD_HINT_TEXT_PIN_PASSWORD},
{"pinKeyboardDeleteAccessibleName",
IDS_PIN_KEYBOARD_DELETE_ACCESSIBLE_NAME},
- {"changePictureTitle", IDS_SETTINGS_CHANGE_PICTURE_DIALOG_TITLE},
{"changePicturePageDescription", IDS_SETTINGS_CHANGE_PICTURE_DIALOG_TEXT},
{"takePhoto", IDS_SETTINGS_CHANGE_PICTURE_TAKE_PHOTO},
{"captureVideo", IDS_SETTINGS_CHANGE_PICTURE_CAPTURE_VIDEO},
@@ -1818,7 +1994,7 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) {
#endif
{"syncOverview", IDS_SETTINGS_SYNC_OVERVIEW},
{"syncDisabled", IDS_PROFILES_DICE_SYNC_DISABLED_TITLE},
- {"syncDisabledByAdministrator", IDS_SIGNED_IN_WITH_SYNC_DISABLED},
+ {"syncDisabledByAdministrator", IDS_SIGNED_IN_WITH_SYNC_DISABLED_BY_POLICY},
{"syncSignin", IDS_SETTINGS_SYNC_SIGNIN},
{"syncDisconnect", IDS_SETTINGS_PEOPLE_SIGN_OUT},
{"syncDisconnectTitle", IDS_SETTINGS_SYNC_DISCONNECT_TITLE},
@@ -1883,6 +2059,9 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) {
};
AddLocalizedStringsBulk(html_source, localized_strings,
base::size(localized_strings));
+#if defined(OS_CHROMEOS)
+ AddFingerprintStrings(html_source);
+#endif // OS_CHROMEOS
html_source->AddString("managementPage",
ManagementUI::GetManagementPageSubtitle(profile));
@@ -1973,7 +2152,13 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) {
html_source->AddString("activityControlsUrl",
chrome::kGoogleAccountActivityControlsURL);
- html_source->AddString("googleAccountUrl", chrome::kGoogleAccountURL);
+ // Add Google Account URL and include UTM parameter to signal the source of
+ // the navigation.
+ html_source->AddString(
+ "googleAccountUrl",
+ net::AppendQueryParameter(GURL(chrome::kGoogleAccountURL), "utm_source",
+ "chrome-settings")
+ .spec());
html_source->AddBoolean("profileShortcutsEnabled",
ProfileShortcutManager::IsFeatureEnabled());
@@ -1991,11 +2176,34 @@ void AddPeopleStrings(content::WebUIDataSource* html_source, Profile* profile) {
html_source->AddBoolean("isAccountManagerEnabled",
chromeos::IsAccountManagerAvailable(profile));
+ PrefService* local_state = g_browser_process->local_state();
+
// Toggles the Chrome OS Kerberos Accounts submenu in the People section.
// Note that the handler is also dependent on this pref.
+ html_source->AddBoolean("isKerberosEnabled",
+ local_state->GetBoolean(prefs::kKerberosEnabled));
+
+ // Whether the 'Remember password' checkbox is enabled.
html_source->AddBoolean(
- "isKerberosEnabled",
- g_browser_process->local_state()->GetBoolean(prefs::kKerberosEnabled));
+ "kerberosRememberPasswordEnabled",
+ local_state->GetBoolean(prefs::kKerberosRememberPasswordEnabled));
+
+ // Whether new Kerberos accounts may be added.
+ html_source->AddBoolean(
+ "kerberosAddAccountsAllowed",
+ local_state->GetBoolean(prefs::kKerberosAddAccountsAllowed));
+
+ // Kerberos default configuration.
+ html_source->AddString(
+ "defaultKerberosConfig",
+ chromeos::KerberosCredentialsManager::GetDefaultKerberosConfig());
+
+ // Kerberos accounts page with "Learn more" link.
+ html_source->AddString(
+ "kerberosAccountsDescription",
+ l10n_util::GetStringFUTF16(
+ IDS_SETTINGS_KERBEROS_ACCOUNTS_DESCRIPTION,
+ GetHelpUrlWithBoard(chrome::kKerberosAccountsLearnMoreURL)));
#endif
}
@@ -2015,18 +2223,24 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) {
{"addCupsPrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_ADD_PRINTER},
{"editPrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_EDIT},
{"removePrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTERS_REMOVE},
+ {"configurePrinter", IDS_SETTINGS_PRINTING_CUPS_PRINTER_CONFIGURE_BUTTON},
{"searchLabel", IDS_SETTINGS_PRINTING_CUPS_SEARCH_LABEL},
{"noSearchResults", IDS_SEARCH_NO_RESULTS},
{"printerDetailsTitle", IDS_SETTINGS_PRINTING_CUPS_PRINTER_DETAILS_TITLE},
{"printerName", IDS_SETTINGS_PRINTING_CUPS_PRINTER_DETAILS_NAME},
{"printerModel", IDS_SETTINGS_PRINTING_CUPS_PRINTER_DETAILS_MODEL},
{"printerQueue", IDS_SETTINGS_PRINTING_CUPS_PRINTER_DETAILS_QUEUE},
+ {"savedPrintersTitle", IDS_SETTINGS_PRINTING_CUPS_SAVED_PRINTERS_TITLE},
{"addPrintersNearbyTitle",
IDS_SETTINGS_PRINTING_CUPS_ADD_PRINTERS_NEARBY_TITLE},
{"addPrintersManuallyTitle",
IDS_SETTINGS_PRINTING_CUPS_ADD_PRINTERS_MANUALLY_TITLE},
{"manufacturerAndModelDialogTitle",
IDS_SETTINGS_PRINTING_CUPS_SELECT_MANUFACTURER_AND_MODEL_TITLE},
+ {"nearbyPrintersListTitle",
+ IDS_SETTINGS_PRINTING_CUPS_PRINTERS_AVAILABLE_PRINTERS},
+ {"nearbyPrintersListDescription",
+ IDS_SETTINGS_PRINTING_CUPS_PRINTERS_ADD_DETECTED_OR_NEW_PRINTER},
{"manufacturerAndModelAdditionalInformation",
IDS_SETTINGS_PRINTING_CUPS_MANUFACTURER_MODEL_ADDITIONAL_INFORMATION},
{"addPrinterButtonText", IDS_SETTINGS_PRINTING_CUPS_ADD_PRINTER_BUTTON_ADD},
@@ -2092,6 +2306,9 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) {
{"currentPpdMessage",
IDS_SETTINGS_PRINTING_CUPS_EDIT_PRINTER_CURRENT_PPD_MESSAGE},
{"printerEulaNotice", IDS_SETTINGS_PRINTING_CUPS_EULA_NOTICE},
+ {"ippPrinterUnreachable", IDS_SETTINGS_PRINTING_CUPS_IPP_URI_UNREACHABLE},
+ {"generalPrinterDialogError",
+ IDS_SETTINGS_PRINTING_CUPS_DIALOG_GENERAL_ERROR},
#else
{"localPrintersTitle", IDS_SETTINGS_PRINTING_LOCAL_PRINTERS_TITLE},
#endif
@@ -2109,6 +2326,10 @@ void AddPrintingStrings(content::WebUIDataSource* html_source) {
html_source->AddString(
"printingCUPSPrintPpdLearnMoreUrl",
GetHelpUrlWithBoard(chrome::kCupsPrintPPDLearnMoreURL));
+
+ html_source->AddBoolean(
+ "updatedCupsPrintersUiEnabled",
+ base::FeatureList::IsEnabled(features::kCupsPrintersUiOverhaul));
#endif
}
@@ -2265,6 +2486,7 @@ void AddSearchStrings(content::WebUIDataSource* html_source, Profile* profile) {
{"osSearchPageTitle", is_assistant_allowed
? IDS_SETTINGS_SEARCH_AND_ASSISTANT
: IDS_SETTINGS_SEARCH},
+ {"osSearchEngineLabel", IDS_OS_SETTINGS_SEARCH_ENGINE_LABEL},
{"searchGoogleAssistant", IDS_SETTINGS_SEARCH_GOOGLE_ASSISTANT},
{"searchGoogleAssistantEnabled",
IDS_SETTINGS_SEARCH_GOOGLE_ASSISTANT_ENABLED},
@@ -2279,6 +2501,9 @@ void AddSearchStrings(content::WebUIDataSource* html_source, Profile* profile) {
base::ASCIIToUTF16(chrome::kOmniboxLearnMoreURL));
html_source->AddString("searchExplanation", search_explanation_text);
#if defined(OS_CHROMEOS)
+ html_source->AddString(
+ "osSearchEngineTooltip",
+ ui::SubstituteChromeOSDeviceType(IDS_OS_SETTINGS_SEARCH_ENGINE_TOOLTIP));
html_source->AddBoolean("isAssistantAllowed", is_assistant_allowed);
#endif
}
@@ -2317,10 +2542,9 @@ void AddGoogleAssistantStrings(content::WebUIDataSource* html_source,
Profile* profile) {
static constexpr LocalizedString kLocalizedStrings[] = {
{"googleAssistantPageTitle", IDS_SETTINGS_GOOGLE_ASSISTANT},
- {"googleAssistantEnableContext",
- IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_CONTEXT},
+ {"googleAssistantEnableContext", IDS_ASSISTANT_SCREEN_CONTEXT_TITLE},
{"googleAssistantEnableContextDescription",
- IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_CONTEXT_DESCRIPTION},
+ IDS_ASSISTANT_SCREEN_CONTEXT_DESC},
{"googleAssistantEnableHotword",
IDS_SETTINGS_GOOGLE_ASSISTANT_ENABLE_HOTWORD},
{"googleAssistantEnableHotwordDescription",
@@ -2328,7 +2552,7 @@ void AddGoogleAssistantStrings(content::WebUIDataSource* html_source,
{"googleAssistantVoiceSettings",
IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS},
{"googleAssistantVoiceSettingsDescription",
- IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS_DESCRIPTION},
+ IDS_ASSISTANT_VOICE_MATCH_RECORDING},
{"googleAssistantVoiceSettingsRetrainButton",
IDS_SETTINGS_GOOGLE_ASSISTANT_VOICE_SETTINGS_RETRAIN},
{"googleAssistantEnableHotwordWithoutDspDescription",
@@ -2354,11 +2578,6 @@ void AddGoogleAssistantStrings(content::WebUIDataSource* html_source,
html_source->AddBoolean("hotwordDspAvailable",
chromeos::IsHotwordDspAvailable());
-
- html_source->AddBoolean(
- "voiceMatchEnabled",
- base::FeatureList::IsEnabled(
- chromeos::assistant::features::kAssistantVoiceMatch));
}
#endif
@@ -2718,8 +2937,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source,
AddLocalizedStringsBulk(html_source, kSensorsLocalizedStrings,
base::size(kSensorsLocalizedStrings));
- html_source->AddBoolean("enableSiteSettings", base::FeatureList::IsEnabled(
- features::kSiteSettings));
html_source->AddBoolean(
"enableSafeBrowsingSubresourceFilter",
base::FeatureList::IsEnabled(
@@ -2783,6 +3000,17 @@ void AddSystemStrings(content::WebUIDataSource* html_source) {
AddLocalizedStringsBulk(html_source, kLocalizedStrings,
base::size(kLocalizedStrings));
+ html_source->AddString(
+ "proxySettingsExtensionLabel",
+ l10n_util::GetStringFUTF16(
+ IDS_SETTINGS_SYSTEM_PROXY_SETTINGS_EXTENSION_LABEL,
+ l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)));
+ html_source->AddString(
+ "proxySettingsPolicyLabel",
+ l10n_util::GetStringFUTF16(
+ IDS_SETTINGS_SYSTEM_PROXY_SETTINGS_POLICY_LABEL,
+ l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)));
+
// TODO(dbeam): we should probably rename anything involving "localized
// strings" to "load time data" as all primitive types are used now.
SystemHandler::AddLoadTimeData(html_source);
@@ -2838,10 +3066,6 @@ void AddMultideviceStrings(content::WebUIDataSource* html_source) {
{"multideviceAndroidMessagesItemTitle",
IDS_SETTINGS_MULTIDEVICE_ANDROID_MESSAGES},
{"multideviceForgetDevice", IDS_SETTINGS_MULTIDEVICE_FORGET_THIS_DEVICE},
- {"multideviceForgetDeviceSummary",
- IDS_SETTINGS_MULTIDEVICE_FORGET_THIS_DEVICE_EXPLANATION},
- {"multideviceForgetDeviceDialogMessage",
- IDS_SETTINGS_MULTIDEVICE_FORGET_DEVICE_DIALOG_MESSAGE},
{"multideviceSmartLockOptions",
IDS_SETTINGS_PEOPLE_LOCK_SCREEN_OPTIONS_LOCK},
};
@@ -2849,6 +3073,14 @@ void AddMultideviceStrings(content::WebUIDataSource* html_source) {
base::size(kLocalizedStrings));
html_source->AddString(
+ "multideviceForgetDeviceSummary",
+ ui::SubstituteChromeOSDeviceType(
+ IDS_SETTINGS_MULTIDEVICE_FORGET_THIS_DEVICE_EXPLANATION));
+ html_source->AddString(
+ "multideviceForgetDeviceDialogMessage",
+ ui::SubstituteChromeOSDeviceType(
+ IDS_SETTINGS_MULTIDEVICE_FORGET_DEVICE_DIALOG_MESSAGE));
+ html_source->AddString(
"multideviceVerificationText",
l10n_util::GetStringFUTF16(
IDS_SETTINGS_MULTIDEVICE_VERIFICATION_TEXT,
@@ -2859,7 +3091,7 @@ void AddMultideviceStrings(content::WebUIDataSource* html_source) {
html_source->AddString(
"multideviceSetupSummary",
l10n_util::GetStringFUTF16(
- IDS_SETTINGS_MULTIDEVICE_SETUP_SUMMARY,
+ IDS_SETTINGS_MULTIDEVICE_SETUP_SUMMARY, ui::GetChromeOSDeviceName(),
base::UTF8ToUTF16(
chromeos::multidevice_setup::
GetBoardSpecificBetterTogetherSuiteLearnMoreUrl()
@@ -2876,6 +3108,7 @@ void AddMultideviceStrings(content::WebUIDataSource* html_source) {
"multideviceAndroidMessagesItemSummary",
l10n_util::GetStringFUTF16(
IDS_SETTINGS_MULTIDEVICE_ANDROID_MESSAGES_SUMMARY,
+ ui::GetChromeOSDeviceName(),
base::UTF8ToUTF16(chromeos::multidevice_setup::
GetBoardSpecificMessagesLearnMoreUrl()
.spec())));
@@ -2883,6 +3116,7 @@ void AddMultideviceStrings(content::WebUIDataSource* html_source) {
"multideviceSmartLockItemSummary",
l10n_util::GetStringFUTF16(
IDS_SETTINGS_MULTIDEVICE_SMART_LOCK_SUMMARY,
+ ui::GetChromeOSDeviceName(),
GetHelpUrlWithBoard(chrome::kEasyUnlockLearnMoreUrl)));
}
#endif
@@ -2894,11 +3128,35 @@ void AddExtensionsStrings(content::WebUIDataSource* html_source) {
void AddSecurityKeysStrings(content::WebUIDataSource* html_source) {
static constexpr LocalizedString kSecurityKeysStrings[] = {
+ {"securityKeysPINTooShort",
+ IDS_SETTINGS_SECURITY_KEYS_PIN_ERROR_TOO_SHORT},
{"securityKeysConfirmPIN", IDS_SETTINGS_SECURITY_KEYS_CONFIRM_PIN},
+ {"securityKeysCredentialWebsite",
+ IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_WEBSITE},
+ {"securityKeysNoCredentialManagement",
+ IDS_SETTINGS_SECURITY_KEYS_NO_CREDENTIAL_MANAGEMENT},
+ {"securityKeysCredentialManagementErase", IDS_REMOVE},
+ {"securityKeysCredentialManagementRemoved",
+ IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_REMOVED},
+ {"securityKeysCredentialManagementDesc",
+ IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_DESC},
+ {"securityKeysCredentialManagementDialogTitle",
+ IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_DIALOG_TITLE},
+ {"securityKeysCredentialManagementLabel",
+ IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_LABEL},
+ {"securityKeysCredentialManagementNoCredentials",
+ IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_NO_CREDENTIALS},
+ {"securityKeysCredentialManagementPinPrompt",
+ IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_PIN_PROMPT},
+ {"securityKeysCredentialManagementTouch",
+ IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_TOUCH},
+ {"securityKeysCredentialUsername",
+ IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_USERNAME},
{"securityKeysCurrentPIN", IDS_SETTINGS_SECURITY_KEYS_CURRENT_PIN},
{"securityKeysCurrentPINIntro",
IDS_SETTINGS_SECURITY_KEYS_CURRENT_PIN_INTRO},
{"securityKeysDesc", IDS_SETTINGS_SECURITY_KEYS_DESC},
+ {"securityKeysHidePINs", IDS_SETTINGS_SECURITY_KEYS_HIDE_PINS},
{"securityKeysNewPIN", IDS_SETTINGS_SECURITY_KEYS_NEW_PIN},
{"securityKeysNoPIN", IDS_SETTINGS_SECURITY_KEYS_NO_PIN},
{"securityKeysNoReset", IDS_SETTINGS_SECURITY_KEYS_NO_RESET},
@@ -2906,12 +3164,17 @@ void AddSecurityKeysStrings(content::WebUIDataSource* html_source) {
{"securityKeysPINError", IDS_SETTINGS_SECURITY_KEYS_PIN_ERROR},
{"securityKeysPINHardLock", IDS_SETTINGS_SECURITY_KEYS_PIN_HARD_LOCK},
{"securityKeysPINIncorrect", IDS_SETTINGS_SECURITY_KEYS_PIN_INCORRECT},
- {"securityKeysPINIncorrectRetriesSin",
- IDS_SETTINGS_SECURITY_KEYS_PIN_INCORRECT_RETRIES_SIN},
{"securityKeysPINIncorrectRetriesPl",
IDS_SETTINGS_SECURITY_KEYS_PIN_INCORRECT_RETRIES_PL},
+ {"securityKeysPINIncorrectRetriesSin",
+ IDS_SETTINGS_SECURITY_KEYS_PIN_INCORRECT_RETRIES_SIN},
+ {"securityKeysPINMismatch",
+ IDS_SETTINGS_SECURITY_KEYS_PIN_ERROR_MISMATCH},
{"securityKeysPINSoftLock", IDS_SETTINGS_SECURITY_KEYS_PIN_SOFT_LOCK},
{"securityKeysPINSuccess", IDS_SETTINGS_SECURITY_KEYS_PIN_SUCCESS},
+ {"securityKeysPINTooLong", IDS_SETTINGS_SECURITY_KEYS_PIN_ERROR_TOO_LONG},
+ {"securityKeysPINTooShort",
+ IDS_SETTINGS_SECURITY_KEYS_PIN_ERROR_TOO_SHORT_SMALL},
{"securityKeysPINTouch", IDS_SETTINGS_SECURITY_KEYS_PIN_TOUCH},
{"securityKeysReset", IDS_SETTINGS_SECURITY_KEYS_RESET},
{"securityKeysResetConfirmTitle",
@@ -2933,6 +3196,7 @@ void AddSecurityKeysStrings(content::WebUIDataSource* html_source) {
{"securityKeysSetPINDesc", IDS_SETTINGS_SECURITY_KEYS_SET_PIN_DESC},
{"securityKeysSetPINInitialTitle",
IDS_SETTINGS_SECURITY_KEYS_SET_PIN_INITIAL_TITLE},
+ {"securityKeysShowPINs", IDS_SETTINGS_SECURITY_KEYS_SHOW_PINS},
{"securityKeysTitle", IDS_SETTINGS_SECURITY_KEYS_TITLE},
};
AddLocalizedStringsBulk(html_source, kSecurityKeysStrings,
@@ -2946,6 +3210,15 @@ void AddSecurityKeysStrings(content::WebUIDataSource* html_source) {
!device::WinWebAuthnApi::GetDefault()->IsAvailable())
#endif
);
+ html_source->AddBoolean(
+ "enableSecurityKeysCredentialManagement",
+ base::FeatureList::IsEnabled(device::kWebAuthPINSupport) &&
+ base::FeatureList::IsEnabled(device::kWebAuthCredentialManagement)
+#if defined(OS_WIN)
+ && (!base::FeatureList::IsEnabled(device::kWebAuthUseNativeWinApi) ||
+ !device::WinWebAuthnApi::GetDefault()->IsAvailable())
+#endif
+ );
}
} // namespace
@@ -2984,7 +3257,6 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source,
#if defined(OS_CHROMEOS)
AddCrostiniStrings(html_source, profile);
AddPluginVmStrings(html_source, profile);
- AddKioskNextShellStrings(html_source);
AddAndroidAppStrings(html_source);
AddAppsStrings(html_source);
AddBluetoothStrings(html_source);
@@ -2992,8 +3264,10 @@ void AddLocalizedStrings(content::WebUIDataSource* html_source,
AddDateTimeStrings(html_source);
AddDeviceStrings(html_source);
AddEasyUnlockStrings(html_source);
+ AddFilesStrings(html_source);
AddInternetStrings(html_source);
AddMultideviceStrings(html_source);
+ AddParentalControlStrings(html_source);
AddUsersStrings(html_source);
#else
AddDefaultBrowserStrings(html_source);
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 fd96a72e558..40505a485bd 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,6 @@
#include "chrome/grit/generated_resources.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
-#include "components/signin/core/browser/account_consistency_method.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_ui.h"
@@ -49,7 +48,7 @@ const char kProfileShortcutNotFound[] = "profileShortcutNotFound";
} // namespace
ManageProfileHandler::ManageProfileHandler(Profile* profile)
- : profile_(profile), observer_(this), weak_factory_(this) {}
+ : profile_(profile), observer_(this) {}
ManageProfileHandler::~ManageProfileHandler() {}
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h
index 32da11d3480..210f76c5bf2 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h
@@ -91,7 +91,7 @@ class ManageProfileHandler : public settings::SettingsPageUIHandler,
ScopedObserver<ProfileAttributesStorage, ManageProfileHandler> observer_;
// For generating weak pointers to itself for callbacks.
- base::WeakPtrFactory<ManageProfileHandler> weak_factory_;
+ base::WeakPtrFactory<ManageProfileHandler> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ManageProfileHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc
index 834603aa371..0215a9b4c38 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.cc
@@ -2,30 +2,32 @@
// 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/settings_security_key_handler.h"
+
#include <utility>
+#include "base/bind.h"
#include "base/callback.h"
#include "base/optional.h"
+#include "base/strings/string_number_conversions.h"
#include "base/values.h"
-#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
-#include "chrome/browser/ui/webui/settings/settings_security_key_handler.h"
+#include "chrome/grit/generated_resources.h"
#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/system_connector.h"
#include "content/public/browser/web_ui.h"
#include "content/public/common/service_manager_connection.h"
+#include "device/fido/credential_management.h"
+#include "device/fido/credential_management_handler.h"
+#include "device/fido/fido_discovery_factory.h"
#include "device/fido/pin.h"
#include "device/fido/reset_request_handler.h"
#include "device/fido/set_pin_request_handler.h"
+#include "ui/base/l10n/l10n_util.h"
using content::BrowserThread;
namespace {
-constexpr char kStartSetPIN[] = "securityKeyStartSetPIN";
-constexpr char kSetPIN[] = "securityKeySetPIN";
-constexpr char kClose[] = "securityKeyClose";
-constexpr char kReset[] = "securityKeyReset";
-constexpr char kCompleteReset[] = "securityKeyCompleteReset";
-
base::flat_set<device::FidoTransportProtocol> supported_transports() {
// If we ever support BLE devices then additional thought will be required
// in the UI; therefore don't enable them here. NFC is not supported on
@@ -33,37 +35,18 @@ base::flat_set<device::FidoTransportProtocol> supported_transports() {
return {device::FidoTransportProtocol::kUsbHumanInterfaceDevice};
}
+void HandleClose(base::Closure close_callback, const base::ListValue* args) {
+ DCHECK_EQ(0u, args->GetSize());
+ close_callback.Run();
+}
+
} // namespace
namespace settings {
-SecurityKeysHandler::SecurityKeysHandler()
- : state_(State::kNone),
- weak_factory_(new base::WeakPtrFactory<SecurityKeysHandler>(this)) {}
+void SecurityKeysHandlerBase::OnJavascriptAllowed() {}
-SecurityKeysHandler::~SecurityKeysHandler() = default;
-
-void SecurityKeysHandler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- kStartSetPIN, base::BindRepeating(&SecurityKeysHandler::HandleStartSetPIN,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kSetPIN, base::BindRepeating(&SecurityKeysHandler::HandleSetPIN,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kClose, base::BindRepeating(&SecurityKeysHandler::HandleClose,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kReset, base::BindRepeating(&SecurityKeysHandler::HandleReset,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- kCompleteReset,
- base::BindRepeating(&SecurityKeysHandler::HandleCompleteReset,
- base::Unretained(this)));
-}
-
-void SecurityKeysHandler::OnJavascriptAllowed() {}
-void SecurityKeysHandler::OnJavascriptDisallowed() {
+void SecurityKeysHandlerBase::OnJavascriptDisallowed() {
// If Javascript is disallowed, |Close| will invalidate all current WeakPtrs
// and thus drop all pending callbacks. This means that
// |IsJavascriptAllowed| doesn't need to be tested before each callback
@@ -72,17 +55,34 @@ void SecurityKeysHandler::OnJavascriptDisallowed() {
Close();
}
-void SecurityKeysHandler::Close() {
+SecurityKeysPINHandler::SecurityKeysPINHandler() = default;
+SecurityKeysPINHandler::~SecurityKeysPINHandler() = default;
+
+void SecurityKeysPINHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "securityKeyStartSetPIN",
+ base::BindRepeating(&SecurityKeysPINHandler::HandleStartSetPIN,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "securityKeySetPIN",
+ base::BindRepeating(&SecurityKeysPINHandler::HandleSetPIN,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "securityKeyPINClose",
+ base::BindRepeating(&HandleClose,
+ base::BindRepeating(&SecurityKeysPINHandler::Close,
+ base::Unretained(this))));
+}
+
+void SecurityKeysPINHandler::Close() {
// Invalidate all existing WeakPtrs so that no stale callbacks occur.
- weak_factory_ =
- std::make_unique<base::WeakPtrFactory<SecurityKeysHandler>>(this);
+ weak_factory_.InvalidateWeakPtrs();
state_ = State::kNone;
set_pin_.reset();
- reset_.reset();
callback_id_.clear();
}
-void SecurityKeysHandler::HandleStartSetPIN(const base::ListValue* args) {
+void SecurityKeysPINHandler::HandleStartSetPIN(const base::ListValue* args) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_EQ(State::kNone, state_);
DCHECK_EQ(1u, args->GetSize());
@@ -92,15 +92,14 @@ void SecurityKeysHandler::HandleStartSetPIN(const base::ListValue* args) {
callback_id_ = args->GetList()[0].GetString();
state_ = State::kStartSetPIN;
set_pin_ = std::make_unique<device::SetPINRequestHandler>(
- content::ServiceManagerConnection::GetForProcess()->GetConnector(),
- supported_transports(),
- base::BindOnce(&SecurityKeysHandler::OnGatherPIN,
- weak_factory_->GetWeakPtr()),
- base::BindRepeating(&SecurityKeysHandler::OnSetPINComplete,
- weak_factory_->GetWeakPtr()));
+ content::GetSystemConnector(), supported_transports(),
+ base::BindOnce(&SecurityKeysPINHandler::OnGatherPIN,
+ weak_factory_.GetWeakPtr()),
+ base::BindRepeating(&SecurityKeysPINHandler::OnSetPINComplete,
+ weak_factory_.GetWeakPtr()));
}
-void SecurityKeysHandler::OnGatherPIN(base::Optional<int64_t> num_retries) {
+void SecurityKeysPINHandler::OnGatherPIN(base::Optional<int64_t> num_retries) {
DCHECK_EQ(State::kStartSetPIN, state_);
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -118,7 +117,7 @@ void SecurityKeysHandler::OnGatherPIN(base::Optional<int64_t> num_retries) {
base::Value(std::move(list)));
}
-void SecurityKeysHandler::OnSetPINComplete(
+void SecurityKeysPINHandler::OnSetPINComplete(
device::CtapDeviceResponseCode code) {
DCHECK(state_ == State::kStartSetPIN || state_ == State::kSettingPIN);
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -138,7 +137,7 @@ void SecurityKeysHandler::OnSetPINComplete(
base::Value(std::move(list)));
}
-void SecurityKeysHandler::HandleSetPIN(const base::ListValue* args) {
+void SecurityKeysPINHandler::HandleSetPIN(const base::ListValue* args) {
DCHECK(state_ == State::kGatherNewPIN || state_ == State::kGatherChangePIN);
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_EQ(3u, args->GetSize());
@@ -155,7 +154,34 @@ void SecurityKeysHandler::HandleSetPIN(const base::ListValue* args) {
set_pin_->ProvidePIN(old_pin, new_pin);
}
-void SecurityKeysHandler::HandleReset(const base::ListValue* args) {
+SecurityKeysResetHandler::SecurityKeysResetHandler() = default;
+SecurityKeysResetHandler::~SecurityKeysResetHandler() = default;
+
+void SecurityKeysResetHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "securityKeyReset",
+ base::BindRepeating(&SecurityKeysResetHandler::HandleReset,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "securityKeyCompleteReset",
+ base::BindRepeating(&SecurityKeysResetHandler::HandleCompleteReset,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "securityKeyResetClose",
+ base::BindRepeating(&HandleClose,
+ base::BindRepeating(&SecurityKeysResetHandler::Close,
+ base::Unretained(this))));
+}
+
+void SecurityKeysResetHandler::Close() {
+ // Invalidate all existing WeakPtrs so that no stale callbacks occur.
+ weak_factory_.InvalidateWeakPtrs();
+ state_ = State::kNone;
+ reset_.reset();
+ callback_id_.clear();
+}
+
+void SecurityKeysResetHandler::HandleReset(const base::ListValue* args) {
DCHECK_EQ(State::kNone, state_);
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_EQ(1u, args->GetSize());
@@ -166,15 +192,14 @@ void SecurityKeysHandler::HandleReset(const base::ListValue* args) {
state_ = State::kStartReset;
reset_ = std::make_unique<device::ResetRequestHandler>(
- content::ServiceManagerConnection::GetForProcess()->GetConnector(),
- supported_transports(),
- base::BindOnce(&SecurityKeysHandler::OnResetSent,
- weak_factory_->GetWeakPtr()),
- base::BindOnce(&SecurityKeysHandler::OnResetFinished,
- weak_factory_->GetWeakPtr()));
+ content::GetSystemConnector(), supported_transports(),
+ base::BindOnce(&SecurityKeysResetHandler::OnResetSent,
+ weak_factory_.GetWeakPtr()),
+ base::BindOnce(&SecurityKeysResetHandler::OnResetFinished,
+ weak_factory_.GetWeakPtr()));
}
-void SecurityKeysHandler::OnResetSent() {
+void SecurityKeysResetHandler::OnResetSent() {
DCHECK_EQ(State::kStartReset, state_);
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -186,7 +211,8 @@ void SecurityKeysHandler::OnResetSent() {
base::Value(0 /* success */));
}
-void SecurityKeysHandler::HandleCompleteReset(const base::ListValue* args) {
+void SecurityKeysResetHandler::HandleCompleteReset(
+ const base::ListValue* args) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_EQ(1u, args->GetSize());
@@ -214,7 +240,7 @@ void SecurityKeysHandler::HandleCompleteReset(const base::ListValue* args) {
}
}
-void SecurityKeysHandler::OnResetFinished(
+void SecurityKeysResetHandler::OnResetFinished(
device::CtapDeviceResponseCode result) {
switch (state_) {
case State::kWaitingForResetNoCallbackYet:
@@ -243,9 +269,250 @@ void SecurityKeysHandler::OnResetFinished(
}
}
-void SecurityKeysHandler::HandleClose(const base::ListValue* args) {
- DCHECK_EQ(0u, args->GetSize());
- Close();
+SecurityKeysCredentialHandler::SecurityKeysCredentialHandler() = default;
+SecurityKeysCredentialHandler::~SecurityKeysCredentialHandler() = default;
+
+void SecurityKeysCredentialHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "securityKeyCredentialManagementStart",
+ base::BindRepeating(&SecurityKeysCredentialHandler::HandleStart,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "securityKeyCredentialManagementPIN",
+ base::BindRepeating(&SecurityKeysCredentialHandler::HandlePIN,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "securityKeyCredentialManagementEnumerate",
+ base::BindRepeating(&SecurityKeysCredentialHandler::HandleEnumerate,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "securityKeyCredentialManagementDelete",
+ base::BindRepeating(&SecurityKeysCredentialHandler::HandleDelete,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "securityKeyCredentialManagementClose",
+ base::BindRepeating(
+ &HandleClose,
+ base::BindRepeating(&SecurityKeysCredentialHandler::Close,
+ base::Unretained(this))));
+}
+
+void SecurityKeysCredentialHandler::Close() {
+ // Invalidate all existing WeakPtrs so that no stale callbacks occur.
+ weak_factory_.InvalidateWeakPtrs();
+ state_ = State::kNone;
+ discovery_factory_.reset();
+ credential_management_.reset();
+ callback_id_.clear();
+ credential_management_provide_pin_cb_.Reset();
+ DCHECK(!credential_management_provide_pin_cb_);
+}
+
+void SecurityKeysCredentialHandler::HandleStart(const base::ListValue* args) {
+ DCHECK_EQ(State::kNone, state_);
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK_EQ(1u, args->GetSize());
+ DCHECK(!credential_management_);
+ DCHECK(!discovery_factory_);
+
+ AllowJavascript();
+ DCHECK(callback_id_.empty());
+ callback_id_ = args->GetList()[0].GetString();
+
+ state_ = State::kStart;
+ discovery_factory_ = std::make_unique<device::FidoDiscoveryFactory>();
+ credential_management_ =
+ std::make_unique<device::CredentialManagementHandler>(
+ content::ServiceManagerConnection::GetForProcess()->GetConnector(),
+ discovery_factory_.get(), supported_transports(),
+ base::BindOnce(
+ &SecurityKeysCredentialHandler::OnCredentialManagementReady,
+ weak_factory_.GetWeakPtr()),
+ base::BindRepeating(&SecurityKeysCredentialHandler::OnGatherPIN,
+ weak_factory_.GetWeakPtr()),
+ base::BindOnce(&SecurityKeysCredentialHandler::OnFinished,
+ weak_factory_.GetWeakPtr()));
+}
+
+void SecurityKeysCredentialHandler::HandlePIN(const base::ListValue* args) {
+ DCHECK_EQ(State::kPIN, state_);
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK_EQ(2u, args->GetSize());
+ DCHECK(credential_management_);
+ DCHECK(credential_management_provide_pin_cb_);
+ DCHECK(callback_id_.empty());
+
+ callback_id_ = args->GetList()[0].GetString();
+ std::string pin = args->GetList()[1].GetString();
+
+ std::move(credential_management_provide_pin_cb_).Run(pin);
+}
+
+void SecurityKeysCredentialHandler::HandleEnumerate(
+ const base::ListValue* args) {
+ DCHECK_EQ(state_, State::kReady);
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK_EQ(1u, args->GetSize());
+ DCHECK(credential_management_);
+ DCHECK(callback_id_.empty());
+
+ state_ = State::kGettingCredentials;
+ callback_id_ = args->GetList()[0].GetString();
+ credential_management_->GetCredentials(
+ base::BindOnce(&SecurityKeysCredentialHandler::OnHaveCredentials,
+ weak_factory_.GetWeakPtr()));
+}
+
+void SecurityKeysCredentialHandler::HandleDelete(const base::ListValue* args) {
+ DCHECK_EQ(State::kReady, state_);
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK_EQ(2u, args->GetSize());
+ DCHECK(credential_management_);
+ DCHECK(callback_id_.empty());
+
+ state_ = State::kDeletingCredentials;
+ callback_id_ = args->GetList()[0].GetString();
+ std::vector<std::vector<uint8_t>> credential_ids;
+ for (const base::Value& el : args->GetList()[1].GetList()) {
+ std::vector<uint8_t> credential_id;
+ if (!base::HexStringToBytes(el.GetString(), &credential_id)) {
+ NOTREACHED();
+ continue;
+ }
+ credential_ids.emplace_back(std::move(credential_id));
+ }
+ credential_management_->DeleteCredentials(
+ std::move(credential_ids),
+ base::BindOnce(&SecurityKeysCredentialHandler::OnCredentialsDeleted,
+ weak_factory_.GetWeakPtr()));
+}
+void SecurityKeysCredentialHandler::OnCredentialManagementReady() {
+ DCHECK(state_ == State::kStart || state_ == State::kPIN);
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK(credential_management_);
+ DCHECK(!callback_id_.empty());
+
+ state_ = State::kReady;
+ ResolveJavascriptCallback(base::Value(std::move(callback_id_)),
+ base::Value());
+}
+
+void SecurityKeysCredentialHandler::OnHaveCredentials(
+ device::CtapDeviceResponseCode status,
+ base::Optional<std::vector<device::AggregatedEnumerateCredentialsResponse>>
+ responses,
+ base::Optional<size_t> remaining_credentials) {
+ DCHECK_EQ(State::kGettingCredentials, state_);
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK(credential_management_);
+ DCHECK(!callback_id_.empty());
+
+ if (status != device::CtapDeviceResponseCode::kSuccess) {
+ OnFinished(device::FidoReturnCode::kAuthenticatorResponseInvalid);
+ return;
+ }
+ DCHECK(responses);
+ DCHECK(remaining_credentials);
+
+ state_ = State::kReady;
+
+ base::Value::ListStorage credentials;
+ for (const auto& response : *responses) {
+ for (const auto& credential : response.credentials) {
+ base::DictionaryValue credential_value;
+ std::string credential_id =
+ base::HexEncode(credential.credential_id_cbor_bytes.data(),
+ credential.credential_id_cbor_bytes.size());
+ if (credential_id.empty()) {
+ NOTREACHED();
+ continue;
+ }
+ credential_value.SetString("id", std::move(credential_id));
+ credential_value.SetString("relyingPartyId", response.rp.id);
+ credential_value.SetString("userName", credential.user.name.value_or(""));
+ credential_value.SetString("userDisplayName",
+ credential.user.display_name.value_or(""));
+ credentials.emplace_back(std::move(credential_value));
+ }
+ }
+
+ ResolveJavascriptCallback(base::Value(std::move(callback_id_)),
+ base::ListValue(std::move(credentials)));
+}
+
+void SecurityKeysCredentialHandler::OnGatherPIN(
+ int64_t num_retries,
+ base::OnceCallback<void(std::string)> callback) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK(!callback_id_.empty());
+ DCHECK(!credential_management_provide_pin_cb_);
+
+ credential_management_provide_pin_cb_ = std::move(callback);
+
+ if (state_ == State::kStart) {
+ // Resolve the promise to startCredentialManagement().
+ state_ = State::kPIN;
+ ResolveJavascriptCallback(base::Value(std::move(callback_id_)),
+ base::Value());
+ return;
+ }
+
+ // Resolve the promise to credentialManagementProvidePIN().
+ DCHECK_EQ(state_, State::kPIN);
+ ResolveJavascriptCallback(base::Value(std::move(callback_id_)),
+ base::Value(static_cast<int>(num_retries)));
+}
+
+void SecurityKeysCredentialHandler::OnCredentialsDeleted(
+ device::CtapDeviceResponseCode status) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK_EQ(State::kDeletingCredentials, state_);
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK(credential_management_);
+ DCHECK(!callback_id_.empty());
+
+ state_ = State::kReady;
+
+ ResolveJavascriptCallback(
+ base::Value(std::move(callback_id_)),
+ base::Value(l10n_util::GetStringUTF8(
+ status == device::CtapDeviceResponseCode::kSuccess
+ ? IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_SUCCESS
+ : IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_FAILED)));
+}
+
+void SecurityKeysCredentialHandler::OnFinished(device::FidoReturnCode status) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ int error;
+
+ switch (status) {
+ case device::FidoReturnCode::kSoftPINBlock:
+ error = IDS_SETTINGS_SECURITY_KEYS_PIN_SOFT_LOCK;
+ break;
+ case device::FidoReturnCode::kHardPINBlock:
+ error = IDS_SETTINGS_SECURITY_KEYS_PIN_HARD_LOCK;
+ break;
+ case device::FidoReturnCode::kAuthenticatorMissingCredentialManagement:
+ error = IDS_SETTINGS_SECURITY_KEYS_NO_CREDENTIAL_MANAGEMENT;
+ break;
+ case device::FidoReturnCode::kAuthenticatorMissingUserVerification:
+ error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_NO_PIN;
+ break;
+ case device::FidoReturnCode::kAuthenticatorResponseInvalid:
+ error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_ERROR;
+ break;
+ case device::FidoReturnCode::kSuccess:
+ error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_REMOVED;
+ break;
+ default:
+ NOTREACHED();
+ error = IDS_SETTINGS_SECURITY_KEYS_CREDENTIAL_MANAGEMENT_ERROR;
+ break;
+ }
+
+ FireWebUIListener("security-keys-credential-management-finished",
+ base::Value(l10n_util::GetStringUTF8(std::move(error))));
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h
index 353d85c6002..2b9e1b17317 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/settings_security_key_handler.h
@@ -11,6 +11,7 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/optional.h"
+#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "device/fido/fido_constants.h"
namespace base {
@@ -18,59 +19,146 @@ class ListValue;
}
namespace device {
+struct AggregatedEnumerateCredentialsResponse;
+class FidoDiscoveryFactory;
+class CredentialManagementHandler;
class SetPINRequestHandler;
class ResetRequestHandler;
} // namespace device
namespace settings {
-// SecurityKeysHandler processes messages from the "Security Keys" section of a
-// settings page. An instance of this class is created for each settings tab and
-// is destroyed when the tab is closed. See the comments in
-// security_keys_browser_proxy.js about the interface.
-class SecurityKeysHandler : public SettingsPageUIHandler {
- public:
- SecurityKeysHandler();
- ~SecurityKeysHandler() override;
+// Base class for message handlers on the "Security Keys" settings subpage.
+class SecurityKeysHandlerBase : public SettingsPageUIHandler {
+ protected:
+ SecurityKeysHandlerBase() = default;
- void RegisterMessages() override;
+ // Subclasses must implement close to invalidate all pending callbacks.
+ virtual void Close() = 0;
+
+ private:
void OnJavascriptAllowed() override;
void OnJavascriptDisallowed() override;
+ SecurityKeysHandlerBase(const SecurityKeysHandlerBase&) = delete;
+ SecurityKeysHandlerBase& operator=(const SecurityKeysHandlerBase&) = delete;
+};
+
+// SecurityKeysPINHandler processes messages from the "Create a PIN" dialog of
+// the "Security Keys" settings subpage. An instance of this class is created
+// for each settings tab and is destroyed when the tab is closed. See
+// SecurityKeysPINBrowserProxy about the interface.
+class SecurityKeysPINHandler : public SecurityKeysHandlerBase {
+ public:
+ SecurityKeysPINHandler();
+ ~SecurityKeysPINHandler() override;
+
private:
enum class State {
kNone,
-
kStartSetPIN,
kGatherNewPIN,
kGatherChangePIN,
kSettingPIN,
+ };
+
+ void RegisterMessages() override;
+ void Close() override;
+
+ void HandleStartSetPIN(const base::ListValue* args);
+ void OnGatherPIN(base::Optional<int64_t> num_retries);
+ void OnSetPINComplete(device::CtapDeviceResponseCode code);
+ void HandleSetPIN(const base::ListValue* args);
+
+ State state_ = State::kNone;
+
+ std::unique_ptr<device::SetPINRequestHandler> set_pin_;
+
+ std::string callback_id_;
+ base::WeakPtrFactory<SecurityKeysPINHandler> weak_factory_{this};
+};
+
+// SecurityKeysResetHandler processes messages from the "Reset your Security
+// Key" dialog of the "Security Keys" settings subpage. An instance of this
+// class is created for each settings tab and is destroyed when the tab is
+// closed. See SecurityKeysResetBrowserProxy about the interface.
+class SecurityKeysResetHandler : public SecurityKeysHandlerBase {
+ public:
+ SecurityKeysResetHandler();
+ ~SecurityKeysResetHandler() override;
+ private:
+ enum class State {
+ kNone,
kStartReset,
kWaitingForResetNoCallbackYet,
kWaitingForResetHaveCallback,
kWaitingForCompleteReset,
};
- void Close();
- void HandleStartSetPIN(const base::ListValue* args);
- void OnGatherPIN(base::Optional<int64_t> num_retries);
- void OnSetPINComplete(device::CtapDeviceResponseCode code);
- void HandleSetPIN(const base::ListValue* args);
+ void RegisterMessages() override;
+ void Close() override;
+
void HandleReset(const base::ListValue* args);
void OnResetSent();
void HandleCompleteReset(const base::ListValue* args);
void OnResetFinished(device::CtapDeviceResponseCode result);
- void HandleClose(const base::ListValue* args);
- State state_;
- std::unique_ptr<device::SetPINRequestHandler> set_pin_;
+ State state_ = State::kNone;
+
std::unique_ptr<device::ResetRequestHandler> reset_;
base::Optional<device::CtapDeviceResponseCode> reset_result_;
+
std::string callback_id_;
- std::unique_ptr<base::WeakPtrFactory<SecurityKeysHandler>> weak_factory_;
+ base::WeakPtrFactory<SecurityKeysResetHandler> weak_factory_{this};
+};
+
+// SecurityKeysCredentialHandler processes messages from the "Manage
+// sign-in data" dialog of the "Security Keys" settings subpage. An instance of
+// this class is created for each settings tab and is destroyed when the tab is
+// closed. See SecurityKeysCredentialBrowserProxy about the interface.
+class SecurityKeysCredentialHandler : public SecurityKeysHandlerBase {
+ public:
+ SecurityKeysCredentialHandler();
+ ~SecurityKeysCredentialHandler() override;
+
+ private:
+ enum class State {
+ kNone,
+ kStart,
+ kPIN,
+ kReady,
+ kGettingCredentials,
+ kDeletingCredentials,
+ };
- DISALLOW_COPY_AND_ASSIGN(SecurityKeysHandler);
+ void RegisterMessages() override;
+ void Close() override;
+
+ void HandleStart(const base::ListValue* args);
+ void HandlePIN(const base::ListValue* args);
+ void HandleEnumerate(const base::ListValue* args);
+ void HandleDelete(const base::ListValue* args);
+
+ void OnCredentialManagementReady();
+ void OnHaveCredentials(
+ device::CtapDeviceResponseCode status,
+ base::Optional<
+ std::vector<device::AggregatedEnumerateCredentialsResponse>>
+ responses,
+ base::Optional<size_t> remaining_credentials);
+ void OnGatherPIN(int64_t num_retries, base::OnceCallback<void(std::string)>);
+ void OnCredentialsDeleted(device::CtapDeviceResponseCode status);
+ void OnFinished(device::FidoReturnCode status);
+
+ State state_ = State::kNone;
+ base::OnceCallback<void(std::string)> credential_management_provide_pin_cb_;
+
+ std::unique_ptr<device::FidoDiscoveryFactory> discovery_factory_;
+ std::unique_ptr<device::CredentialManagementHandler> credential_management_;
+
+ std::string callback_id_;
+ base::WeakPtrFactory<SecurityKeysCredentialHandler> weak_factory_{this};
};
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_ui.cc b/chromium/chrome/browser/ui/webui/settings/settings_ui.cc
index c80633a98f1..d33e9f09336 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_ui.cc
+++ b/chromium/chrome/browser/ui/webui/settings/settings_ui.cc
@@ -14,19 +14,21 @@
#include "ash/public/cpp/ash_features.h"
#include "base/feature_list.h"
#include "base/memory/ptr_util.h"
-#include "base/metrics/histogram_macros.h"
#include "base/stl_util.h"
+#include "build/branding_buildflags.h"
#include "build/build_config.h"
+#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/ui/passwords/manage_passwords_view_utils.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
+#include "chrome/browser/ui/webui/favicon_source.h"
#include "chrome/browser/ui/webui/managed_ui_handler.h"
#include "chrome/browser/ui/webui/metrics_handler.h"
#include "chrome/browser/ui/webui/settings/about_handler.h"
#include "chrome/browser/ui/webui/settings/accessibility_main_handler.h"
#include "chrome/browser/ui/webui/settings/appearance_handler.h"
#include "chrome/browser/ui/webui/settings/browser_lifetime_handler.h"
+#include "chrome/browser/ui/webui/settings/captions_handler.h"
#include "chrome/browser/ui/webui/settings/downloads_handler.h"
#include "chrome/browser/ui/webui/settings/extension_control_handler.h"
#include "chrome/browser/ui/webui/settings/font_handler.h"
@@ -50,10 +52,11 @@
#include "chrome/common/url_constants.h"
#include "chrome/grit/settings_resources.h"
#include "chrome/grit/settings_resources_map.h"
+#include "components/favicon_base/favicon_url_parser.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/unified_consent/feature.h"
-#include "content/public/browser/navigation_handle.h"
+#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
@@ -63,7 +66,7 @@
#include "chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_controller_win.h"
#include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h"
#include "chrome/browser/ui/webui/settings/chrome_cleanup_handler_win.h"
-#if defined(GOOGLE_CHROME_BUILD)
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
#include "chrome/browser/ui/webui/settings/incompatible_applications_handler_win.h"
#include "chrome/browser/win/conflicts/incompatible_applications_updater.h"
#include "chrome/browser/win/conflicts/token_util.h"
@@ -76,7 +79,6 @@
#endif // defined(OS_WIN) || defined(OS_CHROMEOS)
#if defined(OS_CHROMEOS)
-#include "ash/public/cpp/ash_pref_names.h"
#include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h"
#include "ash/public/cpp/stylus_utils.h"
#include "chrome/browser/browser_process.h"
@@ -89,6 +91,8 @@
#include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_utils.h"
#include "chrome/browser/chromeos/multidevice_setup/multidevice_setup_client_factory.h"
#include "chrome/browser/chromeos/plugin_vm/plugin_vm_util.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h"
#include "chrome/browser/ui/webui/settings/chromeos/accessibility_handler.h"
#include "chrome/browser/ui/webui/settings/chromeos/account_manager_handler.h"
@@ -107,6 +111,7 @@
#include "chrome/browser/ui/webui/settings/chromeos/internet_handler.h"
#include "chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h"
#include "chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h"
+#include "chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.h"
#include "chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h"
#include "chrome/browser/web_applications/system_web_app_manager.h"
#include "chrome/common/chrome_features.h"
@@ -117,9 +122,13 @@
#include "chromeos/constants/chromeos_features.h"
#include "chromeos/constants/chromeos_pref_names.h"
#include "chromeos/constants/chromeos_switches.h"
+#include "chromeos/login/auth/password_visibility_utils.h"
#include "chromeos/services/multidevice_setup/public/cpp/prefs.h"
+#include "chromeos/services/network_config/public/mojom/constants.mojom.h" // nogncheck
#include "components/arc/arc_util.h"
#include "components/prefs/pref_service.h"
+#include "components/user_manager/user.h"
+#include "services/service_manager/public/cpp/connector.h"
#include "ui/base/ui_base_features.h"
#include "ui/chromeos/resources/grit/ui_chromeos_resources.h"
#else // !defined(OS_CHROMEOS)
@@ -146,6 +155,25 @@
namespace settings {
+namespace {
+
+#if defined(OS_CHROMEOS)
+bool ShouldShowParentalControls(Profile* profile) {
+ // Show Parental controls for regular and child accounts that are the
+ // primary profile. Do not show it to any secondary profiles, managed
+ // accounts that aren't child accounts (i.e. enterprise and EDU accounts),
+ // OTR accounts, or legacy supervised user accounts.
+ return chromeos::switches::IsParentalControlsSettingsEnabled() &&
+ profile == ProfileManager::GetPrimaryUserProfile() &&
+ !profile->IsLegacySupervised() && !profile->IsGuestSession() &&
+ (profile->IsChild() ||
+ !profile->GetProfilePolicyConnector()->IsManaged());
+}
+
+#endif // defined(OS_CHROMEOS)
+
+} // namespace
+
// static
void SettingsUI::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
@@ -157,8 +185,14 @@ void SettingsUI::RegisterProfilePrefs(
}
SettingsUI::SettingsUI(content::WebUI* web_ui)
+#if defined(OS_CHROMEOS)
+ : ui::MojoWebUIController(web_ui, /*enable_chrome_send =*/true),
+#else
: content::WebUIController(web_ui),
- WebContentsObserver(web_ui->GetWebContents()) {
+#endif
+ webui_load_timer_(web_ui->GetWebContents(),
+ "Settings.LoadDocumentTime.MD",
+ "Settings.LoadCompletedTime.MD") {
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource* html_source =
content::WebUIDataSource::Create(chrome::kChromeUISettingsHost);
@@ -182,14 +216,12 @@ SettingsUI::SettingsUI(content::WebUI* web_ui)
AddSettingsPageUIHandler(std::make_unique<ImportDataHandler>());
#if defined(OS_WIN) || defined(OS_CHROMEOS)
- // TODO(jamescook): Sort out how language is split between Chrome OS and
- // and browser settings.
AddSettingsPageUIHandler(std::make_unique<LanguagesHandler>(web_ui));
#endif // defined(OS_WIN) || defined(OS_CHROMEOS)
AddSettingsPageUIHandler(
std::make_unique<MediaDevicesSelectionHandler>(profile));
-#if defined(GOOGLE_CHROME_BUILD) && !defined(OS_CHROMEOS)
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && !defined(OS_CHROMEOS)
AddSettingsPageUIHandler(std::make_unique<MetricsReportingHandler>());
#endif
AddSettingsPageUIHandler(std::make_unique<OnStartupHandler>(profile));
@@ -199,7 +231,13 @@ SettingsUI::SettingsUI(content::WebUI* web_ui)
AddSettingsPageUIHandler(std::make_unique<SearchEnginesHandler>(profile));
AddSettingsPageUIHandler(std::make_unique<SiteSettingsHandler>(profile));
AddSettingsPageUIHandler(std::make_unique<StartupPagesHandler>(web_ui));
- AddSettingsPageUIHandler(std::make_unique<SecurityKeysHandler>());
+ AddSettingsPageUIHandler(std::make_unique<SecurityKeysPINHandler>());
+ AddSettingsPageUIHandler(std::make_unique<SecurityKeysResetHandler>());
+ AddSettingsPageUIHandler(std::make_unique<SecurityKeysCredentialHandler>());
+
+#if defined(OS_WIN) || defined(OS_MACOSX)
+ AddSettingsPageUIHandler(std::make_unique<CaptionsHandler>());
+#endif
#if defined(OS_CHROMEOS)
// TODO(950007): Remove this when SplitSettings is the default and there are
@@ -219,7 +257,7 @@ SettingsUI::SettingsUI(content::WebUI* web_ui)
AddSettingsPageUIHandler(std::make_unique<ChromeCleanupHandler>(profile));
#endif // defined(OS_WIN)
-#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
+#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING)
bool has_incompatible_applications =
IncompatibleApplicationsUpdater::HasCachedApplications();
html_source->AddBoolean("showIncompatibleApplications",
@@ -229,7 +267,7 @@ SettingsUI::SettingsUI(content::WebUI* web_ui)
if (has_incompatible_applications)
AddSettingsPageUIHandler(
std::make_unique<IncompatibleApplicationsHandler>());
-#endif // OS_WIN && defined(GOOGLE_CHROME_BUILD)
+#endif // OS_WIN && BUILDFLAG(GOOGLE_CHROME_BRANDING)
bool password_protection_available = false;
#if defined(FULL_SAFE_BROWSING)
@@ -261,7 +299,16 @@ SettingsUI::SettingsUI(content::WebUI* web_ui)
html_source->AddBoolean("showImportPasswords",
base::FeatureList::IsEnabled(
password_manager::features::kPasswordImport));
+
+#if defined(OS_CHROMEOS)
+ html_source->AddBoolean("showParentalControls",
+ ShouldShowParentalControls(profile));
+#endif
+
#if defined(OS_CHROMEOS)
+ // This is the browser settings page.
+ html_source->AddBoolean("isOSSettings", false);
+ // If false, hides OS-specific settings (like networks) in browser settings.
html_source->AddBoolean(
"showOSSettings",
!base::FeatureList::IsEnabled(chromeos::features::kSplitSettings));
@@ -307,39 +354,22 @@ SettingsUI::SettingsUI(content::WebUI* web_ui)
AddLocalizedStrings(html_source, profile);
- DarkModeHandler::Initialize(web_ui, html_source);
ManagedUIHandler::Initialize(web_ui, html_source);
content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(),
html_source);
-}
-
-SettingsUI::~SettingsUI() {}
-
-void SettingsUI::AddSettingsPageUIHandler(
- std::unique_ptr<content::WebUIMessageHandler> handler) {
- DCHECK(handler);
- web_ui()->AddMessageHandler(std::move(handler));
-}
-void SettingsUI::DidStartNavigation(
- content::NavigationHandle* navigation_handle) {
- if (navigation_handle->IsSameDocument())
- return;
+ content::URLDataSource::Add(
+ profile, std::make_unique<FaviconSource>(
+ profile, chrome::FaviconUrlFormat::kFavicon2));
- load_start_time_ = base::Time::Now();
-}
-
-void SettingsUI::DocumentLoadedInFrame(
- content::RenderFrameHost* render_frame_host) {
- UMA_HISTOGRAM_TIMES("Settings.LoadDocumentTime.MD",
- base::Time::Now() - load_start_time_);
+#if defined(OS_CHROMEOS)
+ AddHandlerToRegistry(base::BindRepeating(&SettingsUI::BindCrosNetworkConfig,
+ base::Unretained(this)));
+#endif // defined (OS_CHROMEOS)
}
-void SettingsUI::DocumentOnLoadCompletedInMainFrame() {
- UMA_HISTOGRAM_TIMES("Settings.LoadCompletedTime.MD",
- base::Time::Now() - load_start_time_);
-}
+SettingsUI::~SettingsUI() = default;
#if defined(OS_CHROMEOS)
// static
@@ -424,6 +454,11 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile,
: nullptr,
android_sms_service ? android_sms_service->android_sms_app_manager()
: nullptr));
+ if (ShouldShowParentalControls(profile)) {
+ web_ui->AddMessageHandler(
+ std::make_unique<chromeos::settings::ParentalControlsHandler>(
+ profile));
+ }
}
html_source->AddBoolean(
@@ -436,31 +471,33 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile,
html_source->AddBoolean(
"quickUnlockDisabledByPolicy",
chromeos::quick_unlock::IsPinDisabledByPolicy(profile->GetPrefs()));
+ html_source->AddBoolean(
+ "userCannotManuallyEnterPassword",
+ !chromeos::password_visibility::AccountHasUserFacingPassword(
+ chromeos::ProfileHelper::Get()
+ ->GetUserByProfile(profile)
+ ->GetAccountId()));
const bool fingerprint_unlock_enabled =
chromeos::quick_unlock::IsFingerprintEnabled(profile);
html_source->AddBoolean("fingerprintUnlockEnabled",
fingerprint_unlock_enabled);
if (fingerprint_unlock_enabled) {
- html_source->AddBoolean(
- "isFingerprintReaderOnKeyboard",
- chromeos::quick_unlock::IsFingerprintReaderOnKeyboard());
+ html_source->AddInteger(
+ "fingerprintReaderLocation",
+ static_cast<int32_t>(chromeos::quick_unlock::GetFingerprintLocation()));
}
html_source->AddBoolean("lockScreenNotificationsEnabled",
ash::features::IsLockScreenNotificationsEnabled());
html_source->AddBoolean(
"lockScreenHideSensitiveNotificationsSupported",
ash::features::IsLockScreenHideSensitiveNotificationsSupported());
+ html_source->AddBoolean(
+ "lockScreenMediaKeysEnabled",
+ base::FeatureList::IsEnabled(ash::features::kLockScreenMediaKeys));
html_source->AddBoolean("showTechnologyBadge",
!ash::features::IsSeparateNetworkIconsEnabled());
html_source->AddBoolean("hasInternalStylus",
ash::stylus_utils::HasInternalStylus());
-#if defined(KIOSK_NEXT)
- // Remove valueExists call from os_settings_ui.js when the #define is removed.
- html_source->AddBoolean(
- "showKioskNextShell",
- base::FeatureList::IsEnabled(ash::features::kKioskNextShell) &&
- profile->GetPrefs()->GetBoolean(ash::prefs::kKioskNextShellEligible));
-#endif
html_source->AddBoolean("showCrostini",
crostini::IsCrostiniUIAllowedForProfile(
@@ -489,17 +526,31 @@ void SettingsUI::InitOSWebUIHandlers(Profile* profile,
arc::IsArcAllowedForProfile(profile));
html_source->AddBoolean("havePlayStoreApp", arc::IsPlayStoreAvailable());
- // TODO(mash): Support Chrome power settings in Mash. https://crbug.com/644348
- bool enable_power_settings = !::features::IsMultiProcessMash();
- html_source->AddBoolean("enablePowerSettings", enable_power_settings);
- if (enable_power_settings) {
- web_ui->AddMessageHandler(
- std::make_unique<chromeos::settings::PowerHandler>(
- profile->GetPrefs()));
- }
+ html_source->AddBoolean("enablePowerSettings", true);
+ web_ui->AddMessageHandler(
+ std::make_unique<chromeos::settings::PowerHandler>(profile->GetPrefs()));
html_source->AddBoolean(
"showApps", base::FeatureList::IsEnabled(features::kAppManagement));
+
+ html_source->AddBoolean("showParentalControlsSettings",
+ ShouldShowParentalControls(profile));
+}
+#endif // defined(OS_CHROMEOS)
+
+void SettingsUI::AddSettingsPageUIHandler(
+ std::unique_ptr<content::WebUIMessageHandler> handler) {
+ DCHECK(handler);
+ web_ui()->AddMessageHandler(std::move(handler));
+}
+
+#if defined(OS_CHROMEOS)
+void SettingsUI::BindCrosNetworkConfig(
+ chromeos::network_config::mojom::CrosNetworkConfigRequest request) {
+ content::BrowserContext::GetConnectorFor(
+ web_ui()->GetWebContents()->GetBrowserContext())
+ ->BindInterface(chromeos::network_config::mojom::kServiceName,
+ std::move(request));
}
#endif // defined(OS_CHROMEOS)
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_ui.h b/chromium/chrome/browser/ui/webui/settings/settings_ui.h
index c5c2fc9fa46..16d535fe786 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_ui.h
+++ b/chromium/chrome/browser/ui/webui/settings/settings_ui.h
@@ -6,10 +6,15 @@
#define CHROME_BROWSER_UI_WEBUI_SETTINGS_SETTINGS_UI_H_
#include "base/macros.h"
-#include "base/time/time.h"
#include "chrome/browser/profiles/profile.h"
-#include "content/public/browser/web_contents_observer.h"
+#include "chrome/browser/ui/webui/webui_load_timer.h"
+
+#if defined(OS_CHROMEOS)
+#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" // nogncheck
+#include "ui/webui/mojo_web_ui_controller.h"
+#else
#include "content/public/browser/web_ui_controller.h"
+#endif
class Profile;
@@ -25,8 +30,13 @@ class PrefRegistrySyncable;
namespace settings {
// The WebUI handler for chrome://settings.
-class SettingsUI : public content::WebUIController,
- public content::WebContentsObserver {
+class SettingsUI
+#if defined(OS_CHROMEOS)
+ : public ui::MojoWebUIController
+#else
+ : public content::WebUIController
+#endif
+{
public:
static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
@@ -40,18 +50,15 @@ class SettingsUI : public content::WebUIController,
content::WebUIDataSource* html_source);
#endif // defined(OS_CHROMEOS)
- // content::WebContentsObserver:
- void DidStartNavigation(
- content::NavigationHandle* navigation_handle) override;
- void DocumentLoadedInFrame(
- content::RenderFrameHost* render_frame_host) override;
- void DocumentOnLoadCompletedInMainFrame() override;
-
private:
void AddSettingsPageUIHandler(
std::unique_ptr<content::WebUIMessageHandler> handler);
+#if defined(OS_CHROMEOS)
+ void BindCrosNetworkConfig(
+ chromeos::network_config::mojom::CrosNetworkConfigRequest request);
+#endif
- base::Time load_start_time_;
+ WebuiLoadTimer webui_load_timer_;
DISALLOW_COPY_AND_ASSIGN(SettingsUI);
};
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 b2bca94d4c5..6318434a79a 100644
--- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc
@@ -251,7 +251,7 @@ void ConvertSiteGroupMapToListValue(
origin_object.SetKey(kNumCookies, base::Value(0));
origin_object.SetKey(
kHasPermissionSettings,
- base::Value(base::ContainsKey(origin_permission_set, origin)));
+ base::Value(base::Contains(origin_permission_set, origin)));
origin_list.GetList().emplace_back(std::move(origin_object));
}
site_group.SetKey(kNumCookies, base::Value(0));
@@ -474,8 +474,7 @@ void SiteSettingsHandler::OnGetUsageInfo() {
const CookieTreeNode* root = cookies_tree_model_->GetRoot();
std::string usage_string = "";
std::string cookie_string = "";
- for (int i = 0; i < root->child_count(); ++i) {
- const CookieTreeNode* site = root->GetChild(i);
+ for (const auto& site : root->children()) {
std::string title = base::UTF16ToUTF8(site->GetTitle());
if (title != usage_host_)
continue;
@@ -602,11 +601,9 @@ void SiteSettingsHandler::HandleClearUsage(const base::ListValue* args) {
if (!url.is_valid())
return;
AllowJavascript();
- CookieTreeNode* parent = cookies_tree_model_->GetRoot();
- for (int i = 0; i < parent->child_count(); ++i) {
- CookieTreeNode* node = parent->GetChild(i);
+ for (const auto& node : cookies_tree_model_->GetRoot()->children()) {
if (origin == node->GetDetailedInfo().origin.GetURL().spec()) {
- cookies_tree_model_->DeleteCookieNode(node);
+ cookies_tree_model_->DeleteCookieNode(node.get());
return;
}
}
@@ -1385,13 +1382,13 @@ void SiteSettingsHandler::StopObservingSourcesForProfile(Profile* profile) {
void SiteSettingsHandler::TreeNodesAdded(ui::TreeModel* model,
ui::TreeModelNode* parent,
- int start,
- int count) {}
+ size_t start,
+ size_t count) {}
void SiteSettingsHandler::TreeNodesRemoved(ui::TreeModel* model,
ui::TreeModelNode* parent,
- int start,
- int count) {}
+ size_t start,
+ size_t count) {}
void SiteSettingsHandler::TreeNodeChanged(ui::TreeModel* model,
ui::TreeModelNode* node) {}
@@ -1413,9 +1410,7 @@ void SiteSettingsHandler::GetOriginStorage(
std::map<std::string, int64_t>* origin_size_map) {
CHECK(cookies_tree_model_.get());
- const CookieTreeNode* root = cookies_tree_model_->GetRoot();
- for (int i = 0; i < root->child_count(); ++i) {
- const CookieTreeNode* site = root->GetChild(i);
+ for (const auto& site : cookies_tree_model_->GetRoot()->children()) {
int64_t size = site->InclusiveSize();
if (size == 0)
continue;
@@ -1429,9 +1424,7 @@ void SiteSettingsHandler::GetOriginCookies(
std::map<std::string, int>* origin_cookie_map) {
CHECK(cookies_tree_model_.get());
// Get sites that don't have data but have cookies.
- const CookieTreeNode* root = cookies_tree_model_->GetRoot();
- for (int i = 0; i < root->child_count(); ++i) {
- const CookieTreeNode* site = root->GetChild(i);
+ for (const auto& site : cookies_tree_model_->GetRoot()->children()) {
GURL url = site->GetDetailedInfo().origin.GetURL();
(*origin_cookie_map)[url.host()] = site->NumberOfCookies();
CreateOrAppendSiteGroupEntry(all_sites_map, url,
@@ -1450,18 +1443,16 @@ void SiteSettingsHandler::HandleClearEtldPlus1DataAndCookies(
// Find all the nodes that contain the given etld+1.
std::vector<CookieTreeNode*> nodes_to_delete;
- for (int i = 0; i < parent->child_count(); ++i) {
- CookieTreeNode* node = parent->GetChild(i);
+ for (const auto& node : parent->children()) {
std::string cookie_node_etld_plus1 =
net::registry_controlled_domains::GetDomainAndRegistry(
base::UTF16ToUTF8(node->GetTitle()),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
if (etld_plus1_string == cookie_node_etld_plus1)
- nodes_to_delete.push_back(node);
+ nodes_to_delete.push_back(node.get());
}
- for (auto* node : nodes_to_delete) {
+ for (auto* node : nodes_to_delete)
cookies_tree_model_->DeleteCookieNode(node);
- }
LogAllSitesAction(AllSitesAction::kClearData);
}
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 297cae399a8..04848c7d698 100644
--- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h
@@ -55,12 +55,12 @@ class SiteSettingsHandler : public SettingsPageUIHandler,
// WebUI
void TreeNodesAdded(ui::TreeModel* model,
ui::TreeModelNode* parent,
- int start,
- int count) override;
+ size_t start,
+ size_t count) override;
void TreeNodesRemoved(ui::TreeModel* model,
ui::TreeModelNode* parent,
- int start,
- int count) override;
+ size_t start,
+ size_t count) override;
void TreeNodeChanged(ui::TreeModel* model, ui::TreeModelNode* node) override;
void TreeModelEndBatch(CookiesTreeModel* model) override;
diff --git a/chromium/chrome/browser/ui/webui/settings_utils_win.cc b/chromium/chrome/browser/ui/webui/settings_utils_win.cc
index e787f684842..69db0748f26 100644
--- a/chromium/chrome/browser/ui/webui/settings_utils_win.cc
+++ b/chromium/chrome/browser/ui/webui/settings_utils_win.cc
@@ -16,7 +16,10 @@
#include "base/task/post_task.h"
#include "base/threading/thread.h"
#include "base/threading/thread_task_runner_handle.h"
+#include "base/win/windows_version.h"
#include "chrome/browser/browser_process.h"
+#include "chrome/browser/platform_util.h"
+#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/cryptuiapi_shim.h"
#include "content/public/browser/web_contents.h"
#include "ui/gfx/font.h"
@@ -99,9 +102,17 @@ void OpenConnectionDialogCallback() {
}
void ShowNetworkProxySettings(content::WebContents* web_contents) {
- base::PostTaskWithTraits(FROM_HERE,
- {base::TaskPriority::USER_VISIBLE, base::MayBlock()},
- base::BindOnce(&OpenConnectionDialogCallback));
+ if (base::win::GetVersion() >= base::win::Version::WIN10) {
+ // See
+ // https://docs.microsoft.com/en-us/windows/uwp/launch-resume/launch-settings-app#network--internet
+ platform_util::OpenExternal(
+ Profile::FromBrowserContext(web_contents->GetBrowserContext()),
+ GURL("ms-settings:network-proxy"));
+ } else {
+ base::PostTaskWithTraits(
+ FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()},
+ base::BindOnce(&OpenConnectionDialogCallback));
+ }
}
void ShowManageSSLCertificates(content::WebContents* web_contents) {
diff --git a/chromium/chrome/browser/ui/webui/signin/OWNERS b/chromium/chrome/browser/ui/webui/signin/OWNERS
index 541418ca938..a058d8e5b28 100644
--- a/chromium/chrome/browser/ui/webui/signin/OWNERS
+++ b/chromium/chrome/browser/ui/webui/signin/OWNERS
@@ -1,5 +1,4 @@
achuith@chromium.org
-anthonyvd@chromium.org
msarda@chromium.org
rogerta@chromium.org
xiyuan@chromium.org
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 8d4e51f12bd..dd5f7fb4911 100644
--- a/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc
+++ b/chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc
@@ -22,6 +22,7 @@
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_avatar_icon_util.h"
#include "chrome/browser/profiles/profile_manager.h"
+#include "chrome/browser/signin/account_id_from_account_info.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/signin/signin_util.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
@@ -31,18 +32,16 @@
#include "components/keyed_service/content/browser_context_keyed_service_shutdown_notifier_factory.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/account_consistency_method.h"
-#include "components/signin/core/browser/account_info.h"
-#include "components/signin/core/browser/signin_metrics.h"
-#include "components/signin/core/browser/signin_pref_names.h"
+#include "components/signin/public/base/signin_metrics.h"
+#include "components/signin/public/base/signin_pref_names.h"
+#include "components/signin/public/identity_manager/accounts_mutator.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "components/signin/public/identity_manager/primary_account_mutator.h"
#include "components/sync/driver/sync_service.h"
#include "components/sync/driver/sync_user_settings.h"
#include "components/unified_consent/feature.h"
#include "components/unified_consent/unified_consent_service.h"
#include "content/public/browser/storage_partition.h"
-#include "services/identity/public/cpp/accounts_mutator.h"
-#include "services/identity/public/cpp/identity_manager.h"
-#include "services/identity/public/cpp/primary_account_mutator.h"
namespace {
@@ -72,7 +71,7 @@ class DiceTurnSyncOnHelperShutdownNotifierFactory
DISALLOW_COPY_AND_ASSIGN(DiceTurnSyncOnHelperShutdownNotifierFactory);
};
-AccountInfo GetAccountInfo(identity::IdentityManager* identity_manager,
+AccountInfo GetAccountInfo(signin::IdentityManager* identity_manager,
const std::string& account_id) {
auto maybe_account_info =
identity_manager->FindAccountInfoForAccountWithRefreshTokenByAccountId(
@@ -81,7 +80,7 @@ AccountInfo GetAccountInfo(identity::IdentityManager* identity_manager,
: AccountInfo();
}
-class TokensLoadedCallbackRunner : public identity::IdentityManager::Observer {
+class TokensLoadedCallbackRunner : public signin::IdentityManager::Observer {
public:
// Calls |callback| when tokens are loaded.
static void RunWhenLoaded(Profile* profile,
@@ -100,7 +99,7 @@ class TokensLoadedCallbackRunner : public identity::IdentityManager::Observer {
}
private:
- TokensLoadedCallbackRunner(identity::IdentityManager* identity_manager,
+ TokensLoadedCallbackRunner(signin::IdentityManager* identity_manager,
KeyedServiceShutdownNotifier* shutdown_notifier,
base::OnceClosure callback)
: identity_manager_(identity_manager),
@@ -113,7 +112,7 @@ class TokensLoadedCallbackRunner : public identity::IdentityManager::Observer {
scoped_identity_manager_observer_.Add(identity_manager_);
}
- // identity::IdentityManager::Observer implementation:
+ // signin::IdentityManager::Observer implementation:
void OnRefreshTokensLoaded() override {
std::move(callback_).Run();
delete this;
@@ -121,8 +120,8 @@ class TokensLoadedCallbackRunner : public identity::IdentityManager::Observer {
void OnShutdown() { delete this; }
- identity::IdentityManager* identity_manager_;
- ScopedObserver<identity::IdentityManager, TokensLoadedCallbackRunner>
+ signin::IdentityManager* identity_manager_;
+ ScopedObserver<signin::IdentityManager, TokensLoadedCallbackRunner>
scoped_identity_manager_observer_;
base::OnceClosure callback_;
std::unique_ptr<KeyedServiceShutdownNotifier::Subscription>
@@ -153,8 +152,7 @@ DiceTurnSyncOnHelper::DiceTurnSyncOnHelper(
DiceTurnSyncOnHelperShutdownNotifierFactory::GetInstance()
->Get(profile)
->Subscribe(base::Bind(&DiceTurnSyncOnHelper::AbortAndDelete,
- base::Unretained(this)))),
- weak_pointer_factory_(this) {
+ base::Unretained(this)))) {
DCHECK(delegate_);
DCHECK(profile_);
// Should not start syncing if the profile is already authenticated
@@ -501,7 +499,7 @@ void DiceTurnSyncOnHelper::FinishSyncSetupAndDelete(
identity_manager_->GetPrimaryAccountMutator();
DCHECK(primary_account_mutator);
primary_account_mutator->ClearPrimaryAccount(
- identity::PrimaryAccountMutator::ClearAccountsAction::kKeepAll,
+ signin::PrimaryAccountMutator::ClearAccountsAction::kKeepAll,
signin_metrics::ABORT_SIGNIN,
signin_metrics::SignoutDelete::IGNORE_METRIC);
AbortAndDelete();
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 84007e353a0..59e334ddc00 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
@@ -16,12 +16,12 @@
#include "chrome/browser/sync/sync_startup_tracker.h"
#include "chrome/browser/ui/webui/signin/login_ui_service.h"
#include "components/keyed_service/core/keyed_service_shutdown_notifier.h"
-#include "components/signin/core/browser/account_info.h"
-#include "components/signin/core/browser/signin_metrics.h"
+#include "components/signin/public/base/signin_metrics.h"
+#include "components/signin/public/identity_manager/account_info.h"
class Browser;
-namespace identity {
+namespace signin {
class IdentityManager;
}
@@ -196,7 +196,7 @@ class DiceTurnSyncOnHelper : public SyncStartupTracker::Observer {
std::unique_ptr<Delegate> delegate_;
Profile* profile_;
- identity::IdentityManager* identity_manager_;
+ signin::IdentityManager* identity_manager_;
const signin_metrics::AccessPoint signin_access_point_;
const signin_metrics::PromoAction signin_promo_action_;
const signin_metrics::Reason signin_reason_;
@@ -222,7 +222,7 @@ class DiceTurnSyncOnHelper : public SyncStartupTracker::Observer {
std::unique_ptr<KeyedServiceShutdownNotifier::Subscription>
shutdown_subscription_;
- base::WeakPtrFactory<DiceTurnSyncOnHelper> weak_pointer_factory_;
+ base::WeakPtrFactory<DiceTurnSyncOnHelper> weak_pointer_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DiceTurnSyncOnHelper);
};
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 6450d648e88..bcc7150897b 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
@@ -4,6 +4,8 @@
#include "chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h"
+#include <utility>
+
#include "base/bind.h"
#include "base/callback.h"
#include "base/files/file_path.h"
@@ -27,8 +29,10 @@
#include "chrome/test/base/testing_profile.h"
#include "components/account_id/account_id.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/signin_metrics.h"
-#include "components/signin/core/browser/signin_pref_names.h"
+#include "components/signin/public/base/signin_metrics.h"
+#include "components/signin/public/base/signin_pref_names.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "components/sync/driver/mock_sync_service.h"
#include "components/sync/driver/sync_user_settings_mock.h"
#include "components/unified_consent/feature.h"
@@ -36,8 +40,6 @@
#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/identity/public/cpp/identity_test_environment.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -107,12 +109,13 @@ class UnittestProfileManager : public ProfileManagerWithoutInit {
return BuildTestingProfile(file_path, /*delegate=*/nullptr).release();
}
- Profile* CreateProfileAsyncHelper(const base::FilePath& path,
- Delegate* delegate) override {
+ std::unique_ptr<Profile> CreateProfileAsyncHelper(
+ const base::FilePath& path,
+ Delegate* delegate) override {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(base::IgnoreResult(&base::CreateDirectory), path));
- return BuildTestingProfile(path, this).release();
+ return BuildTestingProfile(path, this);
}
};
@@ -127,7 +130,7 @@ class FakeUserPolicySigninService : public policy::UserPolicySigninService {
}
FakeUserPolicySigninService(Profile* profile,
- identity::IdentityManager* identity_manager)
+ signin::IdentityManager* identity_manager)
: UserPolicySigninService(profile,
nullptr,
nullptr,
@@ -228,10 +231,10 @@ class DiceTurnSyncOnHelperTestBase : public testing::Test {
// Basic accessors.
Profile* profile() { return profile_.get(); }
- identity::IdentityTestEnvironment* identity_test_env() {
+ signin::IdentityTestEnvironment* identity_test_env() {
return identity_test_env_profile_adaptor_->identity_test_env();
}
- identity::IdentityManager* identity_manager() {
+ signin::IdentityManager* identity_manager() {
return identity_test_env()->identity_manager();
}
const std::string& account_id() { return account_id_; }
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 48580497d75..d025828e2ed 100644
--- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc
+++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc
@@ -26,7 +26,7 @@
#include "chrome/common/pref_names.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/signin_pref_names.h"
+#include "components/signin/public/base/signin_pref_names.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
@@ -36,7 +36,7 @@
const char kSignInPromoQueryKeyShowAccountManagement[] =
"showAccountManagement";
-InlineLoginHandler::InlineLoginHandler() : weak_ptr_factory_(this) {}
+InlineLoginHandler::InlineLoginHandler() {}
InlineLoginHandler::~InlineLoginHandler() {}
diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h
index 4977139f011..65e1ac89af0 100644
--- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h
+++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h
@@ -88,7 +88,7 @@ class InlineLoginHandler : public content::WebUIMessageHandler {
bool trusted_found,
bool choose_what_to_sync) = 0;
- base::WeakPtrFactory<InlineLoginHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<InlineLoginHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(InlineLoginHandler);
};
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 85b68863cd9..3e034ca354a 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
@@ -16,9 +16,9 @@
#include "chrome/browser/ui/webui/signin/inline_login_handler.h"
#include "chromeos/components/account_manager/account_manager.h"
#include "chromeos/components/account_manager/account_manager_factory.h"
-#include "components/signin/core/browser/account_info.h"
+#include "components/signin/public/identity_manager/account_info.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "google_apis/gaia/gaia_urls.h"
-#include "services/identity/public/cpp/identity_manager.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
namespace chromeos {
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 aaab6f09281..3f4e4878ee9 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
@@ -16,6 +16,7 @@
#include "ui/aura/window.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
+#include "ui/views/widget/widget.h"
#include "url/gurl.h"
namespace chromeos {
@@ -46,6 +47,11 @@ void InlineLoginHandlerDialogChromeOS::Show(const std::string& email) {
dialog->ShowSystemDialog();
}
+void InlineLoginHandlerDialogChromeOS::AdjustWidgetInitParams(
+ views::Widget::InitParams* params) {
+ params->z_order = ui::ZOrderLevel::kNormal;
+}
+
gfx::Size InlineLoginHandlerDialogChromeOS::GetMaximumDialogSize() {
gfx::Size size;
GetDialogSize(&size);
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 703e4a2f9f4..5a5e94fc49e 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
@@ -28,6 +28,9 @@ class InlineLoginHandlerDialogChromeOS
// account re-authentication.
static void Show(const std::string& email = std::string());
+ // ui::SystemWebDialogDelegate overrides.
+ void AdjustWidgetInitParams(views::Widget::InitParams* params) override;
+
// web_modal::WebContentsModalDialogHost overrides.
gfx::Size GetMaximumDialogSize() override;
gfx::NativeView GetHostView() const override;
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 51db0a4ac29..201e1922675 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
@@ -58,19 +58,18 @@
#include "components/password_manager/core/browser/password_store.h"
#include "components/prefs/pref_service.h"
#include "components/signin/core/browser/about_signin_internals.h"
-#include "components/signin/core/browser/signin_header_helper.h"
-#include "components/signin/core/browser/signin_investigator.h"
-#include "components/signin/core/browser/signin_metrics.h"
-#include "components/signin/core/browser/signin_pref_names.h"
+#include "components/signin/public/base/signin_metrics.h"
+#include "components/signin/public/base/signin_pref_names.h"
+#include "components/signin/public/identity_manager/accounts_cookie_mutator.h"
+#include "components/signin/public/identity_manager/accounts_mutator.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "components/signin/public/identity_manager/primary_account_mutator.h"
#include "content/public/browser/storage_partition.h"
#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_urls.h"
#include "net/base/url_util.h"
-#include "services/identity/public/cpp/accounts_mutator.h"
-#include "services/identity/public/cpp/identity_manager.h"
-#include "services/identity/public/cpp/primary_account_mutator.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(OS_WIN)
@@ -250,7 +249,7 @@ void OnSyncSetupComplete(Profile* profile,
const std::string& username,
const std::string& password) {
DCHECK(signin_util::IsForceSigninEnabled());
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
bool has_primary_account = identity_manager->HasPrimaryAccount();
if (has_primary_account && !password.empty()) {
@@ -357,7 +356,7 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened(
AboutSigninInternalsFactory::GetForProfile(profile_);
about_signin_internals->OnRefreshTokenReceived("Successful");
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile_);
std::string primary_email = identity_manager->GetPrimaryAccountInfo().email;
@@ -399,7 +398,7 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened(
if (identity_manager->HasPrimaryAccount()) {
identity_manager->GetAccountsCookieMutator()->AddAccountToCookie(
identity_manager->GetPrimaryAccountId(),
- gaia::GaiaSource::kSigninManager, {});
+ gaia::GaiaSource::kPrimaryAccountManager, {});
}
signin_metrics::LogSigninReason(
@@ -441,7 +440,7 @@ void InlineSigninHelper::UntrustedSigninConfirmed(
void InlineSigninHelper::CreateSyncStarter(const std::string& refresh_token) {
DCHECK(signin_util::IsForceSigninEnabled());
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile_);
if (identity_manager->HasPrimaryAccount()) {
// Already signed in, nothing to do.
@@ -484,7 +483,7 @@ void InlineSigninHelper::OnClientOAuthFailure(
}
InlineLoginHandlerImpl::InlineLoginHandlerImpl()
- : confirm_untrusted_signin_(false), weak_factory_(this) {}
+ : confirm_untrusted_signin_(false) {}
InlineLoginHandlerImpl::~InlineLoginHandlerImpl() {}
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 2782fc32e5a..e05ee3ae67d 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
@@ -125,7 +125,7 @@ class InlineLoginHandlerImpl : public InlineLoginHandler {
// process.
bool confirm_untrusted_signin_;
- base::WeakPtrFactory<InlineLoginHandlerImpl> weak_factory_;
+ base::WeakPtrFactory<InlineLoginHandlerImpl> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(InlineLoginHandlerImpl);
};
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 f39a238c332..9b42b10cf06 100644
--- a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc
+++ b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc
@@ -21,7 +21,6 @@
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
-#include "components/signin/core/browser/account_consistency_method.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/common/content_switches.h"
@@ -99,9 +98,7 @@ bool IsValidChromeSigninReason(const GURL& url) {
} // namespace
-InlineLoginUI::InlineLoginUI(content::WebUI* web_ui)
- : WebDialogUI(web_ui),
- weak_factory_(this) {
+InlineLoginUI::InlineLoginUI(content::WebUI* web_ui) : WebDialogUI(web_ui) {
if (!IsValidChromeSigninReason(web_ui->GetWebContents()->GetVisibleURL()))
return;
diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h
index 3b9ff05f6db..82c0959aa72 100644
--- a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h
+++ b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.h
@@ -18,7 +18,7 @@ class InlineLoginUI : public ui::WebDialogUI {
~InlineLoginUI() override;
private:
- base::WeakPtrFactory<InlineLoginUI> weak_factory_;
+ base::WeakPtrFactory<InlineLoginUI> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(InlineLoginUI);
};
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 c1b51e2def0..aff12cc4469 100644
--- a/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc
+++ b/chromium/chrome/browser/ui/webui/signin/login_ui_service.cc
@@ -16,7 +16,6 @@
#include "chrome/browser/ui/scoped_tabbed_browser_displayer.h"
#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
#include "chrome/common/url_constants.h"
-#include "components/signin/core/browser/account_consistency_method.h"
#include "components/signin/core/browser/signin_header_helper.h"
#if !defined(OS_CHROMEOS)
@@ -112,8 +111,7 @@ void LoginUIService::DisplayLoginResult(Browser* browser,
UserManagerProfileDialog::DisplayErrorMessage();
} else if (browser) {
browser->window()->ShowAvatarBubbleFromAvatarButton(
- error_message.empty() ? BrowserWindow::AVATAR_BUBBLE_MODE_CONFIRM_SIGNIN
- : BrowserWindow::AVATAR_BUBBLE_MODE_SHOW_ERROR,
+ BrowserWindow::AVATAR_BUBBLE_MODE_CONFIRM_SIGNIN,
signin::ManageAccountsParams(),
signin_metrics::AccessPoint::ACCESS_POINT_EXTENSIONS, false);
}
diff --git a/chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.cc b/chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.cc
index 9913b9afa6d..a32321ef2ed 100644
--- a/chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.cc
+++ b/chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.cc
@@ -21,12 +21,12 @@
#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
#include "chrome/browser/ui/webui/signin/signin_utils.h"
#include "chrome/test/base/ui_test_utils.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.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 "services/identity/public/cpp/identity_manager.h"
using content::MessageLoopRunner;
@@ -42,9 +42,9 @@ const char kGetPasswordFieldFromDiceSigninPage[] =
" return e.querySelector('input[type=password]');"
"})()";
-// The SignInObserver observes the signin manager and blocks until a signin
+// The SignInObserver observes the identity manager and blocks until a signin
// success or failure notification is fired.
-class SignInObserver : public identity::IdentityManager::Observer {
+class SignInObserver : public signin::IdentityManager::Observer {
public:
SignInObserver() : seen_(false), running_(false), signed_in_(false) {}
@@ -298,7 +298,7 @@ bool SignInWithUI(Browser* browser,
return false;
#else
SignInObserver signin_observer;
- ScopedObserver<identity::IdentityManager, SignInObserver>
+ ScopedObserver<signin::IdentityManager, SignInObserver>
scoped_signin_observer(&signin_observer);
scoped_signin_observer.Add(
IdentityManagerFactory::GetForProfile(browser->profile()));
diff --git a/chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.h b/chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.h
index 439d50c18ee..8478e113bf1 100644
--- a/chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.h
+++ b/chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.h
@@ -9,7 +9,7 @@
#include <vector>
#include "base/time/time.h"
-#include "components/signin/core/browser/signin_metrics.h"
+#include "components/signin/public/base/signin_metrics.h"
class Browser;
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc
index 5fe27fbbcec..dec3301d61e 100644
--- a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc
+++ b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc
@@ -37,7 +37,6 @@
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/signin_error_controller.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
@@ -45,8 +44,7 @@
#include "ui/base/l10n/l10n_util.h"
SigninCreateProfileHandler::SigninCreateProfileHandler()
- : profile_creation_type_(NO_CREATION_IN_PROGRESS),
- weak_ptr_factory_(this) {}
+ : profile_creation_type_(NO_CREATION_IN_PROGRESS) {}
SigninCreateProfileHandler::~SigninCreateProfileHandler() {}
@@ -64,6 +62,9 @@ void SigninCreateProfileHandler::GetLocalizedValues(
"createProfileTitle",
l10n_util::GetStringUTF16(IDS_PROFILES_CREATE_TITLE));
localized_strings->SetString(
+ "createProfileNamePlaceholder",
+ l10n_util::GetStringUTF16(IDS_PROFILES_CREATE_NAME_PLACEHOLDER));
+ localized_strings->SetString(
"exitAndChildlockLabel",
l10n_util::GetStringUTF16(
IDS_PROFILES_PROFILE_SIGNOUT_BUTTON));
@@ -87,19 +88,6 @@ void SigninCreateProfileHandler::RequestDefaultProfileIcons(
web_ui()->CallJavascriptFunctionUnsafe(
"cr.webUIListenerCallback", base::Value("profile-icons-received"),
*profiles::GetDefaultProfileAvatarIconsAndLabels());
-
- SendNewProfileDefaults();
-}
-
-void SigninCreateProfileHandler::SendNewProfileDefaults() {
- ProfileAttributesStorage& storage =
- g_browser_process->profile_manager()->GetProfileAttributesStorage();
- base::DictionaryValue profile_info;
- profile_info.SetString("name", storage.ChooseNameForNewProfile(0));
-
- web_ui()->CallJavascriptFunctionUnsafe(
- "cr.webUIListenerCallback", base::Value("profile-defaults-received"),
- profile_info);
}
void SigninCreateProfileHandler::CreateProfile(const base::ListValue* args) {
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h
index 12e3a0607e7..db7c0811783 100644
--- a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h
+++ b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.h
@@ -34,7 +34,7 @@ class SigninCreateProfileHandler : public content::WebUIMessageHandler,
protected:
FRIEND_TEST_ALL_PREFIXES(SigninCreateProfileHandlerTest,
- ReturnDefaultProfileNameAndIcons);
+ ReturnDefaultProfileIcons);
FRIEND_TEST_ALL_PREFIXES(SigninCreateProfileHandlerTest,
ReturnSignedInProfiles);
FRIEND_TEST_ALL_PREFIXES(SigninCreateProfileHandlerTest,
@@ -69,10 +69,6 @@ class SigninCreateProfileHandler : public content::WebUIMessageHandler,
// Sends the array of default profile icon URLs to WebUI.
void RequestDefaultProfileIcons(const base::ListValue* args);
- // Sends an object to WebUI of the form: { "name": profileName } after
- // "requestDefaultProfileIcons" is fulfilled.
- void SendNewProfileDefaults();
-
// Asynchronously creates and initializes a new profile.
// The arguments are as follows:
// 0: name (string)
@@ -136,7 +132,7 @@ class SigninCreateProfileHandler : public content::WebUIMessageHandler,
content::NotificationRegistrar registrar_;
- base::WeakPtrFactory<SigninCreateProfileHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<SigninCreateProfileHandler> weak_ptr_factory_{this};
private:
DISALLOW_COPY_AND_ASSIGN(SigninCreateProfileHandler);
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc
index c25759cb41a..8e714ee6b01 100644
--- a/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler_unittest.cc
@@ -123,14 +123,13 @@ class SigninCreateProfileHandlerTest : public BrowserWithTestWindowTest {
std::unique_ptr<TestSigninCreateProfileHandler> handler_;
};
-TEST_F(SigninCreateProfileHandlerTest, ReturnDefaultProfileNameAndIcons) {
+TEST_F(SigninCreateProfileHandlerTest, ReturnDefaultProfileIcons) {
// Request default profile information.
base::ListValue list_args;
handler()->RequestDefaultProfileIcons(&list_args);
- // Expect two JS callbacks. One with profile avatar icons and the other with
- // the default profile name.
- EXPECT_EQ(2U, web_ui()->call_data().size());
+ // Expect one JS callbacks for the profile avatar icons.
+ EXPECT_EQ(1U, web_ui()->call_data().size());
EXPECT_EQ(kTestWebUIResponse, web_ui()->call_data()[0]->function_name());
@@ -141,17 +140,6 @@ TEST_F(SigninCreateProfileHandlerTest, ReturnDefaultProfileNameAndIcons) {
const base::ListValue* profile_icons;
ASSERT_TRUE(web_ui()->call_data()[0]->arg2()->GetAsList(&profile_icons));
EXPECT_NE(0U, profile_icons->GetSize());
-
- EXPECT_EQ(kTestWebUIResponse, web_ui()->call_data()[1]->function_name());
-
- ASSERT_TRUE(web_ui()->call_data()[1]->arg1()->GetAsString(&callback_name));
- EXPECT_EQ("profile-defaults-received", callback_name);
-
- const base::DictionaryValue* profile_info;
- ASSERT_TRUE(web_ui()->call_data()[1]->arg2()->GetAsDictionary(&profile_info));
- std::string profile_name;
- ASSERT_TRUE(profile_info->GetString("name", &profile_name));
- EXPECT_NE("", profile_name);
}
TEST_F(SigninCreateProfileHandlerTest, CreateProfile) {
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc b/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc
index 1eb9149ad76..b7fc877daf6 100644
--- a/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc
+++ b/chromium/chrome/browser/ui/webui/signin/signin_error_ui.cc
@@ -22,7 +22,7 @@
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/generated_resources.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/signin_pref_names.h"
+#include "components/signin/public/base/signin_pref_names.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_utils_desktop.cc b/chromium/chrome/browser/ui/webui/signin/signin_utils_desktop.cc
index b116fe94221..80d414cc9a3 100644
--- a/chromium/chrome/browser/ui/webui/signin/signin_utils_desktop.cc
+++ b/chromium/chrome/browser/ui/webui/signin/signin_utils_desktop.cc
@@ -18,9 +18,10 @@
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "components/guest_view/browser/guest_view_manager.h"
-#include "components/signin/core/browser/identity_utils.h"
-#include "components/signin/core/browser/signin_pref_names.h"
-#include "services/identity/public/cpp/identity_manager.h"
+#include "components/signin/public/base/signin_pref_names.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "components/signin/public/identity_manager/identity_utils.h"
+#include "google_apis/gaia/gaia_auth_util.h"
#include "ui/base/l10n/l10n_util.h"
bool CanOfferSignin(Profile* profile,
@@ -46,9 +47,8 @@ bool CanOfferSignin(Profile* profile,
return false;
// Make sure this username is not prohibited by policy.
- if (!identity::LegacyIsUsernameAllowedByPatternFromPrefs(
- g_browser_process->local_state(), email,
- prefs::kGoogleServicesUsernamePattern)) {
+ if (!signin::IsUsernameAllowedByPatternFromPrefs(
+ g_browser_process->local_state(), email)) {
if (error_message) {
error_message->assign(
l10n_util::GetStringUTF8(IDS_SYNC_LOGIN_NAME_PROHIBITED));
@@ -59,7 +59,7 @@ bool CanOfferSignin(Profile* profile,
if (can_offer == CAN_OFFER_SIGNIN_FOR_SECONDARY_ACCOUNT)
return true;
- // If the signin manager already has an authenticated name, then this is a
+ // If the identity manager already has a primary account, 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 = identity_manager->GetPrimaryAccountInfo().email;
@@ -126,5 +126,5 @@ bool IsCrossAccountError(Profile* profile,
InvestigatedScenario scenario =
SigninInvestigator(email, gaia_id, &provider).Investigate();
- return scenario == InvestigatedScenario::DIFFERENT_ACCOUNT;
+ return scenario == InvestigatedScenario::kDifferentAccount;
}
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 e1d569f56f3..59859724861 100644
--- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc
+++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc
@@ -11,6 +11,7 @@
#include "base/metrics/user_metrics.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/consent_auditor/consent_auditor_factory.h"
+#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_avatar_icon_util.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/ui/browser_list.h"
@@ -21,8 +22,8 @@
#include "chrome/browser/ui/webui/signin/sync_confirmation_ui.h"
#include "chrome/common/webui_url_constants.h"
#include "components/consent_auditor/consent_auditor.h"
-#include "components/signin/core/browser/account_info.h"
-#include "components/signin/core/browser/avatar_icon_util.h"
+#include "components/signin/public/base/avatar_icon_util.h"
+#include "components/signin/public/identity_manager/account_info.h"
#include "components/unified_consent/feature.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
@@ -32,13 +33,11 @@ const int kProfileImageSize = 128;
SyncConfirmationHandler::SyncConfirmationHandler(
Browser* browser,
- const std::unordered_map<std::string, int>& string_to_grd_id_map,
- consent_auditor::Feature consent_feature)
+ const std::unordered_map<std::string, int>& string_to_grd_id_map)
: profile_(browser->profile()),
browser_(browser),
did_user_explicitly_interact(false),
string_to_grd_id_map_(string_to_grd_id_map),
- consent_feature_(consent_feature),
identity_manager_(IdentityManagerFactory::GetForProfile(profile_)) {
DCHECK(profile_);
DCHECK(browser_);
@@ -90,6 +89,7 @@ void SyncConfirmationHandler::HandleConfirm(const base::ListValue* args) {
}
void SyncConfirmationHandler::HandleGoToSettings(const base::ListValue* args) {
+ DCHECK(profile_->IsSyncAllowed());
did_user_explicitly_interact = true;
RecordConsent(args);
CloseModalSigninWindow(LoginUIService::CONFIGURE_SYNC_FIRST);
@@ -102,6 +102,7 @@ void SyncConfirmationHandler::HandleUndo(const base::ListValue* args) {
void SyncConfirmationHandler::HandleAccountImageRequest(
const base::ListValue* args) {
+ DCHECK(profile_->IsSyncAllowed());
base::Optional<AccountInfo> primary_account_info =
identity_manager_->FindExtendedAccountInfoForAccount(
identity_manager_->GetPrimaryAccountInfo());
@@ -120,12 +121,11 @@ void SyncConfirmationHandler::RecordConsent(const base::ListValue* args) {
args->GetList()[0].GetList();
const std::string& consent_confirmation = args->GetList()[1].GetString();
- std::vector<int> consent_text_ids;
-
// The strings returned by the WebUI are not free-form, they must belong into
// a pre-determined set of strings (stored in |string_to_grd_id_map_|). As
// this has privacy and legal implications, CHECK the integrity of the strings
// received from the renderer process before recording the consent.
+ std::vector<int> consent_text_ids;
for (const base::Value& text : consent_description) {
auto iter = string_to_grd_id_map_.find(text.GetString());
CHECK(iter != string_to_grd_id_map_.end()) << "Unexpected string:\n"
@@ -138,33 +138,27 @@ void SyncConfirmationHandler::RecordConsent(const base::ListValue* args) {
<< consent_confirmation;
int consent_confirmation_id = iter->second;
+ sync_pb::UserConsentTypes::SyncConsent sync_consent;
+ sync_consent.set_confirmation_grd_id(consent_confirmation_id);
+ for (int id : consent_text_ids) {
+ sync_consent.add_description_grd_ids(id);
+ }
+ sync_consent.set_status(sync_pb::UserConsentTypes::ConsentStatus::
+ UserConsentTypes_ConsentStatus_GIVEN);
+
consent_auditor::ConsentAuditor* consent_auditor =
ConsentAuditorFactory::GetForProfile(profile_);
- const std::string& account_id = identity_manager_->GetPrimaryAccountId();
- // TODO(markusheintz): Use a bool unified_consent_enabled instead of a
- // consent_auditor::Feature type variable.
- if (consent_feature_ == consent_auditor::Feature::CHROME_UNIFIED_CONSENT) {
- sync_pb::UserConsentTypes::UnifiedConsent unified_consent;
- unified_consent.set_confirmation_grd_id(consent_confirmation_id);
- for (int id : consent_text_ids) {
- unified_consent.add_description_grd_ids(id);
- }
- unified_consent.set_status(sync_pb::UserConsentTypes::ConsentStatus::
- UserConsentTypes_ConsentStatus_GIVEN);
- consent_auditor->RecordUnifiedConsent(account_id, unified_consent);
- } else {
- sync_pb::UserConsentTypes::SyncConsent sync_consent;
- sync_consent.set_confirmation_grd_id(consent_confirmation_id);
- for (int id : consent_text_ids) {
- sync_consent.add_description_grd_ids(id);
- }
- sync_consent.set_status(sync_pb::UserConsentTypes::ConsentStatus::
- UserConsentTypes_ConsentStatus_GIVEN);
- consent_auditor->RecordSyncConsent(account_id, sync_consent);
- }
+ consent_auditor->RecordSyncConsent(identity_manager_->GetPrimaryAccountId(),
+ sync_consent);
}
void SyncConfirmationHandler::SetUserImageURL(const std::string& picture_url) {
+ if (!profile_->IsSyncAllowed()) {
+ // The sync disabled confirmation handler does not present the user image.
+ // Avoid updating the image URL in this case.
+ return;
+ }
+
std::string picture_url_to_load;
GURL picture_gurl(picture_url);
if (picture_gurl.is_valid()) {
@@ -179,12 +173,7 @@ void SyncConfirmationHandler::SetUserImageURL(const std::string& picture_url) {
base::Value picture_url_value(picture_url_to_load);
AllowJavascript();
- if (unified_consent::IsUnifiedConsentFeatureEnabled()) {
- FireWebUIListener("account-image-changed", picture_url_value);
- } else {
- CallJavascriptFunction("sync.confirmation.setUserImageURL",
- picture_url_value);
- }
+ FireWebUIListener("account-image-changed", picture_url_value);
}
void SyncConfirmationHandler::OnExtendedAccountInfoUpdated(
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 5407c208312..c1e1ab98592 100644
--- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.h
+++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.h
@@ -12,19 +12,19 @@
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/browser/ui/webui/signin/login_ui_service.h"
#include "components/consent_auditor/consent_auditor.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/web_ui_message_handler.h"
-#include "services/identity/public/cpp/identity_manager.h"
namespace base {
class ListValue;
}
-namespace identity {
+namespace signin {
class IdentityManager;
}
class SyncConfirmationHandler : public content::WebUIMessageHandler,
- public identity::IdentityManager::Observer,
+ public signin::IdentityManager::Observer,
public BrowserListObserver {
public:
// Creates a SyncConfirmationHandler for the |browser|. All strings in the
@@ -32,14 +32,13 @@ class SyncConfirmationHandler : public content::WebUIMessageHandler,
// mapped to their GRD IDs.
explicit SyncConfirmationHandler(
Browser* browser,
- const std::unordered_map<std::string, int>& string_to_grd_id_map,
- consent_auditor::Feature consent_feature);
+ const std::unordered_map<std::string, int>& string_to_grd_id_map);
~SyncConfirmationHandler() override;
// content::WebUIMessageHandler:
void RegisterMessages() override;
- // identity::IdentityManager::Observer:
+ // signin::IdentityManager::Observer:
void OnExtendedAccountInfoUpdated(const AccountInfo& info) override;
// BrowserListObserver:
@@ -104,10 +103,7 @@ class SyncConfirmationHandler : public content::WebUIMessageHandler,
// and their respective GRD IDs.
std::unordered_map<std::string, int> string_to_grd_id_map_;
- // Contains the features to use when the user consent decision is recorded.
- consent_auditor::Feature consent_feature_;
-
- identity::IdentityManager* identity_manager_;
+ signin::IdentityManager* identity_manager_;
DISALLOW_COPY_AND_ASSIGN(SyncConfirmationHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc
index 4e4a3a9bb6c..3593351d31e 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
@@ -29,7 +29,7 @@
#include "chrome/test/base/dialog_test_browser_window.h"
#include "chrome/test/base/testing_profile.h"
#include "components/consent_auditor/fake_consent_auditor.h"
-#include "components/signin/core/browser/avatar_icon_util.h"
+#include "components/signin/public/base/avatar_icon_util.h"
#include "components/unified_consent/scoped_unified_consent.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_web_ui.h"
@@ -46,9 +46,7 @@ class TestingSyncConfirmationHandler : public SyncConfirmationHandler {
Browser* browser,
content::WebUI* web_ui,
std::unordered_map<std::string, int> string_to_grd_id_map)
- : SyncConfirmationHandler(browser,
- string_to_grd_id_map,
- consent_auditor::Feature::CHROME_SYNC) {
+ : SyncConfirmationHandler(browser, string_to_grd_id_map) {
set_web_ui(web_ui);
}
@@ -125,7 +123,7 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest,
ConsentAuditorFactory::GetForProfile(profile()));
}
- identity::IdentityTestEnvironment* identity_test_env() {
+ signin::IdentityTestEnvironment* identity_test_env() {
return identity_test_env_adaptor_->identity_test_env();
}
@@ -167,7 +165,7 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest,
ASSERT_TRUE(call_data.arg1()->GetAsString(&event));
EXPECT_EQ("account-image-changed", event);
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile());
base::Optional<AccountInfo> primary_account =
identity_manager->FindExtendedAccountInfoForAccount(
@@ -210,62 +208,12 @@ class SyncConfirmationHandlerTest : public BrowserWithTestWindowTest,
DISALLOW_COPY_AND_ASSIGN(SyncConfirmationHandlerTest);
};
-class SyncConfirmationHandlerTest_UnifiedConsentDisabled
- : public SyncConfirmationHandlerTest {
- public:
- SyncConfirmationHandlerTest_UnifiedConsentDisabled()
- : scoped_unified_consent_(
- unified_consent::UnifiedConsentFeatureState::kDisabled) {}
-
- private:
- unified_consent::ScopedUnifiedConsent scoped_unified_consent_;
-
- DISALLOW_COPY_AND_ASSIGN(SyncConfirmationHandlerTest_UnifiedConsentDisabled);
-};
-
const char SyncConfirmationHandlerTest::kConsentText1[] = "consentText1";
const char SyncConfirmationHandlerTest::kConsentText2[] = "consentText2";
const char SyncConfirmationHandlerTest::kConsentText3[] = "consentText3";
const char SyncConfirmationHandlerTest::kConsentText4[] = "consentText4";
const char SyncConfirmationHandlerTest::kConsentText5[] = "consentText5";
-TEST_F(SyncConfirmationHandlerTest_UnifiedConsentDisabled,
- TestSetImageIfPrimaryAccountReady) {
- identity_test_env()->SimulateSuccessfulFetchOfAccountInfo(
- account_info_.account_id, account_info_.email, account_info_.gaia, "",
- "full_name", "given_name", "locale",
- "http://picture.example.com/picture.jpg");
-
- base::ListValue args;
- args.Set(0, std::make_unique<base::Value>(kDefaultDialogHeight));
- handler()->HandleInitializedWithSize(&args);
- EXPECT_EQ(2U, web_ui()->call_data().size());
-
- // When the primary account is ready, setUserImageURL happens before
- // clearFocus since the image URL is known before showing the dialog.
- EXPECT_EQ("sync.confirmation.setUserImageURL",
- web_ui()->call_data()[0]->function_name());
- EXPECT_TRUE(web_ui()->call_data()[0]->arg1()->is_string());
- std::string passed_picture_url;
- EXPECT_TRUE(
- web_ui()->call_data()[0]->arg1()->GetAsString(&passed_picture_url));
-
- EXPECT_EQ("sync.confirmation.clearFocus",
- web_ui()->call_data()[1]->function_name());
-
- identity::IdentityManager* identity_manager =
- IdentityManagerFactory::GetForProfile(profile());
- base::Optional<AccountInfo> primary_account_info =
- identity_manager->FindExtendedAccountInfoForAccount(
- identity_manager->GetPrimaryAccountInfo());
- std::string original_picture_url =
- primary_account_info ? primary_account_info->picture_url : std::string();
- GURL picture_url_with_size = signin::GetAvatarImageURLWithOptions(
- GURL(original_picture_url), kExpectedProfileImageSize,
- false /* no_silhouette */);
- EXPECT_EQ(picture_url_with_size.spec(), passed_picture_url);
-}
-
TEST_F(SyncConfirmationHandlerTest, TestSetImageIfPrimaryAccountReady) {
identity_test_env()->SimulateSuccessfulFetchOfAccountInfo(
account_info_.account_id, account_info_.email, account_info_.gaia, "",
@@ -281,55 +229,6 @@ TEST_F(SyncConfirmationHandlerTest, TestSetImageIfPrimaryAccountReady) {
web_ui()->call_data()[1]->function_name());
}
-TEST_F(SyncConfirmationHandlerTest_UnifiedConsentDisabled,
- TestSetImageIfPrimaryAccountReadyLater) {
- base::ListValue args;
- args.Set(0, std::make_unique<base::Value>(kDefaultDialogHeight));
- handler()->HandleInitializedWithSize(&args);
- EXPECT_EQ(2U, web_ui()->call_data().size());
-
- identity_test_env()->SimulateSuccessfulFetchOfAccountInfo(
- account_info_.account_id, account_info_.email, account_info_.gaia, "",
- "full_name", "given_name", "locale",
- "http://picture.example.com/picture.jpg");
-
- EXPECT_EQ(3U, web_ui()->call_data().size());
-
- // When the primary account isn't yet ready when the dialog is shown,
- // setUserImageURL is called with the default placeholder image.
- EXPECT_EQ("sync.confirmation.setUserImageURL",
- web_ui()->call_data()[0]->function_name());
- EXPECT_TRUE(web_ui()->call_data()[0]->arg1()->is_string());
- std::string passed_picture_url;
- EXPECT_TRUE(
- web_ui()->call_data()[0]->arg1()->GetAsString(&passed_picture_url));
- EXPECT_EQ(profiles::GetPlaceholderAvatarIconUrl(), passed_picture_url);
-
- // When the primary account isn't yet ready when the dialog is shown,
- // clearFocus is called before the second call to setUserImageURL.
- EXPECT_EQ("sync.confirmation.clearFocus",
- web_ui()->call_data()[1]->function_name());
-
- EXPECT_EQ("sync.confirmation.setUserImageURL",
- web_ui()->call_data()[2]->function_name());
- EXPECT_TRUE(web_ui()->call_data()[2]->arg1()->is_string());
- EXPECT_TRUE(
- web_ui()->call_data()[2]->arg1()->GetAsString(&passed_picture_url));
-
- identity::IdentityManager* identity_manager =
- IdentityManagerFactory::GetForProfile(profile());
- base::Optional<AccountInfo> primary_account_info =
- identity_manager->FindExtendedAccountInfoForAccount(
- identity_manager->GetPrimaryAccountInfo());
-
- std::string original_picture_url =
- primary_account_info ? primary_account_info->picture_url : std::string();
- GURL picture_url_with_size = signin::GetAvatarImageURLWithOptions(
- GURL(original_picture_url), kExpectedProfileImageSize,
- false /* no_silhouette */);
- EXPECT_EQ(picture_url_with_size.spec(), passed_picture_url);
-}
-
TEST_F(SyncConfirmationHandlerTest, TestSetImageIfPrimaryAccountReadyLater) {
base::ListValue args;
args.Set(0, std::make_unique<base::Value>(kDefaultDialogHeight));
@@ -349,36 +248,6 @@ TEST_F(SyncConfirmationHandlerTest, TestSetImageIfPrimaryAccountReadyLater) {
ExpectAccountImageChanged(*web_ui()->call_data()[2]);
}
-TEST_F(SyncConfirmationHandlerTest_UnifiedConsentDisabled,
- TestSetImageIgnoredIfSecondaryAccountUpdated) {
- base::ListValue args;
- args.Set(0, std::make_unique<base::Value>(kDefaultDialogHeight));
- handler()->HandleInitializedWithSize(&args);
- EXPECT_EQ(2U, web_ui()->call_data().size());
-
- AccountInfo account_info =
- identity_test_env()->MakeAccountAvailable("bar@example.com");
- identity_test_env()->SimulateSuccessfulFetchOfAccountInfo(
- account_info.account_id, account_info.email, account_info.gaia, "",
- "bar_full_name", "bar_given_name", "bar_locale",
- "http://picture.example.com/bar_picture.jpg");
-
- // Updating the account info of a secondary account should not update the
- // image of the sync confirmation dialog.
- EXPECT_EQ(2U, web_ui()->call_data().size());
-
- identity_test_env()->SimulateSuccessfulFetchOfAccountInfo(
- account_info_.account_id, account_info_.email, account_info_.gaia, "",
- "full_name", "given_name", "locale",
- "http://picture.example.com/picture.jpg");
-
- // Updating the account info of the primary account should update the
- // image of the sync confirmation dialog.
- EXPECT_EQ(3U, web_ui()->call_data().size());
- EXPECT_EQ("sync.confirmation.setUserImageURL",
- web_ui()->call_data()[2]->function_name());
-}
-
TEST_F(SyncConfirmationHandlerTest,
TestSetImageIgnoredIfSecondaryAccountUpdated) {
base::ListValue args;
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 81e3ec8ec9f..5d58676bbbe 100644
--- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc
+++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc
@@ -12,62 +12,59 @@
#include "chrome/browser/signin/account_consistency_mode_manager.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
#include "chrome/browser/ui/webui/signin/sync_confirmation_handler.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/generated_resources.h"
-#include "components/signin/core/browser/avatar_icon_util.h"
+#include "components/signin/public/base/avatar_icon_util.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/strings/grit/components_strings.h"
#include "components/unified_consent/feature.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
-#include "services/identity/public/cpp/identity_manager.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui)
- : SigninWebDialogUI(web_ui),
- consent_feature_(consent_auditor::Feature::CHROME_SYNC) {
+ : SigninWebDialogUI(web_ui) {
+ DCHECK(unified_consent::IsUnifiedConsentFeatureEnabled());
Profile* profile = Profile::FromWebUI(web_ui);
bool is_sync_allowed = profile->IsSyncAllowed();
- bool is_unified_consent_enabled =
- unified_consent::IsUnifiedConsentFeatureEnabled();
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUISyncConfirmationHost);
source->SetJsonPath("strings.js");
source->AddResourcePath("signin_shared_css.html", IDR_SIGNIN_SHARED_CSS_HTML);
- int title_ids = -1;
- int confirm_button_ids = -1;
- int undo_button_ids = -1;
- if (is_unified_consent_enabled && is_sync_allowed) {
- source->SetDefaultResource(IDR_DICE_SYNC_CONFIRMATION_HTML);
+ if (is_sync_allowed) {
+ source->SetDefaultResource(IDR_SYNC_CONFIRMATION_HTML);
source->AddResourcePath("sync_confirmation_browser_proxy.html",
- IDR_DICE_SYNC_CONFIRMATION_BROWSER_PROXY_HTML);
+ IDR_SYNC_CONFIRMATION_BROWSER_PROXY_HTML);
source->AddResourcePath("sync_confirmation_browser_proxy.js",
- IDR_DICE_SYNC_CONFIRMATION_BROWSER_PROXY_JS);
+ IDR_SYNC_CONFIRMATION_BROWSER_PROXY_JS);
source->AddResourcePath("sync_confirmation_app.html",
- IDR_DICE_SYNC_CONFIRMATION_APP_HTML);
+ IDR_SYNC_CONFIRMATION_APP_HTML);
source->AddResourcePath("sync_confirmation_app.js",
- IDR_DICE_SYNC_CONFIRMATION_APP_JS);
- source->AddResourcePath("sync_confirmation.js",
- IDR_DICE_SYNC_CONFIRMATION_JS);
+ IDR_SYNC_CONFIRMATION_APP_JS);
+ source->AddResourcePath("sync_confirmation.js", IDR_SYNC_CONFIRMATION_JS);
+ AddStringResource(source, "syncConfirmationTitle",
+ IDS_SYNC_CONFIRMATION_TITLE);
AddStringResource(source, "syncConfirmationSyncInfoTitle",
- IDS_SYNC_CONFIRMATION_UNITY_SYNC_INFO_TITLE);
+ IDS_SYNC_CONFIRMATION_SYNC_INFO_TITLE);
AddStringResource(source, "syncConfirmationSyncInfoDesc",
- IDS_SYNC_CONFIRMATION_UNITY_SYNC_INFO_DESC);
+ IDS_SYNC_CONFIRMATION_SYNC_INFO_DESC);
AddStringResource(source, "syncConfirmationSettingsInfo",
- IDS_SYNC_CONFIRMATION_UNITY_SETTINGS_INFO);
-
+ IDS_SYNC_CONFIRMATION_SETTINGS_INFO);
AddStringResource(source, "syncConfirmationSettingsLabel",
- IDS_SYNC_CONFIRMATION_DICE_SETTINGS_BUTTON_LABEL);
+ IDS_SYNC_CONFIRMATION_SETTINGS_BUTTON_LABEL);
+ AddStringResource(source, "syncConfirmationConfirmLabel",
+ IDS_SYNC_CONFIRMATION_CONFIRM_BUTTON_LABEL);
+ AddStringResource(source, "syncConfirmationUndoLabel", IDS_CANCEL);
constexpr int kAccountPictureSize = 68;
std::string custom_picture_url = profiles::GetPlaceholderAvatarIconUrl();
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
base::Optional<AccountInfo> primary_account_info =
identity_manager->FindExtendedAccountInfoForAccount(
@@ -82,57 +79,26 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui)
.spec();
}
source->AddString("accountPictureUrl", custom_picture_url);
-
- title_ids = IDS_SYNC_CONFIRMATION_DICE_TITLE;
- confirm_button_ids = IDS_SYNC_CONFIRMATION_DICE_CONFIRM_BUTTON_LABEL;
- undo_button_ids = IDS_CANCEL;
- consent_feature_ = consent_auditor::Feature::CHROME_UNIFIED_CONSENT;
} else {
- source->SetDefaultResource(IDR_SYNC_CONFIRMATION_HTML);
- source->AddResourcePath("sync_confirmation.js", IDR_SYNC_CONFIRMATION_JS);
+ source->SetDefaultResource(IDR_SYNC_DISABLED_CONFIRMATION_HTML);
+ source->AddResourcePath("sync_disabled_confirmation.js",
+ IDR_SYNC_DISABLED_CONFIRMATION_JS);
- source->AddBoolean("isSyncAllowed", is_sync_allowed);
-
- AddStringResource(source, "syncConfirmationChromeSyncTitle",
- IDS_SYNC_CONFIRMATION_CHROME_SYNC_TITLE);
- AddStringResource(source, "syncConfirmationChromeSyncBody",
- IDS_SYNC_CONFIRMATION_CHROME_SYNC_MESSAGE);
- AddStringResource(source, "syncConfirmationPersonalizeServicesTitle",
- IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_TITLE);
- AddStringResource(source, "syncConfirmationPersonalizeServicesBody",
- IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_BODY);
- AddStringResource(source, "syncConfirmationSyncSettingsLinkBody",
- IDS_SYNC_CONFIRMATION_SYNC_SETTINGS_LINK_BODY);
+ AddStringResource(source, "syncDisabledConfirmationTitle",
+ IDS_SYNC_DISABLED_CONFIRMATION_CHROME_SYNC_TITLE);
AddStringResource(source, "syncDisabledConfirmationDetails",
IDS_SYNC_DISABLED_CONFIRMATION_DETAILS);
-
- title_ids = AccountConsistencyModeManager::IsDiceEnabledForProfile(profile)
- ? IDS_SYNC_CONFIRMATION_DICE_TITLE
- : IDS_SYNC_CONFIRMATION_TITLE;
- confirm_button_ids = IDS_SETTINGS_TURN_ON;
- undo_button_ids = IDS_CANCEL;
- consent_feature_ = consent_auditor::Feature::CHROME_SYNC;
- if (!is_sync_allowed) {
- title_ids = IDS_SYNC_DISABLED_CONFIRMATION_CHROME_SYNC_TITLE;
- confirm_button_ids = IDS_SYNC_DISABLED_CONFIRMATION_CONFIRM_BUTTON_LABEL;
- undo_button_ids = IDS_SYNC_DISABLED_CONFIRMATION_UNDO_BUTTON_LABEL;
- }
+ AddStringResource(source, "syncDisabledConfirmationConfirmLabel",
+ IDS_SYNC_DISABLED_CONFIRMATION_CONFIRM_BUTTON_LABEL);
+ AddStringResource(source, "syncDisabledConfirmationUndoLabel",
+ IDS_SYNC_DISABLED_CONFIRMATION_UNDO_BUTTON_LABEL);
}
- DCHECK_GE(title_ids, 0);
- DCHECK_GE(confirm_button_ids, 0);
- DCHECK_GE(undo_button_ids, 0);
-
- AddStringResource(source, "syncConfirmationTitle", title_ids);
- AddStringResource(source, "syncConfirmationConfirmLabel", confirm_button_ids);
- AddStringResource(source, "syncConfirmationUndoLabel", undo_button_ids);
-
base::DictionaryValue strings;
webui::SetLoadTimeDataDefaults(
g_browser_process->GetApplicationLocale(), &strings);
source->AddLocalizedStrings(strings);
- DarkModeHandler::Initialize(web_ui, source);
content::WebUIDataSource::Add(profile, source);
}
@@ -140,7 +106,7 @@ SyncConfirmationUI::~SyncConfirmationUI() {}
void SyncConfirmationUI::InitializeMessageHandlerWithBrowser(Browser* browser) {
web_ui()->AddMessageHandler(std::make_unique<SyncConfirmationHandler>(
- browser, js_localized_string_to_ids_map_, consent_feature_));
+ browser, js_localized_string_to_ids_map_));
}
void SyncConfirmationUI::AddStringResource(content::WebUIDataSource* source,
diff --git a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.h b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.h
index a2b773e1b2d..97a063494c2 100644
--- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.h
+++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.h
@@ -44,8 +44,6 @@ class SyncConfirmationUI : public SigninWebDialogUI {
std::unordered_map<std::string, int> js_localized_string_to_ids_map_;
- consent_auditor::Feature consent_feature_;
-
DISALLOW_COPY_AND_ASSIGN(SyncConfirmationUI);
};
diff --git a/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc b/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc
index 91ffa6957bc..1e7be5fffb2 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
@@ -51,7 +51,6 @@
#include "chrome/grit/generated_resources.h"
#include "components/account_id/account_id.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/account_consistency_method.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/storage_partition.h"
@@ -274,7 +273,7 @@ class UserManagerScreenHandler::ProfileUpdateObserver
// UserManagerScreenHandler ---------------------------------------------------
-UserManagerScreenHandler::UserManagerScreenHandler() : weak_ptr_factory_(this) {
+UserManagerScreenHandler::UserManagerScreenHandler() {
profile_attributes_storage_observer_.reset(
new UserManagerScreenHandler::ProfileUpdateObserver(
g_browser_process->profile_manager(), this));
diff --git a/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h b/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h
index 7a138993aa9..8906900c485 100644
--- a/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.h
@@ -124,7 +124,7 @@ class UserManagerScreenHandler
// The CancelableTaskTracker is currently used by GetProfileStatistics
base::CancelableTaskTracker tracker_;
- base::WeakPtrFactory<UserManagerScreenHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<UserManagerScreenHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(UserManagerScreenHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc b/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc
index 5b44baeee16..cd70f2e9a14 100644
--- a/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc
+++ b/chromium/chrome/browser/ui/webui/signin/user_manager_ui.cc
@@ -9,11 +9,11 @@
#include "base/feature_list.h"
#include "base/values.h"
+#include "build/branding_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_shortcut_manager.h"
#include "chrome/browser/signin/signin_util.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
#include "chrome/browser/ui/webui/signin/signin_create_profile_handler.h"
#include "chrome/browser/ui/webui/signin/signin_utils.h"
#include "chrome/browser/ui/webui/signin/user_manager_screen_handler.h"
@@ -43,9 +43,7 @@ UserManagerUI::UserManagerUI(content::WebUI* web_ui) : WebUIController(web_ui) {
Profile* profile = Profile::FromWebUI(web_ui);
// Set up the chrome://md-user-manager/ source.
- auto* user_source = CreateUIDataSource(localized_strings);
- DarkModeHandler::Initialize(web_ui, user_source);
- content::WebUIDataSource::Add(profile, user_source);
+ content::WebUIDataSource::Add(profile, CreateUIDataSource(localized_strings));
// Set up the chrome://theme/ source
content::URLDataSource::Add(profile, std::make_unique<ThemeSource>(profile));
@@ -99,7 +97,7 @@ void UserManagerUI::GetLocalizedStrings(
const std::string& app_locale = g_browser_process->GetApplicationLocale();
webui::SetLoadTimeDataDefaults(app_locale, localized_strings);
-#if defined(GOOGLE_CHROME_BUILD)
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
localized_strings->SetString("buildType", "chrome");
#else
localized_strings->SetString("buildType", "chromium");
diff --git a/chromium/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc
index decbaaf0e62..9e08935bda3 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
@@ -24,7 +24,6 @@
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/ui_test_utils.h"
-#include "components/signin/core/browser/account_consistency_method.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
diff --git a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc
index d358c42a924..6181aae010b 100644
--- a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc
@@ -14,10 +14,10 @@
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/common/url_constants.h"
#include "components/grit/components_resources.h"
-#include "components/signin/core/browser/about_signin_internals.h"
+#include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
-#include "services/identity/public/cpp/identity_manager.h"
namespace {
@@ -78,9 +78,9 @@ bool SignInInternalsUI::OverrideHandleWebUIMessage(
"chrome.signin.getSigninInfo.handleReply",
*about_signin_internals->GetSigninStatus());
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
- identity::AccountsInCookieJarInfo accounts_in_cookie_jar =
+ signin::AccountsInCookieJarInfo accounts_in_cookie_jar =
identity_manager->GetAccountsInCookieJar();
if (accounts_in_cookie_jar.accounts_are_fresh) {
about_signin_internals->OnAccountsInCookieUpdated(
diff --git a/chromium/chrome/browser/ui/webui/site_settings_helper.cc b/chromium/chrome/browser/ui/webui/site_settings_helper.cc
index 6dd81e16bac..701e6da03b0 100644
--- a/chromium/chrome/browser/ui/webui/site_settings_helper.cc
+++ b/chromium/chrome/browser/ui/webui/site_settings_helper.cc
@@ -116,6 +116,9 @@ const ContentSettingsTypeNameEntry kContentSettingsTypeGroupNames[] = {
{CONTENT_SETTINGS_TYPE_BACKGROUND_FETCH, nullptr},
{CONTENT_SETTINGS_TYPE_INTENT_PICKER_DISPLAY, nullptr},
{CONTENT_SETTINGS_TYPE_PERIODIC_BACKGROUND_SYNC, nullptr},
+ {CONTENT_SETTINGS_TYPE_WAKE_LOCK_SCREEN, nullptr},
+ {CONTENT_SETTINGS_TYPE_WAKE_LOCK_SYSTEM, nullptr},
+ {CONTENT_SETTINGS_TYPE_LEGACY_COOKIE_ACCESS, nullptr},
};
static_assert(base::size(kContentSettingsTypeGroupNames) ==
// ContentSettingsType starts at -1, so add 1 here.
diff --git a/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn
index f83f5c25536..0575b4b15d2 100644
--- a/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn
+++ b/chromium/chrome/browser/ui/webui/snippets_internals/BUILD.gn
@@ -8,4 +8,7 @@ mojom("mojo_bindings") {
sources = [
"snippets_internals.mojom",
]
+
+ # TODO(https://crbug.com/968369): Change to use new names.
+ use_old_js_lite_bindings_names = true
}
diff --git a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc
index c776a28b311..28d6c59af0f 100644
--- a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc
+++ b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc
@@ -23,12 +23,12 @@
#include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
#include "chrome/browser/supervised_user/supervised_user_url_filter.h"
#include "chrome/common/channel_info.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/supervised_user_error_page/supervised_user_error_page.h"
#include "components/url_formatter/url_fixer.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_ui.h"
-#include "services/identity/public/cpp/identity_manager.h"
using content::BrowserThread;
@@ -118,7 +118,7 @@ std::string FilteringBehaviorReasonToString(
} // namespace
SupervisedUserInternalsMessageHandler::SupervisedUserInternalsMessageHandler()
- : scoped_observer_(this), weak_factory_(this) {}
+ : scoped_observer_(this) {}
SupervisedUserInternalsMessageHandler::
~SupervisedUserInternalsMessageHandler() {
@@ -216,7 +216,7 @@ void SupervisedUserInternalsMessageHandler::SendBasicInfo() {
FilteringBehaviorToString(
filter->GetDefaultFilteringBehavior()));
- identity::IdentityManager* identity_manager =
+ signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile);
// |identity_manager| is null in incognito and guest profiles.
if (identity_manager) {
diff --git a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h
index aa6c3d9b680..7be0cfac16b 100644
--- a/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h
+++ b/chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.h
@@ -65,7 +65,8 @@ class SupervisedUserInternalsMessageHandler
ScopedObserver<SupervisedUserURLFilter, SupervisedUserURLFilter::Observer>
scoped_observer_;
- base::WeakPtrFactory<SupervisedUserInternalsMessageHandler> weak_factory_;
+ base::WeakPtrFactory<SupervisedUserInternalsMessageHandler> weak_factory_{
+ this};
DISALLOW_COPY_AND_ASSIGN(SupervisedUserInternalsMessageHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc b/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc
index e5006aac2a8..cf5c1ba9541 100644
--- a/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc
+++ b/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.cc
@@ -60,8 +60,7 @@ void ConvertExtensionStatusToDictionary(
} // namespace
ExtensionStatusesHandler::ExtensionStatusesHandler(Profile* profile)
- : profile_(profile),
- weak_ptr_factory_(this) {}
+ : profile_(profile) {}
ExtensionStatusesHandler::~ExtensionStatusesHandler() {}
diff --git a/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.h b/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.h
index 26fef71c775..60880338cc5 100644
--- a/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.h
+++ b/chromium/chrome/browser/ui/webui/sync_file_system_internals/extension_statuses_handler.h
@@ -37,7 +37,7 @@ class ExtensionStatusesHandler : public content::WebUIMessageHandler {
void DidGetExtensionStatuses(const base::ListValue& list);
Profile* profile_;
- base::WeakPtrFactory<ExtensionStatusesHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<ExtensionStatusesHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ExtensionStatusesHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.cc b/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.cc
index 67a37f009d0..050b6031de3 100644
--- a/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.cc
+++ b/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.cc
@@ -25,8 +25,7 @@ using sync_file_system::SyncServiceState;
namespace syncfs_internals {
FileMetadataHandler::FileMetadataHandler(Profile* profile)
- : profile_(profile),
- weak_factory_(this) {}
+ : profile_(profile) {}
FileMetadataHandler::~FileMetadataHandler() {}
diff --git a/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.h b/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.h
index eac5ccc6239..5a387e05e12 100644
--- a/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.h
+++ b/chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.h
@@ -38,7 +38,7 @@ class FileMetadataHandler : public content::WebUIMessageHandler {
void DidGetFileMetadata(const base::ListValue& files);
Profile* profile_;
- base::WeakPtrFactory<FileMetadataHandler> weak_factory_;
+ base::WeakPtrFactory<FileMetadataHandler> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(FileMetadataHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js b/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js
index 9a179ff2576..ede567340a8 100644
--- a/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js
+++ b/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js
@@ -260,9 +260,8 @@ GEN('#else');
// set.
TEST_F('SyncInternalsWebUITest', 'SyncDisabledByDefault', function() {
expectTrue(this.hasInDetails(true, 'Transport State', 'Disabled'));
- // TODO(crbug.com/906034,crbug.com/973770): Sort out the proper default value
- // for IsSyncRequested() and possibly add the "User choice" disable reason.
- expectTrue(this.hasInDetails(true, 'Disable Reasons', 'Not signed in'));
+ expectTrue(
+ this.hasInDetails(true, 'Disable Reasons', 'Not signed in, User choice'));
expectTrue(this.hasInDetails(true, 'Username', ''));
});
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 4b2ed4b50a9..69dc7e8f23e 100644
--- a/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc
+++ b/chromium/chrome/browser/ui/webui/sync_internals_message_handler.cc
@@ -73,8 +73,7 @@ SyncInternalsMessageHandler::SyncInternalsMessageHandler()
SyncInternalsMessageHandler::SyncInternalsMessageHandler(
AboutSyncDataDelegate about_sync_data_delegate)
: include_specifics_(GetIncludeSpecificsInitialState()),
- about_sync_data_delegate_(std::move(about_sync_data_delegate)),
- weak_ptr_factory_(this) {}
+ about_sync_data_delegate_(std::move(about_sync_data_delegate)) {}
SyncInternalsMessageHandler::~SyncInternalsMessageHandler() {
UnregisterModelNotifications();
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 73c613c6191..8d99944f5a4 100644
--- a/chromium/chrome/browser/ui/webui/sync_internals_message_handler.h
+++ b/chromium/chrome/browser/ui/webui/sync_internals_message_handler.h
@@ -150,7 +150,7 @@ class SyncInternalsMessageHandler : public content::WebUIMessageHandler,
// An abstraction of who creates the about sync info value map.
AboutSyncDataDelegate about_sync_data_delegate_;
- base::WeakPtrFactory<SyncInternalsMessageHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<SyncInternalsMessageHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SyncInternalsMessageHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/system_info_ui.cc b/chromium/chrome/browser/ui/webui/system_info_ui.cc
index f366029fe83..cf886af54c8 100644
--- a/chromium/chrome/browser/ui/webui/system_info_ui.cc
+++ b/chromium/chrome/browser/ui/webui/system_info_ui.cc
@@ -88,7 +88,7 @@ class SystemInfoHandler : public WebUIMessageHandler {
void OnSystemInfo(std::unique_ptr<SystemLogsResponse> sys_info);
private:
- base::WeakPtrFactory<SystemInfoHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<SystemInfoHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SystemInfoHandler);
};
@@ -97,7 +97,7 @@ class SystemInfoHandler : public WebUIMessageHandler {
// SystemInfoHandler
//
////////////////////////////////////////////////////////////////////////////////
-SystemInfoHandler::SystemInfoHandler() : weak_ptr_factory_(this) {}
+SystemInfoHandler::SystemInfoHandler() {}
SystemInfoHandler::~SystemInfoHandler() {}
diff --git a/chromium/chrome/browser/ui/webui/test_data_source.cc b/chromium/chrome/browser/ui/webui/test_data_source.cc
new file mode 100644
index 00000000000..b857b4fd032
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/test_data_source.cc
@@ -0,0 +1,103 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/test_data_source.h"
+
+#include <memory>
+
+#include "base/base_paths.h"
+#include "base/files/file_path.h"
+#include "base/files/file_util.h"
+#include "base/memory/ref_counted_memory.h"
+#include "base/path_service.h"
+#include "base/strings/string_util.h"
+#include "base/task/post_task.h"
+#include "base/task/task_traits.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/common/chrome_paths.h"
+#include "chrome/common/url_constants.h"
+#include "chrome/common/webui_url_constants.h"
+#include "content/public/browser/url_data_source.h"
+#include "content/public/common/url_constants.h"
+
+namespace {
+const char kModuleQuery[] = "module=";
+} // namespace
+
+std::string TestDataSource::GetSource() {
+ return "test";
+}
+
+void TestDataSource::StartDataRequest(
+ const std::string& path,
+ const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
+ const content::URLDataSource::GotDataCallback& callback) {
+ base::PostTaskWithTraits(
+ FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
+ base::BindOnce(&TestDataSource::ReadFile, base::Unretained(this), path,
+ callback));
+}
+
+std::string TestDataSource::GetMimeType(const std::string& path) {
+ if (base::EndsWith(path, ".html", base::CompareCase::INSENSITIVE_ASCII) ||
+ base::StartsWith(GetURLForPath(path).query(), kModuleQuery,
+ base::CompareCase::INSENSITIVE_ASCII)) {
+ // Direct request for HTML, or autogenerated HTML response for module query.
+ return "text/html";
+ }
+ // The test data source currently only serves HTML and JS.
+ CHECK(base::EndsWith(path, ".js", base::CompareCase::INSENSITIVE_ASCII));
+ return "application/javascript";
+}
+
+bool TestDataSource::ShouldServeMimeTypeAsContentTypeHeader() {
+ return true;
+}
+
+bool TestDataSource::AllowCaching() {
+ return false;
+}
+
+std::string TestDataSource::GetContentSecurityPolicyScriptSrc() {
+ return "script-src chrome://* 'self';";
+}
+
+GURL TestDataSource::GetURLForPath(const std::string& path) {
+ return GURL(std::string(content::kChromeUIScheme) + "://" + GetSource() +
+ "/" + path);
+}
+
+void TestDataSource::ReadFile(
+ const std::string& path,
+ const content::URLDataSource::GotDataCallback& callback) {
+ if (test_data_.empty()) {
+ CHECK(base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_));
+ CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &source_root_));
+ }
+ base::FilePath root = test_data_.Append(FILE_PATH_LITERAL("webui"));
+ std::string content;
+
+ GURL url = GetURLForPath(path);
+ CHECK(url.is_valid());
+ if (base::StartsWith(url.query(), kModuleQuery,
+ base::CompareCase::INSENSITIVE_ASCII)) {
+ std::string js_path = url.query().substr(strlen(kModuleQuery));
+ base::FilePath file_path =
+ root.Append(base::FilePath::FromUTF8Unsafe(js_path));
+ // Do some basic validation of the JS file path provided in the query.
+ CHECK_EQ(file_path.Extension(), FILE_PATH_LITERAL(".js"));
+ CHECK(base::PathExists(file_path))
+ << url.spec() << "=" << file_path.value();
+ content = "<script type=\"module\" src=\"" + js_path + "\"></script>";
+ } else {
+ base::FilePath file_path =
+ root.Append(base::FilePath::FromUTF8Unsafe(path));
+ CHECK(base::ReadFileToString(file_path, &content))
+ << url.spec() << "=" << file_path.value();
+ }
+
+ scoped_refptr<base::RefCountedString> response =
+ base::RefCountedString::TakeString(&content);
+ callback.Run(response.get());
+}
diff --git a/chromium/chrome/browser/ui/webui/test_data_source.h b/chromium/chrome/browser/ui/webui/test_data_source.h
new file mode 100644
index 00000000000..680979c02c1
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/test_data_source.h
@@ -0,0 +1,48 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_TEST_DATA_SOURCE_H_
+#define CHROME_BROWSER_UI_WEBUI_TEST_DATA_SOURCE_H_
+
+#include <string>
+
+#include "base/files/file_path.h"
+#include "base/macros.h"
+#include "content/public/browser/url_data_source.h"
+#include "url/gurl.h"
+
+// Serves files at chrome://test/ from //src/chrome/test/data/webui.
+class TestDataSource : public content::URLDataSource {
+ public:
+ TestDataSource() = default;
+ ~TestDataSource() override = default;
+
+ private:
+ void StartDataRequest(
+ const std::string& path,
+ const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
+ const content::URLDataSource::GotDataCallback& callback) override;
+
+ std::string GetMimeType(const std::string& path) override;
+
+ bool ShouldServeMimeTypeAsContentTypeHeader() override;
+
+ bool AllowCaching() override;
+
+ std::string GetSource() override;
+
+ std::string GetContentSecurityPolicyScriptSrc() override;
+
+ GURL GetURLForPath(const std::string& path);
+
+ void ReadFile(const std::string& path,
+ const content::URLDataSource::GotDataCallback& callback);
+
+ base::FilePath test_data_;
+ base::FilePath source_root_;
+
+ DISALLOW_COPY_AND_ASSIGN(TestDataSource);
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_TEST_DATA_SOURCE_H_
diff --git a/chromium/chrome/browser/ui/webui/theme_source.cc b/chromium/chrome/browser/ui/webui/theme_source.cc
index a1d4d24497f..673b625f6e0 100644
--- a/chromium/chrome/browser/ui/webui/theme_source.cc
+++ b/chromium/chrome/browser/ui/webui/theme_source.cc
@@ -8,6 +8,7 @@
#include "base/memory/ref_counted_memory.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/post_task.h"
+#include "build/branding_buildflags.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/resources_util.h"
#include "chrome/browser/search/instant_io_context.h"
@@ -73,7 +74,7 @@ ThemeSource::ThemeSource(Profile* profile) : profile_(profile) {}
ThemeSource::~ThemeSource() = default;
-std::string ThemeSource::GetSource() const {
+std::string ThemeSource::GetSource() {
return chrome::kChromeUIThemeHost;
}
@@ -100,7 +101,7 @@ void ThemeSource::StartDataRequest(
int resource_id = -1;
if (parsed_path == "current-channel-logo") {
switch (chrome::GetChannel()) {
-#if defined(GOOGLE_CHROME_BUILD)
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
case version_info::Channel::CANARY:
resource_id = IDR_PRODUCT_LOGO_32_CANARY;
break;
@@ -157,14 +158,14 @@ void ThemeSource::StartDataRequest(
}
}
-std::string ThemeSource::GetMimeType(const std::string& path) const {
+std::string ThemeSource::GetMimeType(const std::string& path) {
std::string parsed_path;
webui::ParsePathAndScale(GetThemeUrl(path), &parsed_path, nullptr);
return IsNewTabCssPath(parsed_path) ? "text/css" : "image/png";
}
scoped_refptr<base::SingleThreadTaskRunner>
-ThemeSource::TaskRunnerForRequestPath(const std::string& path) const {
+ThemeSource::TaskRunnerForRequestPath(const std::string& path) {
std::string parsed_path;
webui::ParsePathAndScale(GetThemeUrl(path), &parsed_path, nullptr);
@@ -181,14 +182,14 @@ ThemeSource::TaskRunnerForRequestPath(const std::string& path) const {
: nullptr;
}
-bool ThemeSource::AllowCaching() const {
+bool ThemeSource::AllowCaching() {
return false;
}
bool ThemeSource::ShouldServiceRequest(
const GURL& url,
content::ResourceContext* resource_context,
- int render_process_id) const {
+ int render_process_id) {
return url.SchemeIs(chrome::kChromeSearchScheme)
? InstantIOContext::ShouldServiceRequest(url, resource_context,
render_process_id)
diff --git a/chromium/chrome/browser/ui/webui/theme_source.h b/chromium/chrome/browser/ui/webui/theme_source.h
index 724e01fa27c..aa323d6efbc 100644
--- a/chromium/chrome/browser/ui/webui/theme_source.h
+++ b/chromium/chrome/browser/ui/webui/theme_source.h
@@ -21,18 +21,18 @@ class ThemeSource : public content::URLDataSource {
~ThemeSource() override;
// content::URLDataSource implementation.
- std::string GetSource() const override;
+ std::string GetSource() override;
void StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override;
- std::string GetMimeType(const std::string& path) const override;
+ std::string GetMimeType(const std::string& path) override;
scoped_refptr<base::SingleThreadTaskRunner> TaskRunnerForRequestPath(
- const std::string& path) const override;
- bool AllowCaching() const override;
+ const std::string& path) override;
+ bool AllowCaching() override;
bool ShouldServiceRequest(const GURL& url,
content::ResourceContext* resource_context,
- int render_process_id) const override;
+ int render_process_id) override;
private:
// Fetches and sends the theme bitmap.
diff --git a/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn b/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn
index d193360fcec..5229f5ba6f3 100644
--- a/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn
+++ b/chromium/chrome/browser/ui/webui/usb_internals/BUILD.gn
@@ -13,4 +13,7 @@ mojom("mojo_bindings") {
"//services/device/public/mojom:usb",
"//services/device/public/mojom:usb_test",
]
+
+ # TODO(https://crbug.com/968369): Change to use new names.
+ use_old_js_lite_bindings_names = true
}
diff --git a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc
index 3775ba9cf0a..c5989ed4357 100644
--- a/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc
+++ b/chromium/chrome/browser/ui/webui/usb_internals/usb_internals_page_handler.cc
@@ -6,7 +6,7 @@
#include <utility>
-#include "content/public/common/service_manager_connection.h"
+#include "content/public/browser/system_connector.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
@@ -19,15 +19,13 @@ UsbInternalsPageHandler::~UsbInternalsPageHandler() {}
void UsbInternalsPageHandler::BindTestInterface(
device::mojom::UsbDeviceManagerTestRequest request) {
// Forward the request to the DeviceService.
- content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->BindInterface(device::mojom::kServiceName, std::move(request));
+ content::GetSystemConnector()->BindInterface(device::mojom::kServiceName,
+ std::move(request));
}
void UsbInternalsPageHandler::BindUsbDeviceManagerInterface(
device::mojom::UsbDeviceManagerRequest request) {
// Forward the request to the DeviceService.
- content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->BindInterface(device::mojom::kServiceName, std::move(request));
+ content::GetSystemConnector()->BindInterface(device::mojom::kServiceName,
+ std::move(request));
}
diff --git a/chromium/chrome/browser/ui/webui/version_handler.cc b/chromium/chrome/browser/ui/webui/version_handler.cc
index 3737138f7d2..b62cff1dceb 100644
--- a/chromium/chrome/browser/ui/webui/version_handler.cc
+++ b/chromium/chrome/browser/ui/webui/version_handler.cc
@@ -56,7 +56,7 @@ void GetFilePaths(const base::FilePath& profile_path,
} // namespace
-VersionHandler::VersionHandler() : weak_ptr_factory_(this) {}
+VersionHandler::VersionHandler() {}
VersionHandler::~VersionHandler() {
}
diff --git a/chromium/chrome/browser/ui/webui/version_handler.h b/chromium/chrome/browser/ui/webui/version_handler.h
index d121739f25c..e4c27a5308e 100644
--- a/chromium/chrome/browser/ui/webui/version_handler.h
+++ b/chromium/chrome/browser/ui/webui/version_handler.h
@@ -38,7 +38,7 @@ class VersionHandler : public content::WebUIMessageHandler {
void OnGotPlugins(const std::vector<content::WebPluginInfo>& plugins);
// Factory for the creating refs in callbacks.
- base::WeakPtrFactory<VersionHandler> weak_ptr_factory_;
+ base::WeakPtrFactory<VersionHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(VersionHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc
index 501e27d693a..07917010b9f 100644
--- a/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc
+++ b/chromium/chrome/browser/ui/webui/version_handler_chromeos.cc
@@ -9,7 +9,6 @@
#include "chrome/common/channel_info.h"
#include "components/version_info/channel.h"
#include "content/public/browser/web_ui.h"
-#include "ui/base/ui_base_features.h"
VersionHandlerChromeOS::VersionHandlerChromeOS() : weak_factory_(this) {}
@@ -40,15 +39,7 @@ void VersionHandlerChromeOS::HandleRequestVersionInfo(
}
void VersionHandlerChromeOS::OnVersion(const std::string& version) {
- std::string os_version = version;
- // Put a string in about:version so it's easy to copy/paste into bug reports,
- // similar to the OS label on the login/lock screen in canary and dev.
- // String does not need to be localized since it is a feature name.
- if (chrome::GetChannel() <= version_info::Channel::DEV &&
- ::features::IsSingleProcessMash()) {
- os_version += " SingleProcessMash";
- }
- base::Value arg(os_version);
+ base::Value arg(version);
web_ui()->CallJavascriptFunctionUnsafe("returnOsVersion", arg);
}
diff --git a/chromium/chrome/browser/ui/webui/version_handler_win.cc b/chromium/chrome/browser/ui/webui/version_handler_win.cc
index 7f431234f23..3540aa13b9b 100644
--- a/chromium/chrome/browser/ui/webui/version_handler_win.cc
+++ b/chromium/chrome/browser/ui/webui/version_handler_win.cc
@@ -8,74 +8,9 @@
#include "base/strings/stringprintf.h"
#include "base/task/post_task.h"
#include "base/win/windows_version.h"
+#include "chrome/browser/ui/webui/version_util_win.h"
#include "content/public/browser/web_ui.h"
-namespace {
-
-// Return the marketing version of Windows OS, this may return an empty string
-// if values returned by base::win::OSinfo are not defined below.
-std::string FullWindowsVersion() {
- std::string version;
- base::win::OSInfo* gi = base::win::OSInfo::GetInstance();
- const int major = gi->version_number().major;
- const int minor = gi->version_number().minor;
- const int build = gi->version_number().build;
- const int patch = gi->version_number().patch;
- // Server or Desktop
- const bool server =
- gi->version_type() == base::win::VersionType::SUITE_SERVER;
- // Service Pack
- const std::string sp = gi->service_pack_str();
-
- if (major == 10) {
- version += (server) ? "Server OS" : "10 OS";
- } else if (major == 6) {
- switch (minor) {
- case 0:
- // Windows Vista or Server 2008
- version += (server) ? "Server 2008 " : "Vista ";
- version += sp;
- break;
- case 1:
- // Windows 7 or Server 2008 R2
- version += (server) ? "Server 2008 R2 " : "7 ";
- version += sp;
- break;
- case 2:
- // Windows 8 or Server 2012
- version += (server) ? "Server 2012" : "8";
- break;
- case 3:
- // Windows 8.1 or Server 2012 R2
- version += (server) ? "Server 2012 R2" : "8.1";
- break;
- default:
- // unknown version
- return base::StringPrintf("unknown version 6.%d", minor);
- }
- } else if ((major == 5) && (minor > 0)) {
- // Windows XP or Server 2003
- version += (server) ? "Server 2003 " : "XP ";
- version += sp;
- } else {
- // unknown version
- return base::StringPrintf("unknown version %d.%d", major, minor);
- }
-
- const std::string release_id = gi->release_id();
-
- if (!release_id.empty())
- version += " Version " + release_id;
-
- if (patch > 0)
- version += base::StringPrintf(" (Build %d.%d)", build, patch);
- else
- version += base::StringPrintf(" (Build %d)", build);
- return version;
-}
-
-} // namespace
-
VersionHandlerWindows::VersionHandlerWindows() : weak_factory_(this) {}
VersionHandlerWindows::~VersionHandlerWindows() {}
@@ -84,8 +19,8 @@ void VersionHandlerWindows::HandleRequestVersionInfo(
const base::ListValue* args) {
// Start the asynchronous load of the versions.
base::PostTaskWithTraitsAndReplyWithResult(
- FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
- base::BindOnce(&FullWindowsVersion),
+ FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
+ base::BindOnce(&version_utils::win::GetFullWindowsVersion),
base::BindOnce(&VersionHandlerWindows::OnVersion,
weak_factory_.GetWeakPtr()));
@@ -100,5 +35,5 @@ void VersionHandlerWindows::OnVersion(const std::string& version) {
// static
std::string VersionHandlerWindows::GetFullWindowsVersionForTesting() {
- return FullWindowsVersion();
+ return version_utils::win::GetFullWindowsVersion();
}
diff --git a/chromium/chrome/browser/ui/webui/version_ui.cc b/chromium/chrome/browser/ui/webui/version_ui.cc
index a30392ab230..e0759744e1f 100644
--- a/chromium/chrome/browser/ui/webui/version_ui.cc
+++ b/chromium/chrome/browser/ui/webui/version_ui.cc
@@ -12,7 +12,9 @@
#include "build/build_config.h"
#include "chrome/browser/chrome_content_browser_client.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/webui/localized_string.h"
#include "chrome/browser/ui/webui/version_handler.h"
+#include "chrome/browser/ui/webui/version_util_win.h"
#include "chrome/common/channel_info.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/chromium_strings.h"
@@ -38,9 +40,12 @@
#include "chrome/browser/ui/webui/version_handler_chromeos.h"
#endif
+#if defined(OS_MACOSX)
+#include "base/mac/mac_util.h"
+#endif
+
#if defined(OS_WIN)
#include "chrome/browser/ui/webui/version_handler_win.h"
-#include "chrome/install_static/install_details.h"
#endif
using content::WebUIDataSource;
@@ -50,65 +55,105 @@ namespace {
WebUIDataSource* CreateVersionUIDataSource() {
WebUIDataSource* html_source =
WebUIDataSource::Create(chrome::kChromeUIVersionHost);
+ // These localized strings are used to label version details.
+ static constexpr LocalizedString kStrings[] = {
+ {version_ui::kTitle, IDS_VERSION_UI_TITLE},
+ {version_ui::kApplicationLabel, IDS_PRODUCT_NAME},
+ {version_ui::kCompany, IDS_ABOUT_VERSION_COMPANY_NAME},
+ {version_ui::kRevision, IDS_VERSION_UI_REVISION},
+ {version_ui::kUserAgentName, IDS_VERSION_UI_USER_AGENT},
+ {version_ui::kCommandLineName, IDS_VERSION_UI_COMMAND_LINE},
+ {version_ui::kExecutablePathName, IDS_VERSION_UI_EXECUTABLE_PATH},
+ {version_ui::kProfilePathName, IDS_VERSION_UI_PROFILE_PATH},
+ {version_ui::kVariationsName, IDS_VERSION_UI_VARIATIONS},
+ {version_ui::kVariationsCmdName, IDS_VERSION_UI_VARIATIONS_CMD},
+#if defined(OS_CHROMEOS)
+ {version_ui::kARC, IDS_ARC_LABEL},
+ {version_ui::kPlatform, IDS_PLATFORM_LABEL},
+ {version_ui::kCustomizationId, IDS_VERSION_UI_CUSTOMIZATION_ID},
+ {version_ui::kFirmwareVersion, IDS_VERSION_UI_FIRMWARE_VERSION},
+#else
+ {version_ui::kOSName, IDS_VERSION_UI_OS},
+#endif // OS_CHROMEOS
+#if defined(OS_ANDROID)
+ {version_ui::kGmsName, IDS_VERSION_UI_GMS},
+#endif // OS_ANDROID
+ };
+ AddLocalizedStringsBulk(html_source, kStrings, base::size(kStrings));
+
+ VersionUI::AddVersionDetailStrings(html_source);
- // Localized and data strings.
- html_source->AddLocalizedString(version_ui::kTitle, IDS_VERSION_UI_TITLE);
- html_source->AddLocalizedString(version_ui::kApplicationLabel,
- IDS_PRODUCT_NAME);
+ html_source->SetJsonPath("strings.js");
+ html_source->AddResourcePath(version_ui::kVersionJS, IDR_VERSION_UI_JS);
+ html_source->AddResourcePath(version_ui::kAboutVersionCSS,
+ IDR_VERSION_UI_CSS);
+ html_source->SetDefaultResource(IDR_VERSION_UI_HTML);
+ return html_source;
+}
+
+} // namespace
+
+VersionUI::VersionUI(content::WebUI* web_ui)
+ : content::WebUIController(web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+
+#if defined(OS_CHROMEOS)
+ web_ui->AddMessageHandler(std::make_unique<VersionHandlerChromeOS>());
+#elif defined(OS_WIN)
+ web_ui->AddMessageHandler(std::make_unique<VersionHandlerWindows>());
+#else
+ web_ui->AddMessageHandler(std::make_unique<VersionHandler>());
+#endif
+
+#if !defined(OS_ANDROID)
+ // Set up the chrome://theme/ source.
+ content::URLDataSource::Add(profile, std::make_unique<ThemeSource>(profile));
+#endif
+
+ WebUIDataSource::Add(profile, CreateVersionUIDataSource());
+}
+
+VersionUI::~VersionUI() {}
+
+// static
+void VersionUI::AddVersionDetailStrings(content::WebUIDataSource* html_source) {
+ html_source->AddLocalizedString(version_ui::kOfficial,
+ version_info::IsOfficialBuild()
+ ? IDS_VERSION_UI_OFFICIAL
+ : IDS_VERSION_UI_UNOFFICIAL);
+ html_source->AddLocalizedString(
+ version_ui::kVersionBitSize,
+ sizeof(void*) == 8 ? IDS_VERSION_UI_64BIT : IDS_VERSION_UI_32BIT);
+
+ // Data strings.
html_source->AddString(version_ui::kVersion,
version_info::GetVersionNumber());
html_source->AddString(version_ui::kVersionModifier,
chrome::GetChannelName());
html_source->AddString(version_ui::kJSEngine, "V8");
html_source->AddString(version_ui::kJSVersion, V8_VERSION_STRING);
- html_source->AddLocalizedString(version_ui::kCompany,
- IDS_ABOUT_VERSION_COMPANY_NAME);
html_source->AddString(
version_ui::kCopyright,
base::i18n::MessageFormatter::FormatWithNumberedArgs(
l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_COPYRIGHT),
base::Time::Now()));
- html_source->AddLocalizedString(version_ui::kRevision,
- IDS_VERSION_UI_REVISION);
html_source->AddString(version_ui::kCL, version_info::GetLastChange());
- html_source->AddLocalizedString(version_ui::kOfficial,
- version_info::IsOfficialBuild()
- ? IDS_VERSION_UI_OFFICIAL
- : IDS_VERSION_UI_UNOFFICIAL);
- html_source->AddLocalizedString(version_ui::kUserAgentName,
- IDS_VERSION_UI_USER_AGENT);
html_source->AddString(version_ui::kUserAgent, GetUserAgent());
- html_source->AddLocalizedString(version_ui::kCommandLineName,
- IDS_VERSION_UI_COMMAND_LINE);
// Note that the executable path and profile path are retrieved asynchronously
// and returned in VersionHandler::OnGotFilePaths. The area is initially
// blank.
- html_source->AddLocalizedString(version_ui::kExecutablePathName,
- IDS_VERSION_UI_EXECUTABLE_PATH);
html_source->AddString(version_ui::kExecutablePath, std::string());
- html_source->AddLocalizedString(version_ui::kProfilePathName,
- IDS_VERSION_UI_PROFILE_PATH);
html_source->AddString(version_ui::kProfilePath, std::string());
- html_source->AddLocalizedString(version_ui::kVariationsName,
- IDS_VERSION_UI_VARIATIONS);
- html_source->AddLocalizedString(version_ui::kVariationsCmdName,
- IDS_VERSION_UI_VARIATIONS_CMD);
-#if defined(OS_CHROMEOS)
- html_source->AddLocalizedString(version_ui::kARC, IDS_ARC_LABEL);
- html_source->AddLocalizedString(version_ui::kPlatform, IDS_PLATFORM_LABEL);
- html_source->AddLocalizedString(version_ui::kCustomizationId,
- IDS_VERSION_UI_CUSTOMIZATION_ID);
- html_source->AddLocalizedString(version_ui::kFirmwareVersion,
- IDS_VERSION_UI_FIRMWARE_VERSION);
-#else
- html_source->AddLocalizedString(version_ui::kOSName, IDS_VERSION_UI_OS);
+
+#if defined(OS_MACOSX)
+ html_source->AddString(version_ui::kOSType, base::mac::GetOSDisplayName());
+#elif !defined(OS_CHROMEOS)
html_source->AddString(version_ui::kOSType, version_info::GetOSType());
-#endif // OS_CHROMEOS
+#endif // OS_MACOSX
#if defined(OS_ANDROID)
html_source->AddString(version_ui::kOSVersion,
AndroidAboutAppInfo::GetOsInfo());
- html_source->AddLocalizedString(version_ui::kGmsName, IDS_VERSION_UI_GMS);
html_source->AddString(version_ui::kGmsVersion,
AndroidAboutAppInfo::GetGmsInfo());
#else
@@ -118,9 +163,6 @@ WebUIDataSource* CreateVersionUIDataSource() {
html_source->AddString(version_ui::kFlashVersion, std::string());
#endif // OS_ANDROID
- html_source->AddLocalizedString(
- version_ui::kVersionBitSize,
- sizeof(void*) == 8 ? IDS_VERSION_UI_64BIT : IDS_VERSION_UI_32BIT);
#if defined(OS_WIN)
html_source->AddString(
@@ -138,45 +180,9 @@ WebUIDataSource* CreateVersionUIDataSource() {
#endif
#if defined(OS_WIN)
- base::string16 update_cohort_name =
- install_static::InstallDetails::Get().update_cohort_name();
- if (!update_cohort_name.empty()) {
- html_source->AddString(version_ui::kUpdateCohortName,
- l10n_util::GetStringFUTF16(
- IDS_VERSION_UI_COHORT_NAME, update_cohort_name));
- } else {
- html_source->AddString(version_ui::kUpdateCohortName, std::string());
- }
+ html_source->AddString(version_ui::kUpdateCohortName,
+ version_utils::win::GetCohortVersionInfo());
#endif // defined(OS_WIN)
- html_source->SetJsonPath("strings.js");
- html_source->AddResourcePath(version_ui::kVersionJS, IDR_VERSION_UI_JS);
- html_source->AddResourcePath(version_ui::kAboutVersionCSS,
- IDR_VERSION_UI_CSS);
- html_source->SetDefaultResource(IDR_VERSION_UI_HTML);
- return html_source;
-}
-
-} // namespace
-
-VersionUI::VersionUI(content::WebUI* web_ui)
- : content::WebUIController(web_ui) {
- Profile* profile = Profile::FromWebUI(web_ui);
-
-#if defined(OS_CHROMEOS)
- web_ui->AddMessageHandler(std::make_unique<VersionHandlerChromeOS>());
-#elif defined(OS_WIN)
- web_ui->AddMessageHandler(std::make_unique<VersionHandlerWindows>());
-#else
- web_ui->AddMessageHandler(std::make_unique<VersionHandler>());
-#endif
-
-#if !defined(OS_ANDROID)
- // Set up the chrome://theme/ source.
- content::URLDataSource::Add(profile, std::make_unique<ThemeSource>(profile));
-#endif
-
- WebUIDataSource::Add(profile, CreateVersionUIDataSource());
+ html_source->AddString(version_ui::kSanitizer, version_info::GetSanitizerList());
}
-
-VersionUI::~VersionUI() {}
diff --git a/chromium/chrome/browser/ui/webui/version_ui.h b/chromium/chrome/browser/ui/webui/version_ui.h
index 9de2301fd8e..1b0cc1a22f1 100644
--- a/chromium/chrome/browser/ui/webui/version_ui.h
+++ b/chromium/chrome/browser/ui/webui/version_ui.h
@@ -7,6 +7,7 @@
#include "base/macros.h"
#include "content/public/browser/web_ui_controller.h"
+#include "content/public/browser/web_ui_data_source.h"
// The WebUI handler for chrome://version.
class VersionUI : public content::WebUIController {
@@ -14,6 +15,10 @@ class VersionUI : public content::WebUIController {
explicit VersionUI(content::WebUI* web_ui);
~VersionUI() override;
+ // Loads a data source with many named details comprising version info.
+ // The keys are from version_ui_constants.
+ static void AddVersionDetailStrings(content::WebUIDataSource* html_source);
+
private:
DISALLOW_COPY_AND_ASSIGN(VersionUI);
};
diff --git a/chromium/chrome/browser/ui/webui/version_util_win.cc b/chromium/chrome/browser/ui/webui/version_util_win.cc
new file mode 100644
index 00000000000..aeca237461c
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/version_util_win.cc
@@ -0,0 +1,88 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/version_util_win.h"
+
+#include "base/strings/stringprintf.h"
+#include "base/win/windows_version.h"
+#include "chrome/install_static/install_details.h"
+#include "components/strings/grit/components_strings.h"
+#include "ui/base/l10n/l10n_util.h"
+
+namespace version_utils {
+namespace win {
+
+std::string GetFullWindowsVersion() {
+ std::string version;
+ base::win::OSInfo* gi = base::win::OSInfo::GetInstance();
+ const int major = gi->version_number().major;
+ const int minor = gi->version_number().minor;
+ const int build = gi->version_number().build;
+ const int patch = gi->version_number().patch;
+ // Server or Desktop
+ const bool server =
+ gi->version_type() == base::win::VersionType::SUITE_SERVER;
+ // Service Pack
+ const std::string sp = gi->service_pack_str();
+
+ if (major == 10) {
+ version += (server) ? "Server OS" : "10 OS";
+ } else if (major == 6) {
+ switch (minor) {
+ case 0:
+ // Windows Vista or Server 2008
+ version += (server) ? "Server 2008 " : "Vista ";
+ version += sp;
+ break;
+ case 1:
+ // Windows 7 or Server 2008 R2
+ version += (server) ? "Server 2008 R2 " : "7 ";
+ version += sp;
+ break;
+ case 2:
+ // Windows 8 or Server 2012
+ version += (server) ? "Server 2012" : "8";
+ break;
+ case 3:
+ // Windows 8.1 or Server 2012 R2
+ version += (server) ? "Server 2012 R2" : "8.1";
+ break;
+ default:
+ // unknown version
+ return base::StringPrintf("unknown version 6.%d", minor);
+ }
+ } else if ((major == 5) && (minor > 0)) {
+ // Windows XP or Server 2003
+ version += (server) ? "Server 2003 " : "XP ";
+ version += sp;
+ } else {
+ // unknown version
+ return base::StringPrintf("unknown version %d.%d", major, minor);
+ }
+
+ const std::string release_id = gi->release_id();
+
+ if (!release_id.empty())
+ version += " Version " + release_id;
+
+ if (patch > 0)
+ version += base::StringPrintf(" (Build %d.%d)", build, patch);
+ else
+ version += base::StringPrintf(" (Build %d)", build);
+ return version;
+}
+
+base::string16 GetCohortVersionInfo() {
+ base::string16 update_cohort_name =
+ install_static::InstallDetails::Get().update_cohort_name();
+ if (!update_cohort_name.empty()) {
+ return l10n_util::GetStringFUTF16(IDS_VERSION_UI_COHORT_NAME,
+ update_cohort_name);
+ }
+
+ return base::string16();
+}
+
+} // namespace win
+} // namespace version_utils
diff --git a/chromium/chrome/browser/ui/webui/version_util_win.h b/chromium/chrome/browser/ui/webui/version_util_win.h
new file mode 100644
index 00000000000..d5347321e8a
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/version_util_win.h
@@ -0,0 +1,27 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_VERSION_UTIL_WIN_H_
+#define CHROME_BROWSER_UI_WEBUI_VERSION_UTIL_WIN_H_
+
+#include <string>
+
+#include "base/strings/string16.h"
+
+namespace version_utils {
+namespace win {
+
+// Return the marketing version of Windows OS, this may return an empty string
+// if values returned by base::win::OSinfo are not defined.
+std::string GetFullWindowsVersion();
+
+// Return a formatted version of the update cohort string
+// IDS_VERSION_UI_COHORT_NAME filled with the update cohort of this Chromium
+// install.
+base::string16 GetCohortVersionInfo();
+
+} // namespace win
+} // namespace version_utils
+
+#endif // CHROME_BROWSER_UI_WEBUI_VERSION_UTIL_WIN_H_
diff --git a/chromium/chrome/browser/ui/webui/webapks_handler.cc b/chromium/chrome/browser/ui/webui/webapks_handler.cc
index 73e48fff39a..58ef4180aac 100644
--- a/chromium/chrome/browser/ui/webui/webapks_handler.cc
+++ b/chromium/chrome/browser/ui/webui/webapks_handler.cc
@@ -7,7 +7,6 @@
#include <string>
#include "base/bind.h"
-#include "base/callback_forward.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/android/color_helpers.h"
@@ -16,7 +15,9 @@
#include "third_party/blink/public/common/manifest/manifest_util.h"
#include "ui/gfx/color_utils.h"
-WebApksHandler::WebApksHandler() : weak_ptr_factory_(this) {}
+WebApksHandler::WebApksHandler()
+ : delegate_(base::BindRepeating(&WebApksHandler::OnWebApkInfoRetrieved,
+ base::Unretained(this))) {}
WebApksHandler::~WebApksHandler() {}
@@ -25,44 +26,57 @@ void WebApksHandler::RegisterMessages() {
"requestWebApksInfo",
base::BindRepeating(&WebApksHandler::HandleRequestWebApksInfo,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "requestWebApkUpdate",
+ base::BindRepeating(&WebApksHandler::HandleRequestWebApkUpdate,
+ base::Unretained(this)));
}
void WebApksHandler::HandleRequestWebApksInfo(const base::ListValue* args) {
AllowJavascript();
- ShortcutHelper::RetrieveWebApks(base::Bind(
- &WebApksHandler::OnWebApkInfoRetrieved, weak_ptr_factory_.GetWeakPtr()));
+ delegate_.RetrieveWebApks();
}
-void WebApksHandler::OnWebApkInfoRetrieved(
- const std::vector<WebApkInfo>& webapks_list) {
- if (!IsJavascriptAllowed())
- return;
- base::ListValue list;
- for (const auto& webapk_info : webapks_list) {
- std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue());
- result->SetString("name", webapk_info.name);
- result->SetString("shortName", webapk_info.short_name);
- result->SetString("packageName", webapk_info.package_name);
- result->SetInteger("shellApkVersion", webapk_info.shell_apk_version);
- result->SetInteger("versionCode", webapk_info.version_code);
- result->SetString("uri", webapk_info.uri);
- result->SetString("scope", webapk_info.scope);
- result->SetString("manifestUrl", webapk_info.manifest_url);
- result->SetString("manifestStartUrl", webapk_info.manifest_start_url);
- result->SetString("displayMode",
- blink::WebDisplayModeToString(webapk_info.display));
- result->SetString(
- "orientation",
- blink::WebScreenOrientationLockTypeToString(webapk_info.orientation));
- result->SetString("themeColor",
- OptionalSkColorToString(webapk_info.theme_color));
- result->SetString("backgroundColor",
- OptionalSkColorToString(webapk_info.background_color));
- result->SetDouble("lastUpdateCheckTimeMs",
- webapk_info.last_update_check_time.ToJsTime());
- result->SetBoolean("relaxUpdates", webapk_info.relax_updates);
- list.Append(std::move(result));
+void WebApksHandler::HandleRequestWebApkUpdate(const base::ListValue* args) {
+ AllowJavascript();
+ for (const auto& val : args->GetList()) {
+ if (val.is_string())
+ ShortcutHelper::SetForceWebApkUpdate(val.GetString());
}
+}
- CallJavascriptFunction("returnWebApksInfo", list);
+void WebApksHandler::OnWebApkInfoRetrieved(const WebApkInfo& webapk_info) {
+ if (!IsJavascriptAllowed())
+ return;
+ base::DictionaryValue result;
+ result.SetString("name", webapk_info.name);
+ result.SetString("shortName", webapk_info.short_name);
+ result.SetString("packageName", webapk_info.package_name);
+ result.SetString("id", webapk_info.id);
+ result.SetInteger("shellApkVersion", webapk_info.shell_apk_version);
+ result.SetInteger("versionCode", webapk_info.version_code);
+ result.SetString("uri", webapk_info.uri);
+ result.SetString("scope", webapk_info.scope);
+ result.SetString("manifestUrl", webapk_info.manifest_url);
+ result.SetString("manifestStartUrl", webapk_info.manifest_start_url);
+ result.SetString("displayMode",
+ blink::WebDisplayModeToString(webapk_info.display));
+ result.SetString("orientation", blink::WebScreenOrientationLockTypeToString(
+ webapk_info.orientation));
+ result.SetString("themeColor",
+ OptionalSkColorToString(webapk_info.theme_color));
+ result.SetString("backgroundColor",
+ OptionalSkColorToString(webapk_info.background_color));
+ result.SetDouble("lastUpdateCheckTimeMs",
+ webapk_info.last_update_check_time.ToJsTime());
+ result.SetDouble("lastUpdateCompletionTimeMs",
+ webapk_info.last_update_completion_time.ToJsTime());
+ result.SetBoolean("relaxUpdates", webapk_info.relax_updates);
+ result.SetString("backingBrowser", webapk_info.backing_browser_package_name);
+ result.SetBoolean("isBackingBrowser", webapk_info.is_backing_browser);
+ result.SetString("updateStatus",
+ webapk_info.is_backing_browser
+ ? webapk_info.update_status
+ : "Current browser doesn't own this WebAPK.");
+ CallJavascriptFunction("returnWebApkInfo", result);
}
diff --git a/chromium/chrome/browser/ui/webui/webapks_handler.h b/chromium/chrome/browser/ui/webui/webapks_handler.h
index 7d051ee8a1e..bcb67234f20 100644
--- a/chromium/chrome/browser/ui/webui/webapks_handler.h
+++ b/chromium/chrome/browser/ui/webui/webapks_handler.h
@@ -5,10 +5,11 @@
#ifndef CHROME_BROWSER_UI_WEBUI_WEBAPKS_HANDLER_H_
#define CHROME_BROWSER_UI_WEBUI_WEBAPKS_HANDLER_H_
-#include <vector>
+#include <memory>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
+#include "chrome/browser/android/webapk/webapk_handler_delegate.h"
#include "chrome/browser/android/webapk/webapk_info.h"
#include "content/public/browser/web_ui_message_handler.h"
@@ -28,14 +29,18 @@ class WebApksHandler : public content::WebUIMessageHandler {
// Handler for the "requestWebApksInfo" message. This requests
// information for the installed WebAPKs and returns it to JS using
// OnWebApkInfoReceived().
- virtual void HandleRequestWebApksInfo(const base::ListValue* args);
+ void HandleRequestWebApksInfo(const base::ListValue* args);
+
+ // Handler for the "requestWebApkUpdate" message. This sets the
+ // update flag for a set of WebAPKs. |args| should contain the
+ // webapp IDs of the WebAPKs to update.
+ void HandleRequestWebApkUpdate(const base::ListValue* args);
private:
- // Sends information for the installed WebAPKs to JS.
- void OnWebApkInfoRetrieved(const std::vector<WebApkInfo>& webapks_list);
+ // Called once for each installed WebAPK when the WebAPK Info is retrieved.
+ void OnWebApkInfoRetrieved(const WebApkInfo& webapk_info);
- // Factory for the creating refs in callbacks.
- base::WeakPtrFactory<WebApksHandler> weak_ptr_factory_;
+ WebApkHandlerDelegate delegate_;
DISALLOW_COPY_AND_ASSIGN(WebApksHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/webui_load_timer.cc b/chromium/chrome/browser/ui/webui/webui_load_timer.cc
new file mode 100644
index 00000000000..f865c2131df
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/webui_load_timer.cc
@@ -0,0 +1,65 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/webui_load_timer.h"
+
+#include "base/metrics/histogram.h"
+#include "content/public/browser/navigation_handle.h"
+#include "content/public/browser/web_contents.h"
+
+namespace {
+
+// Extract UMA_HISTOGRAM_TIMES to allow multiple calls from the same location
+// with different names. This skips some optimization, but we don't expect to
+// call this frequently.
+void CallUmaHistogramTimes(const std::string& name, base::TimeDelta duration) {
+ base::HistogramBase* histogram = base::Histogram::FactoryTimeGet(
+ name, base::TimeDelta::FromMilliseconds(1),
+ base::TimeDelta::FromSeconds(10), 50,
+ base::HistogramBase::kUmaTargetedHistogramFlag);
+ DCHECK(histogram);
+ histogram->AddTime(duration);
+}
+
+} // namespace
+
+WebuiLoadTimer::WebuiLoadTimer(
+ content::WebContents* web_contents,
+ const std::string& document_initial_load_uma_id,
+ const std::string& document_load_completed_uma_id)
+ : content::WebContentsObserver(web_contents),
+ document_initial_load_uma_id_(document_initial_load_uma_id),
+ document_load_completed_uma_id_(document_load_completed_uma_id) {
+ DCHECK(!document_initial_load_uma_id_.empty());
+ DCHECK(!document_load_completed_uma_id_.empty());
+}
+
+WebuiLoadTimer::~WebuiLoadTimer() = default;
+
+void WebuiLoadTimer::DidStartNavigation(
+ content::NavigationHandle* navigation_handle) {
+ if (!navigation_handle->IsInMainFrame() ||
+ navigation_handle->IsSameDocument()) {
+ return;
+ }
+ timer_ = std::make_unique<base::ElapsedTimer>();
+}
+
+void WebuiLoadTimer::DocumentLoadedInFrame(
+ content::RenderFrameHost* render_frame_host) {
+ // See comment in DocumentOnLoadCompletedInMainFrame.
+ if (!timer_ || render_frame_host != web_contents()->GetMainFrame())
+ return;
+ CallUmaHistogramTimes(document_initial_load_uma_id_, timer_->Elapsed());
+}
+
+void WebuiLoadTimer::DocumentOnLoadCompletedInMainFrame() {
+ // The WebContents could have been created for a child RenderFrameHost so it
+ // would never receive a DidStartNavigation with the main frame, however it
+ // will receive this callback.
+ if (!timer_)
+ return;
+ CallUmaHistogramTimes(document_load_completed_uma_id_, timer_->Elapsed());
+ timer_.reset();
+}
diff --git a/chromium/chrome/browser/ui/webui/webui_load_timer.h b/chromium/chrome/browser/ui/webui/webui_load_timer.h
new file mode 100644
index 00000000000..0fee6dfb048
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/webui_load_timer.h
@@ -0,0 +1,43 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_WEBUI_LOAD_TIMER_H_
+#define CHROME_BROWSER_UI_WEBUI_WEBUI_LOAD_TIMER_H_
+
+#include <memory>
+#include <string>
+
+#include "base/macros.h"
+#include "base/timer/elapsed_timer.h"
+#include "content/public/browser/web_contents_observer.h"
+
+// Measures and reports page load times for WebUI.
+class WebuiLoadTimer : public content::WebContentsObserver {
+ public:
+ // Load times are reported to UMA using the provided strings which
+ // must not be empty.
+ // * |document_initial_load_uma_id| - corresponds to DocumentLoadedInFrame
+ // * |document_load_completed_uma_id| - corresponds to
+ // DocumentOnLoadCompletedInMainFrame
+ WebuiLoadTimer(content::WebContents* web_contents,
+ const std::string& document_initial_load_uma_id,
+ const std::string& document_load_completed_uma_id);
+ ~WebuiLoadTimer() override;
+
+ // WebContentsObserver
+ void DidStartNavigation(
+ content::NavigationHandle* navigation_handle) override;
+ void DocumentLoadedInFrame(
+ content::RenderFrameHost* render_frame_host) override;
+ void DocumentOnLoadCompletedInMainFrame() override;
+
+ private:
+ std::string document_initial_load_uma_id_;
+ std::string document_load_completed_uma_id_;
+ std::unique_ptr<base::ElapsedTimer> timer_;
+
+ DISALLOW_COPY_AND_ASSIGN(WebuiLoadTimer);
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_WEBUI_LOAD_TIMER_H_
diff --git a/chromium/chrome/browser/ui/webui/webui_load_timer_browsertest.cc b/chromium/chrome/browser/ui/webui/webui_load_timer_browsertest.cc
new file mode 100644
index 00000000000..2e9bb955b99
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/webui_load_timer_browsertest.cc
@@ -0,0 +1,38 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/webui_load_timer.h"
+
+#include "base/run_loop.h"
+#include "base/test/metrics/histogram_tester.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/browser_commands.h"
+#include "chrome/test/base/in_process_browser_test.h"
+#include "chrome/test/base/ui_test_utils.h"
+#include "content/public/test/browser_test_utils.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "url/gurl.h"
+
+namespace {
+
+const char kTestUrl[] = "chrome://chrome-urls";
+const char kDocumentInitialLoadUmaId[] = "document_initial_load";
+const char kDocumentLoadCompletedUmaId[] = "document_load_completed";
+
+} // namespace
+
+using WebuiLoadTimerTest = InProcessBrowserTest;
+
+IN_PROC_BROWSER_TEST_F(WebuiLoadTimerTest, Timers) {
+ base::HistogramTester histogram_tester;
+ ui_test_utils::NavigateToURL(browser(), GURL(kTestUrl));
+ WebuiLoadTimer timer(browser()->tab_strip_model()->GetActiveWebContents(),
+ kDocumentInitialLoadUmaId, kDocumentLoadCompletedUmaId);
+ chrome::Reload(browser(), WindowOpenDisposition::CURRENT_TAB);
+ content::WaitForLoadStop(
+ browser()->tab_strip_model()->GetActiveWebContents());
+
+ histogram_tester.ExpectTotalCount(kDocumentInitialLoadUmaId, 1);
+ histogram_tester.ExpectTotalCount(kDocumentLoadCompletedUmaId, 1);
+}
diff --git a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.cc b/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.cc
index bf02622586a..914372cffe1 100644
--- a/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.cc
+++ b/chromium/chrome/browser/ui/webui/welcome/nux/ntp_background_handler.cc
@@ -133,44 +133,46 @@ void NtpBackgroundHandler::HandleSetBackground(const base::ListValue* args) {
switch (backgroundIndex) {
case static_cast<int>(NtpBackgrounds::kArt):
- instant_service->SetCustomBackgroundURLWithAttributions(
+ instant_service->SetCustomBackgroundInfo(
onboardingNtpBackgrounds[backgroundIndex], "Universe Cosmic Vacum",
"Philipp Rietz — Walli",
- GURL("https://walli.shanga.co/image/view/?id=370"));
+ GURL("https://walli.shanga.co/image/view/?id=370"), "");
break;
case static_cast<int>(NtpBackgrounds::kCityscape):
- instant_service->SetCustomBackgroundURLWithAttributions(
+ instant_service->SetCustomBackgroundInfo(
onboardingNtpBackgrounds[backgroundIndex],
l10n_util::GetStringFUTF8(
IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL,
base::UTF8ToUTF16("Ev Tchebotarev")),
"",
GURL("https://500px.com/photo/135751035/"
- "soulseek-by-%E5%B0%A4%E9%87%91%E5%B0%BC-ev-tchebotarev"));
+ "soulseek-by-%E5%B0%A4%E9%87%91%E5%B0%BC-ev-tchebotarev"),
+ "");
break;
case static_cast<int>(NtpBackgrounds::kEarth):
- instant_service->SetCustomBackgroundURLWithAttributions(
+ instant_service->SetCustomBackgroundInfo(
onboardingNtpBackgrounds[backgroundIndex],
l10n_util::GetStringFUTF8(
IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL,
base::UTF8ToUTF16("NASA Image Library")),
- "", GURL("https://www.google.com/sky/"));
+ "", GURL("https://www.google.com/sky/"), "");
break;
case static_cast<int>(NtpBackgrounds::kGeometricShapes):
- instant_service->SetCustomBackgroundURLWithAttributions(
+ instant_service->SetCustomBackgroundInfo(
onboardingNtpBackgrounds[backgroundIndex], "Tessellation 15",
"Justin Prno — Walli",
- GURL("https://walli.shanga.co/image/view/?id=1375"));
+ GURL("https://walli.shanga.co/image/view/?id=1375"), "");
break;
case static_cast<int>(NtpBackgrounds::kLandscape):
- instant_service->SetCustomBackgroundURLWithAttributions(
+ instant_service->SetCustomBackgroundInfo(
onboardingNtpBackgrounds[backgroundIndex],
l10n_util::GetStringFUTF8(
IDS_ONBOARDING_WELCOME_NTP_BACKGROUND_PHOTO_BY_LABEL,
base::UTF8ToUTF16("Giulio Rosso Chioso")),
"",
GURL("https://500px.com/photo/41149196/"
- "le-piscine-sunset-by-giulio-rosso-chioso"));
+ "le-piscine-sunset-by-giulio-rosso-chioso"),
+ "");
break;
}
}
diff --git a/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc b/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc
index e984fb029c1..f8e669c0863 100644
--- a/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc
+++ b/chromium/chrome/browser/ui/webui/welcome/nux_helper.cc
@@ -13,7 +13,7 @@
#include "base/strings/string_split.h"
#include "base/strings/string_tokenizer.h"
#include "base/values.h"
-#include "build/build_config.h"
+#include "build/branding_buildflags.h"
#include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
#include "chrome/browser/policy/browser_signin_policy_handler.h"
#include "chrome/browser/policy/profile_policy_connector.h"
@@ -28,10 +28,6 @@
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_service.h"
-#if defined(OS_MACOSX)
-#include "base/enterprise_util.h"
-#endif // defined(OS_MACOSX)
-
namespace nux {
bool CanShowGoogleAppModule(const policy::PolicyMap& policies) {
@@ -98,7 +94,7 @@ bool CanShowSigninModuleForTesting(const policy::PolicyMap& policies) {
return CanShowSigninModule(policies);
}
-#if defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN)
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN)
// These feature flags are used to tie our experiment to specific studies.
// go/navi-app-variation for details.
// TODO(hcarmona): find a solution that scales better.
@@ -110,7 +106,7 @@ const base::Feature kNaviNTPVariationEnabled = {
"NaviNTPVariationEnabled", base::FEATURE_DISABLED_BY_DEFAULT};
const base::Feature kNaviShortcutVariationEnabled = {
"NaviShortcutVariationEnabled", base::FEATURE_DISABLED_BY_DEFAULT};
-#endif // defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN)
+#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN)
// This feature flag is used to force the feature to be turned on for non-win
// and non-branded builds, like with tests or development on other platforms.
@@ -139,6 +135,12 @@ bool CanExperimentWithVariations(Profile* profile) {
// Must match study name in configs.
const char kNuxOnboardingStudyName[] = "NaviOnboarding";
+// 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
std::string GetOnboardingGroup(Profile* profile) {
if (!CanExperimentWithVariations(profile)) {
// If we cannot run any variations, we bucket the users into a separate
@@ -153,35 +155,22 @@ std::string GetOnboardingGroup(Profile* profile) {
"onboarding-group");
}
-bool IsNuxOnboardingEnabled(Profile* profile) {
- if (base::FeatureList::IsEnabled(nux::kNuxOnboardingForceEnabled)) {
- return true;
- }
-
-#if defined(GOOGLE_CHROME_BUILD)
-
-#if defined(OS_MACOSX)
- return !base::IsMachineExternallyManaged();
-#endif // defined(OS_MACOSX)
-
-#if defined(OS_WIN)
- // 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.
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN)
+void JoinOnboardingGroup(Profile* profile) {
PrefService* prefs = profile->GetPrefs();
- if (!prefs) {
- return false;
- }
-
- std::string onboard_group = prefs->GetString(prefs::kNaviOnboardGroup);
- if (onboard_group.empty()) {
- // Users who onboarded before Navi or are part of an enterprise.
- return false;
- }
-
- if (!CanExperimentWithVariations(profile)) {
- return true; // Default Navi behavior.
+ std::string onboard_group;
+ if (prefs->GetBoolean(prefs::kHasSeenWelcomePage)) {
+ // Get user's original onboarding group.
+ onboard_group = prefs->GetString(prefs::kNaviOnboardGroup);
+
+ // Users who onboarded before Navi won't have an onboarding group.
+ if (onboard_group.empty())
+ return;
+ } else {
+ // Join the latest group if onboarding for the first time!
+ onboard_group = GetOnboardingGroup(profile);
+ profile->GetPrefs()->SetString(prefs::kNaviOnboardGroup, onboard_group);
}
// User will be tied to their original onboarding group, even after
@@ -199,15 +188,17 @@ bool IsNuxOnboardingEnabled(Profile* profile) {
base::FeatureList::IsEnabled(kNaviNTPVariationEnabled);
else if (onboard_group.compare("ShortcutVariationSynthetic-008") == 0)
base::FeatureList::IsEnabled(kNaviShortcutVariationEnabled);
+}
+#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OS_WIN)
- if (base::FeatureList::IsEnabled(nux::kNuxOnboardingFeature)) {
- return true;
- }
-#endif // defined(OS_WIN)
-
-#endif // defined(GOOGLE_CHROME_BUILD)
-
- return false;
+bool IsNuxOnboardingEnabled(Profile* profile) {
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
+ return base::FeatureList::IsEnabled(nux::kNuxOnboardingFeature) ||
+ base::FeatureList::IsEnabled(nux::kNuxOnboardingForceEnabled);
+#else
+ // Allow enabling outside official builds for testing purposes.
+ return base::FeatureList::IsEnabled(nux::kNuxOnboardingForceEnabled);
+#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
}
bool IsAppVariationEnabled() {
@@ -262,7 +253,7 @@ std::string FilterModules(const std::string& requested_modules,
std::back_inserter(filtered_modules),
[available_modules](std::string module) {
return !module.empty() &&
- base::ContainsValue(available_modules, module);
+ base::Contains(available_modules, module);
});
return base::JoinString(filtered_modules, ",");
diff --git a/chromium/chrome/browser/ui/webui/welcome/nux_helper.h b/chromium/chrome/browser/ui/webui/welcome/nux_helper.h
index 719d11eb45a..fb99d65d282 100644
--- a/chromium/chrome/browser/ui/webui/welcome/nux_helper.h
+++ b/chromium/chrome/browser/ui/webui/welcome/nux_helper.h
@@ -9,6 +9,7 @@
#include "base/macros.h"
#include "base/metrics/field_trial_params.h"
+#include "build/build_config.h"
namespace base {
class DictionaryValue;
@@ -29,14 +30,13 @@ extern const base::FeatureParam<std::string>
extern const base::FeatureParam<std::string>
kNuxOnboardingForceEnabledReturningUserModules;
-// 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(Profile* profile);
+#if defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN)
+// Onboarding groups are used for running field trials related to first run
+// experience. This will make a new profile join whatever group is currently
+// active. Any profile that is already part of an onboarding group will remain
+// in that group.
+void JoinOnboardingGroup(Profile* profile);
+#endif // defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN)
bool IsNuxOnboardingEnabled(Profile* profile);
diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc
index e0d62ec0848..222a102b2be 100644
--- a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc
+++ b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc
@@ -15,8 +15,8 @@
#include "chrome/browser/ui/profile_chooser_constants.h"
#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
#include "chrome/common/url_constants.h"
-#include "components/signin/core/browser/signin_metrics.h"
-#include "services/identity/public/cpp/identity_manager.h"
+#include "components/signin/public/base/signin_metrics.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
#include "ui/base/page_transition_types.h"
const char kWelcomeReturningUserUrl[] = "chrome://welcome/returning-user";
diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc
index 6677f1d7645..d05ae4c1e86 100644
--- a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc
+++ b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.cc
@@ -5,11 +5,9 @@
#include "chrome/browser/ui/webui/welcome/welcome_ui.h"
#include "base/bind.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/stl_util.h"
-#include "build/build_config.h"
+#include "base/strings/string_number_conversions.h"
+#include "build/branding_buildflags.h"
#include "chrome/browser/signin/account_consistency_mode_manager.h"
-#include "chrome/browser/ui/webui/dark_mode_handler.h"
#include "chrome/browser/ui/webui/localized_string.h"
#include "chrome/browser/ui/webui/welcome/nux/bookmark_handler.h"
#include "chrome/browser/ui/webui/welcome/nux/constants.h"
@@ -19,18 +17,15 @@
#include "chrome/browser/ui/webui/welcome/nux_helper.h"
#include "chrome/browser/ui/webui/welcome/welcome_handler.h"
#include "chrome/common/pref_names.h"
-#include "chrome/grit/browser_resources.h"
#include "chrome/grit/chrome_unscaled_resources.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/grit/onboarding_welcome_resources.h"
#include "chrome/grit/onboarding_welcome_resources_map.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/signin_pref_names.h"
+#include "components/signin/public/base/signin_pref_names.h"
#include "components/strings/grit/components_strings.h"
-#include "content/public/browser/web_contents.h"
#include "net/base/url_util.h"
-#include "ui/base/l10n/l10n_util.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
@@ -38,13 +33,6 @@
namespace {
-const bool kIsBranded =
-#if defined(GOOGLE_CHROME_BUILD)
- true;
-#else
- false;
-#endif
-
const char kPreviewBackgroundPath[] = "preview-background.jpg";
bool ShouldHandleRequestCallback(base::WeakPtr<WelcomeUI> weak_ptr,
@@ -82,13 +70,11 @@ void HandleRequestCallback(
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},
{"defaultBrowserChanged", IDS_ONBOARDING_DEFAULT_BROWSER_CHANGED},
- {"getStarted", IDS_ONBOARDING_WELCOME_GET_STARTED},
{"headerText", IDS_WELCOME_HEADER},
{"next", IDS_ONBOARDING_WELCOME_NEXT},
{"noThanks", IDS_NO_THANKS},
@@ -116,7 +102,6 @@ void AddOnboardingStrings(content::WebUIDataSource* html_source) {
{"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},
@@ -133,7 +118,7 @@ void AddOnboardingStrings(content::WebUIDataSource* html_source) {
} // namespace
WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url)
- : content::WebUIController(web_ui), weak_ptr_factory_(this) {
+ : content::WebUIController(web_ui) {
Profile* profile = Profile::FromWebUI(web_ui);
// This page is not shown to incognito or guest profiles. If one should end up
@@ -149,105 +134,81 @@ WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url)
content::WebUIDataSource* html_source =
content::WebUIDataSource::Create(url.host());
- DarkModeHandler::Initialize(web_ui, html_source);
-
- // There are multiple possible configurations that affects the layout, but
- // first add resources that are shared across all layouts.
- html_source->AddResourcePath("logo.png", IDR_PRODUCT_LOGO_128);
- html_source->AddResourcePath("logo2x.png", IDR_PRODUCT_LOGO_256);
+ // Add Onboarding welcome strings.
+ AddOnboardingStrings(html_source);
- if (nux::IsNuxOnboardingEnabled(profile)) {
- // Add Onboarding welcome strings.
- AddOnboardingStrings(html_source);
-
- // Add all Onboarding resources.
- for (size_t i = 0; i < kOnboardingWelcomeResourcesSize; ++i) {
- html_source->AddResourcePath(kOnboardingWelcomeResources[i].name,
- kOnboardingWelcomeResources[i].value);
- }
+ // Add all 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);
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
+ // Load unscaled images.
+ html_source->AddResourcePath("images/module_icons/google_dark.svg",
+ IDR_WELCOME_MODULE_ICONS_GOOGLE_DARK);
+ html_source->AddResourcePath("images/module_icons/google_light.svg",
+ IDR_WELCOME_MODULE_ICONS_GOOGLE_LIGHT);
+ html_source->AddResourcePath("images/module_icons/set_default_dark.svg",
+ IDR_WELCOME_MODULE_ICONS_SET_DEFAULT_DARK);
+ html_source->AddResourcePath("images/module_icons/set_default_light.svg",
+ IDR_WELCOME_MODULE_ICONS_SET_DEFAULT_LIGHT);
+ html_source->AddResourcePath("images/module_icons/wallpaper_dark.svg",
+ IDR_WELCOME_MODULE_ICONS_WALLPAPER_DARK);
+ html_source->AddResourcePath("images/module_icons/wallpaper_light.svg",
+ IDR_WELCOME_MODULE_ICONS_WALLPAPER_LIGHT);
+ html_source->AddResourcePath("images/ntp_thumbnails/art.jpg",
+ IDR_WELCOME_NTP_THUMBNAILS_ART);
+ html_source->AddResourcePath("images/ntp_thumbnails/cityscape.jpg",
+ IDR_WELCOME_NTP_THUMBNAILS_CITYSCAPE);
+ html_source->AddResourcePath("images/ntp_thumbnails/earth.jpg",
+ IDR_WELCOME_NTP_THUMBNAILS_EARTH);
+ html_source->AddResourcePath("images/ntp_thumbnails/geometric_shapes.jpg",
+ IDR_WELCOME_NTP_THUMBNAILS_GEOMETRIC_SHAPES);
+ html_source->AddResourcePath("images/ntp_thumbnails/landscape.jpg",
+ IDR_WELCOME_NTP_THUMBNAILS_LANDSCAPE);
+ html_source->AddResourcePath("images/set_default_dark.svg",
+ IDR_WELCOME_SET_DEFAULT_DARK);
+ html_source->AddResourcePath("images/set_default_light.svg",
+ IDR_WELCOME_SET_DEFAULT_LIGHT);
+#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
+
+ // chrome://welcome
+ html_source->SetDefaultResource(IDR_WELCOME_ONBOARDING_WELCOME_WELCOME_HTML);
#if defined(OS_WIN)
- html_source->AddBoolean(
- "is_win10", base::win::GetVersion() >= base::win::Version::WIN10);
+ 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 google apps bookmarking onboarding module.
- web_ui->AddMessageHandler(std::make_unique<nux::GoogleAppsHandler>());
-
- // Add NTP custom background onboarding module.
- web_ui->AddMessageHandler(std::make_unique<nux::NtpBackgroundHandler>());
-
- // 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("signinAllowed", profile->GetPrefs()->GetBoolean(
- prefs::kSigninAllowed));
- html_source->SetRequestFilter(
- base::BindRepeating(&ShouldHandleRequestCallback,
- weak_ptr_factory_.GetWeakPtr()),
- base::BindRepeating(&HandleRequestCallback,
- weak_ptr_factory_.GetWeakPtr()));
- html_source->SetJsonPath("strings.js");
- } else if (kIsBranded &&
- AccountConsistencyModeManager::IsDiceEnabledForProfile(profile)) {
- // Use special layout if the application is branded and DICE is enabled.
- html_source->AddLocalizedString("headerText", IDS_WELCOME_HEADER);
- html_source->AddLocalizedString("acceptText",
- IDS_PROFILES_DICE_SIGNIN_BUTTON);
- html_source->AddLocalizedString("secondHeaderText",
- IDS_DICE_WELCOME_SECOND_HEADER);
- html_source->AddLocalizedString("descriptionText",
- IDS_DICE_WELCOME_DESCRIPTION);
- html_source->AddLocalizedString("declineText",
- IDS_DICE_WELCOME_DECLINE_BUTTON);
- html_source->AddResourcePath("welcome_browser_proxy.html",
- IDR_DICE_WELCOME_BROWSER_PROXY_HTML);
- html_source->AddResourcePath("welcome_browser_proxy.js",
- IDR_DICE_WELCOME_BROWSER_PROXY_JS);
- html_source->AddResourcePath("welcome_app.html", IDR_DICE_WELCOME_APP_HTML);
- html_source->AddResourcePath("welcome_app.js", IDR_DICE_WELCOME_APP_JS);
- html_source->AddResourcePath("welcome.css", IDR_DICE_WELCOME_CSS);
- html_source->SetDefaultResource(IDR_DICE_WELCOME_HTML);
- } else {
- // Use default layout for non-DICE or unbranded build.
- std::string value;
- bool is_everywhere_variant =
- (net::GetValueForKeyInQuery(url, "variant", &value) &&
- value == "everywhere");
-
- if (kIsBranded) {
- base::string16 subheader =
- is_everywhere_variant
- ? base::string16()
- : l10n_util::GetStringUTF16(IDS_WELCOME_SUBHEADER);
- html_source->AddString("subheaderText", subheader);
- }
-
- int header_id = is_everywhere_variant ? IDS_WELCOME_HEADER_AFTER_FIRST_RUN
- : IDS_WELCOME_HEADER;
- html_source->AddString("headerText", l10n_util::GetStringUTF16(header_id));
- html_source->AddLocalizedString("acceptText", IDS_WELCOME_ACCEPT_BUTTON);
- html_source->AddLocalizedString("descriptionText", IDS_WELCOME_DESCRIPTION);
- html_source->AddLocalizedString("declineText", IDS_WELCOME_DECLINE_BUTTON);
- html_source->AddResourcePath("welcome.js", IDR_WELCOME_JS);
- html_source->AddResourcePath("welcome.css", IDR_WELCOME_CSS);
- html_source->SetDefaultResource(IDR_WELCOME_HTML);
- }
+ // Add the shared bookmark handler for onboarding modules.
+ web_ui->AddMessageHandler(
+ std::make_unique<nux::BookmarkHandler>(profile->GetPrefs()));
+
+ // Add google apps bookmarking onboarding module.
+ web_ui->AddMessageHandler(std::make_unique<nux::GoogleAppsHandler>());
+
+ // Add NTP custom background onboarding module.
+ web_ui->AddMessageHandler(std::make_unique<nux::NtpBackgroundHandler>());
+
+ // 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(
+ "signinAllowed", profile->GetPrefs()->GetBoolean(prefs::kSigninAllowed));
+ html_source->SetRequestFilter(
+ base::BindRepeating(&ShouldHandleRequestCallback,
+ weak_ptr_factory_.GetWeakPtr()),
+ base::BindRepeating(&HandleRequestCallback,
+ weak_ptr_factory_.GetWeakPtr()));
+ html_source->SetJsonPath("strings.js");
content::WebUIDataSource::Add(profile, html_source);
}
diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h
index 55896debd39..ed54ca23bc1 100644
--- a/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h
+++ b/chromium/chrome/browser/ui/webui/welcome/welcome_ui.h
@@ -35,7 +35,7 @@ class WelcomeUI : public content::WebUIController {
private:
void StorePageSeen(Profile* profile);
std::unique_ptr<nux::NtpBackgroundFetcher> background_fetcher_;
- base::WeakPtrFactory<WelcomeUI> weak_ptr_factory_;
+ base::WeakPtrFactory<WelcomeUI> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(WelcomeUI);
};
diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_win10_handler.cc b/chromium/chrome/browser/ui/webui/welcome/welcome_win10_handler.cc
deleted file mode 100644
index 954431fb0d8..00000000000
--- a/chromium/chrome/browser/ui/webui/welcome/welcome_win10_handler.cc
+++ /dev/null
@@ -1,198 +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/welcome/welcome_win10_handler.h"
-
-#include "base/bind.h"
-#include "base/metrics/histogram_functions.h"
-#include "base/metrics/histogram_macros.h"
-#include "base/metrics/user_metrics.h"
-#include "base/strings/stringprintf.h"
-#include "base/values.h"
-#include "chrome/browser/shell_integration.h"
-#include "chrome/browser/shell_integration_win.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/browser_navigator.h"
-#include "chrome/common/url_constants.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/common/service_manager_connection.h"
-#include "services/service_manager/public/cpp/connector.h"
-#include "url/gurl.h"
-
-namespace {
-
-void RecordDefaultBrowserResult(
- const std::string& histogram_suffix,
- shell_integration::DefaultWebClientState default_browser_state) {
- // Consider the page successful if this or any other side-by-side install of
- // Chrome was chosen as the user's default browser.
- base::UmaHistogramBoolean(
- base::StringPrintf("Welcome.Win10.DefaultPromptResult_%s",
- histogram_suffix.c_str()),
- (default_browser_state == shell_integration::IS_DEFAULT ||
- default_browser_state == shell_integration::OTHER_MODE_IS_DEFAULT));
-}
-
-void RecordPinnedResult(const std::string& histogram_suffix,
- bool succeeded,
- bool is_pinned) {
- if (!succeeded)
- return;
-
- base::UmaHistogramBoolean(
- base::StringPrintf("Welcome.Win10.PinnedPromptResult_%s",
- histogram_suffix.c_str()),
- is_pinned);
-}
-
-// Returns a new Connector that can be used on a different thread.
-std::unique_ptr<service_manager::Connector> GetClonedConnector() {
- return content::ServiceManagerConnection::GetForProcess()
- ->GetConnector()
- ->Clone();
-}
-
-} // namespace
-
-WelcomeWin10Handler::WelcomeWin10Handler() : weak_ptr_factory_(this) {
- // The check is started as early as possible because waiting for the page to
- // be fully loaded is unnecessarily wasting time.
- StartIsPinnedToTaskbarCheck();
-}
-
-WelcomeWin10Handler::~WelcomeWin10Handler() {
- // The instructions for pinning Chrome to the taskbar were only displayed if
- // Chrome wasn't pinned to the taskbar at page construction time.
- bool pin_instructions_shown =
- pinned_state_result_.has_value() && !pinned_state_result_.value();
-
- std::string histogram_suffix = "Inline";
- histogram_suffix += pin_instructions_shown ? "Combined" : "Default";
-
- // Closing the page. Record whether the instructions were useful.
- base::MakeRefCounted<shell_integration::DefaultBrowserWorker>(
- base::Bind(&RecordDefaultBrowserResult, histogram_suffix))
- ->StartCheckIsDefault();
-
- if (pin_instructions_shown) {
- // On error, call RecordPinnedResult() with |succeeded| == false.
- base::Closure error_callback =
- base::Bind(&RecordPinnedResult, histogram_suffix, false, false);
- shell_integration::win::GetIsPinnedToTaskbarState(
- GetClonedConnector(), error_callback,
- base::Bind(&RecordPinnedResult, histogram_suffix));
- }
-}
-
-void WelcomeWin10Handler::RegisterMessages() {
- web_ui()->RegisterMessageCallback(
- "handleSetDefaultBrowser",
- base::BindRepeating(&WelcomeWin10Handler::HandleSetDefaultBrowser,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "handleContinue",
- base::BindRepeating(&WelcomeWin10Handler::HandleContinue,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "getPinnedToTaskbarState",
- base::BindRepeating(&WelcomeWin10Handler::HandleGetPinnedToTaskbarState,
- base::Unretained(this)));
-}
-
-void WelcomeWin10Handler::OnJavascriptDisallowed() {
- pinned_state_callback_id_.clear();
-}
-
-void WelcomeWin10Handler::HandleGetPinnedToTaskbarState(
- const base::ListValue* args) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- AllowJavascript();
-
- // Save the callback id so that the result can be sent back when it is
- // available.
- bool callback_id_found = args->GetString(0, &pinned_state_callback_id_);
- DCHECK(callback_id_found);
-
- // Send back the result if it is already available.
- if (pinned_state_result_.has_value()) {
- SendPinnedToTaskbarStateResult();
- return;
- }
-
- // Only wait for a small amount of time for the result. If the timer fires,
- // it will be assumed that Chrome isn't pinned to the taskbar. This is to make
- // sure the instructions are displayed in case it was impossible to determine
- // the pinned state.
- constexpr base::TimeDelta kPinnedToTaskbarTimeout =
- base::TimeDelta::FromMilliseconds(200);
- timer_.Start(FROM_HERE, kPinnedToTaskbarTimeout,
- base::Bind(&WelcomeWin10Handler::OnIsPinnedToTaskbarDetermined,
- base::Unretained(this), true, false));
-}
-
-void WelcomeWin10Handler::HandleSetDefaultBrowser(const base::ListValue* args) {
- base::RecordAction(
- base::UserMetricsAction("Win10WelcomePage_SetAsDefaultBrowser"));
- // The worker owns itself.
- base::MakeRefCounted<shell_integration::DefaultBrowserWorker>(
- shell_integration::DefaultWebClientWorkerCallback())
- ->StartSetAsDefault();
-}
-
-void WelcomeWin10Handler::HandleContinue(const base::ListValue* args) {
- content::WebContents* contents = web_ui()->GetWebContents();
- Browser* browser = chrome::FindBrowserWithWebContents(contents);
- NavigateParams params(browser, GURL(chrome::kChromeUINewTabURL),
- ui::PageTransition::PAGE_TRANSITION_LINK);
- params.source_contents = web_ui()->GetWebContents();
- Navigate(&params);
-}
-
-void WelcomeWin10Handler::StartIsPinnedToTaskbarCheck() {
- // Assume that Chrome is pinned to the taskbar if an error occurs.
- base::Closure error_callback =
- base::Bind(&WelcomeWin10Handler::OnIsPinnedToTaskbarDetermined,
- weak_ptr_factory_.GetWeakPtr(), false, true);
-
- shell_integration::win::GetIsPinnedToTaskbarState(
- GetClonedConnector(), error_callback,
- base::Bind(&WelcomeWin10Handler::OnIsPinnedToTaskbarResult,
- weak_ptr_factory_.GetWeakPtr()));
-}
-
-void WelcomeWin10Handler::OnIsPinnedToTaskbarResult(bool succeeded,
- bool is_pinned_to_taskbar) {
- // Assume that Chrome is pinned to the taskbar if an error occured.
- OnIsPinnedToTaskbarDetermined(false, !succeeded || is_pinned_to_taskbar);
-}
-
-void WelcomeWin10Handler::OnIsPinnedToTaskbarDetermined(
- bool timed_out,
- bool is_pinned_to_taskbar) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
-
- // Early exit if the pinned_state was already determined.
- if (pinned_state_result_.has_value())
- return;
-
- UMA_HISTOGRAM_BOOLEAN("Welcome.Win10.PinCheckTimedOut", timed_out);
-
- // Stop the timer if it's still running.
- timer_.Stop();
-
- // Cache the value.
- pinned_state_result_.emplace(is_pinned_to_taskbar);
-
- // If the page already called getPinnedToTaskbarState(), the result can be
- // sent back.
- if (!pinned_state_callback_id_.empty())
- SendPinnedToTaskbarStateResult();
-}
-
-void WelcomeWin10Handler::SendPinnedToTaskbarStateResult() {
- ResolveJavascriptCallback(base::Value(pinned_state_callback_id_),
- base::Value(pinned_state_result_.value()));
-}
diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_win10_handler.h b/chromium/chrome/browser/ui/webui/welcome/welcome_win10_handler.h
deleted file mode 100644
index 504dada5d8e..00000000000
--- a/chromium/chrome/browser/ui/webui/welcome/welcome_win10_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_WELCOME_WELCOME_WIN10_HANDLER_H_
-#define CHROME_BROWSER_UI_WEBUI_WELCOME_WELCOME_WIN10_HANDLER_H_
-
-#include <string>
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/optional.h"
-#include "base/timer/timer.h"
-#include "content/public/browser/web_ui_message_handler.h"
-
-namespace base {
-class ListValue;
-}
-
-// Handles actions on the Windows 10 specific Welcome page.
-class WelcomeWin10Handler : public content::WebUIMessageHandler {
- public:
- WelcomeWin10Handler();
- ~WelcomeWin10Handler() override;
-
- // content::WebUIMessageHandler:
- void RegisterMessages() override;
- void OnJavascriptDisallowed() override;
-
- private:
- // Handlers for javascript calls.
- void HandleGetPinnedToTaskbarState(const base::ListValue* args);
- void HandleSetDefaultBrowser(const base::ListValue* args);
- void HandleContinue(const base::ListValue* args);
-
- void StartIsPinnedToTaskbarCheck();
-
- // Callback for shell_integration::win::GetIsPinnedToTaskbarState().
- void OnIsPinnedToTaskbarResult(bool succeeded, bool is_pinned_to_taskbar);
-
- // Sets the internal result and optionally call
- // SendPinnedToTaskbarStateResult() in the case that
- // |pinned_state_callback_id_| is not empty.
- void OnIsPinnedToTaskbarDetermined(bool timed_out, bool is_pinned_to_taskbar);
-
- // Returns the result to the getPinnedToTaskbarState() javascript call via the
- // promise.
- void SendPinnedToTaskbarStateResult();
-
- base::OneShotTimer timer_;
-
- // Acts as a cache to hold the taskbar pinned state of Chrome. It has no value
- // until this state is determined.
- base::Optional<bool> pinned_state_result_;
-
- // The callback id used to return the result to the getPinnedToTaskbarState()
- // javascript call. This id is empty until we receive the call; thus this
- // variable is used to determine if the result should be sent to the caller
- // when it is received, or wait for the call to happen.
- std::string pinned_state_callback_id_;
-
- base::WeakPtrFactory<WelcomeWin10Handler> weak_ptr_factory_;
-
- DISALLOW_COPY_AND_ASSIGN(WelcomeWin10Handler);
-};
-
-#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_WELCOME_WIN10_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_win10_ui.cc b/chromium/chrome/browser/ui/webui/welcome/welcome_win10_ui.cc
deleted file mode 100644
index efabd678058..00000000000
--- a/chromium/chrome/browser/ui/webui/welcome/welcome_win10_ui.cc
+++ /dev/null
@@ -1,108 +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/welcome/welcome_win10_ui.h"
-
-#include <memory>
-#include <string>
-
-#include "base/feature_list.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/localized_string.h"
-#include "chrome/browser/ui/webui/welcome/welcome_win10_handler.h"
-#include "chrome/common/chrome_features.h"
-#include "chrome/common/pref_names.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/browser_resources.h"
-#include "chrome/grit/chrome_unscaled_resources.h"
-#include "chrome/grit/chromium_strings.h"
-#include "chrome/grit/generated_resources.h"
-#include "components/prefs/pref_service.h"
-#include "content/public/browser/web_ui_data_source.h"
-#include "net/base/url_util.h"
-#include "url/gurl.h"
-
-namespace {
-
-// Helper function to check the presence of a key/value inside the query in the
-// |url|.
-bool UrlContainsKeyValueInQuery(const GURL& url,
- const std::string& key,
- const std::string& expected_value) {
- std::string value;
- return net::GetValueForKeyInQuery(url, key, &value) &&
- value == expected_value;
-}
-
-// Adds all the needed localized strings to |html_source|, depending on
-// the value of |is_first_run|.
-void AddLocalizedStrings(content::WebUIDataSource* html_source,
- bool is_first_run) {
- // Only show the "Welcome to Chrome" text on first run.
- int welcome_header_id = is_first_run
- ? IDS_WIN10_WELCOME_HEADER
- : IDS_WIN10_WELCOME_HEADER_AFTER_FIRST_RUN;
- html_source->AddLocalizedString("headerText", welcome_header_id);
-
- static constexpr LocalizedString kStrings[] = {
- {"continueText", IDS_WIN10_WELCOME_CONTINUE},
-
- // Default browser strings.
- {"defaultBrowserSubheaderText",
- IDS_WIN10_WELCOME_MAKE_DEFAULT_SUBHEADING},
- {"openSettingsText", IDS_WIN10_WELCOME_OPEN_SETTINGS},
- {"clickEdgeText", IDS_WIN10_WELCOME_CLICK_EDGE},
- {"clickSelectChrome", IDS_WIN10_WELCOME_SELECT},
- {"switchAnywayLabel", IDS_WIN10_WELCOME_SWITCH_ANYWAY_LABEL},
- {"clickSwitchAnywayText", IDS_WIN10_WELCOME_CLICK_SWITCH_ANYWAY},
-
- // Taskbar pin strings.
- {"pinSubheaderText", IDS_WIN10_WELCOME_PIN_SUBHEADING},
- {"rightClickText", IDS_WIN10_WELCOME_RIGHT_CLICK_TASKBAR},
- {"pinInstructionText", IDS_WIN10_WELCOME_PIN_INSTRUCTION},
- {"pinToTaskbarLabel", IDS_WIN10_WELCOME_PIN_LABEL},
- };
- AddLocalizedStringsBulk(html_source, kStrings, base::size(kStrings));
-}
-
-} // namespace
-
-WelcomeWin10UI::WelcomeWin10UI(content::WebUI* web_ui, const GURL& url)
- : content::WebUIController(web_ui) {
- // Remember that the Win10 promo page has been shown.
- g_browser_process->local_state()->SetBoolean(prefs::kHasSeenWin10PromoPage,
- true);
-
- // Determine which variation to show.
- bool is_first_run = !UrlContainsKeyValueInQuery(url, "text", "faster");
-
- web_ui->AddMessageHandler(std::make_unique<WelcomeWin10Handler>());
-
- content::WebUIDataSource* html_source =
- content::WebUIDataSource::Create(url.host());
-
- html_source->SetJsonPath("strings.js");
-
- AddLocalizedStrings(html_source, is_first_run);
-
- // Controls the accelerated default browser flow experiment.
- html_source->AddBoolean("acceleratedFlowEnabled",
- base::FeatureList::IsEnabled(
- features::kWin10AcceleratedDefaultBrowserFlow));
-
- html_source->AddResourcePath("welcome_win10.css", IDR_WELCOME_WIN10_CSS);
- html_source->AddResourcePath("welcome_win10.js", IDR_WELCOME_WIN10_JS);
- html_source->AddResourcePath("default.webp", IDR_WELCOME_WIN10_DEFAULT_WEBP);
- html_source->AddResourcePath("pin.webp", IDR_WELCOME_WIN10_PIN_WEBP);
-
- html_source->AddResourcePath("logo-small.png", IDR_PRODUCT_LOGO_64);
- html_source->AddResourcePath("logo-large.png", IDR_PRODUCT_LOGO_128);
-
- html_source->SetDefaultResource(IDR_WELCOME_WIN10_HTML);
-
- content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), html_source);
-}
-
-WelcomeWin10UI::~WelcomeWin10UI() = default;
diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_win10_ui.h b/chromium/chrome/browser/ui/webui/welcome/welcome_win10_ui.h
deleted file mode 100644
index 08c97ead173..00000000000
--- a/chromium/chrome/browser/ui/webui/welcome/welcome_win10_ui.h
+++ /dev/null
@@ -1,21 +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_WELCOME_WELCOME_WIN10_UI_H_
-#define CHROME_BROWSER_UI_WEBUI_WELCOME_WELCOME_WIN10_UI_H_
-
-#include "content/public/browser/web_ui_controller.h"
-
-class GURL;
-
-// The WebUI for chrome://welcome-win10, the page which greets new Windows 10
-// users and educates them about setting the default browser and pinning the
-// browser to their taskbar.
-class WelcomeWin10UI : public content::WebUIController {
- public:
- WelcomeWin10UI(content::WebUI* web_ui, const GURL& url);
- ~WelcomeWin10UI() override;
-};
-
-#endif // CHROME_BROWSER_UI_WEBUI_WELCOME_WELCOME_WIN10_UI_H_
diff --git a/chromium/chrome/browser/vr/BUILD.gn b/chromium/chrome/browser/vr/BUILD.gn
index 18ad1f17fe8..0dc72c1ee03 100644
--- a/chromium/chrome/browser/vr/BUILD.gn
+++ b/chromium/chrome/browser/vr/BUILD.gn
@@ -3,7 +3,7 @@
# found in the LICENSE file.
import("//build/buildflag_header.gni")
-import("//chrome/android/features/dynamic_feature_modules.gni")
+import("//chrome/android/modules/buildflags.gni")
import("//chrome/browser/vr/features.gni")
import("//chrome/common/features.gni")
import("//device/vr/buildflags/buildflags.gni")
@@ -267,6 +267,13 @@ component("vr_common") {
"platform_controller_for_testing.h",
]
+ if (enable_arcore) {
+ sources += [
+ "service/arcore_consent_prompt_interface.cc",
+ "service/arcore_consent_prompt_interface.h",
+ ]
+ }
+
public_deps = [
":vr_base",
]
@@ -295,10 +302,6 @@ component("vr_common") {
if (is_win) {
sources += [
- "service/isolated_device_provider.cc",
- "service/isolated_device_provider.h",
- "service/vr_ui_host.cc",
- "service/vr_ui_host.h",
"win/graphics_delegate_win.cc",
"win/graphics_delegate_win.h",
"win/input_delegate_win.cc",
@@ -309,12 +312,21 @@ component("vr_common") {
"win/vr_browser_renderer_thread_win.h",
]
- deps += [ "//services/ws/public/cpp/gpu" ]
+ deps += [ "//services/viz/public/cpp/gpu" ]
# Windows doesn't have app bundles, so include the UI directly.
deps += [ ":vr_ui" ]
}
+ if (!is_android) {
+ sources += [
+ "service/isolated_device_provider.cc",
+ "service/isolated_device_provider.h",
+ "service/vr_ui_host.cc",
+ "service/vr_ui_host.h",
+ ]
+ }
+
defines = [ "VR_IMPLEMENTATION" ]
if (!use_command_buffer) {
diff --git a/chromium/chrome/browser/web_applications/BUILD.gn b/chromium/chrome/browser/web_applications/BUILD.gn
index e7455451ebc..00d0ad6f6b9 100644
--- a/chromium/chrome/browser/web_applications/BUILD.gn
+++ b/chromium/chrome/browser/web_applications/BUILD.gn
@@ -34,6 +34,10 @@ source_set("web_applications") {
"web_app_install_task.h",
"web_app_registrar.cc",
"web_app_registrar.h",
+ "web_app_sync_bridge.cc",
+ "web_app_sync_bridge.h",
+ "web_app_sync_manager.cc",
+ "web_app_sync_manager.h",
"web_app_tab_helper.cc",
"web_app_tab_helper.h",
]
@@ -49,7 +53,12 @@ source_set("web_applications") {
]
if (is_chromeos) {
- deps += [ "//chromeos/constants" ]
+ deps += [
+ "//ash/public/cpp:cpp",
+ "//chromeos/constants",
+ "//components/arc:arc_base",
+ "//components/arc/common",
+ ]
}
public_deps = [
@@ -69,14 +78,16 @@ source_set("web_applications_test_support") {
"test/test_file_utils.h",
"test/test_install_finalizer.cc",
"test/test_install_finalizer.h",
+ "test/test_pending_app_manager.cc",
+ "test/test_pending_app_manager.h",
"test/test_system_web_app_manager.cc",
"test/test_system_web_app_manager.h",
"test/test_web_app_database.cc",
"test/test_web_app_database.h",
"test/test_web_app_database_factory.cc",
"test/test_web_app_database_factory.h",
- "test/test_web_app_ui_delegate.cc",
- "test/test_web_app_ui_delegate.h",
+ "test/test_web_app_ui_manager.cc",
+ "test/test_web_app_ui_manager.h",
"test/test_web_app_url_loader.cc",
"test/test_web_app_url_loader.h",
"test/web_app_test.cc",
@@ -89,6 +100,7 @@ source_set("web_applications_test_support") {
"//base/test:test_support",
"//chrome/browser",
"//chrome/browser/web_applications/components",
+ "//components/crx_file:crx_file",
"//components/sync:test_support_model",
"//content/test:test_support",
"//testing/gtest",
@@ -104,7 +116,6 @@ source_set("web_applications_unit_tests") {
"web_app_install_manager_unittest.cc",
"web_app_install_task_unittest.cc",
"web_app_registrar_unittest.cc",
- "web_app_utils_unittest.cc",
]
deps = [
@@ -122,7 +133,12 @@ source_set("web_applications_unit_tests") {
]
if (is_chromeos) {
- deps += [ "//chrome/browser/chromeos" ]
+ deps += [
+ "//chrome/browser/chromeos",
+ "//components/arc:arc",
+ "//components/arc:arc_test_support",
+ "//components/arc/common",
+ ]
}
}
diff --git a/chromium/chrome/browser/web_applications/bookmark_apps/BUILD.gn b/chromium/chrome/browser/web_applications/bookmark_apps/BUILD.gn
index eb2e00db0be..a0e5d37981a 100644
--- a/chromium/chrome/browser/web_applications/bookmark_apps/BUILD.gn
+++ b/chromium/chrome/browser/web_applications/bookmark_apps/BUILD.gn
@@ -66,7 +66,6 @@ source_set("unit_tests") {
"//chrome/browser/web_applications:web_applications_on_extensions",
"//chrome/browser/web_applications:web_applications_test_support",
"//chrome/browser/web_applications/components",
- "//chrome/browser/web_applications/components:test_support",
"//chrome/browser/web_applications/extensions",
"//chrome/common:constants",
"//chrome/test:test_support",
diff --git a/chromium/chrome/browser/web_applications/components/BUILD.gn b/chromium/chrome/browser/web_applications/components/BUILD.gn
index bad3dd00c72..3e00c9d2dc4 100644
--- a/chromium/chrome/browser/web_applications/components/BUILD.gn
+++ b/chromium/chrome/browser/web_applications/components/BUILD.gn
@@ -7,6 +7,8 @@ source_set("components") {
"app_registrar.cc",
"app_registrar.h",
"app_registrar_observer.h",
+ "external_install_options.cc",
+ "external_install_options.h",
"externally_installed_web_app_prefs.cc",
"externally_installed_web_app_prefs.h",
"install_bounce_metric.cc",
@@ -15,8 +17,6 @@ source_set("components") {
"install_manager.cc",
"install_manager.h",
"install_manager_observer.h",
- "install_options.cc",
- "install_options.h",
"pending_app_manager.cc",
"pending_app_manager.h",
"policy/web_app_policy_constants.cc",
@@ -47,7 +47,7 @@ source_set("components") {
"web_app_shortcut_win.h",
"web_app_tab_helper_base.cc",
"web_app_tab_helper_base.h",
- "web_app_ui_delegate.h",
+ "web_app_ui_manager.h",
"web_app_url_loader.cc",
"web_app_url_loader.h",
"web_app_utils.cc",
@@ -82,29 +82,13 @@ source_set("components") {
"//components/favicon/content",
"//components/keyed_service/content",
"//components/pref_registry",
+ "//components/user_manager:user_manager",
"//content/public/browser",
"//extensions/common:common_constants",
"//skia",
]
}
-source_set("test_support") {
- testonly = true
-
- sources = [
- "test_pending_app_manager.cc",
- "test_pending_app_manager.h",
- ]
-
- deps = [
- ":components",
- "//base",
- "//base/test:test_support",
- "//content/public/browser",
- "//url",
- ]
-}
-
source_set("unit_tests") {
testonly = true
@@ -117,6 +101,7 @@ source_set("unit_tests") {
"web_app_install_utils_unittest.cc",
"web_app_shortcut_mac_unittest.mm",
"web_app_shortcut_unittest.cc",
+ "web_app_utils_unittest.cc",
]
if (is_desktop_linux) {
@@ -126,16 +111,20 @@ source_set("unit_tests") {
deps = [
":components",
- ":test_support",
"//base/test:test_support",
"//chrome/app/theme:theme_resources",
"//chrome/browser/web_applications:web_app_test_group",
+ "//chrome/browser/web_applications:web_applications_test_support",
"//chrome/test:test_support",
"//content/public/browser",
"//skia",
"//testing/gmock",
"//testing/gtest",
]
+
+ if (is_chromeos) {
+ deps += [ "//chrome/browser/chromeos" ]
+ }
}
source_set("browser_tests") {
diff --git a/chromium/chrome/browser/web_applications/extensions/BUILD.gn b/chromium/chrome/browser/web_applications/extensions/BUILD.gn
index a85433dd639..6f05beba117 100644
--- a/chromium/chrome/browser/web_applications/extensions/BUILD.gn
+++ b/chromium/chrome/browser/web_applications/extensions/BUILD.gn
@@ -50,6 +50,7 @@ source_set("unit_tests") {
"externally_installed_web_app_prefs_unittest.cc",
"install_manager_bookmark_app_unittest.cc",
"pending_bookmark_app_manager_unittest.cc",
+ "web_app_provider_unittest.cc",
]
deps = [
@@ -77,6 +78,8 @@ source_set("browser_tests") {
testonly = true
sources = [
+ "bookmark_app_registrar_browsertest.cc",
+ "install_manager_bookmark_app_browsertest.cc",
"pending_bookmark_app_manager_browsertest.cc",
"web_app_audio_focus_browsertest.cc",
]