summaryrefslogtreecommitdiffstats
path: root/chromium/chrome/browser
diff options
context:
space:
mode:
authorAllan Sandfeld Jensen <allan.jensen@qt.io>2020-10-12 14:27:29 +0200
committerAllan Sandfeld Jensen <allan.jensen@qt.io>2020-10-13 09:35:20 +0000
commitc30a6232df03e1efbd9f3b226777b07e087a1122 (patch)
treee992f45784689f373bcc38d1b79a239ebe17ee23 /chromium/chrome/browser
parent7b5b123ac58f58ffde0f4f6e488bcd09aa4decd3 (diff)
BASELINE: Update Chromium to 85.0.4183.14085-based
Change-Id: Iaa42f4680837c57725b1344f108c0196741f6057 Reviewed-by: Allan Sandfeld Jensen <allan.jensen@qt.io>
Diffstat (limited to 'chromium/chrome/browser')
-rw-r--r--chromium/chrome/browser/BUILD.gn832
-rw-r--r--chromium/chrome/browser/accessibility/accessibility_extension_api.cc56
-rw-r--r--chromium/chrome/browser/accessibility/accessibility_extension_api.h13
-rw-r--r--chromium/chrome/browser/accessibility/accessibility_permission_context.cc7
-rw-r--r--chromium/chrome/browser/accessibility/accessibility_ui.cc36
-rw-r--r--chromium/chrome/browser/accessibility/accessibility_ui.h2
-rw-r--r--chromium/chrome/browser/accessibility/caption_controller.cc40
-rw-r--r--chromium/chrome/browser/accessibility/caption_controller.h12
-rw-r--r--chromium/chrome/browser/accessibility/caption_controller_browsertest.cc579
-rw-r--r--chromium/chrome/browser/accessibility/caption_host_impl.cc17
-rw-r--r--chromium/chrome/browser/accessibility/caption_host_impl.h3
-rw-r--r--chromium/chrome/browser/accessibility/image_annotation_browsertest.cc165
-rw-r--r--chromium/chrome/browser/android/examples/partner_browser_customizations_provider/BUILD.gn1
-rw-r--r--chromium/chrome/browser/android/metrics/BUILD.gn50
-rw-r--r--chromium/chrome/browser/android/vr/BUILD.gn4
-rw-r--r--chromium/chrome/browser/browser_controls/android/BUILD.gn40
-rw-r--r--chromium/chrome/browser/browser_resources.grd421
-rw-r--r--chromium/chrome/browser/browser_switcher/bho/BUILD.gn2
-rw-r--r--chromium/chrome/browser/buildflags.gni8
-rw-r--r--chromium/chrome/browser/chromeos/BUILD.gn222
-rw-r--r--chromium/chrome/browser/chromeos/local_search_service/proxy/BUILD.gn55
-rw-r--r--chromium/chrome/browser/chromeos/local_search_service/proxy/local_search_service_proxy.mojom55
-rw-r--r--chromium/chrome/browser/chromeos/local_search_service/proxy/types.mojom73
-rw-r--r--chromium/chrome/browser/chromeos/net/mojom/network_health.mojom33
-rw-r--r--chromium/chrome/browser/chromeos/net/network_diagnostics/network_diagnostics.mojom72
-rw-r--r--chromium/chrome/browser/contextmenu/BUILD.gn23
-rw-r--r--chromium/chrome/browser/dev_ui_browser_resources.grd133
-rw-r--r--chromium/chrome/browser/devtools/BUILD.gn9
-rw-r--r--chromium/chrome/browser/devtools/device/adb/adb_client_socket_browsertest.cc1
-rw-r--r--chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc12
-rw-r--r--chromium/chrome/browser/devtools/device/android_device_manager.cc5
-rw-r--r--chromium/chrome/browser/devtools/device/cast_device_provider.cc5
-rw-r--r--chromium/chrome/browser/devtools/device/devtools_device_discovery.cc5
-rw-r--r--chromium/chrome/browser/devtools/device/port_forwarding_controller.cc11
-rw-r--r--chromium/chrome/browser/devtools/device/tcp_device_provider.cc6
-rw-r--r--chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc3
-rw-r--r--chromium/chrome/browser/devtools/device/usb/usb_device_manager_helper.cc5
-rw-r--r--chromium/chrome/browser/devtools/devtools_browser_context_manager.cc2
-rw-r--r--chromium/chrome/browser/devtools/devtools_file_helper.cc10
-rw-r--r--chromium/chrome/browser/devtools/devtools_file_system_indexer.cc15
-rw-r--r--chromium/chrome/browser/devtools/devtools_file_watcher_unittest.cc2
-rw-r--r--chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc64
-rw-r--r--chromium/chrome/browser/devtools/devtools_ui_bindings.cc21
-rw-r--r--chromium/chrome/browser/devtools/devtools_window.cc56
-rw-r--r--chromium/chrome/browser/devtools/devtools_window.h6
-rw-r--r--chromium/chrome/browser/devtools/protocol/DEPS1
-rw-r--r--chromium/chrome/browser/devtools/protocol/browser_handler.cc5
-rw-r--r--chromium/chrome/browser/devtools/protocol/security_handler.cc1
-rw-r--r--chromium/chrome/browser/devtools/remote_debugging_server.cc13
-rw-r--r--chromium/chrome/browser/download/android/BUILD.gn61
-rw-r--r--chromium/chrome/browser/enterprise/util/BUILD.gn7
-rw-r--r--chromium/chrome/browser/extensions/BUILD.gn49
-rw-r--r--chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc7
-rw-r--r--chromium/chrome/browser/extensions/api/alarms/alarms_apitest.cc40
-rw-r--r--chromium/chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_api.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_api.h5
-rw-r--r--chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc20
-rw-r--r--chromium/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/autofill_private/autofill_util.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h2
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc35
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc17
-rw-r--r--chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h2
-rw-r--r--chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc57
-rw-r--r--chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.h3
-rw-r--r--chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc25
-rw-r--r--chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.cc19
-rw-r--r--chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.h3
-rw-r--r--chromium/chrome/browser/extensions/api/braille_display_private/mock_braille_controller.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc52
-rw-r--r--chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h38
-rw-r--r--chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc45
-rw-r--r--chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc420
-rw-r--r--chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc11
-rw-r--r--chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc16
-rw-r--r--chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h4
-rw-r--r--chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc11
-rw-r--r--chromium/chrome/browser/extensions/api/content_settings/content_settings_api_constants.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/content_settings/content_settings_api_constants.h2
-rw-r--r--chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc164
-rw-r--r--chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h5
-rw-r--r--chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc76
-rw-r--r--chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h10
-rw-r--r--chromium/chrome/browser/extensions/api/content_settings/content_settings_store_unittest.cc42
-rw-r--r--chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h3
-rw-r--r--chromium/chrome/browser/extensions/api/cookies/cookies_api.cc35
-rw-r--r--chromium/chrome/browser/extensions/api/cookies/cookies_api.h19
-rw-r--r--chromium/chrome/browser/extensions/api/cookies/cookies_apitest.cc57
-rw-r--r--chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h7
-rw-r--r--chromium/chrome/browser/extensions/api/debugger/debugger_api.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc20
-rw-r--r--chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc20
-rw-r--r--chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc26
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_content/content_action.cc30
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_content/content_action.h8
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc110
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_apitest.cc59
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc393
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_unittest.cc80
-rw-r--r--chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc52
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/DEPS6
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc25
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc9
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc16
-rw-r--r--chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc145
-rw-r--r--chromium/chrome/browser/extensions/api/downloads/downloads_api.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc174
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc25
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h1
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc206
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_networking_attributes/OWNERS3
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_api.cc90
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_api.h30
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_apitest.cc210
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc23
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc139
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h17
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc45
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h6
-rw-r--r--chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc49
-rw-r--r--chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc36
-rw-r--r--chromium/chrome/browser/extensions/api/extension_action/page_action_apitest.cc16
-rw-r--r--chromium/chrome/browser/extensions/api/extension_action/page_action_interactive_test.cc36
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/OWNERS1
-rw-r--r--chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.cc9
-rw-r--r--chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.cc143
-rw-r--r--chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.h67
-rw-r--r--chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow.cc33
-rw-r--r--chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow.h16
-rw-r--r--chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow_unittest.cc22
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_apitest.cc288
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_error.cc112
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_error.h90
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc175
-rw-r--r--chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h14
-rw-r--r--chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/operation.cc19
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc9
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc22
-rw-r--r--chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h12
-rw-r--r--chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc100
-rw-r--r--chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h14
-rw-r--r--chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc416
-rw-r--r--chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h126
-rw-r--r--chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h4
-rw-r--r--chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc75
-rw-r--r--chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h8
-rw-r--r--chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api_unittest.cc182
-rw-r--r--chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_unittest.cc12
-rw-r--r--chromium/chrome/browser/extensions/api/management/DEPS10
-rw-r--r--chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/management/management_api_unittest.cc166
-rw-r--r--chromium/chrome/browser/extensions/api/management/management_apitest.cc7
-rw-r--r--chromium/chrome/browser/extensions/api/management/management_browsertest.cc3
-rw-r--r--chromium/chrome/browser/extensions/api/mdns/mdns_apitest.cc46
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc7
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc45
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc9
-rw-r--r--chromium/chrome/browser/extensions/api/notifications/DEPS10
-rw-r--r--chromium/chrome/browser/extensions/api/page_capture/page_capture_api.cc13
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.cc190
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.h39
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate_unittest.cc22
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc32
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h37
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc22
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h22
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc75
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h12
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc77
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/passwords_private_utils_unittest.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.cc63
-rw-r--r--chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.h28
-rw-r--r--chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc97
-rw-r--r--chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h10
-rw-r--r--chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc17
-rw-r--r--chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc13
-rw-r--r--chromium/chrome/browser/extensions/api/preference/preference_apitest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/processes/processes_api.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc1
-rw-r--r--chromium/chrome/browser/extensions/api/resources_private/resources_private_api.cc122
-rw-r--r--chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc9
-rw-r--r--chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc264
-rw-r--r--chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h66
-rw-r--r--chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc205
-rw-r--r--chromium/chrome/browser/extensions/api/sessions/sessions_api.cc8
-rw-r--r--chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/generated_pref.cc29
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/generated_pref.h7
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/generated_pref_test_base.cc16
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/generated_pref_test_base.h66
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/generated_prefs.cc11
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc32
-rw-r--r--chromium/chrome/browser/extensions/api/settings_private/settings_private_apitest.cc23
-rw-r--r--chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/storage/policy_value_store.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/storage/settings_apitest.cc14
-rw-r--r--chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/tabs_api.cc23
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc4
-rw-r--r--chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc10
-rw-r--r--chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.cc5
-rw-r--r--chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc33
-rw-r--r--chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc7
-rw-r--r--chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc455
-rw-r--r--chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc40
-rw-r--r--chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc6
-rw-r--r--chromium/chrome/browser/extensions/api/webstore_private/extension_install_status.cc68
-rw-r--r--chromium/chrome/browser/extensions/api/webstore_private/extension_install_status.h19
-rw-r--r--chromium/chrome/browser/extensions/api/webstore_private/extension_install_status_unittest.cc306
-rw-r--r--chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc79
-rw-r--r--chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h6
-rw-r--r--chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc2
-rw-r--r--chromium/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc144
-rw-r--r--chromium/chrome/browser/flags/BUILD.gn1
-rw-r--r--chromium/chrome/browser/fullscreen/android/BUILD.gn14
-rw-r--r--chromium/chrome/browser/media/feeds/media_feeds_store.mojom45
-rw-r--r--chromium/chrome/browser/media/kaleidoscope/BUILD.gn44
-rw-r--r--chromium/chrome/browser/media/kaleidoscope/kaleidoscope_internal_resources.grd31
-rw-r--r--chromium/chrome/browser/media/kaleidoscope/kaleidoscope_resources.grd14
-rw-r--r--chromium/chrome/browser/media/kaleidoscope/mojom/BUILD.gn11
-rw-r--r--chromium/chrome/browser/media/kaleidoscope/mojom/kaleidoscope.mojom30
-rw-r--r--chromium/chrome/browser/media/kaleidoscope/test/proto/BUILD.gn (renamed from chromium/chrome/browser/resources/chromeos/camera/src/js/lib/BUILD.gn)13
-rw-r--r--chromium/chrome/browser/media/router/BUILD.gn10
-rw-r--r--chromium/chrome/browser/media/webrtc/DEPS3
-rw-r--r--chromium/chrome/browser/media/webrtc/audio_debug_recordings_handler.cc5
-rw-r--r--chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.cc84
-rw-r--r--chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.h15
-rw-r--r--chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context_unittest.cc151
-rw-r--r--chromium/chrome/browser/media/webrtc/desktop_capture_access_handler.cc12
-rw-r--r--chromium/chrome/browser/media/webrtc/desktop_media_list_base.cc11
-rw-r--r--chromium/chrome/browser/media/webrtc/desktop_media_picker_factory_impl.cc21
-rw-r--r--chromium/chrome/browser/media/webrtc/display_media_access_handler.cc24
-rw-r--r--chromium/chrome/browser/media/webrtc/fake_desktop_media_list.cc2
-rw-r--r--chromium/chrome/browser/media/webrtc/media_capture_devices_dispatcher.cc21
-rw-r--r--chromium/chrome/browser/media/webrtc/media_capture_devices_dispatcher_unittest.cc4
-rw-r--r--chromium/chrome/browser/media/webrtc/media_stream_capture_indicator.cc56
-rw-r--r--chromium/chrome/browser/media/webrtc/media_stream_capture_indicator.h7
-rw-r--r--chromium/chrome/browser/media/webrtc/media_stream_capture_indicator_unittest.cc86
-rw-r--r--chromium/chrome/browser/media/webrtc/media_stream_devices_controller_browsertest.cc243
-rw-r--r--chromium/chrome/browser/media/webrtc/native_desktop_media_list.cc35
-rw-r--r--chromium/chrome/browser/media/webrtc/native_desktop_media_list.h1
-rw-r--r--chromium/chrome/browser/media/webrtc/native_desktop_media_list_unittest.cc4
-rw-r--r--chromium/chrome/browser/media/webrtc/permission_bubble_media_access_handler.cc5
-rw-r--r--chromium/chrome/browser/media/webrtc/tab_desktop_media_list_unittest.cc22
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_disable_encryption_flag_browsertest.cc5
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_event_log_history.cc11
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_event_log_manager.cc27
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc4
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_common_unittest.cc6
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.cc66
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.h6
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc29
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader.cc92
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader.h36
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader_impl_unittest.cc39
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_log_uploader_unittest.cc4
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_logging_controller.cc5
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_pan_tilt_zoom_browsertest.cc249
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.cc12
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_rtp_dump_handler_unittest.cc1
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_simulcast_browsertest.cc66
-rw-r--r--chromium/chrome/browser/media/webrtc/webrtc_text_log_handler.cc13
-rw-r--r--chromium/chrome/browser/media/webrtc/window_icon_util_x11.cc33
-rw-r--r--chromium/chrome/browser/metrics/BUILD.gn4
-rw-r--r--chromium/chrome/browser/nearby_sharing/certificates/BUILD.gn61
-rw-r--r--chromium/chrome/browser/nearby_sharing/logging/BUILD.gn24
-rw-r--r--chromium/chrome/browser/nearby_sharing/proto/BUILD.gn17
-rw-r--r--chromium/chrome/browser/nearby_sharing/tachyon/proto/BUILD.gn (renamed from chromium/chrome/browser/enterprise/connectors/BUILD.gn)11
-rw-r--r--chromium/chrome/browser/net/BUILD.gn10
-rw-r--r--chromium/chrome/browser/net/cert_verify_proc_browsertest.cc23
-rw-r--r--chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc8
-rw-r--r--chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory_browsertest.cc9
-rw-r--r--chromium/chrome/browser/net/chrome_network_service_browsertest.cc7
-rw-r--r--chromium/chrome/browser/net/cookie_policy_browsertest.cc178
-rw-r--r--chromium/chrome/browser/net/dns_over_https_browsertest.cc19
-rw-r--r--chromium/chrome/browser/net/dns_probe_browsertest.cc27
-rw-r--r--chromium/chrome/browser/net/errorpage_browsertest.cc43
-rw-r--r--chromium/chrome/browser/net/net_error_tab_helper.cc73
-rw-r--r--chromium/chrome/browser/net/net_error_tab_helper.h20
-rw-r--r--chromium/chrome/browser/net/net_error_tab_helper_unittest.cc8
-rw-r--r--chromium/chrome/browser/net/network_context_configuration_browsertest.cc23
-rw-r--r--chromium/chrome/browser/net/network_quality_estimator_prefs_browsertest.cc6
-rw-r--r--chromium/chrome/browser/net/network_quality_tracker_browsertest.cc4
-rw-r--r--chromium/chrome/browser/net/network_request_metrics_browsertest.cc8
-rw-r--r--chromium/chrome/browser/net/nss_context.cc5
-rw-r--r--chromium/chrome/browser/net/nss_context_chromeos_browsertest.cc13
-rw-r--r--chromium/chrome/browser/net/probe_message.cc1
-rw-r--r--chromium/chrome/browser/net/profile_network_context_service.cc129
-rw-r--r--chromium/chrome/browser/net/profile_network_context_service_browsertest.cc166
-rw-r--r--chromium/chrome/browser/net/referrer_policy_policy_handler_unittest.cc12
-rw-r--r--chromium/chrome/browser/net/secure_dns_config.h2
-rw-r--r--chromium/chrome/browser/net/secure_dns_util.cc85
-rw-r--r--chromium/chrome/browser/net/secure_dns_util.h27
-rw-r--r--chromium/chrome/browser/net/secure_dns_util_unittest.cc120
-rw-r--r--chromium/chrome/browser/net/storage_test_utils.cc102
-rw-r--r--chromium/chrome/browser/net/storage_test_utils.h51
-rw-r--r--chromium/chrome/browser/net/stub_resolver_config_reader.cc43
-rw-r--r--chromium/chrome/browser/net/stub_resolver_config_reader.h38
-rw-r--r--chromium/chrome/browser/net/system_network_context_manager.cc14
-rw-r--r--chromium/chrome/browser/net/system_network_context_manager.h14
-rw-r--r--chromium/chrome/browser/net/system_network_context_manager_browsertest.cc130
-rw-r--r--chromium/chrome/browser/net/trial_comparison_cert_verifier_browsertest.cc18
-rw-r--r--chromium/chrome/browser/net/trial_comparison_cert_verifier_controller_unittest.cc20
-rw-r--r--chromium/chrome/browser/net/variations_http_headers_browsertest.cc102
-rw-r--r--chromium/chrome/browser/net/websocket_browsertest.cc2
-rw-r--r--chromium/chrome/browser/offline_pages/android/BUILD.gn1
-rw-r--r--chromium/chrome/browser/optimization_guide/android/BUILD.gn2
-rw-r--r--chromium/chrome/browser/page_load_metrics/integration_tests/sources.gni1
-rw-r--r--chromium/chrome/browser/password_check/android/BUILD.gn23
-rw-r--r--chromium/chrome/browser/payments/BUILD.gn6
-rw-r--r--chromium/chrome/browser/payments/android/BUILD.gn1
-rw-r--r--chromium/chrome/browser/preferences/BUILD.gn27
-rw-r--r--chromium/chrome/browser/prefs/OWNERS2
-rw-r--r--chromium/chrome/browser/prefs/browser_prefs.cc83
-rw-r--r--chromium/chrome/browser/prefs/chrome_command_line_pref_store_ssl_manager_unittest.cc3
-rw-r--r--chromium/chrome/browser/prefs/chrome_pref_service_factory.cc46
-rw-r--r--chromium/chrome/browser/prefs/incognito_mode_prefs.cc7
-rw-r--r--chromium/chrome/browser/prefs/pref_service_incognito_allowlist.cc (renamed from chromium/chrome/browser/prefs/pref_service_incognito_whitelist.cc)6
-rw-r--r--chromium/chrome/browser/prefs/pref_service_incognito_allowlist.h (renamed from chromium/chrome/browser/prefs/pref_service_incognito_whitelist.h)8
-rw-r--r--chromium/chrome/browser/prefs/pref_service_syncable_util.cc4
-rw-r--r--chromium/chrome/browser/prefs/tracked/pref_hash_browsertest.cc65
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc27
-rw-r--r--chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc4
-rw-r--r--chromium/chrome/browser/printing/pdf_to_emf_converter_browsertest.cc20
-rw-r--r--chromium/chrome/browser/printing/print_browsertest.cc316
-rw-r--r--chromium/chrome/browser/printing/print_error_dialog.cc5
-rw-r--r--chromium/chrome/browser/printing/print_job.cc13
-rw-r--r--chromium/chrome/browser/printing/print_job_manager.h1
-rw-r--r--chromium/chrome/browser/printing/print_job_worker.cc39
-rw-r--r--chromium/chrome/browser/printing/print_preview_dialog_controller.cc2
-rw-r--r--chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc40
-rw-r--r--chromium/chrome/browser/printing/print_preview_dialog_controller_unittest.cc15
-rw-r--r--chromium/chrome/browser/printing/print_preview_message_handler.cc52
-rw-r--r--chromium/chrome/browser/printing/print_preview_message_handler.h19
-rw-r--r--chromium/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc3
-rw-r--r--chromium/chrome/browser/printing/print_view_manager.cc8
-rw-r--r--chromium/chrome/browser/printing/print_view_manager_base.cc41
-rw-r--r--chromium/chrome/browser/printing/print_view_manager_base.h5
-rw-r--r--chromium/chrome/browser/printing/print_view_manager_unittest.cc4
-rw-r--r--chromium/chrome/browser/printing/printer_manager_dialog_linux.cc1
-rw-r--r--chromium/chrome/browser/printing/printer_query.cc4
-rw-r--r--chromium/chrome/browser/printing/printing_message_filter.cc8
-rw-r--r--chromium/chrome/browser/printing/printing_service.cc5
-rw-r--r--chromium/chrome/browser/privacy_budget/BUILD.gn41
-rw-r--r--chromium/chrome/browser/renderer_host/chrome_extension_message_filter.cc3
-rw-r--r--chromium/chrome/browser/renderer_host/chrome_navigation_ui_data.h9
-rw-r--r--chromium/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_browsertest.mm6
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/device_id_fetcher.cc13
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm5
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc3
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc10
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc9
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/pepper_flash_drm_host.cc5
-rw-r--r--chromium/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc3
-rw-r--r--chromium/chrome/browser/resource_coordinator/lifecycle_unit_state.mojom10
-rw-r--r--chromium/chrome/browser/resources/BUILD.gn118
-rw-r--r--chromium/chrome/browser/resources/accessibility/accessibility.html43
-rw-r--r--chromium/chrome/browser/resources/accessibility/accessibility.js6
-rw-r--r--chromium/chrome/browser/resources/bluetooth_internals/resources.grd87
-rw-r--r--chromium/chrome/browser/resources/bookmarks/BUILD.gn30
-rw-r--r--chromium/chrome/browser/resources/bookmarks/actions.js2
-rw-r--r--chromium/chrome/browser/resources/bookmarks/api_listener.js2
-rw-r--r--chromium/chrome/browser/resources/bookmarks/bookmarks.html3
-rw-r--r--chromium/chrome/browser/resources/bookmarks/bookmarks_resources_vulcanized.grd6
-rw-r--r--chromium/chrome/browser/resources/bookmarks/command_manager.js2
-rw-r--r--chromium/chrome/browser/resources/bookmarks/item.html4
-rw-r--r--chromium/chrome/browser/resources/bookmarks/toolbar.html1
-rw-r--r--chromium/chrome/browser/resources/bookmarks/types.js2
-rw-r--r--chromium/chrome/browser/resources/bookmarks/util.js4
-rw-r--r--chromium/chrome/browser/resources/chromeos/BUILD.gn24
-rw-r--r--chromium/chrome/browser/resources/chromeos/accessibility/BUILD.gn20
-rw-r--r--chromium/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn87
-rw-r--r--chromium/chrome/browser/resources/chromeos/accessibility/autoclick/BUILD.gn123
-rw-r--r--chromium/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn43
-rw-r--r--chromium/chrome/browser/resources/chromeos/accessibility/chromevox/i_tutorial/components/BUILD.gn33
-rw-r--r--chromium/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn12
-rw-r--r--chromium/chrome/browser/resources/chromeos/accessibility/common/run_jsbundler.gni (renamed from chromium/chrome/browser/resources/chromeos/accessibility/chromevox/run_jsbundler.gni)0
-rw-r--r--chromium/chrome/browser/resources/chromeos/accessibility/select_to_speak/BUILD.gn6
-rw-r--r--chromium/chrome/browser/resources/chromeos/accessibility/strings/chromevox_strings.grdp8
-rw-r--r--chromium/chrome/browser/resources/chromeos/accessibility/strings/select_to_speak_strings.grdp6
-rw-r--r--chromium/chrome/browser/resources/chromeos/accessibility/switch_access/BUILD.gn117
-rw-r--r--chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/BUILD.gn69
-rw-r--r--chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/bluetooth_pairing_dialog_resources.grd28
-rw-r--r--chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/bluetooth_pairing_dialog_resources_vulcanized.grd25
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/BUILD.gn252
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd137
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/BUILD.gn150
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/browser_proxy/BUILD.gn28
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/device/BUILD.gn44
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/externs/BUILD.gn17
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn43
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/mojo/BUILD.gn39
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/views/BUILD.gn67
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/js/views/camera/BUILD.gn77
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/strings/BUILD.gn71
-rw-r--r--chromium/chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd366
-rw-r--r--chromium/chrome/browser/resources/chromeos/internet_config_dialog/BUILD.gn8
-rw-r--r--chromium/chrome/browser/resources/chromeos/login/BUILD.gn29
-rw-r--r--chromium/chrome/browser/resources/chromeos/login/components/BUILD.gn6
-rw-r--r--chromium/chrome/browser/resources/chromeos/network_ui/BUILD.gn33
-rw-r--r--chromium/chrome/browser/resources/component_extension_resources.grd8
-rw-r--r--chromium/chrome/browser/resources/components/components.js2
-rw-r--r--chromium/chrome/browser/resources/conflicts/about_conflicts.html2
-rw-r--r--chromium/chrome/browser/resources/cryptotoken/enroller.js10
-rw-r--r--chromium/chrome/browser/resources/default_apps/external_extensions.json3
-rw-r--r--chromium/chrome/browser/resources/discards/OWNERS2
-rw-r--r--chromium/chrome/browser/resources/discards/discards_tab.html20
-rw-r--r--chromium/chrome/browser/resources/discards/discards_tab.js48
-rw-r--r--chromium/chrome/browser/resources/discards/graph_doc.js265
-rw-r--r--chromium/chrome/browser/resources/discards/graph_doc_template.html27
-rw-r--r--chromium/chrome/browser/resources/downloads/BUILD.gn1
-rw-r--r--chromium/chrome/browser/resources/downloads/downloads.html3
-rw-r--r--chromium/chrome/browser/resources/downloads/downloads_resources_vulcanized.grd5
-rw-r--r--chromium/chrome/browser/resources/downloads/toolbar.html1
-rw-r--r--chromium/chrome/browser/resources/extensions/BUILD.gn12
-rw-r--r--chromium/chrome/browser/resources/extensions/detail_view.html2
-rw-r--r--chromium/chrome/browser/resources/extensions/detail_view.js12
-rw-r--r--chromium/chrome/browser/resources/extensions/extensions.html2
-rw-r--r--chromium/chrome/browser/resources/extensions/extensions_resources_vulcanized.grd12
-rw-r--r--chromium/chrome/browser/resources/extensions/item.html2
-rw-r--r--chromium/chrome/browser/resources/extensions/item.js10
-rw-r--r--chromium/chrome/browser/resources/extensions/item_util.js8
-rw-r--r--chromium/chrome/browser/resources/feedback/html/default.html29
-rw-r--r--chromium/chrome/browser/resources/feedback/js/event_handler.js15
-rw-r--r--chromium/chrome/browser/resources/gaia_auth_host/authenticator.js2
-rw-r--r--chromium/chrome/browser/resources/gaia_auth_host/gaia_auth_host_resources.grd21
-rw-r--r--chromium/chrome/browser/resources/gaia_auth_host/password_change_authenticator.js67
-rw-r--r--chromium/chrome/browser/resources/history/history.html2
-rw-r--r--chromium/chrome/browser/resources/history/history_resources_vulcanized.grd8
-rw-r--r--chromium/chrome/browser/resources/inline_login/inline_login.js9
-rw-r--r--chromium/chrome/browser/resources/internals/query_tiles/BUILD.gn25
-rw-r--r--chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals.html31
-rw-r--r--chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals.js49
-rw-r--r--chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals_browser_proxy.js75
-rw-r--r--chromium/chrome/browser/resources/interventions_internals/index.css12
-rw-r--r--chromium/chrome/browser/resources/interventions_internals/index.html26
-rw-r--r--chromium/chrome/browser/resources/interventions_internals/index.js76
-rw-r--r--chromium/chrome/browser/resources/invalidations/about_invalidations.html1
-rw-r--r--chromium/chrome/browser/resources/invalidations/invalidations_resources.grd6
-rw-r--r--chromium/chrome/browser/resources/local_ntp/externs.js1
-rw-r--r--chromium/chrome/browser/resources/local_ntp/icons.grdp28
-rw-r--r--chromium/chrome/browser/resources/local_ntp/local_ntp.js44
-rw-r--r--chromium/chrome/browser/resources/local_ntp/voice.js4
-rw-r--r--chromium/chrome/browser/resources/management/management_browser_proxy.js1
-rw-r--r--chromium/chrome/browser/resources/management/management_ui.html4
-rw-r--r--chromium/chrome/browser/resources/management/management_ui.js2
-rw-r--r--chromium/chrome/browser/resources/media/media_data_table.js2
-rw-r--r--chromium/chrome/browser/resources/media/media_feeds.html15
-rw-r--r--chromium/chrome/browser/resources/media/media_feeds.js68
-rw-r--r--chromium/chrome/browser/resources/media/media_history.js2
-rw-r--r--chromium/chrome/browser/resources/media/webrtc_logs_resources.grd6
-rw-r--r--chromium/chrome/browser/resources/nearby_internals/BUILD.gn21
-rw-r--r--chromium/chrome/browser/resources/nearby_internals/OWNERS4
-rw-r--r--chromium/chrome/browser/resources/nearby_internals/index.html17
-rw-r--r--chromium/chrome/browser/resources/nearby_internals/nearby_internals.html1
-rw-r--r--chromium/chrome/browser/resources/nearby_internals/nearby_internals.js11
-rw-r--r--chromium/chrome/browser/resources/nearby_internals/nearby_internals_resources.grd24
-rw-r--r--chromium/chrome/browser/resources/nearby_share/BUILD.gn35
-rw-r--r--chromium/chrome/browser/resources/nearby_share/OWNERS3
-rw-r--r--chromium/chrome/browser/resources/nearby_share/app.html4
-rw-r--r--chromium/chrome/browser/resources/nearby_share/app.js34
-rw-r--r--chromium/chrome/browser/resources/nearby_share/nearby_discovery_page.html1
-rw-r--r--chromium/chrome/browser/resources/nearby_share/nearby_discovery_page.js16
-rw-r--r--chromium/chrome/browser/resources/nearby_share/nearby_share_dialog.html17
-rw-r--r--chromium/chrome/browser/resources/nearby_share/nearby_share_dialog_resources.grd28
-rw-r--r--chromium/chrome/browser/resources/net_internals/browser_bridge.js63
-rw-r--r--chromium/chrome/browser/resources/net_internals/chromeos_view.html83
-rw-r--r--chromium/chrome/browser/resources/net_internals/chromeos_view.js250
-rw-r--r--chromium/chrome/browser/resources/net_internals/domain_security_policy_view.html7
-rw-r--r--chromium/chrome/browser/resources/net_internals/domain_security_policy_view.js28
-rw-r--r--chromium/chrome/browser/resources/net_internals/events_view.html2
-rw-r--r--chromium/chrome/browser/resources/net_internals/index.html1
-rw-r--r--chromium/chrome/browser/resources/net_internals/net_internals_resources.grd4
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/BUILD.gn17
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/app.html45
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/app.js157
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/browser_proxy.js8
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/customize_backgrounds.html15
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/customize_backgrounds.js2
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/customize_dialog.html27
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/customize_themes.html1
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/iframe.html (renamed from chromium/chrome/browser/resources/new_tab_page/untrusted_iframe.html)0
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/iframe.js (renamed from chromium/chrome/browser/resources/new_tab_page/untrusted_iframe.js)26
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/logo.html102
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/logo.js203
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/most_visited.html1
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources.grd7
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources_common.grdp65
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources_vulcanized.grd2
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/realbox.html2
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/realbox.js10
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/realbox_dropdown.html6
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/realbox_dropdown.js6
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/realbox_match.html2
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/realbox_match.js3
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/untrusted/iframe.html24
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/untrusted/one_google_bar.html2
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/untrusted/one_google_bar.js269
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/voice_search_overlay.html61
-rw-r--r--chromium/chrome/browser/resources/new_tab_page/voice_search_overlay.js114
-rw-r--r--chromium/chrome/browser/resources/omnibox/resources.grd38
-rw-r--r--chromium/chrome/browser/resources/optimize_webui.gni11
-rwxr-xr-xchromium/chrome/browser/resources/optimize_webui.py59
-rw-r--r--chromium/chrome/browser/resources/pdf/BUILD.gn95
-rw-r--r--chromium/chrome/browser/resources/pdf/annotation_tool.js2
-rw-r--r--chromium/chrome/browser/resources/pdf/browser_api.js20
-rw-r--r--chromium/chrome/browser/resources/pdf/constants.js11
-rw-r--r--chromium/chrome/browser/resources/pdf/controller.js145
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/BUILD.gn18
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-bookmark.html4
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-error-screen.html6
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-error-screen.js2
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-form-warning.html8
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-form-warning.js4
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-ink-host.js25
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator.html2
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-page-selector.html19
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-page-selector.js2
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-password-screen.html9
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-password-screen.js8
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.html10
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.js17
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar.html80
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar.js161
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-pen-options.html6
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-pen-options.js39
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown.html10
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-zoom-button.html9
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar.html2
-rw-r--r--chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar.js54
-rw-r--r--chromium/chrome/browser/resources/pdf/gesture_detector.js123
-rw-r--r--chromium/chrome/browser/resources/pdf/index.css50
-rw-r--r--chromium/chrome/browser/resources/pdf/index.html21
-rw-r--r--chromium/chrome/browser/resources/pdf/index_pp.html19
-rw-r--r--chromium/chrome/browser/resources/pdf/ink/externs.js74
-rw-r--r--chromium/chrome/browser/resources/pdf/ink/index.html2
-rw-r--r--chromium/chrome/browser/resources/pdf/ink/ink_api.js100
-rw-r--r--chromium/chrome/browser/resources/pdf/ink_controller.js128
-rw-r--r--chromium/chrome/browser/resources/pdf/main.js81
-rw-r--r--chromium/chrome/browser/resources/pdf/main_pp.js12
-rw-r--r--chromium/chrome/browser/resources/pdf/main_util.js83
-rw-r--r--chromium/chrome/browser/resources/pdf/metrics.js77
-rw-r--r--chromium/chrome/browser/resources/pdf/navigator.js8
-rw-r--r--chromium/chrome/browser/resources/pdf/open_pdf_params_parser.js85
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf_scripting_api.js47
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf_viewer.html61
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf_viewer.js1446
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf_viewer_base.js640
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf_viewer_pp.html21
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf_viewer_pp.js379
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf_viewer_shared_style.html33
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf_viewer_shared_style.js11
-rw-r--r--chromium/chrome/browser/resources/pdf/pdf_viewer_utils.js64
-rw-r--r--chromium/chrome/browser/resources/pdf/toolbar_manager.js48
-rw-r--r--chromium/chrome/browser/resources/pdf/viewport.js418
-rw-r--r--chromium/chrome/browser/resources/pdf/viewport_scroller.js15
-rw-r--r--chromium/chrome/browser/resources/pdf/zoom_manager.js36
-rw-r--r--chromium/chrome/browser/resources/print_preview/BUILD.gn16
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/BUILD.gn4
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/destination.js28
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/destination_store.js4
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/model.js6
-rw-r--r--chromium/chrome/browser/resources/print_preview/data/printer_status_cros.js56
-rw-r--r--chromium/chrome/browser/resources/print_preview/metrics.js4
-rw-r--r--chromium/chrome/browser/resources/print_preview/native_layer.js229
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview.html3
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview.js11
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview_pdf_resources.grd28
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview_resources.grd20
-rw-r--r--chromium/chrome/browser/resources/print_preview/print_preview_resources_vulcanized.grd14
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/BUILD.gn24
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/app.js4
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/button_strip.js25
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_dialog.js15
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_dropdown_cros.html150
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_dropdown_cros.js273
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_select_cros.html15
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_select_cros.js251
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/destination_settings.js7
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/header.js53
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/link_container.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/more_settings.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/preview_area.js4
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/print_preview_search_box.html2
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/print_preview_vars_css.html4
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/printer_status_icon_cros.html67
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/printer_status_icon_cros.js40
-rw-r--r--chromium/chrome/browser/resources/print_preview/ui/select_behavior.js9
-rw-r--r--chromium/chrome/browser/resources/quota_internals/event_handler.js18
-rw-r--r--chromium/chrome/browser/resources/quota_internals/main.html30
-rw-r--r--chromium/chrome/browser/resources/quota_internals/message_dispatcher.js10
-rw-r--r--chromium/chrome/browser/resources/quota_internals/quota_internals_resources.grd6
-rw-r--r--chromium/chrome/browser/resources/settings/BUILD.gn9
-rw-r--r--chromium/chrome/browser/resources/settings/autofill_page/BUILD.gn131
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/BUILD.gn149
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/ambient_mode_page/BUILD.gn49
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/bluetooth_page/BUILD.gn83
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/crostini_page/BUILD.gn9
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/date_time_page/BUILD.gn23
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/device_page/BUILD.gn8
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/localized_link/BUILD.gn23
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/multidevice_page/BUILD.gn1
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/plugin_vm_page/BUILD.gn15
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_languages_page/BUILD.gn51
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_privacy_page/BUILD.gn6
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_reset_page/BUILD.gn46
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_settings.gni24
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_settings_page/BUILD.gn1
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_settings_resources_v3.grdp130
-rw-r--r--chromium/chrome/browser/resources/settings/chromeos/os_settings_search_box/BUILD.gn4
-rw-r--r--chromium/chrome/browser/resources/settings/controls/BUILD.gn6
-rw-r--r--chromium/chrome/browser/resources/settings/nearby_share_page/BUILD.gn54
-rw-r--r--chromium/chrome/browser/resources/settings/os_settings_resources.grd66
-rw-r--r--chromium/chrome/browser/resources/settings/os_settings_resources_vulcanized.grd41
-rw-r--r--chromium/chrome/browser/resources/settings/safety_check_page/BUILD.gn47
-rw-r--r--chromium/chrome/browser/resources/settings/settings.gni2
-rw-r--r--chromium/chrome/browser/resources/settings/settings_page/BUILD.gn5
-rw-r--r--chromium/chrome/browser/resources/settings/settings_resources_v3.grdp67
-rw-r--r--chromium/chrome/browser/resources/settings/settings_resources_vulcanized.grd42
-rw-r--r--chromium/chrome/browser/resources/signin/BUILD.gn3
-rw-r--r--chromium/chrome/browser/resources/signin/profile_picker/BUILD.gn36
-rw-r--r--chromium/chrome/browser/resources/signin/profile_picker/icons.js15
-rw-r--r--chromium/chrome/browser/resources/signin/profile_picker/profile_picker.html11
-rw-r--r--chromium/chrome/browser/resources/signin/profile_picker/profile_picker_app.html12
-rw-r--r--chromium/chrome/browser/resources/signin/profile_picker/profile_picker_app.js14
-rw-r--r--chromium/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.html54
-rw-r--r--chromium/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.js20
-rw-r--r--chromium/chrome/browser/resources/signin/profile_picker/profile_picker_resources.grd14
-rw-r--r--chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation_app.html13
-rw-r--r--chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation_app.js14
-rw-r--r--chromium/chrome/browser/resources/signin/signin_error/signin_error.js8
-rw-r--r--chromium/chrome/browser/resources/signin/signin_error/signin_error_app.html16
-rw-r--r--chromium/chrome/browser/resources/signin/signin_error/signin_error_app.js26
-rw-r--r--chromium/chrome/browser/resources/signin/signin_reauth/BUILD.gn33
-rw-r--r--chromium/chrome/browser/resources/signin/signin_reauth/images/account_passwords_reauth_illustration.svg1
-rw-r--r--chromium/chrome/browser/resources/signin/signin_reauth/images/account_passwords_reauth_illustration_dark.svg1
-rw-r--r--chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth.html24
-rw-r--r--chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_app.html87
-rw-r--r--chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_app.js78
-rw-r--r--chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_browser_proxy.js47
-rw-r--r--chromium/chrome/browser/resources/signin/signin_shared_css.html9
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js5
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.html14
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.js21
-rw-r--r--chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation_app.html8
-rw-r--r--chromium/chrome/browser/resources/tab_strip/drag_manager.js19
-rw-r--r--chromium/chrome/browser/resources/tab_strip/tab.js26
-rw-r--r--chromium/chrome/browser/resources/tab_strip/tab_group.js21
-rw-r--r--chromium/chrome/browser/resources/tab_strip/tab_list.html3
-rw-r--r--chromium/chrome/browser/resources/tab_strip/tab_list.js227
-rw-r--r--chromium/chrome/browser/resources/tab_strip/tab_strip_embedder_proxy.js97
-rw-r--r--chromium/chrome/browser/resources/tab_strip/tab_strip_resources.grd60
-rw-r--r--chromium/chrome/browser/resources/tab_strip/tabs_api_proxy.js94
-rw-r--r--chromium/chrome/browser/resources/tools/rollup_plugin.js7
-rwxr-xr-xchromium/chrome/browser/resources/unpack_pak.py55
-rwxr-xr-xchromium/chrome/browser/resources/unpack_pak_test.py65
-rw-r--r--chromium/chrome/browser/resources/usb_internals/resources.grd18
-rw-r--r--chromium/chrome/browser/resources/user_manager/create_profile.js10
-rw-r--r--chromium/chrome/browser/resources/web_app_internals/BUILD.gn22
-rw-r--r--chromium/chrome/browser/resources/web_app_internals/OWNERS1
-rw-r--r--chromium/chrome/browser/resources/web_app_internals/index.html12
-rw-r--r--chromium/chrome/browser/resources/web_app_internals/web_app_internals.html76
-rw-r--r--chromium/chrome/browser/resources/web_app_internals/web_app_internals.js88
-rw-r--r--chromium/chrome/browser/resources/webapks/webapks_ui_resources.grd6
-rw-r--r--chromium/chrome/browser/resources/welcome/welcome_resources.grd48
-rw-r--r--chromium/chrome/browser/safe_browsing/BUILD.gn36
-rw-r--r--chromium/chrome/browser/safe_browsing/android/BUILD.gn28
-rw-r--r--chromium/chrome/browser/safety_check/android/BUILD.gn90
-rw-r--r--chromium/chrome/browser/settings/BUILD.gn8
-rw-r--r--chromium/chrome/browser/share/BUILD.gn2
-rw-r--r--chromium/chrome/browser/share/android/BUILD.gn11
-rw-r--r--chromium/chrome/browser/share/android/java_sources.gni19
-rw-r--r--chromium/chrome/browser/share/android/test_java_sources.gni7
-rw-r--r--chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc4
-rw-r--r--chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h4
-rw-r--r--chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl_win_browsertest.cc9
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc6
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_factory.cc7
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_factory.h7
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc82
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h20
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_language_policy_handlers_unittest.cc16
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_service.cc352
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_service.h98
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc175
-rw-r--r--chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc459
-rw-r--r--chromium/chrome/browser/spellchecker/spelling_request.cc5
-rw-r--r--chromium/chrome/browser/subresource_filter/BUILD.gn1
-rw-r--r--chromium/chrome/browser/tab/BUILD.gn10
-rw-r--r--chromium/chrome/browser/tab_contents/form_interaction_tab_helper.cc5
-rw-r--r--chromium/chrome/browser/tab_contents/form_interaction_tab_helper_unittest.cc14
-rw-r--r--chromium/chrome/browser/tab_contents/navigation_metrics_recorder_browsertest.cc11
-rw-r--r--chromium/chrome/browser/tab_contents/view_source_browsertest.cc21
-rw-r--r--chromium/chrome/browser/tabmodel/BUILD.gn31
-rw-r--r--chromium/chrome/browser/thumbnail/generator/BUILD.gn1
-rw-r--r--chromium/chrome/browser/touch_to_fill/android/BUILD.gn16
-rw-r--r--chromium/chrome/browser/touch_to_fill/android/internal/BUILD.gn1
-rw-r--r--chromium/chrome/browser/ui/BUILD.gn962
-rw-r--r--chromium/chrome/browser/ui/android/appmenu/BUILD.gn6
-rw-r--r--chromium/chrome/browser/ui/android/appmenu/internal/BUILD.gn5
-rw-r--r--chromium/chrome/browser/ui/android/default_browser_promo/BUILD.gn78
-rw-r--r--chromium/chrome/browser/ui/android/native_page/BUILD.gn1
-rw-r--r--chromium/chrome/browser/ui/android/strings/android_chrome_strings.grd331
-rw-r--r--chromium/chrome/browser/ui/android/strings/xr_consent_ui_strings_java.grdp29
-rw-r--r--chromium/chrome/browser/ui/ash/assistant/test_support/BUILD.gn17
-rw-r--r--chromium/chrome/browser/ui/messages/android/BUILD.gn29
-rw-r--r--chromium/chrome/browser/ui/webui/DEPS9
-rw-r--r--chromium/chrome/browser/ui/webui/about_ui.cc21
-rw-r--r--chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc26
-rw-r--r--chromium/chrome/browser/ui/webui/app_launcher_page_ui.h5
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/BUILD.gn2
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/app_management.mojom4
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/app_management_page_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc299
-rw-r--r--chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc79
-rw-r--r--chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory_browsertest.cc42
-rw-r--r--chromium/chrome/browser/ui/webui/chrome_webui_navigation_browsertest.cc28
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/DEPS7
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager/OWNERS2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_error_ui.cc (renamed from chromium/chrome/browser/ui/webui/chromeos/account_manager_error_ui.cc)6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_error_ui.h (renamed from chromium/chrome/browser/ui/webui/chromeos/account_manager_error_ui.h)6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_dialog.cc (renamed from chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc)2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_dialog.h (renamed from chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h)6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_ui.cc (renamed from chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.cc)6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_ui.h (renamed from chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h)6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_dialog.cc (renamed from chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc)4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_dialog.h (renamed from chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h)6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_ui.cc (renamed from chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc)18
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_ui.h (renamed from chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h)6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_migration_proxy_test.js23
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_test.js89
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui_test.cc31
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui_test.h21
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler.cc18
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc10
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils_unittest.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui_browsertest.cc34
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/assistant_optin/assistant_optin_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc28
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc86
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.h27
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer.mojom16
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_dialog.cc16
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_page_handler.cc18
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_page_handler.h9
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_ui.cc30
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_ui.h9
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader.mojom16
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.cc30
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.h4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog_browsertest.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_page_handler.cc70
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_page_handler.h9
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_ui.cc20
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_ui.h9
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc198
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/edu_account_login_handler_chromeos.cc12
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc88
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/OWNERS1
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.h3
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/DEPS3
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc120
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h70
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/assistant_optin_flow_screen_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc193
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h31
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/debug/debug_overlay_handler.cc10
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.cc42
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.h17
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.cc24
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/fake_update_required_screen_handler.h1
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.cc97
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.h43
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/gaia_password_changed_screen_handler.cc77
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/gaia_password_changed_screen_handler.h64
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc27
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h20
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/native_window_delegate.h24
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_display_chooser.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc64
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/saml_challenge_key_handler.cc1
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc101
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h22
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/supervision_transition_screen_handler.cc10
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/supervision_transition_screen_handler.h3
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.cc33
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.h17
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/tpm_error_screen_handler.cc62
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/tpm_error_screen_handler.h60
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/update_screen_handler.h2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.cc103
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.h17
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.cc31
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.h21
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.cc63
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/network_logs_message_handler.cc203
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/network_logs_message_handler.h56
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/network_ui.cc187
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/network_ui.h9
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/onc_import_message_handler.cc124
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/onc_import_message_handler.h57
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.h1
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.h1
-rw-r--r--chromium/chrome/browser/ui/webui/components/components_handler.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/components/components_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc9
-rw-r--r--chromium/chrome/browser/ui/webui/conflicts/conflicts_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/devtools_ui_data_source.cc42
-rw-r--r--chromium/chrome/browser/ui/webui/devtools_ui_data_source_unittest.cc15
-rw-r--r--chromium/chrome/browser/ui/webui/discards/discards.mojom64
-rw-r--r--chromium/chrome/browser/ui/webui/discards/discards_ui.cc13
-rw-r--r--chromium/chrome/browser/ui/webui/discards/graph_dump_impl.cc106
-rw-r--r--chromium/chrome/browser/ui/webui/discards/graph_dump_impl.h11
-rw-r--r--chromium/chrome/browser/ui/webui/discards/graph_dump_impl_unittest.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc52
-rw-r--r--chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/flags_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/help/test_version_updater.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/help/test_version_updater.h1
-rw-r--r--chromium/chrome/browser/ui/webui/help/version_updater.h2
-rw-r--r--chromium/chrome/browser/ui/webui/help/version_updater_basic.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc34
-rw-r--r--chromium/chrome/browser/ui/webui/help/version_updater_chromeos_unittest.cc1
-rw-r--r--chromium/chrome/browser/ui/webui/help/version_updater_mac.mm4
-rw-r--r--chromium/chrome/browser/ui/webui/help/version_updater_win.cc14
-rw-r--r--chromium/chrome/browser/ui/webui/internals/internals_ui.cc59
-rw-r--r--chromium/chrome/browser/ui/webui/internals/internals_ui.h48
-rw-r--r--chromium/chrome/browser/ui/webui/internals/query_tiles/OWNERS1
-rw-r--r--chromium/chrome/browser/ui/webui/internals/query_tiles/query_tiles_internals_ui_message_handler.cc70
-rw-r--r--chromium/chrome/browser/ui/webui/internals/query_tiles/query_tiles_internals_ui_message_handler.h43
-rw-r--r--chromium/chrome/browser/ui/webui/internals/web_app/BUILD.gn (renamed from chromium/chrome/browser/chromeos/net/network_diagnostics/BUILD.gn)6
-rw-r--r--chromium/chrome/browser/ui/webui/internals/web_app/OWNERS4
-rw-r--r--chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals.mojom30
-rw-r--r--chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.cc68
-rw-r--r--chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.h39
-rw-r--r--chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc48
-rw-r--r--chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals.mojom30
-rw-r--r--chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.cc50
-rw-r--r--chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.h10
-rw-r--r--chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc174
-rw-r--r--chromium/chrome/browser/ui/webui/invalidations_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/local_discovery/local_discovery_ui_browsertest.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/management_ui.cc28
-rw-r--r--chromium/chrome/browser/ui/webui/management_ui_handler.cc90
-rw-r--r--chromium/chrome/browser/ui/webui/management_ui_handler.h11
-rw-r--r--chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc138
-rw-r--r--chromium/chrome/browser/ui/webui/media/media_feeds_ui.cc23
-rw-r--r--chromium/chrome/browser/ui/webui/media/media_feeds_ui.h3
-rw-r--r--chromium/chrome/browser/ui/webui/memory_internals_ui.cc13
-rw-r--r--chromium/chrome/browser/ui/webui/nacl_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/nearby_internals/OWNERS4
-rw-r--r--chromium/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui.cc44
-rw-r--r--chromium/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui.h22
-rw-r--r--chromium/chrome/browser/ui/webui/nearby_share/OWNERS3
-rw-r--r--chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui.cc52
-rw-r--r--chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui.h26
-rw-r--r--chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui_browsertest.cc50
-rw-r--r--chromium/chrome/browser/ui/webui/net_internals/net_internals_ui.cc311
-rw-r--r--chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page.mojom56
-rw-r--r--chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.cc175
-rw-r--r--chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.h5
-rw-r--r--chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler_unittest.cc106
-rw-r--r--chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc27
-rw-r--r--chromium/chrome/browser/ui/webui/new_tab_page/untrusted_source.cc44
-rw-r--r--chromium/chrome/browser/ui/webui/new_tab_page/untrusted_source.h7
-rw-r--r--chromium/chrome/browser/ui/webui/new_tab_page/webui_ntp_browsertest.cc79
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc26
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/cookie_controls_handler.cc11
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/cookie_controls_handler.h4
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc38
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h6
-rw-r--r--chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc32
-rw-r--r--chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/policy_ui.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/policy_ui_handler.cc31
-rw-r--r--chromium/chrome/browser/ui/webui/policy_ui_handler.h4
-rw-r--r--chromium/chrome/browser/ui/webui/predictors/predictors_handler.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h3
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_chromeos.cc9
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.cc23
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_handler.h5
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.cc141
-rw-r--r--chromium/chrome/browser/ui/webui/print_preview/print_preview_ui.h19
-rw-r--r--chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.cc26
-rw-r--r--chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.h1
-rw-r--r--chromium/chrome/browser/ui/webui/quota_internals/quota_internals_proxy.cc13
-rw-r--r--chromium/chrome/browser/ui/webui/sandbox/sandbox_handler.cc51
-rw-r--r--chromium/chrome/browser/ui/webui/sandbox/sandbox_internals_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/settings/about_handler.cc15
-rw-r--r--chromium/chrome/browser/ui/webui/settings/about_handler.h1
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/about_section.cc149
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/about_section.h19
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_section.cc176
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_section.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/account_manager_handler.cc14
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.cc191
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.h40
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/apps_section.cc98
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/apps_section.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.cc187
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.h11
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator.cc27
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator.h28
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator_test_api.h19
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/constants/constants_util.cc2
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom29
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/constants/routes_util.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom34
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc90
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h20
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/crostini_section.cc158
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/crostini_section.h6
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc11
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc27
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/date_time_handler.cc11
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/date_time_section.cc54
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/date_time_section.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler.cc46
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler.h26
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler_unittest.cc51
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_section.cc340
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_section.h19
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc15
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h1
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler_unittest.cc52
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/fake_hierarchy.cc53
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/fake_hierarchy.h50
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.cc52
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.h56
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_sections.cc24
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_sections.h26
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/files_section.cc29
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/files_section.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/google_assistant_handler.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/hierarchy.cc318
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/hierarchy.h171
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/internet_section.cc422
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/internet_section.h24
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/languages_section.cc166
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/languages_section.h7
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/main_section.cc37
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/main_section.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_section.cc192
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_section.h10
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_identifier.h24
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.cc8
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.h6
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc13
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc52
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_section.cc39
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_section.h94
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_sections.cc15
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h9
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/people_section.cc271
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/people_section.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/personalization_section.cc72
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/personalization_section.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.cc54
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h10
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/printing_section.cc45
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/printing_section.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/privacy_section.cc41
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/privacy_section.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/reset_section.cc23
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/reset_section.h5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/search/search.mojom64
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/search/search_concept.h3
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler.cc277
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler.h70
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler_unittest.cc238
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/search/search_result_icon.mojom1
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.cc188
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h78
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry_unittest.cc69
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/search_section.cc166
-rw-r--r--chromium/chrome/browser/ui/webui/settings/chromeos/search_section.h8
-rw-r--r--chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/settings/recent_site_settings_helper_unittest.cc6
-rw-r--r--chromium/chrome/browser/ui/webui/settings/safety_check_handler.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/settings/safety_check_handler.h12
-rw-r--r--chromium/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc19
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler_browsertest.cc14
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc105
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc1
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler.cc107
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler.h19
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler_browsertest.cc201
-rw-r--r--chromium/chrome/browser/ui/webui/settings/settings_ui.cc10
-rw-r--r--chromium/chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.cc12
-rw-r--r--chromium/chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.h3
-rw-r--r--chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc41
-rw-r--r--chromium/chrome/browser/ui/webui/settings/site_settings_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc203
-rw-r--r--chromium/chrome/browser/ui/webui/settings/site_settings_helper.cc263
-rw-r--r--chromium/chrome/browser/ui/webui/settings/site_settings_helper.h24
-rw-r--r--chromium/chrome/browser/ui/webui/settings/site_settings_helper_unittest.cc340
-rw-r--r--chromium/chrome/browser/ui/webui/settings/tts_handler.cc10
-rw-r--r--chromium/chrome/browser/ui/webui/settings/tts_handler.h1
-rw-r--r--chromium/chrome/browser/ui/webui/settings_utils_linux.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc119
-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.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_dialog_chromeos.cc (renamed from chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.cc)59
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_dialog_chromeos.h (renamed from chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h)17
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc24
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler.h8
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc12
-rw-r--r--chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc19
-rw-r--r--chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.cc116
-rw-r--r--chromium/chrome/browser/ui/webui/signin/login_ui_test_utils.h10
-rw-r--r--chromium/chrome/browser/ui/webui/signin/profile_picker_ui.h1
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_create_profile_handler.cc1
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.h1
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_error_handler.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_reauth_handler.cc72
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_reauth_handler.h57
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_reauth_ui.cc138
-rw-r--r--chromium/chrome/browser/ui/webui/signin/signin_reauth_ui.h49
-rw-r--r--chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc7
-rw-r--r--chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler_unittest.cc21
-rw-r--r--chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc56
-rw-r--r--chromium/chrome/browser/ui/webui/signin/user_manager_ui_browsertest.cc25
-rw-r--r--chromium/chrome/browser/ui/webui/signin_internals_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc16
-rw-r--r--chromium/chrome/browser/ui/webui/supervised_user_internals_ui.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/sync_file_system_internals/file_metadata_handler.cc1
-rw-r--r--chromium/chrome/browser/ui/webui/sync_internals_browsertest.js8
-rw-r--r--chromium/chrome/browser/ui/webui/sync_internals_ui.cc5
-rw-r--r--chromium/chrome/browser/ui/webui/tab_search/BUILD.gn (renamed from chromium/chrome/browser/chromeos/net/mojom/BUILD.gn)7
-rw-r--r--chromium/chrome/browser/ui/webui/tab_search/OWNERS7
-rw-r--r--chromium/chrome/browser/ui/webui/tab_search/tab_search.mojom70
-rw-r--r--chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler.cc115
-rw-r--r--chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler.h47
-rw-r--r--chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler_unittest.cc203
-rw-r--r--chromium/chrome/browser/ui/webui/tab_search/tab_search_ui.cc38
-rw-r--r--chromium/chrome/browser/ui/webui/tab_search/tab_search_ui.h52
-rw-r--r--chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler.cc80
-rw-r--r--chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler_unittest.cc89
-rw-r--r--chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_metrics.h7
-rw-r--r--chromium/chrome/browser/ui/webui/test_data_source.cc14
-rw-r--r--chromium/chrome/browser/ui/webui/test_data_source.h5
-rw-r--r--chromium/chrome/browser/ui/webui/theme_source.cc17
-rw-r--r--chromium/chrome/browser/ui/webui/theme_source.h2
-rw-r--r--chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.cc101
-rw-r--r--chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.h20
-rw-r--r--chromium/chrome/browser/ui/webui/util/OWNERS6
-rw-r--r--chromium/chrome/browser/ui/webui/util/image_util.cc57
-rw-r--r--chromium/chrome/browser/ui/webui/util/image_util.h22
-rw-r--r--chromium/chrome/browser/ui/webui/web_dialog_web_contents_delegate_unittest.cc3
-rw-r--r--chromium/chrome/browser/ui/webui/webui_util.cc4
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc30
-rw-r--r--chromium/chrome/browser/ui/webui/welcome/welcome_handler.h29
-rw-r--r--chromium/chrome/browser/util/BUILD.gn3
-rw-r--r--chromium/chrome/browser/vr/BUILD.gn14
-rw-r--r--chromium/chrome/browser/vr/testapp/BUILD.gn1
-rw-r--r--chromium/chrome/browser/web_applications/BUILD.gn11
-rw-r--r--chromium/chrome/browser/web_applications/components/BUILD.gn8
-rw-r--r--chromium/chrome/browser/web_applications/extensions/BUILD.gn1
-rw-r--r--chromium/chrome/browser/xsurface/BUILD.gn1
1121 files changed, 32527 insertions, 16788 deletions
diff --git a/chromium/chrome/browser/BUILD.gn b/chromium/chrome/browser/BUILD.gn
index ab78eae16b4..995b99c5ba9 100644
--- a/chromium/chrome/browser/BUILD.gn
+++ b/chromium/chrome/browser/BUILD.gn
@@ -6,6 +6,7 @@ import("//base/allocator/allocator.gni")
import("//build/buildflag_header.gni")
import("//build/config/buildflags_paint_preview.gni")
import("//build/config/chrome_build.gni")
+import("//build/config/chromeos/ui_mode.gni")
import("//build/config/compiler/pgo/pgo.gni")
import("//build/config/crypto.gni")
import("//build/config/features.gni")
@@ -47,6 +48,12 @@ if (is_android) {
additional_modules_list_file =
"$root_gen_dir/chrome/browser/internal/additional_modules_list.txt"
+# Reset sources_assignment_filter for the BUILD.gn file to prevent
+# regression during the migration of Chromium away from the feature.
+# See docs/no_sources_assignment_filter.md for more information.
+# TODO(crbug.com/1018739): remove this when migration is done.
+set_sources_assignment_filter([])
+
if (is_win) {
# This is in a separate config so the flags can be applied to dependents.
# ldflags in GN aren't automatically inherited.
@@ -72,6 +79,7 @@ buildflag_header("buildflags") {
flags = [
"CLANG_PGO=$chrome_pgo_phase",
"ENABLE_KALEIDOSCOPE=$enable_kaleidoscope",
+ "USE_THIN_LTO=$use_thin_lto",
]
}
@@ -101,8 +109,6 @@ static_library("browser") {
"accessibility/caption_util.h",
"after_startup_task_utils.cc",
"after_startup_task_utils.h",
- "app_controller_mac.h",
- "app_controller_mac.mm",
"app_mode/app_mode_utils.cc",
"app_mode/app_mode_utils.h",
"apps/user_type_filter.cc",
@@ -199,16 +205,8 @@ static_library("browser") {
"browser_process_impl.cc",
"browser_process_impl.h",
"browser_process_platform_part.h",
- "browser_process_platform_part_android.cc",
- "browser_process_platform_part_android.h",
"browser_process_platform_part_base.cc",
"browser_process_platform_part_base.h",
- "browser_process_platform_part_chromeos.cc",
- "browser_process_platform_part_chromeos.h",
- "browser_process_platform_part_mac.h",
- "browser_process_platform_part_mac.mm",
- "browser_process_platform_part_win.cc",
- "browser_process_platform_part_win.h",
"browsing_data/browsing_data_file_system_util.cc",
"browsing_data/browsing_data_file_system_util.h",
"browsing_data/browsing_data_history_observer_service.cc",
@@ -253,23 +251,13 @@ static_library("browser") {
"cache_stats_recorder.h",
"chooser_controller/chooser_controller.cc",
"chooser_controller/chooser_controller.h",
- "chrome_browser_application_mac.h",
- "chrome_browser_application_mac.mm",
"chrome_browser_field_trials.cc",
"chrome_browser_field_trials.h",
"chrome_browser_interface_binders.cc",
"chrome_browser_interface_binders.h",
"chrome_browser_main.cc",
"chrome_browser_main.h",
- "chrome_browser_main_android.cc",
- "chrome_browser_main_android.h",
"chrome_browser_main_extra_parts.h",
- "chrome_browser_main_linux.cc",
- "chrome_browser_main_linux.h",
- "chrome_browser_main_mac.h",
- "chrome_browser_main_mac.mm",
- "chrome_browser_main_win.cc",
- "chrome_browser_main_win.h",
"chrome_content_browser_client.cc",
"chrome_content_browser_client.h",
"chrome_content_browser_client_parts.h",
@@ -304,6 +292,8 @@ static_library("browser") {
"component_updater/crowd_deny_component_installer.h",
"component_updater/file_type_policies_component_installer.cc",
"component_updater/file_type_policies_component_installer.h",
+ "component_updater/floc_blocklist_component_installer.cc",
+ "component_updater/floc_blocklist_component_installer.h",
"component_updater/games_component_installer.cc",
"component_updater/games_component_installer.h",
"component_updater/mei_preload_component_installer.cc",
@@ -328,8 +318,6 @@ static_library("browser") {
"component_updater/sth_set_component_remover.h",
"component_updater/subresource_filter_component_installer.cc",
"component_updater/subresource_filter_component_installer.h",
- "component_updater/sw_reporter_installer_win.cc",
- "component_updater/sw_reporter_installer_win.h",
"component_updater/tls_deprecation_config_component_installer.cc",
"component_updater/tls_deprecation_config_component_installer.h",
"component_updater/trust_token_key_commitments_component_installer.cc",
@@ -358,8 +346,6 @@ static_library("browser") {
"content_settings/tab_specific_content_settings_delegate.h",
"crash_upload_list/crash_upload_list.cc",
"crash_upload_list/crash_upload_list.h",
- "crash_upload_list/crash_upload_list_android.cc",
- "crash_upload_list/crash_upload_list_android.h",
"custom_handlers/protocol_handler_registry.cc",
"custom_handlers/protocol_handler_registry.h",
"custom_handlers/protocol_handler_registry_factory.cc",
@@ -399,15 +385,13 @@ static_library("browser") {
"download/download_core_service_factory.h",
"download/download_core_service_impl.cc",
"download/download_core_service_impl.h",
- "download/download_crx_util_android.cc",
+ "download/download_dialog_types.h",
"download/download_file_picker.cc",
"download/download_file_picker.h",
"download/download_history.cc",
"download/download_history.h",
"download/download_item_model.cc",
"download/download_item_model.h",
- "download/download_location_dialog_result.h",
- "download/download_location_dialog_type.h",
"download/download_manager_utils.cc",
"download/download_manager_utils.h",
"download/download_offline_content_provider.cc",
@@ -430,8 +414,6 @@ static_library("browser") {
"download/download_stats.h",
"download/download_status_updater.cc",
"download/download_status_updater.h",
- "download/download_status_updater_mac.mm",
- "download/download_status_updater_win.cc",
"download/download_target_determiner.cc",
"download/download_target_determiner.h",
"download/download_target_determiner_delegate.h",
@@ -461,7 +443,6 @@ static_library("browser") {
"download/simple_download_manager_coordinator_factory.h",
"download/trusted_sources_manager.cc",
"download/trusted_sources_manager.h",
- "download/trusted_sources_manager_win.cc",
"engagement/important_sites_usage_counter.cc",
"engagement/important_sites_usage_counter.h",
"engagement/important_sites_util.cc",
@@ -478,9 +459,15 @@ static_library("browser") {
"engagement/site_engagement_service.h",
"engagement/site_engagement_service_factory.cc",
"engagement/site_engagement_service_factory.h",
+ "enterprise/browser_management/browser_management_service.cc",
+ "enterprise/browser_management/browser_management_service.h",
+ "enterprise/browser_management/browser_management_status_provider.cc",
+ "enterprise/browser_management/browser_management_status_provider.h",
"enterprise/util/managed_browser_utils.cc",
"enterprise/util/managed_browser_utils.h",
"expired_flags_list.h",
+ "external_protocol/auto_launch_protocols_policy_handler.cc",
+ "external_protocol/auto_launch_protocols_policy_handler.h",
"external_protocol/external_protocol_handler.cc",
"external_protocol/external_protocol_handler.h",
"external_protocol/external_protocol_observer.cc",
@@ -497,11 +484,17 @@ static_library("browser") {
"favicon/large_icon_service_factory.h",
"feature_engagement/tracker_factory.cc",
"feature_engagement/tracker_factory.h",
+ "federated_learning/floc_id_provider.h",
+ "federated_learning/floc_id_provider_factory.cc",
+ "federated_learning/floc_id_provider_factory.h",
+ "federated_learning/floc_id_provider_impl.cc",
+ "federated_learning/floc_id_provider_impl.h",
+ "federated_learning/floc_remote_permission_service.cc",
+ "federated_learning/floc_remote_permission_service.h",
+ "federated_learning/floc_remote_permission_service_factory.cc",
+ "federated_learning/floc_remote_permission_service_factory.h",
"file_select_helper.cc",
"file_select_helper.h",
- "file_select_helper_contacts_android.cc",
- "file_select_helper_contacts_android.h",
- "file_select_helper_mac.mm",
"file_util_service.cc",
"file_util_service.h",
"flag_descriptions.cc",
@@ -510,8 +503,6 @@ static_library("browser") {
"font_pref_change_notifier.h",
"font_pref_change_notifier_factory.cc",
"font_pref_change_notifier_factory.h",
- "fullscreen_mac.mm",
- "fullscreen_win.cc",
"games/games_service_factory.cc",
"games/games_service_factory.h",
"gcm/gcm_product_util.cc",
@@ -524,14 +515,8 @@ static_library("browser") {
"generic_sensor/sensor_permission_context.h",
"geolocation/geolocation_permission_context_delegate.cc",
"geolocation/geolocation_permission_context_delegate.h",
- "geolocation/geolocation_permission_context_delegate_android.cc",
- "geolocation/geolocation_permission_context_delegate_android.h",
"geolocation/geolocation_permission_context_extensions.cc",
"geolocation/geolocation_permission_context_extensions.h",
- "global_keyboard_shortcuts_mac.h",
- "global_keyboard_shortcuts_mac.mm",
- "google/did_run_updater_win.cc",
- "google/did_run_updater_win.h",
"google/google_brand.cc",
"google/google_brand.h",
"google/google_search_domain_mixing_metrics_emitter.cc",
@@ -543,8 +528,6 @@ static_library("browser") {
"gpu/gpu_mode_manager.cc",
"gpu/gpu_mode_manager.h",
"hang_monitor/hang_crash_dump.h",
- "hang_monitor/hang_crash_dump_mac.cc",
- "hang_monitor/hang_crash_dump_win.cc",
"heavy_ad_intervention/heavy_ad_blocklist.cc",
"heavy_ad_intervention/heavy_ad_blocklist.h",
"heavy_ad_intervention/heavy_ad_features.cc",
@@ -577,10 +560,6 @@ static_library("browser") {
"history/web_history_service_factory.h",
"icon_loader.cc",
"icon_loader.h",
- "icon_loader_android.cc",
- "icon_loader_chromeos.cc",
- "icon_loader_mac.mm",
- "icon_loader_win.cc",
"icon_manager.cc",
"icon_manager.h",
"idle/idle_detection_permission_context.cc",
@@ -593,11 +572,6 @@ static_library("browser") {
"infobars/infobar_responder.h",
"infobars/infobar_service.cc",
"infobars/infobar_service.h",
- "install_verification/win/module_info.h",
- "install_verification/win/module_list.cc",
- "install_verification/win/module_list.h",
- "install_verification/win/module_verification_common.cc",
- "install_verification/win/module_verification_common.h",
"installable/installable_ambient_badge_infobar_delegate.h",
"installable/installable_data.cc",
"installable/installable_data.h",
@@ -628,9 +602,30 @@ static_library("browser") {
"language/url_language_histogram_factory.h",
"lifetime/application_lifetime.cc",
"lifetime/application_lifetime.h",
- "lifetime/application_lifetime_mac.mm",
"lifetime/browser_shutdown.cc",
"lifetime/browser_shutdown.h",
+ "lite_video/lite_video_decider.cc",
+ "lite_video/lite_video_decider.h",
+ "lite_video/lite_video_features.cc",
+ "lite_video/lite_video_features.h",
+ "lite_video/lite_video_hint.cc",
+ "lite_video/lite_video_hint.h",
+ "lite_video/lite_video_hint_cache.cc",
+ "lite_video/lite_video_hint_cache.h",
+ "lite_video/lite_video_keyed_service.cc",
+ "lite_video/lite_video_keyed_service.h",
+ "lite_video/lite_video_keyed_service_factory.cc",
+ "lite_video/lite_video_keyed_service_factory.h",
+ "lite_video/lite_video_navigation_metrics.cc",
+ "lite_video/lite_video_navigation_metrics.h",
+ "lite_video/lite_video_observer.cc",
+ "lite_video/lite_video_observer.h",
+ "lite_video/lite_video_switches.cc",
+ "lite_video/lite_video_switches.h",
+ "lite_video/lite_video_user_blocklist.cc",
+ "lite_video/lite_video_user_blocklist.h",
+ "lite_video/lite_video_util.cc",
+ "lite_video/lite_video_util.h",
"lookalikes/lookalike_url_blocking_page.cc",
"lookalikes/lookalike_url_blocking_page.h",
"lookalikes/lookalike_url_controller_client.cc",
@@ -641,26 +636,6 @@ static_library("browser") {
"lookalikes/lookalike_url_service.h",
"lookalikes/lookalike_url_tab_storage.cc",
"lookalikes/lookalike_url_tab_storage.h",
- "mac/bluetooth_utility.h",
- "mac/bluetooth_utility.mm",
- "mac/dock.h",
- "mac/dock.mm",
- "mac/exception_processor.h",
- "mac/exception_processor.mm",
- "mac/install_from_dmg.h",
- "mac/install_from_dmg.mm",
- "mac/keystone_glue.h",
- "mac/keystone_glue.mm",
- "mac/keystone_registration.h",
- "mac/keystone_registration.mm",
- "mac/mac_startup_profiler.cc",
- "mac/mac_startup_profiler.h",
- "mac/master_prefs.h",
- "mac/master_prefs.mm",
- "mac/nsprocessinfo_additions.h",
- "mac/nsprocessinfo_additions.mm",
- "mac/relauncher.h",
- "mac/relauncher.mm",
"media/cast_mirroring_service_host.cc",
"media/cast_mirroring_service_host.h",
"media/cast_remoting_connector.cc",
@@ -669,8 +644,6 @@ static_library("browser") {
"media/feeds/media_feeds_utils.h",
"media/history/media_history_contents_observer.cc",
"media/history/media_history_contents_observer.h",
- "media/history/media_history_feed_associated_origins_table.cc",
- "media/history/media_history_feed_associated_origins_table.h",
"media/history/media_history_feed_items_table.cc",
"media/history/media_history_feed_items_table.h",
"media/history/media_history_feeds_table.cc",
@@ -777,9 +750,6 @@ static_library("browser") {
"media/webrtc/webrtc_text_log_handler.cc",
"media/webrtc/webrtc_text_log_handler.h",
"media/webrtc/window_icon_util.h",
- "media/webrtc/window_icon_util_chromeos.cc",
- "media/webrtc/window_icon_util_mac.mm",
- "media/webrtc/window_icon_util_win.cc",
"memory/chrome_browser_main_extra_parts_memory.cc",
"memory/chrome_browser_main_extra_parts_memory.h",
"memory/enterprise_memory_limit_evaluator.cc",
@@ -788,19 +758,12 @@ static_library("browser") {
"memory/enterprise_memory_limit_pref_observer.h",
"memory_details.cc",
"memory_details.h",
- "memory_details_android.cc",
- "memory_details_linux.cc",
- "memory_details_mac.cc",
- "memory_details_win.cc",
- "metrics/antivirus_metrics_provider_win.cc",
- "metrics/antivirus_metrics_provider_win.h",
"metrics/bluetooth_available_utility.cc",
"metrics/bluetooth_available_utility.h",
"metrics/browser_window_histogram_helper.cc",
"metrics/browser_window_histogram_helper.h",
"metrics/chrome_browser_main_extra_parts_metrics.cc",
"metrics/chrome_browser_main_extra_parts_metrics.h",
- "metrics/chrome_browser_main_extra_parts_metrics_mac.mm",
"metrics/chrome_feature_list_creator.cc",
"metrics/chrome_feature_list_creator.h",
"metrics/chrome_metrics_service_accessor.cc",
@@ -811,14 +774,10 @@ static_library("browser") {
"metrics/chrome_metrics_services_manager_client.h",
"metrics/chrome_stability_metrics_provider.cc",
"metrics/chrome_stability_metrics_provider.h",
- "metrics/google_update_metrics_provider_win.cc",
- "metrics/google_update_metrics_provider_win.h",
"metrics/https_engagement_metrics_provider.cc",
"metrics/https_engagement_metrics_provider.h",
"metrics/incognito_observer.cc",
"metrics/incognito_observer.h",
- "metrics/jumplist_metrics_win.cc",
- "metrics/jumplist_metrics_win.h",
"metrics/metrics_memory_details.cc",
"metrics/metrics_memory_details.h",
"metrics/metrics_reporting_state.cc",
@@ -827,8 +786,6 @@ static_library("browser") {
"metrics/network_quality_estimator_provider_impl.h",
"metrics/oom/out_of_memory_reporter.cc",
"metrics/oom/out_of_memory_reporter.h",
- "metrics/power_metrics_provider_mac.h",
- "metrics/power_metrics_provider_mac.mm",
"metrics/process_memory_metrics_emitter.cc",
"metrics/process_memory_metrics_emitter.h",
"metrics/renderer_uptime_tracker.cc",
@@ -837,8 +794,6 @@ static_library("browser") {
"metrics/renderer_uptime_web_contents_observer.h",
"metrics/sampling_metrics_provider.cc",
"metrics/sampling_metrics_provider.h",
- "metrics/subprocess_metrics_provider.cc",
- "metrics/subprocess_metrics_provider.h",
"metrics/tab_count_metrics.cc",
"metrics/tab_count_metrics.h",
"metrics/tab_footprint_aggregator.cc",
@@ -847,8 +802,6 @@ static_library("browser") {
"metrics/testing/metrics_reporting_pref_helper.h",
"metrics/thread_watcher.cc",
"metrics/thread_watcher.h",
- "metrics/thread_watcher_android.cc",
- "metrics/thread_watcher_android.h",
"metrics/thread_watcher_report_hang.cc",
"metrics/thread_watcher_report_hang.h",
"metrics/ukm_background_recorder_service.cc",
@@ -865,8 +818,6 @@ static_library("browser") {
"native_file_system/native_file_system_tab_helper.h",
"native_file_system/origin_scoped_native_file_system_permission_context.cc",
"native_file_system/origin_scoped_native_file_system_permission_context.h",
- "native_file_system/tab_scoped_native_file_system_permission_context.cc",
- "native_file_system/tab_scoped_native_file_system_permission_context.h",
"native_window_notification_source.h",
"navigation_predictor/navigation_predictor.cc",
"navigation_predictor/navigation_predictor.h",
@@ -893,7 +844,6 @@ static_library("browser") {
"net/file_downloader.cc",
"net/file_downloader.h",
"net/net_error_diagnostics_dialog.h",
- "net/net_error_diagnostics_dialog_win.cc",
"net/net_error_tab_helper.cc",
"net/net_error_tab_helper.h",
"net/net_export_helper.cc",
@@ -920,8 +870,6 @@ static_library("browser") {
"net/secure_dns_policy_handler.h",
"net/secure_dns_util.cc",
"net/secure_dns_util.h",
- "net/service_providers_win.cc",
- "net/service_providers_win.h",
"net/stub_resolver_config_reader.cc",
"net/stub_resolver_config_reader.h",
"net/system_network_context_manager.cc",
@@ -930,17 +878,12 @@ static_library("browser") {
"net_benchmarking.h",
"nfc/nfc_permission_context.cc",
"nfc/nfc_permission_context.h",
- "nfc/nfc_permission_context_android.cc",
- "nfc/nfc_permission_context_android.h",
- "notifications/alert_dispatcher_mac.h",
"notifications/metrics/notification_metrics_logger.cc",
"notifications/metrics/notification_metrics_logger.h",
"notifications/metrics/notification_metrics_logger_factory.cc",
"notifications/metrics/notification_metrics_logger_factory.h",
"notifications/non_persistent_notification_handler.cc",
"notifications/non_persistent_notification_handler.h",
- "notifications/notification_channels_provider_android.cc",
- "notifications/notification_channels_provider_android.h",
"notifications/notification_common.cc",
"notifications/notification_common.h",
"notifications/notification_display_service.cc",
@@ -955,8 +898,6 @@ static_library("browser") {
"notifications/notification_permission_context.h",
"notifications/notification_platform_bridge.cc",
"notifications/notification_platform_bridge.h",
- "notifications/notification_platform_bridge_mac.h",
- "notifications/notification_platform_bridge_mac.mm",
"notifications/notification_trigger_scheduler.cc",
"notifications/notification_trigger_scheduler.h",
"notifications/notification_ui_manager.h",
@@ -1001,6 +942,8 @@ static_library("browser") {
"optimization_guide/optimization_guide_permissions_util.h",
"optimization_guide/optimization_guide_session_statistic.cc",
"optimization_guide/optimization_guide_session_statistic.h",
+ "optimization_guide/optimization_guide_test_util.cc",
+ "optimization_guide/optimization_guide_test_util.h",
"optimization_guide/optimization_guide_top_host_provider.cc",
"optimization_guide/optimization_guide_top_host_provider.h",
"optimization_guide/optimization_guide_util.cc",
@@ -1061,6 +1004,8 @@ static_library("browser") {
"page_load_metrics/observers/omnibox_suggestion_used_page_load_metrics_observer.h",
"page_load_metrics/observers/optimization_guide_page_load_metrics_observer.cc",
"page_load_metrics/observers/optimization_guide_page_load_metrics_observer.h",
+ "page_load_metrics/observers/portal_page_load_metrics_observer.cc",
+ "page_load_metrics/observers/portal_page_load_metrics_observer.h",
"page_load_metrics/observers/previews_page_load_metrics_observer.cc",
"page_load_metrics/observers/previews_page_load_metrics_observer.h",
"page_load_metrics/observers/previews_ukm_observer.cc",
@@ -1095,8 +1040,6 @@ static_library("browser") {
"paint_preview/services/paint_preview_tab_service_factory.h",
"password_manager/account_storage/account_password_store_factory.cc",
"password_manager/account_storage/account_password_store_factory.h",
- "password_manager/biometric_authenticator_android.cc",
- "password_manager/biometric_authenticator_android.h",
"password_manager/bulk_leak_check_service_factory.cc",
"password_manager/bulk_leak_check_service_factory.h",
"password_manager/chrome_biometric_authenticator.h",
@@ -1104,10 +1047,6 @@ static_library("browser") {
"password_manager/chrome_password_manager_client.h",
"password_manager/field_info_manager_factory.cc",
"password_manager/field_info_manager_factory.h",
- "password_manager/password_manager_util_mac.h",
- "password_manager/password_manager_util_mac.mm",
- "password_manager/password_manager_util_win.cc",
- "password_manager/password_manager_util_win.h",
"password_manager/password_store_factory.cc",
"password_manager/password_store_factory.h",
"password_manager/password_store_utils.cc",
@@ -1115,8 +1054,12 @@ static_library("browser") {
"payments/payment_handler_permission_context.cc",
"payments/payment_handler_permission_context.h",
"payments/ssl_validity_checker.cc",
+ "performance_hints/performance_hints_features.cc",
+ "performance_hints/performance_hints_features.h",
"performance_hints/performance_hints_observer.cc",
"performance_hints/performance_hints_observer.h",
+ "performance_hints/performance_hints_rewrite_handler.cc",
+ "performance_hints/performance_hints_rewrite_handler.h",
"performance_manager/browser_child_process_watcher.cc",
"performance_manager/browser_child_process_watcher.h",
"performance_manager/chrome_browser_main_extra_parts_performance_manager.cc",
@@ -1139,10 +1082,6 @@ static_library("browser") {
"performance_manager/mechanisms/high_pmf_memory_pressure_signals.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/metrics/memory_pressure_metrics.cc",
"performance_manager/metrics/memory_pressure_metrics.h",
"performance_manager/observers/background_metrics_reporter.h",
@@ -1156,12 +1095,6 @@ static_library("browser") {
"performance_manager/policies/policy_features.h",
"performance_manager/policies/working_set_trimmer_policy.cc",
"performance_manager/policies/working_set_trimmer_policy.h",
- "performance_manager/policies/working_set_trimmer_policy_chromeos.cc",
- "performance_manager/policies/working_set_trimmer_policy_chromeos.h",
- "performance_manager/policies/working_set_trimmer_policy_win.cc",
- "performance_manager/policies/working_set_trimmer_policy_win.h",
- "performance_monitor/metric_evaluator_helper_win.cc",
- "performance_monitor/metric_evaluator_helper_win.h",
"performance_monitor/process_metrics_history.cc",
"performance_monitor/process_metrics_history.h",
"performance_monitor/process_monitor.cc",
@@ -1189,22 +1122,13 @@ static_library("browser") {
"picture_in_picture/picture_in_picture_window_manager.cc",
"picture_in_picture/picture_in_picture_window_manager.h",
"platform_util.h",
- "platform_util_chromeos.cc",
"platform_util_internal.h",
- "platform_util_mac.mm",
- "platform_util_win.cc",
"plugins/pdf_iframe_navigation_throttle.cc",
"plugins/pdf_iframe_navigation_throttle.h",
"plugins/pdf_plugin_placeholder_observer.cc",
"plugins/pdf_plugin_placeholder_observer.h",
"policy/browser_dm_token_storage.cc",
"policy/browser_dm_token_storage.h",
- "policy/browser_dm_token_storage_linux.cc",
- "policy/browser_dm_token_storage_linux.h",
- "policy/browser_dm_token_storage_mac.h",
- "policy/browser_dm_token_storage_mac.mm",
- "policy/browser_dm_token_storage_win.cc",
- "policy/browser_dm_token_storage_win.h",
"policy/browsing_history_policy_handler.cc",
"policy/browsing_history_policy_handler.h",
"policy/chrome_browser_policy_connector.cc",
@@ -1237,13 +1161,26 @@ static_library("browser") {
"policy/homepage_location_policy_handler.h",
"policy/javascript_policy_handler.cc",
"policy/javascript_policy_handler.h",
+ "policy/messaging_layer/encryption/encryption_module.cc",
+ "policy/messaging_layer/encryption/encryption_module.h",
+ "policy/messaging_layer/public/report_client.cc",
+ "policy/messaging_layer/public/report_client.h",
+ "policy/messaging_layer/public/report_queue.cc",
+ "policy/messaging_layer/public/report_queue.h",
"policy/messaging_layer/public/report_queue_configuration.cc",
"policy/messaging_layer/public/report_queue_configuration.h",
+ "policy/messaging_layer/storage/storage.cc",
+ "policy/messaging_layer/storage/storage.h",
+ "policy/messaging_layer/storage/storage_module.cc",
+ "policy/messaging_layer/storage/storage_module.h",
+ "policy/messaging_layer/storage/storage_queue.cc",
+ "policy/messaging_layer/storage/storage_queue.h",
"policy/messaging_layer/util/status.cc",
"policy/messaging_layer/util/status.h",
"policy/messaging_layer/util/status_macros.h",
"policy/messaging_layer/util/statusor.cc",
"policy/messaging_layer/util/statusor.h",
+ "policy/messaging_layer/util/task_runner_context.h",
"policy/network_prediction_policy_handler.cc",
"policy/network_prediction_policy_handler.h",
"policy/profile_policy_connector.cc",
@@ -1287,6 +1224,8 @@ static_library("browser") {
"predictors/predictors_enums.h",
"predictors/predictors_features.cc",
"predictors/predictors_features.h",
+ "predictors/prefetch_manager.cc",
+ "predictors/prefetch_manager.h",
"predictors/proxy_lookup_client_impl.cc",
"predictors/proxy_lookup_client_impl.h",
"predictors/resolve_host_client_impl.cc",
@@ -1309,8 +1248,8 @@ static_library("browser") {
"prefs/origin_trial_prefs.h",
"prefs/pref_metrics_service.cc",
"prefs/pref_metrics_service.h",
- "prefs/pref_service_incognito_whitelist.cc",
- "prefs/pref_service_incognito_whitelist.h",
+ "prefs/pref_service_incognito_allowlist.cc",
+ "prefs/pref_service_incognito_allowlist.h",
"prefs/pref_service_syncable_util.cc",
"prefs/pref_service_syncable_util.h",
"prefs/profile_pref_store_manager.cc",
@@ -1321,16 +1260,22 @@ static_library("browser") {
"prerender/isolated/isolated_prerender_features.h",
"prerender/isolated/isolated_prerender_from_string_url_loader.cc",
"prerender/isolated/isolated_prerender_from_string_url_loader.h",
+ "prerender/isolated/isolated_prerender_network_context_client.cc",
+ "prerender/isolated/isolated_prerender_network_context_client.h",
+ "prerender/isolated/isolated_prerender_origin_prober.cc",
+ "prerender/isolated/isolated_prerender_origin_prober.h",
"prerender/isolated/isolated_prerender_params.cc",
"prerender/isolated/isolated_prerender_params.h",
"prerender/isolated/isolated_prerender_proxy_configurator.cc",
"prerender/isolated/isolated_prerender_proxy_configurator.h",
+ "prerender/isolated/isolated_prerender_proxying_url_loader_factory.cc",
+ "prerender/isolated/isolated_prerender_proxying_url_loader_factory.h",
"prerender/isolated/isolated_prerender_service.cc",
"prerender/isolated/isolated_prerender_service.h",
"prerender/isolated/isolated_prerender_service_factory.cc",
"prerender/isolated/isolated_prerender_service_factory.h",
- "prerender/isolated/isolated_prerender_service_workers_observer.cc",
- "prerender/isolated/isolated_prerender_service_workers_observer.h",
+ "prerender/isolated/isolated_prerender_subresource_manager.cc",
+ "prerender/isolated/isolated_prerender_subresource_manager.h",
"prerender/isolated/isolated_prerender_tab_helper.cc",
"prerender/isolated/isolated_prerender_tab_helper.h",
"prerender/isolated/isolated_prerender_url_loader.cc",
@@ -1345,8 +1290,6 @@ static_library("browser") {
"prerender/prerender_contents.h",
"prerender/prerender_field_trial.cc",
"prerender/prerender_field_trial.h",
- "prerender/prerender_final_status.cc",
- "prerender/prerender_final_status.h",
"prerender/prerender_handle.cc",
"prerender/prerender_handle.h",
"prerender/prerender_histograms.cc",
@@ -1363,8 +1306,6 @@ static_library("browser") {
"prerender/prerender_manager_factory.h",
"prerender/prerender_message_filter.cc",
"prerender/prerender_message_filter.h",
- "prerender/prerender_origin.cc",
- "prerender/prerender_origin.h",
"prerender/prerender_processor_impl.cc",
"prerender/prerender_processor_impl.h",
"prerender/prerender_tab_helper.cc",
@@ -1390,8 +1331,6 @@ static_library("browser") {
"process_resource_usage.cc",
"process_resource_usage.h",
"process_singleton.h",
- "process_singleton_mac.mm",
- "process_singleton_win.cc",
"profiles/avatar_menu_actions.h",
"profiles/bookmark_model_loaded_observer.cc",
"profiles/bookmark_model_loaded_observer.h",
@@ -1450,8 +1389,6 @@ static_library("browser") {
"profiles/profile_metrics.cc",
"profiles/profile_metrics.h",
"profiles/profile_observer.h",
- "profiles/profile_shortcut_manager_win.cc",
- "profiles/profile_shortcut_manager_win.h",
"profiles/profiles_state.cc",
"profiles/profiles_state.h",
"profiles/renderer_updater.cc",
@@ -1485,10 +1422,6 @@ static_library("browser") {
"renderer_context_menu/context_menu_content_type_factory.h",
"renderer_host/chrome_navigation_ui_data.cc",
"renderer_host/chrome_navigation_ui_data.h",
- "renderer_host/chrome_render_widget_host_view_mac_delegate.h",
- "renderer_host/chrome_render_widget_host_view_mac_delegate.mm",
- "renderer_host/chrome_render_widget_host_view_mac_history_swiper.h",
- "renderer_host/chrome_render_widget_host_view_mac_history_swiper.mm",
"renderer_preferences_util.cc",
"renderer_preferences_util.h",
"reputation/local_heuristics.cc",
@@ -1532,8 +1465,6 @@ static_library("browser") {
"search_engines/template_url_service_factory.h",
"search_engines/ui_thread_search_terms_data.cc",
"search_engines/ui_thread_search_terms_data.h",
- "search_engines/ui_thread_search_terms_data_android.cc",
- "search_engines/ui_thread_search_terms_data_android.h",
"search_provider_logos/logo_service_factory.cc",
"search_provider_logos/logo_service_factory.h",
"security_events/security_event_recorder.h",
@@ -1564,15 +1495,18 @@ static_library("browser") {
"sessions/session_common_utils.h",
"sessions/session_data_deleter.cc",
"sessions/session_data_deleter.h",
- "sessions/session_restore_android.cc",
"sessions/session_tab_helper_factory.cc",
"sessions/session_tab_helper_factory.h",
"sessions/tab_restore_service_factory.cc",
"sessions/tab_restore_service_factory.h",
+ "sharesheet/sharesheet_action_cache.cc",
+ "sharesheet/sharesheet_action_cache.h",
+ "sharesheet/sharesheet_service.cc",
+ "sharesheet/sharesheet_service.h",
+ "sharesheet/sharesheet_service_factory.cc",
+ "sharesheet/sharesheet_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",
@@ -1617,8 +1551,6 @@ static_library("browser") {
"sharing/sharing_service.h",
"sharing/sharing_service_factory.cc",
"sharing/sharing_service_factory.h",
- "sharing/sharing_service_proxy_android.cc",
- "sharing/sharing_service_proxy_android.h",
"sharing/sharing_sync_preference.cc",
"sharing/sharing_sync_preference.h",
"sharing/sharing_utils.cc",
@@ -1641,11 +1573,6 @@ static_library("browser") {
"sharing/webrtc/webrtc_flags.h",
"shell_integration.cc",
"shell_integration.h",
- "shell_integration_android.cc",
- "shell_integration_chromeos.cc",
- "shell_integration_mac.mm",
- "shell_integration_win.cc",
- "shell_integration_win.h",
"signin/about_signin_internals_factory.cc",
"signin/about_signin_internals_factory.h",
"signin/account_consistency_mode_manager.cc",
@@ -1684,6 +1611,8 @@ static_library("browser") {
"signin/reauth_result.h",
"signin/reauth_tab_helper.cc",
"signin/reauth_tab_helper.h",
+ "signin/reauth_util.cc",
+ "signin/reauth_util.h",
"signin/signin_error_controller_factory.cc",
"signin/signin_error_controller_factory.h",
"signin/signin_features.cc",
@@ -1694,29 +1623,25 @@ static_library("browser") {
"signin/signin_profile_attributes_updater_factory.h",
"signin/signin_promo_util.cc",
"signin/signin_promo_util.h",
- "signin/signin_status_metrics_provider_chromeos.cc",
- "signin/signin_status_metrics_provider_chromeos.h",
"signin/signin_util.cc",
"signin/signin_util.h",
"site_isolation/prefs_observer.cc",
"site_isolation/prefs_observer.h",
"site_isolation/site_details.cc",
"site_isolation/site_details.h",
- "site_isolation/site_isolation_policy.cc",
- "site_isolation/site_isolation_policy.h",
"speech/chrome_speech_recognition_manager_delegate.cc",
"speech/chrome_speech_recognition_manager_delegate.h",
"speech/speech_recognizer.cc",
"speech/speech_recognizer.h",
"speech/speech_recognizer_delegate.h",
- "speech/tts_controller_delegate_impl.cc",
- "speech/tts_controller_delegate_impl.h",
"ssl/certificate_error_reporter.cc",
"ssl/certificate_error_reporter.h",
"ssl/chrome_security_blocking_page_factory.cc",
"ssl/chrome_security_blocking_page_factory.h",
"ssl/connection_help_tab_helper.cc",
"ssl/connection_help_tab_helper.h",
+ "ssl/insecure_form/insecure_form_controller_client.cc",
+ "ssl/insecure_form/insecure_form_controller_client.h",
"ssl/insecure_sensitive_input_driver.cc",
"ssl/insecure_sensitive_input_driver.h",
"ssl/insecure_sensitive_input_driver_factory.cc",
@@ -1740,8 +1665,6 @@ static_library("browser") {
"ssl/stateful_ssl_host_state_delegate_factory.h",
"ssl/tls_deprecation_config.cc",
"ssl/tls_deprecation_config.h",
- "ssl/typed_navigation_timing_throttle.cc",
- "ssl/typed_navigation_timing_throttle.h",
"startup_data.cc",
"startup_data.h",
"status_icons/status_icon.cc",
@@ -1763,6 +1686,10 @@ static_library("browser") {
"subresource_filter/subresource_filter_profile_context.h",
"subresource_filter/subresource_filter_profile_context_factory.cc",
"subresource_filter/subresource_filter_profile_context_factory.h",
+ "subresource_redirect/https_image_compression_bypass_decider.cc",
+ "subresource_redirect/https_image_compression_bypass_decider.h",
+ "subresource_redirect/https_image_compression_infobar_decider.cc",
+ "subresource_redirect/https_image_compression_infobar_decider.h",
"subresource_redirect/subresource_redirect_observer.cc",
"subresource_redirect/subresource_redirect_observer.h",
"sync/bookmark_sync_service_factory.cc",
@@ -1791,12 +1718,8 @@ static_library("browser") {
"sync/sessions/sync_sessions_web_contents_router_factory.h",
"sync/sync_encryption_keys_tab_helper.cc",
"sync/sync_encryption_keys_tab_helper.h",
- "sync/sync_error_infobar_delegate_android.cc",
- "sync/sync_error_infobar_delegate_android.h",
"sync/sync_startup_tracker.cc",
"sync/sync_startup_tracker.h",
- "sync/trusted_vault_client_android.cc",
- "sync/trusted_vault_client_android.h",
"sync/user_event_service_factory.cc",
"sync/user_event_service_factory.h",
"tab/state/tab_state_db.cc",
@@ -1809,8 +1732,6 @@ static_library("browser") {
"tab_contents/tab_util.h",
"task_manager/web_contents_tags.cc",
"task_manager/web_contents_tags.h",
- "themes/theme_helper_win.cc",
- "themes/theme_helper_win.h",
"tracing/background_tracing_field_trial.cc",
"tracing/background_tracing_field_trial.h",
"tracing/background_tracing_metrics_provider.cc",
@@ -1823,8 +1744,6 @@ static_library("browser") {
"tracing/trace_event_system_stats_monitor.h",
"transition_manager/full_browser_transition_manager.cc",
"transition_manager/full_browser_transition_manager.h",
- "translate/android/translate_utils.cc",
- "translate/android/translate_utils.h",
"translate/chrome_translate_client.cc",
"translate/chrome_translate_client.h",
"translate/translate_accept_languages_factory.cc",
@@ -1866,55 +1785,10 @@ static_library("browser") {
"vr/ui_suppressed_element.h",
"vr/vr_tab_helper.cc",
"vr/vr_tab_helper.h",
- "vr/webxr_permission_context.cc",
- "vr/webxr_permission_context.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",
- "win/app_icon.cc",
- "win/app_icon.h",
- "win/automation_controller.cc",
- "win/automation_controller.h",
- "win/browser_util.cc",
- "win/browser_util.h",
- "win/chrome_elf_init.cc",
- "win/chrome_elf_init.h",
- "win/chrome_select_file_dialog_factory.cc",
- "win/chrome_select_file_dialog_factory.h",
- "win/conflicts/enumerate_input_method_editors.cc",
- "win/conflicts/enumerate_input_method_editors.h",
- "win/conflicts/enumerate_shell_extensions.cc",
- "win/conflicts/enumerate_shell_extensions.h",
- "win/conflicts/inspection_results_cache.cc",
- "win/conflicts/inspection_results_cache.h",
- "win/conflicts/module_database.cc",
- "win/conflicts/module_database.h",
- "win/conflicts/module_database_observer.h",
- "win/conflicts/module_event_sink_impl.cc",
- "win/conflicts/module_event_sink_impl.h",
- "win/conflicts/module_inspector.cc",
- "win/conflicts/module_inspector.h",
- "win/conflicts/third_party_metrics_recorder.cc",
- "win/conflicts/third_party_metrics_recorder.h",
- "win/jumplist.cc",
- "win/jumplist.h",
- "win/jumplist_factory.cc",
- "win/jumplist_factory.h",
- "win/jumplist_file_util.cc",
- "win/jumplist_file_util.h",
- "win/jumplist_update_util.cc",
- "win/jumplist_update_util.h",
- "win/jumplist_updater.cc",
- "win/jumplist_updater.h",
- "win/settings_app_monitor.cc",
- "win/settings_app_monitor.h",
- "win/taskbar_icon_finder.cc",
- "win/taskbar_icon_finder.h",
- "win/titlebar_config.cc",
- "win/titlebar_config.h",
- "win/ui_automation_util.cc",
- "win/ui_automation_util.h",
]
configs += [
@@ -1956,7 +1830,6 @@ static_library("browser") {
":expired_flags_list",
":ntp_background_proto",
":permissions_proto",
- ":reporting_record_proto",
":resource_prefetch_predictor_proto",
":status_proto",
":tab_state_db_content_proto",
@@ -1984,6 +1857,7 @@ static_library("browser") {
"//chrome/browser/metrics/variations:chrome_ui_string_overrider_factory",
"//chrome/browser/net:probe_message_proto",
"//chrome/browser/notifications",
+ "//chrome/browser/privacy_budget",
"//chrome/browser/profiling_host",
"//chrome/browser/push_messaging:budget_proto",
"//chrome/browser/reputation:proto",
@@ -2000,13 +1874,14 @@ static_library("browser") {
"//chrome/browser/updates/announcement_notification",
"//chrome/common:channel_info",
"//chrome/common/net",
+ "//chrome/common/performance_manager/mojom",
"//chrome/installer/util:with_no_strings",
"//components/assist_ranker",
"//components/autofill/content/browser",
"//components/autofill/core/browser",
"//components/background_task_scheduler",
- "//components/blacklist/opt_out_blacklist:opt_out_blacklist",
- "//components/blacklist/opt_out_blacklist/sql:opt_out_blacklist_sql",
+ "//components/blocklist/opt_out_blocklist:opt_out_blocklist",
+ "//components/blocklist/opt_out_blocklist/sql:opt_out_blocklist_sql",
"//components/bookmarks/browser",
"//components/bookmarks/managed",
"//components/browser_sync",
@@ -2030,6 +1905,7 @@ static_library("browser") {
"//components/contextual_search/content:browser",
"//components/contextual_search/core:browser",
"//components/cookie_config",
+ "//components/country_codes",
"//components/crx_file",
"//components/data_reduction_proxy/core/browser",
"//components/data_use_measurement/core:ascriber",
@@ -2042,11 +1918,14 @@ static_library("browser") {
"//components/download/public/background_service:public",
"//components/embedder_support",
"//components/encrypted_messages",
+ "//components/enterprise",
+ "//components/enterprise/common/proto:connectors_proto",
"//components/error_page/common",
"//components/favicon/content",
"//components/favicon/core",
"//components/favicon_base",
"//components/feature_engagement",
+ "//components/federated_learning",
"//components/filename_generation",
"//components/find_in_page",
"//components/flags_ui",
@@ -2056,6 +1935,7 @@ static_library("browser") {
"//components/history/content/browser",
"//components/history/core/browser",
"//components/history/core/common",
+ "//components/infobars/content",
"//components/infobars/core",
"//components/invalidation/impl",
"//components/javascript_dialogs",
@@ -2067,8 +1947,8 @@ static_library("browser") {
"//components/lookalikes/core",
"//components/metrics:call_stack_profile_collector",
"//components/metrics:component_metrics",
+ "//components/metrics:content",
"//components/metrics:demographic_metrics_provider",
- "//components/metrics:gpu",
"//components/metrics:net",
"//components/metrics:ui",
"//components/metrics_services_manager",
@@ -2101,7 +1981,10 @@ static_library("browser") {
"//components/policy/core/browser",
"//components/policy/proto",
"//components/policy/proto:policy_record_constants",
+ "//components/policy/proto:reporting_record_proto",
"//components/prefs",
+ "//components/prerender/common",
+ "//components/prerender/common:mojo_bindings",
"//components/previews/content",
"//components/previews/core",
"//components/profile_metrics",
@@ -2215,6 +2098,7 @@ static_library("browser") {
"//printing/buildflags",
"//rlz/buildflags",
"//services/audio/public/cpp",
+ "//services/cert_verifier:lib",
"//services/data_decoder/public/cpp",
"//services/device/public/cpp:device_features",
"//services/device/public/cpp/usb",
@@ -2278,18 +2162,6 @@ static_library("browser") {
"//ui/web_dialogs",
]
- if (is_win) {
- libs += [
- "secur32.lib",
-
- # Needed for _variant_t used in browser_dm_token_storage_win.cc
- "comsuppw.lib",
- ]
- sources +=
- [ "component_updater/recovery_improved_component_installer_win.cc" ]
- deps += [ "//chrome/elevation_service:elevation_service_idl" ]
- }
-
if (is_posix || is_fuchsia) {
sources += [
"download/trusted_sources_manager_posix.cc",
@@ -2332,6 +2204,8 @@ static_library("browser") {
"android/autofill_assistant/ui_controller_android.h",
"android/autofill_assistant/ui_controller_android_utils.cc",
"android/autofill_assistant/ui_controller_android_utils.h",
+ "android/autofill_assistant/view_handler_android.cc",
+ "android/autofill_assistant/view_handler_android.h",
"android/background_sync_launcher_android.cc",
"android/background_sync_launcher_android.h",
"android/background_tab_manager.cc",
@@ -2631,15 +2505,11 @@ static_library("browser") {
"android/preferences/browser_prefs_android.h",
"android/preferences/clipboard_android.cc",
"android/preferences/clipboard_android.h",
- "android/preferences/cookie_controls_bridge.cc",
- "android/preferences/cookie_controls_bridge.h",
"android/preferences/cookie_controls_service_bridge.cc",
"android/preferences/cookie_controls_service_bridge.h",
"android/preferences/pref_change_registrar_android.cc",
"android/preferences/pref_change_registrar_android.h",
"android/preferences/pref_service_bridge.cc",
- "android/preferences/pref_service_bridge.h",
- "android/preferences/prefs.h",
"android/preferences/privacy_preferences_manager.cc",
"android/profile_key_startup_accessor.cc",
"android/profile_key_startup_accessor.h",
@@ -2705,8 +2575,6 @@ static_library("browser") {
"android/tab_favicon.h",
"android/tab_printer.cc",
"android/tab_printer.h",
- "android/tab_state.cc",
- "android/tab_state.h",
"android/tab_web_contents_delegate_android.cc",
"android/tab_web_contents_delegate_android.h",
"android/trusted_cdn.cc",
@@ -2720,6 +2588,8 @@ static_library("browser") {
"android/usb/web_usb_chooser_android.h",
"android/warmup_manager.cc",
"android/web_contents_factory.cc",
+ "android/web_contents_state.cc",
+ "android/web_contents_state.h",
"android/webapk/webapk_handler_delegate.cc",
"android/webapk/webapk_handler_delegate.h",
"android/webapk/webapk_icon_hasher.cc",
@@ -2756,6 +2626,7 @@ static_library("browser") {
"android/webapps/add_to_homescreen_params.h",
"android/webapps/webapp_registry.cc",
"android/webapps/webapp_registry.h",
+ "android/webauth/fido2helper_native_android.cc",
"autofill/accessory_controller.h",
"autofill/address_accessory_controller.h",
"autofill/address_accessory_controller_impl.cc",
@@ -2778,8 +2649,14 @@ static_library("browser") {
"autofill/manual_filling_view_interface.h",
"banners/app_banner_manager_android.cc",
"banners/app_banner_manager_android.h",
+ "browser_process_platform_part_android.cc",
+ "browser_process_platform_part_android.h",
"chrome_browser_field_trials_mobile.cc",
"chrome_browser_field_trials_mobile.h",
+ "chrome_browser_main_android.cc",
+ "chrome_browser_main_android.h",
+ "crash_upload_list/crash_upload_list_android.cc",
+ "crash_upload_list/crash_upload_list_android.h",
"data_reduction_proxy/data_reduction_promo_infobar_delegate_android.cc",
"data_reduction_proxy/data_reduction_promo_infobar_delegate_android.h",
"data_reduction_proxy/data_reduction_proxy_settings_android.cc",
@@ -2797,9 +2674,8 @@ static_library("browser") {
"download/android/download_controller.h",
"download/android/download_controller_base.cc",
"download/android/download_controller_base.h",
- "download/android/download_location_dialog_bridge.h",
- "download/android/download_location_dialog_bridge_impl.cc",
- "download/android/download_location_dialog_bridge_impl.h",
+ "download/android/download_dialog_bridge.cc",
+ "download/android/download_dialog_bridge.h",
"download/android/download_manager_bridge.cc",
"download/android/download_manager_bridge.h",
"download/android/download_manager_service.cc",
@@ -2821,11 +2697,18 @@ static_library("browser") {
"download/android/service/download_task_scheduler.cc",
"download/android/service/download_task_scheduler.h",
"download/android/string_utils.cc",
+ "download/download_crx_util_android.cc",
"engagement/site_engagement_service_android.cc",
"engagement/site_engagement_service_android.h",
+ "enterprise/util/android_enterprise_info.cc",
+ "enterprise/util/android_enterprise_info.h",
+ "file_select_helper_contacts_android.cc",
+ "file_select_helper_contacts_android.h",
"first_run/android/first_run_utils.cc",
"flags/android/chrome_feature_list.cc",
"flags/android/chrome_feature_list.h",
+ "geolocation/geolocation_permission_context_delegate_android.cc",
+ "geolocation/geolocation_permission_context_delegate_android.h",
"history/android/android_history_provider_service.cc",
"history/android/android_history_provider_service.h",
"history/android/android_provider_backend.cc",
@@ -2834,9 +2717,14 @@ static_library("browser") {
"history/android/bookmark_model_sql_handler.h",
"history/android/sqlite_cursor.cc",
"history/android/sqlite_cursor.h",
+ "icon_loader_android.cc",
"installable/installable_ambient_badge_infobar_delegate.cc",
"installable/installed_webapp_bridge.cc",
"installable/installed_webapp_bridge.h",
+ "installable/installed_webapp_geolocation_bridge.cc",
+ "installable/installed_webapp_geolocation_bridge.h",
+ "installable/installed_webapp_geolocation_context.cc",
+ "installable/installed_webapp_geolocation_context.h",
"installable/installed_webapp_provider.cc",
"installable/installed_webapp_provider.h",
"lifetime/application_lifetime_android.cc",
@@ -2859,11 +2747,18 @@ static_library("browser") {
"media/android/router/media_router_dialog_controller_android.h",
"media/webrtc/screen_capture_infobar_delegate_android.cc",
"media/webrtc/screen_capture_infobar_delegate_android.h",
+ "memory_details_android.cc",
"metrics/chrome_android_metrics_provider.cc",
"metrics/chrome_android_metrics_provider.h",
"metrics/incognito_observer_android.cc",
"metrics/page_load_metrics_provider.cc",
"metrics/page_load_metrics_provider.h",
+ "metrics/thread_watcher_android.cc",
+ "metrics/thread_watcher_android.h",
+ "nfc/nfc_permission_context_android.cc",
+ "nfc/nfc_permission_context_android.h",
+ "notifications/notification_channels_provider_android.cc",
+ "notifications/notification_channels_provider_android.h",
"notifications/notification_platform_bridge_android.cc",
"notifications/notification_platform_bridge_android.h",
"notifications/notification_trigger_scheduler_android.cc",
@@ -2909,6 +2804,8 @@ static_library("browser") {
"password_manager/android/touch_to_fill_view.h",
"password_manager/android/update_password_infobar_delegate_android.cc",
"password_manager/android/update_password_infobar_delegate_android.h",
+ "password_manager/biometric_authenticator_android.cc",
+ "password_manager/biometric_authenticator_android.h",
"payments/android/can_make_payment_query_android.cc",
"payments/android/journey_logger_android.cc",
"payments/android/journey_logger_android.h",
@@ -2949,8 +2846,16 @@ static_library("browser") {
"search/contextual_search_policy_handler_android.h",
"search_engines/template_url_service_factory_android.cc",
"search_engines/template_url_service_factory_android.h",
+ "search_engines/ui_thread_search_terms_data_android.cc",
+ "search_engines/ui_thread_search_terms_data_android.h",
+ "sessions/session_restore_android.cc",
+ "sharing/click_to_call/click_to_call_message_handler_android.cc",
+ "sharing/click_to_call/click_to_call_message_handler_android.h",
"sharing/shared_clipboard/shared_clipboard_message_handler_android.cc",
"sharing/shared_clipboard/shared_clipboard_message_handler_android.h",
+ "sharing/sharing_service_proxy_android.cc",
+ "sharing/sharing_service_proxy_android.h",
+ "shell_integration_android.cc",
"signin/identity_services_provider_android.cc",
"signin/signin_manager_android_factory.cc",
"signin/signin_manager_android_factory.h",
@@ -2968,10 +2873,16 @@ static_library("browser") {
"sync/glue/synced_window_delegates_getter_android.h",
"sync/profile_sync_service_android.cc",
"sync/profile_sync_service_android.h",
+ "sync/sync_error_infobar_delegate_android.cc",
+ "sync/sync_error_infobar_delegate_android.h",
+ "sync/trusted_vault_client_android.cc",
+ "sync/trusted_vault_client_android.h",
"touch_to_fill/touch_to_fill_controller.cc",
"touch_to_fill/touch_to_fill_controller.h",
"translate/android/translate_bridge.cc",
"translate/android/translate_bridge.h",
+ "translate/android/translate_utils.cc",
+ "translate/android/translate_utils.h",
"updates/update_notification_client.cc",
"updates/update_notification_client.h",
"updates/update_notification_service_bridge_android.cc",
@@ -2996,7 +2907,9 @@ static_library("browser") {
"//chrome/browser/notifications/scheduler/public",
"//chrome/browser/offline_pages/prefetch/notifications",
"//chrome/browser/optimization_guide/android:jni_headers",
+ "//chrome/browser/password_check/android",
"//chrome/browser/payments/android:jni_headers",
+ "//chrome/browser/safety_check/android",
"//chrome/browser/share",
"//chrome/browser/updates",
"//chrome/common:non_code_constants",
@@ -3074,15 +2987,6 @@ static_library("browser") {
]
deps += [ "//chrome/android/modules/dev_ui/provider:native" ]
}
-
- if (enable_password_change_in_leaked_dialog) {
- sources += [
- "password_manager/credential_leak_password_change_controller_android.cc",
- "password_manager/credential_leak_password_change_controller_android.h",
- ]
-
- defines += [ "ENABLE_PASSWORD_CHANGE" ]
- }
} else { # !is_android
sources += [
"accessibility/caption_controller.cc",
@@ -3149,6 +3053,12 @@ static_library("browser") {
"banners/app_banner_manager_desktop.h",
"bookmarks/bookmark_html_writer.cc",
"bookmarks/bookmark_html_writer.h",
+ "browsing_data/access_context_audit_database.cc",
+ "browsing_data/access_context_audit_database.h",
+ "browsing_data/access_context_audit_service.cc",
+ "browsing_data/access_context_audit_service.h",
+ "browsing_data/access_context_audit_service_factory.cc",
+ "browsing_data/access_context_audit_service_factory.h",
"certificate_viewer.h",
"chrome_browser_field_trials_desktop.cc",
"chrome_browser_field_trials_desktop.h",
@@ -3158,6 +3068,8 @@ static_library("browser") {
"component_updater/intervention_policy_database_component_installer.h",
"component_updater/soda_component_installer.cc",
"component_updater/soda_component_installer.h",
+ "content_settings/generated_cookie_prefs.cc",
+ "content_settings/generated_cookie_prefs.h",
"custom_handlers/register_protocol_handler_permission_request.cc",
"custom_handlers/register_protocol_handler_permission_request.h",
"device_identity/device_identity_provider.cc",
@@ -3211,8 +3123,10 @@ static_library("browser") {
"enterprise/connectors/connectors_prefs.h",
"enterprise/connectors/enterprise_connectors_policy_handler.cc",
"enterprise/connectors/enterprise_connectors_policy_handler.h",
- "enterprise/connectors/service_providers.cc",
- "enterprise/connectors/service_providers.h",
+ "enterprise/connectors/reporting_service_settings.cc",
+ "enterprise/connectors/reporting_service_settings.h",
+ "enterprise/connectors/service_provider_config.cc",
+ "enterprise/connectors/service_provider_config.h",
"enterprise/reporting/browser_report_generator.cc",
"enterprise/reporting/browser_report_generator.h",
"enterprise/reporting/extension_info.cc",
@@ -3225,15 +3139,12 @@ static_library("browser") {
"enterprise/reporting/notification/extension_request_observer.h",
"enterprise/reporting/notification/extension_request_observer_factory.cc",
"enterprise/reporting/notification/extension_request_observer_factory.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_request_definition.h",
"enterprise/reporting/report_request_queue_generator.cc",
"enterprise/reporting/report_request_queue_generator.h",
"enterprise/reporting/report_scheduler.cc",
@@ -3261,9 +3172,6 @@ static_library("browser") {
"first_run/first_run.h",
"first_run/first_run_dialog.h",
"first_run/first_run_internal.h",
- "first_run/first_run_internal_linux.cc",
- "first_run/first_run_internal_mac.mm",
- "first_run/first_run_internal_win.cc",
"font_family_cache.cc",
"font_family_cache.h",
"hid/chrome_hid_delegate.cc",
@@ -3278,7 +3186,6 @@ static_library("browser") {
"importer/external_process_importer_host.h",
"importer/firefox_profile_lock.cc",
"importer/firefox_profile_lock.h",
- "importer/firefox_profile_lock_win.cc",
"importer/importer_list.cc",
"importer/importer_list.h",
"importer/importer_lock_dialog.h",
@@ -3305,6 +3212,16 @@ static_library("browser") {
"media/feeds/media_feeds_service.h",
"media/feeds/media_feeds_service_factory.cc",
"media/feeds/media_feeds_service_factory.h",
+ "media/kaleidoscope/constants.cc",
+ "media/kaleidoscope/constants.h",
+ "media/kaleidoscope/kaleidoscope_data_provider_impl.cc",
+ "media/kaleidoscope/kaleidoscope_data_provider_impl.h",
+ "media/kaleidoscope/kaleidoscope_switches.cc",
+ "media/kaleidoscope/kaleidoscope_switches.h",
+ "media/kaleidoscope/kaleidoscope_tab_helper.cc",
+ "media/kaleidoscope/kaleidoscope_tab_helper.h",
+ "media/kaleidoscope/kaleidoscope_ui.cc",
+ "media/kaleidoscope/kaleidoscope_ui.h",
"media/unified_autoplay_config.cc",
"media/unified_autoplay_config.h",
"media/webrtc/desktop_capture_devices_util.cc",
@@ -3361,8 +3278,6 @@ static_library("browser") {
"memory/swap_thrashing_monitor.h",
"memory/swap_thrashing_monitor_delegate.cc",
"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",
@@ -3379,6 +3294,8 @@ static_library("browser") {
"metrics/desktop_session_duration/desktop_session_duration_observer.h",
"metrics/desktop_session_duration/desktop_session_duration_tracker.cc",
"metrics/desktop_session_duration/desktop_session_duration_tracker.h",
+ "metrics/desktop_session_duration/touch_mode_stats_tracker.cc",
+ "metrics/desktop_session_duration/touch_mode_stats_tracker.h",
"metrics/first_web_contents_profiler.cc",
"metrics/first_web_contents_profiler.h",
"metrics/incognito_observer_desktop.cc",
@@ -3387,8 +3304,23 @@ static_library("browser") {
"metrics/tab_stats_tracker.cc",
"metrics/tab_stats_tracker.h",
"metrics/tab_stats_tracker_delegate.h",
- "metrics/tab_stats_tracker_delegate_win.cc",
- "metrics/tab_stats_tracker_win.cc",
+ "nearby_sharing/attachment.h",
+ "nearby_sharing/client/nearby_share_api_call_flow.h",
+ "nearby_sharing/client/nearby_share_api_call_flow_impl.cc",
+ "nearby_sharing/client/nearby_share_api_call_flow_impl.h",
+ "nearby_sharing/client/nearby_share_request_error.cc",
+ "nearby_sharing/client/nearby_share_request_error.h",
+ "nearby_sharing/fast_initiation_manager.cc",
+ "nearby_sharing/fast_initiation_manager.h",
+ "nearby_sharing/file_attachment.cc",
+ "nearby_sharing/file_attachment.h",
+ "nearby_sharing/nearby_connection.h",
+ "nearby_sharing/nearby_connections_manager.h",
+ "nearby_sharing/nearby_connections_manager_impl.cc",
+ "nearby_sharing/nearby_connections_manager_impl.h",
+ "nearby_sharing/nearby_constants.h",
+ "nearby_sharing/nearby_process_manager.cc",
+ "nearby_sharing/nearby_process_manager.h",
"nearby_sharing/nearby_sharing_prefs.cc",
"nearby_sharing/nearby_sharing_prefs.h",
"nearby_sharing/nearby_sharing_service.h",
@@ -3396,14 +3328,28 @@ static_library("browser") {
"nearby_sharing/nearby_sharing_service_factory.h",
"nearby_sharing/nearby_sharing_service_impl.cc",
"nearby_sharing/nearby_sharing_service_impl.h",
+ "nearby_sharing/share_target.cc",
+ "nearby_sharing/share_target.h",
+ "nearby_sharing/share_target_discovered_callback.h",
+ "nearby_sharing/tachyon/constants.h",
+ "nearby_sharing/tachyon/receive_messages_express.cc",
+ "nearby_sharing/tachyon/receive_messages_express.h",
+ "nearby_sharing/tachyon/send_message_express.cc",
+ "nearby_sharing/tachyon/send_message_express.h",
+ "nearby_sharing/tachyon/stream_parser.cc",
+ "nearby_sharing/tachyon/stream_parser.h",
+ "nearby_sharing/tachyon/token_fetcher.cc",
+ "nearby_sharing/tachyon/token_fetcher.h",
+ "nearby_sharing/text_attachment.cc",
+ "nearby_sharing/text_attachment.h",
+ "nearby_sharing/transfer_metadata.cc",
+ "nearby_sharing/transfer_metadata.h",
+ "nearby_sharing/transfer_update_callback.h",
"notifications/notification_system_observer.cc",
"notifications/notification_system_observer.h",
"notifications/profile_notification.cc",
"notifications/profile_notification.h",
"obsolete_system/obsolete_system.h",
- "obsolete_system/obsolete_system_linux.cc",
- "obsolete_system/obsolete_system_mac.cc",
- "obsolete_system/obsolete_system_win.cc",
"page_load_metrics/observers/session_restore_page_load_metrics_observer.cc",
"page_load_metrics/observers/session_restore_page_load_metrics_observer.h",
"performance_manager/mechanisms/page_discarder.cc",
@@ -3446,7 +3392,6 @@ static_library("browser") {
"profile_resetter/triggered_profile_resetter.h",
"profile_resetter/triggered_profile_resetter_factory.cc",
"profile_resetter/triggered_profile_resetter_factory.h",
- "profile_resetter/triggered_profile_resetter_win.cc",
"profiles/profile_shortcut_manager.cc",
"profiles/profile_shortcut_manager.h",
"profiles/profile_window.cc",
@@ -3516,8 +3461,6 @@ static_library("browser") {
"resource_coordinator/tab_lifecycle_unit_source.h",
"resource_coordinator/tab_manager.cc",
"resource_coordinator/tab_manager.h",
- "resource_coordinator/tab_manager_delegate_chromeos.cc",
- "resource_coordinator/tab_manager_delegate_chromeos.h",
"resource_coordinator/tab_manager_resource_coordinator_signal_observer.cc",
"resource_coordinator/tab_manager_resource_coordinator_signal_observer.h",
"resource_coordinator/tab_manager_stats_collector.cc",
@@ -3526,10 +3469,10 @@ static_library("browser") {
"resource_coordinator/tab_manager_web_contents_data.h",
"resource_coordinator/tab_metrics_logger.cc",
"resource_coordinator/tab_metrics_logger.h",
- "resource_coordinator/tracing_lifecycle_unit_observer.cc",
- "resource_coordinator/tracing_lifecycle_unit_observer.h",
"resource_coordinator/usage_clock.cc",
"resource_coordinator/usage_clock.h",
+ "safe_browsing/generated_safe_browsing_pref.cc",
+ "safe_browsing/generated_safe_browsing_pref.h",
"search/background/ntp_background_data.cc",
"search/background/ntp_background_data.h",
"search/background/ntp_background_service.cc",
@@ -3685,6 +3628,8 @@ static_library("browser") {
"task_manager/providers/per_profile_worker_task_tracker.h",
"task_manager/providers/render_process_host_task_provider.cc",
"task_manager/providers/render_process_host_task_provider.h",
+ "task_manager/providers/spare_render_process_host_task_provider.cc",
+ "task_manager/providers/spare_render_process_host_task_provider.h",
"task_manager/providers/task.cc",
"task_manager/providers/task.h",
"task_manager/providers/task_provider.cc",
@@ -3737,8 +3682,6 @@ static_library("browser") {
"task_manager/providers/worker_task_provider.cc",
"task_manager/providers/worker_task_provider.h",
"task_manager/sampling/shared_sampler.h",
- "task_manager/sampling/shared_sampler_win.cc",
- "task_manager/sampling/shared_sampler_win_defines.h",
"task_manager/sampling/task_group.cc",
"task_manager/sampling/task_group.h",
"task_manager/sampling/task_group_sampler.cc",
@@ -3794,7 +3737,11 @@ static_library("browser") {
"//base/util/memory_pressure",
"//base/util/timer",
"//chrome/app/vector_icons",
- "//chrome/browser/enterprise/connectors:connectors_proto",
+ "//chrome/browser/media/kaleidoscope/mojom",
+ "//chrome/browser/nearby_sharing/certificates",
+ "//chrome/browser/nearby_sharing/logging",
+ "//chrome/browser/nearby_sharing/proto",
+ "//chrome/browser/nearby_sharing/tachyon/proto",
"//chrome/browser/policy:path_parser",
"//chrome/browser/profile_resetter:profile_reset_report_proto",
"//chrome/browser/resource_coordinator:intervention_policy_database_proto",
@@ -3805,12 +3752,6 @@ static_library("browser") {
"//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_update",
- "//chrome/services/app_service/public/cpp:icon_loader",
- "//chrome/services/app_service/public/cpp:intents",
- "//chrome/services/app_service/public/cpp:preferred_apps",
- "//chrome/services/app_service/public/cpp:publisher",
"//chrome/services/sharing/public/cpp",
"//chrome/services/sharing/public/mojom",
"//chrome/services/speech:buildflags",
@@ -3819,7 +3760,13 @@ static_library("browser") {
"//components/keep_alive_registry",
"//components/ntp_snippets",
"//components/schema_org:extractor",
+ "//components/services/app_service:lib",
"//components/services/app_service/public/cpp:app_file_handling",
+ "//components/services/app_service/public/cpp:app_update",
+ "//components/services/app_service/public/cpp:icon_loader",
+ "//components/services/app_service/public/cpp:intents",
+ "//components/services/app_service/public/cpp:preferred_apps",
+ "//components/services/app_service/public/cpp:publisher",
"//components/soda:constants",
"//components/vector_icons",
"//components/web_modal",
@@ -3865,6 +3812,8 @@ static_library("browser") {
"apps/app_service/uninstall_dialog.h",
"apps/app_service/web_apps_chromeos.cc",
"apps/app_service/web_apps_chromeos.h",
+ "browser_process_platform_part_chromeos.cc",
+ "browser_process_platform_part_chromeos.h",
"component_updater/cros_component_installer_chromeos.cc",
"component_updater/cros_component_installer_chromeos.h",
"component_updater/cros_component_manager.cc",
@@ -3887,6 +3836,7 @@ static_library("browser") {
"google/google_brand_chromeos.h",
"google/google_brand_code_map_chromeos.cc",
"google/google_brand_code_map_chromeos.h",
+ "icon_loader_chromeos.cc",
"media/chromeos_login_media_access_handler.cc",
"media/chromeos_login_media_access_handler.h",
"media/public_session_media_access_handler.cc",
@@ -3895,6 +3845,7 @@ static_library("browser") {
"media/public_session_tab_capture_access_handler.h",
"media/webrtc/desktop_media_list_ash.cc",
"media/webrtc/desktop_media_list_ash.h",
+ "media/webrtc/window_icon_util_chromeos.cc",
"media_galleries/chromeos/mtp_device_delegate_impl_chromeos.cc",
"media_galleries/chromeos/mtp_device_delegate_impl_chromeos.h",
"media_galleries/chromeos/mtp_device_object_enumerator.cc",
@@ -3943,12 +3894,24 @@ static_library("browser") {
"notifications/notifier_controller.h",
"notifications/web_page_notifier_controller.cc",
"notifications/web_page_notifier_controller.h",
+ "performance_manager/mechanisms/working_set_trimmer_chromeos.cc",
+ "performance_manager/mechanisms/working_set_trimmer_chromeos.h",
+ "performance_manager/policies/working_set_trimmer_policy_chromeos.cc",
+ "performance_manager/policies/working_set_trimmer_policy_chromeos.h",
+ "platform_util_chromeos.cc",
"policy/default_geolocation_policy_handler.cc",
"policy/default_geolocation_policy_handler.h",
"renderer_context_menu/quick_answers_menu_observer.cc",
"renderer_context_menu/quick_answers_menu_observer.h",
+ "resource_coordinator/tab_manager_delegate_chromeos.cc",
+ "resource_coordinator/tab_manager_delegate_chromeos.h",
+ "shell_integration_chromeos.cc",
+ "signin/signin_status_metrics_provider_chromeos.cc",
+ "signin/signin_status_metrics_provider_chromeos.h",
"speech/tts_chromeos.cc",
"speech/tts_chromeos.h",
+ "speech/tts_controller_delegate_impl.cc",
+ "speech/tts_controller_delegate_impl.h",
"sync/sync_error_notifier_ash.cc",
"sync/sync_error_notifier_ash.h",
"sync/sync_error_notifier_factory_ash.cc",
@@ -3976,11 +3939,13 @@ static_library("browser") {
]
deps += [
"//ash/public/cpp",
+ "//ash/public/cpp/external_arc",
"//chrome/browser/chromeos",
- "//chrome/services/app_service/public/cpp:instance_update",
"//chromeos/components/account_manager",
+ "//chromeos/components/cdm_factory_daemon:cdm_factory_daemon_browser",
"//chromeos/components/quick_answers",
"//chromeos/components/sync_wifi",
+ "//chromeos/lacros/mojom",
"//chromeos/services/assistant/public/cpp",
"//chromeos/services/cellular_setup",
"//chromeos/services/device_sync/public/mojom",
@@ -3992,8 +3957,10 @@ static_library("browser") {
"//chromeos/services/secure_channel/public/mojom",
"//chromeos/strings",
"//components/metrics/structured",
+ "//components/services/app_service/public/cpp:instance_update",
"//components/services/font:lib",
"//components/services/font/public/mojom",
+ "//components/user_manager",
"//ui/events/ozone",
"//ui/ozone",
]
@@ -4028,14 +3995,55 @@ static_library("browser") {
]
}
+ if (chromeos_is_browser_only) {
+ sources += [
+ "metrics/lacros_metrics_provider.cc",
+ "metrics/lacros_metrics_provider.h",
+ ]
+ deps += [
+ "//chromeos/lacros/browser",
+ "//chromeos/lacros/mojom",
+ ]
+ }
+
if (is_win) {
+ libs += [
+ "secur32.lib",
+
+ # Needed for _variant_t used in browser_dm_token_storage_win.cc
+ "comsuppw.lib",
+ ]
sources += [
"badging/badge_manager_delegate_win.cc",
"badging/badge_manager_delegate_win.h",
+ "browser_process_platform_part_win.cc",
+ "browser_process_platform_part_win.h",
"browser_switcher/browser_switcher_policy_migrator.cc",
"browser_switcher/browser_switcher_policy_migrator.h",
"browser_switcher/browser_switcher_service_win.cc",
"browser_switcher/browser_switcher_service_win.h",
+ "chrome_browser_main_win.cc",
+ "chrome_browser_main_win.h",
+ "component_updater/recovery_improved_component_installer_win.cc",
+ "component_updater/sw_reporter_installer_win.cc",
+ "component_updater/sw_reporter_installer_win.h",
+ "download/download_status_updater_win.cc",
+ "download/trusted_sources_manager_win.cc",
+ "first_run/first_run_internal_win.cc",
+ "first_run/upgrade_util_win.cc",
+ "first_run/upgrade_util_win.h",
+ "fullscreen_win.cc",
+ "google/did_run_updater_win.cc",
+ "google/did_run_updater_win.h",
+ "hang_monitor/hang_crash_dump_win.cc",
+ "icon_loader_win.cc",
+ "importer/firefox_profile_lock_win.cc",
+ "install_verification/win/module_info.h",
+ "install_verification/win/module_list.cc",
+ "install_verification/win/module_list.h",
+ "install_verification/win/module_verification_common.cc",
+ "install_verification/win/module_verification_common.h",
+ "media/webrtc/window_icon_util_win.cc",
"media_galleries/win/mtp_device_delegate_impl_win.cc",
"media_galleries/win/mtp_device_delegate_impl_win.h",
"media_galleries/win/mtp_device_object_entry.cc",
@@ -4048,16 +4056,98 @@ static_library("browser") {
"media_galleries/win/portable_device_map_service.h",
"media_galleries/win/snapshot_file_details.cc",
"media_galleries/win/snapshot_file_details.h",
+ "memory/swap_thrashing_monitor_delegate_win.cc",
+ "memory/swap_thrashing_monitor_delegate_win.h",
+ "memory_details_win.cc",
+ "metrics/antivirus_metrics_provider_win.cc",
+ "metrics/antivirus_metrics_provider_win.h",
+ "metrics/google_update_metrics_provider_win.cc",
+ "metrics/google_update_metrics_provider_win.h",
+ "metrics/jumplist_metrics_win.cc",
+ "metrics/jumplist_metrics_win.h",
+ "metrics/tab_stats_tracker_delegate_win.cc",
+ "metrics/tab_stats_tracker_win.cc",
+ "net/net_error_diagnostics_dialog_win.cc",
+ "net/service_providers_win.cc",
+ "net/service_providers_win.h",
"notifications/win/notification_image_retainer.cc",
"notifications/win/notification_image_retainer.h",
"notifications/win/notification_template_builder.cc",
"notifications/win/notification_template_builder.h",
+ "obsolete_system/obsolete_system_win.cc",
+ "password_manager/password_manager_util_win.cc",
+ "password_manager/password_manager_util_win.h",
+ "performance_manager/mechanisms/working_set_trimmer_win.cc",
+ "performance_manager/mechanisms/working_set_trimmer_win.h",
+ "performance_manager/policies/working_set_trimmer_policy_win.cc",
+ "performance_manager/policies/working_set_trimmer_policy_win.h",
+ "performance_monitor/metric_evaluator_helper_win.cc",
+ "performance_monitor/metric_evaluator_helper_win.h",
+ "platform_util_win.cc",
+ "policy/browser_dm_token_storage_win.cc",
+ "policy/browser_dm_token_storage_win.h",
+ "process_singleton_win.cc",
+ "profile_resetter/triggered_profile_resetter_win.cc",
+ "profiles/profile_shortcut_manager_win.cc",
+ "profiles/profile_shortcut_manager_win.h",
+ "shell_integration_win.cc",
+ "shell_integration_win.h",
"sync/roaming_profile_directory_deleter_win.cc",
"sync/roaming_profile_directory_deleter_win.h",
+ "task_manager/sampling/shared_sampler_win.cc",
+ "task_manager/sampling/shared_sampler_win_defines.h",
"taskbar/taskbar_decorator_win.cc",
"taskbar/taskbar_decorator_win.h",
+ "themes/theme_helper_win.cc",
+ "themes/theme_helper_win.h",
+ "upgrade_detector/get_installed_version_win.cc",
+ "win/app_icon.cc",
+ "win/app_icon.h",
+ "win/automation_controller.cc",
+ "win/automation_controller.h",
+ "win/browser_util.cc",
+ "win/browser_util.h",
+ "win/chrome_elf_init.cc",
+ "win/chrome_elf_init.h",
+ "win/chrome_select_file_dialog_factory.cc",
+ "win/chrome_select_file_dialog_factory.h",
+ "win/conflicts/enumerate_input_method_editors.cc",
+ "win/conflicts/enumerate_input_method_editors.h",
+ "win/conflicts/enumerate_shell_extensions.cc",
+ "win/conflicts/enumerate_shell_extensions.h",
+ "win/conflicts/inspection_results_cache.cc",
+ "win/conflicts/inspection_results_cache.h",
+ "win/conflicts/module_database.cc",
+ "win/conflicts/module_database.h",
+ "win/conflicts/module_database_observer.h",
+ "win/conflicts/module_event_sink_impl.cc",
+ "win/conflicts/module_event_sink_impl.h",
+ "win/conflicts/module_inspector.cc",
+ "win/conflicts/module_inspector.h",
+ "win/conflicts/third_party_metrics_recorder.cc",
+ "win/conflicts/third_party_metrics_recorder.h",
+ "win/icon_reader_service.cc",
+ "win/icon_reader_service.h",
+ "win/jumplist.cc",
+ "win/jumplist.h",
+ "win/jumplist_factory.cc",
+ "win/jumplist_factory.h",
+ "win/jumplist_file_util.cc",
+ "win/jumplist_file_util.h",
+ "win/jumplist_update_util.cc",
+ "win/jumplist_update_util.h",
+ "win/jumplist_updater.cc",
+ "win/jumplist_updater.h",
"win/parental_controls.cc",
"win/parental_controls.h",
+ "win/settings_app_monitor.cc",
+ "win/settings_app_monitor.h",
+ "win/taskbar_icon_finder.cc",
+ "win/taskbar_icon_finder.h",
+ "win/titlebar_config.cc",
+ "win/titlebar_config.h",
+ "win/ui_automation_util.cc",
+ "win/ui_automation_util.h",
"win/util_win_service.cc",
"win/util_win_service.h",
]
@@ -4075,6 +4165,7 @@ static_library("browser") {
"//chrome/chrome_elf:dll_hash",
"//chrome/common:version_header",
"//chrome/credential_provider/common:common_constants",
+ "//chrome/elevation_service:elevation_service_idl",
"//chrome/install_static:install_static_util",
"//chrome/notification_helper:constants",
"//chrome/services/util_win/public/mojom",
@@ -4088,6 +4179,7 @@ static_library("browser") {
"//third_party/wtl",
"//ui/aura_extra",
"//ui/base:fullscreen_win",
+ "//ui/base/cursor",
]
allow_circular_includes_from +=
[ "//chrome/browser/safe_browsing/chrome_cleaner" ]
@@ -4167,13 +4259,72 @@ static_library("browser") {
if (is_mac) {
allow_circular_includes_from += [ "//chrome/browser/apps/app_shim" ]
sources += [
+ "app_controller_mac.h",
+ "app_controller_mac.mm",
"apps/intent_helper/mac_apps_navigation_throttle.h",
"apps/intent_helper/mac_apps_navigation_throttle.mm",
"badging/badge_manager_delegate_mac.cc",
"badging/badge_manager_delegate_mac.h",
+ "browser_process_platform_part_mac.h",
+ "browser_process_platform_part_mac.mm",
+ "chrome_browser_application_mac.h",
+ "chrome_browser_application_mac.mm",
+ "chrome_browser_main_mac.h",
+ "chrome_browser_main_mac.mm",
+ "download/download_status_updater_mac.mm",
"download/drag_download_item_mac.mm",
+ "file_select_helper_mac.mm",
+ "first_run/first_run_internal_mac.mm",
+ "first_run/upgrade_util_mac.cc",
+ "fullscreen_mac.mm",
+ "global_keyboard_shortcuts_mac.h",
+ "global_keyboard_shortcuts_mac.mm",
+ "hang_monitor/hang_crash_dump_mac.cc",
+ "icon_loader_mac.mm",
+ "lifetime/application_lifetime_mac.mm",
+ "mac/bluetooth_utility.h",
+ "mac/bluetooth_utility.mm",
+ "mac/dock.h",
+ "mac/dock.mm",
+ "mac/exception_processor.h",
+ "mac/exception_processor.mm",
+ "mac/install_from_dmg.h",
+ "mac/install_from_dmg.mm",
+ "mac/keystone_glue.h",
+ "mac/keystone_glue.mm",
+ "mac/keystone_registration.h",
+ "mac/keystone_registration.mm",
+ "mac/mac_startup_profiler.cc",
+ "mac/mac_startup_profiler.h",
+ "mac/master_prefs.h",
+ "mac/master_prefs.mm",
+ "mac/nsprocessinfo_additions.h",
+ "mac/nsprocessinfo_additions.mm",
+ "mac/relauncher.h",
+ "mac/relauncher.mm",
+ "media/webrtc/window_icon_util_mac.mm",
"media_galleries/mac/mtp_device_delegate_impl_mac.h",
"media_galleries/mac/mtp_device_delegate_impl_mac.mm",
+ "memory_details_mac.cc",
+ "metrics/chrome_browser_main_extra_parts_metrics_mac.mm",
+ "metrics/power_metrics_provider_mac.h",
+ "metrics/power_metrics_provider_mac.mm",
+ "notifications/alert_dispatcher_mac.h",
+ "notifications/notification_platform_bridge_mac.h",
+ "notifications/notification_platform_bridge_mac.mm",
+ "obsolete_system/obsolete_system_mac.cc",
+ "password_manager/password_manager_util_mac.h",
+ "password_manager/password_manager_util_mac.mm",
+ "platform_util_mac.mm",
+ "policy/browser_dm_token_storage_mac.h",
+ "policy/browser_dm_token_storage_mac.mm",
+ "process_singleton_mac.mm",
+ "renderer_host/chrome_render_widget_host_view_mac_delegate.h",
+ "renderer_host/chrome_render_widget_host_view_mac_delegate.mm",
+ "renderer_host/chrome_render_widget_host_view_mac_history_swiper.h",
+ "renderer_host/chrome_render_widget_host_view_mac_history_swiper.mm",
+ "shell_integration_mac.mm",
+ "upgrade_detector/get_installed_version_mac.mm",
]
deps += [
"//chrome/app_shim",
@@ -4200,6 +4351,15 @@ static_library("browser") {
}
if (is_linux) {
+ sources += [
+ "chrome_browser_main_linux.cc",
+ "chrome_browser_main_linux.h",
+ "first_run/first_run_internal_linux.cc",
+ "memory_details_linux.cc",
+ "obsolete_system/obsolete_system_linux.cc",
+ "policy/browser_dm_token_storage_linux.cc",
+ "policy/browser_dm_token_storage_linux.h",
+ ]
if (use_aura) {
deps += [ "//third_party/fontconfig" ]
if (use_dbus) {
@@ -4209,14 +4369,15 @@ static_library("browser") {
if (use_x11) {
deps += [ "//ui/gfx/x" ]
}
- deps += [ "//services/service_manager/zygote" ]
+ }
+ if (is_chromeos) {
if (use_allocator == "tcmalloc") {
deps += [ "//chrome/common/performance_manager/mojom" ]
sources += [
- "performance_manager/policies/dynamic_tcmalloc_policy_linux.cc",
- "performance_manager/policies/dynamic_tcmalloc_policy_linux.h",
+ "performance_manager/policies/dynamic_tcmalloc_policy_chromeos.cc",
+ "performance_manager/policies/dynamic_tcmalloc_policy_chromeos.h",
]
}
}
@@ -4308,7 +4469,6 @@ static_library("browser") {
if (is_win || is_mac || is_desktop_linux) {
sources += [
"browser_switcher/alternative_browser_driver.h",
- "browser_switcher/alternative_browser_driver_win.cc",
"browser_switcher/browser_switcher_navigation_throttle.cc",
"browser_switcher/browser_switcher_navigation_throttle.h",
"browser_switcher/browser_switcher_prefs.cc",
@@ -4322,6 +4482,9 @@ static_library("browser") {
"browser_switcher/ieem_sitelist_parser.cc",
"browser_switcher/ieem_sitelist_parser.h",
]
+ if (is_win) {
+ sources += [ "browser_switcher/alternative_browser_driver_win.cc" ]
+ }
if (is_mac || is_desktop_linux) {
sources += [ "browser_switcher/alternative_browser_driver_posix.cc" ]
}
@@ -4354,9 +4517,6 @@ static_library("browser") {
"device_identity/device_oauth2_token_store_desktop.h",
"first_run/upgrade_util.cc",
"first_run/upgrade_util.h",
- "first_run/upgrade_util_mac.cc",
- "first_run/upgrade_util_win.cc",
- "first_run/upgrade_util_win.h",
"lifetime/switch_utils.cc",
"lifetime/switch_utils.h",
"metrics/upgrade_metrics_provider.cc",
@@ -4408,8 +4568,6 @@ static_library("browser") {
"signin/signin_global_error_factory.h",
"upgrade_detector/get_installed_version.cc",
"upgrade_detector/get_installed_version.h",
- "upgrade_detector/get_installed_version_mac.mm",
- "upgrade_detector/get_installed_version_win.cc",
"upgrade_detector/installed_version_poller.cc",
"upgrade_detector/installed_version_poller.h",
"upgrade_detector/upgrade_detector_impl.cc",
@@ -4499,28 +4657,38 @@ static_library("browser") {
if (use_x11) {
sources += [
- "chrome_browser_main_extra_parts_x11.cc",
- "chrome_browser_main_extra_parts_x11.h",
"password_manager/password_store_x.cc",
"password_manager/password_store_x.h",
]
}
+ if (use_x11 || use_ozone) {
+ sources += [
+ "chrome_browser_main_extra_parts_ozone.cc",
+ "chrome_browser_main_extra_parts_ozone.h",
+ ]
+ }
+
if (enable_background_mode) {
sources += [
"background/background_application_list_model.cc",
"background/background_application_list_model.h",
"background/background_mode_manager.cc",
"background/background_mode_manager.h",
- "background/background_mode_manager_aura.cc",
- "background/background_mode_manager_chromeos.cc",
- "background/background_mode_manager_mac.mm",
- "background/background_mode_manager_win.cc",
"background/background_mode_optimizer.cc",
"background/background_mode_optimizer.h",
]
- if (!use_aura || is_win || is_chromeos) {
- sources -= [ "background/background_mode_manager_aura.cc" ]
+ if (is_win) {
+ sources += [ "background/background_mode_manager_win.cc" ]
+ }
+ if (is_mac) {
+ sources += [ "background/background_mode_manager_mac.mm" ]
+ }
+ if (is_chromeos) {
+ sources += [ "background/background_mode_manager_chromeos.cc" ]
+ }
+ if (use_aura && !is_win && !is_chromeos) {
+ sources += [ "background/background_mode_manager_aura.cc" ]
}
}
if (enable_background_contents) {
@@ -4548,9 +4716,6 @@ static_library("browser") {
"printing/print_view_manager_common.cc",
"printing/print_view_manager_common.h",
"printing/printer_manager_dialog.h",
- "printing/printer_manager_dialog_linux.cc",
- "printing/printer_manager_dialog_mac.mm",
- "printing/printer_manager_dialog_win.cc",
"printing/printer_query.cc",
"printing/printer_query.h",
"printing/printing_init.cc",
@@ -4569,8 +4734,15 @@ static_library("browser") {
sources += [
"printing/pdf_to_emf_converter.cc",
"printing/pdf_to_emf_converter.h",
+ "printing/printer_manager_dialog_win.cc",
]
}
+ if (is_mac) {
+ sources += [ "printing/printer_manager_dialog_mac.mm" ]
+ }
+ if (is_linux) {
+ sources += [ "printing/printer_manager_dialog_linux.cc" ]
+ }
if (is_win || enable_print_preview) {
deps += [ "//chrome/services/printing/public/mojom" ]
}
@@ -4645,13 +4817,6 @@ static_library("browser") {
]
}
- if (enable_kaleidoscope) {
- deps += [
- "//chrome/browser/media/kaleidoscope/internal",
- "//chrome/browser/media/kaleidoscope/internal/mojom",
- ]
- }
-
if (enable_legacy_desktop_in_product_help) {
sources += [
"feature_engagement/bookmark/bookmark_tracker.cc",
@@ -4675,21 +4840,35 @@ static_library("browser") {
if (enable_dice_support) {
sources += [
+ "signin/dice_intercepted_session_startup_helper.cc",
+ "signin/dice_intercepted_session_startup_helper.h",
"signin/dice_response_handler.cc",
"signin/dice_response_handler.h",
+ "signin/dice_signed_in_profile_creator.cc",
+ "signin/dice_signed_in_profile_creator.h",
"signin/dice_tab_helper.cc",
"signin/dice_tab_helper.h",
"signin/dice_web_signin_interceptor.cc",
"signin/dice_web_signin_interceptor.h",
+ "signin/dice_web_signin_interceptor_delegate.cc",
+ "signin/dice_web_signin_interceptor_delegate.h",
"signin/dice_web_signin_interceptor_factory.cc",
"signin/dice_web_signin_interceptor_factory.h",
"signin/logout_tab_helper.cc",
"signin/logout_tab_helper.h",
"signin/process_dice_header_delegate_impl.cc",
"signin/process_dice_header_delegate_impl.h",
- "signin/signin_util_win.cc",
- "signin/signin_util_win.h",
+ "signin/signin_manager.cc",
+ "signin/signin_manager.h",
+ "signin/signin_manager_factory.cc",
+ "signin/signin_manager_factory.h",
]
+ if (is_win) {
+ sources += [
+ "signin/signin_util_win.cc",
+ "signin/signin_util_win.h",
+ ]
+ }
}
if (enable_extensions) {
@@ -5443,10 +5622,10 @@ static_library("browser") {
}
if (enable_supervised_users && enable_extensions) {
sources += [
+ "supervised_user/supervised_user_extensions_delegate_impl.cc",
+ "supervised_user/supervised_user_extensions_delegate_impl.h",
"supervised_user/supervised_user_extensions_metrics_recorder.cc",
"supervised_user/supervised_user_extensions_metrics_recorder.h",
- "supervised_user/supervised_user_service_management_api_delegate.cc",
- "supervised_user/supervised_user_service_management_api_delegate.h",
]
}
@@ -5459,10 +5638,6 @@ static_library("browser") {
if (is_win) {
sources += [
- "vr/consent/win_xr_consent_helper.cc",
- "vr/consent/win_xr_consent_helper.h",
- "vr/consent/xr_session_request_consent_manager_impl.cc",
- "vr/consent/xr_session_request_consent_manager_impl.h",
"vr/ui_host/vr_ui_host_impl.cc",
"vr/ui_host/vr_ui_host_impl.h",
]
@@ -5486,7 +5661,7 @@ static_library("browser") {
if (enable_wayland_server) {
deps += [
"//components/exo",
- "//components/exo/wayland",
+ "//components/exo/server",
]
sources += [
"exo_parts.cc",
@@ -5703,7 +5878,6 @@ grit("resources") {
if (is_chromeos && optimize_webui) {
deps += [
- "//chrome/browser/resources/chromeos/bluetooth_pairing_dialog:build",
"//chrome/browser/resources/chromeos/internet_config_dialog:build",
"//chrome/browser/resources/chromeos/internet_detail_dialog:build",
]
@@ -5748,6 +5922,8 @@ grit("dev_ui_browser_resources") {
"//chrome/browser/engagement:mojo_bindings_js",
"//chrome/browser/media:mojo_bindings_js",
"//chrome/browser/media/feeds:mojo_bindings_js",
+ "//chrome/browser/resources/web_app_internals:components",
+ "//chrome/browser/ui/webui/internals/web_app:mojo_bindings_js",
"//chrome/browser/ui/webui/interventions_internals:mojo_bindings_js",
]
if (is_android) {
@@ -5939,6 +6115,8 @@ static_library("test_support") {
"chooser_controller/fake_usb_chooser_controller.h",
"download/test_download_shelf.cc",
"download/test_download_shelf.h",
+ "hid/mock_hid_device_observer.cc",
+ "hid/mock_hid_device_observer.h",
"profile_resetter/profile_resetter_test_base.cc",
"profile_resetter/profile_resetter_test_base.h",
"sessions/session_restore_test_helper.cc",
@@ -5964,8 +6142,6 @@ static_library("test_support") {
"chromeos/arc/extensions/fake_arc_support.h",
"chromeos/file_manager/fake_disk_mount_manager.cc",
"chromeos/file_manager/fake_disk_mount_manager.h",
- "chromeos/input_method/mock_assistive_window_controller.cc",
- "chromeos/input_method/mock_assistive_window_controller.h",
"chromeos/input_method/mock_candidate_window_controller.cc",
"chromeos/input_method/mock_candidate_window_controller.h",
"chromeos/input_method/mock_input_method_engine.cc",
@@ -6158,12 +6334,6 @@ if (is_android) {
}
}
-proto_library("reporting_record_proto") {
- proto_in_dir = "//"
- sources = [ "policy/messaging_layer/proto/record.proto" ]
- deps = [ "//components/policy/proto:policy_record_constants" ]
-}
-
proto_library("status_proto") {
sources = [ "policy/messaging_layer/util/status.proto" ]
generate_python = false
diff --git a/chromium/chrome/browser/accessibility/accessibility_extension_api.cc b/chromium/chrome/browser/accessibility/accessibility_extension_api.cc
index 528d180500f..6782b42860e 100644
--- a/chromium/chrome/browser/accessibility/accessibility_extension_api.cc
+++ b/chromium/chrome/browser/accessibility/accessibility_extension_api.cc
@@ -58,11 +58,6 @@ namespace {
const char kErrorNotSupported[] = "This API is not supported on this platform.";
-#if defined(OS_CHROMEOS)
-constexpr int kBackButtonWidth = 45;
-constexpr int kBackButtonHeight = 45;
-#endif
-
} // namespace
ExtensionFunction::ResponseAction
@@ -420,57 +415,6 @@ AccessibilityPrivateToggleDictationFunction::Run() {
}
ExtensionFunction::ResponseAction
-AccessibilityPrivateSetSwitchAccessMenuStateFunction::Run() {
- // TODO(anastasi): Remove this function once menu refactor is complete.
- std::unique_ptr<accessibility_private::SetSwitchAccessMenuState::Params>
- params = accessibility_private::SetSwitchAccessMenuState::Params::Create(
- *args_);
- EXTENSION_FUNCTION_VALIDATE(params);
-
- chromeos::AccessibilityManager* manager =
- chromeos::AccessibilityManager::Get();
-
- if (!params->show) {
- manager->HideSwitchAccessMenu();
- return RespondNow(NoArguments());
- }
-
- accessibility_private::ScreenRect elem = std::move(params->element_bounds);
- gfx::Rect element_bounds(elem.left, elem.top, elem.width, elem.height);
- int item_count = params->item_count;
-
- // If we have an item count of 0, the panel is showing only the back button.
- if (item_count == 0) {
- manager->ShowSwitchAccessMenu(element_bounds, kBackButtonWidth,
- kBackButtonHeight,
- true /* back_button_only */);
- return RespondNow(NoArguments());
- }
-
- int padding = 40;
- int item_width = 88;
-
- 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;
-
- // The number of rows is the number of items divided by the max columns,
- // rounded down.
- int rows = 1 + (item_count - 1) / max_cols;
- int cols = rows == 1 ? item_count : max_cols;
- int width = padding + (item_width * cols);
- int height = padding + (item_height * rows);
-
- manager->ShowSwitchAccessMenu(element_bounds, width, height);
- return RespondNow(NoArguments());
-}
-
-ExtensionFunction::ResponseAction
AccessibilityPrivateForwardKeyEventsToSwitchAccessFunction::Run() {
std::unique_ptr<accessibility_private::ForwardKeyEventsToSwitchAccess::Params>
params =
diff --git a/chromium/chrome/browser/accessibility/accessibility_extension_api.h b/chromium/chrome/browser/accessibility/accessibility_extension_api.h
index 3601324682a..1ea0559c8df 100644
--- a/chromium/chrome/browser/accessibility/accessibility_extension_api.h
+++ b/chromium/chrome/browser/accessibility/accessibility_extension_api.h
@@ -109,8 +109,8 @@ class AccessibilityPrivateOnSelectToSpeakStateChangedFunction
ACCESSIBILITY_PRIVATE_ONSELECTTOSPEAKSTATECHANGED)
};
-// API function that is called when the Autoclick extension finds scrollable
-// bounds.
+// API function that is called when the Accessibility Common extension finds
+// scrollable bounds.
class AccessibilityPrivateOnScrollableBoundsForPointFoundFunction
: public ExtensionFunction {
~AccessibilityPrivateOnScrollableBoundsForPointFoundFunction() override {}
@@ -129,15 +129,6 @@ class AccessibilityPrivateToggleDictationFunction : public ExtensionFunction {
ACCESSIBILITY_PRIVATE_TOGGLEDICTATION)
};
-// API function that is called to show or hide the Switch Access menu.
-class AccessibilityPrivateSetSwitchAccessMenuStateFunction
- : public ExtensionFunction {
- ~AccessibilityPrivateSetSwitchAccessMenuStateFunction() override {}
- ResponseAction Run() override;
- DECLARE_EXTENSION_FUNCTION("accessibilityPrivate.setSwitchAccessMenuState",
- ACCESSIBILITY_PRIVATE_SETSWITCHACCESSMENUSTATE)
-};
-
// API function that requests that key events be forwarded to the Switch
// Access extension.
class AccessibilityPrivateForwardKeyEventsToSwitchAccessFunction
diff --git a/chromium/chrome/browser/accessibility/accessibility_permission_context.cc b/chromium/chrome/browser/accessibility/accessibility_permission_context.cc
index ce2689e3c5b..38fa011f4de 100644
--- a/chromium/chrome/browser/accessibility/accessibility_permission_context.cc
+++ b/chromium/chrome/browser/accessibility/accessibility_permission_context.cc
@@ -7,10 +7,9 @@
AccessibilityPermissionContext::AccessibilityPermissionContext(
content::BrowserContext* browser_context)
- : PermissionContextBase(
- browser_context,
- ContentSettingsType::ACCESSIBILITY_EVENTS,
- blink::mojom::FeaturePolicyFeature::kAccessibilityEvents) {}
+ : PermissionContextBase(browser_context,
+ ContentSettingsType::ACCESSIBILITY_EVENTS,
+ blink::mojom::FeaturePolicyFeature::kNotFound) {}
AccessibilityPermissionContext::~AccessibilityPermissionContext() = default;
diff --git a/chromium/chrome/browser/accessibility/accessibility_ui.cc b/chromium/chrome/browser/accessibility/accessibility_ui.cc
index c77a24e895d..012e421c6e7 100644
--- a/chromium/chrome/browser/accessibility/accessibility_ui.cc
+++ b/chromium/chrome/browser/accessibility/accessibility_ui.cc
@@ -13,6 +13,7 @@
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/json/json_writer.h"
+#include "base/optional.h"
#include "base/strings/pattern.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
@@ -80,6 +81,7 @@ static const char kInternal[] = "internal";
static const char kLabelImages[] = "labelImages";
static const char kNative[] = "native";
static const char kPage[] = "page";
+static const char kPDF[] = "pdf";
static const char kScreenReader[] = "screenreader";
static const char kShowOrRefreshTree[] = "showOrRefreshTree";
static const char kText[] = "text";
@@ -177,6 +179,7 @@ void HandleAccessibilityRequestCallback(
bool text = mode.has_mode(ui::AXMode::kInlineTextBoxes);
bool screenreader = mode.has_mode(ui::AXMode::kScreenReader);
bool html = mode.has_mode(ui::AXMode::kHTML);
+ bool pdf = mode.has_mode(ui::AXMode::kPDF);
// The "native" and "web" flags are disabled if
// --disable-renderer-accessibility is set.
@@ -203,6 +206,9 @@ void HandleAccessibilityRequestCallback(
? (label_images ? kOn : kOff)
: kDisabled);
+ // The "pdf" flag is independent of the others.
+ data.SetString(kPDF, pdf ? kOn : kOff);
+
bool show_internal = pref->GetBoolean(prefs::kShowInternalAccessibilityTree);
data.SetString(kInternal, show_internal ? kOn : kOff);
@@ -367,7 +373,14 @@ void AccessibilityUIObserver::AccessibilityEventReceived(
AccessibilityUIMessageHandler::AccessibilityUIMessageHandler() = default;
-AccessibilityUIMessageHandler::~AccessibilityUIMessageHandler() = default;
+AccessibilityUIMessageHandler::~AccessibilityUIMessageHandler() {
+ if (!observer_)
+ return;
+ content::WebContents* web_contents = observer_->web_contents();
+ if (!web_contents)
+ return;
+ StopRecording(web_contents);
+}
void AccessibilityUIMessageHandler::RegisterMessages() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
@@ -641,6 +654,12 @@ void AccessibilityUIMessageHandler::Callback(const std::string& str) {
event_logs_.push_back(str);
}
+void AccessibilityUIMessageHandler::StopRecording(
+ content::WebContents* web_contents) {
+ web_contents->RecordAccessibilityEvents(false, base::nullopt);
+ observer_.reset(nullptr);
+}
+
void AccessibilityUIMessageHandler::RequestAccessibilityEvents(
const base::ListValue* args) {
const base::DictionaryValue* data;
@@ -648,7 +667,7 @@ void AccessibilityUIMessageHandler::RequestAccessibilityEvents(
int process_id = *data->FindIntPath(kProcessIdField);
int routing_id = *data->FindIntPath(kRoutingIdField);
- bool start = *data->FindBoolPath(kStartField);
+ bool start_recording = *data->FindBoolPath(kStartField);
AllowJavascript();
@@ -661,22 +680,17 @@ void AccessibilityUIMessageHandler::RequestAccessibilityEvents(
std::unique_ptr<base::DictionaryValue> result(BuildTargetDescriptor(rvh));
content::WebContents* web_contents =
content::WebContents::FromRenderViewHost(rvh);
- if (start) {
+ if (start_recording) {
if (observer_) {
return;
}
web_contents->RecordAccessibilityEvents(
- base::BindRepeating(&AccessibilityUIMessageHandler::Callback,
- base::Unretained(this)),
- true);
+ true, base::BindRepeating(&AccessibilityUIMessageHandler::Callback,
+ base::Unretained(this)));
observer_ =
std::make_unique<AccessibilityUIObserver>(web_contents, &event_logs_);
} else {
- web_contents->RecordAccessibilityEvents(
- base::BindRepeating(&AccessibilityUIMessageHandler::Callback,
- base::Unretained(this)),
- false);
- observer_.release();
+ StopRecording(web_contents);
std::string event_logs_str;
for (std::string log : event_logs_) {
diff --git a/chromium/chrome/browser/accessibility/accessibility_ui.h b/chromium/chrome/browser/accessibility/accessibility_ui.h
index e7ead6ef86f..906b24117cd 100644
--- a/chromium/chrome/browser/accessibility/accessibility_ui.h
+++ b/chromium/chrome/browser/accessibility/accessibility_ui.h
@@ -21,6 +21,7 @@ class ListValue;
namespace content {
struct AXEventNotificationDetails;
+class WebContents;
} // namespace content
namespace user_prefs {
@@ -68,6 +69,7 @@ class AccessibilityUIMessageHandler : public content::WebUIMessageHandler {
void RequestNativeUITree(const base::ListValue* args);
void RequestAccessibilityEvents(const base::ListValue* args);
void Callback(const std::string&);
+ void StopRecording(content::WebContents* web_contents);
DISALLOW_COPY_AND_ASSIGN(AccessibilityUIMessageHandler);
};
diff --git a/chromium/chrome/browser/accessibility/caption_controller.cc b/chromium/chrome/browser/accessibility/caption_controller.cc
index b18fa01155d..b84de71e2af 100644
--- a/chromium/chrome/browser/accessibility/caption_controller.cc
+++ b/chromium/chrome/browser/accessibility/caption_controller.cc
@@ -53,15 +53,6 @@ void CaptionController::RegisterProfilePrefs(
registry->RegisterFilePathPref(prefs::kSODAPath, base::FilePath());
}
-// static
-void CaptionController::InitOffTheRecordPrefs(Profile* off_the_record_profile) {
- DCHECK(off_the_record_profile->IsOffTheRecord());
- off_the_record_profile->GetPrefs()->SetBoolean(prefs::kLiveCaptionEnabled,
- false);
- off_the_record_profile->GetPrefs()->SetFilePath(prefs::kSODAPath,
- base::FilePath());
-}
-
void CaptionController::Init() {
// Hidden behind a feature flag.
if (!base::FeatureList::IsEnabled(media::kLiveCaption))
@@ -107,7 +98,8 @@ void CaptionController::UpdateSpeechRecognitionServiceEnabled() {
base::BindOnce(&component_updater::SODAComponentInstallerPolicy::
UpdateSODAComponentOnDemand));
} else {
- // TODO(evliu): Unregister SODA component.
+ // Do nothing. The SODA component will be uninstalled and removed from the
+ // device on the next start up.
}
}
@@ -147,32 +139,42 @@ void CaptionController::UpdateAccessibilityCaptionHistograms() {
}
void CaptionController::OnBrowserAdded(Browser* browser) {
- if (browser->profile() != profile_)
+ if (browser->profile() != profile_ &&
+ browser->profile()->GetOriginalProfile() != profile_) {
return;
+ }
+ DCHECK(!caption_bubble_controllers_.count(browser));
caption_bubble_controllers_[browser] =
CaptionBubbleController::Create(browser);
caption_bubble_controllers_[browser]->UpdateCaptionStyle(caption_style_);
}
void CaptionController::OnBrowserRemoved(Browser* browser) {
- if (browser->profile() != profile_)
+ if (browser->profile() != profile_ &&
+ browser->profile()->GetOriginalProfile() != profile_) {
return;
+ }
DCHECK(caption_bubble_controllers_.count(browser));
caption_bubble_controllers_.erase(browser);
}
-void CaptionController::DispatchTranscription(
+bool CaptionController::DispatchTranscription(
content::WebContents* web_contents,
const chrome::mojom::TranscriptionResultPtr& transcription_result) {
Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
- if (!browser)
- return;
- if (!caption_bubble_controllers_.count(browser))
- return;
- caption_bubble_controllers_[browser]->OnTranscription(transcription_result,
- web_contents);
+ if (!browser || !caption_bubble_controllers_.count(browser))
+ return false;
+ return caption_bubble_controllers_[browser]->OnTranscription(
+ transcription_result, web_contents);
+}
+
+CaptionBubbleController*
+CaptionController::GetCaptionBubbleControllerForBrowser(Browser* browser) {
+ if (!browser || !caption_bubble_controllers_.count(browser))
+ return nullptr;
+ return caption_bubble_controllers_[browser].get();
}
void CaptionController::UpdateCaptionStyle() {
diff --git a/chromium/chrome/browser/accessibility/caption_controller.h b/chromium/chrome/browser/accessibility/caption_controller.h
index 78e3ee77cdf..274b46ab8bf 100644
--- a/chromium/chrome/browser/accessibility/caption_controller.h
+++ b/chromium/chrome/browser/accessibility/caption_controller.h
@@ -62,19 +62,21 @@ class CaptionController : public BrowserListObserver, public KeyedService {
static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
- // Off the record profiles will default to having the feature disabled.
- static void InitOffTheRecordPrefs(Profile* off_the_record_profile);
-
void Init();
// Routes a transcription to the CaptionBubbleController that belongs to the
- // appropriate browser.
- void DispatchTranscription(
+ // appropriate browser. Returns whether the transcription result was routed
+ // successfully. Transcriptions will halt if this returns false.
+ bool DispatchTranscription(
content::WebContents* web_contents,
const chrome::mojom::TranscriptionResultPtr& transcription_result);
+ CaptionBubbleController* GetCaptionBubbleControllerForBrowser(
+ Browser* browser);
+
private:
friend class CaptionControllerFactory;
+ friend class CaptionControllerTest;
// BrowserListObserver:
void OnBrowserAdded(Browser* browser) override;
diff --git a/chromium/chrome/browser/accessibility/caption_controller_browsertest.cc b/chromium/chrome/browser/accessibility/caption_controller_browsertest.cc
new file mode 100644
index 00000000000..5b46895bc04
--- /dev/null
+++ b/chromium/chrome/browser/accessibility/caption_controller_browsertest.cc
@@ -0,0 +1,579 @@
+// Copyright 2020 The Chromium 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_controller.h"
+
+#include "base/files/file_path.h"
+#include "build/build_config.h"
+#include "chrome/browser/accessibility/caption_controller_factory.h"
+#include "chrome/browser/browser_process.h"
+#include "chrome/browser/lifetime/application_lifetime.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/profiles/profile_manager.h"
+#include "chrome/browser/profiles/profile_window.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/browser_window.h"
+#include "chrome/browser/ui/caption_bubble_controller.h"
+#include "chrome/common/pref_names.h"
+#include "chrome/test/base/in_process_browser_test.h"
+#include "chrome/test/base/ui_test_utils.h"
+#include "components/sync_preferences/pref_service_syncable.h"
+#include "content/public/test/browser_test.h"
+#include "media/base/media_switches.h"
+
+namespace captions {
+
+// Blocks until a new profile is created.
+void UnblockOnProfileCreation(base::RunLoop* run_loop,
+ Profile* profile,
+ Profile::CreateStatus status) {
+ if (status == Profile::CREATE_STATUS_INITIALIZED)
+ run_loop->Quit();
+}
+
+Profile* CreateProfile() {
+ ProfileManager* profile_manager = g_browser_process->profile_manager();
+ base::FilePath profile_path =
+ profile_manager->GenerateNextProfileDirectoryPath();
+ base::RunLoop run_loop;
+ profile_manager->CreateProfileAsync(
+ profile_path, base::Bind(&UnblockOnProfileCreation, &run_loop),
+ base::string16(), std::string());
+ run_loop.Run();
+ return profile_manager->GetProfileByPath(profile_path);
+}
+
+class CaptionControllerTest : public InProcessBrowserTest {
+ public:
+ CaptionControllerTest() = default;
+ ~CaptionControllerTest() override = default;
+ CaptionControllerTest(const CaptionControllerTest&) = delete;
+ CaptionControllerTest& operator=(const CaptionControllerTest&) = delete;
+
+ // InProcessBrowserTest overrides:
+ void SetUp() override {
+ scoped_feature_list_.InitAndEnableFeature(media::kLiveCaption);
+ InProcessBrowserTest::SetUp();
+ }
+
+ void SetLiveCaptionEnabled(bool enabled) {
+ browser()->profile()->GetPrefs()->SetBoolean(prefs::kLiveCaptionEnabled,
+ enabled);
+ }
+
+ CaptionController* GetController() {
+ return GetControllerForBrowser(browser());
+ }
+
+ CaptionController* GetControllerForBrowser(Browser* browser) {
+ return GetControllerForProfile(browser->profile());
+ }
+
+ CaptionController* GetControllerForProfile(Profile* profile) {
+ return CaptionControllerFactory::GetForProfile(profile);
+ }
+
+ CaptionBubbleController* GetBubbleController() {
+ return GetBubbleControllerForBrowser(browser());
+ }
+
+ CaptionBubbleController* GetBubbleControllerForBrowser(Browser* browser) {
+ return GetControllerForBrowser(browser)
+ ->GetCaptionBubbleControllerForBrowser(browser);
+ }
+
+ bool DispatchTranscription(std::string text) {
+ return DispatchTranscriptionToBrowser(text, browser());
+ }
+
+ bool DispatchTranscriptionToBrowser(std::string text, Browser* browser) {
+ return DispatchTranscriptionToBrowserForProfile(text, browser,
+ browser->profile());
+ }
+
+ bool DispatchTranscriptionToBrowserForProfile(std::string text,
+ Browser* browser,
+ Profile* profile) {
+ return GetControllerForProfile(profile)->DispatchTranscription(
+ browser->tab_strip_model()->GetActiveWebContents(),
+ chrome::mojom::TranscriptionResult::New(text, true /* is_final */));
+ }
+
+ int NumBubbleControllers() {
+ return NumBubbleControllersForProfile(browser()->profile());
+ }
+
+ int NumBubbleControllersForProfile(Profile* profile) {
+ return GetControllerForProfile(profile)->caption_bubble_controllers_.size();
+ }
+
+ bool IsWidgetVisible() { return IsWidgetVisibleOnBrowser(browser()); }
+
+ bool IsWidgetVisibleOnBrowser(Browser* browser) {
+ return GetBubbleControllerForBrowser(browser)->IsWidgetVisibleForTesting();
+ }
+
+ std::string GetBubbleLabelText() {
+ return GetBubbleLabelTextOnBrowser(browser());
+ }
+
+ std::string GetBubbleLabelTextOnBrowser(Browser* browser) {
+ return GetBubbleControllerForBrowser(browser)
+ ->GetBubbleLabelTextForTesting();
+ }
+
+ private:
+ base::test::ScopedFeatureList scoped_feature_list_;
+};
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest, ProfilePrefsAreRegistered) {
+ EXPECT_FALSE(
+ browser()->profile()->GetPrefs()->GetBoolean(prefs::kLiveCaptionEnabled));
+ EXPECT_EQ(base::FilePath(),
+ browser()->profile()->GetPrefs()->GetFilePath(prefs::kSODAPath));
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest,
+ ProfilePrefsAreRegistered_Incognito) {
+ // Set live caption enabled on the regular profile.
+ SetLiveCaptionEnabled(true);
+ EXPECT_TRUE(
+ browser()->profile()->GetPrefs()->GetBoolean(prefs::kLiveCaptionEnabled));
+ EXPECT_EQ(base::FilePath(),
+ browser()->profile()->GetPrefs()->GetFilePath(prefs::kSODAPath));
+
+ // Ensure that live caption is also enabled in the incognito profile.
+ Profile* incognito_profile = browser()->profile()->GetPrimaryOTRProfile();
+ EXPECT_TRUE(
+ incognito_profile->GetPrefs()->GetBoolean(prefs::kLiveCaptionEnabled));
+ EXPECT_EQ(base::FilePath(),
+ browser()->profile()->GetPrefs()->GetFilePath(prefs::kSODAPath));
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest, LiveCaptionEnabledChanged) {
+ EXPECT_EQ(nullptr, GetBubbleController());
+ EXPECT_EQ(0, NumBubbleControllers());
+
+ SetLiveCaptionEnabled(true);
+ EXPECT_NE(nullptr, GetBubbleController());
+ EXPECT_EQ(1, NumBubbleControllers());
+
+ SetLiveCaptionEnabled(false);
+ EXPECT_EQ(nullptr, GetBubbleController());
+ EXPECT_EQ(0, NumBubbleControllers());
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest,
+ LiveCaptionEnabledChanged_BubbleVisible) {
+ SetLiveCaptionEnabled(true);
+ // Make the bubble visible by dispatching a transcription.
+ DispatchTranscription(
+ "In Switzerland it is illegal to own just one guinea pig.");
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisible());
+#else
+ EXPECT_FALSE(IsWidgetVisible());
+#endif
+
+ SetLiveCaptionEnabled(false);
+ EXPECT_EQ(nullptr, GetBubbleController());
+ EXPECT_EQ(0, NumBubbleControllers());
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest, OnBrowserAdded) {
+ EXPECT_EQ(0, NumBubbleControllers());
+
+ // Add a new browser and then enable live caption. Test that a caption bubble
+ // controller is created.
+ CreateBrowser(browser()->profile());
+ SetLiveCaptionEnabled(true);
+ EXPECT_EQ(2, NumBubbleControllers());
+
+ // Add a new browser and test that a caption bubble controller is created.
+ CreateBrowser(browser()->profile());
+ EXPECT_EQ(3, NumBubbleControllers());
+
+ // Disable live caption. Add a new browser and test that a caption bubble
+ // controller is not created.
+ SetLiveCaptionEnabled(false);
+ CreateBrowser(browser()->profile());
+ EXPECT_EQ(0, NumBubbleControllers());
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest, OnBrowserAdded_Incognito) {
+ EXPECT_EQ(0, NumBubbleControllers());
+
+ // Add a new incognito browser and then enable live caption. Test that a
+ // caption bubble controller is created in each browser (incognito and
+ // regular).
+ CreateIncognitoBrowser();
+ SetLiveCaptionEnabled(true);
+ EXPECT_EQ(2, NumBubbleControllers());
+
+ // Add a new incognito browser and test that a caption bubble controller is
+ // created.
+ CreateIncognitoBrowser();
+ EXPECT_EQ(3, NumBubbleControllers());
+
+ // Disable live caption. Add a new incognito browser and test that a caption
+ // bubble controller is not created.
+ SetLiveCaptionEnabled(false);
+ CreateIncognitoBrowser();
+ EXPECT_EQ(0, NumBubbleControllers());
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest, OnBrowserRemoved) {
+ CaptionController* controller = GetController();
+ Browser* browser1 = browser();
+ // Add 3 browsers.
+ Browser* browser2 = CreateBrowser(browser()->profile());
+ Browser* browser3 = CreateBrowser(browser()->profile());
+ Browser* browser4 = CreateBrowser(browser()->profile());
+
+ SetLiveCaptionEnabled(true);
+ EXPECT_EQ(4, NumBubbleControllers());
+
+ // Close browser4 and test that the caption bubble controller was destroyed.
+ browser4->window()->Close();
+ ui_test_utils::WaitForBrowserToClose();
+ EXPECT_EQ(nullptr,
+ controller->GetCaptionBubbleControllerForBrowser(browser4));
+ EXPECT_EQ(3, NumBubbleControllers());
+
+ // Make the bubble on browser3 visible by dispatching a transcription.
+ DispatchTranscriptionToBrowser(
+ "If you lift a kangaroo's tail off the ground it can't hop.", browser3);
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser3));
+#else
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(browser3));
+#endif
+ browser3->window()->Close();
+ ui_test_utils::WaitForBrowserToClose();
+ EXPECT_EQ(nullptr,
+ controller->GetCaptionBubbleControllerForBrowser(browser3));
+ EXPECT_EQ(2, NumBubbleControllers());
+
+ // Make the bubble on browser2 visible by dispatching a transcription.
+ DispatchTranscriptionToBrowser(
+ "A lion's roar can be heard from 5 miles away.", browser2);
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser2));
+#else
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(browser2));
+#endif
+
+ // Close all browsers and verify that the caption bubbles are destroyed on
+ // the two remaining browsers.
+ chrome::CloseAllBrowsers();
+ ui_test_utils::WaitForBrowserToClose();
+ ui_test_utils::WaitForBrowserToClose();
+ EXPECT_EQ(nullptr,
+ controller->GetCaptionBubbleControllerForBrowser(browser2));
+ EXPECT_EQ(nullptr,
+ controller->GetCaptionBubbleControllerForBrowser(browser1));
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest, OnBrowserRemoved_Incognito) {
+ CaptionController* controller = GetController();
+ Browser* incognito_browser1 = CreateIncognitoBrowser();
+ Browser* incognito_browser2 = CreateIncognitoBrowser();
+
+ SetLiveCaptionEnabled(true);
+ // There is 1 regular browser and 2 incognito browsers.
+ EXPECT_EQ(3, NumBubbleControllers());
+
+ // Close incognito_browser2 and test that the caption bubble controller was
+ // destroyed.
+ incognito_browser2->window()->Close();
+ ui_test_utils::WaitForBrowserToClose();
+ EXPECT_EQ(nullptr, controller->GetCaptionBubbleControllerForBrowser(
+ incognito_browser2));
+ EXPECT_EQ(2, NumBubbleControllers());
+
+ // Make the bubble on incognito_browser1 visible by dispatching a
+ // transcription.
+ DispatchTranscriptionToBrowser(
+ "If you lift a kangaroo's tail off the ground it can't hop.",
+ incognito_browser1);
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(incognito_browser1));
+#else
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(incognito_browser1));
+#endif
+ incognito_browser1->window()->Close();
+ ui_test_utils::WaitForBrowserToClose();
+ EXPECT_EQ(nullptr, controller->GetCaptionBubbleControllerForBrowser(
+ incognito_browser1));
+ EXPECT_EQ(1, NumBubbleControllers());
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest, DispatchTranscription) {
+ bool success = DispatchTranscription("A baby spider is called a spiderling.");
+ EXPECT_FALSE(success);
+ EXPECT_EQ(0, NumBubbleControllers());
+
+ SetLiveCaptionEnabled(true);
+ success = DispatchTranscription(
+ "A baby octopus is about the size of a flea when it is born.");
+ EXPECT_TRUE(success);
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisible());
+ EXPECT_EQ("A baby octopus is about the size of a flea when it is born.",
+ GetBubbleLabelText());
+#else
+ EXPECT_FALSE(IsWidgetVisible());
+#endif
+
+ SetLiveCaptionEnabled(false);
+ success = DispatchTranscription(
+ "Approximately 10-20% of power outages in the US are caused by "
+ "squirrels.");
+ EXPECT_FALSE(success);
+ EXPECT_EQ(0, NumBubbleControllers());
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest,
+ DispatchTranscription_MultipleBrowsers) {
+ Browser* browser1 = browser();
+ Browser* browser2 = CreateBrowser(browser()->profile());
+ Browser* incognito_browser = CreateIncognitoBrowser();
+ SetLiveCaptionEnabled(true);
+
+ // Dispatch transcription routes the transcription to the right browser.
+ bool success = DispatchTranscriptionToBrowser(
+ "Honeybees can recognize human faces.", browser1);
+ EXPECT_TRUE(success);
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser1));
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(browser2));
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(incognito_browser));
+ EXPECT_EQ("Honeybees can recognize human faces.",
+ GetBubbleLabelTextOnBrowser(browser1));
+ EXPECT_EQ("", GetBubbleLabelTextOnBrowser(browser2));
+ EXPECT_EQ("", GetBubbleLabelTextOnBrowser(incognito_browser));
+#else
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(browser1));
+#endif
+
+ success = DispatchTranscriptionToBrowser(
+ "A blue whale's heart is the size of a small car.", browser2);
+ EXPECT_TRUE(success);
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser1));
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser2));
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(incognito_browser));
+ EXPECT_EQ("A blue whale's heart is the size of a small car.",
+ GetBubbleLabelTextOnBrowser(browser2));
+ EXPECT_EQ("Honeybees can recognize human faces.",
+ GetBubbleLabelTextOnBrowser(browser1));
+ EXPECT_EQ("", GetBubbleLabelTextOnBrowser(incognito_browser));
+#else
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(browser2));
+#endif
+
+ success = DispatchTranscriptionToBrowser(
+ "Squirrels forget where they hide about half of their nuts.",
+ incognito_browser);
+ EXPECT_TRUE(success);
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser1));
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser2));
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(incognito_browser));
+ EXPECT_EQ("A blue whale's heart is the size of a small car.",
+ GetBubbleLabelTextOnBrowser(browser2));
+ EXPECT_EQ("Honeybees can recognize human faces.",
+ GetBubbleLabelTextOnBrowser(browser1));
+ EXPECT_EQ("Squirrels forget where they hide about half of their nuts.",
+ GetBubbleLabelTextOnBrowser(incognito_browser));
+#else
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(incognito_browser));
+#endif
+}
+
+#if !defined(OS_CHROMEOS) // No multi-profile on ChromeOS.
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest,
+ LiveCaptionEnabledChanged_MultipleProfiles) {
+ Profile* profile1 = browser()->profile();
+ Profile* profile2 = CreateProfile();
+ CreateBrowser(profile2);
+
+ // The profiles start with no caption bubble controllers.
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile2));
+
+ // Enable live caption on profile1.
+ SetLiveCaptionEnabled(true);
+ EXPECT_EQ(1, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile2));
+
+ // Enable live caption on profile2.
+ profile2->GetPrefs()->SetBoolean(prefs::kLiveCaptionEnabled, true);
+ EXPECT_EQ(1, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(1, NumBubbleControllersForProfile(profile2));
+
+ // Disable live caption on profile1.
+ SetLiveCaptionEnabled(false);
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(1, NumBubbleControllersForProfile(profile2));
+
+ // Disable live caption on profile2.
+ profile2->GetPrefs()->SetBoolean(prefs::kLiveCaptionEnabled, false);
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile2));
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest, OnBrowserAdded_MultipleProfiles) {
+ Profile* profile1 = browser()->profile();
+ Profile* profile2 = CreateProfile();
+
+ // Enable live caption on both profiles.
+ SetLiveCaptionEnabled(true);
+ profile2->GetPrefs()->SetBoolean(prefs::kLiveCaptionEnabled, true);
+
+ // Add a new browser to profile1. Test that there are caption bubble
+ // controllers on all of the existing browsers.
+ CreateBrowser(profile1);
+ EXPECT_EQ(2, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile2));
+
+ // Add a new browser to profile 2. Test that a caption bubble controller is
+ // created in profile2 and not in profile1.
+ Browser* profile2_browser2 = CreateBrowser(profile2);
+ EXPECT_NE(
+ nullptr,
+ GetControllerForProfile(profile2)->GetCaptionBubbleControllerForBrowser(
+ profile2_browser2));
+ EXPECT_EQ(
+ nullptr,
+ GetControllerForProfile(profile1)->GetCaptionBubbleControllerForBrowser(
+ profile2_browser2));
+ EXPECT_EQ(2, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(1, NumBubbleControllersForProfile(profile2));
+
+ // Disable live caption on profile1. Add a new browser to both profiles, and
+ // test that a caption bubble controller is only created on profile2.
+ SetLiveCaptionEnabled(false);
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(1, NumBubbleControllersForProfile(profile2));
+ CreateBrowser(profile1);
+ CreateBrowser(profile2);
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(2, NumBubbleControllersForProfile(profile2));
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest,
+ OnBrowserRemoved_MultipleProfiles) {
+ Profile* profile1 = browser()->profile();
+ Profile* profile2 = CreateProfile();
+ Browser* browser1 = browser();
+ Browser* browser2 = CreateBrowser(profile2);
+ CaptionController* controller1 = GetControllerForProfile(profile1);
+ CaptionController* controller2 = GetControllerForProfile(profile2);
+
+ // Enable live caption on both profiles.
+ SetLiveCaptionEnabled(true);
+ profile2->GetPrefs()->SetBoolean(prefs::kLiveCaptionEnabled, true);
+ EXPECT_EQ(1, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(1, NumBubbleControllersForProfile(profile2));
+
+ // Close browser2 and test that the caption bubble controller was destroyed.
+ browser2->window()->Close();
+ ui_test_utils::WaitForBrowserToClose();
+ EXPECT_EQ(nullptr,
+ controller2->GetCaptionBubbleControllerForBrowser(browser2));
+ EXPECT_EQ(1, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile2));
+
+ // Make the bubble on incognito_browser1 visible by dispatching a
+ // transcription.
+ DispatchTranscriptionToBrowser(
+ "If you lift a kangaroo's tail off the ground it can't hop.", browser1);
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser1));
+#else
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(browser1));
+#endif
+ browser1->window()->Close();
+ ui_test_utils::WaitForBrowserToClose();
+ EXPECT_EQ(nullptr,
+ controller1->GetCaptionBubbleControllerForBrowser(browser1));
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile1));
+ EXPECT_EQ(0, NumBubbleControllersForProfile(profile2));
+}
+
+IN_PROC_BROWSER_TEST_F(CaptionControllerTest,
+ DispatchTranscription_MultipleProfiles) {
+ Profile* profile1 = browser()->profile();
+ Profile* profile2 = CreateProfile();
+ Browser* browser1 = browser();
+ Browser* browser2 = CreateBrowser(profile2);
+
+ // Enable live caption on both profiles.
+ SetLiveCaptionEnabled(true);
+ profile2->GetPrefs()->SetBoolean(prefs::kLiveCaptionEnabled, true);
+
+ // Dispatch transcription routes the transcription to the right browser on the
+ // right profile.
+ bool success = DispatchTranscriptionToBrowserForProfile(
+ "Only female mosquitos bite.", browser1, profile1);
+ EXPECT_TRUE(success);
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser1));
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(browser2));
+ EXPECT_EQ("Only female mosquitos bite.",
+ GetBubbleLabelTextOnBrowser(browser1));
+ EXPECT_EQ("", GetBubbleLabelTextOnBrowser(browser2));
+#else
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(browser1));
+#endif
+
+ success = DispatchTranscriptionToBrowserForProfile(
+ "Mosquitos were around at the time of the dinosaurs.", browser2,
+ profile2);
+ EXPECT_TRUE(success);
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser1));
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser2));
+ EXPECT_EQ("Only female mosquitos bite.",
+ GetBubbleLabelTextOnBrowser(browser1));
+ EXPECT_EQ("Mosquitos were around at the time of the dinosaurs.",
+ GetBubbleLabelTextOnBrowser(browser2));
+#else
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(browser1));
+#endif
+
+ // Dispatch transcription returns false for browsers on different profiles.
+ success = DispatchTranscriptionToBrowserForProfile(
+ "There are over 3000 species of mosquitos.", browser1, profile2);
+ EXPECT_FALSE(success);
+// The CaptionBubbleController is currently only implemented in Views.
+#if defined(TOOLKIT_VIEWS)
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser1));
+ EXPECT_TRUE(IsWidgetVisibleOnBrowser(browser2));
+ EXPECT_EQ("Only female mosquitos bite.",
+ GetBubbleLabelTextOnBrowser(browser1));
+ EXPECT_EQ("Mosquitos were around at the time of the dinosaurs.",
+ GetBubbleLabelTextOnBrowser(browser2));
+#else
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(browser1));
+ EXPECT_FALSE(IsWidgetVisibleOnBrowser(browser2));
+#endif
+}
+
+#endif // !defined (OS_CHROMEOS)
+
+} // namespace captions
diff --git a/chromium/chrome/browser/accessibility/caption_host_impl.cc b/chromium/chrome/browser/accessibility/caption_host_impl.cc
index f16d93d566a..deaa6ec6554 100644
--- a/chromium/chrome/browser/accessibility/caption_host_impl.cc
+++ b/chromium/chrome/browser/accessibility/caption_host_impl.cc
@@ -40,21 +40,28 @@ CaptionHostImpl::CaptionHostImpl(content::RenderFrameHost* frame_host)
CaptionHostImpl::~CaptionHostImpl() = default;
void CaptionHostImpl::OnTranscription(
- chrome::mojom::TranscriptionResultPtr transcription_result) {
- if (!frame_host_)
+ chrome::mojom::TranscriptionResultPtr transcription_result,
+ OnTranscriptionCallback reply) {
+ if (!frame_host_) {
+ std::move(reply).Run(false);
return;
+ }
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(frame_host_);
if (!web_contents) {
frame_host_ = nullptr;
+ std::move(reply).Run(false);
return;
}
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
- if (!profile)
+ if (!profile) {
+ std::move(reply).Run(false);
return;
- CaptionControllerFactory::GetForProfile(profile)->DispatchTranscription(
- web_contents, transcription_result);
+ }
+ std::move(reply).Run(
+ CaptionControllerFactory::GetForProfile(profile)->DispatchTranscription(
+ web_contents, transcription_result));
}
void CaptionHostImpl::RenderFrameDeleted(content::RenderFrameHost* frame_host) {
diff --git a/chromium/chrome/browser/accessibility/caption_host_impl.h b/chromium/chrome/browser/accessibility/caption_host_impl.h
index 0445179620f..3e3615e6c2d 100644
--- a/chromium/chrome/browser/accessibility/caption_host_impl.h
+++ b/chromium/chrome/browser/accessibility/caption_host_impl.h
@@ -38,7 +38,8 @@ class CaptionHostImpl : public chrome::mojom::CaptionHost,
// chrome::mojom::CaptionHost:
void OnTranscription(
- chrome::mojom::TranscriptionResultPtr transcription_result) override;
+ chrome::mojom::TranscriptionResultPtr transcription_result,
+ OnTranscriptionCallback reply) override;
// content::WebContentsObserver:
void RenderFrameDeleted(content::RenderFrameHost* frame_host) override;
diff --git a/chromium/chrome/browser/accessibility/image_annotation_browsertest.cc b/chromium/chrome/browser/accessibility/image_annotation_browsertest.cc
index e979f31f2e4..70fbc9c17e3 100644
--- a/chromium/chrome/browser/accessibility/image_annotation_browsertest.cc
+++ b/chromium/chrome/browser/accessibility/image_annotation_browsertest.cc
@@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include <map>
+
#include "base/bind_helpers.h"
#include "base/check.h"
#include "base/feature_list.h"
@@ -34,13 +36,14 @@
#include "services/image_annotation/public/mojom/image_annotation.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "ui/accessibility/accessibility_features.h"
#include "ui/accessibility/ax_enum_util.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_tree.h"
#include "url/gurl.h"
constexpr base::FilePath::CharType kDocRoot[] =
- FILE_PATH_LITERAL("chrome/test/data/accessibility");
+ FILE_PATH_LITERAL("chrome/test/data");
namespace {
@@ -49,8 +52,13 @@ void DescribeNodesWithAnnotations(const ui::AXNode& node,
std::string annotation =
node.GetStringAttribute(ax::mojom::StringAttribute::kImageAnnotation);
if (!annotation.empty()) {
- descriptions->push_back(ui::ToString(node.data().role) + std::string(" ") +
- annotation);
+ std::string role_str = ui::ToString(node.data().role);
+ std::string name =
+ node.GetStringAttribute(ax::mojom::StringAttribute::kName);
+ if (!name.empty() && node.data().role != ax::mojom::Role::kRootWebArea)
+ descriptions->push_back(role_str + " " + name + " " + annotation);
+ else
+ descriptions->push_back(role_str + " " + annotation);
}
for (const auto* child : node.children())
DescribeNodesWithAnnotations(*child, descriptions);
@@ -58,10 +66,11 @@ void DescribeNodesWithAnnotations(const ui::AXNode& node,
std::vector<std::string> DescribeNodesWithAnnotations(
const ui::AXTreeUpdate& tree_update) {
- ui::AXTree tree(tree_update);
std::vector<std::string> descriptions;
- DCHECK(tree.root());
- DescribeNodesWithAnnotations(*tree.root(), &descriptions);
+ if (tree_update.root_id) {
+ ui::AXTree tree(tree_update);
+ DescribeNodesWithAnnotations(*tree.root(), &descriptions);
+ }
return descriptions;
}
@@ -87,6 +96,11 @@ class FakeAnnotator : public image_annotation::mojom::Annotator {
return_label_results_ = label;
}
+ static void AddCustomLabelResultMapping(const std::string& filename,
+ const std::string& label) {
+ custom_label_result_mapping_[filename] = label;
+ }
+
static void SetReturnErrorCode(
image_annotation::mojom::AnnotateImageError error_code) {
return_error_code_ = error_code;
@@ -114,19 +128,25 @@ class FakeAnnotator : public image_annotation::mojom::Annotator {
return;
}
- // Use the filename to create an annotation string.
- // Adds some trailing whitespace and punctuation to check that clean-up
- // happens correctly when combining annotation strings.
+ // Use the filename to create annotation strings. Check a map from filename
+ // to desired label, otherwise just construct a string based on the
+ // filename. Adds some trailing whitespace and punctuation to check that
+ // clean-up happens correctly when combining annotation strings.
std::string image_filename = GURL(image_id).ExtractFileName();
+ std::string label_text;
+ if (base::Contains(custom_label_result_mapping_, image_filename)) {
+ label_text = custom_label_result_mapping_[image_filename];
+ } else {
+ label_text = image_filename + " '" + description_language_tag + "' Label";
+ }
+ std::string ocr_text = image_filename + " Annotation . ";
+
image_annotation::mojom::AnnotationPtr ocr_annotation =
image_annotation::mojom::Annotation::New(
- image_annotation::mojom::AnnotationType::kOcr, 1.0,
- image_filename + " Annotation . ");
-
+ image_annotation::mojom::AnnotationType::kOcr, 1.0, ocr_text);
image_annotation::mojom::AnnotationPtr label_annotation =
image_annotation::mojom::Annotation::New(
- image_annotation::mojom::AnnotationType::kLabel, 1.0,
- image_filename + " '" + description_language_tag + "' Label");
+ image_annotation::mojom::AnnotationType::kLabel, 1.0, label_text);
// Return enabled results as an annotation.
std::vector<image_annotation::mojom::AnnotationPtr> annotations;
@@ -145,6 +165,7 @@ class FakeAnnotator : public image_annotation::mojom::Annotator {
mojo::ReceiverSet<image_annotation::mojom::Annotator> receivers_;
static bool return_ocr_results_;
static bool return_label_results_;
+ static std::map<std::string, std::string> custom_label_result_mapping_;
static base::Optional<image_annotation::mojom::AnnotateImageError>
return_error_code_;
@@ -156,6 +177,8 @@ bool FakeAnnotator::return_ocr_results_ = false;
// static
bool FakeAnnotator::return_label_results_ = false;
// static
+std::map<std::string, std::string> FakeAnnotator::custom_label_result_mapping_;
+// static
base::Optional<image_annotation::mojom::AnnotateImageError>
FakeAnnotator::return_error_code_;
@@ -197,8 +220,10 @@ class ImageAnnotationBrowserTest : public InProcessBrowserTest {
protected:
void SetUp() override {
- scoped_feature_list_.InitAndEnableFeature(
- features::kExperimentalAccessibilityLabels);
+ scoped_feature_list_.InitWithFeatures(
+ std::vector<base::Feature>({features::kExperimentalAccessibilityLabels,
+ features::kAugmentExistingImageLabels}),
+ std::vector<base::Feature>({}));
InProcessBrowserTest::SetUp();
}
@@ -252,8 +277,8 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest,
AnnotateImageInAccessibilityTree) {
FakeAnnotator::SetReturnOcrResults(true);
FakeAnnotator::SetReturnLabelResults(true);
- ui_test_utils::NavigateToURL(browser(),
- https_server_.GetURL("/image_annotation.html"));
+ ui_test_utils::NavigateToURL(
+ browser(), https_server_.GetURL("/accessibility/image_annotation.html"));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
@@ -266,7 +291,8 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest,
IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, ImagesInLinks) {
FakeAnnotator::SetReturnOcrResults(true);
ui_test_utils::NavigateToURL(
- browser(), https_server_.GetURL("/image_annotation_link.html"));
+ browser(),
+ https_server_.GetURL("/accessibility/image_annotation_link.html"));
// Block until the accessibility tree has at least 8 annotations. If
// that never happens, the test will time out.
@@ -296,10 +322,71 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, ImagesInLinks) {
"image Appears to say: green.png Annotation"));
}
+IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, AugmentImageNames) {
+ FakeAnnotator::SetReturnLabelResults(true);
+ FakeAnnotator::AddCustomLabelResultMapping("frog.jpg", "Tadpole");
+ FakeAnnotator::AddCustomLabelResultMapping("train.png", "Locomotive");
+ FakeAnnotator::AddCustomLabelResultMapping("cloud.png", "Cumulonimbus");
+ FakeAnnotator::AddCustomLabelResultMapping("goat.jpg", "Billy goat");
+ FakeAnnotator::AddCustomLabelResultMapping("dog.jpg", "Puppy");
+
+ ui_test_utils::NavigateToURL(
+ browser(),
+ https_server_.GetURL("/accessibility/image_annotation_augment.html"));
+
+ // Block until the accessibility tree has at least 5 annotations. If
+ // that never happens, the test will time out.
+ content::WebContents* web_contents =
+ browser()->tab_strip_model()->GetActiveWebContents();
+ while (5 > DescribeNodesWithAnnotations(
+ content::GetAccessibilityTreeSnapshot(web_contents))
+ .size()) {
+ content::WaitForAccessibilityTreeToChange(web_contents);
+ }
+
+ ui::AXTreeUpdate ax_tree_update =
+ content::GetAccessibilityTreeSnapshot(web_contents);
+ EXPECT_THAT(DescribeNodesWithAnnotations(ax_tree_update),
+ testing::ElementsAre(
+ "image the Appears to be: Tadpole",
+ "image photo background Appears to be: Locomotive",
+ "image 12345678.jpg Appears to be: Cumulonimbus",
+ "image Sunday, Feb 6, 1966 Appears to be: Billy goat",
+ "image fotografia bianca e nero Appears to be: Puppy"));
+}
+
+IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, AugmentImageNamesInLinks) {
+ FakeAnnotator::SetReturnLabelResults(true);
+ FakeAnnotator::AddCustomLabelResultMapping("frog.jpg", "Tadpole");
+ FakeAnnotator::AddCustomLabelResultMapping("train.png", "Locomotive");
+
+ ui_test_utils::NavigateToURL(
+ browser(), https_server_.GetURL(
+ "/accessibility/image_annotation_augment_links.html"));
+
+ // Block until the accessibility tree has at least 3 annotations. If
+ // that never happens, the test will time out.
+ content::WebContents* web_contents =
+ browser()->tab_strip_model()->GetActiveWebContents();
+ ui::AXTreeUpdate ax_tree_update =
+ content::GetAccessibilityTreeSnapshot(web_contents);
+ while (3 > DescribeNodesWithAnnotations(ax_tree_update).size()) {
+ content::WaitForAccessibilityTreeToChange(web_contents);
+ ax_tree_update = content::GetAccessibilityTreeSnapshot(web_contents);
+ }
+
+ EXPECT_THAT(
+ DescribeNodesWithAnnotations(ax_tree_update),
+ testing::ElementsAre("link photo background Appears to be: Locomotive",
+ "image photo background Appears to be: Locomotive",
+ "image the Appears to be: Tadpole"));
+}
+
IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, ImageDoc) {
FakeAnnotator::SetReturnOcrResults(true);
ui_test_utils::NavigateToURL(
- browser(), https_server_.GetURL("/image_annotation_doc.html"));
+ browser(),
+ https_server_.GetURL("/accessibility/image_annotation_doc.html"));
// Block until the accessibility tree has at least 2 annotations. If
// that never happens, the test will time out.
@@ -323,7 +410,8 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, ImageDoc) {
IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, ImageUrl) {
FakeAnnotator::SetReturnOcrResults(true);
- ui_test_utils::NavigateToURL(browser(), https_server_.GetURL("/red.png"));
+ ui_test_utils::NavigateToURL(browser(),
+ https_server_.GetURL("/accessibility/red.png"));
// Block until the accessibility tree has at least 2 annotations. If
// that never happens, the test will time out.
@@ -351,7 +439,8 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, NoAnnotationsAvailable) {
FakeAnnotator::SetReturnLabelResults(false);
ui_test_utils::NavigateToURL(
- browser(), https_server_.GetURL("/image_annotation_doc.html"));
+ browser(),
+ https_server_.GetURL("/accessibility/image_annotation_doc.html"));
// Block until the annotation status for the root is empty. If that
// never occurs then the test will time out.
@@ -359,8 +448,9 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, NoAnnotationsAvailable) {
browser()->tab_strip_model()->GetActiveWebContents();
ui::AXTreeUpdate snapshot =
content::GetAccessibilityTreeSnapshot(web_contents);
- while (snapshot.nodes[0].GetImageAnnotationStatus() !=
- ax::mojom::ImageAnnotationStatus::kAnnotationEmpty) {
+ while (snapshot.nodes.empty() ||
+ snapshot.nodes[0].GetImageAnnotationStatus() !=
+ ax::mojom::ImageAnnotationStatus::kAnnotationEmpty) {
content::WaitForAccessibilityTreeToChange(web_contents);
snapshot = content::GetAccessibilityTreeSnapshot(web_contents);
}
@@ -372,7 +462,8 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, AnnotationError) {
image_annotation::mojom::AnnotateImageError::kFailure);
ui_test_utils::NavigateToURL(
- browser(), https_server_.GetURL("/image_annotation_doc.html"));
+ browser(),
+ https_server_.GetURL("/accessibility/image_annotation_doc.html"));
// Block until the annotation status for the root contains an error code. If
// that never occurs then the test will time out.
@@ -380,8 +471,9 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, AnnotationError) {
browser()->tab_strip_model()->GetActiveWebContents();
ui::AXTreeUpdate snapshot =
content::GetAccessibilityTreeSnapshot(web_contents);
- while (snapshot.nodes[0].GetImageAnnotationStatus() !=
- ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed) {
+ while (snapshot.nodes.empty() ||
+ snapshot.nodes[0].GetImageAnnotationStatus() !=
+ ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed) {
content::WaitForAccessibilityTreeToChange(web_contents);
snapshot = content::GetAccessibilityTreeSnapshot(web_contents);
}
@@ -390,8 +482,8 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, AnnotationError) {
IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest, ImageWithSrcSet) {
FakeAnnotator::SetReturnOcrResults(true);
FakeAnnotator::SetReturnLabelResults(true);
- ui_test_utils::NavigateToURL(browser(),
- https_server_.GetURL("/image_srcset.html"));
+ ui_test_utils::NavigateToURL(
+ browser(), https_server_.GetURL("/accessibility/image_srcset.html"));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
@@ -406,8 +498,8 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest,
FakeAnnotator::SetReturnOcrResults(true);
FakeAnnotator::SetReturnLabelResults(true);
- ui_test_utils::NavigateToURL(browser(),
- https_server_.GetURL("/image_annotation.html"));
+ ui_test_utils::NavigateToURL(
+ browser(), https_server_.GetURL("/accessibility/image_annotation.html"));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
content::WaitForAccessibilityTreeToContainNodeWithName(
@@ -415,8 +507,8 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest,
"Appears to say: red.png Annotation. Appears to be: red.png 'en' Label");
SetAcceptLanguages("fr,en");
- ui_test_utils::NavigateToURL(browser(),
- https_server_.GetURL("/image_annotation.html"));
+ ui_test_utils::NavigateToURL(
+ browser(), https_server_.GetURL("/accessibility/image_annotation.html"));
web_contents = browser()->tab_strip_model()->GetActiveWebContents();
content::WaitForAccessibilityTreeToContainNodeWithName(
web_contents,
@@ -466,8 +558,8 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest,
FakeAnnotator::SetReturnLabelResults(false);
// The following test page should have at least two images on it.
- ui_test_utils::NavigateToURL(browser(),
- https_server_.GetURL("/image_annotation.html"));
+ ui_test_utils::NavigateToURL(
+ browser(), https_server_.GetURL("/accessibility/image_annotation.html"));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
@@ -504,7 +596,8 @@ IN_PROC_BROWSER_TEST_F(ImageAnnotationBrowserTest,
// The following test page should have at least two images on it.
ui_test_utils::NavigateToURL(
- browser(), https_server_.GetURL("/image_annotation_link.html"));
+ browser(),
+ https_server_.GetURL("/accessibility/image_annotation_link.html"));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
diff --git a/chromium/chrome/browser/android/examples/partner_browser_customizations_provider/BUILD.gn b/chromium/chrome/browser/android/examples/partner_browser_customizations_provider/BUILD.gn
index 632b822acc1..7928b7ee6d4 100644
--- a/chromium/chrome/browser/android/examples/partner_browser_customizations_provider/BUILD.gn
+++ b/chromium/chrome/browser/android/examples/partner_browser_customizations_provider/BUILD.gn
@@ -14,7 +14,6 @@ android_resources("partner_browser_customizations_example_apk_resources") {
}
android_apk("partner_browser_customizations_example_apk") {
- skip_jetify = true
sources = [
"src/org/chromium/example/partnercustomizations/PartnerBookmarksProviderExample.java",
"src/org/chromium/example/partnercustomizations/PartnerBrowserCustomizationsProviderExample.java",
diff --git a/chromium/chrome/browser/android/metrics/BUILD.gn b/chromium/chrome/browser/android/metrics/BUILD.gn
deleted file mode 100644
index 2a7b9c608d0..00000000000
--- a/chromium/chrome/browser/android/metrics/BUILD.gn
+++ /dev/null
@@ -1,50 +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.
-
-if (is_android) {
- import("//build/config/android/rules.gni")
-
- _jni_sources = [ "javatests/src/org/chromium/chrome/browser/metrics/util/UkmUtilsForTest.java" ]
-
- static_library("ukm_utils_for_test") {
- testonly = true
- sources = [ "ukm_utils_for_test.cc" ]
- deps = [
- "//chrome/browser",
- "//chrome/browser/android/metrics:jni_headers",
- "//components/metrics_services_manager:metrics_services_manager",
- "//components/ukm",
- ]
- }
-
- generate_jni("jni_headers") {
- testonly = true
- sources = _jni_sources
- }
-
- android_library("ukm_java_test_support") {
- testonly = true
- sources = _jni_sources
- deps = [ "//base:base_java" ]
- }
-
- android_library("ukm_javatests") {
- testonly = true
- sources =
- [ "javatests/src/org/chromium/chrome/browser/metrics/UkmTest.java" ]
-
- deps = [
- ":ukm_java_test_support",
- "//base:base_java_test_support",
- "//chrome/android:chrome_java",
- "//chrome/browser/tab:java",
- "//chrome/test/android:chrome_java_test_support",
- "//components/metrics:metrics_java",
- "//content/public/test/android:content_java_test_support",
- "//third_party/android_support_test_runner:rules_java",
- "//third_party/android_support_test_runner:runner_java",
- "//third_party/junit",
- ]
- }
-}
diff --git a/chromium/chrome/browser/android/vr/BUILD.gn b/chromium/chrome/browser/android/vr/BUILD.gn
index a37a2b7ea44..bfdfd76eaf2 100644
--- a/chromium/chrome/browser/android/vr/BUILD.gn
+++ b/chromium/chrome/browser/android/vr/BUILD.gn
@@ -27,8 +27,6 @@ static_library("vr_android") {
"cardboard_input_delegate.cc",
"cardboard_input_delegate.h",
"gl_browser_interface.h",
- "gvr_consent_helper.cc",
- "gvr_consent_helper.h",
"gvr_graphics_delegate.cc",
"gvr_graphics_delegate.h",
"gvr_input_delegate.cc",
@@ -78,8 +76,6 @@ static_library("vr_android") {
"arcore_device/arcore.h",
"arcore_device/arcore_anchor_manager.cc",
"arcore_device/arcore_anchor_manager.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",
diff --git a/chromium/chrome/browser/browser_controls/android/BUILD.gn b/chromium/chrome/browser/browser_controls/android/BUILD.gn
new file mode 100644
index 00000000000..507b77f8d1b
--- /dev/null
+++ b/chromium/chrome/browser/browser_controls/android/BUILD.gn
@@ -0,0 +1,40 @@
+# Copyright 2020 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//build/config/android/rules.gni")
+
+android_library("java") {
+ sources = [
+ "java/src/org/chromium/chrome/browser/browser_controls/BrowserControlsMarginSupplier.java",
+ "java/src/org/chromium/chrome/browser/browser_controls/BrowserControlsSizer.java",
+ "java/src/org/chromium/chrome/browser/browser_controls/BrowserControlsStateProvider.java",
+ "java/src/org/chromium/chrome/browser/browser_controls/BrowserControlsUtils.java",
+ "java/src/org/chromium/chrome/browser/browser_controls/BrowserControlsVisibilityManager.java",
+ "java/src/org/chromium/chrome/browser/browser_controls/BrowserStateBrowserControlsVisibilityDelegate.java",
+ ]
+
+ deps = [
+ "//base:base_java",
+ "//chrome/browser/flags:java",
+ "//components/browser_ui/util/android:java",
+ "//content/public/android:content_java",
+ "//ui/android:ui_java",
+ ]
+}
+
+java_library("junit") {
+ # Skip platform checks since Robolectric depends on requires_android targets.
+ bypass_platform_checks = true
+ testonly = true
+ sources = [ "java/src/org/chromium/chrome/browser/browser_controls/BrowserStateBrowserControlsVisibilityDelegateTest.java" ]
+ deps = [
+ ":java",
+ "//base:base_java",
+ "//base:base_junit_test_support",
+ "//content/public/android:content_java",
+ "//third_party/android_deps:robolectric_all_java",
+ "//third_party/junit",
+ "//third_party/mockito:mockito_java",
+ ]
+}
diff --git a/chromium/chrome/browser/browser_resources.grd b/chromium/chrome/browser/browser_resources.grd
index 4c1cb2b3d4d..f8dfa359c30 100644
--- a/chromium/chrome/browser/browser_resources.grd
+++ b/chromium/chrome/browser/browser_resources.grd
@@ -13,32 +13,32 @@
</if>
<if expr="not is_android">
<!-- New Tab Page WebUI. -->
- <structure name="IDR_INCOGNITO_TAB_HTML" file="resources\ntp4\incognito_tab.html" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_INCOGNITO_TAB_THEME_CSS" file="resources\ntp4\incognito_tab_theme.css" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_GUEST_TAB_HTML" file="resources\ntp4\guest_tab.html" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_NEW_TAB_4_HTML" file="resources\ntp4\new_tab.html" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_NEW_TAB_4_THEME_CSS" file="resources\ntp4\new_tab_theme.css" compress="gzip" flattenhtml="true" type="chrome_html" />
+ <structure name="IDR_INCOGNITO_TAB_HTML" file="resources\ntp4\incognito_tab.html" flattenhtml="true" type="chrome_html" />
+ <structure name="IDR_INCOGNITO_TAB_THEME_CSS" file="resources\ntp4\incognito_tab_theme.css" flattenhtml="true" type="chrome_html" />
+ <structure name="IDR_GUEST_TAB_HTML" file="resources\ntp4\guest_tab.html" 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" />
</if>
<if expr="chromeos">
- <structure name="IDR_FIRST_RUN_HTML" file="resources\chromeos\first_run\first_run.html" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_FIRST_RUN_JS" file="resources\chromeos\first_run\first_run.js" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_MD_LOGIN_HTML" file="resources\chromeos\login\md_login.html" compress="gzip" 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" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_OOBE_HTML" file="resources\chromeos\login\oobe.html" compress="gzip" flattenhtml="true" type="chrome_html" variables="OOBE=oobe" expand_variables="true" />
- <structure name="IDR_OOBE_JS" file="resources\chromeos\login\oobe.js" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_KEYBOARD_UTILS_JS" file="resources\chromeos\keyboard\keyboard_utils.js" flattenhtml="true" type="chrome_html" compress="gzip" />
- <structure name="IDR_CHROMEOS_DISCOVER_APP_HTML" file="resources\chromeos\login\discover\discover_app.html" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_CHROMEOS_DISCOVER_APP_JS" file="resources\chromeos\login\discover\discover_app.js" compress="gzip" flattenhtml="true" type="chrome_html" />
+ <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=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" />
+ <structure name="IDR_CHROMEOS_DISCOVER_APP_HTML" file="resources\chromeos\login\discover\discover_app.html" flattenhtml="true" type="chrome_html" />
+ <structure name="IDR_CHROMEOS_DISCOVER_APP_JS" file="resources\chromeos\login\discover\discover_app.js" flattenhtml="true" type="chrome_html" />
<structure name="IDR_CHROMEOS_DISCOVER_MANIFEST" file="resources\chromeos\login\discover\manifest.json" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_CUSTOM_ELEMENTS_OOBE_HTML" file="resources\chromeos\login\custom_elements_oobe.html" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_CUSTOM_ELEMENTS_OOBE_JS" file="resources\chromeos\login\custom_elements_oobe.js" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_CUSTOM_ELEMENTS_LOGIN_HTML" file="resources\chromeos\login\custom_elements_login.html" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_CUSTOM_ELEMENTS_LOGIN_JS" file="resources\chromeos\login\custom_elements_login.js" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_ASSISTANT_OPTIN_HTML" file="resources\chromeos\assistant_optin\assistant_optin.html" compress="gzip" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
- <structure name="IDR_ASSISTANT_OPTIN_JS" file="resources\chromeos\assistant_optin\assistant_optin.js" compress="gzip" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
- <structure name="IDR_OOBE_DEBUGGER_JS" file="resources\chromeos\login\debug\debug.js" compress="gzip" flattenhtml="true" type="chrome_html" />
- <structure name="IDR_OOBE_DEBUGGER_STUB_JS" file="resources\chromeos\login\debug\no_debug.js" compress="gzip" flattenhtml="true" type="chrome_html" />
+ <structure name="IDR_CUSTOM_ELEMENTS_OOBE_HTML" file="resources\chromeos\login\structure\components_common.html" flattenhtml="true" type="chrome_html" variables="OOBE=oobe" expand_variables="true" />
+ <structure name="IDR_CUSTOM_ELEMENTS_OOBE_JS" file="resources\chromeos\login\structure\components_common.js" flattenhtml="true" type="chrome_html" variables="OOBE=oobe" expand_variables="true" />
+ <structure name="IDR_CUSTOM_ELEMENTS_LOGIN_HTML" file="resources\chromeos\login\structure\components_common.html" flattenhtml="true" type="chrome_html" variables="OOBE=login" expand_variables="true" />
+ <structure name="IDR_CUSTOM_ELEMENTS_LOGIN_JS" file="resources\chromeos\login\structure\components_common.js" flattenhtml="true" type="chrome_html" variables="OOBE=login" expand_variables="true" />
+ <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" />
+ <structure name="IDR_OOBE_DEBUGGER_JS" file="resources\chromeos\login\debug\debug.js" flattenhtml="true" type="chrome_html" />
+ <structure name="IDR_OOBE_DEBUGGER_STUB_JS" file="resources\chromeos\login\debug\no_debug.js" flattenhtml="true" type="chrome_html" />
<!-- Gesture Navigation animations. -->
<structure type="chrome_html" name="IDR_GESTURE_NAVIGATION_GO_HOME_ANIMATION" file="resources\chromeos\login\images\gesture_go_home.json" compress="gzip" />
@@ -51,45 +51,45 @@
</structures>
<includes>
<if expr="is_win or is_macosx or desktop_linux or chromeos">
- <include name="IDR_DISCARDS_MOJO_API_JS" file="resources\discards\mojo_api.js" compress="gzip" type="BINDATA" />
- <include name="IDR_DISCARDS_DATABASE_TAB_JS" file="${root_gen_dir}\chrome\browser\resources\discards\database_tab.js" use_base_dir="false" compress="gzip" type="BINDATA" />
- <include name="IDR_DISCARDS_DISCARDS_MAIN_JS" file="${root_gen_dir}\chrome\browser\resources\discards\discards_main.js" use_base_dir="false" compress="gzip" type="BINDATA" />
- <include name="IDR_DISCARDS_DISCARDS_TAB_JS" file="${root_gen_dir}\chrome\browser\resources\discards\discards_tab.js" use_base_dir="false" compress="gzip" type="BINDATA" />
- <include name="IDR_DISCARDS_GRAPH_TAB_JS" file="${root_gen_dir}\chrome\browser\resources\discards\graph_tab.js" compress="gzip" use_base_dir="false" type="BINDATA" />
- <include name="IDR_DISCARDS_HTML" file="resources\discards\discards.html" compress="gzip" allowexternalscript="true" type="BINDATA" />
- <include name="IDR_DISCARDS_JS" file="resources\discards\discards.js" compress="gzip" type="BINDATA" />
- <include name="IDR_DISCARDS_LIFECYCLE_UNIT_STATE_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\resource_coordinator\lifecycle_unit_state.mojom-lite.js" compress="gzip" use_base_dir="false" type="BINDATA" />
- <include name="IDR_DISCARDS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\discards\discards.mojom-lite.js" compress="gzip" use_base_dir="false" type="BINDATA" />
- <include name="IDR_DISCARDS_MOJO_PUBLIC_BASE_PROCESS_ID_MOJOM_LITE_JS" file="${root_gen_dir}\mojo\public\mojom\base\process_id.mojom-lite.js" compress="gzip" use_base_dir="false" type="BINDATA" />
- <include name="IDR_DISCARDS_SITE_DATA_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\discards\site_data.mojom-lite.js" compress="gzip" use_base_dir="false" type="BINDATA" />
- <include name="IDR_DISCARDS_SORTED_TABLE_BEHAVIOR_JS" file="resources\discards\sorted_table_behavior.js" compress="gzip" type="BINDATA" />
+ <include name="IDR_DISCARDS_MOJO_API_JS" file="resources\discards\mojo_api.js" type="BINDATA" />
+ <include name="IDR_DISCARDS_DATABASE_TAB_JS" file="${root_gen_dir}\chrome\browser\resources\discards\database_tab.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DISCARDS_DISCARDS_MAIN_JS" file="${root_gen_dir}\chrome\browser\resources\discards\discards_main.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DISCARDS_DISCARDS_TAB_JS" file="${root_gen_dir}\chrome\browser\resources\discards\discards_tab.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DISCARDS_GRAPH_TAB_JS" file="${root_gen_dir}\chrome\browser\resources\discards\graph_tab.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DISCARDS_HTML" file="resources\discards\discards.html" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_DISCARDS_JS" file="resources\discards\discards.js" type="BINDATA" />
+ <include name="IDR_DISCARDS_LIFECYCLE_UNIT_STATE_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\resource_coordinator\lifecycle_unit_state.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DISCARDS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\discards\discards.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DISCARDS_MOJO_PUBLIC_BASE_PROCESS_ID_MOJOM_LITE_JS" file="${root_gen_dir}\mojo\public\mojom\base\process_id.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DISCARDS_SITE_DATA_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\discards\site_data.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DISCARDS_SORTED_TABLE_BEHAVIOR_JS" file="resources\discards\sorted_table_behavior.js" type="BINDATA" />
</if>
<if expr="is_win or is_macosx or (is_linux and not chromeos)">
- <include name="IDR_BROWSER_SWITCH_APP_JS" file="${root_gen_dir}\chrome\browser\resources\browser_switch\app.js" compress="gzip" use_base_dir="false" type="BINDATA" />
- <include name="IDR_BROWSER_SWITCH_PROXY_JS" file="resources\browser_switch\browser_switch_proxy.js" compress="gzip" type="BINDATA" />
- <include name="IDR_BROWSER_SWITCH_HTML" file="resources\browser_switch\browser_switch.html" compress="gzip" allowexternalscript="true" type="BINDATA" />
- <include name="IDR_BROWSER_SWITCH_INTERNALS_HTML" file="resources\browser_switch\internals\browser_switch_internals.html" compress="gzip" allowexternalscript="true" type="BINDATA" />
- <include name="IDR_BROWSER_SWITCH_INTERNALS_JS" file="resources\browser_switch\internals\browser_switch_internals.js" compress="gzip" type="BINDATA" />
+ <include name="IDR_BROWSER_SWITCH_APP_JS" file="${root_gen_dir}\chrome\browser\resources\browser_switch\app.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_BROWSER_SWITCH_PROXY_JS" file="resources\browser_switch\browser_switch_proxy.js" type="BINDATA" />
+ <include name="IDR_BROWSER_SWITCH_HTML" file="resources\browser_switch\browser_switch.html" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_BROWSER_SWITCH_INTERNALS_HTML" file="resources\browser_switch\internals\browser_switch_internals.html" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_BROWSER_SWITCH_INTERNALS_JS" file="resources\browser_switch\internals\browser_switch_internals.js" type="BINDATA" />
</if>
<if expr="is_win">
- <include name="IDR_ABOUT_CONFLICTS_HTML" file="resources\conflicts\about_conflicts.html" compress="gzip" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
- <include name="IDR_ABOUT_CONFLICTS_JS" file="resources\conflicts\about_conflicts.js" compress="gzip" type="BINDATA" />
+ <include name="IDR_ABOUT_CONFLICTS_HTML" file="resources\conflicts\about_conflicts.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_ABOUT_CONFLICTS_JS" file="resources\conflicts\about_conflicts.js" type="BINDATA" />
</if>
<if expr="not disable_nacl">
- <include name="IDR_ABOUT_NACL_HTML" file="resources\about_nacl\about_nacl.html" compress="gzip" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
- <include name="IDR_ABOUT_NACL_CSS" file="resources\about_nacl\about_nacl.css" compress="gzip" flattenhtml="true" type="chrome_html" />
- <include name="IDR_ABOUT_NACL_JS" file="resources\about_nacl\about_nacl.js" compress="gzip" type="BINDATA" />
+ <include name="IDR_ABOUT_NACL_HTML" file="resources\about_nacl\about_nacl.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_ABOUT_NACL_CSS" file="resources\about_nacl\about_nacl.css" flattenhtml="true" type="chrome_html" />
+ <include name="IDR_ABOUT_NACL_JS" file="resources\about_nacl\about_nacl.js" type="BINDATA" />
</if>
<if expr="not is_android">
- <include name="IDR_ABOUT_SYS_HTML" file="resources\about_sys\about_sys.html" compress="gzip" type="BINDATA" />
- <include name="IDR_ABOUT_SYS_CSS" file="resources\about_sys\about_sys.css" compress="gzip" flattenhtml="true" type="BINDATA" />
- <include name="IDR_ABOUT_SYS_JS" file="resources\about_sys\about_sys.js" compress="gzip" type="BINDATA" />
+ <include name="IDR_ABOUT_SYS_HTML" file="resources\about_sys\about_sys.html" type="BINDATA" />
+ <include name="IDR_ABOUT_SYS_CSS" file="resources\about_sys\about_sys.css" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_ABOUT_SYS_JS" file="resources\about_sys\about_sys.js" type="BINDATA" />
</if>
<include name="IDR_AD_NETWORK_HASHES" file="resources\ad_networks.dat" type="BINDATA" />
<if expr="is_posix and not is_macosx">
- <include name="IDR_CERTIFICATE_VIEWER_HTML" file="resources\certificate_viewer.html" compress="gzip" type="BINDATA" />
- <include name="IDR_CERTIFICATE_VIEWER_JS" file="resources\certificate_viewer.js" compress="gzip" type="BINDATA" />
- <include name="IDR_CERTIFICATE_VIEWER_CSS" file="resources\certificate_viewer.css" compress="gzip" type="BINDATA" />
+ <include name="IDR_CERTIFICATE_VIEWER_HTML" file="resources\certificate_viewer.html" type="BINDATA" />
+ <include name="IDR_CERTIFICATE_VIEWER_JS" file="resources\certificate_viewer.js" type="BINDATA" />
+ <include name="IDR_CERTIFICATE_VIEWER_CSS" file="resources\certificate_viewer.css" type="BINDATA" />
</if>
<if expr="chromeos">
<include name="IDR_CHROME_APP_MANIFEST" file="resources\chrome_app\manifest.json" type="BINDATA" />
@@ -97,18 +97,18 @@
<if expr="enable_printing">
<include name="IDR_CLOUDPRINT_MANIFEST" file="resources\cloud_print_app\manifest.json" type="BINDATA" />
</if>
- <include name="IDR_DEVTOOLS_DISCOVERY_PAGE_HTML" file="devtools\frontend\devtools_discovery_page.html" type="BINDATA" compress="gzip"/>
+ <include name="IDR_DEVTOOLS_DISCOVERY_PAGE_HTML" file="devtools\frontend\devtools_discovery_page.html" type="BINDATA"/>
<include name="IDR_FEEDBACK_MANIFEST" file="resources\feedback\manifest.json" type="BINDATA" />
<if expr="is_android">
- <include name="IDR_DEV_UI_LOADER_ERROR_HTML" file="resources/dev_ui/dev_ui_loader_error.html" compress="gzip" type="BINDATA" />
- <include name="IDR_EXPLORE_SITES_INTERNALS_HTML" file="resources\explore_sites_internals\explore_sites_internals.html" allowexternalscript="true" compress="gzip" type="BINDATA" />
- <include name="IDR_EXPLORE_SITES_INTERNALS_CSS" file="resources\explore_sites_internals\explore_sites_internals.css" compress="gzip" type="BINDATA" />
- <include name="IDR_EXPLORE_SITES_INTERNALS_JS" file="resources\explore_sites_internals\explore_sites_internals.js" compress="gzip" type="BINDATA" />
- <include name="IDR_EXPLORE_SITES_INTERNALS_MOJO_JS" file="${root_gen_dir}\chrome\browser\ui\webui\explore_sites_internals\explore_sites_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_OFFLINE_INTERNALS_HTML" file="resources\offline_pages\offline_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_OFFLINE_INTERNALS_CSS" file="resources\offline_pages\offline_internals.css" type="BINDATA" compress="gzip" />
- <include name="IDR_OFFLINE_INTERNALS_JS" file="resources\offline_pages\offline_internals.js" type="BINDATA" compress="gzip" />
- <include name="IDR_OFFLINE_INTERNALS_BROWSER_PROXY_JS" file="resources\offline_pages\offline_internals_browser_proxy.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_DEV_UI_LOADER_ERROR_HTML" file="resources/dev_ui/dev_ui_loader_error.html" type="BINDATA" />
+ <include name="IDR_EXPLORE_SITES_INTERNALS_HTML" file="resources\explore_sites_internals\explore_sites_internals.html" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_EXPLORE_SITES_INTERNALS_CSS" file="resources\explore_sites_internals\explore_sites_internals.css" type="BINDATA" />
+ <include name="IDR_EXPLORE_SITES_INTERNALS_JS" file="resources\explore_sites_internals\explore_sites_internals.js" type="BINDATA" />
+ <include name="IDR_EXPLORE_SITES_INTERNALS_MOJO_JS" file="${root_gen_dir}\chrome\browser\ui\webui\explore_sites_internals\explore_sites_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_OFFLINE_INTERNALS_HTML" file="resources\offline_pages\offline_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_OFFLINE_INTERNALS_CSS" file="resources\offline_pages\offline_internals.css" type="BINDATA" />
+ <include name="IDR_OFFLINE_INTERNALS_JS" file="resources\offline_pages\offline_internals.js" type="BINDATA" />
+ <include name="IDR_OFFLINE_INTERNALS_BROWSER_PROXY_JS" file="resources\offline_pages\offline_internals_browser_proxy.js" type="BINDATA" />
</if>
<if expr="not is_android">
@@ -138,25 +138,25 @@
<include name="IDR_IDENTITY_API_SCOPE_APPROVAL_MANIFEST" file="resources\identity_scope_approval_dialog\manifest.json" type="BINDATA" />
- <include name="IDR_INLINE_LOGIN_HTML" file="resources\inline_login\inline_login.html" compress="gzip" flattenhtml="true" allowexternalscript="true" type="BINDATA" preprocess="true" />
- <include name="IDR_INLINE_LOGIN_CSS" file="resources\inline_login\inline_login.css" compress="gzip" flattenhtml="true" type="BINDATA" preprocess="true" />
- <include name="IDR_INLINE_LOGIN_JS" file="resources\inline_login\inline_login.js" compress="gzip" flattenhtml="true" type="BINDATA" />
- <include name="IDR_GAIA_AUTH_AUTHENTICATOR_JS" file="resources\gaia_auth_host\authenticator.js" compress="gzip" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_INLINE_LOGIN_HTML" file="resources\inline_login\inline_login.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" preprocess="true" />
+ <include name="IDR_INLINE_LOGIN_CSS" file="resources\inline_login\inline_login.css" flattenhtml="true" type="BINDATA" preprocess="true" />
+ <include name="IDR_INLINE_LOGIN_JS" file="resources\inline_login\inline_login.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_GAIA_AUTH_AUTHENTICATOR_JS" file="resources\gaia_auth_host\authenticator.js" flattenhtml="true" type="BINDATA" />
- <include name="IDR_INSPECT_CSS" file="resources\inspect\inspect.css" compress="gzip" flattenhtml="true" type="BINDATA" />
- <include name="IDR_INSPECT_HTML" file="resources\inspect\inspect.html" compress="gzip" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
- <include name="IDR_INSPECT_JS" file="resources\inspect\inspect.js" compress="gzip" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_INSPECT_CSS" file="resources\inspect\inspect.css" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_INSPECT_HTML" file="resources\inspect\inspect.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_INSPECT_JS" file="resources\inspect\inspect.js" flattenhtml="true" type="BINDATA" />
<include name="IDR_NETWORK_SPEECH_SYNTHESIS_MANIFEST" file="resources\network_speech_synthesis\manifest.json" type="BINDATA" />
<if expr="enable_service_discovery">
- <include name="IDR_LOCAL_DISCOVERY_HTML" file="resources\local_discovery\local_discovery.html" compress="gzip" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
- <include name="IDR_LOCAL_DISCOVERY_CSS" file="resources\local_discovery\local_discovery.css" compress="gzip" flattenhtml="true" type="BINDATA" />
- <include name="IDR_LOCAL_DISCOVERY_JS" file="resources\local_discovery\local_discovery.js" compress="gzip" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_LOCAL_DISCOVERY_HTML" file="resources\local_discovery\local_discovery.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_LOCAL_DISCOVERY_CSS" file="resources\local_discovery\local_discovery.css" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_LOCAL_DISCOVERY_JS" file="resources\local_discovery\local_discovery.js" flattenhtml="true" type="BINDATA" />
</if>
<include name="IDR_DESKTOP_HATS_HTML" file="resources\hats\hats.html" type="BINDATA" />
- <include name="IDR_ORIGIN_MOJO_JS" file="${root_gen_dir}\url\mojom\origin.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip"/>
+ <include name="IDR_ORIGIN_MOJO_JS" file="${root_gen_dir}\url\mojom\origin.mojom-lite.js" use_base_dir="false" type="BINDATA"/>
<if expr="enable_plugins">
<include name="IDR_PDF_MANIFEST" file="resources\pdf\manifest.json" type="BINDATA" />
</if>
@@ -173,12 +173,12 @@
<include name="IDR_PLUGIN_DB_JSON" file="resources\plugin_metadata\plugins_linux.json" type="BINDATA" />
</if>
<if expr="not is_android">
- <include name="IDR_MANAGEMENT_HTML" file="resources\management\management.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_MANAGEMENT_UI_JS" file="${root_gen_dir}/chrome/browser/resources/management/management_ui.js" use_base_dir="false" type="BINDATA" compress="gzip" preprocess="true" />
- <include name="IDR_MANAGEMENT_BROWSER_PROXY_JS" file="resources\management\management_browser_proxy.js" type="BINDATA" compress="gzip" preprocess="true" />
- <include name="IDR_MANAGEMENT_ICONS_JS" file="${root_gen_dir}/chrome/browser/resources/management/icons.js" use_base_dir="false" type="BINDATA" compress="gzip" preprocess="true" />
+ <include name="IDR_MANAGEMENT_HTML" file="resources\management\management.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_MANAGEMENT_UI_JS" file="${root_gen_dir}/chrome/browser/resources/management/management_ui.js" use_base_dir="false" type="BINDATA" preprocess="true" />
+ <include name="IDR_MANAGEMENT_BROWSER_PROXY_JS" file="resources\management\management_browser_proxy.js" type="BINDATA" preprocess="true" />
+ <include name="IDR_MANAGEMENT_ICONS_JS" file="${root_gen_dir}/chrome/browser/resources/management/icons.js" use_base_dir="false" type="BINDATA" preprocess="true" />
</if>
- <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_URL_MOJOM_LITE_JS" file="${root_gen_dir}\url\mojom\url.mojom-lite.js" use_base_dir="false" type="BINDATA" />
<if expr="is_win or is_macosx or desktop_linux or chromeos">
<include name="IDR_SYNC_DISABLED_CONFIRMATION_HTML" file="resources\signin\sync_confirmation\sync_disabled_confirmation.html" type="BINDATA" />
<include name="IDR_SYNC_DISABLED_CONFIRMATION_APP_JS" file="${root_gen_dir}\chrome\browser\resources\signin\sync_confirmation\sync_disabled_confirmation_app.js" use_base_dir="false" preprocess="true" type="BINDATA" />
@@ -186,8 +186,8 @@
<include name="IDR_SYNC_CONFIRMATION_JS" file="resources\signin\sync_confirmation\sync_confirmation.js" 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_JS" file="${root_gen_dir}\chrome\browser\resources\signin\sync_confirmation\sync_confirmation_app.js" use_base_dir="false" preprocess="true" type="BINDATA" />
- <include name="IDR_SYNC_CONFIRMATION_IMAGES_SYNC_CONFIRMATION_ILLUSTRATION_SVG" file="resources\signin\sync_confirmation\images\sync_confirmation_illustration.svg" type="BINDATA" compress="gzip" />
- <include name="IDR_SYNC_CONFIRMATION_IMAGES_SYNC_CONFIRMATION_ILLUSTRATION_DARK_SVG" file="resources\signin\sync_confirmation\images\sync_confirmation_illustration_dark.svg" type="BINDATA" compress="gzip" />
+ <include name="IDR_SYNC_CONFIRMATION_IMAGES_SYNC_CONFIRMATION_ILLUSTRATION_SVG" file="resources\signin\sync_confirmation\images\sync_confirmation_illustration.svg" type="BINDATA" />
+ <include name="IDR_SYNC_CONFIRMATION_IMAGES_SYNC_CONFIRMATION_ILLUSTRATION_DARK_SVG" file="resources\signin\sync_confirmation\images\sync_confirmation_illustration_dark.svg" type="BINDATA" />
</if>
<if expr="is_win or is_macosx or desktop_linux">
<include name="IDR_SIGNIN_EMAIL_CONFIRMATION_HTML" file="resources\signin\signin_email_confirmation\signin_email_confirmation.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
@@ -195,86 +195,81 @@
<include name="IDR_SIGNIN_ERROR_HTML" file="resources\signin\signin_error\signin_error.html" type="BINDATA" />
<include name="IDR_SIGNIN_ERROR_JS" file="resources\signin\signin_error\signin_error.js" type="BINDATA" />
<include name="IDR_SIGNIN_ERROR_APP_JS" file="${root_gen_dir}\chrome\browser\resources\signin\signin_error\signin_error_app.js" use_base_dir="false" preprocess="true" type="BINDATA" />
- </if>
- <include name="IDR_USB_ENUMERATION_OPTIONS_MOJOM_LITE_JS" file="${root_gen_dir}\services\device\public\mojom\usb_enumeration_options.mojom-lite.js" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_USB_DEVICE_MANAGER_CLIENT_MOJOM_LITE_JS" file="${root_gen_dir}\services\device\public\mojom\usb_manager_client.mojom-lite.js" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_USB_DEVICE_MANAGER_MOJOM_LITE_JS" file="${root_gen_dir}\services\device\public\mojom\usb_manager.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_USB_DEVICE_MANAGER_TEST_MOJOM_LITE_JS" file="${root_gen_dir}\services\device\public\mojom\usb_manager_test.mojom-lite.js" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_USB_DEVICE_MOJOM_LITE_JS" file="${root_gen_dir}\services\device\public\mojom\usb_device.mojom-lite.js" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
+ <include name="IDR_SIGNIN_REAUTH_HTML" file="resources\signin\signin_reauth\signin_reauth.html" type="BINDATA" />
+ <include name="IDR_SIGNIN_REAUTH_APP_JS" file="${root_gen_dir}\chrome\browser\resources\signin\signin_reauth\signin_reauth_app.js" use_base_dir="false" preprocess="true" type="BINDATA" />
+ <include name="IDR_SIGNIN_REAUTH_BROWSER_PROXY_JS" file="resources/signin/signin_reauth/signin_reauth_browser_proxy.js" type="BINDATA" />
+ <include name="IDR_SIGNIN_REAUTH_IMAGES_ACCOUNT_PASSWORDS_REAUTH_ILLUSTRATION_SVG" file="resources\signin\signin_reauth\images\account_passwords_reauth_illustration.svg" type="BINDATA" />
+ <include name="IDR_SIGNIN_REAUTH_IMAGES_ACCOUNT_PASSWORDS_REAUTH_ILLUSTRATION_DARK_SVG" file="resources\signin\signin_reauth\images\account_passwords_reauth_illustration_dark.svg" type="BINDATA" />
+ </if>
+ <include name="IDR_USB_ENUMERATION_OPTIONS_MOJOM_LITE_JS" file="${root_gen_dir}\services\device\public\mojom\usb_enumeration_options.mojom-lite.js" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_USB_DEVICE_MANAGER_CLIENT_MOJOM_LITE_JS" file="${root_gen_dir}\services\device\public\mojom\usb_manager_client.mojom-lite.js" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_USB_DEVICE_MANAGER_MOJOM_LITE_JS" file="${root_gen_dir}\services\device\public\mojom\usb_manager.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_USB_DEVICE_MANAGER_TEST_MOJOM_LITE_JS" file="${root_gen_dir}\services\device\public\mojom\usb_manager_test.mojom-lite.js" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_USB_DEVICE_MOJOM_LITE_JS" file="${root_gen_dir}\services\device\public\mojom\usb_device.mojom-lite.js" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
<include name="IDR_WEB_FOOTER_EXPERIMENT_HTML" file="resources\web_footer_experiment\index.html" type="BINDATA" />
<include name="IDR_WEBSTORE_MANIFEST" file="resources\webstore_app\manifest.json" type="BINDATA" />
<include name="IDR_CRYPTOTOKEN_MANIFEST" file="resources\cryptotoken\manifest.json" type="BINDATA" />
<if expr="chromeos">
- <if expr="optimize_webui">
- <then>
- <include name="IDR_BLUETOOTH_PAIRING_DIALOG_VULCANIZED_HTML" file="${root_gen_dir}\chrome\browser\resources\chromeos\bluetooth_pairing_dialog\vulcanized.html" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_BLUETOOTH_PAIRING_DIALOG_CRISPER_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\bluetooth_pairing_dialog\crisper.js" use_base_dir="false" flattenhtml="true" type="BINDATA" compress="gzip" />
- </then>
- <else>
- <include name="IDR_BLUETOOTH_PAIRING_DIALOG_HTML" file="resources\chromeos\bluetooth_pairing_dialog\bluetooth_pairing_dialog.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
- <include name="IDR_BLUETOOTH_PAIRING_DIALOG_JS" file="resources\chromeos\bluetooth_pairing_dialog\bluetooth_pairing_dialog.js" type="chrome_html" />
- </else>
- </if>
<!-- Edu account login resources -->
- <include name="IDR_EDU_LOGIN_EDU_LOGIN_HTML" file="resources\chromeos\edu_login\edu_login.html" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_EDU_LOGIN_EDU_LOGIN_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\app.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_EDU_LOGIN_EDU_LOGIN_UTIL_JS" file="resources\chromeos\edu_login\edu_login_util.js" type="BINDATA" compress="gzip" />
- <include name="IDR_EDU_LOGIN_BROWSER_PROXY_JS" file="resources\chromeos\edu_login\browser_proxy.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_EDU_LOGIN_EDU_LOGIN_HTML" file="resources\chromeos\edu_login\edu_login.html" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_EDU_LOGIN_EDU_LOGIN_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\app.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_EDU_LOGIN_EDU_LOGIN_UTIL_JS" file="resources\chromeos\edu_login\edu_login_util.js" type="BINDATA" />
+ <include name="IDR_EDU_LOGIN_BROWSER_PROXY_JS" file="resources\chromeos\edu_login\browser_proxy.js" type="BINDATA" />
<include name="IDR_EDU_LOGIN_ICONS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\icons.js" use_base_dir="false" type ="BINDATA" />
- <include name="IDR_EDU_LOGIN_EDU_LOGIN_BUTTON_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_button.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_EDU_LOGIN_EDU_LOGIN_TEMPLATE_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_template.js" use_base_dir="false" type="BINDATA" compress="gzip" />
+ <include name="IDR_EDU_LOGIN_EDU_LOGIN_BUTTON_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_button.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_EDU_LOGIN_EDU_LOGIN_TEMPLATE_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_template.js" use_base_dir="false" type="BINDATA" />
<include name="IDR_EDU_LOGIN_EDU_LOGIN_CSS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_css.js" use_base_dir="false" type ="BINDATA" />
- <include name="IDR_EDU_LOGIN_EDU_LOGIN_COEXISTENCE_INFO_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_coexistence_info.js" use_base_dir="false" type ="BINDATA" compress="gzip" preprocess="true" />
- <include name="IDR_EDU_LOGIN_EDU_LOGIN_PARENTS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_parents.js" use_base_dir="false" type ="BINDATA" compress="gzip" preprocess="true" />
- <include name="IDR_EDU_LOGIN_EDU_LOGIN_PARENT_SIGNIN_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_parent_signin.js" use_base_dir="false" type ="BINDATA" compress="gzip" preprocess="true" />
- <include name="IDR_EDU_LOGIN_EDU_LOGIN_PARENT_INFO_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_parent_info.js" use_base_dir="false" type ="BINDATA" compress="gzip" preprocess="true" />
- <include name="IDR_EDU_LOGIN_EDU_LOGIN_SIGNIN_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_signin.js" use_base_dir="false" type ="BINDATA" compress="gzip" />
- <include name="IDR_FAMILY_LINK_LOGO_SVG" file="resources\chromeos\family_link_logo.svg" type="BINDATA" compress="gzip" />
+ <include name="IDR_EDU_LOGIN_EDU_LOGIN_COEXISTENCE_INFO_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_coexistence_info.js" use_base_dir="false" type ="BINDATA" preprocess="true" />
+ <include name="IDR_EDU_LOGIN_EDU_LOGIN_PARENTS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_parents.js" use_base_dir="false" type ="BINDATA" preprocess="true" />
+ <include name="IDR_EDU_LOGIN_EDU_LOGIN_PARENT_SIGNIN_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_parent_signin.js" use_base_dir="false" type ="BINDATA" preprocess="true" />
+ <include name="IDR_EDU_LOGIN_EDU_LOGIN_PARENT_INFO_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_parent_info.js" use_base_dir="false" type ="BINDATA" preprocess="true" />
+ <include name="IDR_EDU_LOGIN_EDU_LOGIN_SIGNIN_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\edu_login\edu_login_signin.js" use_base_dir="false" type ="BINDATA" />
+ <include name="IDR_FAMILY_LINK_LOGO_SVG" file="resources\chromeos\family_link_logo.svg" type="BINDATA" />
<!-- Chrome OS Account Manager welcome screen resources -->
- <include name="IDR_ACCOUNT_MANAGER_SHARED_CSS" file="resources\chromeos\account_manager_shared.css" type="BINDATA" compress="gzip" />
- <include name="IDR_ACCOUNT_MANAGER_WELCOME_HTML" file="resources\chromeos\account_manager_welcome.html" allowexternalscript="true" type="BINDATA" compress="gzip" preprocess="true"/>
- <include name="IDR_ACCOUNT_MANAGER_WELCOME_JS" file="resources\chromeos\account_manager_welcome.js" type="BINDATA" compress="gzip" />
- <include name="IDR_ACCOUNT_MIGRATION_WELCOME_HTML" file="resources\chromeos\account_migration_welcome.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_ACCOUNT_MIGRATION_WELCOME_JS" file="resources\chromeos\account_migration_welcome.js" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_ACCOUNT_MIGRATION_BROWSER_PROXY_HTML" file="resources\chromeos\account_migration_browser_proxy.html" type="BINDATA" compress="gzip" />
- <include name="IDR_ACCOUNT_MIGRATION_BROWSER_PROXY_JS" file="resources\chromeos\account_migration_browser_proxy.js" type="BINDATA" compress="gzip" />
- <include name="IDR_ACCOUNT_MANAGER_ERROR_HTML" file="resources\chromeos\account_manager_error.html" allowexternalscript="true" type="BINDATA" compress="gzip" preprocess="true"/>
- <include name="IDR_ACCOUNT_MANAGER_ERROR_JS" file="resources\chromeos\account_manager_error.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_ACCOUNT_MANAGER_SHARED_CSS" file="resources\chromeos\account_manager\account_manager_shared.css" type="BINDATA" />
+ <include name="IDR_ACCOUNT_MANAGER_WELCOME_HTML" file="resources\chromeos\account_manager\account_manager_welcome.html" allowexternalscript="true" type="BINDATA" preprocess="true"/>
+ <include name="IDR_ACCOUNT_MANAGER_WELCOME_JS" file="resources\chromeos\account_manager\account_manager_welcome.js" type="BINDATA" />
+ <include name="IDR_ACCOUNT_MIGRATION_WELCOME_HTML" file="resources\chromeos\account_manager\account_migration_welcome.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_ACCOUNT_MIGRATION_WELCOME_JS" file="resources\chromeos\account_manager\account_migration_welcome.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_ACCOUNT_MANAGER_BROWSER_PROXY_HTML" file="resources\chromeos\account_manager\account_manager_browser_proxy.html" type="BINDATA" />
+ <include name="IDR_ACCOUNT_MANAGER_BROWSER_PROXY_JS" file="resources\chromeos\account_manager\account_manager_browser_proxy.js" type="BINDATA" />
+ <include name="IDR_ACCOUNT_MANAGER_ERROR_HTML" file="resources\chromeos\account_manager\account_manager_error.html" allowexternalscript="true" type="BINDATA" preprocess="true"/>
+ <include name="IDR_ACCOUNT_MANAGER_ERROR_JS" file="resources\chromeos\account_manager\account_manager_error.js" type="BINDATA" />
<if expr="_google_chrome">
- <include name="IDR_ACCOUNT_MANAGER_WELCOME_1X_PNG" file="resources\chromeos\account_manager_welcome_1x.png" type="BINDATA" compress="gzip" />
- <include name="IDR_ACCOUNT_MANAGER_WELCOME_2X_PNG" file="resources\chromeos\account_manager_welcome_2x.png" type="BINDATA" compress="gzip" />
- <include name="IDR_ACCOUNT_MANAGER_WELCOME_GOOGLE_LOGO_SVG" file="resources\chromeos\googleg.svg" type="BINDATA" compress="gzip" />
+ <include name="IDR_ACCOUNT_MANAGER_WELCOME_1X_PNG" file="resources\chromeos\account_manager\account_manager_welcome_1x.png" type="BINDATA" compress="gzip" />
+ <include name="IDR_ACCOUNT_MANAGER_WELCOME_2X_PNG" file="resources\chromeos\account_manager\account_manager_welcome_2x.png" type="BINDATA" compress="gzip" />
+ <include name="IDR_ACCOUNT_MANAGER_WELCOME_GOOGLE_LOGO_SVG" file="resources\chromeos\googleg.svg" type="BINDATA" />
</if>
- <include name="IDR_PASSWORD_CHANGE_HTML" file="resources\chromeos\password_change\password_change.html" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_PASSWORD_CHANGE_JS" file="resources\chromeos\password_change\password_change.js" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_PASSWORD_CHANGE_CSS" file="resources\chromeos\password_change\password_change.css" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_PASSWORD_CHANGE_AUTHENTICATOR_JS" file="resources\gaia_auth_host\password_change_authenticator.js" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_CONFIRM_PASSWORD_CHANGE_HTML" file="resources\chromeos\password_change\confirm_password_change.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" compress="gzip" />
- <include name="IDR_CONFIRM_PASSWORD_CHANGE_JS" file="resources\chromeos\password_change\confirm_password_change.js" type="chrome_html" compress="gzip" />
- <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" compress="gzip" />
- <include name="IDR_URGENT_PASSWORD_EXPIRY_NOTIFICATION_JS" file="resources\chromeos\password_change\urgent_password_expiry_notification.js" type="chrome_html" compress="gzip" />
+ <include name="IDR_PASSWORD_CHANGE_HTML" file="resources\chromeos\password_change\password_change.html" flattenhtml="true" type="BINDATA" />
+ <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_CROSTINI_INSTALLER_INDEX_HTML" file="resources\chromeos\crostini_installer\index.html" compress="gzip" type="BINDATA" />
- <include name="IDR_CROSTINI_INSTALLER_APP_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\crostini_installer\app.js" compress="gzip" type="BINDATA" use_base_dir="false" />
- <include name="IDR_CROSTINI_INSTALLER_BROWSER_PROXY_JS" file="resources\chromeos\crostini_installer\browser_proxy.js" compress="gzip" type="BINDATA" />
- <include name="IDR_CROSTINI_INSTALLER_MOJO_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\chromeos\crostini_installer\crostini_installer.mojom-lite.js" use_base_dir="false" compress="gzip" type="BINDATA" />
- <include name="IDR_CROSTINI_INSTALLER_TYPES_MOJO_LITE_JS" file="${root_gen_dir}\chrome\browser\chromeos\crostini\crostini_types.mojom-lite.js" use_base_dir="false" compress="gzip" type="BINDATA" />
- <include name="IDR_CROSTINI_UPGRADER_INDEX_HTML" file="resources\chromeos\crostini_upgrader\index.html" compress="gzip" type="BINDATA" />
- <include name="IDR_CROSTINI_UPGRADER_APP_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\crostini_upgrader\app.js" compress="gzip" type="BINDATA" use_base_dir="false" />
- <include name="IDR_CROSTINI_UPGRADER_BROWSER_PROXY_JS" file="resources\chromeos\crostini_upgrader\browser_proxy.js" compress="gzip" type="BINDATA" />
- <include name="IDR_CROSTINI_UPGRADER_MOJO_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\chromeos\crostini_upgrader\crostini_upgrader.mojom-lite.js" use_base_dir="false" compress="gzip" type="BINDATA" />
- <include name="IDR_CRYPTOHOME_HTML" file="resources\chromeos\cryptohome.html" flattenhtml="true" compress="gzip" type="BINDATA" />
- <include name="IDR_CRYPTOHOME_JS" file="resources\chromeos\cryptohome.js" compress="gzip" type="BINDATA" />
+ <include name="IDR_CROSTINI_INSTALLER_INDEX_HTML" file="resources\chromeos\crostini_installer\index.html" type="BINDATA" />
+ <include name="IDR_CROSTINI_INSTALLER_APP_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\crostini_installer\app.js" type="BINDATA" use_base_dir="false" />
+ <include name="IDR_CROSTINI_INSTALLER_BROWSER_PROXY_JS" file="resources\chromeos\crostini_installer\browser_proxy.js" type="BINDATA" />
+ <include name="IDR_CROSTINI_INSTALLER_MOJO_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\chromeos\crostini_installer\crostini_installer.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_CROSTINI_INSTALLER_TYPES_MOJO_LITE_JS" file="${root_gen_dir}\chrome\browser\chromeos\crostini\crostini_types.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_CROSTINI_UPGRADER_INDEX_HTML" file="resources\chromeos\crostini_upgrader\index.html" type="BINDATA" />
+ <include name="IDR_CROSTINI_UPGRADER_APP_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\crostini_upgrader\app.js" type="BINDATA" use_base_dir="false" />
+ <include name="IDR_CROSTINI_UPGRADER_BROWSER_PROXY_JS" file="resources\chromeos\crostini_upgrader\browser_proxy.js" type="BINDATA" />
+ <include name="IDR_CROSTINI_UPGRADER_MOJO_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\chromeos\crostini_upgrader\crostini_upgrader.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_CRYPTOHOME_HTML" file="resources\chromeos\cryptohome.html" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_CRYPTOHOME_JS" file="resources\chromeos\cryptohome.js" type="BINDATA" />
<!-- manifest file of Connectivity Diagnostics app -->
<include name="IDR_CONNECTIVITY_DIAGNOSTICS_MANIFEST" file="resources\chromeos\connectivity_diagnostics\manifest.json" type="BINDATA" />
<include name="IDR_CONNECTIVITY_DIAGNOSTICS_LAUNCHER_MANIFEST" file="resources\chromeos\connectivity_diagnostics_launcher\manifest.json" type="BINDATA" />
- <include name="IDR_DRIVE_INTERNALS_CSS" file="resources\chromeos\drive_internals.css" type="BINDATA" compress="gzip" />
- <include name="IDR_DRIVE_INTERNALS_HTML" file="resources\chromeos\drive_internals.html" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_DRIVE_INTERNALS_JS" file="resources\chromeos\drive_internals.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_DRIVE_INTERNALS_CSS" file="resources\chromeos\drive_internals.css" type="BINDATA" />
+ <include name="IDR_DRIVE_INTERNALS_HTML" file="resources\chromeos\drive_internals.html" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_DRIVE_INTERNALS_JS" file="resources\chromeos\drive_internals.js" type="BINDATA" />
- <include name="IDR_GUEST_SESSION_TAB_HTML" file="resources\chromeos\guest_session_tab.html" flattenhtml="true" type="BINDATA" compress="gzip" />
+ <include name="IDR_GUEST_SESSION_TAB_HTML" file="resources\chromeos\guest_session_tab.html" flattenhtml="true" type="BINDATA" />
<!-- Note: mobile_setup_ui.cc does not support compressed resources. -->
<include name="IDR_MOBILE_MANIFEST" file="resources\chromeos\mobile_app\manifest.json" type="BINDATA" />
@@ -282,13 +277,13 @@
<include name="IDR_MOBILE_SETUP_PORTAL_PAGE_HTML" file="resources\chromeos\mobile_setup_portal.html" flattenhtml="true" type="BINDATA" />
<include name="IDR_ECHO_MANIFEST" file="resources\chromeos\echo\manifest.json" type="BINDATA" />
- <include name="IDR_OS_CREDITS_HTML" file="resources\chromeos\about_os_credits.html" flattenhtml="true" type="BINDATA" compress="gzip" />
+ <include name="IDR_OS_CREDITS_HTML" file="resources\chromeos\about_os_credits.html" flattenhtml="true" type="BINDATA" />
<if expr="optimize_webui">
<then>
- <include name="IDR_INTERNET_CONFIG_DIALOG_VULCANIZED_HTML" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_config_dialog\vulcanized.html" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_INTERNET_CONFIG_DIALOG_CRISPER_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_config_dialog\crisper.js" use_base_dir="false" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_INTERNET_DETAIL_DIALOG_VULCANIZED_HTML" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_detail_dialog\vulcanized.html" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_INTERNET_DETAIL_DIALOG_CRISPER_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_detail_dialog\crisper.js" use_base_dir="false" flattenhtml="true" type="BINDATA" compress="gzip" />
+ <include name="IDR_INTERNET_CONFIG_DIALOG_VULCANIZED_HTML" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_config_dialog\vulcanized.html" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_INTERNET_CONFIG_DIALOG_CRISPER_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_config_dialog\crisper.js" use_base_dir="false" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_INTERNET_DETAIL_DIALOG_VULCANIZED_HTML" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_detail_dialog\vulcanized.html" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_INTERNET_DETAIL_DIALOG_CRISPER_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_detail_dialog\crisper.js" use_base_dir="false" flattenhtml="true" type="BINDATA" />
</then>
<else>
<include name="IDR_INTERNET_CONFIG_DIALOG_HTML" file="resources\chromeos\internet_config_dialog\internet_config_dialog.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
@@ -297,10 +292,10 @@
<include name="IDR_INTERNET_DETAIL_DIALOG_JS" file="resources\chromeos\internet_detail_dialog\internet_detail_dialog.js" type="chrome_html" />
</else>
</if>
- <include name="IDR_CERT_MANAGER_DIALOG_HTML" file="resources\chromeos\certificate_manager_dialog.html" type="BINDATA" compress="gzip" />
- <include name="IDR_SLOW_CSS" file="resources\chromeos\slow.css" type="BINDATA" compress="gzip" />
- <include name="IDR_SLOW_HTML" file="resources\chromeos\slow.html" type="BINDATA" compress="gzip" />
- <include name="IDR_SLOW_JS" file="resources\chromeos\slow.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_CERT_MANAGER_DIALOG_HTML" file="resources\chromeos\certificate_manager_dialog.html" type="BINDATA" />
+ <include name="IDR_SLOW_CSS" file="resources\chromeos\slow.css" type="BINDATA" />
+ <include name="IDR_SLOW_HTML" file="resources\chromeos\slow.html" type="BINDATA" />
+ <include name="IDR_SLOW_JS" file="resources\chromeos\slow.js" type="BINDATA" />
<include name="IDR_HATS_HTML" file="resources\chromeos\hats\hats.html" flattenhtml="false" type="BINDATA" />
<include name="IDR_DEMO_APP_MANIFEST" file="resources\chromeos\demo_app\manifest.json" type="BINDATA" />
<include name="IDR_WALLPAPERMANAGER_MANIFEST" file="resources\chromeos\wallpaper_manager\manifest.json" type="BINDATA" />
@@ -332,14 +327,20 @@
<include name="IDR_USER_MANAGER_TUTORIAL_JS" file="resources\user_manager\user_manager_tutorial.js" type="BINDATA" />
</if>
<if expr="not is_android">
- <include name="IDR_IDENTITY_INTERNALS_HTML" file="resources\identity_internals\identity_internals.html" compress="gzip" type="BINDATA" />
- <include name="IDR_IDENTITY_INTERNALS_CSS" file="resources\identity_internals\identity_internals.css" compress="gzip" type="BINDATA" />
- <include name="IDR_IDENTITY_INTERNALS_JS" file="resources\identity_internals\identity_internals.js" compress="gzip" type="BINDATA" />
+ <include name="IDR_IDENTITY_INTERNALS_HTML" file="resources\identity_internals\identity_internals.html" type="BINDATA" />
+ <include name="IDR_IDENTITY_INTERNALS_CSS" file="resources\identity_internals\identity_internals.css" type="BINDATA" />
+ <include name="IDR_IDENTITY_INTERNALS_JS" file="resources\identity_internals\identity_internals.js" type="BINDATA" />
</if>
<if expr="chromeos">
- <include name="IDR_NETWORK_UI_HTML" file="resources\chromeos\network_ui\network_ui.html" compress="gzip" type="BINDATA" />
- <include name="IDR_NETWORK_UI_JS" file="resources\chromeos\network_ui\network_ui.js" compress="gzip" type="BINDATA" />
- <include name="IDR_NETWORK_UI_CSS" file="resources\chromeos\network_ui\network_ui.css" compress="gzip" type="BINDATA" />
+ <include name="IDR_NETWORK_UI_PAGE_HTML" file="resources\chromeos\network_ui\network.html" type="BINDATA" />
+ <include name="IDR_NETWORK_UI_BROWSER_PROXY_HTML" file="resources\chromeos\network_ui\network_ui_browser_proxy.html" type="BINDATA" />
+ <include name="IDR_NETWORK_UI_BROWSER_PROXY_JS" file="resources\chromeos\network_ui\network_ui_browser_proxy.js" type="BINDATA" />
+ <include name="IDR_NETWORK_UI_HTML" file="resources\chromeos\network_ui\network_ui.html" type="BINDATA" />
+ <include name="IDR_NETWORK_UI_JS" file="resources\chromeos\network_ui\network_ui.js" type="BINDATA" />
+ <include name="IDR_NETWORK_STATE_UI_HTML" file="resources\chromeos\network_ui\network_state_ui.html" type="BINDATA" />
+ <include name="IDR_NETWORK_STATE_UI_JS" file="resources\chromeos\network_ui\network_state_ui.js" type="BINDATA" />
+ <include name="IDR_NETWORK_LOGS_UI_HTML" file="resources\chromeos\network_ui\network_logs_ui.html" type="BINDATA" />
+ <include name="IDR_NETWORK_LOGS_UI_JS" file="resources\chromeos\network_ui\network_logs_ui.js" type="BINDATA" />
</if>
<if expr="_google_chrome">
<include name="IDR_PREF_HASH_SEED_BIN" file="resources\settings_internal\pref_hash_seed.bin" type="BINDATA" />
@@ -373,23 +374,23 @@
<include name="IDR_SOUND_DICTATION_CANCEL_WAV" file="resources\chromeos\sounds\earcons\null_selection.wav" type="BINDATA" />
</if>
<if expr="chromeos">
- <include name="IDR_ABOUT_POWER_HTML" file="resources\chromeos\power.html" compress="gzip" type="BINDATA" />
- <include name="IDR_ABOUT_POWER_JS" file="resources\chromeos\power.js" compress="gzip" type="BINDATA" />
- <include name="IDR_ABOUT_POWER_CSS" file="resources\chromeos\power.css" compress="gzip" type="BINDATA" />
- <include name="IDR_DEVICE_EMULATOR_HTML" file="resources\chromeos\emulator\device_emulator.html" compress="gzip" type="BINDATA" />
- <include name="IDR_DEVICE_EMULATOR_CSS" file="resources\chromeos\emulator\device_emulator.css" compress="gzip" type="BINDATA" />
- <include name="IDR_DEVICE_EMULATOR_AUDIO_SETTINGS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\audio_settings.js" use_base_dir="false" compress="gzip" type="BINDATA" />
+ <include name="IDR_ABOUT_POWER_HTML" file="resources\chromeos\power.html" type="BINDATA" />
+ <include name="IDR_ABOUT_POWER_JS" file="resources\chromeos\power.js" type="BINDATA" />
+ <include name="IDR_ABOUT_POWER_CSS" file="resources\chromeos\power.css" type="BINDATA" />
+ <include name="IDR_DEVICE_EMULATOR_HTML" file="resources\chromeos\emulator\device_emulator.html" type="BINDATA" />
+ <include name="IDR_DEVICE_EMULATOR_CSS" file="resources\chromeos\emulator\device_emulator.css" type="BINDATA" />
+ <include name="IDR_DEVICE_EMULATOR_AUDIO_SETTINGS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\audio_settings.js" use_base_dir="false" type="BINDATA" />
<include name="IDR_DEVICE_EMULATOR_BATTERY_SETTINGS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\battery_settings.js" use_base_dir="false" type="BINDATA" />
- <include name="IDR_DEVICE_EMULATOR_BLUETOOTH_SETTINGS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\bluetooth_settings.js" use_base_dir="false" compress="gzip" type="BINDATA" />
- <include name="IDR_DEVICE_EMULATOR_ICONS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\icons.js" use_base_dir="false" compress="gzip" type="BINDATA" />
- <include name="IDR_DEVICE_EMULATOR_INPUT_DEVICE_SETTINGS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\input_device_settings.js" use_base_dir="false" compress="gzip" type="BINDATA" />
- <include name="IDR_DEVICE_EMULATOR_PAGES_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\device_emulator_pages.js" use_base_dir="false" compress="gzip" type="BINDATA" />
- <include name="IDR_DEVICE_EMULATOR_SHARED_STYLES_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\shared_styles.js" use_base_dir="false" compress="gzip" type="BINDATA" />
+ <include name="IDR_DEVICE_EMULATOR_BLUETOOTH_SETTINGS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\bluetooth_settings.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DEVICE_EMULATOR_ICONS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\icons.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DEVICE_EMULATOR_INPUT_DEVICE_SETTINGS_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\input_device_settings.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DEVICE_EMULATOR_PAGES_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\device_emulator_pages.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_DEVICE_EMULATOR_SHARED_STYLES_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\emulator\shared_styles.js" use_base_dir="false" type="BINDATA" />
</if>
<if expr="chromeos">
- <include name="IDR_SET_TIME_HTML" file="resources\chromeos\set_time_dialog\set_time.html" type="BINDATA" compress="gzip" />
- <include name="IDR_SET_TIME_DIALOG_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\set_time_dialog\set_time_dialog.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_SET_TIME_BROWSER_PROXY_JS" file="resources\chromeos\set_time_dialog\set_time_browser_proxy.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_SET_TIME_HTML" file="resources\chromeos\set_time_dialog\set_time.html" type="BINDATA" />
+ <include name="IDR_SET_TIME_DIALOG_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\set_time_dialog\set_time_dialog.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_SET_TIME_BROWSER_PROXY_JS" file="resources\chromeos\set_time_dialog\set_time_browser_proxy.js" type="BINDATA" />
</if>
<if expr="chromeos">
<if expr="_google_chrome">
@@ -409,9 +410,9 @@
<include name="IDR_BRAILLE_MANIFEST" file="resources\chromeos\accessibility\braille_ime\manifest.json" type="BINDATA" />
</if>
<if expr="not is_android">
- <include name="IDR_MEDIA_ROUTER_INTERNALS_HTML" file="resources\media_router\media_router_internals.html" compress="gzip" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_INTERNALS_CSS" file="resources\media_router\media_router_internals.css" compress="gzip" type="BINDATA" />
- <include name="IDR_MEDIA_ROUTER_INTERNALS_JS" file="resources\media_router\media_router_internals.js" compress="gzip" 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" />
</if>
<if expr="not is_android">
<include name="IDR_IME_WINDOW_CLOSE" file="resources\input_ime\ime_window_close.png" type="BINDATA" />
@@ -420,27 +421,27 @@
</if>
<include name="IDR_PWA_HTML" file="resources\pwa.html" type="BINDATA" />
<if expr="chromeos">
- <include name="IDR_SMB_SHARES_DIALOG_CONTAINER_HTML" file="resources\chromeos\smb_shares\smb_share_dialog_container.html" flattenhtml="true" allowexternalscript="true" compress="gzip" type="chrome_html" />
- <include name="IDR_SMB_SHARES_DIALOG_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\smb_shares\smb_share_dialog.js" use_base_dir="false" compress="gzip" type="chrome_html" />
- <include name="IDR_SMB_CREDENTIALS_DIALOG_CONTAINER_HTML" file="resources\chromeos\smb_shares\smb_credentials_dialog_container.html" flattenhtml="true" allowexternalscript="true" compress="gzip" type="chrome_html" />
- <include name="IDR_SMB_CREDENTIALS_DIALOG_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\smb_shares\smb_credentials_dialog.js" use_base_dir="false" compress="gzip" type="BINDATA" />
- <include name="IDR_SYS_INTERNALS_HTML" file="resources\chromeos\sys_internals\index.html" compress="gzip" type="BINDATA" />
- <include name="IDR_SYS_INTERNALS_CSS" file="resources\chromeos\sys_internals\index.css" compress="gzip" type="BINDATA" />
- <include name="IDR_SYS_INTERNALS_JS" file="resources\chromeos\sys_internals\index.js" compress="gzip" type="BINDATA" />
- <include name="IDR_SYS_INTERNALS_CONSTANT_JS" file="resources\chromeos\sys_internals\constants.js" compress="gzip" type="BINDATA" />
- <include name="IDR_SYS_INTERNALS_LINE_CHART_CSS" file="resources\chromeos\sys_internals\line_chart\line_chart.css" compress="gzip" type="BINDATA" />
- <include name="IDR_SYS_INTERNALS_LINE_CHART_JS" file="resources\chromeos\sys_internals\line_chart\index.js" compress="gzip" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_SMB_SHARES_DIALOG_CONTAINER_HTML" file="resources\chromeos\smb_shares\smb_share_dialog_container.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
+ <include name="IDR_SMB_SHARES_DIALOG_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\smb_shares\smb_share_dialog.js" use_base_dir="false" type="chrome_html" />
+ <include name="IDR_SMB_CREDENTIALS_DIALOG_CONTAINER_HTML" file="resources\chromeos\smb_shares\smb_credentials_dialog_container.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" />
+ <include name="IDR_SMB_CREDENTIALS_DIALOG_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\smb_shares\smb_credentials_dialog.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_SYS_INTERNALS_HTML" file="resources\chromeos\sys_internals\index.html" type="BINDATA" />
+ <include name="IDR_SYS_INTERNALS_CSS" file="resources\chromeos\sys_internals\index.css" type="BINDATA" />
+ <include name="IDR_SYS_INTERNALS_JS" file="resources\chromeos\sys_internals\index.js" type="BINDATA" />
+ <include name="IDR_SYS_INTERNALS_CONSTANT_JS" file="resources\chromeos\sys_internals\constants.js" type="BINDATA" />
+ <include name="IDR_SYS_INTERNALS_LINE_CHART_CSS" file="resources\chromeos\sys_internals\line_chart\line_chart.css" type="BINDATA" />
+ <include name="IDR_SYS_INTERNALS_LINE_CHART_JS" file="resources\chromeos\sys_internals\line_chart\index.js" flattenhtml="true" type="BINDATA" />
<include name="IDR_SYS_INTERNALS_IMAGE_MENU_SVG" file="resources\chromeos\sys_internals\img\menu.svg" type="BINDATA" />
<include name="IDR_SYS_INTERNALS_IMAGE_INFO_SVG" file="resources\chromeos\sys_internals\img\info.svg" type="BINDATA" />
<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="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" />
- <include name="IDR_ADD_SUPERVISION_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\chromeos\add_supervision\add_supervision.mojom-lite.js" compress="gzip" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_ADD_SUPERVISION_HTML" file="resources\chromeos\add_supervision\add_supervision.html" type="chrome_html" />
+ <include name="IDR_ADD_SUPERVISION_NETWORK_UNAVAILABLE_SVG" file="resources\chromeos\add_supervision\images\network_unavailable.svg" type="BINDATA" />
+ <include name="IDR_ADD_SUPERVISION_JS" file="resources\chromeos\add_supervision\add_supervision.js" type="BINDATA" />
+ <include name="IDR_ADD_SUPERVISION_API_SERVER_JS" file="resources\chromeos\add_supervision\add_supervision_api_server.js" type="BINDATA" />
+ <include name="IDR_ADD_SUPERVISION_POST_MESSAGE_API_JS" file="resources\chromeos\add_supervision\post_message_api.js" type="BINDATA" />
+ <include name="IDR_ADD_SUPERVISION_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\chromeos\add_supervision\add_supervision.mojom-lite.js" use_base_dir="false" type="BINDATA" />
</if>
<if expr="chromeos">
<!-- OOBE / Login resources -->
@@ -453,9 +454,9 @@
</if>
</if>
<if expr="safe_browsing_mode == 1">
- <include name="IDR_RESET_PASSWORD_HTML" file="resources\reset_password\reset_password.html" type="BINDATA" compress="gzip" />
- <include name="IDR_RESET_PASSWORD_JS" file="resources\reset_password\reset_password.js" type="BINDATA" compress="gzip" />
- <include name="IDR_RESET_PASSWORD_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\reset_password\reset_password.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
+ <include name="IDR_RESET_PASSWORD_HTML" file="resources\reset_password\reset_password.html" type="BINDATA" />
+ <include name="IDR_RESET_PASSWORD_JS" file="resources\reset_password\reset_password.js" type="BINDATA" />
+ <include name="IDR_RESET_PASSWORD_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\reset_password\reset_password.mojom-lite.js" use_base_dir="false" type="BINDATA" />
</if>
<if expr="not is_android">
<include name="IDR_TAB_RANKER_EXAMPLE_PREPROCESSOR_CONFIG_PB" file="resource_coordinator\tab_ranker\example_preprocessor_config.pb" type="BINDATA" />
@@ -468,25 +469,27 @@
<include name="IDR_SEARCH_RANKER_20190923_EXAMPLE_PREPROCESSOR_CONFIG_PB" file="ui\app_list\search\search_result_ranker\search_ranker_assets\20190923_example_preprocessor_config.pb" type="BINDATA" />
</if>
<if expr="chromeos">
- <include name="IDR_ARC_GRAPHICS_TRACING_HTML" file="resources\chromeos\arc_graphics_tracing\arc_graphics_tracing.html" compress="gzip" type="BINDATA"/>
- <include name="IDR_ARC_GRAPHICS_TRACING_JS" file="resources\chromeos\arc_graphics_tracing\arc_graphics_tracing.js" compress="gzip" type="BINDATA" />
- <include name="IDR_ARC_GRAPHICS_TRACING_UI_JS" file="resources\chromeos\arc_graphics_tracing\arc_graphics_tracing_ui.js" compress="gzip" type="BINDATA" />
- <include name="IDR_ARC_OVERVIEW_TRACING_HTML" file="resources\chromeos\arc_graphics_tracing\arc_overview_tracing.html" compress="gzip" type="BINDATA"/>
- <include name="IDR_ARC_OVERVIEW_TRACING_JS" file="resources\chromeos\arc_graphics_tracing\arc_overview_tracing.js" compress="gzip" type="BINDATA" />
- <include name="IDR_ARC_OVERVIEW_TRACING_UI_JS" file="resources\chromeos\arc_graphics_tracing\arc_overview_tracing_ui.js" compress="gzip" type="BINDATA" />
- <include name="IDR_ARC_TRACING_UI_JS" file="resources\chromeos\arc_graphics_tracing\arc_tracing_ui.js" compress="gzip" type="BINDATA" />
- <include name="IDR_ARC_TRACING_CSS" file="resources\chromeos\arc_graphics_tracing\arc_tracing.css" compress="gzip" type="BINDATA" />
+ <include name="IDR_ARC_GRAPHICS_TRACING_HTML" file="resources\chromeos\arc_graphics_tracing\arc_graphics_tracing.html" type="BINDATA"/>
+ <include name="IDR_ARC_GRAPHICS_TRACING_JS" file="resources\chromeos\arc_graphics_tracing\arc_graphics_tracing.js" type="BINDATA" />
+ <include name="IDR_ARC_GRAPHICS_TRACING_UI_JS" file="resources\chromeos\arc_graphics_tracing\arc_graphics_tracing_ui.js" type="BINDATA" />
+ <include name="IDR_ARC_OVERVIEW_TRACING_HTML" file="resources\chromeos\arc_graphics_tracing\arc_overview_tracing.html" type="BINDATA"/>
+ <include name="IDR_ARC_OVERVIEW_TRACING_JS" file="resources\chromeos\arc_graphics_tracing\arc_overview_tracing.js" type="BINDATA" />
+ <include name="IDR_ARC_OVERVIEW_TRACING_UI_JS" file="resources\chromeos\arc_graphics_tracing\arc_overview_tracing_ui.js" type="BINDATA" />
+ <include name="IDR_ARC_TRACING_UI_JS" file="resources\chromeos\arc_graphics_tracing\arc_tracing_ui.js" type="BINDATA" />
+ <include name="IDR_ARC_TRACING_CSS" file="resources\chromeos\arc_graphics_tracing\arc_tracing.css" type="BINDATA" />
</if>
<if expr="chromeos">
- <include name="IDR_MACHINE_LEARNING_INTERNALS_GRAPH_EXECUTOR_MOJO_JS" file="${root_gen_dir}\chromeos\services\machine_learning\public\mojom\graph_executor.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_MACHINE_LEARNING_INTERNALS_HTML" file="resources\chromeos\machine_learning\machine_learning_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_MACHINE_LEARNING_INTERNALS_JS" file="resources\chromeos\machine_learning\machine_learning_internals.js" type="BINDATA" compress="gzip" />
- <include name="IDR_MACHINE_LEARNING_INTERNALS_UTILS_JS" file="resources\chromeos\machine_learning\machine_learning_internals_utils.js" type="BINDATA" compress="gzip" />
- <include name="IDR_MACHINE_LEARNING_INTERNALS_TEST_MODEL_TAB_JS" file="resources\chromeos\machine_learning\test_model_tab.js" type="BINDATA" compress="gzip" />
- <include name="IDR_MACHINE_LEARNING_INTERNALS_MACHINE_LEARNING_SERVICE_MOJO_JS" file="${root_gen_dir}\chromeos\services\machine_learning\public\mojom\machine_learning_service.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_MACHINE_LEARNING_INTERNALS_MODEL_MOJO_JS" file="${root_gen_dir}\chromeos\services\machine_learning\public\mojom\model.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_MACHINE_LEARNING_INTERNALS_PAGE_HANDLER_MOJO_JS" file="${root_gen_dir}\chrome\browser\ui\webui\chromeos\machine_learning\machine_learning_internals_page_handler.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_MACHINE_LEARNING_INTERNALS_TENSOR_MOJO_JS" file="${root_gen_dir}\chromeos\services\machine_learning\public\mojom\tensor.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
+ <include name="IDR_MACHINE_LEARNING_INTERNALS_GRAPH_EXECUTOR_MOJO_JS" file="${root_gen_dir}\chromeos\services\machine_learning\public\mojom\graph_executor.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_MACHINE_LEARNING_INTERNALS_HANDWRITING_RECOGNIZER_MOJO_JS" file="${root_gen_dir}\chromeos\services\machine_learning\public\mojom\handwriting_recognizer.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_MACHINE_LEARNING_INTERNALS_HTML" file="resources\chromeos\machine_learning\machine_learning_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_MACHINE_LEARNING_INTERNALS_JS" file="resources\chromeos\machine_learning\machine_learning_internals.js" type="BINDATA" />
+ <include name="IDR_MACHINE_LEARNING_INTERNALS_MACHINE_LEARNING_SERVICE_MOJO_JS" file="${root_gen_dir}\chromeos\services\machine_learning\public\mojom\machine_learning_service.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_MACHINE_LEARNING_INTERNALS_MODEL_MOJO_JS" file="${root_gen_dir}\chromeos\services\machine_learning\public\mojom\model.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_MACHINE_LEARNING_INTERNALS_PAGE_HANDLER_MOJO_JS" file="${root_gen_dir}\chrome\browser\ui\webui\chromeos\machine_learning\machine_learning_internals_page_handler.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_MACHINE_LEARNING_INTERNALS_TENSOR_MOJO_JS" file="${root_gen_dir}\chromeos\services\machine_learning\public\mojom\tensor.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_MACHINE_LEARNING_INTERNALS_TEST_MODEL_TAB_JS" file="resources\chromeos\machine_learning\test_model_tab.js" type="BINDATA" />
+ <include name="IDR_MACHINE_LEARNING_INTERNALS_TIME_MOJO_JS" file="${root_gen_dir}\mojo/public/mojom/base/time.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_MACHINE_LEARNING_INTERNALS_UTILS_JS" file="resources\chromeos\machine_learning\machine_learning_internals_utils.js" type="BINDATA" />
</if>
</includes>
</release>
diff --git a/chromium/chrome/browser/browser_switcher/bho/BUILD.gn b/chromium/chrome/browser/browser_switcher/bho/BUILD.gn
index 56203fe8755..63fa7d4284b 100644
--- a/chromium/chrome/browser/browser_switcher/bho/BUILD.gn
+++ b/chromium/chrome/browser/browser_switcher/bho/BUILD.gn
@@ -58,7 +58,7 @@ shared_library("browser_switcher_bho") {
]
} else {
sources = [
- "//base/win/atl.h",
+ "atl.h",
"bho.cc",
"bho.h",
"browser_switcher_core.cc",
diff --git a/chromium/chrome/browser/buildflags.gni b/chromium/chrome/browser/buildflags.gni
index 16404b08165..a67afd18351 100644
--- a/chromium/chrome/browser/buildflags.gni
+++ b/chromium/chrome/browser/buildflags.gni
@@ -2,7 +2,13 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+import("//build/config/chrome_build.gni")
+
declare_args() {
- enable_kaleidoscope = false
+ # Enable Kaleidoscope if we are not Android and we have access to the internal
+ # code. For now we are disabled on Windows and Chrome OS until the build issues
+ # are fixed.
+ enable_kaleidoscope = !is_android && !is_win && !is_chromeos && is_chrome_branded
+
tpm_fallback = false
}
diff --git a/chromium/chrome/browser/chromeos/BUILD.gn b/chromium/chrome/browser/chromeos/BUILD.gn
index b748814c49f..44a1ea38a22 100644
--- a/chromium/chrome/browser/chromeos/BUILD.gn
+++ b/chromium/chrome/browser/chromeos/BUILD.gn
@@ -36,6 +36,7 @@ source_set("chromeos") {
"//chromeos/dbus:runtime_probe_proto",
"//chromeos/dbus:seneschal_proto",
"//chromeos/dbus:vm_applications_apps_proto",
+ "//chromeos/dbus:vm_permission_service_proto",
"//chromeos/dbus/power:power_manager_proto",
"//chromeos/services/assistant/public/mojom",
"//chromeos/strings",
@@ -61,12 +62,12 @@ source_set("chromeos") {
":user_activity_event_proto",
":user_charging_event_proto",
"crostini:crostini_installer_types_mojom",
- "net/network_diagnostics:network_diagnostics_mojom",
"//apps",
"//ash",
"//ash/public/cpp",
+ "//ash/public/cpp/external_arc",
"//ash/public/mojom",
- "//ash/system/message_center/arc",
+ "//base/util/timer",
"//build:branding_buildflags",
"//chrome/app:command_ids",
"//chrome/app/vector_icons",
@@ -74,7 +75,7 @@ source_set("chromeos") {
"//chrome/browser/apps/platform_apps",
"//chrome/browser/apps/platform_apps/api",
"//chrome/browser/chromeos/child_accounts/time_limits/web_time_limit_error_page",
- "//chrome/browser/chromeos/net/mojom",
+ "//chrome/browser/chromeos/local_search_service/proxy:mojom",
"//chrome/browser/chromeos/power/ml/smart_dim",
"//chrome/browser/devtools",
"//chrome/browser/extensions",
@@ -90,10 +91,7 @@ source_set("chromeos") {
"//chrome/browser/web_applications/extensions:extensions",
"//chrome/common",
"//chrome/common/extensions/api",
- "//chrome/common/string_matching",
- "//chrome/services/app_service:lib",
- "//chrome/services/app_service/public/cpp:app_update",
- "//chrome/services/app_service/public/cpp:instance_update",
+ "//chrome/installer/util:with_no_strings",
"//chrome/services/file_util/public/cpp",
"//chrome/services/keymaster/public/mojom",
"//chrome/services/printing/public/mojom",
@@ -103,6 +101,7 @@ source_set("chromeos") {
"//chromeos/attestation",
"//chromeos/audio",
"//chromeos/components/account_manager",
+ "//chromeos/components/cdm_factory_daemon:cdm_factory_daemon_browser",
"//chromeos/components/drivefs",
"//chromeos/components/drivefs/mojom",
"//chromeos/components/help_app_ui",
@@ -116,7 +115,9 @@ source_set("chromeos") {
"//chromeos/components/quick_answers/public/cpp:prefs",
"//chromeos/components/smbfs",
"//chromeos/components/smbfs/mojom",
+ "//chromeos/components/string_matching",
"//chromeos/components/sync_wifi",
+ "//chromeos/components/telemetry_extension_ui/mojom",
"//chromeos/components/tether",
"//chromeos/constants",
"//chromeos/cryptohome",
@@ -126,10 +127,13 @@ source_set("chromeos") {
"//chromeos/dbus:plugin_vm_service_proto",
"//chromeos/dbus:update_engine_proto",
"//chromeos/dbus:vm_plugin_dispatcher_proto",
+ "//chromeos/dbus/attestation",
+ "//chromeos/dbus/attestation:attestation_proto",
"//chromeos/dbus/audio",
"//chromeos/dbus/authpolicy",
"//chromeos/dbus/authpolicy:authpolicy_proto",
"//chromeos/dbus/biod",
+ "//chromeos/dbus/cdm_factory_daemon",
"//chromeos/dbus/constants",
"//chromeos/dbus/cros_healthd",
"//chromeos/dbus/cryptohome",
@@ -139,6 +143,7 @@ source_set("chromeos") {
"//chromeos/dbus/cups_proxy",
"//chromeos/dbus/dlcservice",
"//chromeos/dbus/dlcservice:dlcservice_proto",
+ "//chromeos/dbus/hermes",
"//chromeos/dbus/ip_peripheral",
"//chromeos/dbus/kerberos",
"//chromeos/dbus/kerberos:kerberos_proto",
@@ -156,6 +161,7 @@ source_set("chromeos") {
"//chromeos/dbus/upstart",
"//chromeos/disks",
"//chromeos/geolocation",
+ "//chromeos/lacros/mojom",
"//chromeos/login/auth",
"//chromeos/login/login_state",
"//chromeos/login/session",
@@ -179,6 +185,7 @@ source_set("chromeos") {
"//chromeos/services/multidevice_setup/public/cpp:prefs",
"//chromeos/services/network_config:in_process_instance",
"//chromeos/services/network_config/public/cpp:cpp",
+ "//chromeos/services/network_health/public/mojom",
"//chromeos/services/secure_channel",
"//chromeos/services/secure_channel/public/cpp/client",
"//chromeos/settings",
@@ -217,6 +224,7 @@ source_set("chromeos") {
"//components/language/core/browser",
"//components/language/core/common",
"//components/login",
+ "//components/metrics",
"//components/metrics:serialization",
"//components/omnibox/browser",
"//components/onc",
@@ -239,6 +247,9 @@ source_set("chromeos") {
"//components/rlz",
"//components/safe_browsing/core:csd_proto",
"//components/safe_browsing/core/db:metadata_proto",
+ "//components/services/app_service:lib",
+ "//components/services/app_service/public/cpp:app_update",
+ "//components/services/app_service/public/cpp:instance_update",
"//components/session_manager/core",
"//components/signin/public/identity_manager",
"//components/signin/public/webdata",
@@ -375,8 +386,6 @@ source_set("chromeos") {
"accessibility/spoken_feedback_event_rewriter_delegate.h",
"accessibility/switch_access_event_handler_delegate.cc",
"accessibility/switch_access_event_handler_delegate.h",
- "accessibility/switch_access_panel.cc",
- "accessibility/switch_access_panel.h",
"account_manager/account_manager_migrator.cc",
"account_manager/account_manager_migrator.h",
"account_manager/account_manager_policy_controller.cc",
@@ -440,19 +449,21 @@ source_set("chromeos") {
"app_mode/kiosk_app_icon_loader.h",
"app_mode/kiosk_app_launch_error.cc",
"app_mode/kiosk_app_launch_error.h",
+ "app_mode/kiosk_app_launcher.cc",
+ "app_mode/kiosk_app_launcher.h",
"app_mode/kiosk_app_manager.cc",
"app_mode/kiosk_app_manager.h",
"app_mode/kiosk_app_manager_base.cc",
"app_mode/kiosk_app_manager_base.h",
"app_mode/kiosk_app_manager_observer.h",
+ "app_mode/kiosk_app_types.cc",
+ "app_mode/kiosk_app_types.h",
"app_mode/kiosk_app_update_install_gate.cc",
"app_mode/kiosk_app_update_install_gate.h",
"app_mode/kiosk_app_update_service.cc",
"app_mode/kiosk_app_update_service.h",
"app_mode/kiosk_cryptohome_remover.cc",
"app_mode/kiosk_cryptohome_remover.h",
- "app_mode/kiosk_diagnosis_runner.cc",
- "app_mode/kiosk_diagnosis_runner.h",
"app_mode/kiosk_external_update_validator.cc",
"app_mode/kiosk_external_update_validator.h",
"app_mode/kiosk_external_updater.cc",
@@ -936,6 +947,8 @@ source_set("chromeos") {
"crostini/crostini_shelf_utils.cc",
"crostini/crostini_shelf_utils.h",
"crostini/crostini_simple_types.h",
+ "crostini/crostini_stability_monitor.cc",
+ "crostini/crostini_stability_monitor.h",
"crostini/crostini_terminal.cc",
"crostini/crostini_terminal.h",
"crostini/crostini_unsupported_action_notifier.cc",
@@ -1001,6 +1014,8 @@ source_set("chromeos") {
"dbus/smb_fs_service_provider.h",
"dbus/virtual_file_request_service_provider.cc",
"dbus/virtual_file_request_service_provider.h",
+ "dbus/vm/vm_permission_service_provider.cc",
+ "dbus/vm/vm_permission_service_provider.h",
"dbus/vm_applications_service_provider.cc",
"dbus/vm_applications_service_provider.h",
"device_sync/device_sync_client_factory.cc",
@@ -1242,6 +1257,8 @@ source_set("chromeos") {
"first_run/first_run_controller.h",
"first_run/first_run_view.cc",
"first_run/first_run_view.h",
+ "first_run/help_app_first_run_field_trial.cc",
+ "first_run/help_app_first_run_field_trial.h",
"first_run/step.cc",
"first_run/step.h",
"first_run/step_names.cc",
@@ -1274,6 +1291,8 @@ source_set("chromeos") {
"input_method/assistive_suggester.h",
"input_method/assistive_window_controller.cc",
"input_method/assistive_window_controller.h",
+ "input_method/assistive_window_controller_delegate.h",
+ "input_method/assistive_window_properties.cc",
"input_method/assistive_window_properties.h",
"input_method/browser_state_monitor.cc",
"input_method/browser_state_monitor.h",
@@ -1293,6 +1312,8 @@ source_set("chromeos") {
"input_method/input_method_delegate_impl.h",
"input_method/input_method_engine.cc",
"input_method/input_method_engine.h",
+ "input_method/input_method_engine_base.cc",
+ "input_method/input_method_engine_base.h",
"input_method/input_method_manager_impl.cc",
"input_method/input_method_manager_impl.h",
"input_method/input_method_persistence.cc",
@@ -1306,14 +1327,39 @@ source_set("chromeos") {
"input_method/suggester.h",
"input_method/suggestion_enums.h",
"input_method/suggestion_handler_interface.h",
+ "input_method/ui/assistive_delegate.h",
+ "input_method/ui/border_factory.cc",
+ "input_method/ui/border_factory.h",
+ "input_method/ui/candidate_view.cc",
+ "input_method/ui/candidate_view.h",
+ "input_method/ui/candidate_window_constants.h",
+ "input_method/ui/candidate_window_view.cc",
+ "input_method/ui/candidate_window_view.h",
+ "input_method/ui/infolist_window.cc",
+ "input_method/ui/infolist_window.h",
+ "input_method/ui/input_method_menu_item.cc",
+ "input_method/ui/input_method_menu_item.h",
+ "input_method/ui/input_method_menu_manager.cc",
+ "input_method/ui/input_method_menu_manager.h",
+ "input_method/ui/suggestion_details.h",
+ "input_method/ui/suggestion_view.cc",
+ "input_method/ui/suggestion_view.h",
+ "input_method/ui/suggestion_window_view.cc",
+ "input_method/ui/suggestion_window_view.h",
+ "input_method/ui/undo_window.cc",
+ "input_method/ui/undo_window.h",
"kerberos/kerberos_credentials_manager.cc",
"kerberos/kerberos_credentials_manager.h",
"kerberos/kerberos_credentials_manager_factory.cc",
"kerberos/kerberos_credentials_manager_factory.h",
"kerberos/kerberos_ticket_expiry_notification.cc",
"kerberos/kerberos_ticket_expiry_notification.h",
+ "lacros/ash_chrome_service_impl.cc",
+ "lacros/ash_chrome_service_impl.h",
"lacros/lacros_loader.cc",
"lacros/lacros_loader.h",
+ "lacros/lacros_manager.cc",
+ "lacros/lacros_manager.h",
"lacros/lacros_util.cc",
"lacros/lacros_util.h",
"language_preferences.cc",
@@ -1324,14 +1370,32 @@ source_set("chromeos") {
"launcher_search_provider/launcher_search_provider_service.h",
"launcher_search_provider/launcher_search_provider_service_factory.cc",
"launcher_search_provider/launcher_search_provider_service_factory.h",
+ "local_search_service/content_extraction_utils.cc",
+ "local_search_service/content_extraction_utils.h",
"local_search_service/index.cc",
"local_search_service/index.h",
"local_search_service/inverted_index.cc",
"local_search_service/inverted_index.h",
+ "local_search_service/inverted_index_search.cc",
+ "local_search_service/inverted_index_search.h",
+ "local_search_service/linear_map_search.cc",
+ "local_search_service/linear_map_search.h",
"local_search_service/local_search_service.cc",
"local_search_service/local_search_service.h",
"local_search_service/local_search_service_factory.cc",
"local_search_service/local_search_service_factory.h",
+ "local_search_service/proxy/index_proxy.cc",
+ "local_search_service/proxy/index_proxy.h",
+ "local_search_service/proxy/local_search_service_proxy.cc",
+ "local_search_service/proxy/local_search_service_proxy.h",
+ "local_search_service/proxy/local_search_service_proxy_factory.cc",
+ "local_search_service/proxy/local_search_service_proxy_factory.h",
+ "local_search_service/search_metrics_reporter.cc",
+ "local_search_service/search_metrics_reporter.h",
+ "local_search_service/search_utils.cc",
+ "local_search_service/search_utils.h",
+ "local_search_service/shared_structs.cc",
+ "local_search_service/shared_structs.h",
"locale_change_guard.cc",
"locale_change_guard.h",
"lock_screen_apps/app_manager.h",
@@ -1461,6 +1525,8 @@ source_set("chromeos") {
"login/login_auth_recorder.h",
"login/login_client_cert_usage_observer.cc",
"login/login_client_cert_usage_observer.h",
+ "login/login_pref_names.cc",
+ "login/login_pref_names.h",
"login/login_screen_extensions_lifetime_manager.cc",
"login/login_screen_extensions_lifetime_manager.h",
"login/login_screen_extensions_storage_cleaner.cc",
@@ -1510,6 +1576,8 @@ source_set("chromeos") {
"login/saml/saml_profile_prefs.h",
"login/screen_manager.cc",
"login/screen_manager.h",
+ "login/screens/active_directory_password_change_screen.cc",
+ "login/screens/active_directory_password_change_screen.h",
"login/screens/app_downloading_screen.cc",
"login/screens/app_downloading_screen.h",
"login/screens/arc_terms_of_service_screen.cc",
@@ -1540,6 +1608,8 @@ source_set("chromeos") {
"login/screens/eula_screen.h",
"login/screens/fingerprint_setup_screen.cc",
"login/screens/fingerprint_setup_screen.h",
+ "login/screens/gaia_password_changed_screen.cc",
+ "login/screens/gaia_password_changed_screen.h",
"login/screens/gaia_screen.cc",
"login/screens/gaia_screen.h",
"login/screens/gesture_navigation_screen.cc",
@@ -1575,6 +1645,8 @@ source_set("chromeos") {
"login/screens/sync_consent_screen.h",
"login/screens/terms_of_service_screen.cc",
"login/screens/terms_of_service_screen.h",
+ "login/screens/tpm_error_screen.cc",
+ "login/screens/tpm_error_screen.h",
"login/screens/update_required_screen.cc",
"login/screens/update_required_screen.h",
"login/screens/update_screen.cc",
@@ -1742,6 +1814,12 @@ source_set("chromeos") {
"net/delay_network_call.h",
"net/dhcp_wpad_url_client.cc",
"net/dhcp_wpad_url_client.h",
+ "net/network_diagnostics/dns_latency_routine.cc",
+ "net/network_diagnostics/dns_latency_routine.h",
+ "net/network_diagnostics/dns_resolution_routine.cc",
+ "net/network_diagnostics/dns_resolution_routine.h",
+ "net/network_diagnostics/dns_resolver_present_routine.cc",
+ "net/network_diagnostics/dns_resolver_present_routine.h",
"net/network_diagnostics/gateway_can_be_pinged_routine.cc",
"net/network_diagnostics/gateway_can_be_pinged_routine.h",
"net/network_diagnostics/has_secure_wifi_connection_routine.cc",
@@ -1754,8 +1832,12 @@ source_set("chromeos") {
"net/network_diagnostics/network_diagnostics_routine.h",
"net/network_diagnostics/signal_strength_routine.cc",
"net/network_diagnostics/signal_strength_routine.h",
- "net/network_health.cc",
- "net/network_health.h",
+ "net/network_health/network_health.cc",
+ "net/network_health/network_health.h",
+ "net/network_health/network_health_localized_strings.cc",
+ "net/network_health/network_health_localized_strings.h",
+ "net/network_health/network_health_service.cc",
+ "net/network_health/network_health_service.h",
"net/network_portal_detector_impl.cc",
"net/network_portal_detector_impl.h",
"net/network_portal_detector_test_impl.cc",
@@ -1834,20 +1916,18 @@ source_set("chromeos") {
"policy/affiliated_invalidation_service_provider_impl.h",
"policy/android_management_client.cc",
"policy/android_management_client.h",
- "policy/app_install_event_log.cc",
- "policy/app_install_event_log.h",
"policy/app_install_event_log_collector.cc",
"policy/app_install_event_log_collector.h",
- "policy/app_install_event_log_manager.cc",
- "policy/app_install_event_log_manager.h",
"policy/app_install_event_log_manager_wrapper.cc",
"policy/app_install_event_log_manager_wrapper.h",
- "policy/app_install_event_log_uploader.cc",
- "policy/app_install_event_log_uploader.h",
- "policy/app_install_event_log_util.cc",
- "policy/app_install_event_log_util.h",
"policy/app_install_event_logger.cc",
"policy/app_install_event_logger.h",
+ "policy/arc_app_install_event_log.cc",
+ "policy/arc_app_install_event_log.h",
+ "policy/arc_app_install_event_log_manager.cc",
+ "policy/arc_app_install_event_log_manager.h",
+ "policy/arc_app_install_event_log_uploader.cc",
+ "policy/arc_app_install_event_log_uploader.h",
"policy/auto_enrollment_client.h",
"policy/auto_enrollment_client_impl.cc",
"policy/auto_enrollment_client_impl.h",
@@ -1920,8 +2000,18 @@ source_set("chromeos") {
"policy/enrollment_config.h",
"policy/enrollment_handler_chromeos.cc",
"policy/enrollment_handler_chromeos.h",
+ "policy/enrollment_requisition_manager.cc",
+ "policy/enrollment_requisition_manager.h",
+ "policy/extension_install_event_log.cc",
+ "policy/extension_install_event_log.h",
"policy/extension_install_event_log_collector.cc",
"policy/extension_install_event_log_collector.h",
+ "policy/extension_install_event_log_manager.cc",
+ "policy/extension_install_event_log_manager.h",
+ "policy/extension_install_event_log_manager_wrapper.cc",
+ "policy/extension_install_event_log_manager_wrapper.h",
+ "policy/extension_install_event_log_uploader.cc",
+ "policy/extension_install_event_log_uploader.h",
"policy/extension_install_event_logger.cc",
"policy/extension_install_event_logger.h",
"policy/external_data_handlers/cloud_external_data_policy_handler.cc",
@@ -1950,6 +2040,13 @@ source_set("chromeos") {
"policy/heartbeat_scheduler.h",
"policy/hostname_handler.cc",
"policy/hostname_handler.h",
+ "policy/install_event_log.h",
+ "policy/install_event_log_manager.cc",
+ "policy/install_event_log_manager.h",
+ "policy/install_event_log_uploader_base.cc",
+ "policy/install_event_log_uploader_base.h",
+ "policy/install_event_log_util.cc",
+ "policy/install_event_log_util.h",
"policy/lock_to_single_user_manager.cc",
"policy/lock_to_single_user_manager.h",
"policy/login_profile_policy_provider.cc",
@@ -2028,8 +2125,11 @@ source_set("chromeos") {
"policy/server_backed_device_state.h",
"policy/server_backed_state_keys_broker.cc",
"policy/server_backed_state_keys_broker.h",
- "policy/single_app_install_event_log.cc",
- "policy/single_app_install_event_log.h",
+ "policy/single_arc_app_install_event_log.cc",
+ "policy/single_arc_app_install_event_log.h",
+ "policy/single_extension_install_event_log.cc",
+ "policy/single_extension_install_event_log.h",
+ "policy/single_install_event_log.h",
"policy/status_collector/activity_storage.cc",
"policy/status_collector/activity_storage.h",
"policy/status_collector/affiliated_session_service.cc",
@@ -2258,6 +2358,8 @@ source_set("chromeos") {
"printing/usb_printer_util.h",
"printing/zeroconf_printer_detector.cc",
"printing/zeroconf_printer_detector.h",
+ "process_snapshot_server.cc",
+ "process_snapshot_server.h",
"profiles/profile_helper.cc",
"profiles/profile_helper.h",
"release_notes/release_notes_notification.cc",
@@ -2269,6 +2371,7 @@ source_set("chromeos") {
"scheduler_configuration_manager.h",
"secure_channel/secure_channel_client_provider.cc",
"secure_channel/secure_channel_client_provider.h",
+ "service_sandbox_type.h",
"session_length_limiter.cc",
"session_length_limiter.h",
"set_time_dialog.cc",
@@ -2357,6 +2460,8 @@ source_set("chromeos") {
"sync/os_sync_util.h",
"sync/os_syncable_service_model_type_controller.cc",
"sync/os_syncable_service_model_type_controller.h",
+ "sync/split_settings_sync_field_trial.cc",
+ "sync/split_settings_sync_field_trial.h",
"sync/turn_sync_on_helper.cc",
"sync/turn_sync_on_helper.h",
"system/automatic_reboot_manager.cc",
@@ -2399,6 +2504,8 @@ source_set("chromeos") {
"system_logs/device_event_log_source.h",
"system_logs/iwlwifi_dump_log_source.cc",
"system_logs/iwlwifi_dump_log_source.h",
+ "system_logs/network_health_source.cc",
+ "system_logs/network_health_source.h",
"system_logs/single_debug_daemon_log_source.cc",
"system_logs/single_debug_daemon_log_source.h",
"system_logs/single_log_file_log_source.cc",
@@ -2425,6 +2532,8 @@ source_set("chromeos") {
"tpm_firmware_update.h",
"tpm_firmware_update_notification.cc",
"tpm_firmware_update_notification.h",
+ "tracing_allocation_failure_tracker.cc",
+ "tracing_allocation_failure_tracker.h",
"u2f_notification.cc",
"u2f_notification.h",
"ui/echo_dialog_listener.h",
@@ -2446,6 +2555,8 @@ source_set("chromeos") {
"ui/screen_capture_notification_ui_chromeos.h",
"ui/tpm_auto_update_notification.cc",
"ui/tpm_auto_update_notification.h",
+ "ui/update_required_notification.cc",
+ "ui/update_required_notification.h",
"usb/cros_usb_detector.cc",
"usb/cros_usb_detector.h",
"virtual_machines/virtual_machines_util.cc",
@@ -2545,12 +2656,6 @@ source_set("chromeos") {
"extensions/printing/print_job_controller.h",
"extensions/printing/printer_capabilities_provider.cc",
"extensions/printing/printer_capabilities_provider.h",
- "extensions/printing_metrics/print_job_finished_event_dispatcher.cc",
- "extensions/printing_metrics/print_job_finished_event_dispatcher.h",
- "extensions/printing_metrics/print_job_info_idl_conversions.cc",
- "extensions/printing_metrics/print_job_info_idl_conversions.h",
- "extensions/printing_metrics/printing_metrics_api.cc",
- "extensions/printing_metrics/printing_metrics_api.h",
"extensions/quick_unlock_private/quick_unlock_private_api.cc",
"extensions/quick_unlock_private/quick_unlock_private_api.h",
"extensions/users_private/users_private_api.cc",
@@ -2582,6 +2687,12 @@ source_set("chromeos") {
"extensions/printing/printing_api_handler.h",
"extensions/printing/printing_api_utils.cc",
"extensions/printing/printing_api_utils.h",
+ "extensions/printing_metrics/print_job_finished_event_dispatcher.cc",
+ "extensions/printing_metrics/print_job_finished_event_dispatcher.h",
+ "extensions/printing_metrics/print_job_info_idl_conversions.cc",
+ "extensions/printing_metrics/print_job_info_idl_conversions.h",
+ "extensions/printing_metrics/printing_metrics_api.cc",
+ "extensions/printing_metrics/printing_metrics_api.h",
"printing/cups_print_job_manager_impl.cc",
"printing/cups_proxy_service_delegate_impl.cc",
"printing/cups_proxy_service_delegate_impl.h",
@@ -2628,6 +2739,7 @@ action("dbus_service_files") {
"dbus/org.chromium.SmbFsService.conf",
"dbus/org.chromium.VirtualFileRequestService.conf",
"dbus/org.chromium.VmApplicationsService.conf",
+ "dbus/vm/org.chromium.VmPermissionService.conf",
]
output_conf_file = "$root_out_dir/dbus/chrome_dbus_services.conf"
outputs = [ output_conf_file ]
@@ -2766,7 +2878,6 @@ source_set("unit_tests") {
"../policy/default_geolocation_policy_handler_unittest.cc",
"../resources/chromeos/zip_archiver/test/char_coding_test.cc",
"../ui/browser_finder_chromeos_unittest.cc",
- "accessibility/switch_access_panel_unittest.cc",
"account_manager/account_migration_runner_unittest.cc",
"android_sms/android_sms_app_manager_impl_unittest.cc",
"android_sms/android_sms_app_setup_controller_impl_unittest.cc",
@@ -2780,7 +2891,9 @@ source_set("unit_tests") {
"apps/apk_web_app_installer_unittest.cc",
"apps/intent_helper/chromeos_apps_navigation_throttle_unittest.cc",
"apps/metrics/intent_handling_metrics_unittest.cc",
+ "arc/accessibility/accessibility_node_info_data_wrapper_unittest.cc",
"arc/accessibility/arc_accessibility_helper_bridge_unittest.cc",
+ "arc/accessibility/arc_accessibility_util_unittest.cc",
"arc/accessibility/ax_tree_source_arc_unittest.cc",
"arc/app_shortcuts/arc_app_shortcuts_menu_builder_unittest.cc",
"arc/app_shortcuts/arc_app_shortcuts_request_unittest.cc",
@@ -2907,6 +3020,7 @@ source_set("unit_tests") {
"crostini/crostini_port_forwarder_unittest.cc",
"crostini/crostini_reporting_util_unittest.cc",
"crostini/crostini_shelf_utils_unittest.cc",
+ "crostini/crostini_stability_monitor_unittest.cc",
"crostini/crostini_unsupported_action_notifier_unittest.cc",
"crostini/crostini_util_unittest.cc",
"crostini/crosvm_metrics_unittest.cc",
@@ -2939,9 +3053,6 @@ source_set("unit_tests") {
"extensions/printing/fake_print_job_controller.cc",
"extensions/printing/fake_print_job_controller.h",
"extensions/printing/printer_capabilities_provider_unittest.cc",
- "extensions/printing_metrics/print_job_finished_event_dispatcher_unittest.cc",
- "extensions/printing_metrics/print_job_info_idl_conversions_unittest.cc",
- "extensions/printing_metrics/printing_metrics_api_unittest.cc",
"extensions/public_session_permission_helper_unittest.cc",
"extensions/quick_unlock_private/quick_unlock_private_api_unittest.cc",
"extensions/signin_screen_policy_provider_unittest.cc",
@@ -3011,6 +3122,7 @@ source_set("unit_tests") {
"guest_os/guest_os_share_path_unittest.cc",
"hats/hats_finch_helper_unittest.cc",
"hats/hats_notification_controller_unittest.cc",
+ "input_method/assistive_suggester_unittest.cc",
"input_method/assistive_window_controller_unittest.cc",
"input_method/emoji_suggester_unittest.cc",
"input_method/input_method_configuration_unittest.cc",
@@ -3018,12 +3130,23 @@ source_set("unit_tests") {
"input_method/input_method_manager_impl_unittest.cc",
"input_method/input_method_persistence_unittest.cc",
"input_method/personal_info_suggester_unittest.cc",
+ "input_method/ui/candidate_view_unittest.cc",
+ "input_method/ui/candidate_window_view_unittest.cc",
+ "input_method/ui/input_method_menu_item_unittest.cc",
+ "input_method/ui/input_method_menu_manager_unittest.cc",
+ "input_method/ui/suggestion_window_view_unittest.cc",
"kerberos/kerberos_credentials_manager_test.cc",
"kerberos/kerberos_ticket_expiry_notification_test.cc",
"lacros/lacros_util_unittest.cc",
- "local_search_service/index_unittest.cc",
+ "local_search_service/content_extraction_utils_unittest.cc",
+ "local_search_service/inverted_index_search_unittest.cc",
"local_search_service/inverted_index_unittest.cc",
+ "local_search_service/linear_map_search_unittest.cc",
"local_search_service/local_search_service_unittest.cc",
+ "local_search_service/proxy/local_search_service_proxy_unittest.cc",
+ "local_search_service/proxy/types_mojom_traits_unittest.cc",
+ "local_search_service/search_metrics_reporter_unittest.cc",
+ "local_search_service/search_utils_unittest.cc",
"local_search_service/test_utils.cc",
"local_search_service/test_utils.h",
"locale_change_guard_unittest.cc",
@@ -3073,12 +3196,15 @@ source_set("unit_tests") {
"login/version_updater/version_updater_unittest.cc",
"mobile/mobile_activator_unittest.cc",
"net/client_cert_store_chromeos_unittest.cc",
+ "net/network_diagnostics/dns_latency_routine_unittest.cc",
+ "net/network_diagnostics/dns_resolution_routine_unittest.cc",
+ "net/network_diagnostics/dns_resolver_present_routine_unittest.cc",
"net/network_diagnostics/gateway_can_be_pinged_routine_unittest.cc",
"net/network_diagnostics/has_secure_wifi_connection_routine_unittest.cc",
"net/network_diagnostics/lan_connectivity_routine_unittest.cc",
"net/network_diagnostics/network_diagnostics_routine_unittest.cc",
"net/network_diagnostics/signal_strength_routine_unittest.cc",
- "net/network_health_unittest.cc",
+ "net/network_health/network_health_unittest.cc",
"net/network_portal_detector_impl_unittest.cc",
"net/network_pref_state_observer_unittest.cc",
"net/network_throttling_observer_unittest.cc",
@@ -3099,11 +3225,11 @@ source_set("unit_tests") {
"policy/affiliated_invalidation_service_provider_impl_unittest.cc",
"policy/android_management_client_unittest.cc",
"policy/app_install_event_log_collector_unittest.cc",
- "policy/app_install_event_log_manager_unittest.cc",
"policy/app_install_event_log_manager_wrapper_unittest.cc",
- "policy/app_install_event_log_unittest.cc",
- "policy/app_install_event_log_uploader_unittest.cc",
"policy/app_install_event_logger_unittest.cc",
+ "policy/arc_app_install_event_log_manager_unittest.cc",
+ "policy/arc_app_install_event_log_unittest.cc",
+ "policy/arc_app_install_event_log_uploader_unittest.cc",
"policy/auto_enrollment_client_impl_unittest.cc",
"policy/bluetooth_policy_handler_unittest.cc",
"policy/cached_policy_key_loader_chromeos_unittest.cc",
@@ -3124,6 +3250,7 @@ source_set("unit_tests") {
"policy/dm_token_storage_unittest.cc",
"policy/extension_cache_unittest.cc",
"policy/extension_install_event_log_collector_unittest.cc",
+ "policy/extension_install_event_log_unittest.cc",
"policy/extension_install_event_logger_unittest.cc",
"policy/external_data_handlers/device_native_printers_external_data_handler_unittest.cc",
"policy/fake_affiliated_invalidation_service_provider.cc",
@@ -3151,9 +3278,11 @@ source_set("unit_tests") {
"policy/scheduled_update_checker/device_scheduled_update_checker_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",
+ "policy/single_arc_app_install_event_log_unittest.cc",
+ "policy/status_collector/activity_storage_unittest.cc",
"policy/status_collector/affiliated_session_service_unittest.cc",
"policy/status_collector/app_info_generator_unittest.cc",
+ "policy/status_collector/enterprise_activity_storage_unittest.cc",
"policy/status_collector/interval_map_unittest.cc",
"policy/status_uploader_unittest.cc",
"policy/system_features_disable_list_policy_handler_unittest.cc",
@@ -3227,6 +3356,7 @@ source_set("unit_tests") {
"printing/test_printer_configurer.h",
"printing/usb_printer_detector_unittest.cc",
"printing/zeroconf_printer_detector_unittest.cc",
+ "process_snapshot_server_unittest.cc",
"proxy_config_service_impl_unittest.cc",
"release_notes/release_notes_notification_unittest.cc",
"release_notes/release_notes_storage_unittest.cc",
@@ -3316,6 +3446,9 @@ source_set("unit_tests") {
sources += [
"extensions/printing/printing_api_handler_unittest.cc",
"extensions/printing/printing_api_utils_unittest.cc",
+ "extensions/printing_metrics/print_job_finished_event_dispatcher_unittest.cc",
+ "extensions/printing_metrics/print_job_info_idl_conversions_unittest.cc",
+ "extensions/printing_metrics/printing_metrics_api_unittest.cc",
"printing/test_cups_wrapper.cc",
"printing/test_cups_wrapper.h",
]
@@ -3329,8 +3462,8 @@ source_set("unit_tests") {
":user_activity_event_proto",
"//ash",
"//ash/public/cpp:test_support",
- "//ash/system/message_center/arc",
- "//ash/system/message_center/arc:test_support",
+ "//ash/public/cpp/external_arc",
+ "//ash/public/cpp/external_arc:test_support",
"//base",
"//chrome/app:command_ids",
"//chrome/browser/resources/chromeos/zip_archiver:char_coding",
@@ -3552,9 +3685,11 @@ if (use_libfuzzer) {
deps = [
":policy_fuzzer_proto",
+ "//base/test:test_support",
"//chrome/browser",
"//chrome/browser/chromeos",
"//chromeos/dbus:dbus",
+ "//chromeos/tpm",
"//third_party/libprotobuf-mutator",
]
}
@@ -3567,6 +3702,11 @@ if (use_libfuzzer) {
"$root_gen_dir/components/policy/proto",
]
+ proto_deps = [
+ "//components/policy:cloud_policy_full_runtime_proto",
+ "//components/policy/proto:chrome_device_policy_full_runtime_proto",
+ ]
+
link_deps = [
"//components/policy:cloud_policy_full_runtime_proto",
"//components/policy/proto:chrome_device_policy_full_runtime_proto",
diff --git a/chromium/chrome/browser/chromeos/local_search_service/proxy/BUILD.gn b/chromium/chrome/browser/chromeos/local_search_service/proxy/BUILD.gn
new file mode 100644
index 00000000000..f3883946d90
--- /dev/null
+++ b/chromium/chrome/browser/chromeos/local_search_service/proxy/BUILD.gn
@@ -0,0 +1,55 @@
+# Copyright 2020 The Chromium 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 = [
+ "local_search_service_proxy.mojom",
+ "types.mojom",
+ ]
+
+ public_deps = [ "//mojo/public/mojom/base" ]
+
+ cpp_typemaps = [
+ {
+ types = [
+ {
+ mojom = "local_search_service.mojom.IndexId"
+ cpp = "::local_search_service::IndexId"
+ },
+ {
+ mojom = "local_search_service.mojom.Content"
+ cpp = "::local_search_service::Content"
+ },
+ {
+ mojom = "local_search_service.mojom.Data"
+ cpp = "::local_search_service::Data"
+ },
+ {
+ mojom = "local_search_service.mojom.SearchParams"
+ cpp = "::local_search_service::SearchParams"
+ },
+ {
+ mojom = "local_search_service.mojom.Position"
+ cpp = "::local_search_service::Position"
+ },
+ {
+ mojom = "local_search_service.mojom.Result"
+ cpp = "::local_search_service::Result"
+ },
+ {
+ mojom = "local_search_service.mojom.ResponseStatus"
+ cpp = "::local_search_service::ResponseStatus"
+ },
+ {
+ mojom = "local_search_service.mojom.Backend"
+ cpp = "::local_search_service::Backend"
+ },
+ ]
+ traits_headers = [ "//chrome/browser/chromeos/local_search_service/proxy/types_mojom_traits.h" ]
+ traits_sources = [ "//chrome/browser/chromeos/local_search_service/proxy/types_mojom_traits.cc" ]
+ },
+ ]
+}
diff --git a/chromium/chrome/browser/chromeos/local_search_service/proxy/local_search_service_proxy.mojom b/chromium/chrome/browser/chromeos/local_search_service/proxy/local_search_service_proxy.mojom
new file mode 100644
index 00000000000..dbe6983c4a7
--- /dev/null
+++ b/chromium/chrome/browser/chromeos/local_search_service/proxy/local_search_service_proxy.mojom
@@ -0,0 +1,55 @@
+// Copyright 2020 The Chromium 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 local_search_service.mojom;
+
+import "chrome/browser/chromeos/local_search_service/proxy/types.mojom";
+import "mojo/public/mojom/base/string16.mojom";
+
+enum IndexId {
+ kCrosSettings = 0
+ // Add new client IDs here.
+};
+
+enum Backend {
+ kLinearMap = 0,
+ kInvertedIndex = 1
+};
+
+// LocalSearchServiceProxy creates and owns content-specific IndexProxies.
+// Clients can call |GetIndex| to get an IndexProxy for a given index id.
+interface LocalSearchServiceProxy {
+ // A client can call this function to bind an IndexProxy for |index_id|. If
+ // the Index isn't created when this function is called, LocalSearchService
+ // will create one.
+ // Note, there should be one primary client that is the owner of the data and
+ // can read/write the data to the Index. The other clients should only use
+ // the Index for query search.
+ GetIndex(IndexId index_id, Backend backend,
+ pending_receiver<IndexProxy> index_receiver);
+};
+
+// A proxy to a local search service Index.
+// An Index has a registry of searchable data, which can be updated. It also
+// runs a search function to find matching items for a given query.
+// Each Index can serve multiple clients, but only one client (the primary
+// client) that owns the data should be allowed to modify the Index.
+interface IndexProxy {
+ // Returns number of data items.
+ GetSize() => (uint64 num_items);
+
+ // Adds or updates data and callbacks upon completion.
+ // Only the primary client should be allowed to do this operation.
+ AddOrUpdate(array<Data> data) => ();
+
+ // Deletes data with |ids| and returns the number of items deleted.
+ // If an id doesn't exist in the Index, no operation will be done.
+ // Only the primary client should be allowed to do this operation.
+ Delete(array<string> ids) => (uint32 num_deleted);
+
+ // Takes an asynchronous search request call and returns results and status
+ // code via a callback. |results| will be null if there is an error.
+ Find(mojo_base.mojom.String16 query, uint32 max_results)
+ => (ResponseStatus status, array<Result>? results);
+};
diff --git a/chromium/chrome/browser/chromeos/local_search_service/proxy/types.mojom b/chromium/chrome/browser/chromeos/local_search_service/proxy/types.mojom
new file mode 100644
index 00000000000..70c32a21897
--- /dev/null
+++ b/chromium/chrome/browser/chromeos/local_search_service/proxy/types.mojom
@@ -0,0 +1,73 @@
+// Copyright 2020 The Chromium 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 local_search_service.mojom;
+
+import "mojo/public/mojom/base/string16.mojom";
+
+struct Content {
+ // An identifier for the content in Data.
+ string id;
+ mojo_base.mojom.String16 content;
+ double weight = 1.0;
+};
+
+struct Data {
+ // Identifier of the data item, should be unique across the registry. Clients
+ // will decide what ids to use, they could be paths, urls or any opaque
+ // string identifiers.
+ // Ideally IDs should persist across sessions, but this is not strictly
+ // required now because data is not persisted across sessions.
+ string id;
+
+ // Data item will be matched between its search tags and query term.
+ array<Content> contents;
+
+ // If unset, we will use system configured locale.
+ string locale;
+};
+
+struct SearchParams {
+ double relevance_threshold = 0.32;
+ double prefix_threshold = 0.6;
+ double fuzzy_threshold = 0.6;
+};
+
+struct Position {
+ string content_id;
+ uint32 start;
+ uint32 length;
+};
+
+// Result is one item that matches a given query. It contains the id of the
+// item and its matching score.
+struct Result {
+ // Id of the data.
+ string id;
+ // Relevance score.
+ // Currently only linear map is implemented with fuzzy matching and score
+ // will always be in [0,1]. In the future, when an inverted index is
+ // implemented, the score will not be in this range any more. Client will be
+ // able to select a search backend to use (linear map vs inverted index) and
+ // hence client will be able to expect the range of the scores.
+ double score;
+ // Position of the matching text.
+ // We currently use linear map, which will return one matching content,
+ // hence the vector has only one element. When we have inverted index, we
+ // will have multiple matching contents.
+ array<Position> positions;
+};
+
+// Status of the search attempt.
+// More will be added later.
+enum ResponseStatus {
+ kUnknownError,
+ // Search operation is successful. But there could be no item and result list
+ // is empty.
+ kSuccess,
+ // Query is empty.
+ kEmptyQuery,
+ // Index is empty (i.e. no data).
+ kEmptyIndex
+};
diff --git a/chromium/chrome/browser/chromeos/net/mojom/network_health.mojom b/chromium/chrome/browser/chromeos/net/mojom/network_health.mojom
deleted file mode 100644
index f3d27f503cf..00000000000
--- a/chromium/chrome/browser/chromeos/net/mojom/network_health.mojom
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2020 The Chromium 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.network_health.mojom;
-
-import "chromeos/services/network_config/public/mojom/network_types.mojom";
-
-// Contains information for a single network.
-struct Network {
- chromeos.network_config.mojom.ConnectionStateType connection_state;
- string name;
- chromeos.network_config.mojom.NetworkType type;
-};
-
-// Contains information for a single network device.
-struct Device {
- chromeos.network_config.mojom.DeviceStateType connection_state;
- // Optional string for the device’s mac_address. Will only be populated if
- // applicable to the device.
- string? mac_address;
- chromeos.network_config.mojom.NetworkType type;
-};
-
-// Interface for retrieving aggregated information about the current network
-// state and health.
-interface NetworkHealthService {
- // Returns a list of the network devices.
- GetDeviceList() => (array<Device> devices);
-
- // Returns a list of the active (connected or connecting) networks.
- GetActiveNetworkList() => (array<Network> active_networks);
-};
diff --git a/chromium/chrome/browser/chromeos/net/network_diagnostics/network_diagnostics.mojom b/chromium/chrome/browser/chromeos/net/network_diagnostics/network_diagnostics.mojom
deleted file mode 100644
index a001427d1be..00000000000
--- a/chromium/chrome/browser/chromeos/net/network_diagnostics/network_diagnostics.mojom
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2020 The Chromium 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.network_diagnostics.mojom;
-
-// Each routine can result in one of the possible verdicts.
-[Extensible]
-enum RoutineVerdict {
- // Routine ran successfully and no connectivity problem found.
- kNoProblem,
- // Routine ran successfully and connectivity problem found.
- kProblem,
- // Routine has not been run.
- kNotRun,
-};
-
-// Problems related to the SignalStrength routine.
-[Extensible]
-enum SignalStrengthProblem {
- kSignalNotFound,
- kWeakSignal,
-};
-
-// Problems related to the GatewayCanBePinged routine.
-[Extensible]
-enum GatewayCanBePingedProblem {
- // All gateways are unreachable, hence cannot be pinged.
- kUnreachableGateway,
- // The default network cannot be pinged.
- kFailedToPingDefaultNetwork,
- // The default network has a latency above the threshold.
- kDefaultNetworkAboveLatencyThreshold,
- // One or more of the non-default networks has failed pings.
- kUnsuccessfulNonDefaultNetworksPings,
- // One of more of the non-default networks has a latency above the threshold.
- kNonDefaultNetworksAboveLatencyThreshold,
-};
-
-// Messages related to the HasSecureWiFiConnection routine.
-[Extensible]
-enum HasSecureWiFiConnectionProblem {
- kSecurityTypeNone,
- kSecurityTypeWep8021x,
- kSecurityTypeWepPsk,
- kUnknownSecurityType,
-};
-
-// This interface is to be used by any clients that need to run specific
-// network-related diagnostics. Expected clients of this interface are
-// NetworkHealth, cros_healthd, and a connectivity diagnostics Web UI (to name
-// a few). The bound implementation is intended to live in the browser process.
-interface NetworkDiagnosticsRoutines {
- // Tests whether the device is connected to a LAN. It is possible that the
- // device may be trapped in a captive portal yet pass this test successfully.
- // Captive portal checks are done separately and are outside of the scope of
- // this routine.
- LanConnectivity() => (RoutineVerdict verdict);
-
- // Tests whether there is an acceptable signal strength on wireless networks.
- SignalStrength() => (RoutineVerdict verdict,
- array<SignalStrengthProblem> problems);
-
- // Tests whether the gateway of connected networks is pingable.
- GatewayCanBePinged() => (RoutineVerdict verdict,
- array<GatewayCanBePingedProblem> problems);
-
- // Tests whether the WiFi connection is secure. Note that if WiFi is not
- // connected, the routine will result in a |kNotRun| verdict.
- HasSecureWiFiConnection() => (RoutineVerdict verdict,
- array<HasSecureWiFiConnectionProblem> problems);
-};
diff --git a/chromium/chrome/browser/contextmenu/BUILD.gn b/chromium/chrome/browser/contextmenu/BUILD.gn
new file mode 100644
index 00000000000..cf6a8445037
--- /dev/null
+++ b/chromium/chrome/browser/contextmenu/BUILD.gn
@@ -0,0 +1,23 @@
+# Copyright 2020 The Chromium 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")
+import("//chrome/browser/buildflags.gni")
+
+android_library("java") {
+ sources = [
+ "java/src/org/chromium/chrome/browser/contextmenu/ContextMenuItem.java",
+ "java/src/org/chromium/chrome/browser/contextmenu/ContextMenuItemDelegate.java",
+ "java/src/org/chromium/chrome/browser/contextmenu/ContextMenuPopulator.java",
+ ]
+
+ srcjar_deps = [ "//chrome:context_menu_image_format_enum_javagen" ]
+
+ deps = [
+ "//base:base_java",
+ "//components/embedder_support/android:context_menu_java",
+ "//content/public/android:content_java",
+ ]
+}
diff --git a/chromium/chrome/browser/dev_ui_browser_resources.grd b/chromium/chrome/browser/dev_ui_browser_resources.grd
index cad2c93b7b8..f9fd04eb85a 100644
--- a/chromium/chrome/browser/dev_ui_browser_resources.grd
+++ b/chromium/chrome/browser/dev_ui_browser_resources.grd
@@ -18,84 +18,89 @@ This file specifies browser resources for developer-facing chrome:// pages
</outputs>
<release seq="1">
<includes>
- <include name="IDR_ACCESSIBILITY_HTML" file="resources\accessibility\accessibility.html" flattenhtml="true" allowexternalscript="true" compress="gzip" type="BINDATA" />
- <include name="IDR_ACCESSIBILITY_CSS" file="resources\accessibility\accessibility.css" compress="gzip" type="BINDATA" />
- <include name="IDR_ACCESSIBILITY_JS" file="resources\accessibility\accessibility.js" flattenhtml="true" compress="gzip" type="BINDATA" />
- <include name="IDR_COMPONENTS_COMPONENTS_HTML" file="resources\components\components.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_COMPONENTS_COMPONENTS_JS" file="resources\components\components.js" type="BINDATA" compress="gzip" />
- <include name="IDR_DEVICE_LOG_UI_HTML" file="resources\device_log_ui\device_log_ui.html" type="BINDATA" compress="gzip" />
- <include name="IDR_DEVICE_LOG_UI_JS" file="resources\device_log_ui\device_log_ui.js" type="BINDATA" compress="gzip" />
- <include name="IDR_DEVICE_LOG_UI_CSS" file="resources\device_log_ui\device_log_ui.css" type="BINDATA" compress="gzip" />
- <include name="IDR_DOMAIN_RELIABILITY_INTERNALS_HTML" file="resources\domain_reliability_internals\domain_reliability_internals.html" compress="gzip" type="BINDATA" />
- <include name="IDR_DOMAIN_RELIABILITY_INTERNALS_CSS" file="resources\domain_reliability_internals\domain_reliability_internals.css" compress="gzip" type="BINDATA" />
- <include name="IDR_DOMAIN_RELIABILITY_INTERNALS_JS" file="resources\domain_reliability_internals\domain_reliability_internals.js" compress="gzip" type="BINDATA" />
- <include name="IDR_DOWNLOAD_INTERNALS_HTML" file="resources\download_internals\download_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_DOWNLOAD_INTERNALS_CSS" file="resources\download_internals\download_internals.css" type="BINDATA" compress="gzip" />
- <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_INTERVENTIONS_INTERNALS_INDEX_HTML" file="resources\interventions_internals\index.html" flattenhtml="true" allowexternalscript="true" compress="gzip" type="BINDATA" />
- <include name="IDR_INTERVENTIONS_INTERNALS_INDEX_JS" file="resources\interventions_internals\index.js" type="BINDATA" compress="gzip" />
- <include name="IDR_INTERVENTIONS_INTERNALS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\interventions_internals\interventions_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_INTERVENTIONS_INTERNALS_UNSUPPORTED_PAGE_HTML" file="resources\interventions_internals\unsupported_page.html" flattenhtml="true" allowexternalscript="true" compress="gzip" type="BINDATA" />
- <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_MEDIA_DATA_TABLE_JS" file="resources\media\media_data_table.js" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_MEDIA_ENGAGEMENT_HTML" file="resources\media\media_engagement.html" flattenhtml="true" type="BINDATA" compress="gzip" allowexternalscript="true" />
- <include name="IDR_MEDIA_ENGAGEMENT_JS" file="resources\media\media_engagement.js" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_MEDIA_ENGAGEMENT_SCORE_DETAILS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\media\media_engagement_score_details.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_MEDIA_FEEDS_HTML" file="resources\media\media_feeds.html" flattenhtml="true" type="BINDATA" compress="gzip" allowexternalscript="true" />
- <include name="IDR_MEDIA_FEEDS_JS" file="resources\media\media_feeds.js" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_MEDIA_FEEDS_STORE_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\media\feeds\media_feeds_store.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_MEDIA_HISTORY_HTML" file="resources\media\media_history.html" flattenhtml="true" type="BINDATA" compress="gzip" allowexternalscript="true" />
- <include name="IDR_MEDIA_HISTORY_JS" file="resources\media\media_history.js" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_MEDIA_HISTORY_STORE_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\media\history\media_history_store.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_MEMORY_INTERNALS_HTML" file="resources\memory_internals\memory_internals.html" type="BINDATA" compress="gzip" />
- <include name="IDR_MEMORY_INTERNALS_JS" file="resources\memory_internals\memory_internals.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_PREDICTORS_HTML" file="resources\predictors\predictors.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_PREDICTORS_JS" file="resources\predictors\predictors.js" flattenhtml="true" type="BINDATA" compress="gzip" />
- <include name="IDR_MEDIA_SESSION_MOJOM_LITE_JS" file="${root_gen_dir}\services\media_session\public\mojom\media_session.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_UI_GEOMETRY_MOJOM_LITE_JS" file="${root_gen_dir}\ui\gfx\geometry\mojom\geometry.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
+ <include name="IDR_ACCESSIBILITY_HTML" file="resources\accessibility\accessibility.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_ACCESSIBILITY_CSS" file="resources\accessibility\accessibility.css" type="BINDATA" />
+ <include name="IDR_ACCESSIBILITY_JS" file="resources\accessibility\accessibility.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_COMPONENTS_COMPONENTS_HTML" file="resources\components\components.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_COMPONENTS_COMPONENTS_JS" file="resources\components\components.js" type="BINDATA" />
+ <include name="IDR_DEVICE_LOG_UI_HTML" file="resources\device_log_ui\device_log_ui.html" type="BINDATA" />
+ <include name="IDR_DEVICE_LOG_UI_JS" file="resources\device_log_ui\device_log_ui.js" type="BINDATA" />
+ <include name="IDR_DEVICE_LOG_UI_CSS" file="resources\device_log_ui\device_log_ui.css" type="BINDATA" />
+ <include name="IDR_DOMAIN_RELIABILITY_INTERNALS_HTML" file="resources\domain_reliability_internals\domain_reliability_internals.html" type="BINDATA" />
+ <include name="IDR_DOMAIN_RELIABILITY_INTERNALS_CSS" file="resources\domain_reliability_internals\domain_reliability_internals.css" type="BINDATA" />
+ <include name="IDR_DOMAIN_RELIABILITY_INTERNALS_JS" file="resources\domain_reliability_internals\domain_reliability_internals.js" type="BINDATA" />
+ <include name="IDR_DOWNLOAD_INTERNALS_HTML" file="resources\download_internals\download_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_DOWNLOAD_INTERNALS_CSS" file="resources\download_internals\download_internals.css" type="BINDATA" />
+ <include name="IDR_DOWNLOAD_INTERNALS_JS" file="resources\download_internals\download_internals.js" type="BINDATA" />
+ <include name="IDR_DOWNLOAD_INTERNALS_BROWSER_PROXY_JS" file="resources\download_internals\download_internals_browser_proxy.js" type="BINDATA" />
+ <include name="IDR_DOWNLOAD_INTERNALS_VISUALS_JS" file="resources\download_internals\download_internals_visuals.js" type="BINDATA" />
+ <include name="IDR_INTERVENTIONS_INTERNALS_INDEX_HTML" file="resources\interventions_internals\index.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_INTERVENTIONS_INTERNALS_INDEX_JS" file="resources\interventions_internals\index.js" type="BINDATA" />
+ <include name="IDR_INTERVENTIONS_INTERNALS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\interventions_internals\interventions_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_INTERVENTIONS_INTERNALS_UNSUPPORTED_PAGE_HTML" file="resources\interventions_internals\unsupported_page.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_LOCAL_STATE_HTML" file="resources\local_state\local_state.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_LOCAL_STATE_JS" file="resources\local_state\local_state.js" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_MEDIA_DATA_TABLE_JS" file="resources\media\media_data_table.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_MEDIA_ENGAGEMENT_HTML" file="resources\media\media_engagement.html" flattenhtml="true" type="BINDATA" allowexternalscript="true" />
+ <include name="IDR_MEDIA_ENGAGEMENT_JS" file="resources\media\media_engagement.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_MEDIA_ENGAGEMENT_SCORE_DETAILS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\media\media_engagement_score_details.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_MEDIA_FEEDS_HTML" file="resources\media\media_feeds.html" flattenhtml="true" type="BINDATA" allowexternalscript="true" />
+ <include name="IDR_MEDIA_FEEDS_JS" file="resources\media\media_feeds.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_MEDIA_FEEDS_STORE_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\media\feeds\media_feeds_store.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_MEDIA_HISTORY_HTML" file="resources\media\media_history.html" flattenhtml="true" type="BINDATA" allowexternalscript="true" />
+ <include name="IDR_MEDIA_HISTORY_JS" file="resources\media\media_history.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_MEDIA_HISTORY_STORE_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\media\history\media_history_store.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_MEMORY_INTERNALS_HTML" file="resources\memory_internals\memory_internals.html" type="BINDATA" />
+ <include name="IDR_MEMORY_INTERNALS_JS" file="resources\memory_internals\memory_internals.js" type="BINDATA" />
+ <include name="IDR_NOTIFICATIONS_INTERNALS_HTML" file="resources\notifications_internals\notifications_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_NOTIFICATIONS_INTERNALS_CSS" file="resources\notifications_internals\notifications_internals.css" type="BINDATA" />
+ <include name="IDR_NOTIFICATIONS_INTERNALS_JS" file="resources\notifications_internals\notifications_internals.js" type="BINDATA" />
+ <include name="IDR_NOTIFICATIONS_INTERNALS_BROWSER_PROXY_JS" file="resources\notifications_internals\notifications_internals_browser_proxy.js" type="BINDATA" />
+ <include name="IDR_PREDICTORS_HTML" file="resources\predictors\predictors.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_PREDICTORS_JS" file="resources\predictors\predictors.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_MEDIA_SESSION_MOJOM_LITE_JS" file="${root_gen_dir}\services\media_session\public\mojom\media_session.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_UI_GEOMETRY_MOJOM_LITE_JS" file="${root_gen_dir}\ui\gfx\geometry\mojom\geometry.mojom-lite.js" 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" />
- <include name="IDR_SANDBOX_INTERNALS_JS" file="resources\sandbox_internals\sandbox_internals.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_SANDBOX_INTERNALS_HTML" file="resources\sandbox_internals\sandbox_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_SANDBOX_INTERNALS_JS" file="resources\sandbox_internals\sandbox_internals.js" type="BINDATA" />
</if>
<if expr="is_win">
- <include name="IDR_SANDBOX_INTERNALS_HTML" file="resources\sandbox_internals\sandbox_internals.html" preprocess="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_SANDBOX_INTERNALS_JS" file="resources\sandbox_internals\sandbox_internals_win.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_SANDBOX_INTERNALS_HTML" file="resources\sandbox_internals\sandbox_internals.html" preprocess="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_SANDBOX_INTERNALS_JS" file="resources\sandbox_internals\sandbox_internals_win.js" type="BINDATA" />
</if>
- <include name="IDR_SITE_ENGAGEMENT_HTML" file="resources\engagement\site_engagement.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <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_SITE_ENGAGEMENT_HTML" file="resources\engagement\site_engagement.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_SITE_ENGAGEMENT_JS" file="resources\engagement\site_engagement.js" flattenhtml="true" type="BINDATA" />
+ <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" />
<if expr="is_android">
- <include name="IDR_FEED_INTERNALS_HTML" file="resources\feed_internals\feed_internals.html" allowexternalscript="true" compress="gzip" type="BINDATA" />
- <include name="IDR_FEED_INTERNALS_CSS" file="resources\feed_internals\feed_internals.css" allowexternalscript="true" compress="gzip" type="BINDATA" />
- <include name="IDR_FEED_INTERNALS_JS" file="resources\feed_internals\feed_internals.js" compress="gzip" type="BINDATA" />
- <include name="IDR_FEED_INTERNALS_MOJO_JS" file="${root_gen_dir}\chrome\browser\ui\webui\feed_internals\feed_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
- <include name="IDR_SNIPPETS_INTERNALS_HTML" file="resources\snippets_internals\snippets_internals.html" allowexternalscript="true" compress="gzip" type="BINDATA" />
- <include name="IDR_SNIPPETS_INTERNALS_CSS" file="resources\snippets_internals\snippets_internals.css" compress="gzip" type="BINDATA" />
- <include name="IDR_SNIPPETS_INTERNALS_JS" file="resources\snippets_internals\snippets_internals.js" compress="gzip" type="BINDATA" />
- <include name="IDR_SNIPPETS_INTERNALS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\snippets_internals\snippets_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
+ <include name="IDR_FEED_INTERNALS_HTML" file="resources\feed_internals\feed_internals.html" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_FEED_INTERNALS_CSS" file="resources\feed_internals\feed_internals.css" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_FEED_INTERNALS_JS" file="resources\feed_internals\feed_internals.js" type="BINDATA" />
+ <include name="IDR_FEED_INTERNALS_MOJO_JS" file="${root_gen_dir}\chrome\browser\ui\webui\feed_internals\feed_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_QUERY_TILES_INTERNALS_HTML" file="resources\internals\query_tiles\query_tiles_internals.html" type="BINDATA" />
+ <include name="IDR_QUERY_TILES_INTERNALS_JS" file="resources\internals\query_tiles\query_tiles_internals.js" type="BINDATA" />
+ <include name="IDR_QUERY_TILES_INTERNALS_BROWSER_PROXY_JS" file="resources\internals\query_tiles\query_tiles_internals_browser_proxy.js" type="BINDATA" />
+ <include name="IDR_SNIPPETS_INTERNALS_HTML" file="resources\snippets_internals\snippets_internals.html" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_SNIPPETS_INTERNALS_CSS" file="resources\snippets_internals\snippets_internals.css" type="BINDATA" />
+ <include name="IDR_SNIPPETS_INTERNALS_JS" file="resources\snippets_internals\snippets_internals.js" type="BINDATA" />
+ <include name="IDR_SNIPPETS_INTERNALS_MOJOM_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\snippets_internals\snippets_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" />
</if>
<if expr="enable_supervised_users">
- <include name="IDR_SUPERVISED_USER_INTERNALS_HTML" file="resources\supervised_user_internals\supervised_user_internals.html" allowexternalscript="true" compress="gzip" type="BINDATA" />
- <include name="IDR_SUPERVISED_USER_INTERNALS_CSS" file="resources\supervised_user_internals\supervised_user_internals.css" compress="gzip" type="BINDATA" />
- <include name="IDR_SUPERVISED_USER_INTERNALS_JS" file="resources\supervised_user_internals\supervised_user_internals.js" compress="gzip" type="BINDATA" />
+ <include name="IDR_SUPERVISED_USER_INTERNALS_HTML" file="resources\supervised_user_internals\supervised_user_internals.html" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_SUPERVISED_USER_INTERNALS_CSS" file="resources\supervised_user_internals\supervised_user_internals.css" type="BINDATA" />
+ <include name="IDR_SUPERVISED_USER_INTERNALS_JS" file="resources\supervised_user_internals\supervised_user_internals.js" type="BINDATA" />
</if>
-
<include name="IDR_TRANSLATE_INTERNALS_HTML" file="../../components/translate/translate_internals/translate_internals.html" flattenhtml="true" allowexternalscript="true" compress="gzip" type="BINDATA" />
<include name="IDR_TRANSLATE_INTERNALS_JS" file="../../components/translate/translate_internals/translate_internals.js" flattenhtml="true" compress="gzip" type="BINDATA" />
- <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" />
+ <include name="IDR_WEB_APP_INTERNALS_HTML" file="resources/web_app_internals/index.html" type="BINDATA" />
+ <include name="IDR_WEB_APP_INTERNALS_JS" file="${root_gen_dir}/chrome/browser/resources/web_app_internals/web_app_internals.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_WEB_APP_INTERNALS_MOJOM_LITE_JS" file="${root_gen_dir}/chrome/browser/ui/webui/internals/web_app/web_app_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" />
+ <include name="IDR_UKM_INTERNALS_HTML" file="../../components/ukm/debug/ukm_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_UKM_INTERNALS_JS" file="../../components/ukm/debug/ukm_internals.js" flattenhtml="true" type="BINDATA" />
+ <include name="IDR_UKM_INTERNALS_CSS" file="../../components/ukm/debug/ukm_internals.css" flattenhtml="true" type="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/devtools/BUILD.gn b/chromium/chrome/browser/devtools/BUILD.gn
index e094572221e..7a6188b2df4 100644
--- a/chromium/chrome/browser/devtools/BUILD.gn
+++ b/chromium/chrome/browser/devtools/BUILD.gn
@@ -92,6 +92,15 @@ static_library("devtools") {
deps = [
"//base",
+
+ # To prevent circular GN dependencies, this target does not depend on
+ # //chrome/browser:browser, even though it has a real build dependency on
+ # it. However, depending on the order in which this target and
+ # //chrome/browser:browser are built it's possible that the connectors
+ # proto header (which //chrome/browser:browser depends on) is not generated
+ # yet causing devtools not to compile. Adding this indirect dependency to
+ # the proto to fix that.
+ "//components/enterprise/common/proto:connectors_proto",
"//content/public/browser",
"//net",
"//services/viz/privileged/mojom/compositing",
diff --git a/chromium/chrome/browser/devtools/device/adb/adb_client_socket_browsertest.cc b/chromium/chrome/browser/devtools/device/adb/adb_client_socket_browsertest.cc
index c0bcc02d0c2..b425918e39d 100644
--- a/chromium/chrome/browser/devtools/device/adb/adb_client_socket_browsertest.cc
+++ b/chromium/chrome/browser/devtools/device/adb/adb_client_socket_browsertest.cc
@@ -3,7 +3,6 @@
// found in the LICENSE file.
#include "base/run_loop.h"
-#include "base/logging.h"
#include "chrome/browser/devtools/device/adb/adb_device_provider.h"
#include "chrome/browser/devtools/device/adb/mock_adb_server.h"
#include "chrome/browser/devtools/device/devtools_android_bridge.h"
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 816aebdd877..489f125562d 100644
--- a/chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc
+++ b/chromium/chrome/browser/devtools/device/adb/mock_adb_server.cc
@@ -18,7 +18,6 @@
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
-#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
@@ -651,17 +650,16 @@ void MockAndroidConnection::SendHTTPResponse(const std::string& body) {
void StartMockAdbServer(FlushMode flush_mode) {
base::RunLoop run_loop;
- base::PostTaskAndReply(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&StartMockAdbServerOnIOThread, flush_mode),
+ content::GetIOThreadTaskRunner({})->PostTaskAndReply(
+ FROM_HERE, base::BindOnce(&StartMockAdbServerOnIOThread, flush_mode),
run_loop.QuitClosure());
run_loop.Run();
}
void StopMockAdbServer() {
base::RunLoop run_loop;
- base::PostTaskAndReply(FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&StopMockAdbServerOnIOThread),
- run_loop.QuitClosure());
+ content::GetIOThreadTaskRunner({})->PostTaskAndReply(
+ FROM_HERE, base::BindOnce(&StopMockAdbServerOnIOThread),
+ run_loop.QuitClosure());
run_loop.Run();
}
diff --git a/chromium/chrome/browser/devtools/device/android_device_manager.cc b/chromium/chrome/browser/devtools/device/android_device_manager.cc
index 02a50e12c56..e3716a6f5da 100644
--- a/chromium/chrome/browser/devtools/device/android_device_manager.cc
+++ b/chromium/chrome/browser/devtools/device/android_device_manager.cc
@@ -17,7 +17,6 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/threading/thread.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -382,8 +381,8 @@ class DevicesRequest : public base::RefCountedThreadSafe<DevicesRequest> {
void OnCountDevices(const base::Callback<void(int)>& callback,
int device_count) {
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(callback, device_count));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(callback, device_count));
}
} // namespace
diff --git a/chromium/chrome/browser/devtools/device/cast_device_provider.cc b/chromium/chrome/browser/devtools/device/cast_device_provider.cc
index 8cae795aa7e..553d95dab45 100644
--- a/chromium/chrome/browser/devtools/device/cast_device_provider.cc
+++ b/chromium/chrome/browser/devtools/device/cast_device_provider.cc
@@ -14,7 +14,6 @@
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
-#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/local_discovery/service_discovery_shared_client.h"
#include "content/public/browser/browser_task_traits.h"
@@ -156,8 +155,8 @@ void CastDeviceProvider::QueryDevices(const SerialsCallback& callback) {
if (!lister_delegate_) {
lister_delegate_.reset(new DeviceListerDelegate(
weak_factory_.GetWeakPtr(), base::ThreadTaskRunnerHandle::Get()));
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&DeviceListerDelegate::StartDiscovery,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&DeviceListerDelegate::StartDiscovery,
lister_delegate_->AsWeakPtr()));
}
std::set<net::HostPortPair> targets;
diff --git a/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc b/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc
index 952af2c6614..bd3cefdedef 100644
--- a/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc
+++ b/chromium/chrome/browser/devtools/device/devtools_device_discovery.cc
@@ -16,7 +16,6 @@
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "base/values.h"
#include "chrome/browser/devtools/devtools_window.h"
#include "content/public/browser/browser_task_traits.h"
@@ -46,8 +45,8 @@ const char kPageReloadCommand[] = "{'method': 'Page.reload', id: 1}";
const char kWebViewSocketPrefix[] = "webview_devtools_remote";
static void ScheduleTaskDefault(const base::Closure& task) {
- base::PostDelayedTask(FROM_HERE, {BrowserThread::UI}, task,
- base::TimeDelta::FromMilliseconds(kPollingIntervalMs));
+ content::GetUIThreadTaskRunner({})->PostDelayedTask(
+ FROM_HERE, task, base::TimeDelta::FromMilliseconds(kPollingIntervalMs));
}
// ProtocolCommand ------------------------------------------------------------
diff --git a/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc b/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc
index 65421861737..3b54c9d9c5c 100644
--- a/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc
+++ b/chromium/chrome/browser/devtools/device/port_forwarding_controller.cc
@@ -17,7 +17,6 @@
#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"
@@ -236,8 +235,8 @@ class SocketTunnel {
adb_thread_runner_(base::ThreadTaskRunnerHandle::Get()) {
ResolveHostCallback resolve_host_callback = base::BindOnce(
&SocketTunnel::OnResolveHostComplete, base::Unretained(this));
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&ResolveHost, profile, host, port,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&ResolveHost, profile, host, port,
std::move(resolve_host_callback)));
}
@@ -495,9 +494,6 @@ void PortForwardingController::Connection::SendCommand(
pending_responses_[id] =
base::Bind(&Connection::ProcessBindResponse,
base::Unretained(this), port);
-#if BUILDFLAG(DEBUG_DEVTOOLS)
- port_status_[port] = kStatusConnecting;
-#endif // BUILDFLAG(DEBUG_DEVTOOLS)
} else {
auto it = port_status_.find(port);
if (it != port_status_.end() && it->second == kStatusError) {
@@ -509,9 +505,6 @@ void PortForwardingController::Connection::SendCommand(
pending_responses_[id] =
base::Bind(&Connection::ProcessUnbindResponse,
base::Unretained(this), port);
-#if BUILDFLAG(DEBUG_DEVTOOLS)
- port_status_[port] = kStatusDisconnecting;
-#endif // BUILDFLAG(DEBUG_DEVTOOLS)
}
web_socket_->SendFrame(SerializeCommand(id, method, std::move(params)));
diff --git a/chromium/chrome/browser/devtools/device/tcp_device_provider.cc b/chromium/chrome/browser/devtools/device/tcp_device_provider.cc
index 52c3216c503..d1634123e61 100644
--- a/chromium/chrome/browser/devtools/device/tcp_device_provider.cc
+++ b/chromium/chrome/browser/devtools/device/tcp_device_provider.cc
@@ -12,12 +12,12 @@
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
-#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/devtools/device/adb/adb_client_socket.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "content/public/browser/browser_task_traits.h"
+#include "content/public/browser/browser_thread.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "net/base/completion_repeating_callback.h"
#include "net/base/net_errors.h"
@@ -47,8 +47,8 @@ class ResolveHostAndOpenSocket final : public network::ResolveHostClientBase {
const AdbClientSocket::SocketCallback& callback)
: callback_(callback) {
mojo::Remote<network::mojom::HostResolver> resolver;
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(
[](mojo::PendingReceiver<network::mojom::HostResolver>
pending_receiver) {
g_browser_process->system_network_context_manager()
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 6d38d17048b..f5bede887f1 100644
--- a/chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc
+++ b/chromium/chrome/browser/devtools/device/usb/android_usb_browsertest.cc
@@ -17,7 +17,6 @@
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/devtools/device/adb/mock_adb_server.h"
#include "chrome/browser/devtools/device/devtools_android_bridge.h"
@@ -527,7 +526,7 @@ class AndroidUsbDiscoveryTest : public InProcessBrowserTest {
void ScheduleDeviceCountRequest(const base::Closure& request) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
scheduler_invoked_++;
- base::PostTask(FROM_HERE, {BrowserThread::UI}, request);
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, request);
}
virtual std::unique_ptr<FakeUsbDeviceManager> CreateFakeUsbManager() {
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 fcc10845fc9..a6452ed6bf9 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
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/device_service.h"
@@ -193,8 +192,8 @@ void UsbDeviceManagerHelper::EnsureUsbDeviceManagerConnection() {
return;
}
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&BindDeviceServiceOnUIThread,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&BindDeviceServiceOnUIThread,
device_manager_.BindNewPipeAndPassReceiver()));
device_manager_.set_disconnect_handler(
diff --git a/chromium/chrome/browser/devtools/devtools_browser_context_manager.cc b/chromium/chrome/browser/devtools/devtools_browser_context_manager.cc
index cc6da5ee753..3974183c25b 100644
--- a/chromium/chrome/browser/devtools/devtools_browser_context_manager.cc
+++ b/chromium/chrome/browser/devtools/devtools_browser_context_manager.cc
@@ -35,7 +35,7 @@ content::BrowserContext* DevToolsBrowserContextManager::CreateBrowserContext() {
ProfileManager::GetActiveUserProfile()->GetOriginalProfile();
Profile* otr_profile = original_profile->GetOffTheRecordProfile(
- Profile::OTRProfileID::CreateUnique("Devtools::BrowserContext"));
+ Profile::OTRProfileID::CreateUniqueForDevTools());
const std::string& context_id = otr_profile->UniqueId();
otr_profiles_[context_id] = otr_profile;
otr_profile->AddObserver(this);
diff --git a/chromium/chrome/browser/devtools/devtools_file_helper.cc b/chromium/chrome/browser/devtools/devtools_file_helper.cc
index 1b441f5cc4d..98ab93a0e0b 100644
--- a/chromium/chrome/browser/devtools/devtools_file_helper.cc
+++ b/chromium/chrome/browser/devtools/devtools_file_helper.cc
@@ -17,7 +17,7 @@
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/threading/sequenced_task_runner_handle.h"
-#include "base/value_conversions.h"
+#include "base/util/values/values_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/devtools/devtools_file_watcher.h"
#include "chrome/browser/download/download_prefs.h"
@@ -245,9 +245,9 @@ void DevToolsFileHelper::Save(const std::string& url,
const base::Value* path_value;
if (file_map->Get(base::MD5String(url), &path_value)) {
- // Ignore base::GetValueAsFilePath() failure since we handle empty
- // |initial_path| below.
- ignore_result(base::GetValueAsFilePath(*path_value, &initial_path));
+ base::Optional<base::FilePath> path = util::ValueToFilePath(*path_value);
+ if (path)
+ initial_path = std::move(*path);
}
if (initial_path.empty()) {
@@ -301,7 +301,7 @@ void DevToolsFileHelper::SaveAsFileSelected(const std::string& url,
DictionaryPrefUpdate update(profile_->GetPrefs(),
prefs::kDevToolsEditedFiles);
base::DictionaryValue* files_map = update.Get();
- files_map->SetKey(base::MD5String(url), base::CreateFilePathValue(path));
+ files_map->SetKey(base::MD5String(url), util::FilePathToValue(path));
std::string file_system_path = path.AsUTF8Unsafe();
callback.Run(file_system_path);
file_task_runner_->PostTask(FROM_HERE, BindOnce(&WriteToFile, path, content));
diff --git a/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc b/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc
index 0f7479de0c5..542b35f637d 100644
--- a/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc
+++ b/chromium/chrome/browser/devtools/devtools_file_system_indexer.cc
@@ -20,7 +20,6 @@
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/lazy_thread_pool_task_runner.h"
-#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
@@ -322,8 +321,8 @@ void DevToolsFileSystemIndexer::FileSystemIndexingJob::CollectFilesToIndex() {
}
if (file_path.empty()) {
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- BindOnce(total_work_callback_, file_path_times_.size()));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, BindOnce(total_work_callback_, file_path_times_.size()));
indexing_it_ = file_path_times_.begin();
IndexFiles();
return;
@@ -359,7 +358,7 @@ void DevToolsFileSystemIndexer::FileSystemIndexingJob::IndexFiles() {
return;
if (indexing_it_ == file_path_times_.end()) {
g_trigram_index.Get().NormalizeVectors();
- base::PostTask(FROM_HERE, {BrowserThread::UI}, done_callback_);
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, done_callback_);
return;
}
FilePath file_path = indexing_it_->first;
@@ -451,8 +450,8 @@ void DevToolsFileSystemIndexer::FileSystemIndexingJob::ReportWorked() {
++files_indexed_;
if (should_send_worked_nitification) {
last_worked_notification_time_ = current_time;
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- BindOnce(worked_callback_, files_indexed_));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, BindOnce(worked_callback_, files_indexed_));
files_indexed_ = 0;
}
}
@@ -515,6 +514,6 @@ void DevToolsFileSystemIndexer::SearchInPathOnImplSequence(
if (path.IsParent(*it))
result.push_back(it->AsUTF8Unsafe());
}
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- BindOnce(callback, std::move(result)));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, BindOnce(callback, std::move(result)));
}
diff --git a/chromium/chrome/browser/devtools/devtools_file_watcher_unittest.cc b/chromium/chrome/browser/devtools/devtools_file_watcher_unittest.cc
index b40aa6978a9..a67aa887196 100644
--- a/chromium/chrome/browser/devtools/devtools_file_watcher_unittest.cc
+++ b/chromium/chrome/browser/devtools/devtools_file_watcher_unittest.cc
@@ -71,7 +71,7 @@ TEST_F(DevToolsFileWatcherTest, BasicUsage) {
}
expected_removed_paths_.insert(added_path.AsUTF8Unsafe());
- base::DeleteFile(added_path, false);
+ base::DeleteFile(added_path);
while (!expected_removed_paths_.empty()) {
task_environment_.RunUntilIdle();
base::PlatformThread::Sleep(TestTimeouts::tiny_timeout());
diff --git a/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc b/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc
index 86d3a035d4e..53722ab2dbd 100644
--- a/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc
+++ b/chromium/chrome/browser/devtools/devtools_sanity_browsertest.cc
@@ -24,7 +24,6 @@
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_restrictions.h"
@@ -37,6 +36,7 @@
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_service.h"
+#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/unpacked_installer.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/lifetime/browser_shutdown.h"
@@ -114,7 +114,6 @@
#include "chromeos/constants/chromeos_switches.h"
#endif
-using content::BrowserThread;
using content::DevToolsAgentHost;
using content::DevToolsAgentHostObserver;
using content::NavigationController;
@@ -217,7 +216,7 @@ void SwitchToExtensionPanel(DevToolsWindow* window,
class DevToolsSanityTest : public InProcessBrowserTest {
public:
- DevToolsSanityTest() : window_(NULL) {}
+ DevToolsSanityTest() : window_(nullptr) {}
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
@@ -258,6 +257,14 @@ class DevToolsSanityTest : public InProcessBrowserTest {
is_docked);
}
+ void OpenDevToolsWindowOnOffTheRecordTab(const std::string& test_page) {
+ GURL url = spawned_test_server()->GetURL("").Resolve(test_page);
+ auto* otr_browser = OpenURLOffTheRecord(browser()->profile(), url);
+
+ window_ = DevToolsWindowTesting::OpenDevToolsWindowSync(
+ otr_browser->tab_strip_model()->GetWebContentsAt(0), false);
+ }
+
WebContents* GetInspectedTab() {
return browser()->tab_strip_model()->GetWebContentsAt(0);
}
@@ -611,7 +618,7 @@ class DevToolsExperimentalExtensionTest : public DevToolsExtensionTest {
class WorkerDevToolsSanityTest : public InProcessBrowserTest {
public:
- WorkerDevToolsSanityTest() : window_(NULL) {}
+ WorkerDevToolsSanityTest() : window_(nullptr) {}
protected:
class WorkerCreationObserver : public DevToolsAgentHostObserver {
@@ -632,7 +639,7 @@ class WorkerDevToolsSanityTest : public InProcessBrowserTest {
if (host->GetType() == DevToolsAgentHost::kTypeSharedWorker &&
host->GetURL().path().rfind(path_) != std::string::npos) {
*out_host_ = host;
- base::PostTask(FROM_HERE, {BrowserThread::UI}, quit_);
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, quit_);
delete this;
}
}
@@ -854,6 +861,25 @@ IN_PROC_BROWSER_TEST_F(DevToolsExtensionTest,
RunTest("waitForTestResultsInConsole", std::string());
}
+// Tests that chrome.devtools extension is correctly exposed.
+IN_PROC_BROWSER_TEST_F(DevToolsExtensionTest, TestExtensionOnNewTab) {
+ // Not really required by this test, but the underlying code happens
+ // to expect it.
+ ASSERT_TRUE(embedded_test_server()->Start());
+ // Install the dynamically-generated devtools extension.
+ const Extension* devtools_extension = LoadExtensionForTest(
+ "Devtools Extension", "panel_devtools_page.html", "");
+ ASSERT_TRUE(devtools_extension);
+ extensions::util::SetIsIncognitoEnabled(devtools_extension->id(),
+ browser()->profile(), true);
+
+ OpenDevToolsWindowOnOffTheRecordTab(chrome::kChromeUINewTabURL);
+
+ // Wait for the extension's panel to finish loading -- it'll output 'PASS'
+ // when it's installed. waitForTestResultsInConsole waits until that 'PASS'.
+ RunTestFunction(window_, "waitForTestResultsInConsole");
+}
+
// Tests that http Iframes within the visible devtools panel for the devtools
// extension are rendered in their own processes and not in the devtools process
// or the extension's process. This is tested because this is one of the
@@ -1115,8 +1141,9 @@ IN_PROC_BROWSER_TEST_F(DevToolsExtensionTest,
// Tests that iframes to a non-devtools extension embedded in a devtools
// extension will be isolated from devtools and the devtools extension.
// http://crbug.com/570483
+// Disabled due to flakiness https://crbug.com/1062802
IN_PROC_BROWSER_TEST_F(DevToolsExtensionTest,
- NonDevToolsExtensionInDevToolsExtension) {
+ DISABLED_NonDevToolsExtensionInDevToolsExtension) {
ASSERT_TRUE(embedded_test_server()->Start());
// Install the dynamically-generated non-devtools extension.
@@ -1510,8 +1537,13 @@ IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
-IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
- TestPauseWhenLoadingDevTools) {
+// Flaky on win and linux: crbug.com/1092924.
+#if defined(OS_WIN) || defined(OS_LINUX)
+#define MAYBE_TestPauseWhenLoadingDevTools DISABLED_TestPauseWhenLoadingDevTools
+#else
+#define MAYBE_TestPauseWhenLoadingDevTools TestPauseWhenLoadingDevTools
+#endif
+IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
@@ -1600,7 +1632,13 @@ IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkPushTime) {
CloseDevToolsWindow();
}
-IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDOMWarnings) {
+#if defined(OS_WIN)
+// Flaky on Windows: https://crbug.com/1087320
+#define MAYBE_TestDOMWarnings DISABLED_TestDOMWarnings
+#else
+#define MAYBE_TestDOMWarnings TestDOMWarnings
+#endif
+IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestDOMWarnings) {
RunTest("testDOMWarnings", kDOMWarningsTestPage);
}
@@ -1687,6 +1725,14 @@ IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, testKeyEventUnhandled) {
CloseDevToolsWindow();
}
+// Tests that the keys that are forwarded from the browser update
+// when their shortcuts change
+IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, testForwardedKeysChanged) {
+ OpenDevToolsWindow("about:blank", true);
+ RunTestFunction(window_, "testForwardedKeysChanged");
+ CloseDevToolsWindow();
+}
+
// Test that showing a certificate in devtools does not crash the process.
// Disabled on windows as this opens a modal in its own thread, which leads to a
// test timeout.
diff --git a/chromium/chrome/browser/devtools/devtools_ui_bindings.cc b/chromium/chrome/browser/devtools/devtools_ui_bindings.cc
index 3af6ba32420..7986d2e6ecb 100644
--- a/chromium/chrome/browser/devtools/devtools_ui_bindings.cc
+++ b/chromium/chrome/browser/devtools/devtools_ui_bindings.cc
@@ -103,6 +103,10 @@ static const char kDevToolsKeyboardShortcutFiredHistogram[] =
"DevTools.KeyboardShortcutFired";
static const char kDevToolsIssuesPanelOpenedFromHistogram[] =
"DevTools.IssuesPanelOpenedFrom";
+static const char kDevToolsKeybindSetSettingChanged[] =
+ "DevTools.KeybindSetSettingChanged";
+static const char kDevToolsDualScreenDeviceEmulatedHistogram[] =
+ "DevTools.DualScreenDeviceEmulated";
static const char kRemotePageActionInspect[] = "inspect";
static const char kRemotePageActionReload[] = "reload";
@@ -1237,13 +1241,17 @@ void DevToolsUIBindings::RecordEnumeratedHistogram(const std::string& name,
// Each histogram name must follow a different code path in
// order to UMA_HISTOGRAM_EXACT_LINEAR work correctly.
if (name == kDevToolsActionTakenHistogram)
- UMA_HISTOGRAM_EXACT_LINEAR(name, sample, boundary_value);
+ base::UmaHistogramExactLinear(name, sample, boundary_value);
else if (name == kDevToolsPanelShownHistogram)
- UMA_HISTOGRAM_EXACT_LINEAR(name, sample, boundary_value);
+ base::UmaHistogramExactLinear(name, sample, boundary_value);
else if (name == kDevToolsKeyboardShortcutFiredHistogram)
- UMA_HISTOGRAM_EXACT_LINEAR(name, sample, boundary_value);
+ base::UmaHistogramExactLinear(name, sample, boundary_value);
else if (name == kDevToolsIssuesPanelOpenedFromHistogram)
- UMA_HISTOGRAM_EXACT_LINEAR(name, sample, boundary_value);
+ base::UmaHistogramExactLinear(name, sample, boundary_value);
+ else if (name == kDevToolsKeybindSetSettingChanged)
+ base::UmaHistogramExactLinear(name, sample, boundary_value);
+ else if (name == kDevToolsDualScreenDeviceEmulatedHistogram)
+ base::UmaHistogramExactLinear(name, sample, boundary_value);
else
frontend_host_->BadMessageRecieved();
}
@@ -1551,12 +1559,7 @@ void DevToolsUIBindings::ReadyToCommitNavigation(
}
void DevToolsUIBindings::DocumentOnLoadCompletedInMainFrame() {
- // In the DEBUG_DEVTOOLS mode, the DocumentOnLoadCompletedInMainFrame event
- // arrives before the LoadCompleted event, thus it should not trigger the
- // frontend load handling.
-#if !BUILDFLAG(DEBUG_DEVTOOLS)
FrontendLoaded();
-#endif
}
void DevToolsUIBindings::DidNavigateMainFrame() {
diff --git a/chromium/chrome/browser/devtools/devtools_window.cc b/chromium/chrome/browser/devtools/devtools_window.cc
index 817fd22ff31..f85ed231165 100644
--- a/chromium/chrome/browser/devtools/devtools_window.cc
+++ b/chromium/chrome/browser/devtools/devtools_window.cc
@@ -37,7 +37,6 @@
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "components/javascript_dialogs/app_modal_dialog_manager.h"
-#include "components/performance_manager/embedder/performance_manager_registry.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/sessions/content/session_tab_helper.h"
@@ -170,7 +169,7 @@ content::WebContents* DevToolsToolboxDelegate::OpenURLFromTab(
const content::OpenURLParams& params) {
DCHECK(source == web_contents());
if (!params.url.SchemeIs(content::kChromeDevToolsScheme))
- return NULL;
+ return nullptr;
source->GetController().LoadURLWithParams(
content::NavigationController::LoadURLParams(params));
return source;
@@ -205,12 +204,12 @@ BrowserWindow* DevToolsToolboxDelegate::GetInspectedBrowserWindow() {
WebContents* inspected_contents =
inspected_contents_observer_->web_contents();
if (!inspected_contents)
- return NULL;
- Browser* browser = NULL;
+ return nullptr;
+ Browser* browser = nullptr;
int tab = 0;
if (FindInspectedBrowserAndTabIndex(inspected_contents, &browser, &tab))
return browser->window();
- return NULL;
+ return nullptr;
}
// static
@@ -227,9 +226,9 @@ GURL DecorateFrontendURL(const GURL& base_url) {
switches::kDevToolsFlags);
}
-#if BUILDFLAG(DEBUG_DEVTOOLS)
- url_string += "&debugFrontend=true";
-#endif // BUILDFLAG(DEBUG_DEVTOOLS)
+ if (command_line->HasSwitch(switches::kCustomDevtoolsFrontend)) {
+ url_string += "&debugFrontend=true";
+ }
return GURL(url_string);
}
@@ -456,18 +455,18 @@ content::WebContents* DevToolsWindow::GetInTabWebContents(
DevToolsWindow* window = GetInstanceForInspectedWebContents(
inspected_web_contents);
if (!window || window->life_stage_ == kClosing)
- return NULL;
+ return nullptr;
// Not yet loaded window is treated as docked, but we should not present it
// until we decided on docking.
bool is_docked_set = window->life_stage_ == kLoadCompleted ||
window->life_stage_ == kIsDockedSet;
if (!is_docked_set)
- return NULL;
+ return nullptr;
// Undocked window should have toolbox web contents.
if (!window->is_docked_ && !window->toolbox_web_contents_)
- return NULL;
+ return nullptr;
if (out_strategy)
out_strategy->CopyFrom(window->contents_resizing_strategy_);
@@ -480,13 +479,13 @@ content::WebContents* DevToolsWindow::GetInTabWebContents(
DevToolsWindow* DevToolsWindow::GetInstanceForInspectedWebContents(
WebContents* inspected_web_contents) {
if (!inspected_web_contents || !g_devtools_window_instances.IsCreated())
- return NULL;
+ return nullptr;
DevToolsWindows* instances = g_devtools_window_instances.Pointer();
for (auto it(instances->begin()); it != instances->end(); ++it) {
if ((*it)->GetInspectedWebContents() == inspected_web_contents)
return *it;
}
- return NULL;
+ return nullptr;
}
// static
@@ -732,7 +731,7 @@ void DevToolsWindow::InspectElement(
scoped_refptr<DevToolsAgentHost> agent(
DevToolsAgentHost::GetOrCreateFor(web_contents));
agent->InspectElement(inspected_frame_host, x, y);
- bool should_measure_time = FindDevToolsWindow(agent.get()) == NULL;
+ bool should_measure_time = !FindDevToolsWindow(agent.get());
base::TimeTicks start_time = base::TimeTicks::Now();
// TODO(loislo): we should initiate DevTools window opening from within
// renderer. Otherwise, we still can hit a race condition here.
@@ -800,7 +799,7 @@ void DevToolsWindow::Show(const DevToolsToggleAction& action) {
return;
if (is_docked_) {
DCHECK(can_dock_);
- Browser* inspected_browser = NULL;
+ Browser* inspected_browser = nullptr;
int inspected_tab_index = -1;
FindInspectedBrowserAndTabIndex(GetInspectedWebContents(),
&inspected_browser,
@@ -959,8 +958,6 @@ DevToolsWindow::DevToolsWindow(FrontendType frontend_type,
zoom::ZoomController::CreateForWebContents(main_web_contents_);
zoom::ZoomController::FromWebContents(main_web_contents_)
->SetShowsNotificationBubble(false);
- performance_manager::PerformanceManagerRegistry::GetInstance()
- ->CreatePageNodeForWebContents(main_web_contents_);
g_devtools_window_instances.Get().push_back(this);
@@ -1101,26 +1098,26 @@ GURL DevToolsWindow::GetDevToolsURL(Profile* profile,
DevToolsWindow* DevToolsWindow::FindDevToolsWindow(
DevToolsAgentHost* agent_host) {
if (!agent_host || !g_devtools_window_instances.IsCreated())
- return NULL;
+ return nullptr;
DevToolsWindows* instances = g_devtools_window_instances.Pointer();
for (auto it(instances->begin()); it != instances->end(); ++it) {
if ((*it)->bindings_->IsAttachedTo(agent_host))
return *it;
}
- return NULL;
+ return nullptr;
}
// static
DevToolsWindow* DevToolsWindow::AsDevToolsWindow(
content::WebContents* web_contents) {
if (!web_contents || !g_devtools_window_instances.IsCreated())
- return NULL;
+ return nullptr;
DevToolsWindows* instances = g_devtools_window_instances.Pointer();
for (auto it(instances->begin()); it != instances->end(); ++it) {
if ((*it)->main_web_contents_ == web_contents)
return *it;
}
- return NULL;
+ return nullptr;
}
WebContents* DevToolsWindow::OpenURLFromTab(
@@ -1366,7 +1363,7 @@ void DevToolsWindow::SetIsDocked(bool dock_requested) {
// Removing the only WebContents from the tab strip of browser_ will
// eventually lead to the destruction of browser_ as well, which is why it's
// okay to just null the raw pointer here.
- browser_ = NULL;
+ browser_ = nullptr;
owned_main_web_contents_ = tab_strip_model->DetachWebContentsAt(
tab_strip_model->GetIndexOfWebContents(main_web_contents_));
@@ -1475,7 +1472,7 @@ void DevToolsWindow::ShowCertificateViewer(const std::string& cert_chain) {
WebContents* inspected_contents =
is_docked_ ? GetInspectedWebContents() : main_web_contents_;
- Browser* browser = NULL;
+ Browser* browser = nullptr;
int tab = 0;
if (!FindInspectedBrowserAndTabIndex(inspected_contents, &browser, &tab))
return;
@@ -1549,11 +1546,12 @@ void DevToolsWindow::CreateDevToolsBrowser() {
}
BrowserWindow* DevToolsWindow::GetInspectedBrowserWindow() {
- Browser* browser = NULL;
+ Browser* browser = nullptr;
int tab;
- return FindInspectedBrowserAndTabIndex(GetInspectedWebContents(),
- &browser, &tab) ?
- browser->window() : NULL;
+ return FindInspectedBrowserAndTabIndex(GetInspectedWebContents(), &browser,
+ &tab)
+ ? browser->window()
+ : nullptr;
}
void DevToolsWindow::DoAction(const DevToolsToggleAction& action) {
@@ -1589,7 +1587,7 @@ void DevToolsWindow::DoAction(const DevToolsToggleAction& action) {
void DevToolsWindow::UpdateBrowserToolbar() {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
- inspected_window->UpdateToolbar(NULL);
+ inspected_window->UpdateToolbar(nullptr);
}
void DevToolsWindow::UpdateBrowserWindow() {
@@ -1601,7 +1599,7 @@ void DevToolsWindow::UpdateBrowserWindow() {
WebContents* DevToolsWindow::GetInspectedWebContents() {
return inspected_contents_observer_
? inspected_contents_observer_->web_contents()
- : NULL;
+ : nullptr;
}
void DevToolsWindow::LoadCompleted() {
diff --git a/chromium/chrome/browser/devtools/devtools_window.h b/chromium/chrome/browser/devtools/devtools_window.h
index e89f2698aeb..d593dad9323 100644
--- a/chromium/chrome/browser/devtools/devtools_window.h
+++ b/chromium/chrome/browser/devtools/devtools_window.h
@@ -58,15 +58,15 @@ class DevToolsWindow : public DevToolsUIBindings::Delegate,
content::WebContents* web_contents);
// Return the DevToolsWindow for the given WebContents if one exists,
- // otherwise NULL.
+ // otherwise nullptr.
static DevToolsWindow* GetInstanceForInspectedWebContents(
content::WebContents* inspected_web_contents);
// Return the docked DevTools WebContents for the given inspected WebContents
- // if one exists and should be shown in browser window, otherwise NULL.
+ // if one exists and should be shown in browser window, otherwise nullptr.
// This method will return only fully initialized window ready to be
// presented in UI.
- // If |out_strategy| is not NULL, it will contain resizing strategy.
+ // If |out_strategy| is not nullptr, it will contain resizing strategy.
// For immediately-ready-to-use but maybe not yet fully initialized DevTools
// use |GetInstanceForInspectedRenderViewHost| instead.
static content::WebContents* GetInTabWebContents(
diff --git a/chromium/chrome/browser/devtools/protocol/DEPS b/chromium/chrome/browser/devtools/protocol/DEPS
index 76297a762e6..109e3a5657e 100644
--- a/chromium/chrome/browser/devtools/protocol/DEPS
+++ b/chromium/chrome/browser/devtools/protocol/DEPS
@@ -1,5 +1,4 @@
specific_include_rules = {
- # TODO(mash): Fix. https://crbug.com/758061
"window_manager_handler\.cc": [
"+ash/shell.h",
"+ash/wm/overview/overview_controller.h",
diff --git a/chromium/chrome/browser/devtools/protocol/browser_handler.cc b/chromium/chrome/browser/devtools/protocol/browser_handler.cc
index 3ba37138d18..1f8425dec8d 100644
--- a/chromium/chrome/browser/devtools/protocol/browser_handler.cc
+++ b/chromium/chrome/browser/devtools/protocol/browser_handler.cc
@@ -9,7 +9,6 @@
#include "base/bind.h"
#include "base/memory/ref_counted_memory.h"
-#include "base/task/post_task.h"
#include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
#include "chrome/browser/devtools/devtools_dock_tile.h"
#include "chrome/browser/lifetime/application_lifetime.h"
@@ -112,8 +111,8 @@ Response BrowserHandler::GetWindowBounds(
}
Response BrowserHandler::Close() {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI}, base::BindOnce([]() {
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce([]() {
if (ChromeDevToolsManagerDelegate::GetInstance())
ChromeDevToolsManagerDelegate::GetInstance()->BrowserCloseRequested();
chrome::ExitIgnoreUnloadHandlers();
diff --git a/chromium/chrome/browser/devtools/protocol/security_handler.cc b/chromium/chrome/browser/devtools/protocol/security_handler.cc
index 03b2d85aa6c..c44998a5ca9 100644
--- a/chromium/chrome/browser/devtools/protocol/security_handler.cc
+++ b/chromium/chrome/browser/devtools/protocol/security_handler.cc
@@ -47,7 +47,6 @@ std::string SecurityLevelToProtocolSecurityState(
return protocol::Security::SecurityStateEnum::Insecure;
return protocol::Security::SecurityStateEnum::Neutral;
case security_state::SECURE_WITH_POLICY_INSTALLED_CERT:
- case security_state::EV_SECURE:
case security_state::SECURE:
return protocol::Security::SecurityStateEnum::Secure;
case security_state::DANGEROUS:
diff --git a/chromium/chrome/browser/devtools/remote_debugging_server.cc b/chromium/chrome/browser/devtools/remote_debugging_server.cc
index e57ed9c6da7..4a5a033c65b 100644
--- a/chromium/chrome/browser/devtools/remote_debugging_server.cc
+++ b/chromium/chrome/browser/devtools/remote_debugging_server.cc
@@ -16,9 +16,11 @@
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_paths.h"
+#include "chrome/common/chrome_switches.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_socket_factory.h"
#include "content/public/common/content_switches.h"
+#include "net/base/filename_util.h"
#include "net/base/net_errors.h"
#include "net/log/net_log_source.h"
#include "net/socket/tcp_server_socket.h"
@@ -108,10 +110,13 @@ RemoteDebuggingServer::RemoteDebuggingServer() {
}
base::FilePath debug_frontend_dir;
-#if BUILDFLAG(DEBUG_DEVTOOLS)
- base::PathService::Get(chrome::DIR_INSPECTOR_DEBUG, &debug_frontend_dir);
-#endif
-
+ if (command_line.HasSwitch(::switches::kCustomDevtoolsFrontend)) {
+ GURL custom_devtools_frontend_url(command_line.GetSwitchValueASCII(
+ ::switches::kCustomDevtoolsFrontend));
+ if (custom_devtools_frontend_url.SchemeIsFile()) {
+ net::FileURLToFilePath(custom_devtools_frontend_url, &debug_frontend_dir);
+ }
+ }
content::DevToolsAgentHost::StartRemoteDebuggingServer(
std::make_unique<TCPServerSocketFactory>(port), output_dir,
debug_frontend_dir);
diff --git a/chromium/chrome/browser/download/android/BUILD.gn b/chromium/chrome/browser/download/android/BUILD.gn
index 38b102bb5f2..2e4b33585f4 100644
--- a/chromium/chrome/browser/download/android/BUILD.gn
+++ b/chromium/chrome/browser/download/android/BUILD.gn
@@ -10,18 +10,30 @@ android_library("java") {
"java/src/org/chromium/chrome/browser/download/DirectoryOption.java",
"java/src/org/chromium/chrome/browser/download/DownloadConstants.java",
"java/src/org/chromium/chrome/browser/download/DownloadDelegateImpl.java",
+ "java/src/org/chromium/chrome/browser/download/DownloadDialogBridge.java",
"java/src/org/chromium/chrome/browser/download/DownloadDirectoryProvider.java",
"java/src/org/chromium/chrome/browser/download/DownloadFileProvider.java",
"java/src/org/chromium/chrome/browser/download/DownloadFilter.java",
"java/src/org/chromium/chrome/browser/download/DownloadInfo.java",
- "java/src/org/chromium/chrome/browser/download/DownloadLocationCustomView.java",
- "java/src/org/chromium/chrome/browser/download/DownloadLocationDialogBridge.java",
+ "java/src/org/chromium/chrome/browser/download/DownloadLaterMetrics.java",
"java/src/org/chromium/chrome/browser/download/DownloadManagerBridge.java",
"java/src/org/chromium/chrome/browser/download/DownloadStartupUtils.java",
"java/src/org/chromium/chrome/browser/download/DownloadStatus.java",
"java/src/org/chromium/chrome/browser/download/MediaStoreHelper.java",
"java/src/org/chromium/chrome/browser/download/MimeUtils.java",
"java/src/org/chromium/chrome/browser/download/StringUtils.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadDateTimePickerDialogCoordinator.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadDateTimePickerDialogProperties.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadDateTimePickerView.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadLaterDialogChoice.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadLaterDialogController.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadLaterDialogCoordinator.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadLaterDialogHelper.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadLaterDialogProperties.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadLaterDialogView.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadLocationCustomView.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadLocationDialogController.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadLocationDialogCoordinator.java",
"java/src/org/chromium/chrome/browser/download/home/DownloadManagerCoordinator.java",
"java/src/org/chromium/chrome/browser/download/home/DownloadManagerUiConfig.java",
"java/src/org/chromium/chrome/browser/download/home/FaviconProvider.java",
@@ -41,6 +53,7 @@ android_library("java") {
"//chrome/browser/flags:java",
"//chrome/browser/offline_pages/android:java",
"//chrome/browser/preferences:java",
+ "//chrome/browser/profiles/android:java",
"//chrome/browser/ui/messages/android:java",
"//chrome/browser/util:java",
"//components/browser_ui/modaldialog/android:java",
@@ -53,8 +66,12 @@ android_library("java") {
"//components/feature_engagement:feature_engagement_java",
"//components/feed/core/shared_prefs:feed_shared_prefs",
"//components/offline_items_collection/core:core_java",
+ "//components/prefs/android:java",
+ "//components/user_prefs/android:java",
"//content/public/android:content_java",
"//third_party/android_deps:androidx_core_core_java",
+ "//third_party/android_deps:androidx_fragment_fragment_java",
+ "//third_party/android_deps:androidx_preference_preference_java",
"//third_party/android_deps:com_google_android_material_material_java",
"//ui/android:ui_java",
]
@@ -65,14 +82,18 @@ android_library("java") {
}
android_library_factory("factory_java") {
+ # These deps will be inherited by the resulting android_library target.
deps = [ ":java" ]
- sources = [ "java/src/org/chromium/chrome/browser/download/home/DownloadManagerCoordinatorFactory.java" ]
+
+ # This internal file will be replaced by a generated file so the resulting
+ # android_library target does not actually depend on this internal file.
+ sources = [ "//chrome/browser/download/internal/android/java/src/org/chromium/chrome/browser/download/home/DownloadManagerCoordinatorFactory.java" ]
}
generate_jni("jni_headers") {
sources = [
+ "java/src/org/chromium/chrome/browser/download/DownloadDialogBridge.java",
"java/src/org/chromium/chrome/browser/download/DownloadInfo.java",
- "java/src/org/chromium/chrome/browser/download/DownloadLocationDialogBridge.java",
"java/src/org/chromium/chrome/browser/download/DownloadManagerBridge.java",
"java/src/org/chromium/chrome/browser/download/DownloadStartupUtils.java",
"java/src/org/chromium/chrome/browser/download/MimeUtils.java",
@@ -94,6 +115,7 @@ android_library("download_java_tests") {
"//base:base_java",
"//base:base_java_test_support",
"//chrome/test/android:chrome_java_test_support",
+ "//components/browser_ui/util/android:java",
"//components/offline_items_collection/core:core_java",
"//third_party/android_support_test_runner:runner_java",
"//third_party/junit",
@@ -101,6 +123,34 @@ android_library("download_java_tests") {
]
}
+android_library("junit_tests") {
+ # Platform checks are broken for Robolectric. See https://crbug.com/1071638.
+ bypass_platform_checks = true
+ testonly = true
+
+ sources = [
+ "java/src/org/chromium/chrome/browser/download/DownloadDialogBridgeUnitTest.java",
+ "java/src/org/chromium/chrome/browser/download/DownloadLaterMetricsUnitTest.java",
+ "java/src/org/chromium/chrome/browser/download/dialogs/DownloadLaterDialogHelperUnitTest.java",
+ ]
+
+ deps = [
+ ":java",
+ "//base:base_java",
+ "//base:base_java_test_support",
+ "//base:base_junit_test_support",
+ "//chrome/browser/flags:java",
+ "//chrome/browser/preferences:java",
+ "//chrome/test/android:chrome_java_test_support",
+ "//components/offline_items_collection/core:core_java",
+ "//components/prefs/android:java",
+ "//third_party/android_deps:robolectric_all_java",
+ "//third_party/junit",
+ "//third_party/mockito:mockito_java",
+ "//ui/android:ui_full_java",
+ ]
+}
+
android_resources("java_resources") {
sources = [
"java/res/color/tint_on_blue_bg.xml",
@@ -131,6 +181,8 @@ android_resources("java_resources") {
"java/res/layout/confirm_oma_download.xml",
"java/res/layout/download_home_tabs.xml",
"java/res/layout/download_home_toolbar.xml",
+ "java/res/layout/download_later_date_time_picker_dialog.xml",
+ "java/res/layout/download_later_dialog.xml",
"java/res/layout/download_location_dialog.xml",
"java/res/layout/download_location_preference.xml",
"java/res/layout/download_location_preference_item.xml",
@@ -160,6 +212,7 @@ android_resources("java_resources") {
"java/res/values-night-v17/colors.xml",
"java/res/values-v17/attrs.xml",
"java/res/values-v17/colors.xml",
+ "java/res/values-v17/dimens.xml",
"java/res/values-v17/ids.xml",
"java/res/values-v17/styles.xml",
"java/res/xml/download_preferences.xml",
diff --git a/chromium/chrome/browser/enterprise/util/BUILD.gn b/chromium/chrome/browser/enterprise/util/BUILD.gn
index 3b343b4cdf2..62b4dbcbcc0 100644
--- a/chromium/chrome/browser/enterprise/util/BUILD.gn
+++ b/chromium/chrome/browser/enterprise/util/BUILD.gn
@@ -2,8 +2,8 @@
# 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")
-
android_library("java") {
sources = [ "android/java/src/org/chromium/chrome/browser/enterprise/util/ManagedBrowserUtils.java" ]
deps = [
@@ -15,5 +15,8 @@ android_library("java") {
}
generate_jni("jni_headers") {
- sources = [ "android/java/src/org/chromium/chrome/browser/enterprise/util/ManagedBrowserUtils.java" ]
+ sources = [
+ "../../../android/java/src/org/chromium/chrome/browser/policy/EnterpriseInfo.java",
+ "android/java/src/org/chromium/chrome/browser/enterprise/util/ManagedBrowserUtils.java",
+ ]
}
diff --git a/chromium/chrome/browser/extensions/BUILD.gn b/chromium/chrome/browser/extensions/BUILD.gn
index 358b0a3b16f..a1f5e2a7e0e 100644
--- a/chromium/chrome/browser/extensions/BUILD.gn
+++ b/chromium/chrome/browser/extensions/BUILD.gn
@@ -190,6 +190,8 @@ static_library("extensions") {
"api/identity/identity_constants.h",
"api/identity/identity_get_accounts_function.cc",
"api/identity/identity_get_accounts_function.h",
+ "api/identity/identity_get_auth_token_error.cc",
+ "api/identity/identity_get_auth_token_error.h",
"api/identity/identity_get_auth_token_function.cc",
"api/identity/identity_get_auth_token_function.h",
"api/identity/identity_get_profile_user_info_function.cc",
@@ -610,14 +612,14 @@ static_library("extensions") {
"external_provider_impl.h",
"external_registry_loader_win.cc",
"external_registry_loader_win.h",
- "forced_extensions/installation_metrics.cc",
- "forced_extensions/installation_metrics.h",
- "forced_extensions/installation_reporter.cc",
- "forced_extensions/installation_reporter.h",
- "forced_extensions/installation_reporter_factory.cc",
- "forced_extensions/installation_reporter_factory.h",
- "forced_extensions/installation_tracker.cc",
- "forced_extensions/installation_tracker.h",
+ "forced_extensions/force_installed_metrics.cc",
+ "forced_extensions/force_installed_metrics.h",
+ "forced_extensions/force_installed_tracker.cc",
+ "forced_extensions/force_installed_tracker.h",
+ "forced_extensions/install_stage_tracker.cc",
+ "forced_extensions/install_stage_tracker.h",
+ "forced_extensions/install_stage_tracker_factory.cc",
+ "forced_extensions/install_stage_tracker_factory.h",
"global_shortcut_listener.cc",
"global_shortcut_listener.h",
"global_shortcut_listener_mac.h",
@@ -645,6 +647,8 @@ static_library("extensions") {
"launch_util.h",
"load_error_reporter.cc",
"load_error_reporter.h",
+ "media_router_extension_access_logger_impl.cc",
+ "media_router_extension_access_logger_impl.h",
"menu_manager.cc",
"menu_manager.h",
"menu_manager_factory.cc",
@@ -751,7 +755,7 @@ static_library("extensions") {
# Lots of APIs use headers from the list above.
"//chrome/browser/extensions/api:api_registration",
- # TODO(loyso): Remove this circular dependency. http://crbug.com/876576.
+ # TODO(crbug.com/1065748): Remove this circular dependency.
"//chrome/browser/web_applications/extensions",
# TODO(crbug/925153): Remove this circular dependency.
@@ -796,11 +800,13 @@ static_library("extensions") {
"//chrome/browser/resource_coordinator:intervention_policy_database_proto",
"//chrome/browser/resource_coordinator:mojo_bindings",
"//chrome/browser/safe_browsing",
+ "//chrome/browser/web_applications",
"//chrome/browser/web_applications/components",
+
+ # TODO(crbug.com/1065748): Remove this dependency:
"//chrome/browser/web_applications/extensions",
"//chrome/common/extensions/api:extensions_features",
"//chrome/common/safe_browsing:proto",
- "//chrome/services/app_service/public/mojom",
"//chrome/services/removable_storage_writer/public/mojom",
"//components/autofill/content/browser",
"//components/bookmarks/browser",
@@ -853,6 +859,7 @@ static_library("extensions") {
"//components/safe_browsing/core/common:safe_browsing_prefs",
"//components/safe_browsing/core/db:database_manager",
"//components/search_engines",
+ "//components/services/app_service/public/mojom",
"//components/services/patch/content",
"//components/services/unzip/content",
"//components/services/unzip/public/cpp",
@@ -897,6 +904,7 @@ static_library("extensions") {
"//services/audio/public/cpp",
"//services/data_decoder/public/cpp",
"//services/device/public/mojom",
+ "//services/metrics/public/cpp:ukm_builders",
"//services/network/public/mojom",
"//services/service_manager/public/cpp",
"//services/service_manager/public/mojom",
@@ -947,6 +955,8 @@ static_library("extensions") {
"api/certificate_provider/certificate_provider_api.h",
"api/enterprise_device_attributes/enterprise_device_attributes_api.cc",
"api/enterprise_device_attributes/enterprise_device_attributes_api.h",
+ "api/enterprise_networking_attributes/enterprise_networking_attributes_api.cc",
+ "api/enterprise_networking_attributes/enterprise_networking_attributes_api.h",
"api/enterprise_platform_keys/enterprise_platform_keys_api.cc",
"api/enterprise_platform_keys/enterprise_platform_keys_api.h",
"api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc",
@@ -1004,10 +1014,12 @@ static_library("extensions") {
"//ash/keyboard/ui:resources_grit_grit",
"//ash/public/cpp",
"//chrome/browser/chromeos/crostini:crostini_installer_types_mojom",
- "//chrome/browser/resources/chromeos/camera:chrome_camera_app",
"//chrome/browser/ui/webui/settings/chromeos/constants:mojom",
"//chromeos",
"//chromeos/attestation",
+ "//chromeos/components/camera_app_ui",
+ "//chromeos/components/camera_app_ui:mojo_bindings",
+ "//chromeos/components/camera_app_ui/resources:chrome_camera_app",
"//chromeos/components/proximity_auth",
"//chromeos/constants",
"//chromeos/cryptohome",
@@ -1023,11 +1035,11 @@ static_library("extensions") {
"//chromeos/services/machine_learning/public/cpp",
"//chromeos/services/machine_learning/public/mojom",
"//chromeos/services/media_perception/public/mojom",
+ "//chromeos/services/tts/public/mojom",
"//chromeos/settings",
"//chromeos/system",
"//chromeos/tpm",
"//components/arc",
- "//components/chromeos_camera:camera_app_helper",
"//components/constrained_window",
"//components/drive",
"//components/user_manager",
@@ -1160,17 +1172,6 @@ static_library("extensions") {
]
}
- if (is_win || (is_linux && !is_chromeos)) {
- sources += [
- "api/input_ime/input_ime_api.cc",
- "api/input_ime/input_ime_api.h",
- "api/input_ime/input_ime_api_nonchromeos.cc",
- "api/input_ime/input_ime_api_nonchromeos.h",
- "api/input_ime/input_ime_event_router_base.cc",
- "api/input_ime/input_ime_event_router_base.h",
- ]
- }
-
if (enable_plugins) {
sources += [
"plugin_manager.cc",
@@ -1220,7 +1221,7 @@ static_library("extensions") {
"api/braille_display_private/brlapi_keycode_map.cc",
"api/braille_display_private/brlapi_keycode_map.h",
]
- deps += [ "//build/linux/libbrlapi" ]
+ deps += [ "//third_party/libbrlapi" ]
} else {
sources += [ "api/braille_display_private/braille_controller_stub.cc" ]
}
diff --git a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc
index 5d7be8f6b8c..f26c3ec2c48 100644
--- a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc
@@ -58,13 +58,13 @@ class ActivityLogApiTest : public ExtensionApiTest {
base::CommandLine saved_cmdline_;
};
-#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
-// TODO(crbug.com/299393): Flaky on Mac, Windows and Linux.
+#if !defined(NDEBUG) || defined(ADDRESS_SANITIZER)
+// TODO(crbug.com/299393): This test is very long and can time out in debug or
+// ASAN builds.
#define MAYBE_TriggerEvent DISABLED_TriggerEvent
#else
#define MAYBE_TriggerEvent TriggerEvent
#endif
-
// The test extension sends a message to its 'friend'. The test completes
// if it successfully sees the 'friend' receive the message.
IN_PROC_BROWSER_TEST_F(ActivityLogApiTest, MAYBE_TriggerEvent) {
@@ -82,4 +82,3 @@ IN_PROC_BROWSER_TEST_F(ActivityLogApiTest, MAYBE_TriggerEvent) {
}
} // namespace extensions
-
diff --git a/chromium/chrome/browser/extensions/api/alarms/alarms_apitest.cc b/chromium/chrome/browser/extensions/api/alarms/alarms_apitest.cc
index eacee156995..1de49aa22be 100644
--- a/chromium/chrome/browser/extensions/api/alarms/alarms_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/alarms/alarms_apitest.cc
@@ -6,6 +6,7 @@
#include "content/public/test/browser_test.h"
#include "extensions/browser/event_router.h"
#include "extensions/common/api/test.h"
+#include "extensions/common/scoped_worker_based_extensions_channel.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
#include "net/dns/mock_host_resolver.h"
@@ -15,12 +16,20 @@ using extensions::ResultCatcher;
namespace extensions {
-class AlarmsApiTest : public ExtensionApiTest {
+using ContextType = ExtensionApiTest::ContextType;
+
+class AlarmsApiTest : public ExtensionApiTest,
+ public testing::WithParamInterface<ContextType> {
public:
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartEmbeddedTestServer());
+
+ // Service Workers are currently only available on certain channels, so set
+ // the channel for those tests.
+ if (GetParam() == ContextType::kServiceWorker)
+ current_channel_ = std::make_unique<ScopedWorkerBasedExtensionsChannel>();
}
static std::unique_ptr<base::ListValue> BuildEventArguments(
@@ -30,11 +39,30 @@ class AlarmsApiTest : public ExtensionApiTest {
info.last_message = last_message;
return api::test::OnMessage::Create(info);
}
+
+ const Extension* LoadAlarmsExtensionIncognito(const char* path) {
+ int flags = kFlagEnableFileAccess | kFlagEnableIncognito;
+ if (GetParam() == ContextType::kServiceWorker)
+ flags |= kFlagRunAsServiceWorkerBasedExtension;
+
+ return LoadExtensionWithFlags(
+ test_data_dir_.AppendASCII("alarms").AppendASCII(path), flags);
+ }
+
+ private:
+ std::unique_ptr<ScopedWorkerBasedExtensionsChannel> current_channel_;
};
+INSTANTIATE_TEST_SUITE_P(EventPage,
+ AlarmsApiTest,
+ ::testing::Values(ContextType::kEventPage));
+INSTANTIATE_TEST_SUITE_P(ServiceWorker,
+ AlarmsApiTest,
+ ::testing::Values(ContextType::kServiceWorker));
+
// Tests that an alarm created by an extension with incognito split mode is
// only triggered in the browser context it was created in.
-IN_PROC_BROWSER_TEST_F(AlarmsApiTest, IncognitoSplit) {
+IN_PROC_BROWSER_TEST_P(AlarmsApiTest, IncognitoSplit) {
// We need 2 ResultCatchers because we'll be running the same test in both
// regular and incognito mode.
Profile* incognito_profile = browser()->profile()->GetOffTheRecordProfile();
@@ -48,8 +76,7 @@ IN_PROC_BROWSER_TEST_F(AlarmsApiTest, IncognitoSplit) {
ExtensionTestMessageListener listener_incognito("ready: true", false);
- ASSERT_TRUE(LoadExtensionIncognito(
- test_data_dir_.AppendASCII("alarms").AppendASCII("split")));
+ ASSERT_TRUE(LoadAlarmsExtensionIncognito("split"));
EXPECT_TRUE(listener.WaitUntilSatisfied());
EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());
@@ -67,12 +94,11 @@ IN_PROC_BROWSER_TEST_F(AlarmsApiTest, IncognitoSplit) {
// Tests that the behavior for an alarm created in incognito context should be
// the same if incognito is in spanning mode.
-IN_PROC_BROWSER_TEST_F(AlarmsApiTest, IncognitoSpanning) {
+IN_PROC_BROWSER_TEST_P(AlarmsApiTest, IncognitoSpanning) {
ResultCatcher catcher;
catcher.RestrictToBrowserContext(browser()->profile());
- ASSERT_TRUE(LoadExtensionIncognito(
- test_data_dir_.AppendASCII("alarms").AppendASCII("spanning")));
+ ASSERT_TRUE(LoadAlarmsExtensionIncognito("spanning"));
// Open incognito window.
OpenURLOffTheRecord(browser()->profile(), GURL("about:blank"));
diff --git a/chromium/chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_api.cc b/chromium/chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_api.cc
index a96f3c9d9d7..cb6fe1e90f2 100644
--- a/chromium/chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_api.cc
@@ -189,9 +189,19 @@ void AutofillAssistantPrivateEventRouter::OnInfoBoxChanged(
void AutofillAssistantPrivateEventRouter::OnProgressChanged(int progress) {}
+void AutofillAssistantPrivateEventRouter::OnProgressActiveStepChanged(
+ int active_step) {}
+
void AutofillAssistantPrivateEventRouter::OnProgressVisibilityChanged(
bool visible) {}
+void AutofillAssistantPrivateEventRouter::OnStepProgressBarConfigurationChanged(
+ const autofill_assistant::ShowProgressBarProto::
+ StepProgressBarConfiguration& configuration) {}
+
+void AutofillAssistantPrivateEventRouter::OnProgressBarErrorStateChanged(
+ bool error) {}
+
void AutofillAssistantPrivateEventRouter::OnTouchableAreaChanged(
const autofill_assistant::RectF& visual_viewport,
const std::vector<autofill_assistant::RectF>& touchable_areas,
diff --git a/chromium/chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_api.h b/chromium/chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_api.h
index d9b1b8fdea7..034c4e7decc 100644
--- a/chromium/chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_api.h
+++ b/chromium/chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_api.h
@@ -139,7 +139,12 @@ class AutofillAssistantPrivateEventRouter
void OnDetailsChanged(const autofill_assistant::Details* details) override;
void OnInfoBoxChanged(const autofill_assistant::InfoBox* info_box) override;
void OnProgressChanged(int progress) override;
+ void OnProgressActiveStepChanged(int active_step) override;
void OnProgressVisibilityChanged(bool visible) override;
+ void OnStepProgressBarConfigurationChanged(
+ const autofill_assistant::ShowProgressBarProto::
+ StepProgressBarConfiguration& configuration) override;
+ void OnProgressBarErrorStateChanged(bool error) override;
void OnTouchableAreaChanged(
const autofill_assistant::RectF& visual_viewport,
const std::vector<autofill_assistant::RectF>& touchable_areas,
diff --git a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc
index 450445fb776..9e6591918d7 100644
--- a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc
@@ -347,11 +347,31 @@ ExtensionFunction::ResponseAction AutofillPrivateSaveCreditCardFunction::Run() {
base::UTF8ToUTF16(*card->expiration_year));
}
+ if (card->nickname) {
+ credit_card.SetNickname(base::UTF8ToUTF16(*card->nickname));
+ }
+
if (use_existing_card) {
+ // Only updates when the card info changes.
+ if (existing_card && existing_card->Compare(credit_card) == 0)
+ return RespondNow(NoArguments());
+
+ // Record when nickname is updated.
+ if (credit_card.HasValidNickname() &&
+ existing_card->nickname() != credit_card.nickname()) {
+ base::RecordAction(
+ base::UserMetricsAction("AutofillCreditCardsEditedWithNickname"));
+ }
+
personal_data->UpdateCreditCard(credit_card);
+ base::RecordAction(base::UserMetricsAction("AutofillCreditCardsEdited"));
} else {
personal_data->AddCreditCard(credit_card);
base::RecordAction(base::UserMetricsAction("AutofillCreditCardsAdded"));
+ if (credit_card.HasValidNickname()) {
+ base::RecordAction(
+ base::UserMetricsAction("AutofillCreditCardsAddedWithNickname"));
+ }
}
return RespondNow(NoArguments());
diff --git a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc
index 00a1b8607db..48da5f15a0a 100644
--- a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_apitest.cc
@@ -44,8 +44,7 @@ class AutofillPrivateApiTest : public ExtensionApiTest {
// TODO(hcarmona): Investigate converting these tests to unittests.
-// TODO(crbug.com/643097) Disabled for flakiness.
-IN_PROC_BROWSER_TEST_F(AutofillPrivateApiTest, DISABLED_GetCountryList) {
+IN_PROC_BROWSER_TEST_F(AutofillPrivateApiTest, GetCountryList) {
EXPECT_TRUE(RunAutofillSubtest("getCountryList")) << message_;
}
diff --git a/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.cc b/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.cc
index cbe58c41776..10fe596182d 100644
--- a/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.cc
+++ b/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.cc
@@ -146,6 +146,10 @@ autofill_private::CreditCardEntry CreditCardToCreditCardEntry(
credit_card.GetRawInfo(autofill::CREDIT_CARD_EXP_MONTH))));
card.expiration_year.reset(new std::string(base::UTF16ToUTF8(
credit_card.GetRawInfo(autofill::CREDIT_CARD_EXP_4_DIGIT_YEAR))));
+ if (!credit_card.nickname().empty()) {
+ card.nickname.reset(
+ new std::string(base::UTF16ToUTF8(credit_card.nickname())));
+ }
// Create address metadata and add it to |address|.
std::unique_ptr<autofill_private::AutofillMetadata> metadata(
diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc
index 660aa4ed198..806848fbcb0 100644
--- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc
@@ -757,7 +757,7 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, WriteCharacteristicValue) {
.WillRepeatedly(Return(chrc0_.get()));
std::vector<uint8_t> write_value;
- EXPECT_CALL(*chrc0_, WriteRemoteCharacteristic_(_, _, _))
+ EXPECT_CALL(*chrc0_, DeprecatedWriteRemoteCharacteristic_(_, _, _))
.Times(2)
.WillOnce(InvokeCallbackArgument<2>(
BluetoothRemoteGattService::GATT_ERROR_FAILED))
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 7b0cdb28d3d..cde5b9d368a 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
@@ -68,12 +68,12 @@ namespace StartDrag = api::bookmark_manager_private::StartDrag;
namespace {
// Returns a single bookmark node from the argument ID.
-// This returns NULL in case of failure.
+// This returns nullptr in case of failure.
const BookmarkNode* GetNodeFromString(BookmarkModel* model,
const std::string& id_string) {
int64_t id;
if (!base::StringToInt64(id_string, &id))
- return NULL;
+ return nullptr;
return bookmarks::GetBookmarkNodeByID(model, id);
}
@@ -197,7 +197,7 @@ void BookmarkManagerPrivateEventRouter::BookmarkModelChanged() {}
void BookmarkManagerPrivateEventRouter::BookmarkModelBeingDeleted(
BookmarkModel* model) {
- bookmark_model_ = NULL;
+ bookmark_model_ = nullptr;
}
BookmarkManagerPrivateAPI::BookmarkManagerPrivateAPI(
@@ -304,7 +304,7 @@ const BookmarkNodeData*
BookmarkManagerPrivateDragEventRouter::GetBookmarkNodeData() {
if (bookmark_drag_data_.is_valid())
return &bookmark_drag_data_;
- return NULL;
+ return nullptr;
}
void BookmarkManagerPrivateDragEventRouter::ClearBookmarkNodeData() {
@@ -509,7 +509,7 @@ BookmarkManagerPrivateGetSubtreeFunction::RunOnReady() {
if (!params)
return BadMessage();
- const BookmarkNode* node = NULL;
+ const BookmarkNode* node = nullptr;
if (params->id.empty()) {
BookmarkModel* model =
diff --git a/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h
index b2617d86624..27e4655bd64 100644
--- a/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h
+++ b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h
@@ -104,7 +104,7 @@ class BookmarkManagerPrivateDragEventRouter
void OnDrop(const bookmarks::BookmarkNodeData& data) override;
// The bookmark drag and drop data. This gets set after a drop was done on
- // the page. This returns NULL if no data is available.
+ // the page. This returns nullptr if no data is available.
const bookmarks::BookmarkNodeData* GetBookmarkNodeData();
// Clears the drag and drop data.
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 5f90d3df246..8671eb11e31 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
@@ -35,11 +35,11 @@ namespace bookmark_api_helpers {
class ExtensionBookmarksTest : public testing::Test {
public:
ExtensionBookmarksTest()
- : managed_(NULL),
- model_(NULL),
- node_(NULL),
- node2_(NULL),
- folder_(NULL) {}
+ : managed_(nullptr),
+ model_(nullptr),
+ node_(nullptr),
+ node2_(nullptr),
+ folder_(nullptr) {}
void SetUp() override {
profile_.CreateBookmarkModel(false);
diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc
index 0664a2e51ba..78136b17ddb 100644
--- a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc
@@ -19,12 +19,37 @@
#include "components/bookmarks/test/bookmark_test_helpers.h"
#include "components/prefs/pref_service.h"
#include "content/public/test/browser_test.h"
+#include "extensions/common/scoped_worker_based_extensions_channel.h"
using bookmarks::BookmarkModel;
namespace extensions {
-IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Bookmarks) {
+using ContextType = ExtensionApiTest::ContextType;
+
+class BookmarksApiTest : public ExtensionApiTest,
+ public testing::WithParamInterface<ContextType> {
+ public:
+ void SetUp() override {
+ ExtensionApiTest::SetUp();
+ // Service Workers are currently only available on certain channels, so set
+ // the channel for those tests.
+ if (GetParam() == ContextType::kServiceWorker)
+ current_channel_ = std::make_unique<ScopedWorkerBasedExtensionsChannel>();
+ }
+
+ private:
+ std::unique_ptr<ScopedWorkerBasedExtensionsChannel> current_channel_;
+};
+
+INSTANTIATE_TEST_SUITE_P(EventPage,
+ BookmarksApiTest,
+ ::testing::Values(ContextType::kEventPage));
+INSTANTIATE_TEST_SUITE_P(ServiceWorker,
+ BookmarksApiTest,
+ ::testing::Values(ContextType::kServiceWorker));
+
+IN_PROC_BROWSER_TEST_P(BookmarksApiTest, Bookmarks) {
// Add test managed bookmarks to verify that the bookmarks API can read them
// and can't modify them.
Profile* profile = browser()->profile();
@@ -45,7 +70,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Bookmarks) {
profile->GetPrefs()->Set(bookmarks::prefs::kManagedBookmarks, list);
ASSERT_EQ(2u, managed->managed_node()->children().size());
- ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_;
+ if (GetParam() == ContextType::kEventPage) {
+ ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_;
+ } else {
+ ASSERT_TRUE(RunExtensionTestWithFlags(
+ "bookmarks", kFlagRunAsServiceWorkerBasedExtension, kFlagNone))
+ << message_;
+ }
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc
index f7fa8079e88..2e7f7b8235d 100644
--- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc
+++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc
@@ -272,7 +272,7 @@ void BookmarkEventRouter::BookmarkModelLoaded(BookmarkModel* model,
}
void BookmarkEventRouter::BookmarkModelBeingDeleted(BookmarkModel* model) {
- model_ = NULL;
+ model_ = nullptr;
}
void BookmarkEventRouter::BookmarkNodeMoved(BookmarkModel* model,
@@ -744,17 +744,12 @@ void BookmarksIOFunction::ShowSelectFileDialog(
gfx::NativeWindow owning_window =
web_contents ? platform_util::GetTopLevel(web_contents->GetNativeView())
: gfx::kNullNativeWindow;
- // |web_contents| can be NULL (for background pages), which is fine. In such
- // a case if file-selection dialogs are forbidden by policy, we will not
+ // |web_contents| can be nullptr (for background pages), which is fine. In
+ // such a case if file-selection dialogs are forbidden by policy, we will not
// show an InfoBar, which is better than letting one appear out of the blue.
- select_file_dialog_->SelectFile(type,
- base::string16(),
- default_path,
- &file_type_info,
- 0,
- base::FilePath::StringType(),
- owning_window,
- NULL);
+ select_file_dialog_->SelectFile(
+ type, base::string16(), default_path, &file_type_info, 0,
+ base::FilePath::StringType(), owning_window, nullptr);
}
void BookmarksIOFunction::FileSelectionCanceled(void* params) {
diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h
index e604b22d732..73703408cde 100644
--- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h
+++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h
@@ -165,7 +165,7 @@ class BookmarksFunction : public ExtensionFunction,
bool EditBookmarksEnabled();
// Helper that checks if |node| can be modified. Returns false if |node|
- // is NULL, or a managed node, or the root node. In these cases the node
+ // is nullptr, or a managed node, or the root node. In these cases the node
// can't be edited, can't have new child nodes appended, and its direct
// children can't be moved or reordered.
bool CanBeModified(const bookmarks::BookmarkNode* node, std::string* error);
diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc b/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc
index ab44ae9d90a..c1a99212564 100644
--- a/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc
+++ b/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc
@@ -15,7 +15,6 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/stl_util.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/time/time.h"
@@ -74,18 +73,17 @@ BrailleControllerImpl::~BrailleControllerImpl() {
void BrailleControllerImpl::TryLoadLibBrlApi() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- if (libbrlapi_loader_.loaded())
+ if (skip_libbrlapi_so_load_ || libbrlapi_loader_.loaded())
return;
- // These versions of libbrlapi work the same for the functions we
- // are using. (0.6.0 adds brlapi_writeWText).
- static const char* const kSupportedVersions[] = {
- "libbrlapi.so.0.5", "libbrlapi.so.0.6", "libbrlapi.so.0.7",
- "libbrlapi.so.0.8"};
- for (size_t i = 0; i < base::size(kSupportedVersions); ++i) {
- if (libbrlapi_loader_.Load(kSupportedVersions[i]))
- return;
+
+ // This api version needs to match the one contained in
+ // third_party/libbrlapi/brlapi.h.
+ static const char* const kSupportedVersion = "libbrlapi.so.0.8";
+
+ if (!libbrlapi_loader_.Load(kSupportedVersion)) {
+ LOG(WARNING) << "Couldn't load libbrlapi(" << kSupportedVersion << ": "
+ << strerror(errno);
}
- LOG(WARNING) << "Couldn't load libbrlapi: " << strerror(errno);
}
std::unique_ptr<DisplayState> BrailleControllerImpl::GetDisplayState() {
@@ -102,6 +100,10 @@ std::unique_ptr<DisplayState> BrailleControllerImpl::GetDisplayState() {
display_state->available = true;
display_state->text_column_count.reset(new int(columns));
display_state->text_row_count.reset(new int(rows));
+
+ unsigned int cell_size = 0;
+ connection_->GetCellSize(&cell_size);
+ display_state->cell_size.reset(new int(cell_size));
}
}
return display_state;
@@ -134,9 +136,9 @@ void BrailleControllerImpl::WriteDots(const std::vector<uint8_t>& cells,
void BrailleControllerImpl::AddObserver(BrailleObserver* observer) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- if (!base::PostTask(FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&BrailleControllerImpl::StartConnecting,
- base::Unretained(this)))) {
+ if (!content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&BrailleControllerImpl::StartConnecting,
+ base::Unretained(this)))) {
NOTREACHED();
}
observers_.AddObserver(observer);
@@ -168,7 +170,7 @@ void BrailleControllerImpl::StartConnecting() {
return;
started_connecting_ = true;
TryLoadLibBrlApi();
- if (!libbrlapi_loader_.loaded()) {
+ if (!libbrlapi_loader_.loaded() && !skip_libbrlapi_so_load_) {
return;
}
@@ -212,8 +214,8 @@ void BrailleControllerImpl::OnSocketDirChangedOnTaskThread(
LOG(ERROR) << "Error watching brlapi directory: " << path.value();
return;
}
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&BrailleControllerImpl::OnSocketDirChangedOnIOThread,
base::Unretained(this)));
}
@@ -230,7 +232,7 @@ void BrailleControllerImpl::OnSocketDirChangedOnIOThread() {
void BrailleControllerImpl::TryToConnect() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- DCHECK(libbrlapi_loader_.loaded());
+ DCHECK(skip_libbrlapi_so_load_ || libbrlapi_loader_.loaded());
connect_scheduled_ = false;
if (!connection_.get())
connection_ = create_brlapi_connection_function_.Run();
@@ -271,10 +273,11 @@ void BrailleControllerImpl::ScheduleTryToConnect() {
}
VLOG(1) << "Scheduling connection retry to brlapi";
connect_scheduled_ = true;
- base::PostDelayedTask(FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&BrailleControllerImpl::TryToConnect,
- base::Unretained(this)),
- kConnectionDelay);
+ content::GetIOThreadTaskRunner({})->PostDelayedTask(
+ FROM_HERE,
+ base::BindOnce(&BrailleControllerImpl::TryToConnect,
+ base::Unretained(this)),
+ kConnectionDelay);
}
void BrailleControllerImpl::Disconnect() {
@@ -288,7 +291,7 @@ void BrailleControllerImpl::Disconnect() {
std::unique_ptr<BrlapiConnection>
BrailleControllerImpl::CreateBrlapiConnection() {
- DCHECK(libbrlapi_loader_.loaded());
+ DCHECK(skip_libbrlapi_so_load_ || libbrlapi_loader_.loaded());
return BrlapiConnection::Create(&libbrlapi_loader_);
}
@@ -316,8 +319,8 @@ void BrailleControllerImpl::DispatchKeys() {
void BrailleControllerImpl::DispatchKeyEvent(std::unique_ptr<KeyEvent> event) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&BrailleControllerImpl::DispatchKeyEvent,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&BrailleControllerImpl::DispatchKeyEvent,
base::Unretained(this), std::move(event)));
return;
}
@@ -329,8 +332,8 @@ void BrailleControllerImpl::DispatchKeyEvent(std::unique_ptr<KeyEvent> event) {
void BrailleControllerImpl::DispatchOnDisplayStateChanged(
std::unique_ptr<DisplayState> new_state) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
- if (!base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ if (!content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&BrailleControllerImpl::DispatchOnDisplayStateChanged,
base::Unretained(this), std::move(new_state)))) {
diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.h b/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.h
index fc98d3d832d..db1054e140c 100644
--- a/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.h
+++ b/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.h
@@ -83,6 +83,9 @@ class BrailleControllerImpl : public BrailleController {
// Manipulated by the SequencedTaskRunner.
base::FilePathWatcher file_path_watcher_;
+ // Set by tests to skip libbrlapi.so loading.
+ bool skip_libbrlapi_so_load_ = false;
+
friend struct base::DefaultSingletonTraits<BrailleControllerImpl>;
DISALLOW_COPY_AND_ASSIGN(BrailleControllerImpl);
diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.cc b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.cc
index fb509eb68ac..f77120a3600 100644
--- a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.cc
@@ -89,7 +89,7 @@ bool BrailleDisplayPrivateAPI::IsProfileActive() {
// Since we are creating one instance per profile / user, we should be fine
// comparing against the active user. That said - if we ever change that,
// this code will need to be changed.
- return profile_->IsSameProfile(ProfileManager::GetActiveUserProfile());
+ return profile_->IsSameOrParent(ProfileManager::GetActiveUserProfile());
#else // !defined(OS_CHROMEOS)
return true;
#endif
diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc
index 12ff95b9219..573132b3aa6 100644
--- a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc
@@ -6,7 +6,6 @@
#include "base/bind.h"
#include "base/containers/circular_deque.h"
-#include "base/task/post_task.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
@@ -50,6 +49,7 @@ struct MockBrlapiConnectionData {
bool connected;
size_t display_columns;
size_t display_rows;
+ size_t cell_size;
brlapi_error_t error;
std::vector<std::string> written_content;
// List of brlapi key codes. A negative number makes the connection mock
@@ -69,8 +69,8 @@ class MockBrlapiConnection : public BrlapiConnection {
data_->connected = true;
on_data_ready_ = on_data_ready;
if (!data_->pending_keys.empty()) {
- base::PostTask(FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&MockBrlapiConnection::NotifyDataReady,
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&MockBrlapiConnection::NotifyDataReady,
base::Unretained(this)));
}
return CONNECT_SUCCESS;
@@ -80,8 +80,8 @@ class MockBrlapiConnection : public BrlapiConnection {
data_->connected = false;
if (data_->reappear_on_disconnect) {
data_->display_columns *= 2;
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&BrailleControllerImpl::PokeSocketDirForTesting,
base::Unretained(BrailleControllerImpl::GetInstance())));
@@ -125,12 +125,17 @@ class MockBrlapiConnection : public BrlapiConnection {
}
}
+ bool GetCellSize(unsigned int* cell_size) override {
+ *cell_size = data_->cell_size;
+ return true;
+ }
+
private:
void NotifyDataReady() {
on_data_ready_.Run();
if (!data_->pending_keys.empty()) {
- base::PostTask(FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&MockBrlapiConnection::NotifyDataReady,
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&MockBrlapiConnection::NotifyDataReady,
base::Unretained(this)));
}
}
@@ -152,6 +157,7 @@ class BrailleDisplayPrivateApiTest : public ExtensionApiTest {
base::Bind(
&BrailleDisplayPrivateApiTest::CreateBrlapiConnection,
base::Unretained(this)));
+ BrailleControllerImpl::GetInstance()->skip_libbrlapi_so_load_ = true;
DisableAccessibilityManagerBraille();
}
@@ -178,6 +184,7 @@ class BrailleDisplayPrivateApiTest : public ExtensionApiTest {
IN_PROC_BROWSER_TEST_F(BrailleDisplayPrivateApiTest, WriteDots) {
connection_data_.display_columns = 11;
connection_data_.display_rows = 1;
+ connection_data_.cell_size = 6;
ASSERT_TRUE(RunComponentExtensionTest("braille_display_private/write_dots"))
<< message_;
ASSERT_EQ(3U, connection_data_.written_content.size());
@@ -195,6 +202,7 @@ IN_PROC_BROWSER_TEST_F(BrailleDisplayPrivateApiTest, WriteDots) {
IN_PROC_BROWSER_TEST_F(BrailleDisplayPrivateApiTest, KeyEvents) {
connection_data_.display_columns = 11;
connection_data_.display_rows = 1;
+ connection_data_.cell_size = 6;
// Braille navigation commands.
connection_data_.pending_keys.push_back(BRLAPI_KEY_TYPE_CMD |
@@ -259,6 +267,7 @@ IN_PROC_BROWSER_TEST_F(BrailleDisplayPrivateApiTest, KeyEvents) {
IN_PROC_BROWSER_TEST_F(BrailleDisplayPrivateApiTest, DisplayStateChanges) {
connection_data_.display_columns = 11;
connection_data_.display_rows = 1;
+ connection_data_.cell_size = 6;
connection_data_.pending_keys.push_back(kErrorKeyCode);
connection_data_.reappear_on_disconnect = true;
ASSERT_TRUE(RunComponentExtensionTest(
@@ -321,7 +330,7 @@ IN_PROC_BROWSER_TEST_F(BrailleDisplayPrivateAPIUserTest, KeyEventOnLockScreen) {
// Make sure the signin profile and active profile are different.
Profile* signin_profile = chromeos::ProfileHelper::GetSigninProfile();
Profile* user_profile = ProfileManager::GetActiveUserProfile();
- ASSERT_FALSE(signin_profile->IsSameProfile(user_profile))
+ ASSERT_FALSE(signin_profile->IsSameOrParent(user_profile))
<< signin_profile->GetDebugName() << " vs "
<< user_profile->GetDebugName();
diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.cc b/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.cc
index 4995fa32b19..3d04c0cdc44 100644
--- a/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.cc
+++ b/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.cc
@@ -7,6 +7,7 @@
#include <errno.h>
#include "base/files/file_descriptor_watcher_posix.h"
+#include "base/logging.h"
#include "base/memory/free_deleter.h"
#include "base/stl_util.h"
#include "base/system/sys_info.h"
@@ -44,6 +45,7 @@ class BrlapiConnectionImpl : public BrlapiConnection {
bool GetDisplaySize(unsigned int* rows, unsigned int* columns) override;
bool WriteDots(const std::vector<unsigned char>& cells) override;
int ReadKey(brlapi_keyCode_t* keyCode) override;
+ bool GetCellSize(unsigned int* cell_size) override;
private:
bool CheckConnected();
@@ -180,6 +182,23 @@ int BrlapiConnectionImpl::ReadKey(brlapi_keyCode_t* key_code) {
handle_.get(), 0 /*wait*/, key_code);
}
+bool BrlapiConnectionImpl::GetCellSize(unsigned int* cell_size) {
+ if (!CheckConnected()) {
+ return false;
+ }
+
+ brlapi_param_deviceCellSize_t device_cell_size;
+ ssize_t result = libbrlapi_loader_->brlapi__getParameter(
+ handle_.get(), BRLAPI_PARAM_DEVICE_CELL_SIZE, 0, BRLAPI_PARAMF_GLOBAL,
+ &device_cell_size, sizeof(device_cell_size));
+
+ if (result == -1 || result != sizeof(device_cell_size))
+ return false;
+
+ *cell_size = device_cell_size;
+ return true;
+}
+
bool BrlapiConnectionImpl::CheckConnected() {
if (!handle_) {
BrlapiError()->brlerrno = BRLAPI_ERROR_ILLEGAL_INSTRUCTION;
diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.h b/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.h
index 0d1fddeb00a..3a7d028e6a8 100644
--- a/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.h
+++ b/chromium/chrome/browser/extensions/api/braille_display_private/brlapi_connection.h
@@ -67,6 +67,9 @@ class BrlapiConnection {
// value.
virtual int ReadKey(brlapi_keyCode_t* keyCode) = 0;
+ // Gets the number of dots in a braille cell.
+ virtual bool GetCellSize(unsigned int* cell_size) = 0;
+
protected:
BrlapiConnection();
DISALLOW_COPY_AND_ASSIGN(BrlapiConnection);
diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/mock_braille_controller.cc b/chromium/chrome/browser/extensions/api/braille_display_private/mock_braille_controller.cc
index 0e07e7aa2e6..2b2b867331b 100644
--- a/chromium/chrome/browser/extensions/api/braille_display_private/mock_braille_controller.cc
+++ b/chromium/chrome/browser/extensions/api/braille_display_private/mock_braille_controller.cc
@@ -9,7 +9,7 @@ namespace api {
namespace braille_display_private {
MockBrailleController::MockBrailleController()
- : available_(false), observer_(NULL) {}
+ : available_(false), observer_(nullptr) {}
std::unique_ptr<DisplayState> MockBrailleController::GetDisplayState() {
std::unique_ptr<DisplayState> state(new DisplayState());
@@ -22,13 +22,13 @@ std::unique_ptr<DisplayState> MockBrailleController::GetDisplayState() {
}
void MockBrailleController::AddObserver(BrailleObserver* observer) {
- CHECK(observer_ == NULL);
+ CHECK(!observer_);
observer_ = observer;
}
void MockBrailleController::RemoveObserver(BrailleObserver* observer) {
CHECK(observer == observer_);
- observer_ = NULL;
+ observer_ = nullptr;
}
void MockBrailleController::SetAvailable(bool available) {
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 3ec6c150da5..a769041140d 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
@@ -12,7 +12,6 @@
#include <utility>
#include "base/bind.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/values.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h"
@@ -102,7 +101,7 @@ static_assert((kFilterableDataTypes &
"kFilterableDataTypes must be a subset of "
"ChromeBrowsingDataRemoverDelegate::FILTERABLE_DATA_TYPES");
-int MaskForKey(const char* key) {
+uint64_t MaskForKey(const char* key) {
if (strcmp(key, extension_browsing_data_api_constants::kAppCacheKey) == 0)
return content::BrowsingDataRemover::DATA_TYPE_APP_CACHE;
if (strcmp(key, extension_browsing_data_api_constants::kCacheKey) == 0)
@@ -133,12 +132,12 @@ int MaskForKey(const char* key) {
if (strcmp(key, extension_browsing_data_api_constants::kWebSQLKey) == 0)
return content::BrowsingDataRemover::DATA_TYPE_WEB_SQL;
- return 0;
+ return 0ULL;
}
// Returns false if any of the selected data types are not allowed to be
// deleted.
-bool IsRemovalPermitted(int removal_mask, PrefService* prefs) {
+bool IsRemovalPermitted(uint64_t removal_mask, PrefService* prefs) {
// Enterprise policy or user preference might prohibit deleting browser or
// download history.
if ((removal_mask & ChromeBrowsingDataRemoverDelegate::DATA_TYPE_HISTORY) ||
@@ -391,8 +390,8 @@ void BrowsingDataRemoverFunction::CheckRemovingPluginDataSupported(
if (!PluginDataRemoverHelper::IsSupported(plugin_prefs.get()))
removal_mask_ &= ~ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PLUGIN_DATA;
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&BrowsingDataRemoverFunction::StartRemoving, this));
}
#endif
@@ -456,7 +455,7 @@ void BrowsingDataRemoverFunction::StartRemoving() {
bool BrowsingDataRemoverFunction::ParseOriginTypeMask(
const base::DictionaryValue& options,
- int* origin_type_mask) {
+ uint64_t* origin_type_mask) {
// Parse the |options| dictionary to generate the origin set mask. Default to
// UNPROTECTED_WEB if the developer doesn't specify anything.
*origin_type_mask = content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB;
@@ -533,7 +532,7 @@ bool BrowsingDataRemoverFunction::ParseOrigins(const base::Value& list_value,
// Parses the |dataToRemove| argument to generate the removal mask.
// Returns false if parse was not successful, i.e. if 'dataToRemove' is not
// present or any data-type keys don't have supported (boolean) values.
-bool BrowsingDataRemoveFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveFunction::GetRemovalMask(uint64_t* removal_mask) {
base::DictionaryValue* data_to_remove;
if (!args_->GetDictionary(1, &data_to_remove))
return false;
@@ -556,73 +555,82 @@ bool BrowsingDataRemoveFunction::IsPauseSyncAllowed() {
return false;
}
-bool BrowsingDataRemoveAppcacheFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveAppcacheFunction::GetRemovalMask(
+ uint64_t* removal_mask) {
*removal_mask = content::BrowsingDataRemover::DATA_TYPE_APP_CACHE;
return true;
}
-bool BrowsingDataRemoveCacheFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveCacheFunction::GetRemovalMask(uint64_t* removal_mask) {
*removal_mask = content::BrowsingDataRemover::DATA_TYPE_CACHE;
return true;
}
-bool BrowsingDataRemoveCookiesFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveCookiesFunction::GetRemovalMask(uint64_t* removal_mask) {
*removal_mask = content::BrowsingDataRemover::DATA_TYPE_COOKIES;
return true;
}
-bool BrowsingDataRemoveDownloadsFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveDownloadsFunction::GetRemovalMask(
+ uint64_t* removal_mask) {
*removal_mask = content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS;
return true;
}
-bool BrowsingDataRemoveFileSystemsFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveFileSystemsFunction::GetRemovalMask(
+ uint64_t* removal_mask) {
*removal_mask = content::BrowsingDataRemover::DATA_TYPE_FILE_SYSTEMS;
return true;
}
-bool BrowsingDataRemoveFormDataFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveFormDataFunction::GetRemovalMask(
+ uint64_t* removal_mask) {
*removal_mask = ChromeBrowsingDataRemoverDelegate::DATA_TYPE_FORM_DATA;
return true;
}
-bool BrowsingDataRemoveHistoryFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveHistoryFunction::GetRemovalMask(uint64_t* removal_mask) {
*removal_mask = ChromeBrowsingDataRemoverDelegate::DATA_TYPE_HISTORY;
return true;
}
-bool BrowsingDataRemoveIndexedDBFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveIndexedDBFunction::GetRemovalMask(
+ uint64_t* removal_mask) {
*removal_mask = content::BrowsingDataRemover::DATA_TYPE_INDEXED_DB;
return true;
}
-bool BrowsingDataRemoveLocalStorageFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveLocalStorageFunction::GetRemovalMask(
+ uint64_t* removal_mask) {
*removal_mask = content::BrowsingDataRemover::DATA_TYPE_LOCAL_STORAGE;
return true;
}
-bool BrowsingDataRemovePluginDataFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemovePluginDataFunction::GetRemovalMask(
+ uint64_t* removal_mask) {
*removal_mask = ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PLUGIN_DATA;
return true;
}
-bool BrowsingDataRemovePasswordsFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemovePasswordsFunction::GetRemovalMask(
+ uint64_t* removal_mask) {
*removal_mask = ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PASSWORDS;
return true;
}
bool BrowsingDataRemoveServiceWorkersFunction::GetRemovalMask(
- int* removal_mask) {
+ uint64_t* removal_mask) {
*removal_mask = content::BrowsingDataRemover::DATA_TYPE_SERVICE_WORKERS;
return true;
}
-bool BrowsingDataRemoveCacheStorageFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveCacheStorageFunction::GetRemovalMask(
+ uint64_t* removal_mask) {
*removal_mask = content::BrowsingDataRemover::DATA_TYPE_CACHE_STORAGE;
return true;
}
-bool BrowsingDataRemoveWebSQLFunction::GetRemovalMask(int* removal_mask) {
+bool BrowsingDataRemoveWebSQLFunction::GetRemovalMask(uint64_t* removal_mask) {
*removal_mask = content::BrowsingDataRemover::DATA_TYPE_WEB_SQL;
return true;
}
diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h
index 6d39a5dfc38..e181262ab99 100644
--- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h
+++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h
@@ -116,7 +116,7 @@ class BrowsingDataRemoverFunction
// based on the API call they represent.
// Returns whether or not removal mask retrieval was successful.
// |removal_mask| is populated with the result, if successful.
- virtual bool GetRemovalMask(int* removal_mask) = 0;
+ virtual bool GetRemovalMask(uint64_t* removal_mask) = 0;
// Returns true if the data removal is allowed to pause Sync. Returns true by
// default. Subclasses can override it to return false and prevent Sync from
@@ -135,7 +135,7 @@ class BrowsingDataRemoverFunction
// that can be used with the BrowsingDataRemover.
// Returns true if parsing was successful.
bool ParseOriginTypeMask(const base::DictionaryValue& options,
- int* origin_type_mask);
+ uint64_t* origin_type_mask);
// Parses the developer-provided list of origins into |result|.
// Returns whether or not parsing was successful. In case of parse failure,
@@ -152,8 +152,8 @@ class BrowsingDataRemoverFunction
void OnTaskFinished();
base::Time remove_since_;
- int removal_mask_ = 0;
- int origin_type_mask_ = 0;
+ uint64_t removal_mask_ = 0;
+ uint64_t origin_type_mask_ = 0;
std::vector<url::Origin> origins_;
content::BrowsingDataFilterBuilder::Mode mode_ =
content::BrowsingDataFilterBuilder::Mode::BLACKLIST;
@@ -174,7 +174,7 @@ class BrowsingDataRemoveAppcacheFunction : public BrowsingDataRemoverFunction {
~BrowsingDataRemoveAppcacheFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemoveFunction : public BrowsingDataRemoverFunction {
@@ -185,7 +185,7 @@ class BrowsingDataRemoveFunction : public BrowsingDataRemoverFunction {
~BrowsingDataRemoveFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
bool IsPauseSyncAllowed() override;
};
@@ -198,7 +198,7 @@ class BrowsingDataRemoveCacheFunction : public BrowsingDataRemoverFunction {
~BrowsingDataRemoveCacheFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemoveCookiesFunction : public BrowsingDataRemoverFunction {
@@ -210,7 +210,7 @@ class BrowsingDataRemoveCookiesFunction : public BrowsingDataRemoverFunction {
~BrowsingDataRemoveCookiesFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemoveDownloadsFunction : public BrowsingDataRemoverFunction {
@@ -222,7 +222,7 @@ class BrowsingDataRemoveDownloadsFunction : public BrowsingDataRemoverFunction {
~BrowsingDataRemoveDownloadsFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemoveFileSystemsFunction
@@ -235,7 +235,7 @@ class BrowsingDataRemoveFileSystemsFunction
~BrowsingDataRemoveFileSystemsFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemoveFormDataFunction : public BrowsingDataRemoverFunction {
@@ -247,7 +247,7 @@ class BrowsingDataRemoveFormDataFunction : public BrowsingDataRemoverFunction {
~BrowsingDataRemoveFormDataFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemoveHistoryFunction : public BrowsingDataRemoverFunction {
@@ -259,7 +259,7 @@ class BrowsingDataRemoveHistoryFunction : public BrowsingDataRemoverFunction {
~BrowsingDataRemoveHistoryFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemoveIndexedDBFunction : public BrowsingDataRemoverFunction {
@@ -271,7 +271,7 @@ class BrowsingDataRemoveIndexedDBFunction : public BrowsingDataRemoverFunction {
~BrowsingDataRemoveIndexedDBFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemoveLocalStorageFunction
@@ -284,7 +284,7 @@ class BrowsingDataRemoveLocalStorageFunction
~BrowsingDataRemoveLocalStorageFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemovePluginDataFunction
@@ -297,7 +297,7 @@ class BrowsingDataRemovePluginDataFunction
~BrowsingDataRemovePluginDataFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemovePasswordsFunction : public BrowsingDataRemoverFunction {
@@ -309,7 +309,7 @@ class BrowsingDataRemovePasswordsFunction : public BrowsingDataRemoverFunction {
~BrowsingDataRemovePasswordsFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemoveServiceWorkersFunction
@@ -322,7 +322,7 @@ class BrowsingDataRemoveServiceWorkersFunction
~BrowsingDataRemoveServiceWorkersFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemoveCacheStorageFunction
@@ -335,7 +335,7 @@ class BrowsingDataRemoveCacheStorageFunction
~BrowsingDataRemoveCacheStorageFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
class BrowsingDataRemoveWebSQLFunction : public BrowsingDataRemoverFunction {
@@ -347,7 +347,7 @@ class BrowsingDataRemoveWebSQLFunction : public BrowsingDataRemoverFunction {
~BrowsingDataRemoveWebSQLFunction() override {}
// BrowsingDataRemoverFunction:
- bool GetRemovalMask(int* removal_mask) override;
+ bool GetRemovalMask(uint64_t* removal_mask) override;
};
#endif // CHROME_BROWSER_EXTENSIONS_API_BROWSING_DATA_BROWSING_DATA_API_H_
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 9713ed1a3d0..8dc6ced4f5b 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
@@ -29,6 +29,7 @@
#include "google_apis/gaia/google_service_auth_error.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "net/cookies/canonical_cookie.h"
+#include "net/cookies/cookie_inclusion_status.h"
#include "url/gurl.h"
using extension_function_test_utils::RunFunctionAndReturnSingleResult;
@@ -61,10 +62,9 @@ bool SetGaiaCookieForProfile(Profile* profile) {
bool success = false;
base::RunLoop loop;
base::OnceClosure loop_quit = loop.QuitClosure();
- base::OnceCallback<void(net::CanonicalCookie::CookieInclusionStatus)>
- callback = base::BindLambdaForTesting(
- [&success,
- &loop_quit](net::CanonicalCookie::CookieInclusionStatus s) {
+ base::OnceCallback<void(net::CookieInclusionStatus)> callback =
+ base::BindLambdaForTesting(
+ [&success, &loop_quit](net::CookieInclusionStatus s) {
success = s.IsInclude();
std::move(loop_quit).Run();
});
@@ -74,9 +74,9 @@ bool SetGaiaCookieForProfile(Profile* profile) {
cookie_manager->SetCanonicalCookie(
cookie, google_url, net::CookieOptions::MakeAllInclusive(),
mojo::WrapCallbackWithDefaultInvokeIfNotRun(
- std::move(callback), net::CanonicalCookie::CookieInclusionStatus(
- net::CanonicalCookie::CookieInclusionStatus::
- EXCLUDE_UNKNOWN_ERROR)));
+ std::move(callback),
+ net::CookieInclusionStatus(
+ net::CookieInclusionStatus::EXCLUDE_UNKNOWN_ERROR)));
loop.Run();
return success;
}
diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc
index eb659cae14f..953451e762f 100644
--- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc
@@ -72,15 +72,17 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase {
return remover_->GetLastUsedBeginTimeForTesting();
}
- int GetRemovalMask() { return remover_->GetLastUsedRemovalMaskForTesting(); }
+ uint64_t GetRemovalMask() {
+ return remover_->GetLastUsedRemovalMaskForTesting();
+ }
- int GetOriginTypeMask() {
+ uint64_t GetOriginTypeMask() {
return remover_->GetLastUsedOriginTypeMaskForTesting();
}
- int GetAsMask(const base::DictionaryValue* dict,
- std::string path,
- int mask_value) {
+ uint64_t GetAsMask(const base::DictionaryValue* dict,
+ std::string path,
+ uint64_t mask_value) {
bool result;
EXPECT_TRUE(dict->GetBoolean(path, &result)) << "for " << path;
return result ? mask_value : 0;
@@ -88,7 +90,7 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase {
void RunBrowsingDataRemoveFunctionAndCompareRemovalMask(
const std::string& data_types,
- int expected_mask) {
+ uint64_t expected_mask) {
auto function = base::MakeRefCounted<BrowsingDataRemoveFunction>();
SCOPED_TRACE(data_types);
EXPECT_EQ(NULL, RunFunctionAndReturnSingleResult(
@@ -99,15 +101,16 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase {
EXPECT_EQ(UNPROTECTED_WEB, GetOriginTypeMask());
}
- void RunBrowsingDataRemoveWithKeyAndCompareRemovalMask(const std::string& key,
- int expected_mask) {
+ void RunBrowsingDataRemoveWithKeyAndCompareRemovalMask(
+ const std::string& key,
+ uint64_t expected_mask) {
RunBrowsingDataRemoveFunctionAndCompareRemovalMask(
std::string("{\"") + key + "\": true}", expected_mask);
}
void RunBrowsingDataRemoveFunctionAndCompareOriginTypeMask(
const std::string& protectedStr,
- int expected_mask) {
+ uint64_t expected_mask) {
auto function = base::MakeRefCounted<BrowsingDataRemoveFunction>();
SCOPED_TRACE(protectedStr);
EXPECT_EQ(NULL, RunFunctionAndReturnSingleResult(
@@ -119,7 +122,7 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase {
}
template <class ShortcutFunction>
- void RunAndCompareRemovalMask(int expected_mask) {
+ void RunAndCompareRemovalMask(uint64_t expected_mask) {
scoped_refptr<ShortcutFunction> function = new ShortcutFunction();
SCOPED_TRACE(ShortcutFunction::function_name());
EXPECT_EQ(NULL,
@@ -161,8 +164,8 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase {
}
void SetPrefsAndVerifySettings(int data_type_flags,
- int expected_origin_type_mask,
- int expected_removal_mask) {
+ uint64_t expected_origin_type_mask,
+ uint64_t expected_removal_mask) {
PrefService* prefs = browser()->profile()->GetPrefs();
prefs->SetInteger(
browsing_data::prefs::kLastClearBrowsingDataTab,
@@ -200,8 +203,8 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase {
}
void SetBasicPrefsAndVerifySettings(int data_type_flags,
- int expected_origin_type_mask,
- int expected_removal_mask) {
+ uint64_t expected_origin_type_mask,
+ uint64_t expected_removal_mask) {
PrefService* prefs = browser()->profile()->GetPrefs();
prefs->SetInteger(
browsing_data::prefs::kLastClearBrowsingDataTab,
@@ -223,8 +226,8 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase {
VerifyRemovalMask(expected_origin_type_mask, expected_removal_mask);
}
- void VerifyRemovalMask(int expected_origin_type_mask,
- int expected_removal_mask) {
+ void VerifyRemovalMask(uint64_t expected_origin_type_mask,
+ uint64_t expected_removal_mask) {
scoped_refptr<BrowsingDataSettingsFunction> function =
new BrowsingDataSettingsFunction();
SCOPED_TRACE("settings");
@@ -238,7 +241,7 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase {
EXPECT_TRUE(result->GetDictionary("options", &options));
base::DictionaryValue* origin_types;
EXPECT_TRUE(options->GetDictionary("originTypes", &origin_types));
- int origin_type_mask =
+ uint64_t origin_type_mask =
GetAsMask(origin_types, "unprotectedWeb", UNPROTECTED_WEB) |
GetAsMask(origin_types, "protectedWeb", PROTECTED_WEB) |
GetAsMask(origin_types, "extension", EXTENSION);
@@ -246,7 +249,7 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase {
base::DictionaryValue* data_to_remove;
EXPECT_TRUE(result->GetDictionary("dataToRemove", &data_to_remove));
- int removal_mask =
+ uint64_t removal_mask =
GetAsMask(data_to_remove, "appcache",
content::BrowsingDataRemover::DATA_TYPE_APP_CACHE) |
GetAsMask(data_to_remove, "cache",
@@ -467,9 +470,9 @@ TEST_F(BrowsingDataApiTest, BrowsingDataRemovalInputFromSettings) {
prefs->SetBoolean(browsing_data::prefs::kDeleteHostedAppsData, false);
prefs->SetBoolean(browsing_data::prefs::kDeletePasswords, false);
prefs->SetBoolean(prefs::kClearPluginLSODataEnabled, false);
- int expected_mask = content::BrowsingDataRemover::DATA_TYPE_CACHE |
- content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS |
- ChromeBrowsingDataRemoverDelegate::DATA_TYPE_HISTORY;
+ uint64_t expected_mask = content::BrowsingDataRemover::DATA_TYPE_CACHE |
+ content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS |
+ ChromeBrowsingDataRemoverDelegate::DATA_TYPE_HISTORY;
std::string json;
// Scoping for the traces.
{
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
deleted file mode 100644
index 6ebf8e5713e..00000000000
--- a/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc
+++ /dev/null
@@ -1,420 +0,0 @@
-// 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.
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <algorithm>
-#include <cmath>
-#include <memory>
-#include <utility>
-#include <vector>
-
-#include "base/bind.h"
-#include "base/command_line.h"
-#include "base/macros.h"
-#include "base/run_loop.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/stringprintf.h"
-#include "base/threading/thread_restrictions.h"
-#include "build/build_config.h"
-#include "chrome/browser/extensions/extension_apitest.h"
-#include "chrome/common/chrome_switches.h"
-#include "content/public/common/content_features.h"
-#include "content/public/common/content_switches.h"
-#include "content/public/test/browser_test.h"
-#include "extensions/common/switches.h"
-#include "media/base/bind_to_current_loop.h"
-#include "media/base/video_frame.h"
-#include "media/cast/cast_config.h"
-#include "media/cast/cast_environment.h"
-#include "media/cast/test/utility/audio_utility.h"
-#include "media/cast/test/utility/default_config.h"
-#include "media/cast/test/utility/in_process_receiver.h"
-#include "media/cast/test/utility/net_utility.h"
-#include "media/cast/test/utility/standalone_cast_environment.h"
-#include "net/base/net_errors.h"
-#include "net/base/rand_callback.h"
-#include "net/log/net_log_source.h"
-#include "net/socket/udp_server_socket.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-using media::cast::test::GetFreeLocalPort;
-
-namespace extensions {
-
-class CastStreamingApiTest : public ExtensionApiTest {
- public:
- void SetUpCommandLine(base::CommandLine* command_line) override {
- ExtensionApiTest::SetUpCommandLine(command_line);
- command_line->AppendSwitchASCII(
- extensions::switches::kWhitelistedExtensionID,
- "ddchlicdkolnonkihahngkmmmjnjlkkf");
- command_line->AppendSwitchASCII(::switches::kWindowSize, "300,300");
- }
-};
-
-// Test running the test extension for Cast Mirroring API.
-IN_PROC_BROWSER_TEST_F(CastStreamingApiTest, Basics) {
- ASSERT_TRUE(RunExtensionSubtest("cast_streaming", "basics.html")) << message_;
-}
-
-IN_PROC_BROWSER_TEST_F(CastStreamingApiTest, Stats) {
- ASSERT_TRUE(RunExtensionSubtest("cast_streaming", "stats.html")) << message_;
-}
-
-IN_PROC_BROWSER_TEST_F(CastStreamingApiTest, BadLogging) {
- ASSERT_TRUE(RunExtensionSubtest("cast_streaming", "bad_logging.html"))
- << message_;
-}
-
-IN_PROC_BROWSER_TEST_F(CastStreamingApiTest, DestinationNotSet) {
- ASSERT_TRUE(RunExtensionSubtest("cast_streaming", "destination_not_set.html"))
- << message_;
-}
-
-IN_PROC_BROWSER_TEST_F(CastStreamingApiTest, StopNoStart) {
- ASSERT_TRUE(RunExtensionSubtest("cast_streaming", "stop_no_start.html"))
- << message_;
-}
-
-IN_PROC_BROWSER_TEST_F(CastStreamingApiTest, NullStream) {
- ASSERT_TRUE(RunExtensionSubtest("cast_streaming", "null_stream.html"))
- << message_;
-}
-
-namespace {
-
-struct YUVColor {
- int y;
- int u;
- int v;
-
- YUVColor() : y(0), u(0), v(0) {}
- YUVColor(int y_val, int u_val, int v_val) : y(y_val), u(u_val), v(v_val) {}
-};
-
-media::cast::FrameReceiverConfig WithFakeAesKeyAndIv(
- media::cast::FrameReceiverConfig config) {
- config.aes_key = "0123456789abcdef";
- config.aes_iv_mask = "fedcba9876543210";
- return config;
-}
-
-// An in-process Cast receiver that examines the audio/video frames being
-// received for expected colors and tones. Used in
-// CastStreamingApiTest.EndToEnd, below.
-class TestPatternReceiver : public media::cast::InProcessReceiver {
- public:
- explicit TestPatternReceiver(
- const scoped_refptr<media::cast::CastEnvironment>& cast_environment,
- const net::IPEndPoint& local_end_point)
- : InProcessReceiver(
- cast_environment,
- local_end_point,
- net::IPEndPoint(),
- WithFakeAesKeyAndIv(media::cast::GetDefaultAudioReceiverConfig()),
- WithFakeAesKeyAndIv(media::cast::GetDefaultVideoReceiverConfig())) {
- }
-
- ~TestPatternReceiver() override {}
-
- void AddExpectedTone(int tone_frequency) {
- expected_tones_.push_back(tone_frequency);
- }
-
- void AddExpectedColor(const YUVColor& yuv_color) {
- expected_yuv_colors_.push_back(yuv_color);
- }
-
- // Blocks the caller until all expected tones and colors have been observed.
- void WaitForExpectedTonesAndColors() {
- base::RunLoop run_loop;
- cast_env()->PostTask(
- media::cast::CastEnvironment::MAIN, FROM_HERE,
- base::BindOnce(
- &TestPatternReceiver::NotifyOnceObservedAllTonesAndColors,
- base::Unretained(this),
- media::BindToCurrentLoop(run_loop.QuitClosure())));
- run_loop.Run();
- }
-
- private:
- void NotifyOnceObservedAllTonesAndColors(const base::Closure& done_callback) {
- DCHECK(cast_env()->CurrentlyOn(media::cast::CastEnvironment::MAIN));
- done_callback_ = done_callback;
- MaybeRunDoneCallback();
- }
-
- void MaybeRunDoneCallback() {
- DCHECK(cast_env()->CurrentlyOn(media::cast::CastEnvironment::MAIN));
- if (done_callback_.is_null())
- return;
- if (expected_tones_.empty() && expected_yuv_colors_.empty()) {
- std::move(done_callback_).Run();
- } else {
- LOG(INFO) << "Waiting to encounter " << expected_tones_.size()
- << " more tone(s) and " << expected_yuv_colors_.size()
- << " more color(s).";
- }
- }
-
- // Invoked by InProcessReceiver for each received audio frame.
- void OnAudioFrame(std::unique_ptr<media::AudioBus> audio_frame,
- base::TimeTicks playout_time,
- bool is_continuous) override {
- DCHECK(cast_env()->CurrentlyOn(media::cast::CastEnvironment::MAIN));
-
- if (audio_frame->frames() <= 0) {
- NOTREACHED() << "OnAudioFrame called with no samples?!?";
- return;
- }
-
- if (done_callback_.is_null() || expected_tones_.empty())
- return; // No need to waste CPU doing analysis on the signal.
-
- // Assume the audio signal is a single sine wave (it can have some
- // low-amplitude noise). Count zero crossings, and extrapolate the
- // frequency of the sine wave in |audio_frame|.
- int crossings = 0;
- for (int ch = 0; ch < audio_frame->channels(); ++ch) {
- crossings += media::cast::CountZeroCrossings(audio_frame->channel(ch),
- audio_frame->frames());
- }
- crossings /= audio_frame->channels(); // Take the average.
- const float seconds_per_frame =
- audio_frame->frames() / static_cast<float>(audio_config().rtp_timebase);
- const float frequency = crossings / seconds_per_frame / 2.0f;
- VLOG(1) << "Current audio tone frequency: " << frequency;
-
- const int kTargetWindowHz = 20;
- for (auto it = expected_tones_.begin(); it != expected_tones_.end(); ++it) {
- if (abs(static_cast<int>(frequency) - *it) < kTargetWindowHz) {
- LOG(INFO) << "Heard tone at frequency " << *it << " Hz.";
- expected_tones_.erase(it);
- MaybeRunDoneCallback();
- break;
- }
- }
- }
-
- void OnVideoFrame(scoped_refptr<media::VideoFrame> video_frame,
- base::TimeTicks playout_time,
- bool is_continuous) override {
- DCHECK(cast_env()->CurrentlyOn(media::cast::CastEnvironment::MAIN));
-
- CHECK(video_frame->format() == media::PIXEL_FORMAT_YV12 ||
- video_frame->format() == media::PIXEL_FORMAT_I420 ||
- video_frame->format() == media::PIXEL_FORMAT_I420A);
-
- if (done_callback_.is_null() || expected_yuv_colors_.empty())
- return; // No need to waste CPU doing analysis on the frame.
-
- // Take the median value of each plane because the test image will contain a
- // letterboxed content region of mostly a solid color plus a small piece of
- // "something" that's animating to keep the tab capture pipeline generating
- // new frames.
- const gfx::Rect region = FindLetterboxedContentRegion(*video_frame);
- YUVColor current_color;
- current_color.y = ComputeMedianIntensityInRegionInPlane(
- region,
- video_frame->stride(media::VideoFrame::kYPlane),
- video_frame->data(media::VideoFrame::kYPlane));
- current_color.u = ComputeMedianIntensityInRegionInPlane(
- gfx::ScaleToEnclosedRect(region, 0.5f),
- video_frame->stride(media::VideoFrame::kUPlane),
- video_frame->data(media::VideoFrame::kUPlane));
- current_color.v = ComputeMedianIntensityInRegionInPlane(
- gfx::ScaleToEnclosedRect(region, 0.5f),
- video_frame->stride(media::VideoFrame::kVPlane),
- video_frame->data(media::VideoFrame::kVPlane));
- VLOG(1) << "Current video color: yuv(" << current_color.y << ", "
- << current_color.u << ", " << current_color.v << ')';
-
- // Note: The range of acceptable colors is quite large because there's no
- // way to know whether software compositing is being used for screen
- // capture; and, if software compositing is being used, there is no color
- // space management and color values can be off by a lot. That said, color
- // accuracy is being tested by a suite of content_browsertests.
- const int kTargetWindow = 50;
- for (auto it = expected_yuv_colors_.begin();
- it != expected_yuv_colors_.end(); ++it) {
- if (abs(current_color.y - it->y) < kTargetWindow &&
- abs(current_color.u - it->u) < kTargetWindow &&
- abs(current_color.v - it->v) < kTargetWindow) {
- LOG(INFO) << "Saw expected color yuv(" << it->y << ", " << it->u << ", "
- << it->v << ") as yuv(" << current_color.y << ", "
- << current_color.u << ", " << current_color.v << ").";
- expected_yuv_colors_.erase(it);
- MaybeRunDoneCallback();
- break;
- }
- }
- }
-
- // Return the region that excludes the black letterboxing borders surrounding
- // the content within |frame|, if any.
- static gfx::Rect FindLetterboxedContentRegion(
- const media::VideoFrame& frame) {
- const int kNonBlackIntensityThreshold = 20; // 16 plus some fuzz.
- const int width = frame.row_bytes(media::VideoFrame::kYPlane);
- const int height = frame.rows(media::VideoFrame::kYPlane);
- const int stride = frame.stride(media::VideoFrame::kYPlane);
-
- gfx::Rect result;
-
- // Scan from the bottom-right until the first non-black pixel is
- // encountered.
- for (int y = height - 1; y >= 0; --y) {
- const uint8_t* const start =
- frame.data(media::VideoFrame::kYPlane) + y * stride;
- const uint8_t* const end = start + width;
- for (const uint8_t* p = end - 1; p >= start; --p) {
- if (*p > kNonBlackIntensityThreshold) {
- result.set_width(p - start + 1);
- result.set_height(y + 1);
- y = 0; // Discontinue outer loop.
- break;
- }
- }
- }
-
- // Scan from the upper-left until the first non-black pixel is encountered.
- for (int y = 0; y < result.height(); ++y) {
- const uint8_t* const start =
- frame.data(media::VideoFrame::kYPlane) + y * stride;
- const uint8_t* const end = start + result.width();
- for (const uint8_t* p = start; p < end; ++p) {
- if (*p > kNonBlackIntensityThreshold) {
- result.set_x(p - start);
- result.set_width(result.width() - result.x());
- result.set_y(y);
- result.set_height(result.height() - result.y());
- y = result.height(); // Discontinue outer loop.
- break;
- }
- }
- }
-
- return result;
- }
-
- static uint8_t ComputeMedianIntensityInRegionInPlane(const gfx::Rect& region,
- int stride,
- const uint8_t* data) {
- if (region.IsEmpty())
- return 0;
- const size_t num_values = region.size().GetArea();
- std::unique_ptr<uint8_t[]> values(new uint8_t[num_values]);
- for (int y = 0; y < region.height(); ++y) {
- memcpy(values.get() + y * region.width(),
- data + (region.y() + y) * stride + region.x(),
- region.width());
- }
- const size_t middle_idx = num_values / 2;
- std::nth_element(values.get(),
- values.get() + middle_idx,
- values.get() + num_values);
- return values[middle_idx];
- }
-
- std::vector<int> expected_tones_;
- std::vector<YUVColor> expected_yuv_colors_;
- base::Closure done_callback_;
-
- DISALLOW_COPY_AND_ASSIGN(TestPatternReceiver);
-};
-
-} // namespace
-
-class CastStreamingApiTestWithPixelOutput
- : public CastStreamingApiTest,
- public testing::WithParamInterface<bool> {
- public:
-
- void SetUp() override {
- EnablePixelOutput();
- CastStreamingApiTest::SetUp();
- }
-
- void SetUpCommandLine(base::CommandLine* command_line) override {
- command_line->AppendSwitchASCII(::switches::kWindowSize, "128,128");
- CastStreamingApiTest::SetUpCommandLine(command_line);
- }
-
- private:
- base::test::ScopedFeatureList audio_service_features_;
-};
-
-// Tests the Cast streaming API and its basic functionality end-to-end. An
-// extension subtest is run to generate test content, capture that content, and
-// use the API to send it out. At the same time, this test launches an
-// in-process Cast receiver, listening on a localhost UDP socket, to receive the
-// content and check whether it matches expectations.
-#if defined(NDEBUG) && !defined(OS_MACOSX)
-#define MAYBE_EndToEnd EndToEnd
-#else
-// Flaky on Mac: https://crbug.com/841387
-#define MAYBE_EndToEnd DISABLED_EndToEnd // crbug.com/396413
-#endif
-IN_PROC_BROWSER_TEST_F(CastStreamingApiTestWithPixelOutput, MAYBE_EndToEnd) {
- std::unique_ptr<net::UDPServerSocket> receive_socket(
- new net::UDPServerSocket(NULL, net::NetLogSource()));
- receive_socket->AllowAddressReuse();
- ASSERT_EQ(net::OK, receive_socket->Listen(GetFreeLocalPort()));
- net::IPEndPoint receiver_end_point;
- ASSERT_EQ(net::OK, receive_socket->GetLocalAddress(&receiver_end_point));
- receive_socket.reset();
-
- // Start the in-process receiver that examines audio/video for the expected
- // test patterns.
- const scoped_refptr<media::cast::StandaloneCastEnvironment> cast_environment(
- new media::cast::StandaloneCastEnvironment());
- TestPatternReceiver* const receiver =
- new TestPatternReceiver(cast_environment, receiver_end_point);
-
- // Launch the page that: 1) renders the source content; 2) uses the
- // chrome.tabCapture and chrome.cast.streaming APIs to capture its content and
- // stream using Cast; and 3) calls chrome.test.succeed() once it is
- // operational.
- const std::string page_url = base::StringPrintf(
- "end_to_end_sender.html?port=%d&aesKey=%s&aesIvMask=%s",
- receiver_end_point.port(),
- base::HexEncode(receiver->audio_config().aes_key.data(),
- receiver->audio_config().aes_key.size()).c_str(),
- base::HexEncode(receiver->audio_config().aes_iv_mask.data(),
- receiver->audio_config().aes_iv_mask.size()).c_str());
- ASSERT_TRUE(RunExtensionSubtest("cast_streaming", page_url)) << message_;
-
- // Examine the Cast receiver for expected audio/video test patterns. The
- // colors and tones specified here must match those in end_to_end_sender.js.
- // Note that we do not check that the color and tone are received
- // simultaneously since A/V sync should be measured in perf tests.
- receiver->AddExpectedTone(200 /* Hz */);
- receiver->AddExpectedTone(500 /* Hz */);
- receiver->AddExpectedTone(1800 /* Hz */);
- receiver->AddExpectedColor(YUVColor(63, 102, 239)); // rgb(255, 0, 0)
- receiver->AddExpectedColor(YUVColor(173, 41, 26)); // rgb(0, 255, 0)
- receiver->AddExpectedColor(YUVColor(32, 239, 117)); // rgb(0, 0, 255)
- receiver->Start();
- receiver->WaitForExpectedTonesAndColors();
- receiver->Stop();
-
- delete receiver;
- base::ScopedAllowBlockingForTesting allow_blocking;
- cast_environment->Shutdown();
-}
-
-#if !defined(OS_MACOSX)
-#define MAYBE_RtpStreamError RtpStreamError
-#else
-// Flaky on Mac https://crbug.com/841986
-#define MAYBE_RtpStreamError DISABLED_RtpStreamError
-#endif
-IN_PROC_BROWSER_TEST_F(CastStreamingApiTestWithPixelOutput,
- MAYBE_RtpStreamError) {
- ASSERT_TRUE(RunExtensionSubtest("cast_streaming", "rtp_stream_error.html"));
-}
-
-} // namespace extensions
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 69a5d995237..5be83c91173 100644
--- a/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc
+++ b/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc
@@ -742,9 +742,14 @@ IN_PROC_BROWSER_TEST_P(CastV2PerformanceTest, DISABLED_Performance) {
// Load the extension and test page, and tell the extension to start tab
// capture + Cast Streaming.
- LoadExtension(GetApiTestDataDir()
- .AppendASCII("cast_streaming")
- .AppendASCII("perftest_extension"));
+
+ // TODO(https://crbug.com/974427): Update test to no longer require
+ // extension APIs.
+
+ // LoadExtension(GetApiTestDataDir()
+ // .AppendASCII("cast_streaming")
+ // .AppendASCII("perftest_extension"));
+
NavigateToTestPage(test_page_html_);
const base::Value response = SendMessageToExtension(base::StringPrintf(
"{start:true, enableAutoThrottling:%s, maxFrameRate:%d, recvPort:%d,"
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 80918c5ca00..472210d290f 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
@@ -249,8 +249,8 @@ CertificateProviderStopPinRequestFunction::
ExtensionFunction::ResponseAction
CertificateProviderStopPinRequestFunction::Run() {
- std::unique_ptr<api_cp::RequestPin::Params> params(
- api_cp::RequestPin::Params::Create(*args_));
+ std::unique_ptr<api_cp::StopPinRequest::Params> params(
+ api_cp::StopPinRequest::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
// TODO(crbug.com/1046860): Remove logging after stabilizing the feature.
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 57049879e4c..f9fe19fc02a 100644
--- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc
+++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc
@@ -46,15 +46,12 @@
#include "chrome/common/url_constants.h"
#include "chrome/common/webui_url_constants.h"
#include "components/pdf/browser/pdf_web_contents_helper.h"
-#include "components/performance_manager/embedder/performance_manager_registry.h"
-#include "components/performance_manager/public/performance_manager.h"
#include "components/signin/core/browser/signin_header_helper.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_frame_host.h"
#include "content/public/browser/web_contents.h"
-#include "extensions/browser/api/management/supervised_user_service_delegate.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"
@@ -62,6 +59,7 @@
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/guest_view/web_view/web_view_guest.h"
#include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
+#include "extensions/browser/supervised_user_extensions_delegate.h"
#include "extensions/browser/value_store/value_store_factory.h"
#include "google_apis/gaia/gaia_urls.h"
#include "printing/buildflags/buildflags.h"
@@ -81,7 +79,7 @@
#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
// TODO(https://crbug.com/1060801): Here and elsewhere, possibly switch build
// flag to #if defined(OS_CHROMEOS)
-#include "chrome/browser/supervised_user/supervised_user_service_management_api_delegate.h"
+#include "chrome/browser/supervised_user/supervised_user_extensions_delegate_impl.h"
#endif
namespace extensions {
@@ -116,10 +114,6 @@ void ChromeExtensionsAPIClient::AttachWebContentsHelpers(
extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
web_contents);
- if (auto* performance_manager_registry =
- performance_manager::PerformanceManagerRegistry::GetInstance()) {
- performance_manager_registry->CreatePageNodeForWebContents(web_contents);
- }
}
bool ChromeExtensionsAPIClient::ShouldHideResponseHeader(
@@ -340,10 +334,10 @@ ManagementAPIDelegate* ChromeExtensionsAPIClient::CreateManagementAPIDelegate()
return new ChromeManagementAPIDelegate;
}
-std::unique_ptr<SupervisedUserServiceDelegate>
-ChromeExtensionsAPIClient::CreateSupervisedUserServiceDelegate() const {
+std::unique_ptr<SupervisedUserExtensionsDelegate>
+ChromeExtensionsAPIClient::CreateSupervisedUserExtensionsDelegate() const {
#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
- return std::make_unique<SupervisedUserServiceManagementAPIDelegate>();
+ return std::make_unique<SupervisedUserExtensionsDelegateImpl>();
#else
return nullptr;
#endif
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 a9498af9053..98d45c99383 100644
--- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h
+++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h
@@ -67,8 +67,8 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient {
std::unique_ptr<VirtualKeyboardDelegate> CreateVirtualKeyboardDelegate(
content::BrowserContext* browser_context) const override;
ManagementAPIDelegate* CreateManagementAPIDelegate() const override;
- std::unique_ptr<SupervisedUserServiceDelegate>
- CreateSupervisedUserServiceDelegate() const override;
+ std::unique_ptr<SupervisedUserExtensionsDelegate>
+ CreateSupervisedUserExtensionsDelegate() const override;
std::unique_ptr<DisplayInfoProvider> CreateDisplayInfoProvider()
const override;
diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc
index cd71b0bd21c..f21fdbb45dd 100644
--- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc
+++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc
@@ -33,6 +33,7 @@
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
+#include "components/content_settings/core/common/features.h"
#include "components/permissions/features.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
@@ -311,6 +312,16 @@ ContentSettingsContentSettingSetFunction::Run() {
store->SetExtensionContentSetting(extension_id(), primary_pattern,
secondary_pattern, content_type,
resource_identifier, setting, scope);
+
+ if (base::FeatureList::IsEnabled(
+ content_settings::kDisallowWildcardsInPluginContentSettings) &&
+ content_type == ContentSettingsType::PLUGINS &&
+ primary_pattern.HasHostWildcards()) {
+ WriteToConsole(
+ blink::mojom::ConsoleMessageLevel::kError,
+ content_settings_api_constants::kWildcardPatternsForPluginsDisallowed);
+ }
+
return RespondNow(NoArguments());
}
diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api_constants.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api_constants.cc
index efd89b9c283..27aa53d3720 100644
--- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api_constants.cc
+++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api_constants.cc
@@ -23,6 +23,8 @@ const char kIncognitoSessionOnlyError[] =
"You cannot read incognito content settings when no incognito window "
"is open.";
const char kInvalidUrlError[] = "The URL \"*\" is invalid.";
-
+const char kWildcardPatternsForPluginsDisallowed[] =
+ "Host wildcards ('*') and \"<all_urls>\" are no longer "
+ "supported in `primaryPattern` for `plugins`.";
} // namespace content_settings_api_constants
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api_constants.h b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api_constants.h
index 492fb00260e..65cef1f6b24 100644
--- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api_constants.h
+++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api_constants.h
@@ -23,7 +23,7 @@ extern const char kSecondaryPatternKey[];
extern const char kIncognitoContextError[];
extern const char kIncognitoSessionOnlyError[];
extern const char kInvalidUrlError[];
-
+extern const char kWildcardPatternsForPluginsDisallowed[];
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc
index b34033a96b1..60626f7d26f 100644
--- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc
@@ -18,15 +18,19 @@
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/extensions/api/content_settings/content_settings_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
+#include "chrome/browser/permissions/permission_manager_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
+#include "components/content_settings/core/common/features.h"
#include "components/keep_alive_registry/keep_alive_types.h"
#include "components/keep_alive_registry/scoped_keep_alive.h"
#include "components/permissions/features.h"
+#include "components/permissions/permission_manager.h"
+#include "components/permissions/permission_result.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/plugin_service.h"
@@ -36,12 +40,15 @@
#include "content/public/test/test_utils.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/test_extension_registry_observer.h"
+#include "extensions/common/scoped_worker_based_extensions_channel.h"
namespace extensions {
+using ContextType = ExtensionApiTest::ContextType;
+
class ExtensionContentSettingsApiTest : public ExtensionApiTest {
public:
- ExtensionContentSettingsApiTest() : profile_(NULL) {}
+ ExtensionContentSettingsApiTest() : profile_(nullptr) {}
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
@@ -89,7 +96,7 @@ class ExtensionContentSettingsApiTest : public ExtensionApiTest {
map->GetContentSetting(example_url, example_url,
ContentSettingsType::JAVASCRIPT, std::string()));
EXPECT_EQ(
- CONTENT_SETTING_ALLOW,
+ CONTENT_SETTING_BLOCK,
map->GetContentSetting(example_url, example_url,
ContentSettingsType::PLUGINS, std::string()));
EXPECT_EQ(
@@ -134,7 +141,7 @@ class ExtensionContentSettingsApiTest : public ExtensionApiTest {
EXPECT_EQ(CONTENT_SETTING_BLOCK,
map->GetContentSetting(url, url, ContentSettingsType::JAVASCRIPT,
std::string()));
- EXPECT_EQ(CONTENT_SETTING_DETECT_IMPORTANT_CONTENT,
+ EXPECT_EQ(CONTENT_SETTING_BLOCK,
map->GetContentSetting(url, url, ContentSettingsType::PLUGINS,
std::string()));
EXPECT_EQ(CONTENT_SETTING_ALLOW,
@@ -256,6 +263,42 @@ class ExtensionContentSettingsApiTest : public ExtensionApiTest {
std::unique_ptr<ScopedKeepAlive> keep_alive_;
};
+class ExtensionContentSettingsApiLazyTest
+ : public ExtensionContentSettingsApiTest,
+ public testing::WithParamInterface<ContextType> {
+ public:
+ void SetUp() override {
+ ExtensionContentSettingsApiTest::SetUp();
+ // Service Workers are currently only available on certain channels, so set
+ // the channel for those tests.
+ if (GetParam() == ContextType::kServiceWorker)
+ current_channel_ = std::make_unique<ScopedWorkerBasedExtensionsChannel>();
+ }
+
+ protected:
+ bool RunLazyTest(const std::string& extension_name) {
+ return RunLazyTestWithArg(extension_name, nullptr);
+ }
+
+ bool RunLazyTestWithArg(const std::string& extension_name, const char* arg) {
+ int browser_test_flags = kFlagNone;
+ if (GetParam() == ContextType::kServiceWorker)
+ browser_test_flags |= kFlagRunAsServiceWorkerBasedExtension;
+
+ return RunExtensionTestWithFlagsAndArg(extension_name, arg,
+ browser_test_flags, kFlagNone);
+ }
+
+ std::unique_ptr<ScopedWorkerBasedExtensionsChannel> current_channel_;
+};
+
+INSTANTIATE_TEST_SUITE_P(EventPage,
+ ExtensionContentSettingsApiLazyTest,
+ ::testing::Values(ContextType::kEventPage));
+INSTANTIATE_TEST_SUITE_P(ServiceWorker,
+ ExtensionContentSettingsApiLazyTest,
+ ::testing::Values(ContextType::kServiceWorker));
+
IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest, Standard) {
CheckContentSettingsDefault();
@@ -285,7 +328,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest, Standard) {
// brittle or just have the JS side look for the additional plugins.
//
// Flaky on the trybots. See http://crbug.com/96725.
-IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest,
+IN_PROC_BROWSER_TEST_P(ExtensionContentSettingsApiLazyTest,
DISABLED_GetResourceIdentifiers) {
base::FilePath::CharType kFooPath[] =
FILE_PATH_LITERAL("/plugins/foo.plugin");
@@ -307,21 +350,22 @@ IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest,
base::ASCIIToUTF16("bar")),
false);
- EXPECT_TRUE(RunExtensionTest("content_settings/getresourceidentifiers"))
+ EXPECT_TRUE(RunLazyTest("content_settings/getresourceidentifiers"))
<< message_;
}
-IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest,
+IN_PROC_BROWSER_TEST_P(ExtensionContentSettingsApiLazyTest,
UnsupportedDefaultSettings) {
const char kExtensionPath[] = "content_settings/unsupporteddefaultsettings";
- EXPECT_TRUE(RunExtensionSubtest(kExtensionPath, "test.html")) << message_;
+ EXPECT_TRUE(RunExtensionTest(kExtensionPath)) << message_;
}
// Tests if an extension clearing content settings for one content type leaves
// the others unchanged.
-IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest, ClearProperlyGranular) {
+IN_PROC_BROWSER_TEST_P(ExtensionContentSettingsApiLazyTest,
+ ClearProperlyGranular) {
const char kExtensionPath[] = "content_settings/clearproperlygranular";
- EXPECT_TRUE(RunExtensionSubtest(kExtensionPath, "test.html")) << message_;
+ EXPECT_TRUE(RunLazyTest(kExtensionPath)) << message_;
}
// Tests if changing permissions in incognito mode keeps the previous state of
@@ -333,9 +377,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest, IncognitoIsolation) {
std::vector<int> content_settings_before = GetContentSettingsSnapshot(url);
// Run extension, set all permissions to allow, and check if they are changed.
- EXPECT_TRUE(RunExtensionSubtest("content_settings/incognitoisolation",
- "test.html?allow", kFlagEnableIncognito,
- kFlagUseIncognito))
+ EXPECT_TRUE(RunExtensionSubtestWithArgAndFlags(
+ "content_settings/incognitoisolation", "test.html", "allow",
+ kFlagEnableIncognito, kFlagUseIncognito))
<< message_;
// Get content settings after running extension to ensure nothing is changed.
@@ -343,9 +387,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest, IncognitoIsolation) {
EXPECT_EQ(content_settings_before, content_settings_after);
// Run extension, set all permissions to block, and check if they are changed.
- EXPECT_TRUE(RunExtensionSubtest("content_settings/incognitoisolation",
- "test.html?block", kFlagEnableIncognito,
- kFlagUseIncognito))
+ EXPECT_TRUE(RunExtensionSubtestWithArgAndFlags(
+ "content_settings/incognitoisolation", "test.html", "block",
+ kFlagEnableIncognito, kFlagUseIncognito))
<< message_;
// Get content settings after running extension to ensure nothing is changed.
@@ -356,16 +400,16 @@ IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest, IncognitoIsolation) {
// Tests if changing incognito mode permissions in regular profile are rejected.
IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest,
IncognitoNotAllowedInRegular) {
- EXPECT_FALSE(RunExtensionSubtest("content_settings/incognitoisolation",
- "test.html?allow"))
+ EXPECT_FALSE(RunExtensionSubtestWithArg("content_settings/incognitoisolation",
+ "test.html", "allow"))
<< message_;
}
-IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest,
+IN_PROC_BROWSER_TEST_P(ExtensionContentSettingsApiLazyTest,
EmbeddedSettingsMetric) {
base::HistogramTester histogram_tester;
const char kExtensionPath[] = "content_settings/embeddedsettingsmetric";
- EXPECT_TRUE(RunExtensionSubtest(kExtensionPath, "test.html")) << message_;
+ EXPECT_TRUE(RunLazyTest(kExtensionPath)) << message_;
size_t num_values = 0;
int images_type = ContentSettingTypeToHistogramValue(
@@ -391,7 +435,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest,
}
class ExtensionContentSettingsApiTestWithPermissionDelegationDisabled
- : public ExtensionContentSettingsApiTest {
+ : public ExtensionContentSettingsApiLazyTest {
public:
ExtensionContentSettingsApiTestWithPermissionDelegationDisabled() {
feature_list_.InitAndDisableFeature(
@@ -402,8 +446,18 @@ class ExtensionContentSettingsApiTestWithPermissionDelegationDisabled
base::test::ScopedFeatureList feature_list_;
};
+INSTANTIATE_TEST_SUITE_P(
+ EventPage,
+ ExtensionContentSettingsApiTestWithPermissionDelegationDisabled,
+ ::testing::Values(ContextType::kEventPage));
+
+INSTANTIATE_TEST_SUITE_P(
+ ServiceWorker,
+ ExtensionContentSettingsApiTestWithPermissionDelegationDisabled,
+ ::testing::Values(ContextType::kServiceWorker));
+
class ExtensionContentSettingsApiTestWithPermissionDelegationEnabled
- : public ExtensionContentSettingsApiTest {
+ : public ExtensionContentSettingsApiLazyTest {
public:
ExtensionContentSettingsApiTestWithPermissionDelegationEnabled() {
feature_list_.InitAndEnableFeature(
@@ -414,20 +468,76 @@ class ExtensionContentSettingsApiTestWithPermissionDelegationEnabled
base::test::ScopedFeatureList feature_list_;
};
-IN_PROC_BROWSER_TEST_F(
+INSTANTIATE_TEST_SUITE_P(
+ EventPage,
+ ExtensionContentSettingsApiTestWithPermissionDelegationEnabled,
+ ::testing::Values(ContextType::kEventPage));
+
+INSTANTIATE_TEST_SUITE_P(
+ ServiceWorker,
+ ExtensionContentSettingsApiTestWithPermissionDelegationEnabled,
+ ::testing::Values(ContextType::kServiceWorker));
+
+IN_PROC_BROWSER_TEST_P(
ExtensionContentSettingsApiTestWithPermissionDelegationDisabled,
EmbeddedSettings) {
const char kExtensionPath[] = "content_settings/embeddedsettings";
- EXPECT_TRUE(RunExtensionSubtest(kExtensionPath, "test.html")) << message_;
+ EXPECT_TRUE(RunLazyTestWithArg(kExtensionPath, nullptr)) << message_;
}
-IN_PROC_BROWSER_TEST_F(
+IN_PROC_BROWSER_TEST_P(
ExtensionContentSettingsApiTestWithPermissionDelegationEnabled,
EmbeddedSettings) {
const char kExtensionPath[] = "content_settings/embeddedsettings";
- EXPECT_TRUE(
- RunExtensionSubtest(kExtensionPath, "test.html?permission_delegation"))
- << message_;
+ EXPECT_TRUE(RunLazyTestWithArg(kExtensionPath, "permission")) << message_;
+}
+
+class ExtensionContentSettingsApiTestWithWildcardMatchingDisabled
+ : public ExtensionContentSettingsApiLazyTest {
+ public:
+ ExtensionContentSettingsApiTestWithWildcardMatchingDisabled() {
+ scoped_feature_list_.InitAndEnableFeature(
+ content_settings::kDisallowWildcardsInPluginContentSettings);
+ }
+
+ private:
+ base::test::ScopedFeatureList scoped_feature_list_;
+};
+
+INSTANTIATE_TEST_SUITE_P(
+ EventPage,
+ ExtensionContentSettingsApiTestWithWildcardMatchingDisabled,
+ ::testing::Values(ContextType::kEventPage));
+
+INSTANTIATE_TEST_SUITE_P(
+ ServiceWorker,
+ ExtensionContentSettingsApiTestWithWildcardMatchingDisabled,
+ ::testing::Values(ContextType::kServiceWorker));
+
+IN_PROC_BROWSER_TEST_P(
+ ExtensionContentSettingsApiTestWithWildcardMatchingDisabled,
+ PluginTest) {
+ constexpr char kExtensionPath[] = "content_settings/pluginswildcardmatching";
+ EXPECT_TRUE(RunLazyTest(kExtensionPath)) << message_;
+
+ constexpr char kGoogleMailUrl[] = "http://mail.google.com:443";
+ constexpr char kGoogleDriveUrl[] = "http://drive.google.com:443";
+
+ permissions::PermissionManager* permission_manager =
+ PermissionManagerFactory::GetForProfile(browser()->profile());
+ EXPECT_EQ(
+ permission_manager
+ ->GetPermissionStatus(ContentSettingsType::PLUGINS,
+ GURL(kGoogleMailUrl), GURL(kGoogleMailUrl))
+ .content_setting,
+ ContentSetting::CONTENT_SETTING_BLOCK);
+
+ EXPECT_EQ(
+ permission_manager
+ ->GetPermissionStatus(ContentSettingsType::PLUGINS,
+ GURL(kGoogleDriveUrl), GURL(kGoogleDriveUrl))
+ .content_setting,
+ ContentSetting::CONTENT_SETTING_ALLOW);
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc
index a8042a43b0e..40b9e99f0de 100644
--- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc
+++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc
@@ -32,6 +32,14 @@ std::unique_ptr<RuleIterator> CustomExtensionProvider::GetRuleIterator(
incognito);
}
+std::unique_ptr<RuleIterator> CustomExtensionProvider::GetDiscardedRuleIterator(
+ ContentSettingsType content_type,
+ const ResourceIdentifier& resource_identifier,
+ bool incognito) const {
+ return extensions_settings_->GetDiscardedRuleIterator(
+ content_type, resource_identifier, incognito);
+}
+
bool CustomExtensionProvider::SetWebsiteSetting(
const ContentSettingsPattern& primary_pattern,
const ContentSettingsPattern& secondary_pattern,
diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h b/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h
index 3532f1f10c9..45e74998fd9 100644
--- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h
+++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h
@@ -30,6 +30,11 @@ class CustomExtensionProvider : public ObservableProvider,
const ResourceIdentifier& resource_identifier,
bool incognito) const override;
+ std::unique_ptr<RuleIterator> GetDiscardedRuleIterator(
+ ContentSettingsType content_type,
+ const ResourceIdentifier& resource_identifier,
+ bool incognito) const override;
+
bool SetWebsiteSetting(
const ContentSettingsPattern& primary_pattern,
const ContentSettingsPattern& secondary_pattern,
diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc
index ca3eab1fb10..bc148ab971c 100644
--- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc
+++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc
@@ -25,6 +25,7 @@
#include "components/content_settings/core/browser/content_settings_utils.h"
#include "components/content_settings/core/browser/website_settings_info.h"
#include "components/content_settings/core/common/content_settings_utils.h"
+#include "components/content_settings/core/common/features.h"
#include "components/permissions/features.h"
#include "content/public/browser/browser_thread.h"
@@ -37,6 +38,51 @@ using content_settings::ResourceIdentifier;
namespace extensions {
+namespace {
+
+enum class FilterType {
+ WANT_DISCARDED_PATTERNS,
+ WANT_VALID_PATTERNS,
+};
+
+class FilterRuleIterator : public RuleIterator {
+ public:
+ FilterRuleIterator(std::unique_ptr<RuleIterator> iterator,
+ const FilterType filter_type)
+ : iterator_(std::move(iterator)), filter_type_(filter_type) {}
+
+ ~FilterRuleIterator() override = default;
+
+ bool HasNext() const override {
+ if (!iterator_)
+ return false;
+ if (current_rule_)
+ return true;
+ while (iterator_->HasNext()) {
+ current_rule_ = iterator_->Next();
+ if (!((filter_type_ == FilterType::WANT_DISCARDED_PATTERNS) ^
+ current_rule_->primary_pattern.HasHostWildcards())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ Rule Next() override {
+ DCHECK(current_rule_.has_value());
+ Rule rule = std::move(*current_rule_);
+ current_rule_.reset();
+ return rule;
+ }
+
+ private:
+ std::unique_ptr<RuleIterator> iterator_;
+ const FilterType filter_type_;
+ mutable base::Optional<Rule> current_rule_;
+};
+
+} // namespace
+
struct ContentSettingsStore::ExtensionEntry {
// Extension id.
std::string id;
@@ -63,6 +109,36 @@ std::unique_ptr<RuleIterator> ContentSettingsStore::GetRuleIterator(
ContentSettingsType type,
const content_settings::ResourceIdentifier& identifier,
bool incognito) const {
+ if (base::FeatureList::IsEnabled(
+ content_settings::kDisallowWildcardsInPluginContentSettings) &&
+ type == ContentSettingsType::PLUGINS) {
+ return std::make_unique<FilterRuleIterator>(
+ GetAllRulesIterator(type, identifier, incognito),
+ FilterType::WANT_VALID_PATTERNS);
+ } else {
+ return GetAllRulesIterator(type, identifier, incognito);
+ }
+}
+
+std::unique_ptr<RuleIterator> ContentSettingsStore::GetDiscardedRuleIterator(
+ ContentSettingsType type,
+ const content_settings::ResourceIdentifier& identifier,
+ bool incognito) const {
+ if (base::FeatureList::IsEnabled(
+ content_settings::kDisallowWildcardsInPluginContentSettings) &&
+ type == ContentSettingsType::PLUGINS) {
+ return std::make_unique<FilterRuleIterator>(
+ GetAllRulesIterator(type, identifier, incognito),
+ FilterType::WANT_DISCARDED_PATTERNS);
+ } else {
+ return std::make_unique<content_settings::EmptyRuleIterator>();
+ }
+}
+
+std::unique_ptr<RuleIterator> ContentSettingsStore::GetAllRulesIterator(
+ ContentSettingsType type,
+ const content_settings::ResourceIdentifier& identifier,
+ bool incognito) const {
std::vector<std::unique_ptr<RuleIterator>> iterators;
// The individual |RuleIterators| shouldn't lock; pass |lock_| to the
diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h
index 286201f338a..291975c5aa2 100644
--- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h
+++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h
@@ -59,6 +59,16 @@ class ContentSettingsStore
const content_settings::ResourceIdentifier& identifier,
bool incognito) const;
+ std::unique_ptr<content_settings::RuleIterator> GetDiscardedRuleIterator(
+ ContentSettingsType type,
+ const content_settings::ResourceIdentifier& identifier,
+ bool incognito) const;
+
+ std::unique_ptr<content_settings::RuleIterator> GetAllRulesIterator(
+ ContentSettingsType type,
+ const content_settings::ResourceIdentifier& identifier,
+ bool incognito) const;
+
// Sets the content |setting| for |pattern| of extension |ext_id|. The
// |incognito| flag allow to set whether the provided setting is for
// incognito mode only.
diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store_unittest.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store_unittest.cc
index ec02e12ba9a..51f9f783604 100644
--- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store_unittest.cc
@@ -15,6 +15,7 @@
#include "components/content_settings/core/browser/content_settings_rule.h"
#include "components/content_settings/core/browser/content_settings_utils.h"
#include "components/content_settings/core/common/content_settings_utils.h"
+#include "components/content_settings/core/common/features.h"
#include "components/content_settings/core/test/content_settings_test_utils.h"
#include "components/permissions/features.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -374,4 +375,45 @@ TEST_F(ContentSettingsStoreTest, RemoveEmbedded) {
store()->RemoveObserver(&observer);
}
+TEST_F(ContentSettingsStoreTest, DisallowWildcardsInFlash) {
+ // Enabling the feature which disallows wildcard matching for Plugin content
+ // settings.
+ base::test::ScopedFeatureList scoped_feature_list;
+ scoped_feature_list.InitAndEnableFeature(
+ content_settings::kDisallowWildcardsInPluginContentSettings);
+
+ // Register extension.
+ std::string ext_id("my_extension");
+ RegisterExtension(ext_id);
+ ContentSettingsPattern primary_pattern =
+ ContentSettingsPattern::FromString("https://[*.]google.com");
+ ContentSettingsPattern secondary_pattern = ContentSettingsPattern::Wildcard();
+ store()->SetExtensionContentSetting(
+ ext_id, primary_pattern, secondary_pattern, ContentSettingsType::PLUGINS,
+ std::string(), CONTENT_SETTING_ALLOW, kExtensionPrefsScopeRegular);
+ store()->SetExtensionContentSetting(
+ ext_id, primary_pattern, secondary_pattern, ContentSettingsType::COOKIES,
+ std::string(), CONTENT_SETTING_ALLOW, kExtensionPrefsScopeRegular);
+
+ std::vector<content_settings::Rule> rules;
+ rules = GetSettingsForOneTypeFromStore(store(), ContentSettingsType::PLUGINS,
+ std::string(), false);
+ // Number of rules will be zero because we tried to add a pattern with
+ // wildcards.
+ ASSERT_EQ(rules.size(), 0u);
+
+ rules = GetSettingsForOneTypeFromStore(store(), ContentSettingsType::COOKIES,
+ std::string(), false);
+ // Here we will have one rule because wildcard patterns are allowed for
+ // ContentSettingsType::COOKIES.
+ ASSERT_EQ(rules.size(), 1u);
+
+ std::unique_ptr<content_settings::RuleIterator> discarded_rules_iterator =
+ store()->GetDiscardedRuleIterator(ContentSettingsType::PLUGINS,
+ std::string(), false);
+ ASSERT_TRUE(discarded_rules_iterator->HasNext());
+ ASSERT_EQ(discarded_rules_iterator->Next().primary_pattern, primary_pattern);
+ ASSERT_FALSE(discarded_rules_iterator->HasNext());
+}
+
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.cc b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.cc
index a4f8124fa44..8710a97caf1 100644
--- a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.cc
+++ b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.cc
@@ -99,6 +99,10 @@ MenuItem::ContextList GetContexts(const std::vector<
// Not available for <webview>.
contexts.Add(extensions::MenuItem::PAGE_ACTION);
break;
+ case extensions::api::context_menus::CONTEXT_TYPE_ACTION:
+ // Not available for <webview>.
+ contexts.Add(extensions::MenuItem::ACTION);
+ break;
case extensions::api::context_menus::CONTEXT_TYPE_NONE:
NOTREACHED();
}
diff --git a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h
index 28335e39113..b45a66a8a0a 100644
--- a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h
+++ b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h
@@ -101,7 +101,8 @@ bool CreateMenuItem(const PropertyWithEnumT& create_properties,
}
if (contexts.Contains(MenuItem::BROWSER_ACTION) ||
- contexts.Contains(MenuItem::PAGE_ACTION)) {
+ contexts.Contains(MenuItem::PAGE_ACTION) ||
+ contexts.Contains(MenuItem::ACTION)) {
// Action items are not allowed for <webview>.
if (!extension->is_extension() || is_webview) {
*error = kActionNotAllowedError;
diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc
index 8fa3cd840d0..5dbb6f601d9 100644
--- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc
+++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc
@@ -256,16 +256,17 @@ ExtensionFunction::ResponseAction CookiesGetFunction::Run() {
}
void CookiesGetFunction::GetCookieListCallback(
- const net::CookieStatusList& cookie_status_list,
- const net::CookieStatusList& excluded_cookies) {
+ const net::CookieAccessResultList& cookie_list,
+ const net::CookieAccessResultList& excluded_cookies) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- for (const net::CookieWithStatus& cookie_with_status : cookie_status_list) {
+ for (const net::CookieWithAccessResult& cookie_with_access_result :
+ cookie_list) {
// Return the first matching cookie. Relies on the fact that the
// CookieManager interface returns them in canonical order (longest path,
// then earliest creation time).
- if (cookie_with_status.cookie.Name() == parsed_args_->details.name) {
+ if (cookie_with_access_result.cookie.Name() == parsed_args_->details.name) {
api::cookies::Cookie api_cookie = cookies_helpers::CreateCookie(
- cookie_with_status.cookie, *parsed_args_->details.store_id);
+ cookie_with_access_result.cookie, *parsed_args_->details.store_id);
Respond(ArgumentList(api::cookies::Get::Results::Create(api_cookie)));
return;
}
@@ -336,14 +337,14 @@ void CookiesGetAllFunction::GetAllCookiesCallback(
}
void CookiesGetAllFunction::GetCookieListCallback(
- const net::CookieStatusList& cookie_status_list,
- const net::CookieStatusList& excluded_cookies) {
+ const net::CookieAccessResultList& cookie_list,
+ const net::CookieAccessResultList& excluded_cookies) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
ResponseValue response;
if (extension()) {
std::vector<api::cookies::Cookie> match_vector;
- cookies_helpers::AppendMatchingCookiesFromCookieStatusListToVector(
- cookie_status_list, &parsed_args_->details, extension(), &match_vector);
+ cookies_helpers::AppendMatchingCookiesFromCookieAccessResultListToVector(
+ cookie_list, &parsed_args_->details, extension(), &match_vector);
response =
ArgumentList(api::cookies::GetAll::Results::Create(match_vector));
@@ -437,7 +438,8 @@ ExtensionFunction::ResponseAction CookiesSetFunction::Run() {
// is generated.
success_ = false;
state_ = SET_COMPLETED;
- GetCookieListCallback(net::CookieStatusList(), net::CookieStatusList());
+ GetCookieListCallback(net::CookieAccessResultList(),
+ net::CookieAccessResultList());
return AlreadyResponded();
}
@@ -461,7 +463,7 @@ ExtensionFunction::ResponseAction CookiesSetFunction::Run() {
}
void CookiesSetFunction::SetCanonicalCookieCallback(
- net::CanonicalCookie::CookieInclusionStatus set_cookie_result) {
+ net::CookieInclusionStatus set_cookie_result) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_EQ(NO_RESPONSE, state_);
state_ = SET_COMPLETED;
@@ -469,8 +471,8 @@ void CookiesSetFunction::SetCanonicalCookieCallback(
}
void CookiesSetFunction::GetCookieListCallback(
- const net::CookieStatusList& cookie_list,
- const net::CookieStatusList& excluded_cookies) {
+ const net::CookieAccessResultList& cookie_list,
+ const net::CookieAccessResultList& excluded_cookies) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_EQ(SET_COMPLETED, state_);
state_ = GET_COMPLETED;
@@ -485,16 +487,17 @@ void CookiesSetFunction::GetCookieListCallback(
}
ResponseValue value;
- for (const net::CookieWithStatus& cookie_with_status : cookie_list) {
+ for (const net::CookieWithAccessResult& cookie_with_access_result :
+ cookie_list) {
// Return the first matching cookie. Relies on the fact that the
// CookieMonster returns them in canonical order (longest path, then
// earliest creation time).
std::string name =
parsed_args_->details.name.get() ? *parsed_args_->details.name
: std::string();
- if (cookie_with_status.cookie.Name() == name) {
+ if (cookie_with_access_result.cookie.Name() == name) {
api::cookies::Cookie api_cookie = cookies_helpers::CreateCookie(
- cookie_with_status.cookie, *parsed_args_->details.store_id);
+ cookie_with_access_result.cookie, *parsed_args_->details.store_id);
value = ArgumentList(api::cookies::Set::Results::Create(api_cookie));
break;
}
diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h
index d6b171b5f04..a506809822a 100644
--- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h
+++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h
@@ -23,6 +23,7 @@
#include "mojo/public/cpp/bindings/remote.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_change_dispatcher.h"
+#include "net/cookies/cookie_inclusion_status.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
#include "url/gurl.h"
@@ -105,8 +106,9 @@ class CookiesGetFunction : public ExtensionFunction {
ResponseAction Run() override;
private:
- void GetCookieListCallback(const net::CookieStatusList& cookie_status_list,
- const net::CookieStatusList& excluded_cookies);
+ void GetCookieListCallback(
+ const net::CookieAccessResultList& cookie_list,
+ const net::CookieAccessResultList& excluded_cookies);
GURL url_;
mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_;
@@ -130,8 +132,9 @@ class CookiesGetAllFunction : public ExtensionFunction {
// For the two different callback signatures for getting cookies for a URL vs
// getting all cookies. They do the same thing.
void GetAllCookiesCallback(const net::CookieList& cookie_list);
- void GetCookieListCallback(const net::CookieStatusList& cookie_status_list,
- const net::CookieStatusList& excluded_cookies);
+ void GetCookieListCallback(
+ const net::CookieAccessResultList& cookie_list,
+ const net::CookieAccessResultList& excluded_cookies);
GURL url_;
mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_;
@@ -150,10 +153,10 @@ class CookiesSetFunction : public ExtensionFunction {
ResponseAction Run() override;
private:
- void SetCanonicalCookieCallback(
- net::CanonicalCookie::CookieInclusionStatus set_cookie_result);
- void GetCookieListCallback(const net::CookieStatusList& cookie_list,
- const net::CookieStatusList& excluded_cookies);
+ void SetCanonicalCookieCallback(net::CookieInclusionStatus set_cookie_result);
+ void GetCookieListCallback(
+ const net::CookieAccessResultList& cookie_list,
+ const net::CookieAccessResultList& excluded_cookies);
enum { NO_RESPONSE, SET_COMPLETED, GET_COMPLETED } state_;
GURL url_;
diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_apitest.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_apitest.cc
index bf114b6f2be..e5f22089cac 100644
--- a/chromium/chrome/browser/extensions/api/cookies/cookies_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/cookies/cookies_apitest.cc
@@ -6,10 +6,16 @@
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/test/browser_test.h"
+#include "extensions/common/scoped_worker_based_extensions_channel.h"
#include "net/cookies/cookie_util.h"
namespace extensions {
+using ContextType = ExtensionApiTest::ContextType;
+
+// TODO(crbug.com/1093066): This test uses the DOM to set and
+// check cookies for one test. Figure out how to isolate that
+// test and adapt the rest of it for a SW-based extension.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Cookies) {
ASSERT_TRUE(RunExtensionTestWithArg(
"cookies/api",
@@ -19,21 +25,60 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Cookies) {
<< message_;
}
-IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CookiesEvents) {
- ASSERT_TRUE(RunExtensionTest("cookies/events")) << message_;
+class CookiesApiTest : public ExtensionApiTest,
+ public testing::WithParamInterface<ContextType> {
+ public:
+ void SetUp() override {
+ ExtensionApiTest::SetUp();
+ // Service Workers are currently only available on certain channels, so set
+ // the channel for those tests.
+ if (GetParam() == ContextType::kServiceWorker)
+ current_channel_ = std::make_unique<ScopedWorkerBasedExtensionsChannel>();
+ }
+
+ protected:
+ bool RunTest(const std::string& extension_name) {
+ return RunTestWithFlags(extension_name, kFlagNone);
+ }
+
+ bool RunTestIncognito(const std::string& extension_name) {
+ return RunTestWithFlags(extension_name, kFlagEnableIncognito);
+ }
+
+ bool RunTestWithFlags(const std::string& extension_name,
+ int browser_test_flags) {
+ if (GetParam() == ContextType::kServiceWorker)
+ browser_test_flags |= kFlagRunAsServiceWorkerBasedExtension;
+
+ return RunExtensionTestWithFlags(extension_name, browser_test_flags,
+ kFlagNone);
+ }
+
+ std::unique_ptr<ScopedWorkerBasedExtensionsChannel> current_channel_;
+};
+
+INSTANTIATE_TEST_SUITE_P(EventPage,
+ CookiesApiTest,
+ ::testing::Values(ContextType::kEventPage));
+INSTANTIATE_TEST_SUITE_P(ServiceWorker,
+ CookiesApiTest,
+ ::testing::Values(ContextType::kServiceWorker));
+
+IN_PROC_BROWSER_TEST_P(CookiesApiTest, CookiesEvents) {
+ ASSERT_TRUE(RunTest("cookies/events")) << message_;
}
-IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CookiesEventsSpanning) {
+IN_PROC_BROWSER_TEST_P(CookiesApiTest, CookiesEventsSpanning) {
// We need to initialize an incognito mode window in order have an initialized
// incognito cookie store. Otherwise, the chrome.cookies.set operation is just
// ignored and we won't be notified about a newly set cookie for which we want
// to test whether the storeId is set correctly.
OpenURLOffTheRecord(browser()->profile(), GURL("chrome://newtab/"));
- ASSERT_TRUE(RunExtensionTestIncognito("cookies/events_spanning")) << message_;
+ ASSERT_TRUE(RunTestIncognito("cookies/events_spanning")) << message_;
}
-IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CookiesNoPermission) {
- ASSERT_TRUE(RunExtensionTest("cookies/no_permission")) << message_;
+IN_PROC_BROWSER_TEST_P(CookiesApiTest, CookiesNoPermission) {
+ ASSERT_TRUE(RunTest("cookies/no_permission")) << message_;
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc
index 43bb1619bfb..9aee1f6143b 100644
--- a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc
+++ b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc
@@ -182,14 +182,14 @@ void AppendMatchingCookiesFromCookieListToVector(
}
}
-void AppendMatchingCookiesFromCookieStatusListToVector(
- const net::CookieStatusList& all_cookies_with_statuses,
+void AppendMatchingCookiesFromCookieAccessResultListToVector(
+ const net::CookieAccessResultList& all_cookies_with_access_result,
const GetAll::Params::Details* details,
const Extension* extension,
std::vector<Cookie>* match_vector) {
- for (const net::CookieWithStatus& cookie_with_status :
- all_cookies_with_statuses) {
- const net::CanonicalCookie& cookie = cookie_with_status.cookie;
+ for (const net::CookieWithAccessResult& cookie_with_access_result :
+ all_cookies_with_access_result) {
+ const net::CanonicalCookie& cookie = cookie_with_access_result.cookie;
AppendCookieToVectorIfMatchAndHasHostPermission(cookie, details, extension,
match_vector);
}
diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h
index 298b16e49a7..9d5acf0fbc7 100644
--- a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h
+++ b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h
@@ -85,9 +85,10 @@ void AppendMatchingCookiesFromCookieListToVector(
const Extension* extension,
std::vector<api::cookies::Cookie>* match_vector);
-// Same as above except takes a CookieStatusList (and ignores the statuses).
-void AppendMatchingCookiesFromCookieStatusListToVector(
- const net::CookieStatusList& all_cookies_with_statuses,
+// Same as above except takes a CookieAccessResultList (and ignores the access
+// results).
+void AppendMatchingCookiesFromCookieAccessResultListToVector(
+ const net::CookieAccessResultList& all_cookies_with_access_result,
const api::cookies::GetAll::Params::Details* details,
const Extension* extension,
std::vector<api::cookies::Cookie>* match_vector);
diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc
index 253ce751bd9..3aaf2863859 100644
--- a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc
+++ b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc
@@ -389,9 +389,7 @@ bool ExtensionDevToolsClientHost::MayWriteLocalFiles() {
// DebuggerFunction -----------------------------------------------------------
-DebuggerFunction::DebuggerFunction()
- : client_host_(NULL) {
-}
+DebuggerFunction::DebuggerFunction() : client_host_(nullptr) {}
DebuggerFunction::~DebuggerFunction() = default;
diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc b/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc
index 704f95eed0c..71ce5a3399d 100644
--- a/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc
@@ -381,4 +381,24 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessDebuggerExtensionApiTest, Debugger) {
<< message_;
}
+IN_PROC_BROWSER_TEST_F(SitePerProcessDebuggerExtensionApiTest,
+ AutoAttachPermissions) {
+ GURL url(embedded_test_server()->GetURL(
+ "a.com",
+ "/extensions/api_test/debugger_auto_attach_permissions/page.html"));
+ ASSERT_TRUE(RunExtensionTestWithArg("debugger_auto_attach_permissions",
+ url.spec().c_str()))
+ << message_;
+}
+
+IN_PROC_BROWSER_TEST_F(SitePerProcessDebuggerExtensionApiTest,
+ NavigateSubframe) {
+ GURL url(embedded_test_server()->GetURL(
+ "a.com",
+ "/extensions/api_test/debugger_navigate_subframe/inspected_page.html"));
+ ASSERT_TRUE(
+ RunExtensionTestWithArg("debugger_navigate_subframe", url.spec().c_str()))
+ << message_;
+}
+
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc b/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc
index 13265b25237..06daba2fe34 100644
--- a/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc
@@ -199,18 +199,9 @@ IN_PROC_BROWSER_TEST_F(DeclarativeApiTest, PersistRules) {
EXPECT_EQ(kTestTitle, GetTitle());
}
-// Disabled for flakiness: http://crbug.com/851854
-#if defined(OS_MACOSX) && defined(ADDRESS_SANITIZER)
-#define MAYBE_ExtensionLifetimeRulesHandling \
- DISABLED_ExtensionLifetimeRulesHandling
-#else
-#define MAYBE_ExtensionLifetimeRulesHandling ExtensionLifetimeRulesHandling
-#endif
-
// Test that the rules are correctly persisted and (de)activated during
// changing the "installed" and "enabled" status of an extension.
-IN_PROC_BROWSER_TEST_F(DeclarativeApiTest,
- MAYBE_ExtensionLifetimeRulesHandling) {
+IN_PROC_BROWSER_TEST_F(DeclarativeApiTest, ExtensionLifetimeRulesHandling) {
TestExtensionDir ext_dir;
// 1. Install the extension. Rules should become active.
@@ -276,17 +267,10 @@ IN_PROC_BROWSER_TEST_F(DeclarativeApiTest,
EXPECT_EQ(0u, NumberOfRegisteredRules(extension_id));
}
-// Disabled for flakiness: http://crbug.com/851854
-#if defined(OS_MACOSX) && defined(ADDRESS_SANITIZER)
-#define MAYBE_NoTracesAfterUninstalling DISABLED_NoTracesAfterUninstalling
-#else
-#define MAYBE_NoTracesAfterUninstalling NoTracesAfterUninstalling
-#endif
-
// When an extension is uninstalled, the state store deletes all preferences
// stored for that extension. We need to make sure we don't store anything after
// that deletion occurs.
-IN_PROC_BROWSER_TEST_F(DeclarativeApiTest, MAYBE_NoTracesAfterUninstalling) {
+IN_PROC_BROWSER_TEST_F(DeclarativeApiTest, NoTracesAfterUninstalling) {
TestExtensionDir ext_dir;
// 1. Install the extension. Verify that rules become active and some prefs
diff --git a/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc b/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc
index 8b25d8e15ff..97ef56d188a 100644
--- a/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc
@@ -10,11 +10,11 @@
#include "base/bind.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
-#include "base/task/post_task.h"
#include "chrome/test/base/testing_profile.h"
#include "components/version_info/channel.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_task_traits.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_task_environment.h"
#include "extensions/browser/api/declarative/test_rules_registry.h"
#include "extensions/browser/api/declarative_webrequest/webrequest_constants.h"
@@ -84,23 +84,23 @@ TEST_F(RulesRegistryServiceTest, TestConstructionAndMultiThreading) {
EXPECT_TRUE(registry_service.GetRulesRegistry(key, "io").get());
EXPECT_FALSE(registry_service.GetRulesRegistry(key, "foo").get());
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&InsertRule, registry_service.GetRulesRegistry(key, "ui"),
"ui_task"));
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&InsertRule, registry_service.GetRulesRegistry(key, "io"),
"io_task"));
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&VerifyNumberOfRules,
registry_service.GetRulesRegistry(key, "ui"), 1));
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&VerifyNumberOfRules,
registry_service.GetRulesRegistry(key, "io"), 1));
@@ -120,13 +120,13 @@ TEST_F(RulesRegistryServiceTest, TestConstructionAndMultiThreading) {
.Build();
registry_service.SimulateExtensionUninstalled(extension.get());
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&VerifyNumberOfRules,
registry_service.GetRulesRegistry(key, "ui"), 0));
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&VerifyNumberOfRules,
registry_service.GetRulesRegistry(key, "io"), 0));
diff --git a/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc b/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc
index 9951f0a2666..b06e0ae94c4 100644
--- a/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc
@@ -235,7 +235,7 @@ std::unique_ptr<ContentAction> RequestContentScript::Create(
// static
std::unique_ptr<ContentAction> RequestContentScript::CreateForTest(
- DeclarativeUserScriptMaster* master,
+ DeclarativeUserScriptSet* script_set,
const Extension* extension,
const base::Value& json_action,
std::string* error) {
@@ -256,10 +256,10 @@ std::unique_ptr<ContentAction> RequestContentScript::CreateForTest(
if (!InitScriptData(action_dict, error, &script_data))
return std::unique_ptr<ContentAction>();
- // Inject provided DeclarativeUserScriptMaster, rather than looking it up
+ // Inject provided DeclarativeUserScriptSet, rather than looking it up
// using a BrowserContext.
return base::WrapUnique(
- new RequestContentScript(master, extension, script_data));
+ new RequestContentScript(script_set, extension, script_data));
}
// static
@@ -309,25 +309,24 @@ RequestContentScript::RequestContentScript(
HostID host_id(HostID::EXTENSIONS, extension->id());
InitScript(host_id, extension, script_data);
- master_ = DeclarativeUserScriptManager::Get(browser_context)
- ->GetDeclarativeUserScriptMasterByID(host_id);
+ script_set_ = DeclarativeUserScriptManager::Get(browser_context)
+ ->GetDeclarativeUserScriptSetByID(host_id);
AddScript();
}
-RequestContentScript::RequestContentScript(
- DeclarativeUserScriptMaster* master,
- const Extension* extension,
- const ScriptData& script_data) {
+RequestContentScript::RequestContentScript(DeclarativeUserScriptSet* script_set,
+ const Extension* extension,
+ const ScriptData& script_data) {
HostID host_id(HostID::EXTENSIONS, extension->id());
InitScript(host_id, extension, script_data);
- master_ = master;
+ script_set_ = script_set;
AddScript();
}
RequestContentScript::~RequestContentScript() {
- DCHECK(master_);
- master_->RemoveScript(UserScriptIDPair(script_.id(), script_.host_id()));
+ DCHECK(script_set_);
+ script_set_->RemoveScript(UserScriptIDPair(script_.id(), script_.host_id()));
}
void RequestContentScript::InitScript(const HostID& host_id,
@@ -355,8 +354,8 @@ void RequestContentScript::InitScript(const HostID& host_id,
}
void RequestContentScript::AddScript() {
- DCHECK(master_);
- master_->AddScript(UserScript::CopyMetadataFrom(script_));
+ DCHECK(script_set_);
+ script_set_->AddScript(UserScript::CopyMetadataFrom(script_));
}
void RequestContentScript::Apply(const ApplyInfo& apply_info) const {
@@ -394,7 +393,8 @@ std::unique_ptr<ContentAction> SetIcon::Create(
gfx::ImageSkia icon;
const base::DictionaryValue* canvas_set = NULL;
if (dict->GetDictionary("imageData", &canvas_set) &&
- !ExtensionAction::ParseIconFromCanvasDictionary(*canvas_set, &icon)) {
+ ExtensionAction::ParseIconFromCanvasDictionary(*canvas_set, &icon) !=
+ ExtensionAction::IconParseResult::kSuccess) {
*error = kInvalidIconDictionary;
return nullptr;
}
diff --git a/chromium/chrome/browser/extensions/api/declarative_content/content_action.h b/chromium/chrome/browser/extensions/api/declarative_content/content_action.h
index c16e87cca97..ea28a5a863a 100644
--- a/chromium/chrome/browser/extensions/api/declarative_content/content_action.h
+++ b/chromium/chrome/browser/extensions/api/declarative_content/content_action.h
@@ -9,7 +9,7 @@
#include <string>
#include "base/macros.h"
-#include "extensions/browser/declarative_user_script_master.h"
+#include "extensions/browser/declarative_user_script_set.h"
#include "extensions/common/user_script.h"
namespace base {
@@ -74,7 +74,7 @@ class RequestContentScript : public ContentAction {
RequestContentScript(content::BrowserContext* browser_context,
const Extension* extension,
const ScriptData& script_data);
- RequestContentScript(DeclarativeUserScriptMaster* master,
+ RequestContentScript(DeclarativeUserScriptSet* script_set,
const Extension* extension,
const ScriptData& script_data);
@@ -87,7 +87,7 @@ class RequestContentScript : public ContentAction {
std::string* error);
static std::unique_ptr<ContentAction> CreateForTest(
- DeclarativeUserScriptMaster* master,
+ DeclarativeUserScriptSet* master,
const Extension* extension,
const base::Value& json_action,
std::string* error);
@@ -112,7 +112,7 @@ class RequestContentScript : public ContentAction {
const Extension* extension) const;
UserScript script_;
- DeclarativeUserScriptMaster* master_;
+ DeclarativeUserScriptSet* script_set_;
DISALLOW_COPY_AND_ASSIGN(RequestContentScript);
};
diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc
index 73650f930ac..dc7055aea74 100644
--- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc
@@ -9,6 +9,7 @@
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
+#include "chrome/browser/extensions/chrome_extension_test_notification_observer.h"
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/extension_action_manager.h"
#include "chrome/browser/extensions/extension_action_test_util.h"
@@ -257,8 +258,7 @@ void DeclarativeContentApiTest::CheckBookmarkEvents(bool match_is_bookmarked) {
EXPECT_EQ(!match_is_bookmarked, action->GetIsVisible(tab_id));
}
-// Disabled due to flake. https://crbug.com/606574.
-IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, DISABLED_Overview) {
+IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, Overview) {
ext_dir_.WriteManifest(kDeclarativeContentManifest);
ext_dir_.WriteFile(
FILE_PATH_LITERAL("background.js"),
@@ -295,14 +295,20 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, DISABLED_Overview) {
browser()->tab_strip_model()->GetWebContentsAt(0);
const int tab_id = ExtensionTabUtil::GetTabId(tab);
- NavigateInRenderer(tab, GURL("http://test1/"));
+ // Observer to track page action visibility. This helps avoid
+ // flakes by waiting to check visibility until there is an
+ // actual update to the page action.
+ ChromeExtensionTestNotificationObserver test_observer(browser());
+ NavigateInRenderer(tab, GURL("http://test1/"));
// The declarative API should show the page action instantly, rather
// than waiting for the extension to run.
+ test_observer.WaitForPageActionVisibilityChangeTo(1);
EXPECT_TRUE(action->GetIsVisible(tab_id));
// Make sure leaving a matching page unshows the page action.
NavigateInRenderer(tab, GURL("http://not_checked/"));
+ test_observer.WaitForPageActionVisibilityChangeTo(0);
EXPECT_FALSE(action->GetIsVisible(tab_id));
// Insert a password field to make sure that's noticed.
@@ -311,10 +317,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, DISABLED_Overview) {
tab, "document.body.innerHTML = '<input type=\"password\">';"
"document.body.offsetTop;"));
- // Give the style match a chance to run and send back the matching-selector
- // update.
- ASSERT_TRUE(content::ExecuteScript(tab, std::string()));
-
+ test_observer.WaitForPageActionVisibilityChangeTo(1);
EXPECT_TRUE(action->GetIsVisible(tab_id))
<< "Adding a matching element should show the page action.";
@@ -324,10 +327,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, DISABLED_Overview) {
tab, "document.body.innerHTML = 'Hello world';"
"document.body.offsetTop;"));
- // Give the style match a chance to run and send back the matching-selector
- // update.
- ASSERT_TRUE(content::ExecuteScript(tab, std::string()));
-
+ test_observer.WaitForPageActionVisibilityChangeTo(0);
EXPECT_FALSE(action->GetIsVisible(tab_id))
<< "Removing the matching element should hide the page action again.";
}
@@ -643,11 +643,17 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest,
EXPECT_TRUE(incognito_action->GetIsVisible(incognito_tab_id));
}
+constexpr char kRulesExtensionName[] =
+ "Declarative content persistence apitest";
+
+// TODO(crbug.com/512431): Flaky on Windows release builds.
+#if defined(OS_WIN) && defined(NDEBUG)
+#define MAYBE_PRE_RulesPersistence DISABLED_PRE_RulesPersistence
+#else
+#define MAYBE_PRE_RulesPersistence PRE_RulesPersistence
+#endif
// Sets up rules matching http://test1/ in a normal and incognito browser.
-// Frequently times out on ChromiumOS, Linux ASan, and Windows:
-// https://crbug.com/512431.
-IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest,
- DISABLED_PRE_RulesPersistence) {
+IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, MAYBE_PRE_RulesPersistence) {
ExtensionTestMessageListener ready("ready", false);
ExtensionTestMessageListener ready_split("ready (split)", false);
// An on-disk extension is required so that it can be reloaded later in the
@@ -656,30 +662,36 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest,
LoadExtensionIncognito(test_data_dir_.AppendASCII("declarative_content")
.AppendASCII("persistence"));
ASSERT_TRUE(extension);
+ ASSERT_EQ(kRulesExtensionName, extension->name());
ASSERT_TRUE(ready.WaitUntilSatisfied());
CreateIncognitoBrowser();
ASSERT_TRUE(ready_split.WaitUntilSatisfied());
}
+// TODO(crbug.com/512431): Flaky on Windows release builds.
+#if defined(OS_WIN) && defined(NDEBUG)
+#define MAYBE_RulesPersistence DISABLED_RulesPersistence
+#else
+#define MAYBE_RulesPersistence RulesPersistence
+#endif
// Reloads the extension from PRE_RulesPersistence and checks that the rules
// continue to work as expected after being persisted and reloaded.
-IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, DISABLED_RulesPersistence) {
- ExtensionTestMessageListener ready("second run ready", false);
- ExtensionTestMessageListener ready_split("second run ready (split)", false);
- ASSERT_TRUE(ready.WaitUntilSatisfied());
-
- ExtensionRegistry* registry = ExtensionRegistry::Get(profile());
- const Extension* extension =
- GetExtensionByPath(registry->enabled_extensions(),
- test_data_dir_.AppendASCII("declarative_content")
- .AppendASCII("persistence"));
+IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, MAYBE_RulesPersistence) {
+ const Extension* extension = GetSingleLoadedExtension();
+ ASSERT_TRUE(extension) << message_;
+ ASSERT_EQ(kRulesExtensionName, extension->name());
// Check non-incognito browser.
content::WebContents* const tab =
browser()->tab_strip_model()->GetWebContentsAt(0);
const int tab_id = ExtensionTabUtil::GetTabId(tab);
+ // Observer to track page action visibility. This helps avoid
+ // flakes by waiting to check visibility until there is an
+ // actual update to the page action.
+ ChromeExtensionTestNotificationObserver test_observer(browser());
+
const ExtensionAction* action =
ExtensionActionManager::Get(browser()->profile())
->GetExtensionAction(*extension);
@@ -687,11 +699,15 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, DISABLED_RulesPersistence) {
EXPECT_FALSE(action->GetIsVisible(tab_id));
NavigateInRenderer(tab, GURL("http://test_normal/"));
+ test_observer.WaitForPageActionVisibilityChangeTo(1);
EXPECT_TRUE(action->GetIsVisible(tab_id));
NavigateInRenderer(tab, GURL("http://test_split/"));
+ test_observer.WaitForPageActionVisibilityChangeTo(0);
EXPECT_FALSE(action->GetIsVisible(tab_id));
+ ExtensionTestMessageListener ready_split("second run ready (split)", false);
+
// Check incognito browser.
Browser* incognito_browser = CreateIncognitoBrowser();
ASSERT_TRUE(ready_split.WaitUntilSatisfied());
@@ -699,35 +715,35 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, DISABLED_RulesPersistence) {
incognito_browser->tab_strip_model()->GetWebContentsAt(0);
const int incognito_tab_id = ExtensionTabUtil::GetTabId(incognito_tab);
+ ChromeExtensionTestNotificationObserver incognito_test_observer(
+ incognito_browser);
+
const ExtensionAction* incognito_action =
ExtensionActionManager::Get(incognito_browser->profile())
->GetExtensionAction(*extension);
ASSERT_TRUE(incognito_action);
NavigateInRenderer(incognito_tab, GURL("http://test_split/"));
+ incognito_test_observer.WaitForPageActionVisibilityChangeTo(1);
EXPECT_TRUE(incognito_action->GetIsVisible(incognito_tab_id));
NavigateInRenderer(incognito_tab, GURL("http://test_normal/"));
+ incognito_test_observer.WaitForPageActionVisibilityChangeTo(0);
EXPECT_FALSE(incognito_action->GetIsVisible(incognito_tab_id));
}
// http://crbug.com/304373
-#if defined(OS_WIN)
-// Fails on XP: http://crbug.com/515717
-#define MAYBE_UninstallWhileActivePageAction \
- DISABLED_UninstallWhileActivePageAction
-#else
-#define MAYBE_UninstallWhileActivePageAction UninstallWhileActivePageAction
-#endif
IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest,
- MAYBE_UninstallWhileActivePageAction) {
+ UninstallWhileActivePageAction) {
ext_dir_.WriteManifest(kDeclarativeContentManifest);
- ext_dir_.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundHelpers);
+ std::string script =
+ kBackgroundHelpers + std::string("\nchrome.test.sendMessage('ready');");
+ ext_dir_.WriteFile(FILE_PATH_LITERAL("background.js"), script);
+ ExtensionTestMessageListener ready_listener("ready", false);
const Extension* extension = LoadExtension(ext_dir_.UnpackedPath());
ASSERT_TRUE(extension);
- // Wait for declarative rules to be set up.
- content::BrowserContext::GetDefaultStoragePartition(profile())
- ->FlushNetworkInterfaceForTesting();
+ ASSERT_TRUE(ready_listener.WaitUntilSatisfied());
+
const std::string extension_id = extension->id();
const ExtensionAction* action =
ExtensionActionManager::Get(browser()->profile())
@@ -754,10 +770,10 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest,
EXPECT_EQ(1u, extension_action_test_util::GetVisiblePageActionCount(tab));
EXPECT_EQ(1u, extension_action_test_util::GetTotalPageActionCount(tab));
+ ExtensionTestMessageListener reload_ready_listener("ready", false);
ReloadExtension(extension_id); // Invalidates action and extension.
- // Wait for declarative rules to be removed.
- content::BrowserContext::GetDefaultStoragePartition(profile())
- ->FlushNetworkInterfaceForTesting();
+ ASSERT_TRUE(reload_ready_listener.WaitUntilSatisfied());
+
EXPECT_EQ("test_rule",
ExecuteScriptInBackgroundPage(extension_id, kTestRule));
// TODO(jyasskin): Apply new rules to existing tabs, without waiting for a
@@ -779,7 +795,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest,
// This tests against a renderer crash that was present during development.
IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest,
- DISABLED_AddExtensionMatchingExistingTabWithDeadFrames) {
+ AddExtensionMatchingExistingTabWithDeadFrames) {
ext_dir_.WriteManifest(kDeclarativeContentManifest);
ext_dir_.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundHelpers);
content::WebContents* const tab =
@@ -792,6 +808,10 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest,
ASSERT_TRUE(content::ExecuteScript(
tab, "document.body.innerHTML = '<span class=\"foo\">';"));
+ // Observer to track page action visibility. This helps avoid flakes by
+ // waiting to check visibility until there is an update to the page action.
+ ChromeExtensionTestNotificationObserver test_observer(browser());
+
const Extension* extension = LoadExtension(ext_dir_.UnpackedPath());
ASSERT_TRUE(extension);
const ExtensionAction* action =
@@ -807,13 +827,8 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest,
" css: [\"span[class=foo]\"]})],\n"
" actions: [new ShowAction()]\n"
"}], 'rule0');\n"));
- // Give the renderer a chance to apply the rules change and notify the
- // browser. This takes one time through the Blink message loop to receive
- // the rule change and apply the new stylesheet, and a second to dedupe the
- // update.
- ASSERT_TRUE(content::ExecuteScript(tab, std::string()));
- ASSERT_TRUE(content::ExecuteScript(tab, std::string()));
+ test_observer.WaitForPageActionVisibilityChangeTo(1);
EXPECT_FALSE(tab->IsCrashed());
EXPECT_TRUE(action->GetIsVisible(tab_id))
<< "Loading an extension when an open page matches its rules "
@@ -825,6 +840,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest,
"onPageChanged.removeRules(undefined, function() {\n"
" window.domAutomationController.send('removed');\n"
"});\n"));
+ test_observer.WaitForPageActionVisibilityChangeTo(0);
EXPECT_FALSE(action->GetIsVisible(tab_id));
}
diff --git a/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc
index 65865c4235a..4a99b452a50 100644
--- a/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc
@@ -113,7 +113,7 @@ class RequestContentScriptAPITest : public ExtensionBrowserTest {
};
RequestContentScriptAPITest::RequestContentScriptAPITest()
- : extension_(NULL) {}
+ : extension_(nullptr) {}
testing::AssertionResult RequestContentScriptAPITest::RunTest(
PermissionOrMatcherType manifest_permission,
diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_apitest.cc
index 827ac893936..76c4987a474 100644
--- a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_apitest.cc
@@ -10,13 +10,19 @@
#include "base/macros.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/test/browser_test.h"
+#include "extensions/common/scoped_worker_based_extensions_channel.h"
#include "net/dns/mock_host_resolver.h"
namespace {
-class DeclarativeNetRequestAPItest : public extensions::ExtensionApiTest {
+using ContextType = extensions::ExtensionApiTest::ContextType;
+using extensions::ScopedWorkerBasedExtensionsChannel;
+
+class DeclarativeNetRequestAPItest
+ : public extensions::ExtensionApiTest,
+ public testing::WithParamInterface<ContextType> {
public:
- DeclarativeNetRequestAPItest() {}
+ DeclarativeNetRequestAPItest() = default;
protected:
// ExtensionApiTest override.
@@ -40,28 +46,55 @@ class DeclarativeNetRequestAPItest : public extensions::ExtensionApiTest {
// Override the path used for loading the extension.
test_data_dir_ = temp_dir_.GetPath().AppendASCII("declarative_net_request");
+
+ // Service Workers are currently only available on certain channels, so set
+ // the channel for those tests.
+ if (GetParam() == ContextType::kServiceWorker)
+ current_channel_ = std::make_unique<ScopedWorkerBasedExtensionsChannel>();
+ }
+
+ bool RunTest(const std::string& extension_path) {
+ if (GetParam() != ContextType::kServiceWorker) {
+ return RunExtensionTest(extension_path);
+ }
+ return RunExtensionTestWithFlags(
+ extension_path, kFlagRunAsServiceWorkerBasedExtension, kFlagNone);
}
private:
base::ScopedTempDir temp_dir_;
- DISALLOW_COPY_AND_ASSIGN(DeclarativeNetRequestAPItest);
+ std::unique_ptr<ScopedWorkerBasedExtensionsChannel> current_channel_;
};
-IN_PROC_BROWSER_TEST_F(DeclarativeNetRequestAPItest, DynamicRules) {
- ASSERT_TRUE(RunExtensionTest("dynamic_rules")) << message_;
+using DeclarativeNetRequestLazyAPItest = DeclarativeNetRequestAPItest;
+
+INSTANTIATE_TEST_SUITE_P(PersistentBackground,
+ DeclarativeNetRequestAPItest,
+ ::testing::Values(ContextType::kPersistentBackground));
+INSTANTIATE_TEST_SUITE_P(EventPage,
+ DeclarativeNetRequestLazyAPItest,
+ ::testing::Values(ContextType::kEventPage));
+INSTANTIATE_TEST_SUITE_P(ServiceWorker,
+ DeclarativeNetRequestLazyAPItest,
+ ::testing::Values(ContextType::kServiceWorker));
+
+IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestLazyAPItest, DynamicRules) {
+ ASSERT_TRUE(RunTest("dynamic_rules")) << message_;
+}
+
+IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestLazyAPItest, OnRulesMatchedDebug) {
+ ASSERT_TRUE(RunTest("on_rules_matched_debug")) << message_;
}
-// TODO(crbug.com/1029233) Restore this test. This is disabled due to
-// flakiness.
-IN_PROC_BROWSER_TEST_F(DeclarativeNetRequestAPItest,
- DISABLED_OnRulesMatchedDebug) {
- ASSERT_TRUE(RunExtensionTest("on_rules_matched_debug")) << message_;
+// This test uses webRequest/webRequestBlocking, so it's not currently
+// supported for service workers.
+IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestAPItest, ModifyHeaders) {
+ ASSERT_TRUE(RunTest("modify_headers")) << message_;
}
-// TODO(crbug.com/1070344): Disabled due to flakiness.
-IN_PROC_BROWSER_TEST_F(DeclarativeNetRequestAPItest, DISABLED_GetMatchedRules) {
- ASSERT_TRUE(RunExtensionTest("get_matched_rules")) << message_;
+IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestLazyAPItest, GetMatchedRules) {
+ ASSERT_TRUE(RunTest("get_matched_rules")) << message_;
}
} // namespace
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 a5d9df75278..26f4b57d2bc 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
@@ -546,6 +546,24 @@ class DeclarativeNetRequestBrowserTest
return results;
}
+ TestRule CreateModifyHeadersRule(
+ int id,
+ int priority,
+ const std::string& url_filter,
+ base::Optional<std::vector<TestHeaderInfo>> request_headers,
+ base::Optional<std::vector<TestHeaderInfo>> response_headers) {
+ TestRule rule = CreateGenericRule();
+ rule.id = id;
+ rule.priority = priority;
+ rule.condition->url_filter = url_filter;
+ rule.condition->resource_types = std::vector<std::string>({"sub_frame"});
+ rule.action->type = "modifyHeaders";
+ rule.action->request_headers = std::move(request_headers);
+ rule.action->response_headers = std::move(response_headers);
+
+ return rule;
+ }
+
private:
// Handler to monitor the requests which reach the EmbeddedTestServer. This
// will be run on the EmbeddedTestServer's IO thread.
@@ -650,10 +668,9 @@ class DeclarativeNetRequestBrowserTest
tester.ExpectTotalCount(
"Extensions.DeclarativeNetRequest.CreateVerifiedMatcherTime",
expected_enabled_rulesets_count);
- tester.ExpectUniqueSample(
- "Extensions.DeclarativeNetRequest.LoadRulesetResult",
- RulesetMatcher::kLoadSuccess /*sample*/,
- expected_enabled_rulesets_count);
+ tester.ExpectUniqueSample(kLoadRulesetResultHistogram,
+ LoadRulesetResult::kSuccess /*sample*/,
+ expected_enabled_rulesets_count);
EXPECT_TRUE(AreAllIndexedStaticRulesetsValid(*extension, profile()));
@@ -692,8 +709,9 @@ using DeclarativeNetRequestBrowserTest_Packed =
using DeclarativeNetRequestBrowserTest_Unpacked =
DeclarativeNetRequestBrowserTest;
-#if defined(OS_WIN) && !defined(NDEBUG)
+#if (defined(OS_WIN) || defined(OS_MACOSX)) && !defined(NDEBUG)
// TODO: test times out on win7-debug. http://crbug.com/900447.
+// Also times out on mac-debug: https://crbug.com/900447
#define MAYBE_BlockRequests_UrlFilter DISABLED_BlockRequests_UrlFilter
#else
#define MAYBE_BlockRequests_UrlFilter BlockRequests_UrlFilter
@@ -2091,8 +2109,6 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
EXPECT_FALSE(IsNavigationBlocked(unblocked_url));
};
- const char* kLoadRulesetResultHistogram =
- "Extensions.DeclarativeNetRequest.LoadRulesetResult";
const char* kReindexHistogram =
"Extensions.DeclarativeNetRequest.RulesetReindexSuccessful";
@@ -2104,19 +2120,13 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
base::HistogramTester tester;
test_extension_works_after_reload();
- // Loading the ruleset would have failed initially due to checksum mismatch
- // and later succeeded.
- tester.ExpectBucketCount(kLoadRulesetResultHistogram,
- RulesetMatcher::LoadRulesetResult::
- kLoadErrorChecksumMismatch /* sample */,
- 1 /* count */);
- // Count of 2 because we load both static and dynamic rulesets.
- tester.ExpectBucketCount(
- kLoadRulesetResultHistogram,
- RulesetMatcher::LoadRulesetResult::kLoadSuccess /* sample */,
- 2 /* count */);
- // Verify that reindexing of the static ruleset succeeded.
+ // Loading the static ruleset would fail initially due to checksum mismatch
+ // but will succeed on re-indexing.
tester.ExpectBucketCount(kReindexHistogram, true /*sample*/, 1 /*count*/);
+ // Count of 2 because we load both static and dynamic rulesets.
+ tester.ExpectBucketCount(kLoadRulesetResultHistogram,
+ LoadRulesetResult::kSuccess /* sample */,
+ 2 /* count */);
}
// Test dynamic ruleset re-indexing.
@@ -2127,19 +2137,14 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
base::HistogramTester tester;
test_extension_works_after_reload();
- // Loading the ruleset would have failed initially due to checksum mismatch
- // and later succeeded.
- tester.ExpectBucketCount(kLoadRulesetResultHistogram,
- RulesetMatcher::LoadRulesetResult::
- kLoadErrorChecksumMismatch /* sample */,
- 1 /* count */);
- // Count of 2 because we load both static and dynamic rulesets.
- tester.ExpectBucketCount(
- kLoadRulesetResultHistogram,
- RulesetMatcher::LoadRulesetResult::kLoadSuccess /* sample */,
- 2 /* count */);
- // Verify that reindexing of the dynamic ruleset succeeded.
+ // Loading the dynamic ruleset would have failed initially due to checksum
+ // mismatch and later succeeded on re-indexing.
tester.ExpectBucketCount(kReindexHistogram, true /*sample*/, 1 /*count*/);
+
+ // Count of 2 because we load both static and dynamic rulesets.
+ tester.ExpectBucketCount(kLoadRulesetResultHistogram,
+ LoadRulesetResult::kSuccess /* sample */,
+ 2 /* count */);
}
// Go crazy and corrupt both static and dynamic rulesets.
@@ -2153,17 +2158,11 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
// Loading the ruleset would have failed initially due to checksum mismatch
// and later succeeded.
+ tester.ExpectBucketCount(kReindexHistogram, true /*sample*/, 2 /*count*/);
+ // Count of 2 because we load both static and dynamic rulesets.
tester.ExpectBucketCount(kLoadRulesetResultHistogram,
- RulesetMatcher::LoadRulesetResult::
- kLoadErrorChecksumMismatch /* sample */,
+ LoadRulesetResult::kSuccess /* sample */,
2 /* count */);
- // Count of 2 because we load both static and dynamic rulesets.
- tester.ExpectBucketCount(
- kLoadRulesetResultHistogram,
- RulesetMatcher::LoadRulesetResult::kLoadSuccess /* sample */,
- 2 /* count */);
- // Verify that reindexing of both the rulesets succeeded.
- tester.ExpectBucketCount(kReindexHistogram, true /*sample*/, 2 /*count*/);
}
}
@@ -2228,17 +2227,15 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
// Verify that loading the corrupted rulesets failed due to checksum mismatch.
// The non-corrupted rulesets should load fine.
- tester.ExpectTotalCount("Extensions.DeclarativeNetRequest.LoadRulesetResult",
- rulesets.size());
+ tester.ExpectTotalCount(kLoadRulesetResultHistogram, rulesets.size());
EXPECT_EQ(corrupted_ruleset_indices.size(),
static_cast<size_t>(tester.GetBucketCount(
- "Extensions.DeclarativeNetRequest.LoadRulesetResult",
- RulesetMatcher::LoadRulesetResult::
- kLoadErrorChecksumMismatch /*sample*/)));
+ kLoadRulesetResultHistogram,
+ LoadRulesetResult::kErrorChecksumMismatch /*sample*/)));
EXPECT_EQ(non_corrupted_ruleset_indices.size(),
- static_cast<size_t>(tester.GetBucketCount(
- "Extensions.DeclarativeNetRequest.LoadRulesetResult",
- RulesetMatcher::LoadRulesetResult::kLoadSuccess /*sample*/)));
+ static_cast<size_t>(
+ tester.GetBucketCount(kLoadRulesetResultHistogram,
+ LoadRulesetResult::kSuccess /*sample*/)));
// Verify that re-indexing the corrupted rulesets failed.
tester.ExpectUniqueSample(
@@ -2305,22 +2302,14 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed,
// We add 1 to include the dynamic ruleset.
const int kNumRulesets = kNumStaticRulesets + 1;
- // Verify that loading the static and dynamic rulesets would have failed
- // initially due to version header mismatch and later succeeded.
- EXPECT_EQ(kNumRulesets,
- tester.GetBucketCount(
- "Extensions.DeclarativeNetRequest.LoadRulesetResult",
- RulesetMatcher::LoadRulesetResult::
- kLoadErrorVersionMismatch /*sample*/));
- EXPECT_EQ(kNumRulesets,
- tester.GetBucketCount(
- "Extensions.DeclarativeNetRequest.LoadRulesetResult",
- RulesetMatcher::LoadRulesetResult::kLoadSuccess /*sample*/));
-
- // Verify that reindexing succeeded.
+ // Verify that loading the static and dynamic rulesets would cause reindexing
+ // due to version header mismatch and later succeeded.
tester.ExpectUniqueSample(
"Extensions.DeclarativeNetRequest.RulesetReindexSuccessful",
true /*sample*/, kNumRulesets /*count*/);
+ EXPECT_EQ(kNumRulesets,
+ tester.GetBucketCount(kLoadRulesetResultHistogram,
+ LoadRulesetResult::kSuccess /*sample*/));
// Ensure that the new checksum was correctly persisted in prefs.
const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
@@ -2762,11 +2751,15 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
int priority;
std::string action_type;
base::Optional<std::string> redirect_url;
+ base::Optional<std::vector<TestHeaderInfo>> request_headers;
} rules_data[] = {
- {"abc.com", 1, 1, "block", base::nullopt},
- {"def.com", 2, 1, "redirect", "http://zzz.com"},
- {"abcd.com", 4, 1, "block", base::nullopt},
- {"abcd", 5, 1, "allow", base::nullopt},
+ {"abc.com", 1, 1, "block", base::nullopt, base::nullopt},
+ {"def.com", 2, 1, "redirect", "http://zzz.com", base::nullopt},
+ {"jkl.com", 3, 1, "modifyHeaders", base::nullopt,
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("referer", "remove", base::nullopt)})},
+ {"abcd.com", 4, 1, "block", base::nullopt, base::nullopt},
+ {"abcd", 5, 1, "allow", base::nullopt, base::nullopt},
};
// Load the extension.
@@ -2781,6 +2774,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
rule.action->type = rule_data.action_type;
rule.action->redirect.emplace();
rule.action->redirect->url = rule_data.redirect_url;
+ rule.action->request_headers = rule_data.request_headers;
rules.push_back(rule);
}
@@ -2810,10 +2804,17 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
// def.com is redirected by a matching rule and should increment the badge
// text.
{"def.com", "2", false},
+ // jkl.com matches with a modifyHeaders rule which removes the referer
+ // header, but has no headers. Therefore no action is taken and the badge
+ // text stays the same.
+ {"jkl.com", "2", false},
+ // jkl.com matches with a modifyHeaders rule and has a referer header.
+ // Therefore the badge text should be incremented.
+ {"jkl.com", "3", true},
// abcd.com matches both a block rule and an allow rule. Since the allow
// rule overrides the block rule, no action is taken and the badge text
// stays the same,
- {"abcd.com", "2", false},
+ {"abcd.com", "3", false},
};
ui_test_utils::NavigateToURL(browser(), page_url);
@@ -2879,9 +2880,11 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
// Four rules should be matched on the tab with |first_tab_id|:
// - the block rule for abc.com (ruleId = 1)
// - the redirect rule for def.com (ruleId = 2)
+ // - the modifyHeaders rule for jkl.com (ruleId = 3)
// - the allow rule for abcd.com (ruleId = 5)
- EXPECT_EQ(base::StringPrintf("1,%s|2,%s|5,%s", kDefaultRulesetID,
- kDefaultRulesetID, kDefaultRulesetID),
+ EXPECT_EQ(base::StringPrintf("1,%s|2,%s|3,%s|5,%s", kDefaultRulesetID,
+ kDefaultRulesetID, kDefaultRulesetID,
+ kDefaultRulesetID),
get_matched_rules(first_tab_id));
// No rule should be matched on the tab with |second_tab_id|.
@@ -3180,6 +3183,10 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
"/pages_with_script/index.html");
};
+ auto get_set_cookie_url = [this](std::string hostname) {
+ return embedded_test_server()->GetURL(hostname, "/set-cookie?a=b");
+ };
+
struct {
std::string url_filter;
int id;
@@ -3187,16 +3194,24 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
std::string action_type;
std::vector<std::string> resource_types;
base::Optional<std::string> redirect_url;
+ base::Optional<std::vector<TestHeaderInfo>> response_headers;
} rules_data[] = {
{"abc.com", 1, 1, "block", std::vector<std::string>({"script"}),
- base::nullopt},
+ base::nullopt, base::nullopt},
{"||def.com", 2, 1, "redirect", std::vector<std::string>({"main_frame"}),
- get_url_for_host("abc.com").spec()},
+ get_url_for_host("abc.com").spec(), base::nullopt},
{"gotodef.com", 3, 1, "redirect",
std::vector<std::string>({"main_frame"}),
- get_url_for_host("def.com").spec()},
+ get_url_for_host("def.com").spec(), base::nullopt},
{"ghi.com", 4, 1, "block", std::vector<std::string>({"main_frame"}),
- base::nullopt},
+ base::nullopt, base::nullopt},
+ {"gotosetcookie.com", 5, 1, "redirect",
+ std::vector<std::string>({"main_frame"}),
+ get_set_cookie_url("setcookie.com").spec(), base::nullopt},
+ {"setcookie.com", 6, 1, "modifyHeaders",
+ std::vector<std::string>({"main_frame"}), base::nullopt,
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("set-cookie", "remove", base::nullopt)})},
};
// Load the extension.
@@ -3210,6 +3225,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
rule.action->type = rule_data.action_type;
rule.action->redirect.emplace();
rule.action->redirect->url = rule_data.redirect_url;
+ rule.action->response_headers = rule_data.response_headers;
rules.push_back(rule);
}
@@ -3245,6 +3261,10 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
// gotodef.com to def.com caused by a rule match. Therefore the badge text
// should be 3.
{"gotodef.com", "3"},
+ // The request to gotosetcookie.com will match with a rule and redirect to
+ // setcookie.com. The Set-Cookie header on setcookie.com will also match
+ // with a rule and get removed. Therefore the badge text should be 2.
+ {"gotosetcookie.com", "2"},
};
int first_tab_id = ExtensionTabUtil::GetTabId(web_contents());
@@ -3258,6 +3278,160 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
}
}
+IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
+ ModifyHeadersBadgeText) {
+ auto get_referer_url = [this](const std::string& host) {
+ return embedded_test_server()->GetURL(host, "/set-header?referer: none");
+ };
+ auto get_set_cookie_url = [this](const std::string& host) {
+ return embedded_test_server()->GetURL(host, "/set-cookie?a=b");
+ };
+ auto get_no_headers_url = [this](const std::string& host) {
+ return embedded_test_server()->GetURL(host,
+ "/pages_with_script/index.html");
+ };
+
+ const std::string kFrameName1 = "frame1";
+ const GURL page_url = embedded_test_server()->GetURL(
+ "nomatch.com", "/page_with_two_frames.html");
+
+ // Create an extension with rules and get the ExtensionAction for it.
+ TestRule example_set_cookie_rule = CreateModifyHeadersRule(
+ kMinValidID, kMinValidPriority, "example.com", base::nullopt,
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("set-cookie", "remove", base::nullopt)}));
+
+ TestRule both_headers_rule = CreateModifyHeadersRule(
+ kMinValidID + 1, kMinValidPriority, "google.com",
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("referer", "remove", base::nullopt)}),
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("set-cookie", "remove", base::nullopt)}));
+
+ TestRule abc_set_cookie_rule = CreateModifyHeadersRule(
+ kMinValidID + 2, kMinValidPriority, "abc.com", base::nullopt,
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("set-cookie", "remove", base::nullopt)}));
+
+ TestRule abc_referer_rule = CreateModifyHeadersRule(
+ kMinValidID + 3, kMinValidPriority, "abc.com",
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("referer", "remove", base::nullopt)}),
+ base::nullopt);
+
+ TestRule ext1_set_custom_request_header_rule = CreateModifyHeadersRule(
+ kMinValidID + 4, kMinValidPriority, "def.com",
+ std::vector<TestHeaderInfo>({TestHeaderInfo("header1", "set", "ext_1")}),
+ base::nullopt);
+
+ TestRule ext1_add_custom_response_header_rule = CreateModifyHeadersRule(
+ kMinValidID + 5, kMinValidPriority, "ghi.com", base::nullopt,
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("header2", "append", "ext_1")}));
+
+ ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
+ {example_set_cookie_rule, both_headers_rule, abc_set_cookie_rule,
+ abc_referer_rule, ext1_set_custom_request_header_rule,
+ ext1_add_custom_response_header_rule},
+ "extension_1", {URLPattern::kAllUrlsPattern}));
+
+ const ExtensionId extension_1_id = last_loaded_extension_id();
+ ExtensionPrefs::Get(profile())->SetDNRUseActionCountAsBadgeText(
+ extension_1_id, true);
+
+ ExtensionAction* extension_1_action =
+ ExtensionActionManager::Get(web_contents()->GetBrowserContext())
+ ->GetExtensionAction(*extension_registry()->GetExtensionById(
+ extension_1_id, extensions::ExtensionRegistry::ENABLED));
+
+ // Create another extension which removes the referer header from example.com
+ // and get the ExtensionAction for it.
+ TestRule example_referer_rule = CreateModifyHeadersRule(
+ kMinValidID, kMinValidPriority, "example.com",
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("referer", "remove", base::nullopt)}),
+ base::nullopt);
+
+ TestRule ext2_set_custom_request_header_rule = CreateModifyHeadersRule(
+ kMinValidID + 4, kMinValidPriority, "def.com",
+ std::vector<TestHeaderInfo>({TestHeaderInfo("header1", "set", "ext_2")}),
+ base::nullopt);
+
+ TestRule ext2_add_custom_response_header_rule = CreateModifyHeadersRule(
+ kMinValidID + 5, kMinValidPriority, "ghi.com", base::nullopt,
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("header2", "append", "ext_2")}));
+
+ ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(
+ {example_referer_rule, ext2_set_custom_request_header_rule,
+ ext2_add_custom_response_header_rule},
+ "extension_2", {URLPattern::kAllUrlsPattern}));
+
+ const ExtensionId extension_2_id = last_loaded_extension_id();
+ ExtensionPrefs::Get(profile())->SetDNRUseActionCountAsBadgeText(
+ extension_2_id, true);
+
+ ExtensionAction* extension_2_action =
+ ExtensionActionManager::Get(web_contents()->GetBrowserContext())
+ ->GetExtensionAction(*extension_registry()->GetExtensionById(
+ extension_2_id, extensions::ExtensionRegistry::ENABLED));
+
+ struct {
+ GURL url;
+ bool use_referrer;
+ std::string expected_ext_1_badge_text;
+ std::string expected_ext_2_badge_text;
+ } test_cases[] = {
+ // This request only has a Set-Cookie header. Only the badge text for the
+ // extension with a remove Set-Cookie header rule should be incremented.
+ {get_set_cookie_url("example.com"), false, "1", ""},
+ // This request only has a Referer header. Only the badge text for the
+ // extension with a remove Referer header rule should be incremented.
+ {get_referer_url("example.com"), true, "1", "1"},
+ // This request has both a Referer and a Set-Cookie header. The badge text
+ // for both extensions should be incremented.
+ {get_set_cookie_url("example.com"), true, "2", "2"},
+ // This request with a Referer and Set-Cookie header matches with one rule
+ // from |extension_1| and so the action count for |extension_1| should
+ // only increment by one,
+ {get_set_cookie_url("google.com"), true, "3", "2"},
+ // This request with a Referer and Set-Cookie header matches with two
+ // separate rules from |extension_1| and so the action count for
+ // |extension_1| should increment by two.
+ {get_set_cookie_url("abc.com"), true, "5", "2"},
+ // This request without headers matches rules to set the header1 request
+ // header from both extensions. Since |extension_2| was installed later
+ // than |extension_1|, only the rule from |extension_2| should take effect
+ // and so the action count for |extension_2| should increment by one.
+ {get_no_headers_url("def.com"), false, "5", "3"},
+ // This request without headers matches rules to append the header2
+ // response header from both extensions. Since each extension has a rule
+ // which has taken effect, the action count for both extensions should
+ // increment by one.
+ {get_no_headers_url("ghi.com"), false, "6", "4"},
+ };
+
+ ui_test_utils::NavigateToURL(browser(), page_url);
+ ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame()));
+
+ int first_tab_id = ExtensionTabUtil::GetTabId(web_contents());
+ EXPECT_EQ("", extension_1_action->GetDisplayBadgeText(first_tab_id));
+ EXPECT_EQ("", extension_2_action->GetDisplayBadgeText(first_tab_id));
+
+ for (const auto& test_case : test_cases) {
+ SCOPED_TRACE(base::StringPrintf("Testing URL: %s, using referrer: %s",
+ test_case.url.spec().c_str(),
+ test_case.use_referrer ? "true" : "false"));
+
+ NavigateFrame(kFrameName1, test_case.url, test_case.use_referrer);
+ EXPECT_EQ(test_case.expected_ext_1_badge_text,
+ extension_1_action->GetDisplayBadgeText(first_tab_id));
+
+ EXPECT_EQ(test_case.expected_ext_2_badge_text,
+ extension_2_action->GetDisplayBadgeText(first_tab_id));
+ }
+}
+
// Test that the onRuleMatchedDebug event is only available for unpacked
// extensions.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
@@ -3286,6 +3460,81 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
ASSERT_EQ(expected_event_availability, actual_event_availability);
}
+// Test that the onRuleMatchedDebug event returns the correct number of matched
+// rules for a request which is matched with multiple rules.
+IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Unpacked,
+ OnRuleMatchedDebugMultipleRules) {
+ // This is only tested for unpacked extensions since the onRuleMatchedDebug
+ // event is only available for unpacked extensions.
+ ASSERT_EQ(ExtensionLoadType::UNPACKED, GetParam());
+
+ // Load the extension with a background script so scripts can be run from its
+ // generated background page. Also grant the feedback permission for the
+ // extension so it has access to the onRuleMatchedDebug event.
+ set_config_flags(ConfigFlag::kConfig_HasBackgroundScript |
+ ConfigFlag::kConfig_HasFeedbackPermission);
+
+ const std::string kFrameName1 = "frame1";
+ const std::string sub_frame_host = "abc.com";
+ const GURL page_url = embedded_test_server()->GetURL(
+ "nomatch.com", "/page_with_two_frames.html");
+
+ TestRule abc_referer_rule = CreateModifyHeadersRule(
+ kMinValidID, kMinValidPriority, sub_frame_host,
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("referer", "remove", base::nullopt)}),
+ base::nullopt);
+
+ TestRule abc_set_cookie_rule = CreateModifyHeadersRule(
+ kMinValidID + 1, kMinValidPriority, sub_frame_host, base::nullopt,
+ std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("set-cookie", "remove", base::nullopt)}));
+
+ // Load an extension with removeHeaders rules for the Referer and Set-Cookie
+ // headers.
+ ASSERT_NO_FATAL_FAILURE(
+ LoadExtensionWithRules({abc_set_cookie_rule, abc_referer_rule},
+ "extension_1", {URLPattern::kAllUrlsPattern}));
+
+ ui_test_utils::NavigateToURL(browser(), page_url);
+ ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame()));
+
+ // Start the onRuleMatchedDebug observer.
+ const char kOnRuleMatchedDebugScript[] = R"(
+ var matchedRules = [];
+ var onRuleMatchedDebugCallback = (rule) => {
+ matchedRules.push(rule);
+ };
+
+ chrome.declarativeNetRequest.onRuleMatchedDebug.addListener(
+ onRuleMatchedDebugCallback);
+ window.domAutomationController.send('ready');
+ )";
+
+ ASSERT_EQ("ready", ExecuteScriptInBackgroundPage(last_loaded_extension_id(),
+ kOnRuleMatchedDebugScript));
+
+ auto set_cookie_and_referer_url =
+ embedded_test_server()->GetURL(sub_frame_host, "/set-cookie?a=b");
+
+ NavigateFrame(kFrameName1, set_cookie_and_referer_url);
+
+ // Now query the onRuleMatchedDebug results.
+ const char kQueryMatchedRulesScript[] = R"(
+ chrome.declarativeNetRequest.onRuleMatchedDebug.removeListener(
+ onRuleMatchedDebugCallback);
+ var ruleIds = matchedRules.map(matchedRule => matchedRule.rule.ruleId);
+ window.domAutomationController.send(ruleIds.sort().join());
+ )";
+
+ std::string matched_rule_ids = ExecuteScriptInBackgroundPage(
+ last_loaded_extension_id(), kQueryMatchedRulesScript);
+
+ // The request to |set_cookie_and_referer_url| should be matched with the
+ // Referer rule (ruleId 1) and the Set-Cookie rule (ruleId 2).
+ EXPECT_EQ("1,2", matched_rule_ids);
+}
+
// Test that getMatchedRules returns the correct rules when called by different
// extensions with rules matched by requests initiated from different tabs.
IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest,
diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_unittest.cc
index e4b0f34e4ee..4e96958b66a 100644
--- a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_unittest.cc
@@ -38,6 +38,7 @@
#include "extensions/browser/api/declarative_net_request/ruleset_manager.h"
#include "extensions/browser/api/declarative_net_request/ruleset_matcher.h"
#include "extensions/browser/api/declarative_net_request/test_utils.h"
+#include "extensions/browser/api/declarative_net_request/utils.h"
#include "extensions/browser/api_test_utils.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/test_extension_registry_observer.h"
@@ -335,9 +336,9 @@ class SingleRulesetTest : public DeclarativeNetRequestUnittest {
else
rules_count = rules_list_.size();
- // We only index up to dnr_api::MAX_NUMBER_OF_RULES rules per ruleset.
- rules_count = std::min(rules_count,
- static_cast<size_t>(dnr_api::MAX_NUMBER_OF_RULES));
+ // We only index up to GetStaticRuleLimit() rules per ruleset.
+ rules_count =
+ std::min(rules_count, static_cast<size_t>(GetStaticRuleLimit()));
DeclarativeNetRequestUnittest::LoadAndExpectSuccess(rules_count,
rules_count, true);
@@ -652,10 +653,14 @@ TEST_P(SingleRulesetTest, InvalidJSONRules_Parsed) {
}
}
-// Ensure that we can add up to MAX_NUMBER_OF_RULES.
+// Ensure that we can add up to GetStaticRuleLimit() rules.
TEST_P(SingleRulesetTest, RuleCountLimitMatched) {
+ // Override the API rule limit to prevent a timeout on loading the extension.
+ base::AutoReset<int> rule_limit_override =
+ CreateScopedStaticRuleLimitOverrideForTesting(100);
+
TestRule rule = CreateGenericRule();
- for (int i = 0; i < dnr_api::MAX_NUMBER_OF_RULES; ++i) {
+ for (int i = 0; i < GetStaticRuleLimit(); ++i) {
rule.id = kMinValidID + i;
rule.condition->url_filter = std::to_string(i);
AddRule(rule);
@@ -665,8 +670,12 @@ TEST_P(SingleRulesetTest, RuleCountLimitMatched) {
// Ensure that we get an install warning on exceeding the rule count limit.
TEST_P(SingleRulesetTest, RuleCountLimitExceeded) {
+ // Override the API rule limit to prevent a timeout on loading the extension.
+ base::AutoReset<int> rule_limit_override =
+ CreateScopedStaticRuleLimitOverrideForTesting(100);
+
TestRule rule = CreateGenericRule();
- for (int i = 1; i <= dnr_api::MAX_NUMBER_OF_RULES + 1; ++i) {
+ for (int i = 1; i <= GetStaticRuleLimit() + 1; ++i) {
rule.id = kMinValidID + i;
rule.condition->url_filter = std::to_string(i);
AddRule(rule);
@@ -749,10 +758,14 @@ TEST_P(SingleRulesetTest, WarningAndError) {
// Ensure that we get an install warning on exceeding the regex rule count
// limit.
TEST_P(SingleRulesetTest, RegexRuleCountExceeded) {
+ // Override the API rule limit to prevent a timeout on loading the extension.
+ base::AutoReset<int> rule_limit_override =
+ CreateScopedRegexRuleLimitOverrideForTesting(100);
+
TestRule regex_rule = CreateGenericRule();
regex_rule.condition->url_filter.reset();
int rule_id = kMinValidID;
- for (int i = 1; i <= dnr_api::MAX_NUMBER_OF_REGEX_RULES + 5; ++i, ++rule_id) {
+ for (int i = 1; i <= GetRegexRuleLimit() + 5; ++i, ++rule_id) {
regex_rule.id = rule_id;
regex_rule.condition->regex_filter = std::to_string(i);
AddRule(regex_rule);
@@ -767,8 +780,7 @@ TEST_P(SingleRulesetTest, RegexRuleCountExceeded) {
}
extension_loader()->set_ignore_manifest_warnings(true);
- LoadAndExpectSuccess(dnr_api::MAX_NUMBER_OF_REGEX_RULES +
- kCountNonRegexRules);
+ LoadAndExpectSuccess(GetRegexRuleLimit() + kCountNonRegexRules);
// TODO(crbug.com/879355): CrxInstaller reloads the extension after moving it,
// which causes it to lose the install warning. This should be fixed.
if (GetParam() != ExtensionLoadType::PACKED) {
@@ -952,10 +964,9 @@ class MultipleRulesetsTest : public DeclarativeNetRequestUnittest {
for (const TestRulesetInfo& info : rulesets_) {
size_t count = info.rules_value.GetList().size();
- // We only index up to dnr_api::MAX_NUMBER_OF_RULES per ruleset, but may
+ // We only index up to GetStaticRuleLimit() rules per ruleset, but may
// index more rules than this limit across rulesets.
- count =
- std::min(count, static_cast<size_t>(dnr_api::MAX_NUMBER_OF_RULES));
+ count = std::min(count, static_cast<size_t>(GetStaticRuleLimit()));
rules_count += count;
if (info.enabled)
@@ -1017,6 +1028,12 @@ TEST_P(MultipleRulesetsTest, ListNotPassed) {
// Tests an extension with multiple static rulesets with each ruleset generating
// some install warnings.
TEST_P(MultipleRulesetsTest, InstallWarnings) {
+ // Override the API rule limit to prevent a timeout on loading the extension.
+ base::AutoReset<int> rule_limit_override =
+ CreateScopedStaticRuleLimitOverrideForTesting(100);
+ base::AutoReset<int> regex_rule_limit_override =
+ CreateScopedRegexRuleLimitOverrideForTesting(60);
+
size_t expected_rule_count = 0;
size_t enabled_rule_count = 0;
std::vector<std::string> expected_warnings;
@@ -1045,29 +1062,27 @@ TEST_P(MultipleRulesetsTest, InstallWarnings) {
{
// Persist a ruleset with an install warning for exceeding the rule count.
TestRulesetInfo info =
- CreateRuleset(kId2, dnr_api::MAX_NUMBER_OF_RULES + 1, 0, false);
+ CreateRuleset(kId2, GetStaticRuleLimit() + 1, 0, false);
AddRuleset(info);
expected_warnings.push_back(
GetErrorWithFilename(kRuleCountExceeded, info.relative_file_path));
- expected_rule_count += dnr_api::MAX_NUMBER_OF_RULES;
+ expected_rule_count += GetStaticRuleLimit();
}
{
// Persist a ruleset with an install warning for exceeding the regex rule
// count.
size_t kCountNonRegexRules = 5;
- TestRulesetInfo info =
- CreateRuleset(kId3, kCountNonRegexRules,
- dnr_api::MAX_NUMBER_OF_REGEX_RULES + 1, false);
+ TestRulesetInfo info = CreateRuleset(kId3, kCountNonRegexRules,
+ GetRegexRuleLimit() + 1, false);
AddRuleset(info);
expected_warnings.push_back(
GetErrorWithFilename(kRegexRuleCountExceeded, info.relative_file_path));
- expected_rule_count +=
- kCountNonRegexRules + dnr_api::MAX_NUMBER_OF_REGEX_RULES;
+ expected_rule_count += kCountNonRegexRules + GetRegexRuleLimit();
}
extension_loader()->set_ignore_manifest_warnings(true);
@@ -1111,12 +1126,16 @@ TEST_P(MultipleRulesetsTest, EnabledRulesCount) {
// Ensure that exceeding the rules count limit across rulesets raises an install
// warning.
TEST_P(MultipleRulesetsTest, StaticRuleCountExceeded) {
+ // Override the API rule limit to prevent a timeout on loading the extension.
+ base::AutoReset<int> rule_limit_override =
+ CreateScopedStaticRuleLimitOverrideForTesting(50);
+
// Enabled on load.
AddRuleset(CreateRuleset(kId1, 10, 0, true));
// Disabled by default.
AddRuleset(CreateRuleset(kId2, 20, 0, false));
// Not enabled on load since including it exceeds the static rules count.
- AddRuleset(CreateRuleset(kId3, dnr_api::MAX_NUMBER_OF_RULES + 10, 0, true));
+ AddRuleset(CreateRuleset(kId3, GetStaticRuleLimit() + 10, 0, true));
// Enabled on load.
AddRuleset(CreateRuleset(kId4, 30, 0, true));
@@ -1126,8 +1145,6 @@ TEST_P(MultipleRulesetsTest, StaticRuleCountExceeded) {
{
// To prevent timeouts in debug builds, increase the wait timeout to the
// test launcher's timeout. See crbug.com/1071403.
- // TODO(karandeepb): Provide a way to fake dnr_api::MAX_NUMBER_OF_RULES in
- // tests to decrease test runtime.
base::test::ScopedRunLoopTimeout specific_timeout(
FROM_HERE, TestTimeouts::test_launcher_timeout());
LoadAndExpectSuccess();
@@ -1167,7 +1184,7 @@ TEST_P(MultipleRulesetsTest, RegexRuleCountExceeded) {
AddRuleset(CreateRuleset(kId1, 10000, 100, true));
// Won't be enabled on load since including it will exceed the regex rule
// count.
- AddRuleset(CreateRuleset(kId2, 1, dnr_api::MAX_NUMBER_OF_REGEX_RULES, true));
+ AddRuleset(CreateRuleset(kId2, 1, GetRegexRuleLimit(), true));
// Won't be enabled on load since it is disabled by default.
AddRuleset(CreateRuleset(kId3, 10, 10, false));
// Enabled on load.
@@ -1225,8 +1242,12 @@ TEST_P(MultipleRulesetsTest, UpdateEnabledRulesets_InvalidRulesetID) {
}
TEST_P(MultipleRulesetsTest, UpdateEnabledRulesets_RuleCountExceeded) {
+ // Override the API rule limit to prevent a timeout on loading the extension.
+ base::AutoReset<int> rule_limit_override =
+ CreateScopedStaticRuleLimitOverrideForTesting(100);
+
AddRuleset(CreateRuleset(kId1, 10, 10, true));
- AddRuleset(CreateRuleset(kId2, dnr_api::MAX_NUMBER_OF_RULES, 0, false));
+ AddRuleset(CreateRuleset(kId2, GetStaticRuleLimit(), 0, false));
RulesetManagerObserver ruleset_waiter(manager());
LoadAndExpectSuccess();
@@ -1245,7 +1266,7 @@ TEST_P(MultipleRulesetsTest, UpdateEnabledRulesets_RuleCountExceeded) {
TEST_P(MultipleRulesetsTest, UpdateEnabledRulesets_RegexRuleCountExceeded) {
AddRuleset(CreateRuleset(kId1, 0, 10, false));
- AddRuleset(CreateRuleset(kId2, 0, dnr_api::MAX_NUMBER_OF_REGEX_RULES, true));
+ AddRuleset(CreateRuleset(kId2, 0, GetRegexRuleLimit(), true));
RulesetManagerObserver ruleset_waiter(manager());
LoadAndExpectSuccess();
@@ -1274,8 +1295,7 @@ TEST_P(MultipleRulesetsTest, UpdateEnabledRulesets_InternalError) {
// First delete the indexed ruleset file for the second ruleset. Enabling it
// should cause re-indexing and succeed in enabling the ruleset.
base::HistogramTester tester;
- ASSERT_TRUE(base::DeleteFile(static_sources[1].indexed_path(),
- false /* recursive */));
+ ASSERT_TRUE(base::DeleteFile(static_sources[1].indexed_path()));
RunUpdateEnabledRulesetsFunction(*extension(), {kId1}, {kId2},
base::nullopt);
@@ -1290,10 +1310,8 @@ TEST_P(MultipleRulesetsTest, UpdateEnabledRulesets_InternalError) {
// Now delete both the indexed and json ruleset file for the first ruleset.
// This will prevent enabling the first ruleset since re-indexing will fail.
base::HistogramTester tester;
- ASSERT_TRUE(base::DeleteFile(static_sources[0].indexed_path(),
- false /* recursive */));
- ASSERT_TRUE(
- base::DeleteFile(static_sources[0].json_path(), false /* recursive */));
+ ASSERT_TRUE(base::DeleteFile(static_sources[0].indexed_path()));
+ ASSERT_TRUE(base::DeleteFile(static_sources[0].json_path()));
RunUpdateEnabledRulesetsFunction(*extension(), {}, {kId1},
kInternalErrorUpdatingEnabledRulesets);
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 2c18c239b23..b1c2a521b2d 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
@@ -14,7 +14,6 @@
#include "chrome/browser/extensions/api/declarative_net_request/dnr_test_base.h"
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/extension_util.h"
-#include "components/version_info/channel.h"
#include "extensions/browser/api/declarative_net_request/composite_matcher.h"
#include "extensions/browser/api/declarative_net_request/request_action.h"
#include "extensions/browser/api/declarative_net_request/ruleset_matcher.h"
@@ -28,7 +27,6 @@
#include "extensions/common/api/declarative_net_request.h"
#include "extensions/common/api/declarative_net_request/constants.h"
#include "extensions/common/api/declarative_net_request/test_utils.h"
-#include "extensions/common/features/feature_channel.h"
#include "extensions/common/file_util.h"
#include "extensions/common/manifest_handlers/background_info.h"
#include "extensions/common/url_pattern.h"
@@ -96,7 +94,7 @@ class RulesetManagerTest : public DNRTestBase {
&expected_checksum));
std::vector<std::unique_ptr<RulesetMatcher>> matchers(1);
- EXPECT_EQ(RulesetMatcher::kLoadSuccess,
+ EXPECT_EQ(LoadRulesetResult::kSuccess,
RulesetMatcher::CreateVerifiedMatcher(
std::move(sources[0]), expected_checksum, &matchers[0]));
@@ -458,22 +456,18 @@ TEST_P(RulesetManagerTest, ExtensionScheme) {
// Test that the correct modifyHeaders actions are returned for each extension.
TEST_P(RulesetManagerTest, ModifyHeaders) {
- // TODO(crbug.com/947591): Remove the channel override once implementation of
- // modifyHeaders action is complete.
- ScopedCurrentChannel channel(::version_info::Channel::UNKNOWN);
-
const Extension* extension_1 = nullptr;
const Extension* extension_2 = nullptr;
- // Add an extension which removes the "header1" and "header2" headers.
+ // Add an extension which removes "header1" and sets "header2".
{
std::unique_ptr<CompositeMatcher> matcher;
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("*");
rule.action->type = std::string("modifyHeaders");
- rule.action->request_headers =
- std::vector<TestHeaderInfo>({TestHeaderInfo("header1", "remove"),
- TestHeaderInfo("header2", "remove")});
+ rule.action->request_headers = std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("header1", "remove", base::nullopt),
+ TestHeaderInfo("header2", "set", "value2")});
ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules(
{rule}, "test extension", &matcher, {URLPattern::kAllUrlsPattern}));
@@ -481,16 +475,16 @@ TEST_P(RulesetManagerTest, ModifyHeaders) {
manager()->AddRuleset(extension_1->id(), std::move(matcher));
}
- // Add another extension which removes the "header1" and "header3" headers.
+ // Add another extension which removes "header1" and appends "header3".
{
std::unique_ptr<CompositeMatcher> matcher;
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("*");
rule.action->type = std::string("modifyHeaders");
- rule.action->request_headers =
- std::vector<TestHeaderInfo>({TestHeaderInfo("header1", "remove")});
- rule.action->response_headers =
- std::vector<TestHeaderInfo>({TestHeaderInfo("header3", "remove")});
+ rule.action->request_headers = std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("header1", "remove", base::nullopt)});
+ rule.action->response_headers = std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("header3", "append", "value3")});
ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules(
{rule}, "test extension 2", &matcher, {URLPattern::kAllUrlsPattern}));
@@ -509,18 +503,20 @@ TEST_P(RulesetManagerTest, ModifyHeaders) {
RequestAction expected_action_1 = CreateRequestActionForTesting(
RequestActionType::MODIFY_HEADERS, kMinValidID, kDefaultPriority,
kMinValidStaticRulesetID, extension_2->id());
- expected_action_1.request_headers_to_modify = {
- RequestAction::HeaderInfo("header1", dnr_api::HEADER_OPERATION_REMOVE)};
- expected_action_1.response_headers_to_modify = {
- RequestAction::HeaderInfo("header3", dnr_api::HEADER_OPERATION_REMOVE)};
+ expected_action_1.request_headers_to_modify = {RequestAction::HeaderInfo(
+ "header1", dnr_api::HEADER_OPERATION_REMOVE, base::nullopt)};
+ expected_action_1.response_headers_to_modify = {RequestAction::HeaderInfo(
+ "header3", dnr_api::HEADER_OPERATION_APPEND, "value3")};
// Create the expected RequestAction for |extension_1|.
RequestAction expected_action_2 = CreateRequestActionForTesting(
RequestActionType::MODIFY_HEADERS, kMinValidID, kDefaultPriority,
kMinValidStaticRulesetID, extension_1->id());
expected_action_2.request_headers_to_modify = {
- RequestAction::HeaderInfo("header1", dnr_api::HEADER_OPERATION_REMOVE),
- RequestAction::HeaderInfo("header2", dnr_api::HEADER_OPERATION_REMOVE)};
+ RequestAction::HeaderInfo("header1", dnr_api::HEADER_OPERATION_REMOVE,
+ base::nullopt),
+ RequestAction::HeaderInfo("header2", dnr_api::HEADER_OPERATION_SET,
+ "value2")};
// Verify that the list of actions is sorted in descending order of extension
// priority.
@@ -533,18 +529,14 @@ TEST_P(RulesetManagerTest, ModifyHeaders) {
// Test that an extension's modify header rules are applied on a request only if
// it has host permissions for the request.
TEST_P(RulesetManagerTest, ModifyHeaders_HostPermissions) {
- // TODO(crbug.com/947591): Remove the channel override once implementation of
- // modifyHeaders action is complete.
- ScopedCurrentChannel channel(::version_info::Channel::UNKNOWN);
-
// Add an extension which removes the "header1" header with host permissions
// for example.com.
std::unique_ptr<CompositeMatcher> matcher;
TestRule rule = CreateGenericRule();
rule.condition->url_filter = std::string("*");
rule.action->type = std::string("modifyHeaders");
- rule.action->request_headers =
- std::vector<TestHeaderInfo>({TestHeaderInfo("header1", "remove")});
+ rule.action->request_headers = std::vector<TestHeaderInfo>(
+ {TestHeaderInfo("header1", "remove", base::nullopt)});
ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules(
{rule}, "test extension", &matcher, {"*://example.com/*"}));
@@ -561,8 +553,8 @@ TEST_P(RulesetManagerTest, ModifyHeaders_HostPermissions) {
RequestAction expected_action = CreateRequestActionForTesting(
RequestActionType::MODIFY_HEADERS, kMinValidID, kDefaultPriority,
kMinValidStaticRulesetID, extension->id());
- expected_action.request_headers_to_modify = {
- RequestAction::HeaderInfo("header1", dnr_api::HEADER_OPERATION_REMOVE)};
+ expected_action.request_headers_to_modify = {RequestAction::HeaderInfo(
+ "header1", dnr_api::HEADER_OPERATION_REMOVE, base::nullopt)};
EXPECT_THAT(actual_actions, ::testing::ElementsAre(::testing::Eq(
::testing::ByRef(expected_action))));
diff --git a/chromium/chrome/browser/extensions/api/developer_private/DEPS b/chromium/chrome/browser/extensions/api/developer_private/DEPS
index 5b9436cd654..96ba367d2e6 100644
--- a/chromium/chrome/browser/extensions/api/developer_private/DEPS
+++ b/chromium/chrome/browser/extensions/api/developer_private/DEPS
@@ -7,4 +7,10 @@ specific_include_rules = {
# Allow the unittest to create a data_decoder service.
"+services/data_decoder"
],
+
+ # This DEPS violation snuck in while there was a bug in the checkdeps tool.
+ # https://crbug.com/1084826
+ "developer_private_api\.cc": [
+ "+chrome/browser/apps/app_service/app_launch_params.h",
+ ],
}
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 c496bd428c4..56c6abbd526 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
@@ -19,7 +19,6 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/apps/app_service/app_launch_params.h"
#include "chrome/browser/devtools/devtools_window.h"
@@ -394,7 +393,8 @@ void DeveloperPrivateEventRouter::RemoveExtensionId(
void DeveloperPrivateEventRouter::OnExtensionLoaded(
content::BrowserContext* browser_context,
const Extension* extension) {
- DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context)));
+ DCHECK(
+ profile_->IsSameOrParent(Profile::FromBrowserContext(browser_context)));
BroadcastItemStateChanged(developer::EVENT_TYPE_LOADED, extension->id());
}
@@ -402,7 +402,8 @@ void DeveloperPrivateEventRouter::OnExtensionUnloaded(
content::BrowserContext* browser_context,
const Extension* extension,
UnloadedExtensionReason reason) {
- DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context)));
+ DCHECK(
+ profile_->IsSameOrParent(Profile::FromBrowserContext(browser_context)));
BroadcastItemStateChanged(developer::EVENT_TYPE_UNLOADED, extension->id());
}
@@ -410,7 +411,8 @@ void DeveloperPrivateEventRouter::OnExtensionInstalled(
content::BrowserContext* browser_context,
const Extension* extension,
bool is_update) {
- DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context)));
+ DCHECK(
+ profile_->IsSameOrParent(Profile::FromBrowserContext(browser_context)));
BroadcastItemStateChanged(developer::EVENT_TYPE_INSTALLED, extension->id());
}
@@ -418,7 +420,8 @@ void DeveloperPrivateEventRouter::OnExtensionUninstalled(
content::BrowserContext* browser_context,
const Extension* extension,
extensions::UninstallReason reason) {
- DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context)));
+ DCHECK(
+ profile_->IsSameOrParent(Profile::FromBrowserContext(browser_context)));
BroadcastItemStateChanged(developer::EVENT_TYPE_UNINSTALLED, extension->id());
}
@@ -1486,8 +1489,8 @@ void DeveloperPrivateLoadDirectoryFunction::ClearExistingDirectoryContent(
pending_copy_operations_count_ = 1;
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPI,
this, project_path, project_path.BaseName()));
@@ -1555,8 +1558,8 @@ void DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPICb(
response = NoArguments();
else
response = Error(error_);
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::Respond, this,
std::move(response)));
}
@@ -1597,8 +1600,8 @@ void DeveloperPrivateLoadDirectoryFunction::CopyFile(
pending_copy_operations_count_--;
if (!pending_copy_operations_count_) {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::Load, this));
}
}
diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc
index 42ae22ba000..79ba1f83ece 100644
--- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc
@@ -466,7 +466,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivatePackFunction) {
// Try to pack a final time when omitting (an existing) pem file. We should
// get an error.
- base::DeleteFile(crx_path, false);
+ base::DeleteFile(crx_path);
EXPECT_TRUE(pack_args.Remove(1u, nullptr)); // Remove the pem key argument.
EXPECT_TRUE(pack_args.Remove(1u, nullptr)); // Remove the flags argument.
EXPECT_TRUE(TestPackExtensionFunction(
diff --git a/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc b/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc
index afb404e5637..ad7d48b8c67 100644
--- a/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc
+++ b/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc
@@ -7,7 +7,6 @@
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/strings/string_util.h"
-#include "base/task/post_task.h"
#include "chrome/browser/extensions/api/developer_private/developer_private_api.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/ui/chrome_select_file_policy.h"
@@ -37,14 +36,14 @@ EntryPicker::EntryPicker(EntryPickerClient* client,
: client_(client) {
if (g_skip_picker_for_test) {
if (g_path_to_be_picked_for_test) {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&EntryPicker::FileSelected, base::Unretained(this),
*g_path_to_be_picked_for_test, 1,
static_cast<void*>(nullptr)));
} else {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&EntryPicker::FileSelectionCanceled,
base::Unretained(this), static_cast<void*>(nullptr)));
}
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 6c4f2b9c43f..af6a8022a03 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
@@ -522,17 +522,10 @@ void ExtensionInfoGenerator::CreateExtensionInfoHelper(
// ControlledInfo.
bool is_policy_location = Manifest::IsPolicyLocation(extension.location());
if (is_policy_location) {
- info->controlled_info.reset(new developer::ControlledInfo());
- if (is_policy_location) {
- info->controlled_info->type = developer::CONTROLLER_TYPE_POLICY;
- info->controlled_info->text =
- l10n_util::GetStringUTF8(IDS_EXTENSIONS_INSTALL_LOCATION_ENTERPRISE);
- } else {
- info->controlled_info->type =
- developer::CONTROLLER_TYPE_SUPERVISED_USER_CUSTODIAN;
- info->controlled_info->text = l10n_util::GetStringUTF8(
- IDS_EXTENSIONS_INSTALLED_BY_SUPERVISED_USER_CUSTODIAN);
- }
+ info->controlled_info = std::make_unique<developer::ControlledInfo>();
+ info->controlled_info->type = developer::CONTROLLER_TYPE_POLICY;
+ info->controlled_info->text =
+ l10n_util::GetStringUTF8(IDS_EXTENSIONS_INSTALL_LOCATION_ENTERPRISE);
}
bool is_enabled = state == developer::EXTENSION_STATE_ENABLED;
@@ -578,6 +571,7 @@ void ExtensionInfoGenerator::CreateExtensionInfoHelper(
bool permissions_increase =
(disable_reasons & disable_reason::DISABLE_PERMISSIONS_INCREASE) != 0;
info->disable_reasons.parent_disabled_permissions =
+ supervised_user_service_->IsChild() &&
!supervised_user_service_
->GetSupervisedUserExtensionsMayRequestPermissionsPref() &&
(custodian_approval_required || permissions_increase);
diff --git a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc
index c80a16f7e47..47d6e81852b 100644
--- a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc
@@ -11,6 +11,7 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback_helpers.h"
+#include "base/files/file_path.h"
#include "base/json/json_file_value_serializer.h"
#include "base/json/json_writer.h"
#include "base/macros.h"
@@ -22,12 +23,13 @@
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/error_console/error_console.h"
#include "chrome/browser/extensions/extension_service.h"
-#include "chrome/browser/extensions/extension_service_test_base.h"
+#include "chrome/browser/extensions/extension_service_test_with_install.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/permissions_test_util.h"
#include "chrome/browser/extensions/permissions_updater.h"
#include "chrome/browser/extensions/scripting_permissions_modifier.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/common/buildflags.h"
#include "chrome/common/extensions/api/developer_private.h"
#include "chrome/common/pref_names.h"
#include "components/crx_file/id_util.h"
@@ -44,6 +46,12 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
+#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
+#include "chrome/browser/supervised_user/supervised_user_service.h"
+#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
+#include "chrome/browser/supervised_user/supervised_user_test_util.h"
+#endif // BUILDFLAG(ENABLE_SUPERVISED_USERS)
+
namespace extensions {
namespace developer = api::developer_private;
@@ -88,15 +96,20 @@ std::string SiteControlsToString(
} // namespace
-class ExtensionInfoGeneratorUnitTest : public ExtensionServiceTestBase {
+class ExtensionInfoGeneratorUnitTest : public ExtensionServiceTestWithInstall {
public:
ExtensionInfoGeneratorUnitTest() {}
~ExtensionInfoGeneratorUnitTest() override {}
protected:
void SetUp() override {
- ExtensionServiceTestBase::SetUp();
- InitializeEmptyExtensionService();
+ ExtensionServiceTestWithInstall::SetUp();
+ InitializeExtensionService(GetExtensionServiceInitParams());
+ }
+
+ // Returns the initialization parameters for the extension service.
+ virtual ExtensionServiceInitParams GetExtensionServiceInitParams() {
+ return CreateDefaultInitParams();
}
void OnInfoGenerated(std::unique_ptr<developer::ExtensionInfo>* info_out,
@@ -810,4 +823,128 @@ TEST_F(ExtensionInfoGeneratorUnitTest, Blacklisted) {
EXPECT_EQ(developer::EXTENSION_STATE_ENABLED, info2->state);
}
+// Tests that the parent_disabled_permissions disable reason is never set for
+// regular users. Prevents a regression to crbug/1100395.
+TEST_F(ExtensionInfoGeneratorUnitTest,
+ NoParentDisabledPermissionsForRegularUsers) {
+ // Preconditions.
+ ASSERT_FALSE(profile()->IsChild());
+
+ base::FilePath base_path = data_dir().AppendASCII("permissions_increase");
+ base::FilePath pem_path = base_path.AppendASCII("permissions.pem");
+ base::FilePath path = base_path.AppendASCII("v1");
+ const Extension* extension = PackAndInstallCRX(path, pem_path, INSTALL_NEW);
+ // The extension must now be installed and enabled.
+ ASSERT_TRUE(extension);
+ ASSERT_TRUE(registry()->enabled_extensions().Contains(extension->id()));
+
+ // Save the id, as |extension| will be destroyed during updating.
+ std::string extension_id = extension->id();
+
+ // Update to a new version with increased permissions.
+ path = base_path.AppendASCII("v2");
+ PackCRXAndUpdateExtension(extension_id, path, pem_path, DISABLED);
+
+ // The extension should be disabled pending approval for permission increases.
+ EXPECT_TRUE(registry()->disabled_extensions().Contains(extension_id));
+
+ // Due to a permissions increase, prefs will contain escalation information.
+ ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
+ EXPECT_TRUE(prefs->DidExtensionEscalatePermissions(extension_id));
+
+ std::unique_ptr<api::developer_private::ExtensionInfo> info =
+ GenerateExtensionInfo(extension_id);
+
+ // Verify that the kite icon error tooltip doesn't appear for regular users.
+ EXPECT_FALSE(info->disable_reasons.parent_disabled_permissions);
+}
+
+#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
+// Tests for supervised users (child accounts). Supervised users are not allowed
+// to install apps or extensions unless their parent approves.
+class ExtensionInfoGeneratorUnitTestSupervised
+ : public ExtensionInfoGeneratorUnitTest {
+ public:
+ ExtensionInfoGeneratorUnitTestSupervised() = default;
+ ~ExtensionInfoGeneratorUnitTestSupervised() override = default;
+
+ SupervisedUserService* GetSupervisedUserService() {
+ return SupervisedUserServiceFactory::GetForProfile(profile());
+ }
+
+ // ExtensionInfoGeneratorUnitTest:
+ ExtensionServiceInitParams GetExtensionServiceInitParams() override {
+ ExtensionServiceInitParams params =
+ ExtensionInfoGeneratorUnitTest::GetExtensionServiceInitParams();
+ // Force a TestingPrefServiceSyncable to be created.
+ params.pref_file.clear();
+ params.profile_is_supervised = true;
+ return params;
+ }
+
+ void SetUp() override {
+ ExtensionInfoGeneratorUnitTest::SetUp();
+
+ // Set up custodians (parents) for the child.
+ supervised_user_test_util::AddCustodians(profile());
+
+ GetSupervisedUserService()->Init();
+ // Set the pref to allow the child to request extension install.
+ GetSupervisedUserService()
+ ->SetSupervisedUserExtensionsMayRequestPermissionsPrefForTesting(true);
+ }
+};
+
+// Tests that when an extension is disabled pending permission updates, and the
+// parent has turned off the "Permissions for sites, apps and extensions"
+// toggle, then supervised users will see a kite error icon with a tooltip.
+TEST_F(ExtensionInfoGeneratorUnitTestSupervised,
+ ParentDisabledPermissionsForSupervisedUsers) {
+ // Preconditions.
+ ASSERT_TRUE(profile()->IsChild());
+
+ base::FilePath base_path = data_dir().AppendASCII("permissions_increase");
+ base::FilePath pem_path = base_path.AppendASCII("permissions.pem");
+ base::FilePath path = base_path.AppendASCII("v1");
+ const Extension* extension =
+ PackAndInstallCRX(path, pem_path, INSTALL_WITHOUT_LOAD);
+ // The extension should be installed but disabled pending custodian approval.
+ ASSERT_TRUE(extension);
+ EXPECT_TRUE(registry()->disabled_extensions().Contains(extension->id()));
+
+ // Save the id, as |extension| will be destroyed during updating.
+ std::string extension_id = extension->id();
+
+ ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
+ EXPECT_TRUE(prefs->HasDisableReason(
+ extension_id, disable_reason::DISABLE_CUSTODIAN_APPROVAL_REQUIRED));
+
+ // Simulate parent approval for the extension installation.
+ GetSupervisedUserService()->AddExtensionApproval(*extension);
+ // The extension should be enabled now.
+ EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_id));
+
+ // Update to a new version with increased permissions.
+ path = base_path.AppendASCII("v2");
+ PackCRXAndUpdateExtension(extension_id, path, pem_path, DISABLED);
+
+ // The extension should be disabled pending approval for permission increases.
+ EXPECT_TRUE(registry()->disabled_extensions().Contains(extension_id));
+
+ // Due to a permission increase, prefs will contain escalation information.
+ EXPECT_TRUE(prefs->DidExtensionEscalatePermissions(extension_id));
+
+ // Simulate the parent disallowing the child from approving permission
+ // updates.
+ GetSupervisedUserService()
+ ->SetSupervisedUserExtensionsMayRequestPermissionsPrefForTesting(false);
+
+ std::unique_ptr<api::developer_private::ExtensionInfo> info =
+ GenerateExtensionInfo(extension_id);
+
+ // Verify that the kite icon error tooltip appears for supervised users.
+ EXPECT_TRUE(info->disable_reasons.parent_disabled_permissions);
+}
+
+#endif // BUILDFLAG(ENABLE_SUPERVISED_USERS)
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc
index 2ae57ab4ddd..cd347b06c7b 100644
--- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc
+++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc
@@ -1563,7 +1563,7 @@ ExtensionFunction::ResponseAction DownloadsSetShelfEnabledFunction::Run() {
(current_service == incognito_service)) &&
browser->window()->IsDownloadShelfVisible() &&
!current_service->IsShelfEnabled())
- browser->window()->GetDownloadShelf()->Close(DownloadShelf::AUTOMATIC);
+ browser->window()->GetDownloadShelf()->Close();
}
}
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 fc10f9ec110..fbf95144f6e 100644
--- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc
@@ -18,7 +18,6 @@
#include "base/run_loop.h"
#include "base/stl_util.h"
#include "base/strings/stringprintf.h"
-#include "base/task/post_task.h"
#include "base/test/bind_test_util.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_restrictions.h"
@@ -68,12 +67,6 @@
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
-#include "net/test/url_request/url_request_slow_download_job.h"
-#include "net/url_request/url_request.h"
-#include "net/url_request/url_request_context.h"
-#include "net/url_request/url_request_job.h"
-#include "net/url_request/url_request_job_factory.h"
-#include "net/url_request/url_request_job_factory_impl.h"
#include "storage/browser/file_system/file_system_context.h"
#include "storage/browser/file_system/file_system_operation_runner.h"
#include "storage/browser/file_system/file_system_url.h"
@@ -114,8 +107,8 @@ void OnOpenPromptCreated(download::DownloadItem* item,
DownloadOpenPrompt* prompt) {
EXPECT_FALSE(item->GetOpened());
// Posts a task to accept the DownloadOpenPrompt.
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&DownloadOpenPrompt::AcceptConfirmationDialogForTesting,
base::Unretained(prompt)));
}
@@ -321,10 +314,9 @@ class DownloadOpenObserver : public download::DownloadItem::Observer {
class DownloadExtensionTest : public ExtensionApiTest {
public:
DownloadExtensionTest()
- : extension_(NULL),
- incognito_browser_(NULL),
- current_browser_(NULL) {
- }
+ : extension_(nullptr),
+ incognito_browser_(nullptr),
+ current_browser_(nullptr) {}
protected:
// Used with CreateHistoryDownloads
@@ -709,8 +701,8 @@ class MockIconExtractorImpl : public DownloadFileIconExtractor {
if (expected_path_ == path &&
expected_icon_size_ == icon_size) {
callback_ = callback;
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&MockIconExtractorImpl::RunCallback,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&MockIconExtractorImpl::RunCallback,
base::Unretained(this)));
return true;
} else {
@@ -793,14 +785,14 @@ class HTML5FileWriter {
// Invoke the fileapi to copy it into the sandboxed filesystem.
bool result = false;
base::RunLoop run_loop;
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&CreateFileForTestingOnIOThread,
base::Unretained(context), path, temp_file,
base::Unretained(&result), run_loop.QuitClosure()));
// Wait for that to finish.
run_loop.Run();
- base::DeleteFile(temp_file, false);
+ base::DeleteFile(temp_file);
return result;
}
@@ -810,7 +802,7 @@ class HTML5FileWriter {
base::File::Error error) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
*result = error == base::File::FILE_OK;
- base::PostTask(FROM_HERE, {BrowserThread::UI}, quit_closure);
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, quit_closure);
}
static void CreateFileForTestingOnIOThread(
@@ -882,14 +874,7 @@ downloads::InterruptReason InterruptReasonContentToExtension(
} // namespace
-#if defined(OS_CHROMEOS)
-// http://crbug.com/396510
-#define MAYBE_DownloadExtensionTest_Open DISABLED_DownloadExtensionTest_Open
-#else
-#define MAYBE_DownloadExtensionTest_Open DownloadExtensionTest_Open
-#endif
-IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
- MAYBE_DownloadExtensionTest_Open) {
+IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_Open) {
LoadExtension("downloads_split");
DownloadsOpenFunction* open_function = new DownloadsOpenFunction();
open_function->set_user_gesture(true);
@@ -1056,16 +1041,10 @@ scoped_refptr<ExtensionFunction> MockedGetFileIconFunction(
return function;
}
-// https://crbug.com/678967
-#if defined(OS_WIN) || defined(OS_LINUX)
-#define MAYBE_DownloadExtensionTest_FileIcon_Active DISABLED_DownloadExtensionTest_FileIcon_Active
-#else
-#define MAYBE_DownloadExtensionTest_FileIcon_Active DownloadExtensionTest_FileIcon_Active
-#endif
// Test downloads.getFileIcon() on in-progress, finished, cancelled and deleted
// download items.
IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
- MAYBE_DownloadExtensionTest_FileIcon_Active) {
+ DownloadExtensionTest_FileIcon_Active) {
DownloadItem* download_item = CreateFirstSlowTestDownload();
ASSERT_TRUE(download_item);
ASSERT_FALSE(download_item->GetTargetFilePath().empty());
@@ -1202,7 +1181,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, FileExistenceCheckAfterSearch) {
// Finish the download and try again.
FinishFirstSlowDownloads();
- base::DeleteFile(download_item->GetTargetFilePath(), false);
+ base::DeleteFile(download_item->GetTargetFilePath());
ASSERT_FALSE(download_item->GetFileExternallyRemoved());
std::unique_ptr<base::Value> result(
@@ -1266,14 +1245,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
// Test the |id| parameter for search().
//
-// http://crbug.com/508949
-#if defined(MEMORY_SANITIZER)
-#define MAYBE_DownloadExtensionTest_SearchId DISABLED_DownloadExtensionTest_SearchId
-#else
-#define MAYBE_DownloadExtensionTest_SearchId DownloadExtensionTest_SearchId
-#endif
-IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
- MAYBE_DownloadExtensionTest_SearchId) {
+IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchId) {
DownloadManager::DownloadVector items;
CreateTwoDownloads(&items);
ScopedItemVectorCanceller delete_items(&items);
@@ -1294,14 +1266,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
// Test specifying both the |id| and |filename| parameters for search().
//
-// http://crbug.com/508949
-#if defined(MEMORY_SANITIZER)
-#define MAYBE_DownloadExtensionTest_SearchIdAndFilename DISABLED_DownloadExtensionTest_SearchIdAndFilename
-#else
-#define MAYBE_DownloadExtensionTest_SearchIdAndFilename DownloadExtensionTest_SearchIdAndFilename
-#endif
IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
- MAYBE_DownloadExtensionTest_SearchIdAndFilename) {
+ DownloadExtensionTest_SearchIdAndFilename) {
DownloadManager::DownloadVector items;
CreateTwoDownloads(&items);
ScopedItemVectorCanceller delete_items(&items);
@@ -1400,15 +1366,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
}
// Test the |state| option for search().
-//
-// http://crbug.com/508949
-#if defined(MEMORY_SANITIZER)
-#define MAYBE_DownloadExtensionTest_SearchState DISABLED_DownloadExtensionTest_SearchState
-#else
-#define MAYBE_DownloadExtensionTest_SearchState DownloadExtensionTest_SearchState
-#endif
IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
- MAYBE_DownloadExtensionTest_SearchState) {
+ DownloadExtensionTest_SearchState) {
DownloadManager::DownloadVector items;
CreateTwoDownloads(&items);
ScopedItemVectorCanceller delete_items(&items);
@@ -1424,15 +1383,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
}
// Test the |limit| option for search().
-//
-// http://crbug.com/508949
-#if defined(MEMORY_SANITIZER)
-#define MAYBE_DownloadExtensionTest_SearchLimit DISABLED_DownloadExtensionTest_SearchLimit
-#else
-#define MAYBE_DownloadExtensionTest_SearchLimit DownloadExtensionTest_SearchLimit
-#endif
IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
- MAYBE_DownloadExtensionTest_SearchLimit) {
+ DownloadExtensionTest_SearchLimit) {
DownloadManager::DownloadVector items;
CreateTwoDownloads(&items);
ScopedItemVectorCanceller delete_items(&items);
@@ -1495,21 +1447,13 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
ASSERT_EQ(items[2]->GetTargetFilePath().value(), item_name);
}
-// https://crbug.com/874946, flaky on Win.
-#if defined(OS_WIN)
-#define MAYBE_DownloadExtensionTest_SearchPauseResumeCancelGetFileIconIncognito \
- DISABLED_DownloadExtensionTest_SearchPauseResumeCancelGetFileIconIncognito
-#else
-#define MAYBE_DownloadExtensionTest_SearchPauseResumeCancelGetFileIconIncognito \
- DownloadExtensionTest_SearchPauseResumeCancelGetFileIconIncognito
-#endif
// Test that incognito downloads are only visible in incognito contexts, and
// test that on-record downloads are visible in both incognito and on-record
// contexts, for DownloadsSearchFunction, DownloadsPauseFunction,
// DownloadsResumeFunction, and DownloadsCancelFunction.
IN_PROC_BROWSER_TEST_F(
DownloadExtensionTest,
- MAYBE_DownloadExtensionTest_SearchPauseResumeCancelGetFileIconIncognito) {
+ DownloadExtensionTest_SearchPauseResumeCancelGetFileIconIncognito) {
std::unique_ptr<base::Value> result_value;
base::ListValue* result_list = NULL;
base::DictionaryValue* result_dict = NULL;
@@ -1887,18 +1831,9 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
result_id)));
}
-#if defined(OS_WIN)
-// This test is very flaky on Win. http://crbug.com/248438
-#define MAYBE_DownloadExtensionTest_Download_UnsafeHeaders \
- DISABLED_DownloadExtensionTest_Download_UnsafeHeaders
-#else
-#define MAYBE_DownloadExtensionTest_Download_UnsafeHeaders \
- DownloadExtensionTest_Download_UnsafeHeaders
-#endif
-
// Test that we disallow certain headers case-insensitively.
IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
- MAYBE_DownloadExtensionTest_Download_UnsafeHeaders) {
+ DownloadExtensionTest_Download_UnsafeHeaders) {
LoadExtension("downloads_split");
ASSERT_TRUE(StartEmbeddedTestServer());
GoOnTheRecord();
@@ -1975,6 +1910,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
download_url.c_str())).c_str());
}
+// This test is very flaky on Win. http://crbug.com/248438
#if defined(OS_WIN)
#define MAYBE_DownloadExtensionTest_Download_Subdirectory\
DISABLED_DownloadExtensionTest_Download_Subdirectory
@@ -2043,19 +1979,10 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
download_url.c_str())).c_str());
}
-// flaky on mac: crbug.com/392288
-#if defined(OS_MACOSX)
-#define MAYBE_DownloadExtensionTest_Download_InvalidURLs \
- DISABLED_DownloadExtensionTest_Download_InvalidURLs
-#else
-#define MAYBE_DownloadExtensionTest_Download_InvalidURLs \
- DownloadExtensionTest_Download_InvalidURLs
-#endif
-
class DownloadExtensionTestWithFtp : public DownloadExtensionTest {
public:
DownloadExtensionTestWithFtp() {
- // DownloadExtensionTest_Download_InvalidURLs requires FTP support.
+ // DownloadExtensionTest_Download_InvalidURLs2 requires FTP support.
// TODO(https://crbug.com/333943): Remove FTP tests and FTP feature flags.
scoped_feature_list_.InitAndEnableFeature(features::kFtpProtocol);
}
@@ -2066,27 +1993,27 @@ class DownloadExtensionTestWithFtp : public DownloadExtensionTest {
// Test that downloading invalid URLs immediately returns kInvalidURLError.
IN_PROC_BROWSER_TEST_F(DownloadExtensionTestWithFtp,
- MAYBE_DownloadExtensionTest_Download_InvalidURLs) {
- LoadExtension("downloads_split");
- GoOnTheRecord();
-
- static const char* const kInvalidURLs[] = {
- "foo bar",
- "../hello",
- "/hello",
- "http://",
- "#frag",
- "foo/bar.html#frag",
- "google.com/",
+ DownloadExtensionTest_Download_InvalidURLs1) {
+ static constexpr const char* kInvalidURLs[] = {
+ "foo bar", "../hello", "/hello", "http://",
+ "#frag", "foo/bar.html#frag", "google.com/",
};
- for (size_t index = 0; index < base::size(kInvalidURLs); ++index) {
+ for (const char* url : kInvalidURLs) {
EXPECT_STREQ(errors::kInvalidURL,
- RunFunctionAndReturnError(new DownloadsDownloadFunction(),
- base::StringPrintf(
- "[{\"url\": \"%s\"}]", kInvalidURLs[index])).c_str())
- << kInvalidURLs[index];
+ RunFunctionAndReturnError(
+ new DownloadsDownloadFunction(),
+ base::StringPrintf("[{\"url\": \"%s\"}]", url))
+ .c_str())
+ << url;
}
+}
+
+// Test various failure modes for downloading invalid URLs.
+IN_PROC_BROWSER_TEST_F(DownloadExtensionTestWithFtp,
+ DownloadExtensionTest_Download_InvalidURLs2) {
+ LoadExtension("downloads_split");
+ GoOnTheRecord();
int result_id = -1;
std::unique_ptr<base::Value> result(RunFunctionAndReturnResult(
@@ -4255,8 +4182,11 @@ IN_PROC_BROWSER_TEST_F(
// resumed. http://crbug.com/225901
ui_test_utils::NavigateToURLWithDisposition(
current_browser(),
- GURL(net::URLRequestSlowDownloadJob::kUnknownSizeUrl),
- WindowOpenDisposition::CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE);
+ // This code used to use a mock class that no longer works, due to the
+ // NetworkService shipping.
+ // TODO(https://crbug.com/700382): Fix or delete this test.
+ GURL(), WindowOpenDisposition::CURRENT_TAB,
+ ui_test_utils::BROWSER_TEST_NONE);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS));
DownloadManager::DownloadVector items;
@@ -4293,8 +4223,10 @@ IN_PROC_BROWSER_TEST_F(
ClearEvents();
ui_test_utils::NavigateToURLWithDisposition(
current_browser(),
- GURL(net::URLRequestSlowDownloadJob::kErrorDownloadUrl),
- WindowOpenDisposition::NEW_BACKGROUND_TAB,
+ // This code used to use a mock class that no longer works, due to the
+ // NetworkService shipping.
+ // TODO(https://crbug.com/700382): Fix or delete this test.
+ GURL(), WindowOpenDisposition::NEW_BACKGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
// Errors caught before filename determination are delayed until after
@@ -4393,12 +4325,14 @@ void OnDangerPromptCreated(DownloadDangerPrompt* prompt) {
prompt->InvokeActionForTesting(DownloadDangerPrompt::ACCEPT);
}
-#if defined(OS_MACOSX)
-// Flakily triggers and assert on Mac.
+#if defined(OS_MACOSX) && !defined(NDEBUG)
+// Flaky on Mac debug, failing with a timeout.
// http://crbug.com/180759
-#define MAYBE_DownloadExtensionTest_AcceptDanger DISABLED_DownloadExtensionTest_AcceptDanger
+#define MAYBE_DownloadExtensionTest_AcceptDanger \
+ DISABLED_DownloadExtensionTest_AcceptDanger
#else
-#define MAYBE_DownloadExtensionTest_AcceptDanger DownloadExtensionTest_AcceptDanger
+#define MAYBE_DownloadExtensionTest_AcceptDanger \
+ DownloadExtensionTest_AcceptDanger
#endif
IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
MAYBE_DownloadExtensionTest_AcceptDanger) {
diff --git a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc
index d94b303a10b..1e25f6a94be 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc
@@ -26,14 +26,17 @@ namespace {
// Checks for the current browser context if the user is affiliated or belongs
// to the sign-in profile.
-bool IsPermittedToGetDeviceAttributes(content::BrowserContext* context) {
- if (chromeos::ProfileHelper::IsSigninProfile(
- Profile::FromBrowserContext(context))) {
+bool CanGetDeviceAttributesForBrowserContext(content::BrowserContext* context) {
+ const Profile* profile = Profile::FromBrowserContext(context);
+
+ if (chromeos::ProfileHelper::IsSigninProfile(profile))
return true;
- }
+
+ if (!profile->IsRegularProfile())
+ return false;
+
const user_manager::User* user =
- chromeos::ProfileHelper::Get()->GetUserByProfile(
- Profile::FromBrowserContext(context));
+ chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
return user->IsAffiliated();
}
@@ -48,7 +51,7 @@ EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction::
ExtensionFunction::ResponseAction
EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction::Run() {
std::string device_id;
- if (IsPermittedToGetDeviceAttributes(browser_context())) {
+ if (CanGetDeviceAttributesForBrowserContext(browser_context())) {
device_id = g_browser_process->platform_part()
->browser_policy_connector_chromeos()
->GetDirectoryApiID();
@@ -67,7 +70,7 @@ EnterpriseDeviceAttributesGetDeviceSerialNumberFunction::
ExtensionFunction::ResponseAction
EnterpriseDeviceAttributesGetDeviceSerialNumberFunction::Run() {
std::string serial_number;
- if (IsPermittedToGetDeviceAttributes(browser_context())) {
+ if (CanGetDeviceAttributesForBrowserContext(browser_context())) {
serial_number = chromeos::system::StatisticsProvider::GetInstance()
->GetEnterpriseMachineID();
}
@@ -85,7 +88,7 @@ EnterpriseDeviceAttributesGetDeviceAssetIdFunction::
ExtensionFunction::ResponseAction
EnterpriseDeviceAttributesGetDeviceAssetIdFunction::Run() {
std::string asset_id;
- if (IsPermittedToGetDeviceAttributes(browser_context())) {
+ if (CanGetDeviceAttributesForBrowserContext(browser_context())) {
asset_id = g_browser_process->platform_part()
->browser_policy_connector_chromeos()
->GetDeviceAssetID();
@@ -104,7 +107,7 @@ EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction::
ExtensionFunction::ResponseAction
EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction::Run() {
std::string annotated_location;
- if (IsPermittedToGetDeviceAttributes(browser_context())) {
+ if (CanGetDeviceAttributesForBrowserContext(browser_context())) {
annotated_location = g_browser_process->platform_part()
->browser_policy_connector_chromeos()
->GetDeviceAnnotatedLocation();
@@ -123,7 +126,7 @@ EnterpriseDeviceAttributesGetDeviceHostnameFunction::
ExtensionFunction::ResponseAction
EnterpriseDeviceAttributesGetDeviceHostnameFunction::Run() {
std::string hostname;
- if (IsPermittedToGetDeviceAttributes(browser_context())) {
+ if (CanGetDeviceAttributesForBrowserContext(browser_context())) {
hostname = g_browser_process->platform_part()
->browser_policy_connector_chromeos()
->GetHostnameHandler()
diff --git a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h
index 0974be24255..33d41d1169b 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h
+++ b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h
@@ -6,6 +6,7 @@
#define CHROME_BROWSER_EXTENSIONS_API_ENTERPRISE_DEVICE_ATTRIBUTES_ENTERPRISE_DEVICE_ATTRIBUTES_API_H_
#include "extensions/browser/extension_function.h"
+#include "extensions/browser/extension_function_histogram_value.h"
namespace extensions {
diff --git a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc
index 0309f441857..cfbdae447b1 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc
@@ -2,38 +2,21 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include <memory>
-
-#include "base/bind.h"
-#include "base/json/json_writer.h"
-#include "base/path_service.h"
-#include "base/task/post_task.h"
+#include "base/files/file_path.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/policy/affiliation_test_helper.h"
-#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
-#include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h"
+#include "chrome/browser/chromeos/policy/device_policy_builder.h"
+#include "chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.h"
#include "chrome/browser/extensions/extension_apitest.h"
-#include "chrome/browser/extensions/policy_test_utils.h"
-#include "chrome/common/chrome_paths.h"
-#include "chrome/test/base/ui_test_utils.h"
#include "chromeos/dbus/session_manager/fake_session_manager_client.h"
#include "chromeos/system/fake_statistics_provider.h"
#include "chromeos/system/statistics_provider.h"
-#include "chromeos/tpm/stub_install_attributes.h"
-#include "components/account_id/account_id.h"
-#include "components/policy/core/common/cloud/device_management_service.h"
-#include "components/policy/core/common/mock_configuration_policy_provider.h"
-#include "components/prefs/pref_service.h"
#include "components/user_manager/user_manager.h"
-#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/notification_service.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_utils.h"
-#include "extensions/browser/api_test_utils.h"
#include "extensions/browser/extension_registry.h"
-#include "extensions/test/result_catcher.h"
+#include "url/gurl.h"
namespace {
@@ -42,30 +25,10 @@ constexpr char kSerialNumber[] = "serial_number";
constexpr char kAssetId[] = "asset_id";
constexpr char kAnnotatedLocation[] = "annotated_location";
constexpr char kHostname[] = "hostname";
-constexpr char kUpdateManifestPath[] =
- "/extensions/api_test/enterprise_device_attributes/update_manifest.xml";
-constexpr char kAffiliatedUserEmail[] = "user@example.com";
-constexpr char kAffiliatedUserGaiaId[] = "1029384756";
-constexpr char kAffiliationID[] = "some-affiliation-id";
-constexpr char kAnotherAffiliationID[] = "another-affiliation-id";
-
-// The managed_storage extension has a key defined in its manifest, so that
-// its extension ID is well-known and the policy system can push policies for
-// the extension.
constexpr char kTestExtensionID[] = "nbiliclbejdndfpchgkbmfoppjplbdok";
-
-struct Params {
- explicit Params(bool affiliated) : affiliated(affiliated) {}
- bool affiliated;
-};
-
-// Must be a valid test name (no spaces etc.). Makes the test show up as e.g.
-// AffiliationCheck/U.A.B.T.Affiliated/NotAffiliated_NotActiveDirectory
-std::string PrintParam(testing::TestParamInfo<Params> param_info) {
- return base::StringPrintf("%sAffiliated",
- param_info.param.affiliated ? "" : "Not");
-}
+constexpr char kUpdateManifestPath[] =
+ "/extensions/api_test/enterprise_device_attributes/update_manifest.xml";
base::Value BuildCustomArg(const std::string& expected_directory_device_id,
const std::string& expected_serial_number,
@@ -89,49 +52,21 @@ base::Value BuildCustomArg(const std::string& expected_directory_device_id,
namespace extensions {
class EnterpriseDeviceAttributesTest
- : public ExtensionApiTest,
- public ::testing::WithParamInterface<Params> {
+ : public ForceInstalledAffiliatedExtensionApiTest,
+ public ::testing::WithParamInterface<bool> {
public:
- EnterpriseDeviceAttributesTest() {
+ EnterpriseDeviceAttributesTest()
+ : ForceInstalledAffiliatedExtensionApiTest(GetParam()) {
fake_statistics_provider_.SetMachineStatistic(
chromeos::system::kSerialNumberKeyForTest, kSerialNumber);
- set_exit_when_last_browser_closes(false);
- set_chromeos_user_ = false;
}
protected:
- // ExtensionApiTest
- void SetUpCommandLine(base::CommandLine* command_line) override {
- ExtensionApiTest::SetUpCommandLine(command_line);
- policy::AffiliationTestHelper::AppendCommandLineSwitchesForLoginManager(
- command_line);
- }
-
+ // ForceInstalledAffiliatedExtensionApiTest
void SetUpInProcessBrowserTestFixture() override {
- ExtensionApiTest::SetUpInProcessBrowserTestFixture();
-
- chromeos::SessionManagerClient::InitializeFakeInMemory();
- policy::AffiliationTestHelper affiliation_helper =
- policy::AffiliationTestHelper::CreateForCloud(
- chromeos::FakeSessionManagerClient::Get());
+ ForceInstalledAffiliatedExtensionApiTest::
+ SetUpInProcessBrowserTestFixture();
- std::set<std::string> device_affiliation_ids;
- device_affiliation_ids.insert(kAffiliationID);
- ASSERT_NO_FATAL_FAILURE(affiliation_helper.SetDeviceAffiliationIDs(
- &test_helper_, device_affiliation_ids));
- test_helper_.InstallOwnerKey();
-
- std::set<std::string> user_affiliation_ids;
- if (GetParam().affiliated) {
- user_affiliation_ids.insert(kAffiliationID);
- } else {
- user_affiliation_ids.insert(kAnotherAffiliationID);
- }
- policy::UserPolicyBuilder user_policy;
- ASSERT_NO_FATAL_FAILURE(affiliation_helper.SetUserAffiliationIDs(
- &user_policy, affiliated_account_id_, user_affiliation_ids));
-
- test_helper_.InstallOwnerKey();
// Init the device policy.
policy::DevicePolicyBuilder* device_policy = test_helper_.device_policy();
device_policy->SetDefaultSigningKey();
@@ -146,67 +81,9 @@ class EnterpriseDeviceAttributesTest
chromeos::FakeSessionManagerClient::Get()->set_device_policy(
device_policy->GetBlob());
chromeos::FakeSessionManagerClient::Get()->OnPropertyChangeComplete(true);
-
- // Init the user policy provider.
- EXPECT_CALL(policy_provider_, IsInitializationComplete(testing::_))
- .WillRepeatedly(testing::Return(true));
- policy_provider_.SetAutoRefresh();
- policy::BrowserPolicyConnector::SetPolicyProviderForTesting(
- &policy_provider_);
-
- // Set retry delay to prevent timeouts.
- policy::DeviceManagementService::SetRetryDelayForTesting(0);
}
- void SetUpOnMainThread() override {
- const base::ListValue* users =
- g_browser_process->local_state()->GetList("LoggedInUsers");
- if (!users->empty())
- policy::AffiliationTestHelper::LoginUser(affiliated_account_id_);
-
- ExtensionApiTest::SetUpOnMainThread();
- }
-
- // Load |page_url| in |browser| and wait for PASSED or FAILED notification.
- // The functionality of this function is reduced functionality of
- // RunExtensionSubtest(), but we don't use it here because it requires
- // function InProcessBrowserTest::browser() to return non-NULL pointer.
- // Unfortunately it returns the value which is set in constructor and can't be
- // modified. Because on login flow there is no browser, the function
- // InProcessBrowserTest::browser() always returns NULL. Besides this we need
- // only very little functionality from RunExtensionSubtest(). Thus so that
- // don't make RunExtensionSubtest() to complex we just introduce a new
- // function.
- bool TestExtension(Browser* browser,
- const std::string& page_url,
- const base::Value& custom_arg_value) {
- DCHECK(!page_url.empty()) << "page_url cannot be empty";
-
- std::string custom_arg;
- base::JSONWriter::Write(custom_arg_value, &custom_arg);
- SetCustomArg(custom_arg);
-
- extensions::ResultCatcher catcher;
- ui_test_utils::NavigateToURL(browser, GURL(page_url));
-
- if (!catcher.GetNextResult()) {
- message_ = catcher.message();
- return false;
- }
- return true;
- }
-
- const AccountId affiliated_account_id_ =
- AccountId::FromUserEmailGaiaId(kAffiliatedUserEmail,
- kAffiliatedUserGaiaId);
-
- policy::MockConfigurationPolicyProvider policy_provider_;
-
private:
- chromeos::ScopedStubInstallAttributes test_install_attributes_{
- chromeos::StubInstallAttributes::CreateCloudManaged("fake-domain",
- "fake-id")};
- policy::DevicePolicyCrosTestHelper test_helper_;
chromeos::system::ScopedFakeStatisticsProvider fake_statistics_provider_;
};
@@ -215,36 +92,33 @@ IN_PROC_BROWSER_TEST_P(EnterpriseDeviceAttributesTest, PRE_Success) {
}
IN_PROC_BROWSER_TEST_P(EnterpriseDeviceAttributesTest, Success) {
- policy_test_utils::SetUpEmbeddedTestServer(embedded_test_server());
- ASSERT_TRUE(embedded_test_server()->Start());
- policy_test_utils::SetExtensionInstallForcelistPolicy(
- kTestExtensionID, embedded_test_server()->GetURL(kUpdateManifestPath),
- profile(), &policy_provider_);
+ const bool is_affiliated = GetParam();
+ EXPECT_EQ(is_affiliated, user_manager::UserManager::Get()
+ ->FindUser(affiliated_account_id_)
+ ->IsAffiliated());
- EXPECT_EQ(GetParam().affiliated, user_manager::UserManager::Get()
- ->FindUser(affiliated_account_id_)
- ->IsAffiliated());
+ const Extension* extension =
+ ForceInstallExtension(kTestExtensionID, kUpdateManifestPath);
+ const GURL test_url = extension->GetResourceURL("basic.html");
// Device attributes are available only for affiliated user.
- std::string expected_directory_device_id =
- GetParam().affiliated ? kDeviceId : "";
- std::string expected_serial_number =
- GetParam().affiliated ? kSerialNumber : "";
- std::string expected_asset_id = GetParam().affiliated ? kAssetId : "";
+ std::string expected_directory_device_id = is_affiliated ? kDeviceId : "";
+ std::string expected_serial_number = is_affiliated ? kSerialNumber : "";
+ std::string expected_asset_id = is_affiliated ? kAssetId : "";
std::string expected_annotated_location =
- GetParam().affiliated ? kAnnotatedLocation : "";
- std::string expected_hostname = GetParam().affiliated ? kHostname : "";
-
- // Pass the expected value (device_id) to test.
- ASSERT_TRUE(TestExtension(
- CreateBrowser(profile()),
- base::StringPrintf("chrome-extension://%s/basic.html", kTestExtensionID),
- BuildCustomArg(expected_directory_device_id, expected_serial_number,
- expected_asset_id, expected_annotated_location,
- expected_hostname)))
- << message_;
+ is_affiliated ? kAnnotatedLocation : "";
+ std::string expected_hostname = is_affiliated ? kHostname : "";
+ TestExtension(CreateBrowser(profile()), test_url,
+ BuildCustomArg(expected_directory_device_id,
+ expected_serial_number, expected_asset_id,
+ expected_annotated_location, expected_hostname));
}
+// Both cases of affiliated and non-affiliated users are tested.
+INSTANTIATE_TEST_SUITE_P(AffiliationCheck,
+ EnterpriseDeviceAttributesTest,
+ ::testing::Bool());
+
// Ensure that extensions that are not pre-installed by policy throw an install
// warning if they request the enterprise.deviceAttributes permission in the
// manifest and that such extensions don't see the
@@ -258,10 +132,10 @@ IN_PROC_BROWSER_TEST_F(
base::FilePath extension_path =
test_data_dir_.AppendASCII("enterprise_device_attributes");
- extensions::ExtensionRegistry* registry =
- extensions::ExtensionRegistry::Get(profile());
const extensions::Extension* extension =
- GetExtensionByPath(registry->enabled_extensions(), extension_path);
+ extensions::ExtensionRegistry::Get(profile())
+ ->enabled_extensions()
+ .GetByID(kTestExtensionID);
ASSERT_FALSE(extension->install_warnings().empty());
EXPECT_EQ(
"'enterprise.deviceAttributes' is not allowed for specified install "
@@ -269,10 +143,4 @@ IN_PROC_BROWSER_TEST_F(
extension->install_warnings()[0].message);
}
-// Both cases of affiliated and non-affiliated on the device user are tested.
-INSTANTIATE_TEST_SUITE_P(AffiliationCheck,
- EnterpriseDeviceAttributesTest,
- ::testing::Values(Params(true /* affiliated */),
- Params(false /* affiliated */)),
- PrintParam);
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/OWNERS b/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/OWNERS
new file mode 100644
index 00000000000..d11193dcf55
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/OWNERS
@@ -0,0 +1,3 @@
+hendrich@chromium.org
+
+# COMPONENT: Enterprise
diff --git a/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_api.cc b/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_api.cc
new file mode 100644
index 00000000000..981d40da62b
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_api.cc
@@ -0,0 +1,90 @@
+// Copyright 2020 The Chromium 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/enterprise_networking_attributes/enterprise_networking_attributes_api.h"
+
+#include "base/values.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/common/extensions/api/enterprise_networking_attributes.h"
+#include "chromeos/network/device_state.h"
+#include "chromeos/network/network_handler.h"
+#include "chromeos/network/network_state.h"
+#include "chromeos/network/network_state_handler.h"
+#include "chromeos/network/network_util.h"
+#include "components/user_manager/user.h"
+#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"
+
+namespace extensions {
+
+namespace {
+
+const char kErrorUserNotAffiliated[] =
+ "Network attributes can only be read by an affiliated user.";
+const char kErrorNetworkNotConnected[] =
+ "Device is not connected to a network.";
+
+// Checks for the current browser context if the user is affiliated or belongs
+// to the sign-in profile.
+bool CanGetNetworkAttributesForBrowserContext(
+ content::BrowserContext* context) {
+ const Profile* profile = Profile::FromBrowserContext(context);
+
+ if (chromeos::ProfileHelper::IsSigninProfile(profile))
+ return true;
+
+ if (!profile->IsRegularProfile())
+ return false;
+
+ const user_manager::User* user =
+ chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
+ return user->IsAffiliated();
+}
+
+} // namespace
+
+EnterpriseNetworkingAttributesGetNetworkDetailsFunction::
+ EnterpriseNetworkingAttributesGetNetworkDetailsFunction() = default;
+
+EnterpriseNetworkingAttributesGetNetworkDetailsFunction::
+ ~EnterpriseNetworkingAttributesGetNetworkDetailsFunction() = default;
+
+ExtensionFunction::ResponseAction
+EnterpriseNetworkingAttributesGetNetworkDetailsFunction::Run() {
+ if (!CanGetNetworkAttributesForBrowserContext(browser_context())) {
+ return RespondNow(Error(kErrorUserNotAffiliated));
+ }
+
+ chromeos::NetworkStateHandler* network_state_handler =
+ chromeos::NetworkHandler::Get()->network_state_handler();
+ const chromeos::NetworkState* network =
+ network_state_handler->DefaultNetwork();
+ if (!network) {
+ // Not connected to a network.
+ return RespondNow(Error(kErrorNetworkNotConnected));
+ }
+ const chromeos::DeviceState* device =
+ network_state_handler->GetDeviceState(network->device_path());
+ if (!device) {
+ return RespondNow(Error(kErrorNetworkNotConnected));
+ }
+
+ const std::string mac_address =
+ chromeos::network_util::FormattedMacAddress(device->mac_address());
+ const std::string ipv4_address = device->GetIpAddressByType(shill::kTypeIPv4);
+ const std::string ipv6_address = device->GetIpAddressByType(shill::kTypeIPv6);
+
+ api::enterprise_networking_attributes::NetworkDetails details;
+ details.mac_address = mac_address;
+ if (!ipv4_address.empty()) {
+ details.ipv4 = std::make_unique<std::string>(ipv4_address);
+ }
+ if (!ipv6_address.empty()) {
+ details.ipv6 = std::make_unique<std::string>(ipv6_address);
+ }
+
+ return RespondNow(OneArgument(details.ToValue()));
+}
+
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_api.h b/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_api.h
new file mode 100644
index 00000000000..85f23e82822
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_api.h
@@ -0,0 +1,30 @@
+// Copyright 2020 The Chromium 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_ENTERPRISE_NETWORKING_ATTRIBUTES_ENTERPRISE_NETWORKING_ATTRIBUTES_API_H_
+#define CHROME_BROWSER_EXTENSIONS_API_ENTERPRISE_NETWORKING_ATTRIBUTES_ENTERPRISE_NETWORKING_ATTRIBUTES_API_H_
+
+#include "extensions/browser/extension_function.h"
+#include "extensions/browser/extension_function_histogram_value.h"
+
+namespace extensions {
+
+class EnterpriseNetworkingAttributesGetNetworkDetailsFunction
+ : public ExtensionFunction {
+ public:
+ EnterpriseNetworkingAttributesGetNetworkDetailsFunction();
+
+ protected:
+ ~EnterpriseNetworkingAttributesGetNetworkDetailsFunction() override;
+
+ ResponseAction Run() override;
+
+ private:
+ DECLARE_EXTENSION_FUNCTION(
+ "enterprise.networkingAttributes.getNetworkDetails",
+ ENTERPRISE_NETWORKINGATTRIBUTES_GETNETWORKDETAILS)
+};
+
+} // namespace extensions
+#endif // CHROME_BROWSER_EXTENSIONS_API_ENTERPRISE_NETWORKING_ATTRIBUTES_ENTERPRISE_NETWORKING_ATTRIBUTES_API_H_
diff --git a/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_apitest.cc b/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_apitest.cc
new file mode 100644
index 00000000000..a3c7706efdc
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_apitest.cc
@@ -0,0 +1,210 @@
+// Copyright 2020 The Chromium 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 <memory>
+#include <string>
+
+#include "base/values.h"
+#include "chrome/browser/chromeos/policy/affiliation_test_helper.h"
+#include "chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.h"
+#include "chrome/browser/extensions/extension_apitest.h"
+#include "chromeos/dbus/shill/shill_device_client.h"
+#include "chromeos/dbus/shill/shill_ipconfig_client.h"
+#include "chromeos/dbus/shill/shill_profile_client.h"
+#include "chromeos/dbus/shill/shill_service_client.h"
+#include "content/public/test/browser_test.h"
+#include "url/gurl.h"
+
+namespace {
+
+const char kErrorUserNotAffiliated[] =
+ "Network attributes can only be read by an affiliated user.";
+const char kErrorNetworkNotConnected[] =
+ "Device is not connected to a network.";
+
+constexpr char kTestExtensionID[] = "pkhdjpcjgonhlomdjmnddhbfpgkdhgle";
+constexpr char kUpdateManifestPath[] =
+ "/extensions/api_test/enterprise_networking_attributes/update_manifest.xml";
+
+constexpr char kMacAddress[] = "0123456789AB";
+constexpr char kFormattedMacAddress[] = "01:23:45:67:89:AB";
+constexpr char kIpv4Address[] = "192.168.0.42";
+constexpr char kIpv6Address[] = "fe80::1262:d0ff:fef5:e8a9";
+
+constexpr char kWifiDevicePath[] = "/device/stub_wifi";
+constexpr char kWifiServicePath[] = "/service/stub_wifi";
+constexpr char kWifiIPConfigV4Path[] = "/ipconfig/stub_wifi-ipv4";
+constexpr char kWifiIPConfigV6Path[] = "/ipconfig/stub_wifi-ipv6";
+
+base::Value BuildCustomArgForSuccess(const std::string& expected_mac_address,
+ const std::string& expected_ipv4_address,
+ const std::string& expected_ipv6_address) {
+ base::Value network_details(base::Value::Type::DICTIONARY);
+ network_details.SetKey("macAddress", base::Value(expected_mac_address));
+ network_details.SetKey("ipv4", base::Value(expected_ipv4_address));
+ network_details.SetKey("ipv6", base::Value(expected_ipv6_address));
+
+ base::Value custom_arg(base::Value::Type::DICTIONARY);
+ custom_arg.SetKey("testName", base::Value("success"));
+ custom_arg.SetKey("expectedResult", std::move(network_details));
+ return custom_arg;
+}
+
+base::Value BuildCustomArgForFailure(
+ const std::string& expected_error_message) {
+ base::Value custom_arg(base::Value::Type::DICTIONARY);
+ custom_arg.SetKey("testName", base::Value("failure"));
+ custom_arg.SetKey("expectedErrorMessage",
+ base::Value(expected_error_message));
+ return custom_arg;
+}
+
+} // namespace
+
+namespace extensions {
+
+class EnterpriseNetworkingAttributesTest
+ : public ForceInstalledAffiliatedExtensionApiTest,
+ public ::testing::WithParamInterface<bool> {
+ public:
+ EnterpriseNetworkingAttributesTest()
+ : ForceInstalledAffiliatedExtensionApiTest(GetParam()) {}
+
+ void SetupDisconnectedNetwork() {
+ chromeos::ShillDeviceClient::TestInterface* shill_device_client =
+ chromeos::DBusThreadManager::Get()
+ ->GetShillDeviceClient()
+ ->GetTestInterface();
+ chromeos::ShillIPConfigClient::TestInterface* shill_ipconfig_client =
+ chromeos::DBusThreadManager::Get()
+ ->GetShillIPConfigClient()
+ ->GetTestInterface();
+ chromeos::ShillServiceClient::TestInterface* shill_service_client =
+ chromeos::DBusThreadManager::Get()
+ ->GetShillServiceClient()
+ ->GetTestInterface();
+ chromeos::ShillProfileClient::TestInterface* shill_profile_client =
+ chromeos::DBusThreadManager::Get()
+ ->GetShillProfileClient()
+ ->GetTestInterface();
+
+ shill_service_client->ClearServices();
+ shill_device_client->ClearDevices();
+
+ shill_device_client->AddDevice(kWifiDevicePath, shill::kTypeWifi,
+ "stub_wifi_device");
+ shill_device_client->SetDeviceProperty(
+ kWifiDevicePath, shill::kAddressProperty, base::Value(kMacAddress),
+ /* notify_changed= */ false);
+
+ base::DictionaryValue ipconfig_v4_dictionary;
+ ipconfig_v4_dictionary.SetKey(shill::kAddressProperty,
+ base::Value(kIpv4Address));
+ ipconfig_v4_dictionary.SetKey(shill::kMethodProperty,
+ base::Value(shill::kTypeIPv4));
+ shill_ipconfig_client->AddIPConfig(kWifiIPConfigV4Path,
+ ipconfig_v4_dictionary);
+
+ base::DictionaryValue ipconfig_v6_dictionary;
+ ipconfig_v6_dictionary.SetKey(shill::kAddressProperty,
+ base::Value(kIpv6Address));
+ ipconfig_v6_dictionary.SetKey(shill::kMethodProperty,
+ base::Value(shill::kTypeIPv6));
+ shill_ipconfig_client->AddIPConfig(kWifiIPConfigV6Path,
+ ipconfig_v6_dictionary);
+
+ base::ListValue ip_configs;
+ ip_configs.AppendString(kWifiIPConfigV4Path);
+ ip_configs.AppendString(kWifiIPConfigV6Path);
+ shill_device_client->SetDeviceProperty(
+ kWifiDevicePath, shill::kIPConfigsProperty, ip_configs,
+ /*notify_changed=*/false);
+
+ shill_service_client->AddService(kWifiServicePath, "wifi_guid",
+ "wifi_network_name", shill::kTypeWifi,
+ shill::kStateIdle, /* visible= */ true);
+ shill_service_client->SetServiceProperty(
+ kWifiServicePath, shill::kConnectableProperty, base::Value(true));
+
+ shill_profile_client->AddService(
+ chromeos::ShillProfileClient::GetSharedProfilePath(), kWifiServicePath);
+
+ base::RunLoop().RunUntilIdle();
+ }
+
+ void ConnectNetwork() {
+ chromeos::ShillServiceClient::TestInterface* shill_service_client =
+ chromeos::DBusThreadManager::Get()
+ ->GetShillServiceClient()
+ ->GetTestInterface();
+ shill_service_client->SetServiceProperty(kWifiServicePath,
+ shill::kStateProperty,
+ base::Value(shill::kStateOnline));
+ base::RunLoop().RunUntilIdle();
+ }
+};
+
+IN_PROC_BROWSER_TEST_P(EnterpriseNetworkingAttributesTest,
+ PRE_GetNetworkDetails) {
+ policy::AffiliationTestHelper::PreLoginUser(affiliated_account_id_);
+}
+
+IN_PROC_BROWSER_TEST_P(EnterpriseNetworkingAttributesTest, GetNetworkDetails) {
+ const bool is_affiliated = GetParam();
+ EXPECT_EQ(is_affiliated, user_manager::UserManager::Get()
+ ->FindUser(affiliated_account_id_)
+ ->IsAffiliated());
+
+ const Extension* extension =
+ ForceInstallExtension(kTestExtensionID, kUpdateManifestPath);
+ SetupDisconnectedNetwork();
+ const GURL test_url = extension->GetResourceURL("test.html");
+
+ // Run test without connected network.
+ base::Value custom_arg_disconnected =
+ is_affiliated ? BuildCustomArgForFailure(kErrorNetworkNotConnected)
+ : BuildCustomArgForFailure(kErrorUserNotAffiliated);
+ TestExtension(CreateBrowser(profile()), test_url,
+ std::move(custom_arg_disconnected));
+
+ // Run test with connected network.
+ ConnectNetwork();
+ base::Value custom_arg_connected =
+ is_affiliated ? BuildCustomArgForSuccess(kFormattedMacAddress,
+ kIpv4Address, kIpv6Address)
+ : BuildCustomArgForFailure(kErrorUserNotAffiliated);
+ TestExtension(CreateBrowser(profile()), test_url,
+ std::move(custom_arg_connected));
+}
+
+// Both cases of affiliated and non-affiliated users are tested.
+INSTANTIATE_TEST_SUITE_P(AffiliationCheck,
+ EnterpriseNetworkingAttributesTest,
+ ::testing::Bool());
+
+// Ensure that extensions that are not pre-installed by policy throw an install
+// warning if they request the enterprise.networkingAttributes permission in the
+// manifest and that such extensions don't see the
+// chrome.enterprise.networkingAttributes namespace.
+IN_PROC_BROWSER_TEST_F(
+ ExtensionApiTest,
+ EnterpriseNetworkingAttributesIsRestrictedToPolicyExtension) {
+ ASSERT_TRUE(RunExtensionSubtest("enterprise_networking_attributes",
+ "api_not_available.html",
+ kFlagIgnoreManifestWarnings, kFlagNone));
+
+ base::FilePath extension_path =
+ test_data_dir_.AppendASCII("enterprise_networking_attributes");
+ const extensions::Extension* extension =
+ extensions::ExtensionRegistry::Get(profile())
+ ->enabled_extensions()
+ .GetByID(kTestExtensionID);
+ ASSERT_FALSE(extension->install_warnings().empty());
+ EXPECT_EQ(
+ "'enterprise.networkingAttributes' is not allowed for specified install "
+ "location.",
+ extension->install_warnings()[0].message);
+}
+
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc
index f3a5cfa7d60..26dbef23d59 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/bind.h"
-#include "base/task/post_task.h"
#include "base/values.h"
#include "chrome/browser/chromeos/platform_keys/extension_platform_keys_service.h"
#include "chrome/browser/chromeos/platform_keys/extension_platform_keys_service_factory.h"
@@ -300,7 +299,7 @@ EnterprisePlatformKeysChallengeMachineKeyFunction::Run() {
chromeos::attestation::KEY_DEVICE, scoped_refptr<ExtensionFunction>(this),
std::move(callback), StringFromVector(params->challenge),
params->register_key ? *params->register_key : false);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI}, std::move(task));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(task));
return RespondLater();
}
@@ -334,7 +333,7 @@ EnterprisePlatformKeysChallengeUserKeyFunction::Run() {
chromeos::attestation::KEY_USER, scoped_refptr<ExtensionFunction>(this),
std::move(callback), StringFromVector(params->challenge),
params->register_key);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI}, std::move(task));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(task));
return RespondLater();
}
diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc
index 3f946e23d57..4cdb396d069 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc
@@ -25,6 +25,7 @@
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "crypto/nss_util_internal.h"
+#include "crypto/scoped_nss_types.h"
#include "crypto/scoped_test_system_nss_key_slot.h"
#include "extensions/browser/extension_registry.h"
#include "net/cert/nss_cert_database.h"
@@ -117,17 +118,17 @@ void ImportPrivateKeyPKCS8ToSlot(const unsigned char* pkcs8_der,
const_cast<unsigned char*>(pkcs8_der),
pkcs8_der_size};
- SECKEYPrivateKey* seckey = NULL;
- ASSERT_EQ(SECSuccess,
- PK11_ImportDERPrivateKeyInfoAndReturnKey(slot,
- &pki_der_user,
- NULL, // nickname
- NULL, // publicValue
- true, // isPerm
- true, // isPrivate
- KU_ALL, // usage
- &seckey,
- NULL));
+ SECKEYPrivateKey* seckey_raw = nullptr;
+ ASSERT_EQ(SECSuccess, PK11_ImportDERPrivateKeyInfoAndReturnKey(
+ slot, &pki_der_user,
+ /*nickname=*/nullptr,
+ /*publicValue=*/nullptr,
+ /*isPerm=*/true,
+ /*isPrivate=*/true,
+ /*usage=*/KU_ALL, &seckey_raw, /*wincx=*/nullptr));
+
+ // Make sure that the memory allocated for the key gets freed.
+ crypto::ScopedSECKEYPrivateKey seckey(seckey_raw);
}
// The managed_storage extension has a key defined in its manifest, so that
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 275d148f325..6051e3a45ea 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
@@ -6,7 +6,6 @@
#include "base/base64.h"
#include "base/bind.h"
-#include "base/task/post_task.h"
#include "base/values.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/extensions/chrome_extension_function_details.h"
@@ -116,7 +115,7 @@ EnterprisePlatformKeysPrivateChallengeMachineKeyFunction::Run() {
chromeos::attestation::KEY_DEVICE, scoped_refptr<ExtensionFunction>(this),
std::move(callback), challenge,
/*register_key=*/false);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI}, std::move(task));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(task));
return RespondLater();
}
@@ -161,7 +160,7 @@ EnterprisePlatformKeysPrivateChallengeUserKeyFunction::Run() {
&EPKPChallengeKey::Run, base::Unretained(&impl_),
chromeos::attestation::KEY_USER, scoped_refptr<ExtensionFunction>(this),
std::move(callback), challenge, params->register_key);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI}, std::move(task));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(task));
return RespondLater();
}
diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc
index 36d3139b284..caa30811789 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc
@@ -242,87 +242,91 @@ const wchar_t kDefaultRegistryPath[] =
L"SOFTWARE\\Google\\Endpoint Verification";
const wchar_t kValueName[] = L"Safe Storage";
-std::string ReadEncryptedSecret() {
+LONG ReadEncryptedSecret(std::string* encrypted_secret) {
base::win::RegKey key;
DWORD kMaxRawSize = 1024;
char raw_data[kMaxRawSize];
DWORD raw_data_size = kMaxRawSize;
DWORD raw_type;
- if (ERROR_SUCCESS !=
- key.Open(HKEY_CURRENT_USER, kDefaultRegistryPath, KEY_READ) ||
- ERROR_SUCCESS !=
- key.ReadValue(kValueName, raw_data, &raw_data_size, &raw_type) ||
- raw_type != REG_BINARY) {
- return std::string();
+ encrypted_secret->clear();
+ LONG result = key.Open(HKEY_CURRENT_USER, kDefaultRegistryPath, KEY_READ);
+ if (result != ERROR_SUCCESS)
+ return result;
+ result = key.ReadValue(kValueName, raw_data, &raw_data_size, &raw_type);
+ if (result != ERROR_SUCCESS)
+ return result;
+ if (raw_type != REG_BINARY) {
+ key.DeleteValue(kValueName);
+ return ERROR_INVALID_DATATYPE;
}
- std::string encrypted_secret;
- encrypted_secret.insert(0, raw_data, raw_data_size);
- return encrypted_secret;
+ encrypted_secret->insert(0, raw_data, raw_data_size);
+ return ERROR_SUCCESS;
}
// Encrypts the |plaintext| and write the result in |cyphertext|. This
// function was taken from os_crypt/os_crypt_win.cc (Chromium).
-bool EncryptString(const std::string& plaintext, std::string* ciphertext) {
+LONG EncryptString(const std::string& plaintext, std::string* ciphertext) {
DATA_BLOB input;
input.pbData =
const_cast<BYTE*>(reinterpret_cast<const BYTE*>(plaintext.data()));
input.cbData = static_cast<DWORD>(plaintext.length());
+ ciphertext->clear();
DATA_BLOB output;
BOOL result = ::CryptProtectData(&input, nullptr, nullptr, nullptr, nullptr,
0, &output);
if (!result)
- return false;
+ return ::GetLastError();
// this does a copy
ciphertext->assign(reinterpret_cast<std::string::value_type*>(output.pbData),
output.cbData);
LocalFree(output.pbData);
- return true;
+ return ERROR_SUCCESS;
}
// Decrypts the |cyphertext| and write the result in |plaintext|. This
// function was taken from os_crypt/os_crypt_win.cc (Chromium).
-bool DecryptString(const std::string& ciphertext, std::string* plaintext) {
+LONG DecryptString(const std::string& ciphertext, std::string* plaintext) {
DATA_BLOB input;
input.pbData =
const_cast<BYTE*>(reinterpret_cast<const BYTE*>(ciphertext.data()));
input.cbData = static_cast<DWORD>(ciphertext.length());
+ plaintext->clear();
DATA_BLOB output;
BOOL result =
::CryptUnprotectData(&input, nullptr, nullptr, nullptr, nullptr, 0,
&output);
if (!result)
- return false;
+ return ::GetLastError();
plaintext->assign(reinterpret_cast<char*>(output.pbData), output.cbData);
LocalFree(output.pbData);
- return true;
+ return ERROR_SUCCESS;
}
-std::string CreateRandomSecret() {
+LONG CreateRandomSecret(std::string* secret) {
// Generate a password with 128 bits of randomness.
const int kBytes = 128 / 8;
- std::string secret;
- base::Base64Encode(base::RandBytesAsString(kBytes), &secret);
+ std::string generated_secret;
+ base::Base64Encode(base::RandBytesAsString(kBytes), &generated_secret);
std::string encrypted_secret;
- if (!EncryptString(secret, &encrypted_secret)) {
- return std::string();
- }
+ LONG result = EncryptString(generated_secret, &encrypted_secret);
+ if (result != ERROR_SUCCESS)
+ return result;
base::win::RegKey key;
- if (ERROR_SUCCESS !=
- key.Create(HKEY_CURRENT_USER, kDefaultRegistryPath, KEY_WRITE)) {
- return std::string();
- }
- if (ERROR_SUCCESS != key.WriteValue(kValueName, encrypted_secret.data(),
- encrypted_secret.size(), REG_BINARY)) {
- return std::string();
- }
- return secret;
+ result = key.Create(HKEY_CURRENT_USER, kDefaultRegistryPath, KEY_WRITE);
+ if (result != ERROR_SUCCESS)
+ return result;
+ result = key.WriteValue(kValueName, encrypted_secret.data(),
+ encrypted_secret.size(), REG_BINARY);
+ if (result == ERROR_SUCCESS)
+ *secret = generated_secret;
+ return result;
}
#elif defined(OS_MACOSX) // defined(OS_WIN)
@@ -330,7 +334,8 @@ std::string CreateRandomSecret() {
constexpr char kServiceName[] = "Endpoint Verification Safe Storage";
constexpr char kAccountName[] = "Endpoint Verification";
-std::string AddRandomPasswordToKeychain(const crypto::AppleKeychain& keychain) {
+OSStatus AddRandomPasswordToKeychain(const crypto::AppleKeychain& keychain,
+ std::string* secret) {
// Generate a password with 128 bits of randomness.
const int kBytes = 128 / 8;
std::string password;
@@ -342,32 +347,29 @@ std::string AddRandomPasswordToKeychain(const crypto::AppleKeychain& keychain) {
strlen(kServiceName), kServiceName, strlen(kAccountName), kAccountName,
password.size(), password_data, nullptr);
- if (error != noErr)
- return std::string();
- return password;
+ if (error == noErr)
+ *secret = password;
+ else
+ secret->clear();
+ return error;
}
-std::string ReadEncryptedSecret() {
+OSStatus ReadEncryptedSecret(std::string* secret) {
UInt32 password_length = 0;
void* password_data = nullptr;
crypto::AppleKeychain keychain;
+ secret->clear();
OSStatus error = keychain.FindGenericPassword(
strlen(kServiceName), kServiceName, strlen(kAccountName), kAccountName,
&password_length, &password_data, nullptr);
if (error == noErr) {
- std::string password =
- std::string(static_cast<char*>(password_data), password_length);
+ *secret = std::string(static_cast<char*>(password_data), password_length);
keychain.ItemFreeContent(password_data);
- return password;
+ } else if (error == errSecItemNotFound) {
+ error = AddRandomPasswordToKeychain(keychain, secret);
}
-
- if (error == errSecItemNotFound) {
- std::string password = AddRandomPasswordToKeychain(keychain);
- return password;
- }
-
- return std::string();
+ return error;
}
#endif // defined(OS_MACOSX)
@@ -483,9 +485,9 @@ void StoreDeviceData(const std::string& id,
success = base::Move(tmp_path, data_file);
} else {
// Not passing a second parameter means clear the data sored under |id|.
- success = base::DeleteFile(data_file, false);
+ success = base::DeleteFile(data_file);
if (base::IsDirectoryEmpty(data_file.DirName()))
- base::DeleteFile(data_file.DirName(), false);
+ base::DeleteFile(data_file.DirName());
}
std::move(callback).Run(success);
@@ -493,17 +495,19 @@ void StoreDeviceData(const std::string& id,
void RetrieveDeviceData(
const std::string& id,
- base::OnceCallback<void(const std::string&, bool)> callback) {
+ base::OnceCallback<void(const std::string&, RetrieveDeviceDataStatus)>
+ callback) {
base::FilePath data_file = GetEndpointVerificationDir();
if (data_file.empty()) {
- std::move(callback).Run("", false);
+ std::move(callback).Run("",
+ RetrieveDeviceDataStatus::kDataDirectoryUnknown);
return;
}
data_file = data_file.AppendASCII(id);
// If the file does not exist don't treat this as an error rather return an
// empty string.
if (!base::PathExists(data_file)) {
- std::move(callback).Run("", true);
+ std::move(callback).Run("", RetrieveDeviceDataStatus::kDataRecordNotFound);
return;
}
std::string data;
@@ -512,32 +516,27 @@ void RetrieveDeviceData(
// Chrome.
bool result = base::ReadFileToString(data_file, &data);
- std::move(callback).Run(data, result);
+ std::move(callback).Run(
+ data, result ? RetrieveDeviceDataStatus::kSuccess
+ : RetrieveDeviceDataStatus::kDataRecordRetrievalError);
}
void RetrieveDeviceSecret(
- base::OnceCallback<void(const std::string&, bool)> callback) {
+ base::OnceCallback<void(const std::string&, long int)> callback) {
std::string secret;
#if defined(OS_WIN)
- std::string encrypted_secret = ReadEncryptedSecret();
- if (encrypted_secret.empty()) {
- secret = CreateRandomSecret();
- std::move(callback).Run(secret, !secret.empty());
- return;
- }
- if (!DecryptString(encrypted_secret, &secret)) {
- std::move(callback).Run("", false);
- return;
- }
+ std::string encrypted_secret;
+ LONG result = ReadEncryptedSecret(&encrypted_secret);
+ if (result == ERROR_FILE_NOT_FOUND)
+ result = CreateRandomSecret(&secret);
+ else if (result == ERROR_SUCCESS)
+ result = DecryptString(encrypted_secret, &secret);
#elif defined(OS_MACOSX)
- secret = ReadEncryptedSecret();
- if (secret.empty()) {
- std::move(callback).Run(secret, false);
- return;
- }
-
+ OSStatus result = ReadEncryptedSecret(&secret);
+#else
+ long int result = -1; // Anything but 0 is a failure.
#endif
- std::move(callback).Run(secret, true);
+ std::move(callback).Run(secret, static_cast<long int>(result));
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h
index fd6d229ea24..764db67ed36 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h
+++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h
@@ -21,6 +21,18 @@ class DictionaryValue;
namespace extensions {
+// Result of the retrieve operation
+enum class RetrieveDeviceDataStatus {
+ // The operation finished successfully.
+ kSuccess,
+ // The path for device data can not be identified.
+ kDataDirectoryUnknown,
+ // The requested device data record does not exist.
+ kDataRecordNotFound,
+ // The requested device data record can not be read.
+ kDataRecordRetrievalError,
+};
+
// Transfer the input from Json file to protobuf. Return nullptr if the input
// is not valid.
std::unique_ptr<enterprise_management::ChromeDesktopReportRequest>
@@ -40,7 +52,8 @@ void StoreDeviceData(const std::string& id,
// completion with the data retrieved if the second parameter is true.
void RetrieveDeviceData(
const std::string& id,
- base::OnceCallback<void(const std::string&, bool)> callback);
+ base::OnceCallback<void(const std::string&, RetrieveDeviceDataStatus)>
+ callback);
// Get the Endpoint Verification secret (symmetric key) for this system. If no
// password exists in the Registry then one is generated, stored in the
@@ -48,7 +61,7 @@ void RetrieveDeviceData(
// If one exists then it is fetched from the Registry and returned.
// If an error occurs then the second parameter is false.
void RetrieveDeviceSecret(
- base::OnceCallback<void(const std::string&, bool)> callback);
+ base::OnceCallback<void(const std::string&, long int)> callback);
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc
index 5ec66328e92..4594ebe731a 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc
@@ -16,7 +16,6 @@
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h"
#include "chrome/browser/extensions/api/enterprise_reporting_private/device_info_fetcher.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/policy/browser_dm_token_storage.h"
@@ -35,6 +34,10 @@ namespace {
void LogReportError(const std::string& reason) {
VLOG(1) << "Enterprise report is not uploaded: " << reason;
}
+void LogReportErrorCode(const std::string& reason, long int code) {
+ VLOG(1) << "Enterprise report is not uploaded: " << reason
+ << " code: " << code;
+}
} // namespace
@@ -48,8 +51,7 @@ const char kEndpointVerificationRetrievalFailed[] =
"Failed to retrieve the endpoint verification data.";
const char kEndpointVerificationStoreFailed[] =
"Failed to store the endpoint verification data.";
-// const char kEndpointVerificationSecretRetrievalFailed[] = "Failed to retrieve
-// the endpoint verification secret.";
+const char kEndpointVerificationSecretRetrievalFailed[] = "%ld";
} // namespace enterprise_reporting
@@ -193,15 +195,17 @@ EnterpriseReportingPrivateGetPersistentSecretFunction::Run() {
void EnterpriseReportingPrivateGetPersistentSecretFunction::OnDataRetrieved(
const std::string& data,
- bool status) {
- if (status) {
+ long int status) {
+ if (status == 0) { // Success.
VLOG(1) << "The Endpoint Verification secret was retrieved.";
Respond(OneArgument(std::make_unique<base::Value>(base::Value::BlobStorage(
reinterpret_cast<const uint8_t*>(data.data()),
reinterpret_cast<const uint8_t*>(data.data() + data.size())))));
} else {
- LogReportError("Endpoint Verification secret retrieval error.");
- Respond(Error(enterprise_reporting::kEndpointVerificationRetrievalFailed));
+ LogReportErrorCode("Endpoint Verification secret retrieval error.", status);
+ Respond(Error(base::StringPrintf(
+ enterprise_reporting::kEndpointVerificationSecretRetrievalFailed,
+ static_cast<long int>(status))));
}
}
@@ -231,15 +235,24 @@ EnterpriseReportingPrivateGetDeviceDataFunction::Run() {
void EnterpriseReportingPrivateGetDeviceDataFunction::OnDataRetrieved(
const std::string& data,
- bool status) {
- if (status) {
- VLOG(1) << "The Endpoint Verification data was retrieved.";
- Respond(OneArgument(std::make_unique<base::Value>(base::Value::BlobStorage(
- reinterpret_cast<const uint8_t*>(data.data()),
- reinterpret_cast<const uint8_t*>(data.data() + data.size())))));
- } else {
- LogReportError("Endpoint Verification data retrieval error.");
- Respond(Error(enterprise_reporting::kEndpointVerificationRetrievalFailed));
+ RetrieveDeviceDataStatus status) {
+ switch (status) {
+ case RetrieveDeviceDataStatus::kSuccess:
+ VLOG(1) << "The Endpoint Verification data was retrieved.";
+ Respond(
+ OneArgument(std::make_unique<base::Value>(base::Value::BlobStorage(
+ reinterpret_cast<const uint8_t*>(data.data()),
+ reinterpret_cast<const uint8_t*>(data.data() + data.size())))));
+ return;
+ case RetrieveDeviceDataStatus::kDataRecordNotFound:
+ VLOG(1) << "The Endpoint Verification data is not present.";
+ Respond(NoArguments());
+ return;
+ default:
+ LogReportErrorCode("Endpoint Verification data retrieval error.",
+ static_cast<long int>(status));
+ Respond(
+ Error(enterprise_reporting::kEndpointVerificationRetrievalFailed));
}
}
diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h
index c33bfe43276..1778b6c6868 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h
+++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h
@@ -9,6 +9,7 @@
#include <string>
#include "base/memory/ref_counted.h"
+#include "chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h"
#include "chrome/common/extensions/api/enterprise_reporting_private.h"
#include "components/policy/core/common/cloud/dm_token.h"
#include "extensions/browser/extension_function.h"
@@ -104,7 +105,7 @@ class EnterpriseReportingPrivateGetPersistentSecretFunction
ExtensionFunction::ResponseAction Run() override;
// Callback once the data was retrieved from the file.
- void OnDataRetrieved(const std::string& data, bool status);
+ void OnDataRetrieved(const std::string& data, long int status);
};
class EnterpriseReportingPrivateGetDeviceDataFunction
@@ -126,7 +127,8 @@ class EnterpriseReportingPrivateGetDeviceDataFunction
ExtensionFunction::ResponseAction Run() override;
// Callback once the data was retrieved from the file.
- void OnDataRetrieved(const std::string& data, bool status);
+ void OnDataRetrieved(const std::string& data,
+ RetrieveDeviceDataStatus status);
};
class EnterpriseReportingPrivateSetDeviceDataFunction
diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc
index 325ef19e167..76dd8a810e4 100644
--- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc
@@ -81,6 +81,7 @@ class EnterpriseReportingPrivateUploadChromeDesktopReportTest
private:
network::TestURLLoaderFactory test_url_loader_factory_;
+ policy::FakeBrowserDMTokenStorage storage_;
DISALLOW_COPY_AND_ASSIGN(
EnterpriseReportingPrivateUploadChromeDesktopReportTest);
@@ -204,7 +205,7 @@ TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, DeviceDataMissing) {
browser(),
extensions::api_test_utils::NONE);
ASSERT_TRUE(function->GetResultList());
- EXPECT_EQ(1u, function->GetResultList()->GetSize());
+ EXPECT_EQ(0u, function->GetResultList()->GetSize());
EXPECT_TRUE(function->GetError().empty());
}
@@ -282,11 +283,8 @@ TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, RetrieveDeviceData) {
std::move(values2), browser(),
extensions::api_test_utils::NONE);
ASSERT_TRUE(get_function2->GetResultList());
- EXPECT_TRUE(get_function2->GetResultList()->Get(0, &single_result));
+ EXPECT_EQ(0u, get_function2->GetResultList()->GetSize());
EXPECT_TRUE(get_function2->GetError().empty());
- ASSERT_TRUE(single_result);
- ASSERT_TRUE(single_result->is_blob());
- EXPECT_EQ(base::Value::BlobStorage(), single_result->GetBlob());
}
// TODO(pastarmovj): Remove once implementation for the other platform exists.
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 5b236b80e49..69618e22c88 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
@@ -806,13 +806,9 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, CloseBackgroundPage) {
const ExtensionHostDestructionObserver& other) = delete;
~ExtensionHostDestructionObserver() override = default;
- void OnExtensionHostDestroyed(const ExtensionHost* host) override {
- // TODO(devlin): It would be nice to
- // ASSERT_TRUE(host_observer_.IsObserving(host));
- // host_observer_.Remove(host);
- // But we can't, because |host| is const. Work around it by just
- // RemoveAll()ing.
- host_observer_.RemoveAll();
+ void OnExtensionHostDestroyed(ExtensionHost* host) override {
+ ASSERT_TRUE(host_observer_.IsObserving(host));
+ host_observer_.Remove(host);
run_loop_.QuitWhenIdle();
}
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 b2fa34c8b44..573ad4f32f0 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
@@ -11,6 +11,7 @@
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/location.h"
+#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
@@ -240,11 +241,10 @@ void ExtensionActionAPI::Shutdown() {
//
ExtensionActionFunction::ExtensionActionFunction()
- : details_(NULL),
+ : details_(nullptr),
tab_id_(ExtensionAction::kDefaultTabId),
- contents_(NULL),
- extension_action_(NULL) {
-}
+ contents_(nullptr),
+ extension_action_(nullptr) {}
ExtensionActionFunction::~ExtensionActionFunction() {
}
@@ -356,7 +356,26 @@ void ExtensionActionSetIconFunction::SetReportErrorForInvisibleIconForTesting(
ExtensionFunction::ResponseAction
ExtensionActionSetIconFunction::RunExtensionAction() {
- EXTENSION_FUNCTION_VALIDATE(details_);
+ // TODO(devlin): Temporary logging to track down https://crbug.com/1087948.
+ // Remove this (and the redundant `if (!x) { VALIDATE(x); }`) checks after
+ // the bug is fixed.
+ // Don't reorder or remove values.
+ enum class FailureType {
+ kFailedToParseDetails = 0,
+ kFailedToDecodeCanvas = 1,
+ kFailedToUnpickleCanvas = 2,
+ kNoImageDataOrIconIndex = 3,
+ kMaxValue = kNoImageDataOrIconIndex,
+ };
+
+ auto log_set_icon_failure = [](FailureType type) {
+ base::UmaHistogramEnumeration("Extensions.ActionSetIconFailureType", type);
+ };
+
+ if (!details_) {
+ log_set_icon_failure(FailureType::kFailedToParseDetails);
+ EXTENSION_FUNCTION_VALIDATE(details_);
+ }
// setIcon can take a variant argument: either a dictionary of canvas
// ImageData, or an icon index.
@@ -365,8 +384,23 @@ ExtensionActionSetIconFunction::RunExtensionAction() {
if (details_->GetDictionary("imageData", &canvas_set)) {
gfx::ImageSkia icon;
- EXTENSION_FUNCTION_VALIDATE(
- ExtensionAction::ParseIconFromCanvasDictionary(*canvas_set, &icon));
+ ExtensionAction::IconParseResult parse_result =
+ ExtensionAction::ParseIconFromCanvasDictionary(*canvas_set, &icon);
+
+ if (parse_result != ExtensionAction::IconParseResult::kSuccess) {
+ switch (parse_result) {
+ case ExtensionAction::IconParseResult::kDecodeFailure:
+ log_set_icon_failure(FailureType::kFailedToDecodeCanvas);
+ break;
+ case ExtensionAction::IconParseResult::kUnpickleFailure:
+ log_set_icon_failure(FailureType::kFailedToUnpickleCanvas);
+ break;
+ case ExtensionAction::IconParseResult::kSuccess:
+ NOTREACHED();
+ break;
+ }
+ EXTENSION_FUNCTION_VALIDATE(false);
+ }
if (icon.isNull())
return RespondNow(Error("Icon invalid."));
@@ -391,6 +425,7 @@ ExtensionActionSetIconFunction::RunExtensionAction() {
// Obsolete argument: ignore it.
return RespondNow(NoArguments());
} else {
+ log_set_icon_failure(FailureType::kNoImageDataOrIconIndex);
EXTENSION_FUNCTION_VALIDATE(false);
}
NotifyChange();
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 1bddc30de58..1549e17b027 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
@@ -549,24 +549,16 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPICanvasTest, DynamicSetIcon) {
"background": { "scripts": ["background.js"] }
})";
- 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, GetManifestKeyForActionType(GetParam())));
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(kSetIconBackgroundJsTemplate,
GetAPINameForActionType(GetParam())));
- test_dir.WriteFile(FILE_PATH_LITERAL("blue_icon.png"), blue_icon);
- test_dir.WriteFile(FILE_PATH_LITERAL("red_icon.png"), red_icon);
+ test_dir.CopyFileTo(test_data_dir_.AppendASCII("icon_rgb_0_0_255.png"),
+ FILE_PATH_LITERAL("blue_icon.png"));
+ test_dir.CopyFileTo(test_data_dir_.AppendASCII("icon_rgb_255_0_0.png"),
+ FILE_PATH_LITERAL("red_icon.png"));
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
@@ -672,20 +664,14 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPITest, SetIconWithJavascriptHooks) {
"background": { "scripts": ["background.js"] }
})";
- std::string blue_icon;
- {
- base::ScopedAllowBlockingForTesting allow_blocking;
- ASSERT_TRUE(base::ReadFileToString(
- test_data_dir_.AppendASCII("icon_rgb_0_0_255.png"), &blue_icon));
- }
-
TestExtensionDir test_dir;
test_dir.WriteManifest(base::StringPrintf(
kManifestTemplate, GetManifestKeyForActionType(GetParam())));
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(kSetIconBackgroundJsTemplate,
GetAPINameForActionType(GetParam())));
- test_dir.WriteFile(FILE_PATH_LITERAL("blue_icon.png"), blue_icon);
+ test_dir.CopyFileTo(test_data_dir_.AppendASCII("icon_rgb_0_0_255.png"),
+ FILE_PATH_LITERAL("blue_icon.png"));
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
@@ -738,13 +724,6 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPITest, SetIconWithSelfDefined) {
"background": { "scripts": ["background.js"] }
})";
- std::string blue_icon;
- {
- base::ScopedAllowBlockingForTesting allow_blocking;
- ASSERT_TRUE(base::ReadFileToString(
- test_data_dir_.AppendASCII("icon_rgb_0_0_255.png"), &blue_icon));
- }
-
TestExtensionDir test_dir;
test_dir.WriteManifest(base::StringPrintf(
kManifestTemplate, GetManifestKeyForActionType(GetParam())));
@@ -752,7 +731,8 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPITest, SetIconWithSelfDefined) {
test_dir.WriteFile(FILE_PATH_LITERAL("background.js"),
base::StringPrintf(kSetIconBackgroundJsTemplate,
GetAPINameForActionType(GetParam())));
- test_dir.WriteFile(FILE_PATH_LITERAL("blue_icon.png"), blue_icon);
+ test_dir.CopyFileTo(test_data_dir_.AppendASCII("icon_rgb_0_0_255.png"),
+ FILE_PATH_LITERAL("blue_icon.png"));
const Extension* extension = LoadExtension(test_dir.UnpackedPath());
ASSERT_TRUE(extension);
diff --git a/chromium/chrome/browser/extensions/api/extension_action/page_action_apitest.cc b/chromium/chrome/browser/extensions/api/extension_action/page_action_apitest.cc
index 7c2a722b840..25dbaadb950 100644
--- a/chromium/chrome/browser/extensions/api/extension_action/page_action_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/extension_action/page_action_apitest.cc
@@ -171,22 +171,6 @@ IN_PROC_BROWSER_TEST_F(PageActionApiTest, RemovePopup) {
<< "Page action popup should have been removed.";
}
-// Tests popups in page actions.
-// Flaky on the trybots. See http://crbug.com/96725.
-IN_PROC_BROWSER_TEST_F(PageActionApiTest, DISABLED_ShowPageActionPopup) {
- ASSERT_TRUE(RunExtensionTest("page_action/popup")) << message_;
- const Extension* extension = GetSingleLoadedExtension();
- ASSERT_TRUE(extension) << message_;
-
- ASSERT_TRUE(WaitForPageActionVisibilityChangeTo(1));
-
- {
- ResultCatcher catcher;
- ExtensionActionAPI::Get(browser()->profile())
- ->ShowExtensionActionPopupForAPICall(extension, browser());
- ASSERT_TRUE(catcher.GetNextResult());
- }
-}
// Test http://crbug.com/57333: that two page action extensions using the same
// icon for the page action icon and the extension icon do not crash.
diff --git a/chromium/chrome/browser/extensions/api/extension_action/page_action_interactive_test.cc b/chromium/chrome/browser/extensions/api/extension_action/page_action_interactive_test.cc
new file mode 100644
index 00000000000..09c8a9b7e61
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/extension_action/page_action_interactive_test.cc
@@ -0,0 +1,36 @@
+// Copyright 2020 The Chromium 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/extension_action/extension_action_api.h"
+#include "chrome/browser/extensions/extension_apitest.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/browser_window.h"
+#include "chrome/test/base/interactive_test_utils.h"
+#include "content/public/test/browser_test.h"
+#include "extensions/test/result_catcher.h"
+
+namespace extensions {
+namespace {
+
+using PageActionInteractiveTest = ExtensionApiTest;
+
+// Tests popups in page actions.
+IN_PROC_BROWSER_TEST_F(PageActionInteractiveTest, ShowPageActionPopup) {
+ ASSERT_TRUE(RunExtensionTest("page_action/popup")) << message_;
+ const Extension* extension = GetSingleLoadedExtension();
+ ASSERT_TRUE(extension) << message_;
+
+ ASSERT_TRUE(WaitForPageActionVisibilityChangeTo(1));
+
+ ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
+ ASSERT_TRUE(browser()->window()->IsActive());
+
+ ResultCatcher catcher;
+ ASSERT_TRUE(ExtensionActionAPI::Get(browser()->profile())
+ ->ShowExtensionActionPopupForAPICall(extension, browser()));
+ ASSERT_TRUE(catcher.GetNextResult());
+}
+
+} // namespace
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/feedback_private/OWNERS b/chromium/chrome/browser/extensions/api/feedback_private/OWNERS
index bd30e9ff740..5c0b2c9fb1e 100644
--- a/chromium/chrome/browser/extensions/api/feedback_private/OWNERS
+++ b/chromium/chrome/browser/extensions/api/feedback_private/OWNERS
@@ -1,4 +1,5 @@
afakhry@chromium.org
jkardatzke@chromium.org
+iby@chromium.org
# COMPONENT: Platform>Apps>Feedback
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 cb3b85fb7b6..312a3838cda 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
@@ -70,9 +70,10 @@ ChromeFeedbackPrivateDelegate::GetStrings(
std::make_unique<base::DictionaryValue>();
#define SET_STRING(id, idr) dict->SetString(id, l10n_util::GetStringUTF16(idr))
- SET_STRING("page-title", from_crash
- ? IDS_FEEDBACK_REPORT_PAGE_TITLE_SAD_TAB_FLOW
- : IDS_FEEDBACK_REPORT_PAGE_TITLE);
+ SET_STRING("pageTitle", from_crash
+ ? IDS_FEEDBACK_REPORT_PAGE_TITLE_SAD_TAB_FLOW
+ : IDS_FEEDBACK_REPORT_PAGE_TITLE);
+ SET_STRING("appTitle", IDS_FEEDBACK_REPORT_APP_TITLE);
SET_STRING("additionalInfo", IDS_FEEDBACK_ADDITIONAL_INFO_LABEL);
SET_STRING("minimizeBtnLabel", IDS_FEEDBACK_MINIMIZE_BUTTON_LABEL);
SET_STRING("closeBtnLabel", IDS_FEEDBACK_CLOSE_BUTTON_LABEL);
@@ -117,7 +118,7 @@ ChromeFeedbackPrivateDelegate::GetStrings(
system_logs::SystemLogsFetcher*
ChromeFeedbackPrivateDelegate::CreateSystemLogsFetcher(
content::BrowserContext* context) const {
- return system_logs::BuildChromeSystemLogsFetcher();
+ return system_logs::BuildChromeSystemLogsFetcher(/*scrub_data=*/true);
}
#if defined(OS_CHROMEOS)
diff --git a/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc b/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc
index 408f09d5342..f02f4eb82cd 100644
--- a/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc
+++ b/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc
@@ -165,7 +165,7 @@ class FileSystemApiTestForDrive : public PlatformAppBrowserTest {
SetUpTestFileHierarchy();
integration_service_ = new drive::DriveIntegrationService(
- profile, nullptr, "", test_cache_root_.GetPath(),
+ profile, "", test_cache_root_.GetPath(),
fake_drivefs_helper_->CreateFakeDriveFsListenerFactory());
return integration_service_;
}
@@ -312,7 +312,7 @@ class FileSystemApiTestForRequestFileSystem : public PlatformAppBrowserTest {
profile, drivefs_root_.GetPath().Append("drive-user"));
return new drive::DriveIntegrationService(
- profile, nullptr, "", {},
+ profile, "", {},
fake_drivefs_helper_->CreateFakeDriveFsListenerFactory());
}
diff --git a/chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.cc b/chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.cc
new file mode 100644
index 00000000000..e1cfefca8a1
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.cc
@@ -0,0 +1,143 @@
+// Copyright 2020 The Chromium 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/force_installed_affiliated_extension_apitest.h"
+
+#include "base/json/json_writer.h"
+#include "chrome/browser/browser_process.h"
+#include "chrome/browser/chromeos/policy/affiliation_test_helper.h"
+#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
+#include "chrome/browser/extensions/policy_test_utils.h"
+#include "chrome/test/base/ui_test_utils.h"
+#include "chromeos/dbus/session_manager/fake_session_manager_client.h"
+#include "components/prefs/pref_service.h"
+#include "extensions/browser/extension_registry.h"
+#include "extensions/test/result_catcher.h"
+
+namespace {
+
+// If running with |is_affiliated|==true, the test will use the same
+// |kAffiliationID| as user and device affiliation ID, which makes the user
+// affiliated (affiliation IDs overlap).
+// If running with |is_affiliated|==false, the test will use |kAffiliationID| as
+// device and |kAnotherAffiliationID| as user affiliation ID, which makes the
+// user non-affiliated (affiliation IDs don't overlap).
+constexpr char kAffiliationID[] = "some-affiliation-id";
+constexpr char kAnotherAffiliationID[] = "another-affiliation-id";
+
+constexpr char kAffiliatedUserEmail[] = "user@example.com";
+constexpr char kAffiliatedUserGaiaId[] = "1029384756";
+
+} // namespace
+
+namespace extensions {
+
+ForceInstalledAffiliatedExtensionApiTest::
+ ForceInstalledAffiliatedExtensionApiTest(bool is_affiliated)
+ : is_affiliated_(is_affiliated),
+ affiliated_account_id_(
+ AccountId::FromUserEmailGaiaId(kAffiliatedUserEmail,
+ kAffiliatedUserGaiaId)),
+ test_install_attributes_(
+ chromeos::StubInstallAttributes::CreateCloudManaged("fake-domain",
+ "fake-id")) {
+ set_exit_when_last_browser_closes(false);
+ set_chromeos_user_ = false;
+}
+
+ForceInstalledAffiliatedExtensionApiTest::
+ ~ForceInstalledAffiliatedExtensionApiTest() = default;
+
+void ForceInstalledAffiliatedExtensionApiTest::SetUpCommandLine(
+ base::CommandLine* command_line) {
+ ExtensionApiTest::SetUpCommandLine(command_line);
+ policy::AffiliationTestHelper::AppendCommandLineSwitchesForLoginManager(
+ command_line);
+}
+
+void ForceInstalledAffiliatedExtensionApiTest::
+ SetUpInProcessBrowserTestFixture() {
+ ExtensionApiTest::SetUpInProcessBrowserTestFixture();
+
+ // Initialize clients here so they are available during setup. They will be
+ // shutdown in ChromeBrowserMain.
+ chromeos::SessionManagerClient::InitializeFakeInMemory();
+ policy::AffiliationTestHelper affiliation_helper =
+ policy::AffiliationTestHelper::CreateForCloud(
+ chromeos::FakeSessionManagerClient::Get());
+
+ std::set<std::string> device_affiliation_ids;
+ device_affiliation_ids.insert(kAffiliationID);
+ ASSERT_NO_FATAL_FAILURE(affiliation_helper.SetDeviceAffiliationIDs(
+ &test_helper_, device_affiliation_ids));
+ test_helper_.InstallOwnerKey();
+
+ std::set<std::string> user_affiliation_ids;
+ if (is_affiliated_) {
+ user_affiliation_ids.insert(kAffiliationID);
+ } else {
+ user_affiliation_ids.insert(kAnotherAffiliationID);
+ }
+ policy::UserPolicyBuilder user_policy;
+ ASSERT_NO_FATAL_FAILURE(affiliation_helper.SetUserAffiliationIDs(
+ &user_policy, affiliated_account_id_, user_affiliation_ids));
+ test_helper_.InstallOwnerKey();
+
+ // Init the user policy provider.
+ EXPECT_CALL(policy_provider_, IsInitializationComplete(testing::_))
+ .WillRepeatedly(testing::Return(true));
+ policy_provider_.SetAutoRefresh();
+ policy::BrowserPolicyConnector::SetPolicyProviderForTesting(
+ &policy_provider_);
+
+ // Set retry delay to prevent timeouts.
+ policy::DeviceManagementService::SetRetryDelayForTesting(0);
+}
+
+void ForceInstalledAffiliatedExtensionApiTest::SetUpOnMainThread() {
+ // Log in user that was created with
+ // policy::AffiliationTestHelper::PreLoginUser() in the PRE_ test.
+ const base::ListValue* users =
+ g_browser_process->local_state()->GetList("LoggedInUsers");
+ if (!users->empty()) {
+ policy::AffiliationTestHelper::LoginUser(affiliated_account_id_);
+ }
+
+ policy_test_utils::SetUpEmbeddedTestServer(embedded_test_server());
+ ASSERT_TRUE(embedded_test_server()->Start());
+
+ ExtensionApiTest::SetUpOnMainThread();
+}
+
+const extensions::Extension*
+ForceInstalledAffiliatedExtensionApiTest::ForceInstallExtension(
+ const extensions::ExtensionId& extension_id,
+ const std::string& update_manifest_path) {
+ policy_test_utils::SetExtensionInstallForcelistPolicy(
+ extension_id, embedded_test_server()->GetURL(update_manifest_path),
+ profile(), &policy_provider_);
+ const extensions::Extension* extension =
+ ExtensionRegistry::Get(profile())->enabled_extensions().GetByID(
+ extension_id);
+ DCHECK(extension);
+ return extension;
+}
+
+void ForceInstalledAffiliatedExtensionApiTest::TestExtension(
+ Browser* browser,
+ const GURL& page_url,
+ const base::Value& custom_arg_value) {
+ DCHECK(page_url.is_valid()) << "page_url must be valid";
+
+ std::string custom_arg;
+ base::JSONWriter::Write(custom_arg_value, &custom_arg);
+ SetCustomArg(custom_arg);
+
+ extensions::ResultCatcher catcher;
+ ui_test_utils::NavigateToURL(browser, GURL(page_url));
+
+ ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
+}
+
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.h b/chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.h
new file mode 100644
index 00000000000..7707876e67b
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.h
@@ -0,0 +1,67 @@
+// Copyright 2020 The Chromium 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_FORCE_INSTALLED_AFFILIATED_EXTENSION_APITEST_H_
+#define CHROME_BROWSER_EXTENSIONS_API_FORCE_INSTALLED_AFFILIATED_EXTENSION_APITEST_H_
+
+#include <string>
+
+#include "base/values.h"
+#include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h"
+#include "chrome/browser/extensions/extension_apitest.h"
+#include "chromeos/tpm/stub_install_attributes.h"
+#include "components/account_id/account_id.h"
+#include "components/policy/core/common/mock_configuration_policy_provider.h"
+#include "extensions/common/extension_id.h"
+#include "url/gurl.h"
+
+class Browser;
+
+namespace base {
+class CommandLine;
+} // namespace base
+
+namespace extensions {
+
+class Extension;
+
+// TODO(https://crbug.com/1082195) Create force-installed extension and user
+// affiliation test mixins to replace this class.
+
+// Helper class to test force-installed extensions in a
+// affiliated/non-affiliated user profile.
+class ForceInstalledAffiliatedExtensionApiTest : public ExtensionApiTest {
+ public:
+ explicit ForceInstalledAffiliatedExtensionApiTest(bool is_affiliated);
+ ~ForceInstalledAffiliatedExtensionApiTest() override;
+
+ protected:
+ // ExtensionApiTest
+ void SetUpCommandLine(base::CommandLine* command_line) override;
+ void SetUpInProcessBrowserTestFixture() override;
+ void SetUpOnMainThread() override;
+
+ const extensions::Extension* ForceInstallExtension(
+ const extensions::ExtensionId& extension_id,
+ const std::string& update_manifest_path);
+
+ // Sets |custom_arg_value|, loads |page_url| and waits for an extension API
+ // test pass/fail notification.
+ void TestExtension(Browser* browser,
+ const GURL& page_url,
+ const base::Value& custom_arg_value);
+
+ // Whether the user should be affiliated (= user and device affiliation IDs
+ // overlap).
+ const bool is_affiliated_;
+
+ const AccountId affiliated_account_id_;
+ policy::MockConfigurationPolicyProvider policy_provider_;
+ chromeos::ScopedStubInstallAttributes test_install_attributes_;
+ policy::DevicePolicyCrosTestHelper test_helper_;
+};
+
+} // namespace extensions
+
+#endif // CHROME_BROWSER_EXTENSIONS_API_FORCE_INSTALLED_AFFILIATED_EXTENSION_APITEST_H_
diff --git a/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc b/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc
index d9b189cf106..623b7a0697c 100644
--- a/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc
@@ -60,7 +60,7 @@ namespace extensions {
class GcmApiTest : public ExtensionApiTest {
public:
- GcmApiTest() : fake_gcm_profile_service_(NULL) {}
+ GcmApiTest() : fake_gcm_profile_service_(nullptr) {}
protected:
void SetUpCommandLine(base::CommandLine* command_line) override;
diff --git a/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow.cc b/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow.cc
index e650e3f1ebb..bd091a6f0e2 100644
--- a/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow.cc
+++ b/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow.cc
@@ -5,6 +5,7 @@
#include "chrome/browser/extensions/api/identity/gaia_remote_consent_flow.h"
#include "base/bind.h"
+#include "base/metrics/histogram_functions.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/extensions/api/identity/identity_api.h"
#include "chrome/browser/profiles/profile.h"
@@ -24,6 +25,15 @@
namespace extensions {
+namespace {
+
+void RecordResultHistogram(GaiaRemoteConsentFlow::Failure failure) {
+ base::UmaHistogramEnumeration("Signin.Extensions.GaiaRemoteConsentFlowResult",
+ failure);
+}
+
+} // namespace
+
GaiaRemoteConsentFlow::Delegate::~Delegate() = default;
GaiaRemoteConsentFlow::GaiaRemoteConsentFlow(
@@ -61,7 +71,7 @@ void GaiaRemoteConsentFlow::OnSetAccountsComplete(
}
if (result != signin::SetAccountsInCookieResult::kSuccess) {
- delegate_->OnGaiaRemoteConsentFlowFailed(
+ GaiaRemoteConsentFlowFailed(
GaiaRemoteConsentFlow::Failure::SET_ACCOUNTS_IN_COOKIE_FAILED);
return;
}
@@ -100,16 +110,16 @@ void GaiaRemoteConsentFlow::OnConsentResultSet(
std::string gaia_id;
if (!gaia::ParseOAuth2MintTokenConsentResult(consent_result,
&consent_approved, &gaia_id)) {
- delegate_->OnGaiaRemoteConsentFlowFailed(
- GaiaRemoteConsentFlow::INVALID_CONSENT_RESULT);
+ GaiaRemoteConsentFlowFailed(GaiaRemoteConsentFlow::INVALID_CONSENT_RESULT);
return;
}
if (!consent_approved) {
- delegate_->OnGaiaRemoteConsentFlowFailed(GaiaRemoteConsentFlow::NO_GRANT);
+ GaiaRemoteConsentFlowFailed(GaiaRemoteConsentFlow::NO_GRANT);
return;
}
+ RecordResultHistogram(GaiaRemoteConsentFlow::NONE);
delegate_->OnGaiaRemoteConsentFlowApproved(consent_result, gaia_id);
}
@@ -129,7 +139,7 @@ void GaiaRemoteConsentFlow::OnAuthFlowFailure(WebAuthFlow::Failure failure) {
break;
}
- delegate_->OnGaiaRemoteConsentFlowFailed(gaia_failure);
+ GaiaRemoteConsentFlowFailed(gaia_failure);
}
std::unique_ptr<GaiaAuthFetcher>
@@ -146,7 +156,15 @@ GaiaRemoteConsentFlow::GetCookieManagerForPartition() {
}
void GaiaRemoteConsentFlow::OnEndBatchOfRefreshTokenStateChanges() {
+// On ChromeOS, new accounts are added through the account manager. They need to
+// be pushed to the partition used by this flow explicitly.
+// On Desktop, sign-in happens on the Web and a new account is directly added to
+// this partition's cookie jar. An extra update triggered from here might change
+// cookies order in the middle of the flow. This may lead to a bug like
+// https://crbug.com/1112343.
+#if defined(OS_CHROMEOS)
SetAccountsInCookie();
+#endif
}
void GaiaRemoteConsentFlow::SetWebAuthFlowForTesting(
@@ -196,4 +214,9 @@ void GaiaRemoteConsentFlow::SetAccountsInCookie() {
base::Unretained(this)));
}
+void GaiaRemoteConsentFlow::GaiaRemoteConsentFlowFailed(Failure failure) {
+ RecordResultHistogram(failure);
+ delegate_->OnGaiaRemoteConsentFlowFailed(failure);
+}
+
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow.h b/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow.h
index 433777bc7c0..0fd5cc8de97 100644
--- a/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow.h
+++ b/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow.h
@@ -25,12 +25,16 @@ class GaiaRemoteConsentFlow
public signin::AccountsCookieMutator::PartitionDelegate,
public signin::IdentityManager::Observer {
public:
+ // These values are persisted to logs. Entries should not be renumbered and
+ // numeric values should never be reused.
enum Failure {
- WINDOW_CLOSED,
- LOAD_FAILED,
- SET_ACCOUNTS_IN_COOKIE_FAILED,
- INVALID_CONSENT_RESULT,
- NO_GRANT
+ NONE = 0,
+ WINDOW_CLOSED = 1,
+ LOAD_FAILED = 2,
+ SET_ACCOUNTS_IN_COOKIE_FAILED = 3,
+ INVALID_CONSENT_RESULT = 4,
+ NO_GRANT = 5,
+ kMaxValue = NO_GRANT
};
class Delegate {
@@ -80,6 +84,8 @@ class GaiaRemoteConsentFlow
private:
void SetAccountsInCookie();
+ void GaiaRemoteConsentFlowFailed(Failure failure);
+
Delegate* delegate_;
Profile* profile_;
CoreAccountId account_id_;
diff --git a/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow_unittest.cc b/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow_unittest.cc
index fa1a7c19ed7..bf65e8160b6 100644
--- a/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/identity/gaia_remote_consent_flow_unittest.cc
@@ -7,6 +7,7 @@
#include <vector>
#include "base/run_loop.h"
+#include "base/test/metrics/histogram_tester.h"
#include "chrome/browser/signin/identity_test_environment_profile_adaptor.h"
#include "chrome/test/base/testing_profile.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
@@ -17,6 +18,9 @@
namespace extensions {
+const char kResultHistogramName[] =
+ "Signin.Extensions.GaiaRemoteConsentFlowResult";
+
const char kWindowKey[] = "window_key";
const char kGaiaId[] = "fake_gaia_id";
const char kConsentResult[] = "CAESCUVOQ1JZUFRFRBoMZmFrZV9nYWlhX2lk";
@@ -98,8 +102,11 @@ class IdentityGaiaRemoteConsentFlowTest : public testing::Test {
window_key));
}
+ base::HistogramTester* histogram_tester() { return &histogram_tester_; }
+
protected:
base::test::TaskEnvironment task_env_;
+ base::HistogramTester histogram_tester_;
testing::StrictMock<MockGaiaRemoteConsentFlowDelegate> delegate_;
};
@@ -108,6 +115,8 @@ TEST_F(IdentityGaiaRemoteConsentFlowTest, ConsentResult) {
EXPECT_CALL(delegate_,
OnGaiaRemoteConsentFlowApproved(kConsentResult, kGaiaId));
flow->OnConsentResultSet(kConsentResult, kWindowKey);
+ histogram_tester()->ExpectUniqueSample(kResultHistogramName,
+ GaiaRemoteConsentFlow::NONE, 1);
}
TEST_F(IdentityGaiaRemoteConsentFlowTest, ConsentResult_WrongWindowIgnored) {
@@ -130,6 +139,8 @@ TEST_F(IdentityGaiaRemoteConsentFlowTest, ConsentResult_TwoWindows) {
EXPECT_CALL(delegate_,
OnGaiaRemoteConsentFlowApproved(kConsentResult, kGaiaId));
flow->OnConsentResultSet(kConsentResult, kWindowKey);
+ histogram_tester()->ExpectUniqueSample(kResultHistogramName,
+ GaiaRemoteConsentFlow::NONE, 2);
}
TEST_F(IdentityGaiaRemoteConsentFlowTest, InvalidConsentResult) {
@@ -139,6 +150,8 @@ TEST_F(IdentityGaiaRemoteConsentFlowTest, InvalidConsentResult) {
OnGaiaRemoteConsentFlowFailed(
GaiaRemoteConsentFlow::Failure::INVALID_CONSENT_RESULT));
flow->OnConsentResultSet(kInvalidConsentResult, kWindowKey);
+ histogram_tester()->ExpectUniqueSample(
+ kResultHistogramName, GaiaRemoteConsentFlow::INVALID_CONSENT_RESULT, 1);
}
TEST_F(IdentityGaiaRemoteConsentFlowTest, NoGrant) {
@@ -147,6 +160,8 @@ TEST_F(IdentityGaiaRemoteConsentFlowTest, NoGrant) {
EXPECT_CALL(delegate_, OnGaiaRemoteConsentFlowFailed(
GaiaRemoteConsentFlow::Failure::NO_GRANT));
flow->OnConsentResultSet(kNoGrantConsentResult, kWindowKey);
+ histogram_tester()->ExpectUniqueSample(kResultHistogramName,
+ GaiaRemoteConsentFlow::NO_GRANT, 1);
}
TEST_F(IdentityGaiaRemoteConsentFlowTest, SetAccountsFailure) {
@@ -157,6 +172,9 @@ TEST_F(IdentityGaiaRemoteConsentFlowTest, SetAccountsFailure) {
GaiaRemoteConsentFlow::Failure::SET_ACCOUNTS_IN_COOKIE_FAILED));
flow->OnSetAccountsComplete(
signin::SetAccountsInCookieResult::kPersistentError);
+ histogram_tester()->ExpectUniqueSample(
+ kResultHistogramName,
+ GaiaRemoteConsentFlow::SET_ACCOUNTS_IN_COOKIE_FAILED, 1);
}
TEST_F(IdentityGaiaRemoteConsentFlowTest, WebAuthFlowFailure_WindowClosed) {
@@ -164,6 +182,8 @@ TEST_F(IdentityGaiaRemoteConsentFlowTest, WebAuthFlowFailure_WindowClosed) {
EXPECT_CALL(delegate_, OnGaiaRemoteConsentFlowFailed(
GaiaRemoteConsentFlow::Failure::WINDOW_CLOSED));
flow->OnAuthFlowFailure(WebAuthFlow::Failure::WINDOW_CLOSED);
+ histogram_tester()->ExpectUniqueSample(
+ kResultHistogramName, GaiaRemoteConsentFlow::WINDOW_CLOSED, 1);
}
TEST_F(IdentityGaiaRemoteConsentFlowTest, WebAuthFlowFailure_LoadFailed) {
@@ -171,6 +191,8 @@ TEST_F(IdentityGaiaRemoteConsentFlowTest, WebAuthFlowFailure_LoadFailed) {
EXPECT_CALL(delegate_, OnGaiaRemoteConsentFlowFailed(
GaiaRemoteConsentFlow::Failure::LOAD_FAILED));
flow->OnAuthFlowFailure(WebAuthFlow::Failure::LOAD_FAILED);
+ histogram_tester()->ExpectUniqueSample(kResultHistogramName,
+ GaiaRemoteConsentFlow::LOAD_FAILED, 1);
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc
index 68327bb525c..71f36451b23 100644
--- a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc
@@ -14,6 +14,7 @@
#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
+#include "base/test/metrics/histogram_tester.h"
#include "base/values.h"
#include "build/build_config.h"
#include "build/buildflag.h"
@@ -23,6 +24,7 @@
#include "chrome/browser/extensions/api/identity/identity_api.h"
#include "chrome/browser/extensions/api/identity/identity_constants.h"
#include "chrome/browser/extensions/api/identity/identity_get_accounts_function.h"
+#include "chrome/browser/extensions/api/identity/identity_get_auth_token_error.h"
#include "chrome/browser/extensions/api/identity/identity_get_auth_token_function.h"
#include "chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.h"
#include "chrome/browser/extensions/api/identity/identity_launch_web_auth_flow_function.h"
@@ -91,8 +93,13 @@ namespace {
namespace errors = identity_constants;
namespace utils = extension_function_test_utils;
-static const char kAccessToken[] = "auth_token";
-static const char kExtensionId[] = "ext_id";
+const char kAccessToken[] = "auth_token";
+const char kExtensionId[] = "ext_id";
+
+const char kGetAuthTokenResultHistogramName[] =
+ "Signin.Extensions.GetAuthTokenResult";
+const char kGetAuthTokenResultAfterConsentApprovedHistogramName[] =
+ "Signin.Extensions.GetAuthTokenResult.RemoteConsentApproved";
#if defined(OS_CHROMEOS)
void InitNetwork() {
@@ -681,9 +688,9 @@ IN_PROC_BROWSER_TEST_F(IdentityGetAccountsFunctionTest, NoPrimaryAccount) {
}
IN_PROC_BROWSER_TEST_F(IdentityGetAccountsFunctionTest,
- PrimaryAccountHasNoRefreshToken) {
+ PrimaryAccountHasInvalidRefreshToken) {
CoreAccountId primary_account_id = SignIn("primary@example.com");
- identity_test_env()->RemoveRefreshTokenForAccount(primary_account_id);
+ identity_test_env()->SetInvalidRefreshTokenForPrimaryAccount();
EXPECT_TRUE(ExpectGetAccounts({}));
}
@@ -938,6 +945,8 @@ class GetAuthTokenFunctionTest
id_api()->mint_queue()->RequestComplete(type, key, request);
}
+ base::HistogramTester* histogram_tester() { return &histogram_tester_; }
+
base::OnceClosure on_access_token_requested_;
private:
@@ -950,6 +959,7 @@ class GetAuthTokenFunctionTest
std::move(on_access_token_requested_).Run();
}
+ base::HistogramTester histogram_tester_;
std::string extension_id_;
std::set<std::string> oauth_scopes_;
};
@@ -962,6 +972,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NoClientId) {
EXPECT_EQ(std::string(errors::kInvalidClientId), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kInvalidClientId, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NoScopes) {
@@ -972,6 +985,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NoScopes) {
EXPECT_EQ(std::string(errors::kInvalidScopes), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kEmptyScopes, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveNotSignedIn) {
@@ -982,6 +998,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveNotSignedIn) {
EXPECT_EQ(std::string(errors::kUserNotSignedIn), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kUserNotSignedIn, 1);
}
// The signin flow is simply not used on ChromeOS.
@@ -996,6 +1015,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(errors::kUserNotSignedIn), error);
EXPECT_TRUE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kSignInFailed, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1018,6 +1040,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(errors::kBrowserSigninNotAllowed), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kBrowserSigninNotAllowed, 1);
}
#endif
@@ -1032,6 +1057,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveMintFailure) {
base::CompareCase::INSENSITIVE_ASCII));
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kMintTokenAuthFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1044,6 +1072,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
utils::RunFunctionAndReturnError(func.get(), "[{}]", browser());
EXPECT_TRUE(base::StartsWith(error, errors::kAuthFailure,
base::CompareCase::INSENSITIVE_ASCII));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGetAccessTokenAuthFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1061,6 +1092,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_ADVICE,
GetCachedToken(CoreAccountId()).status());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGaiaConsentInteractionRequired, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1076,6 +1110,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
base::CompareCase::INSENSITIVE_ASCII));
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kMintTokenAuthFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1091,6 +1128,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
base::CompareCase::INSENSITIVE_ASCII));
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kMintTokenAuthFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1109,6 +1149,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
// in a valid state.
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kMintTokenAuthFailure, 1);
}
// The signin flow is simply not used on ChromeOS.
@@ -1129,6 +1172,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
base::CompareCase::INSENSITIVE_ASCII));
EXPECT_TRUE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kMintTokenAuthFailure, 1);
}
#endif
@@ -1147,6 +1193,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NoOptionsSuccess) {
EXPECT_FALSE(func->scope_ui_shown());
EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN,
GetCachedToken(CoreAccountId()).status());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveSuccess) {
@@ -1164,6 +1213,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveSuccess) {
EXPECT_FALSE(func->scope_ui_shown());
EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN,
GetCachedToken(CoreAccountId()).status());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveLoginCanceled) {
@@ -1179,6 +1231,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveLoginCanceled) {
EXPECT_TRUE(func->login_ui_shown());
#endif
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kSignInFailed, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1195,6 +1250,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
base::CompareCase::INSENSITIVE_ASCII));
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kMintTokenAuthFailure, 1);
}
// The interactive login flow is always short-circuited out with failure on
@@ -1213,6 +1271,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
base::CompareCase::INSENSITIVE_ASCII));
EXPECT_TRUE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kMintTokenAuthFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1228,6 +1289,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
base::CompareCase::INSENSITIVE_ASCII));
EXPECT_TRUE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kMintTokenAuthFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1242,6 +1306,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
base::CompareCase::INSENSITIVE_ASCII));
EXPECT_TRUE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGetAccessTokenAuthFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1259,6 +1326,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(kAccessToken), access_token);
EXPECT_TRUE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1273,6 +1343,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(errors::kUserRejected), error);
EXPECT_TRUE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGaiaFlowRejected, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1290,6 +1363,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(kAccessToken), access_token);
EXPECT_TRUE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
#endif
@@ -1304,6 +1380,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveApprovalAborted) {
EXPECT_EQ(std::string(errors::kUserRejected), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGaiaFlowRejected, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1318,6 +1397,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(errors::kPageLoadFailure), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kPageLoadFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1332,6 +1414,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(errors::kInvalidRedirect), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kInvalidRedirect, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1348,6 +1433,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
base::CompareCase::INSENSITIVE_ASCII));
EXPECT_FALSE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGaiaFlowAuthFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1366,6 +1454,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
// The login UI should not be shown as the account is in a valid state.
EXPECT_FALSE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGaiaFlowAuthFailure, 1);
}
// The signin flow is simply not used on ChromeOS.
@@ -1388,6 +1479,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_TRUE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGaiaFlowAuthFailure, 1);
}
#endif
@@ -1396,15 +1490,24 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
SignIn("primary@example.com");
scoped_refptr<const Extension> extension(CreateExtension(CLIENT_ID | SCOPES));
- std::map<std::string, std::string> error_map;
- error_map.insert(std::make_pair("access_denied", errors::kUserRejected));
- error_map.insert(std::make_pair("invalid_scope", errors::kInvalidScopes));
- error_map.insert(std::make_pair(
- "unmapped_error", std::string(errors::kAuthFailure) + "unmapped_error"));
+ struct TestCase {
+ std::string oauth_error;
+ std::string error_message;
+ IdentityGetAuthTokenError::State error_state;
+ };
- for (std::map<std::string, std::string>::const_iterator it =
- error_map.begin();
- it != error_map.end(); ++it) {
+ std::vector<TestCase> test_cases;
+ test_cases.push_back({"access_denied", errors::kUserRejected,
+ IdentityGetAuthTokenError::State::kOAuth2AccessDenied});
+ test_cases.push_back(
+ {"invalid_scope", errors::kInvalidScopes,
+ IdentityGetAuthTokenError::State::kOAuth2InvalidScopes});
+ test_cases.push_back({"unmapped_error",
+ std::string(errors::kAuthFailure) + "unmapped_error",
+ IdentityGetAuthTokenError::State::kOAuth2Failure});
+
+ for (const auto& test_case : test_cases) {
+ base::HistogramTester histogram_tester;
scoped_refptr<FakeGetAuthTokenFunction> func(
new FakeGetAuthTokenFunction());
func->set_extension(extension.get());
@@ -1412,12 +1515,14 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
// flow to be leaked.
id_api()->EraseAllCachedTokens();
func->push_mint_token_result(TestOAuth2MintTokenFlow::ISSUE_ADVICE_SUCCESS);
- func->set_scope_ui_oauth_error(it->first);
+ func->set_scope_ui_oauth_error(test_case.oauth_error);
std::string error = utils::RunFunctionAndReturnError(
func.get(), "[{\"interactive\": true}]", browser());
- EXPECT_EQ(it->second, error);
+ EXPECT_EQ(test_case.error_message, error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester.ExpectUniqueSample(kGetAuthTokenResultHistogramName,
+ test_case.error_state, 1);
}
}
@@ -1438,6 +1543,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveApprovalSuccess) {
EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN,
GetCachedToken(CoreAccountId()).status());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
#if !defined(OS_MACOSX)
@@ -1472,6 +1580,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
// The login screen should not be shown when the browser process is shutting
// down.
EXPECT_FALSE(func->login_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGaiaFlowAuthFailure, 1);
}
#endif // !defined(OS_MACOSX)
@@ -1506,6 +1617,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NoninteractiveQueue) {
EXPECT_EQ(std::string(kAccessToken), access_token);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveQueue) {
@@ -1540,6 +1654,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveQueue) {
EXPECT_EQ(std::string(kAccessToken), access_token);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveQueueShutdown) {
@@ -1571,6 +1688,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveQueueShutdown) {
EXPECT_FALSE(func->scope_ui_shown());
QueueRequestComplete(type, &queued_request);
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kCanceled, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NoninteractiveShutdown) {
@@ -1585,6 +1705,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NoninteractiveShutdown) {
// After the request is canceled, the function will complete.
func->OnIdentityAPIShutdown();
EXPECT_EQ(std::string(errors::kCanceled), WaitForError(func.get()));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kCanceled, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1611,6 +1734,10 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_FALSE(func->scope_ui_shown());
QueueRequestComplete(type, &queued_request);
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGaiaConsentInteractionAlreadyRunning,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveCacheHit) {
@@ -1632,6 +1759,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveCacheHit) {
EXPECT_EQ(std::string(kAccessToken), access_token);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
// Checks that the first account in Gaia cookie can be used when extensions are
@@ -1665,6 +1795,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
std::string error =
utils::RunFunctionAndReturnError(func.get(), "[{}]", browser());
EXPECT_EQ(std::string(errors::kUserNotSignedIn), error);
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kUserNotSignedIn, 1);
} else {
// Use the account from Gaia cookies.
std::unique_ptr<base::Value> value(
@@ -1672,6 +1805,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
std::string access_token;
EXPECT_TRUE(value->GetAsString(&access_token));
EXPECT_EQ(std::string(kAccessToken), access_token);
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kNone, 1);
}
EXPECT_FALSE(func->login_ui_shown());
@@ -1697,6 +1833,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(errors::kNoGrant), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGaiaConsentInteractionRequired, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveCacheHit) {
@@ -1734,6 +1873,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveCacheHit) {
EXPECT_EQ(std::string(kAccessToken), access_token);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
// The interactive login UI is never shown on ChromeOS, so tests of the
@@ -1763,6 +1905,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, LoginInvalidatesTokenCache) {
EXPECT_TRUE(func->scope_ui_shown());
EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_NOTFOUND,
GetCachedToken(CoreAccountId()).status());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
#endif
@@ -1789,6 +1934,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(kAccessToken, value->GetString());
EXPECT_TRUE(func->scope_ui_shown());
EXPECT_FALSE(GetCachedGaiaId().has_value());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1814,6 +1962,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(errors::kUserRejected), error);
EXPECT_TRUE(func->scope_ui_shown());
EXPECT_FALSE(GetCachedGaiaId().has_value());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGaiaFlowRejected, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ComponentWithChromeClientId) {
@@ -1852,6 +2003,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, IdentityAPIShutdown) {
id_api()->Shutdown();
EXPECT_EQ(std::string(errors::kCanceled), WaitForError(func.get()));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kCanceled, 1);
}
// Ensure that when there are multiple active function calls, IdentityAPI
@@ -1920,6 +2074,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ManuallyIssueToken) {
GetCachedToken(CoreAccountId()).status());
EXPECT_THAT(func->login_access_tokens(),
testing::ElementsAre(primary_account_access_token));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ManuallyIssueTokenFailure) {
@@ -1947,6 +2104,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ManuallyIssueTokenFailure) {
GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE)
.ToString(),
WaitForError(func.get()));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGetAccessTokenAuthFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -1976,6 +2136,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
GetCachedToken(CoreAccountId()).status());
EXPECT_THAT(func->login_access_tokens(),
testing::ElementsAre(primary_account_access_token));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -2007,6 +2170,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
GetCachedToken(CoreAccountId()).status());
EXPECT_THAT(func->login_access_tokens(),
testing::ElementsAre(primary_account_access_token));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -2033,6 +2199,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(errors::kUserNonPrimary), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kUserNonPrimary, 1);
return;
}
@@ -2052,6 +2221,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
GetCachedToken(secondary_account_id).status());
EXPECT_THAT(func->login_access_tokens(),
testing::ElementsAre(secondary_account_access_token));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -2068,10 +2240,17 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
func.get(), "[{\"account\": { \"id\": \"unknown@example.com\" } }]",
browser());
std::string expected_error;
- if (id_api()->AreExtensionsRestrictedToPrimaryAccount())
+ if (id_api()->AreExtensionsRestrictedToPrimaryAccount()) {
EXPECT_EQ(errors::kUserNonPrimary, error);
- else
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kUserNonPrimary, 1);
+ } else {
EXPECT_EQ(errors::kUserNotSignedIn, error);
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kUserNotSignedIn, 1);
+ }
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -2094,6 +2273,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
base::CompareCase::INSENSITIVE_ASCII));
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kMintTokenAuthFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -2114,6 +2296,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
browser());
EXPECT_TRUE(base::StartsWith(error, errors::kAuthFailure,
base::CompareCase::INSENSITIVE_ASCII));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGetAccessTokenAuthFailure, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
@@ -2137,6 +2322,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(errors::kUserRejected), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kGaiaFlowRejected, 1);
}
// Tests that Chrome remembers user's choice of an account at the end of the
@@ -2172,6 +2360,12 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
if (id_api()->AreExtensionsRestrictedToPrimaryAccount()) {
EXPECT_EQ(std::string(errors::kUserNonPrimary), WaitForError(func.get()));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kRemoteConsentUserNonPrimary, 1);
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultAfterConsentApprovedHistogramName,
+ IdentityGetAuthTokenError::State::kRemoteConsentUserNonPrimary, 1);
return;
}
@@ -2189,6 +2383,12 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_THAT(func->login_access_tokens(),
testing::ElementsAre(primary_account_access_token,
secondary_account_access_token));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kNone, 1);
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultAfterConsentApprovedHistogramName,
+ IdentityGetAuthTokenError::State::kNone, 1);
}
{
@@ -2204,6 +2404,12 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(kAccessToken), access_token);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kNone, 2);
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultAfterConsentApprovedHistogramName,
+ IdentityGetAuthTokenError::State::kNone, 1);
}
}
@@ -2261,6 +2467,10 @@ IN_PROC_BROWSER_TEST_F(
EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN,
GetCachedToken(account.account_id).status());
+
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 2);
}
// Tests two concurrent remote consent flows. Both of them should succeed.
@@ -2325,6 +2535,10 @@ IN_PROC_BROWSER_TEST_F(
EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN,
GetCachedToken(account.account_id).status());
+
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 2);
}
// The signin flow is simply not used on ChromeOS.
@@ -2356,6 +2570,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(errors::kUserNonPrimary), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kUserNonPrimary, 1);
} else {
// Extensions can show the login UI for secondary accounts, and get the auth
// token.
@@ -2366,6 +2583,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest,
EXPECT_EQ(std::string(kAccessToken), access_token);
EXPECT_TRUE(func->login_ui_shown());
EXPECT_TRUE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kNone, 1);
}
}
#endif
@@ -2386,6 +2606,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesDefault) {
EXPECT_EQ(2ul, token_key->scopes.size());
EXPECT_TRUE(base::Contains(token_key->scopes, "scope1"));
EXPECT_TRUE(base::Contains(token_key->scopes, "scope2"));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmpty) {
@@ -2397,6 +2620,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmpty) {
func.get(), "[{\"scopes\": []}]", browser()));
EXPECT_EQ(errors::kInvalidScopes, error);
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kEmptyScopes, 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmail) {
@@ -2414,6 +2640,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmail) {
const ExtensionTokenKey* token_key = func->GetExtensionTokenKeyForTest();
EXPECT_EQ(1ul, token_key->scopes.size());
EXPECT_TRUE(base::Contains(token_key->scopes, "email"));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmailFooBar) {
@@ -2433,6 +2662,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ScopesEmailFooBar) {
EXPECT_TRUE(base::Contains(token_key->scopes, "email"));
EXPECT_TRUE(base::Contains(token_key->scopes, "foo"));
EXPECT_TRUE(base::Contains(token_key->scopes, "bar"));
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
#if defined(OS_CHROMEOS)
@@ -2488,11 +2720,12 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionPublicSessionTest, NonWhitelisted) {
EXPECT_EQ(std::string(errors::kUserNotSignedIn), error);
EXPECT_FALSE(func->login_ui_shown());
EXPECT_FALSE(func->scope_ui_shown());
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName,
+ IdentityGetAuthTokenError::State::kNotWhitelistedInPublicSession, 1);
}
-// TODO(crbug.com/830052): This test is flaky.
-IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionPublicSessionTest,
- DISABLED_Whitelisted) {
+IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionPublicSessionTest, Whitelisted) {
// GetAuthToken() should return a token for whitelisted extensions.
user_manager::ScopedUserManager user_manager_enabler(
base::WrapUnique(user_manager_));
@@ -2504,6 +2737,9 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionPublicSessionTest,
std::string access_token;
EXPECT_TRUE(value->GetAsString(&access_token));
EXPECT_EQ(std::string(kAccessToken), access_token);
+ histogram_tester()->ExpectUniqueSample(
+ kGetAuthTokenResultHistogramName, IdentityGetAuthTokenError::State::kNone,
+ 1);
}
#endif
@@ -2829,19 +3065,19 @@ IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest, FireOnPrimaryAccountSignOut) {
#endif // !defined(OS_CHROMEOS)
// Test that an event is fired when the primary account has a refresh token
-// revoked.
+// invalidated.
IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest,
- FireOnPrimaryAccountRefreshTokenRevoked) {
+ FireOnPrimaryAccountRefreshTokenInvalidated) {
api::identity::AccountInfo account_info;
account_info.id = "gaia_id_for_primary_example.com";
AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, true));
CoreAccountId primary_account_id = SignIn("primary@example.com");
- AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, false));
+ AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, true));
// Revoke the refresh token and verify that the callback fires.
- identity_test_env()->RemoveRefreshTokenForAccount(primary_account_id);
+ identity_test_env()->SetInvalidRefreshTokenForPrimaryAccount();
EXPECT_FALSE(HasExpectedEvent());
}
@@ -2856,14 +3092,14 @@ IN_PROC_BROWSER_TEST_F(OnSignInChangedEventTest,
CoreAccountId primary_account_id = SignIn("primary@example.com");
- AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, false));
- identity_test_env()->RemoveRefreshTokenForAccount(primary_account_id);
+ AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, true));
+ identity_test_env()->SetInvalidRefreshTokenForPrimaryAccount();
account_info.id = "gaia_id_for_primary_example.com";
AddExpectedEvent(api::identity::OnSignInChanged::Create(account_info, true));
// Make the primary account available again and check that the callback fires.
- identity_test_env()->MakeAccountAvailable("primary@example.com");
+ identity_test_env()->SetRefreshTokenForPrimaryAccount();
EXPECT_FALSE(HasExpectedEvent());
}
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_error.cc b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_error.cc
new file mode 100644
index 00000000000..7f02651c90d
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_error.cc
@@ -0,0 +1,112 @@
+// Copyright 2020 The Chromium 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/identity/identity_get_auth_token_error.h"
+
+#include "base/strings/string_piece.h"
+#include "chrome/browser/extensions/api/identity/identity_constants.h"
+
+namespace extensions {
+
+// static
+IdentityGetAuthTokenError IdentityGetAuthTokenError::FromGaiaFlowAuthError(
+ base::StringPiece error_message) {
+ return IdentityGetAuthTokenError(State::kGaiaFlowAuthFailure, error_message);
+}
+
+// static
+IdentityGetAuthTokenError IdentityGetAuthTokenError::FromMintTokenAuthError(
+ base::StringPiece error_message) {
+ return IdentityGetAuthTokenError(State::kMintTokenAuthFailure, error_message);
+}
+
+// static
+IdentityGetAuthTokenError
+IdentityGetAuthTokenError::FromGetAccessTokenAuthError(
+ base::StringPiece error_message) {
+ return IdentityGetAuthTokenError(State::kGetAccessTokenAuthFailure,
+ error_message);
+}
+
+// static
+IdentityGetAuthTokenError IdentityGetAuthTokenError::FromOAuth2Error(
+ base::StringPiece oauth2_error) {
+ const char kOAuth2ErrorAccessDenied[] = "access_denied";
+ const char kOAuth2ErrorInvalidScope[] = "invalid_scope";
+
+ if (oauth2_error == kOAuth2ErrorAccessDenied) {
+ return IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kOAuth2AccessDenied);
+ } else if (oauth2_error == kOAuth2ErrorInvalidScope) {
+ return IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kOAuth2InvalidScopes);
+ } else {
+ return IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kOAuth2Failure, oauth2_error);
+ }
+}
+
+IdentityGetAuthTokenError::IdentityGetAuthTokenError()
+ : IdentityGetAuthTokenError(State::kNone) {}
+
+IdentityGetAuthTokenError::IdentityGetAuthTokenError(State state)
+ : IdentityGetAuthTokenError(state, base::StringPiece()) {}
+
+IdentityGetAuthTokenError::State IdentityGetAuthTokenError::state() const {
+ return state_;
+}
+
+std::string IdentityGetAuthTokenError::ToString() const {
+ switch (state_) {
+ case State::kNone:
+ return std::string();
+ case State::kInvalidClientId:
+ return identity_constants::kInvalidClientId;
+ case State::kEmptyScopes:
+ case State::kOAuth2InvalidScopes:
+ return identity_constants::kInvalidScopes;
+ case State::kGaiaFlowAuthFailure:
+ case State::kMintTokenAuthFailure:
+ case State::kGetAccessTokenAuthFailure:
+ case State::kOAuth2Failure:
+ return identity_constants::kAuthFailure + error_message_;
+ case State::kNoGrant:
+ case State::kGaiaConsentInteractionRequired:
+ case State::kGaiaConsentInteractionAlreadyRunning:
+ return identity_constants::kNoGrant;
+ case State::kOAuth2AccessDenied:
+ case State::kGaiaFlowRejected:
+ case State::kRemoteConsentFlowRejected:
+ return identity_constants::kUserRejected;
+ case State::kUserNotSignedIn:
+ case State::kNotWhitelistedInPublicSession:
+ case State::kSignInFailed:
+ case State::kRemoteConsentUserNotSignedIn:
+ return identity_constants::kUserNotSignedIn;
+ case State::kUserNonPrimary:
+ case State::kRemoteConsentUserNonPrimary:
+ return identity_constants::kUserNonPrimary;
+ case State::kBrowserSigninNotAllowed:
+ return identity_constants::kBrowserSigninNotAllowed;
+ case State::kInvalidRedirect:
+ return identity_constants::kInvalidRedirect;
+ case State::kOffTheRecord:
+ return identity_constants::kOffTheRecord;
+ case State::kPageLoadFailure:
+ case State::kRemoteConsentPageLoadFailure:
+ return identity_constants::kPageLoadFailure;
+ case State::kSetAccountsInCookieFailure:
+ return identity_constants::kSetAccountsInCookieFailure;
+ case State::kInvalidConsentResult:
+ return identity_constants::kInvalidConsentResult;
+ case State::kCanceled:
+ return identity_constants::kCanceled;
+ }
+}
+
+IdentityGetAuthTokenError::IdentityGetAuthTokenError(State state,
+ base::StringPiece error)
+ : state_(state), error_message_(error) {}
+
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_error.h b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_error.h
new file mode 100644
index 00000000000..e03a89cea0b
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_error.h
@@ -0,0 +1,90 @@
+// Copyright 2020 The Chromium 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_IDENTITY_IDENTITY_GET_AUTH_TOKEN_ERROR_H_
+#define CHROME_BROWSER_EXTENSIONS_API_IDENTITY_IDENTITY_GET_AUTH_TOKEN_ERROR_H_
+
+#include <string>
+
+#include "base/strings/string_piece_forward.h"
+
+namespace extensions {
+
+class IdentityGetAuthTokenError {
+ public:
+ // These values are persisted to logs. Entries should not be renumbered and
+ // numeric values should never be reused.
+ enum class State {
+ kNone = 0,
+ kInvalidClientId = 1,
+ kEmptyScopes = 2,
+ kOAuth2InvalidScopes = 3,
+ kGaiaFlowAuthFailure = 4,
+ kMintTokenAuthFailure = 5,
+ kGetAccessTokenAuthFailure = 6,
+ kOAuth2Failure = 7,
+ kNoGrant = 8,
+ kGaiaConsentInteractionRequired = 9,
+ kGaiaConsentInteractionAlreadyRunning = 10,
+ kOAuth2AccessDenied = 11,
+ kGaiaFlowRejected = 12,
+ kRemoteConsentFlowRejected = 13,
+ kUserNotSignedIn = 14,
+ kNotWhitelistedInPublicSession = 15,
+ kSignInFailed = 16,
+ kRemoteConsentUserNotSignedIn = 17,
+ kUserNonPrimary = 18,
+ kRemoteConsentUserNonPrimary = 19,
+ kBrowserSigninNotAllowed = 20,
+ kInvalidRedirect = 21,
+ kOffTheRecord = 22,
+ kPageLoadFailure = 23,
+ kRemoteConsentPageLoadFailure = 24,
+ kSetAccountsInCookieFailure = 25,
+ kInvalidConsentResult = 26,
+ kCanceled = 27,
+ kMaxValue = kCanceled,
+ };
+
+ // Constructs a |State::kGaiaFlowAuthFailure| error with an |error_message|.
+ static IdentityGetAuthTokenError FromGaiaFlowAuthError(
+ base::StringPiece error_message);
+
+ // Constructs a |State::kMintTokenAuthFailure| error with an
+ // |error_message|.
+ static IdentityGetAuthTokenError FromMintTokenAuthError(
+ base::StringPiece error_message);
+
+ // Constructs a |State::kGetAccessTokenAuthFailure| error with an
+ // |error_message|.
+ static IdentityGetAuthTokenError FromGetAccessTokenAuthError(
+ base::StringPiece error_message);
+
+ // Constructs an IdentityGetAuthTokenError from |oauth2_error|.
+ static IdentityGetAuthTokenError FromOAuth2Error(
+ base::StringPiece oauth2_error);
+
+ // Constructs a |State::kNone| error.
+ IdentityGetAuthTokenError();
+
+ // Constructs an IdentityGetAuthTokenError from |state| with no additional
+ // data.
+ explicit IdentityGetAuthTokenError(State state);
+
+ State state() const;
+
+ // Returns an error message that can be returned to the developer in
+ // chrome.runtime.lastError.
+ std::string ToString() const;
+
+ private:
+ IdentityGetAuthTokenError(State state, base::StringPiece error);
+
+ State state_;
+ std::string error_message_;
+};
+
+} // namespace extensions
+
+#endif // CHROME_BROWSER_EXTENSIONS_API_IDENTITY_IDENTITY_GET_AUTH_TOKEN_ERROR_H_
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 39a89fd15be..4e52c3887e1 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
@@ -10,14 +10,16 @@
#include "base/bind.h"
#include "base/feature_list.h"
#include "base/location.h"
+#include "base/metrics/histogram_functions.h"
+#include "base/notreached.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
-#include "base/task/post_task.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/extensions/api/identity/identity_api.h"
#include "chrome/browser/extensions/api/identity/identity_constants.h"
+#include "chrome/browser/extensions/api/identity/identity_get_auth_token_error.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/chrome_device_id_helper.h"
#include "chrome/browser/signin/identity_manager_factory.h"
@@ -77,6 +79,17 @@ std::string GetOAuth2MintTokenFlowChannel() {
return version_info::GetChannelString(chrome::GetChannel());
}
+void RecordFunctionResult(const IdentityGetAuthTokenError& error,
+ bool remote_consent_approved) {
+ base::UmaHistogramEnumeration("Signin.Extensions.GetAuthTokenResult",
+ error.state());
+ if (remote_consent_approved) {
+ base::UmaHistogramEnumeration(
+ "Signin.Extensions.GetAuthTokenResult.RemoteConsentApproved",
+ error.state());
+ }
+}
+
} // namespace
IdentityGetAuthTokenFunction::IdentityGetAuthTokenFunction()
@@ -104,7 +117,10 @@ ExtensionFunction::ResponseAction IdentityGetAuthTokenFunction::Run() {
this, "extension", extension()->id());
if (GetProfile()->IsOffTheRecord()) {
- return RespondNow(Error(identity_constants::kOffTheRecord));
+ IdentityGetAuthTokenError error(
+ IdentityGetAuthTokenError::State::kOffTheRecord);
+ RecordFunctionResult(error, remote_consent_approved_);
+ return RespondNow(Error(error.ToString()));
}
std::unique_ptr<api::identity::GetAuthToken::Params> params(
@@ -122,7 +138,10 @@ ExtensionFunction::ResponseAction IdentityGetAuthTokenFunction::Run() {
// Check that the necessary information is present in the manifest.
oauth2_client_id_ = GetOAuth2ClientId();
if (oauth2_client_id_.empty()) {
- return RespondNow(Error(identity_constants::kInvalidClientId));
+ IdentityGetAuthTokenError error(
+ IdentityGetAuthTokenError::State::kInvalidClientId);
+ RecordFunctionResult(error, remote_consent_approved_);
+ return RespondNow(Error(error.ToString()));
}
std::set<std::string> scopes(oauth2_info.scopes.begin(),
@@ -140,7 +159,10 @@ ExtensionFunction::ResponseAction IdentityGetAuthTokenFunction::Run() {
}
if (scopes.empty()) {
- return RespondNow(Error(identity_constants::kInvalidScopes));
+ IdentityGetAuthTokenError error(
+ IdentityGetAuthTokenError::State::kEmptyScopes);
+ RecordFunctionResult(error, remote_consent_approved_);
+ return RespondNow(Error(error.ToString()));
}
token_key_.scopes = scopes;
@@ -159,15 +181,15 @@ ExtensionFunction::ResponseAction IdentityGetAuthTokenFunction::Run() {
if (gaia_id.empty() || IsPrimaryAccountOnly()) {
// Try the primary account.
// TODO(https://crbug.com/932400): collapse the asynchronicity
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&IdentityGetAuthTokenFunction::GetAuthTokenForPrimaryAccount,
weak_ptr_factory_.GetWeakPtr(), gaia_id));
} else {
// Get the AccountInfo for the account that the extension wishes to use.
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&IdentityGetAuthTokenFunction::FetchExtensionAccountInfo,
weak_ptr_factory_.GetWeakPtr(), gaia_id));
}
@@ -186,7 +208,8 @@ void IdentityGetAuthTokenFunction::GetAuthTokenForPrimaryAccount(
// than the primary account.
if (primary_account_only && !extension_gaia_id.empty() &&
extension_gaia_id != primary_account_info.gaia) {
- CompleteFunctionWithError(identity_constants::kUserNonPrimary);
+ CompleteFunctionWithError(IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kUserNonPrimary));
return;
}
@@ -230,7 +253,8 @@ void IdentityGetAuthTokenFunction::OnReceivedExtensionAccountInfo(
if (connector->IsEnterpriseManaged() && (is_kiosk || is_public_session)) {
if (is_public_session && !IsOriginWhitelistedInPublicSession()) {
- CompleteFunctionWithError(identity_constants::kUserNotSignedIn);
+ CompleteFunctionWithError(IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kNotWhitelistedInPublicSession));
return;
}
@@ -243,10 +267,11 @@ void IdentityGetAuthTokenFunction::OnReceivedExtensionAccountInfo(
!IdentityManagerFactory::GetForProfile(GetProfile())
->HasAccountWithRefreshToken(account_info->account_id)) {
if (!ShouldStartSigninFlow()) {
- CompleteFunctionWithError(
+ IdentityGetAuthTokenError error(
IsBrowserSigninAllowed(GetProfile())
- ? identity_constants::kUserNotSignedIn
- : identity_constants::kBrowserSigninNotAllowed);
+ ? IdentityGetAuthTokenError::State::kUserNotSignedIn
+ : IdentityGetAuthTokenError::State::kBrowserSigninNotAllowed);
+ CompleteFunctionWithError(error);
return;
}
// Display a login prompt.
@@ -303,14 +328,16 @@ void IdentityGetAuthTokenFunction::CompleteAsyncRun(ResponseValue response) {
void IdentityGetAuthTokenFunction::CompleteFunctionWithResult(
const std::string& access_token) {
+ RecordFunctionResult(IdentityGetAuthTokenError(), remote_consent_approved_);
CompleteAsyncRun(OneArgument(std::make_unique<base::Value>(access_token)));
}
void IdentityGetAuthTokenFunction::CompleteFunctionWithError(
- const std::string& error) {
+ const IdentityGetAuthTokenError& error) {
TRACE_EVENT_NESTABLE_ASYNC_INSTANT1("identity", "CompleteFunctionWithError",
- this, "error", error);
- CompleteAsyncRun(Error(error));
+ this, "error", error.ToString());
+ RecordFunctionResult(error, remote_consent_approved_);
+ CompleteAsyncRun(Error(error.ToString()));
}
bool IdentityGetAuthTokenFunction::ShouldStartSigninFlow() {
@@ -394,14 +421,17 @@ void IdentityGetAuthTokenFunction::StartMintTokenFlow(
if (type == IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE) {
// GAIA told us to do a consent UI.
- CompleteFunctionWithError(identity_constants::kNoGrant);
+ CompleteFunctionWithError(IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kGaiaConsentInteractionRequired));
return;
}
if (!id_api->mint_queue()->empty(
IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE, token_key_)) {
// Another call is going through a consent UI.
- CompleteFunctionWithError(identity_constants::kNoGrant);
+ CompleteFunctionWithError(
+ IdentityGetAuthTokenError(IdentityGetAuthTokenError::State::
+ kGaiaConsentInteractionAlreadyRunning));
return;
}
}
@@ -437,7 +467,9 @@ void IdentityGetAuthTokenFunction::StartMintToken(
// Always force minting token for ChromeOS kiosk app and public session.
if (user_manager::UserManager::Get()->IsLoggedInAsPublicAccount() &&
!IsOriginWhitelistedInPublicSession()) {
- CompleteFunctionWithError(identity_constants::kUserNotSignedIn);
+ CompleteFunctionWithError(
+ IdentityGetAuthTokenError(IdentityGetAuthTokenError::State::
+ kNotWhitelistedInPublicSession));
return;
}
@@ -556,8 +588,8 @@ void IdentityGetAuthTokenFunction::OnMintTokenFailure(
break;
}
- CompleteFunctionWithError(std::string(identity_constants::kAuthFailure) +
- error.ToString());
+ CompleteFunctionWithError(
+ IdentityGetAuthTokenError::FromMintTokenAuthError(error.ToString()));
}
void IdentityGetAuthTokenFunction::OnIssueAdviceSuccess(
@@ -614,6 +646,20 @@ void IdentityGetAuthTokenFunction::OnRefreshTokenUpdatedForAccount(
}
}
+bool IdentityGetAuthTokenFunction::TryRecoverFromServiceAuthError(
+ const GoogleServiceAuthError& error) {
+ // If this is really an authentication error and not just a transient
+ // network error, then we show signin UI if appropriate.
+ if (error.state() != GoogleServiceAuthError::CONNECTION_FAILED &&
+ error.state() != GoogleServiceAuthError::SERVICE_UNAVAILABLE) {
+ if (ShouldStartSigninFlow()) {
+ StartSigninFlow();
+ return true;
+ }
+ }
+ return false;
+}
+
void IdentityGetAuthTokenFunction::OnPrimaryAccountSet(
const CoreAccountInfo& primary_account_info) {
if (account_listening_mode_ != AccountListeningMode::kListeningPrimaryAccount)
@@ -635,7 +681,8 @@ void IdentityGetAuthTokenFunction::OnPrimaryAccountSet(
void IdentityGetAuthTokenFunction::SigninFailed() {
TRACE_EVENT_NESTABLE_ASYNC_INSTANT0("identity", "SigninFailed", this);
- CompleteFunctionWithError(identity_constants::kUserNotSignedIn);
+ CompleteFunctionWithError(IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kSignInFailed));
}
void IdentityGetAuthTokenFunction::OnGaiaFlowFailure(
@@ -643,43 +690,40 @@ void IdentityGetAuthTokenFunction::OnGaiaFlowFailure(
GoogleServiceAuthError service_error,
const std::string& oauth_error) {
CompleteMintTokenFlow();
- std::string error;
+ IdentityGetAuthTokenError error;
switch (failure) {
case GaiaWebAuthFlow::WINDOW_CLOSED:
- error = identity_constants::kUserRejected;
+ error = IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kGaiaFlowRejected);
break;
case GaiaWebAuthFlow::INVALID_REDIRECT:
- error = identity_constants::kInvalidRedirect;
+ error = IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kInvalidRedirect);
break;
case GaiaWebAuthFlow::SERVICE_AUTH_ERROR:
- // If this is really an authentication error and not just a transient
- // network error, then we show signin UI if appropriate.
- if (service_error.state() != GoogleServiceAuthError::CONNECTION_FAILED &&
- service_error.state() !=
- GoogleServiceAuthError::SERVICE_UNAVAILABLE) {
- if (ShouldStartSigninFlow()) {
- StartSigninFlow();
- return;
- }
+ if (TryRecoverFromServiceAuthError(service_error)) {
+ return;
}
- error = std::string(identity_constants::kAuthFailure) +
- service_error.ToString();
+ error = IdentityGetAuthTokenError::FromGaiaFlowAuthError(
+ service_error.ToString());
break;
case GaiaWebAuthFlow::OAUTH_ERROR:
- error = MapOAuth2ErrorToDescription(oauth_error);
+ error = IdentityGetAuthTokenError::FromOAuth2Error(oauth_error);
break;
case GaiaWebAuthFlow::LOAD_FAILED:
- error = identity_constants::kPageLoadFailure;
+ error = IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kPageLoadFailure);
break;
default:
NOTREACHED() << "Unexpected error from gaia web auth flow: " << failure;
- error = identity_constants::kInvalidRedirect;
+ error = IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kInvalidRedirect);
break;
}
@@ -706,27 +750,36 @@ void IdentityGetAuthTokenFunction::OnGaiaFlowCompleted(
void IdentityGetAuthTokenFunction::OnGaiaRemoteConsentFlowFailed(
GaiaRemoteConsentFlow::Failure failure) {
CompleteMintTokenFlow();
- std::string error;
+ IdentityGetAuthTokenError error;
switch (failure) {
case GaiaRemoteConsentFlow::WINDOW_CLOSED:
- error = identity_constants::kUserRejected;
+ error = IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kRemoteConsentFlowRejected);
break;
case GaiaRemoteConsentFlow::SET_ACCOUNTS_IN_COOKIE_FAILED:
- error = identity_constants::kSetAccountsInCookieFailure;
+ error = IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kSetAccountsInCookieFailure);
break;
case GaiaRemoteConsentFlow::LOAD_FAILED:
- error = identity_constants::kPageLoadFailure;
+ error = IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kRemoteConsentPageLoadFailure);
break;
case GaiaRemoteConsentFlow::INVALID_CONSENT_RESULT:
- error = identity_constants::kInvalidConsentResult;
+ error = IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kInvalidConsentResult);
break;
case GaiaRemoteConsentFlow::NO_GRANT:
- error = identity_constants::kNoGrant;
+ error =
+ IdentityGetAuthTokenError(IdentityGetAuthTokenError::State::kNoGrant);
+ break;
+
+ case GaiaRemoteConsentFlow::NONE:
+ NOTREACHED();
break;
}
@@ -739,13 +792,15 @@ void IdentityGetAuthTokenFunction::OnGaiaRemoteConsentFlowApproved(
TRACE_EVENT_NESTABLE_ASYNC_INSTANT1(
"identity", "OnGaiaRemoteConsentFlowApproved", this, "gaia_id", gaia_id);
DCHECK(!consent_result.empty());
+ remote_consent_approved_ = true;
base::Optional<AccountInfo> account =
IdentityManagerFactory::GetForProfile(GetProfile())
->FindExtendedAccountInfoForAccountWithRefreshTokenByGaiaId(gaia_id);
if (!account) {
CompleteMintTokenFlow();
- CompleteFunctionWithError(identity_constants::kUserNotSignedIn);
+ CompleteFunctionWithError(IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kRemoteConsentUserNotSignedIn));
return;
}
@@ -755,7 +810,8 @@ void IdentityGetAuthTokenFunction::OnGaiaRemoteConsentFlowApproved(
->GetPrimaryAccountId();
if (primary_account_id != account->account_id) {
CompleteMintTokenFlow();
- CompleteFunctionWithError(identity_constants::kUserNonPrimary);
+ CompleteFunctionWithError(IdentityGetAuthTokenError(
+ IdentityGetAuthTokenError::State::kRemoteConsentUserNonPrimary));
return;
}
}
@@ -795,8 +851,13 @@ void IdentityGetAuthTokenFunction::OnGetAccessTokenComplete(
TRACE_EVENT_NESTABLE_ASYNC_END1("identity", "GetAccessToken", this, "error",
error.ToString());
- OnGaiaFlowFailure(GaiaWebAuthFlow::SERVICE_AUTH_ERROR, error,
- std::string());
+ CompleteMintTokenFlow();
+ if (TryRecoverFromServiceAuthError(error)) {
+ return;
+ }
+ CompleteFunctionWithError(
+ IdentityGetAuthTokenError::FromGetAccessTokenAuthError(
+ error.ToString()));
}
}
@@ -841,7 +902,8 @@ void IdentityGetAuthTokenFunction::OnIdentityAPIShutdown() {
->mint_queue()
->RequestCancel(token_key_, this);
- CompleteFunctionWithError(identity_constants::kCanceled);
+ CompleteFunctionWithError(
+ IdentityGetAuthTokenError(IdentityGetAuthTokenError::State::kCanceled));
}
#if defined(OS_CHROMEOS)
@@ -964,19 +1026,6 @@ bool IdentityGetAuthTokenFunction::HasRefreshTokenForTokenKeyAccount() const {
return identity_manager->HasAccountWithRefreshToken(token_key_.account_id);
}
-std::string IdentityGetAuthTokenFunction::MapOAuth2ErrorToDescription(
- const std::string& error) {
- const char kOAuth2ErrorAccessDenied[] = "access_denied";
- const char kOAuth2ErrorInvalidScope[] = "invalid_scope";
-
- if (error == kOAuth2ErrorAccessDenied)
- return std::string(identity_constants::kUserRejected);
- else if (error == kOAuth2ErrorInvalidScope)
- return std::string(identity_constants::kInvalidScopes);
- else
- return std::string(identity_constants::kAuthFailure) + error;
-}
-
std::string IdentityGetAuthTokenFunction::GetOAuth2ClientId() const {
const OAuth2Info& oauth2_info = OAuth2Info::GetOAuth2Info(extension());
std::string client_id = oauth2_info.client_id;
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 77dae78c32d..48b802ef28c 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
@@ -28,6 +28,7 @@ struct AccessTokenInfo;
} // namespace signin
namespace extensions {
+class IdentityGetAuthTokenError;
// identity.getAuthToken fetches an OAuth 2 function for the
// caller. The request has three sub-flows: non-interactive,
@@ -155,6 +156,11 @@ class IdentityGetAuthTokenFunction : public ExtensionFunction,
void OnPrimaryAccountSet(
const CoreAccountInfo& primary_account_info) override;
+ // Attempts to show the signin UI after the service auth error if this error
+ // isn't transient.
+ // Returns true iff the signin flow was triggered.
+ bool TryRecoverFromServiceAuthError(const GoogleServiceAuthError& error);
+
// ExtensionFunction:
ResponseAction Run() override;
@@ -162,7 +168,7 @@ class IdentityGetAuthTokenFunction : public ExtensionFunction,
void StartAsyncRun();
void CompleteAsyncRun(ResponseValue response);
void CompleteFunctionWithResult(const std::string& access_token);
- void CompleteFunctionWithError(const std::string& error);
+ void CompleteFunctionWithError(const IdentityGetAuthTokenError& error);
// Whether a signin flow should be initiated in the user's current state.
bool ShouldStartSigninFlow();
@@ -202,10 +208,6 @@ class IdentityGetAuthTokenFunction : public ExtensionFunction,
// Checks if there is a master login token to mint tokens for the extension.
bool HasRefreshTokenForTokenKeyAccount() const;
- // Maps OAuth2 protocol errors to an error message returned to the
- // developer in chrome.runtime.lastError.
- std::string MapOAuth2ErrorToDescription(const std::string& error);
-
std::string GetOAuth2ClientId() const;
// Returns true if extensions are restricted to the primary account.
@@ -231,6 +233,8 @@ class IdentityGetAuthTokenFunction : public ExtensionFunction,
RemoteConsentResolutionData resolution_data_;
std::unique_ptr<GaiaRemoteConsentFlow> gaia_remote_consent_flow_;
std::string consent_result_;
+ // Added for debugging https://crbug.com/1091423.
+ bool remote_consent_approved_ = false;
// Invoked when IdentityAPI is shut down.
std::unique_ptr<base::CallbackList<void()>::Subscription>
diff --git a/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc b/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc
index de1e3443c03..c3c748e6d98 100644
--- a/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc
+++ b/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc
@@ -80,7 +80,7 @@ WebAuthFlow::WebAuthFlow(Delegate* delegate,
}
WebAuthFlow::~WebAuthFlow() {
- DCHECK(delegate_ == NULL);
+ DCHECK(!delegate_);
// Stop listening to notifications first since some of the code
// below may generate notifications.
@@ -134,7 +134,7 @@ void WebAuthFlow::Start() {
}
void WebAuthFlow::DetachDelegateAndDelete() {
- delegate_ = NULL;
+ delegate_ = nullptr;
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
}
@@ -170,7 +170,7 @@ void WebAuthFlow::OnAppWindowAdded(AppWindow* app_window) {
void WebAuthFlow::OnAppWindowRemoved(AppWindow* app_window) {
if (app_window->window_key() == app_window_key_ &&
app_window->extension_id() == extension_misc::kIdentityApiUiAppId) {
- app_window_ = NULL;
+ app_window_ = nullptr;
registrar_.RemoveAll();
WebContentsObserver::Observe(nullptr);
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 1d58c0f6f7e..60b1c97a814 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
@@ -12,7 +12,6 @@
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/sequenced_task_runner.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/image_writer_private/operation.h"
@@ -201,7 +200,7 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
success_ = cancel_;
quit_called_ = true;
- base::PostTask(FROM_HERE, {content::BrowserThread::UI}, quit_closure_);
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, quit_closure_);
}
void Shutdown() {
@@ -210,7 +209,7 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest {
image_writer_utility_client_->Shutdown();
quit_called_ = true;
- base::PostTask(FROM_HERE, {content::BrowserThread::UI}, quit_closure_);
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, quit_closure_);
}
static void FillFile(const base::FilePath& path, char pattern) {
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc
index 608842bfe5d..582b050d487 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc
@@ -8,7 +8,6 @@
#include "base/bind.h"
#include "base/files/file_util.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/image_writer_private/error_messages.h"
@@ -20,8 +19,6 @@
namespace extensions {
namespace image_writer {
-using content::BrowserThread;
-
namespace {
const int kMD5BufferSize = 1024;
@@ -129,16 +126,16 @@ void Operation::Finish() {
CleanUp();
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&OperationManager::OnComplete, manager_, extension_id_));
}
void Operation::Error(const std::string& error_message) {
DCHECK(IsRunningInCorrectSequence());
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&OperationManager::OnError, manager_, extension_id_,
stage_, progress_, error_message));
@@ -158,8 +155,8 @@ void Operation::SetProgress(int progress) {
progress_ = progress;
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&OperationManager::OnProgress, manager_,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&OperationManager::OnProgress, manager_,
extension_id_, stage_, progress_));
}
@@ -172,8 +169,8 @@ void Operation::SetStage(image_writer_api::Stage stage) {
stage_ = stage;
progress_ = 0;
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&OperationManager::OnProgress, manager_,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&OperationManager::OnProgress, manager_,
extension_id_, stage_, progress_));
}
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc
index 5140db323c9..746ca29eacf 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc
@@ -5,7 +5,6 @@
#include <stdint.h>
#include "base/bind.h"
-#include "base/task/post_task.h"
#include "chrome/browser/extensions/api/image_writer_private/error_messages.h"
#include "chrome/browser/extensions/api/image_writer_private/operation.h"
#include "chromeos/dbus/dbus_thread_manager.h"
@@ -26,8 +25,8 @@ namespace {
void ClearImageBurner() {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&ClearImageBurner));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&ClearImageBurner));
return;
}
@@ -45,8 +44,8 @@ void Operation::Write(const base::Closure& continuation) {
// Note this has to be run on the FILE thread to avoid concurrent access.
AddCleanUpFunction(base::BindOnce(&ClearImageBurner));
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&Operation::UnmountVolumes, this, continuation));
}
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc
index e069f5f485a..bb46532fd22 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc
@@ -15,6 +15,7 @@
#include <memory>
+#include "base/logging.h"
#include "base/memory/scoped_refptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc
index cc3d4473c73..fe3d9928022 100644
--- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc
@@ -45,7 +45,7 @@ TEST_F(ImageWriterFromFileTest, InvalidFile) {
test_utils_.GetDevicePath().AsUTF8Unsafe(),
base::FilePath(FILE_PATH_LITERAL("/var/tmp")));
- base::DeleteFile(test_utils_.GetImagePath(), false);
+ base::DeleteFile(test_utils_.GetImagePath());
EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, _, _)).Times(0);
EXPECT_CALL(manager_, OnComplete(kDummyExtensionId)).Times(0);
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 942e3587a50..6b78d3f8de1 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
@@ -6,7 +6,6 @@
#include "base/bind.h"
#include "base/run_loop.h"
-#include "base/task/post_task.h"
#include "chrome/browser/extensions/api/image_writer_private/error_messages.h"
#include "chrome/browser/extensions/api/image_writer_private/test_utils.h"
#include "chrome/test/base/testing_profile.h"
@@ -137,15 +136,7 @@ class ImageWriterWriteFromUrlOperationTest : public ImageWriterUnitTestBase {
MockOperationManager manager_;
};
-// Crashes on Tsan. http://crbug.com/859317
-#if defined(THREAD_SANITIZER)
-#define MAYBE_SelectTargetWithoutExtension DISABLED_SelectTargetWithoutExtension
-#define MAYBE_SelectTargetWithExtension DISABLED_SelectTargetWithExtension
-#else
-#define MAYBE_SelectTargetWithoutExtension SelectTargetWithoutExtension
-#define MAYBE_SelectTargetWithExtension SelectTargetWithExtension
-#endif
-TEST_F(ImageWriterWriteFromUrlOperationTest, MAYBE_SelectTargetWithoutExtension) {
+TEST_F(ImageWriterWriteFromUrlOperationTest, SelectTargetWithoutExtension) {
scoped_refptr<WriteFromUrlOperationForTest> operation =
CreateOperation(GURL("http://localhost/foo/bar"), "");
@@ -160,7 +151,7 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, MAYBE_SelectTargetWithoutExtension)
content::RunAllTasksUntilIdle();
}
-TEST_F(ImageWriterWriteFromUrlOperationTest, MAYBE_SelectTargetWithExtension) {
+TEST_F(ImageWriterWriteFromUrlOperationTest, SelectTargetWithExtension) {
scoped_refptr<WriteFromUrlOperationForTest> operation =
CreateOperation(GURL("http://localhost/foo/bar.zip"), "");
@@ -173,9 +164,6 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, MAYBE_SelectTargetWithExtension) {
operation->Cancel();
}
-#undef MAYBE_SelectTargetWithoutExtension
-#undef MAYBE_SelectTargetWithExtension
-
TEST_F(ImageWriterWriteFromUrlOperationTest, DownloadFile) {
// This test actually triggers the URL fetch code, which will drain the
@@ -242,10 +230,8 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, VerifyFile) {
// soon.
operation->VerifyDownload(base::Bind(
[](base::OnceClosure quit_closure) {
- base::PostTask(
- FROM_HERE,
- {content::BrowserThread::UI, base::TaskPriority::USER_VISIBLE},
- std::move(quit_closure));
+ content::GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE})
+ ->PostTask(FROM_HERE, std::move(quit_closure));
},
run_loop.QuitClosure()));
diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc
index 62d7d390b82..37ea54f92ab 100644
--- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc
+++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc
@@ -10,14 +10,14 @@
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "extensions/browser/extension_registry.h"
-#include "ui/base/ime/ime_bridge.h"
+#include "ui/base/ime/chromeos/ime_bridge.h"
namespace input_ime = extensions::api::input_ime;
namespace KeyEventHandled = extensions::api::input_ime::KeyEventHandled;
namespace SetComposition = extensions::api::input_ime::SetComposition;
namespace CommitText = extensions::api::input_ime::CommitText;
namespace SendKeyEvents = extensions::api::input_ime::SendKeyEvents;
-using input_method::InputMethodEngineBase;
+using chromeos::InputMethodEngineBase;
namespace {
const char kErrorRouterNotAvailable[] = "The router is not available.";
diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h
index 0c4eaac6687..934a51efa74 100644
--- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h
+++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h
@@ -14,8 +14,8 @@
#include "base/scoped_observer.h"
#include "base/values.h"
#include "build/build_config.h"
+#include "chrome/browser/chromeos/input_method/input_method_engine_base.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/input_method/input_method_engine_base.h"
#include "chrome/common/extensions/api/input_ime.h"
#include "components/keyed_service/core/keyed_service.h"
#include "extensions/browser/browser_context_keyed_api_factory.h"
@@ -31,8 +31,6 @@
#if defined(OS_CHROMEOS)
#include "chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h"
-#elif defined(OS_LINUX) || defined(OS_WIN)
-#include "chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h"
#endif // defined(OS_CHROMEOS)
class Profile;
@@ -40,19 +38,21 @@ class Profile;
namespace ui {
class IMEEngineHandlerInterface;
-class ImeObserver : public input_method::InputMethodEngineBase::Observer {
+using chromeos::InputMethodEngineBase;
+
+class ImeObserver : public InputMethodEngineBase::Observer {
public:
ImeObserver(const std::string& extension_id, Profile* profile);
~ImeObserver() override = default;
- // input_method::InputMethodEngineBase::Observer overrides.
+ // InputMethodEngineBase::Observer overrides.
void OnActivate(const std::string& component_id) override;
void OnFocus(const IMEEngineHandlerInterface::InputContext& context) override;
void OnBlur(int context_id) override;
void OnKeyEvent(
const std::string& component_id,
- const input_method::InputMethodEngineBase::KeyboardEvent& event,
+ const InputMethodEngineBase::KeyboardEvent& event,
IMEEngineHandlerInterface::KeyEventDoneCallback key_data) override;
void OnReset(const std::string& component_id) override;
void OnDeactivated(const std::string& component_id) override;
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 b9dfada4e67..e58f51d6e4f 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
@@ -13,6 +13,7 @@
#include "base/feature_list.h"
#include "base/macros.h"
#include "base/strings/stringprintf.h"
+#include "chrome/browser/chromeos/input_method/assistive_window_properties.h"
#include "chrome/browser/chromeos/input_method/input_method_engine.h"
#include "chrome/browser/chromeos/input_method/native_input_method_engine.h"
#include "chrome/browser/chromeos/login/lock/screen_locker.h"
@@ -43,6 +44,8 @@ namespace SetCursorPosition = extensions::api::input_ime::SetCursorPosition;
namespace SetCandidates = extensions::api::input_ime::SetCandidates;
namespace SetCandidateWindowProperties =
extensions::api::input_ime::SetCandidateWindowProperties;
+namespace SetAssistiveWindowProperties =
+ extensions::api::input_ime::SetAssistiveWindowProperties;
namespace ClearComposition = extensions::api::input_ime::ClearComposition;
namespace OnCompositionBoundsChanged =
extensions::api::input_method_private::OnCompositionBoundsChanged;
@@ -54,9 +57,9 @@ namespace SetSelectionRange =
extensions::api::input_method_private::SetSelectionRange;
namespace FinishComposingText =
extensions::api::input_method_private::FinishComposingText;
-using ui::IMEEngineHandlerInterface;
-using input_method::InputMethodEngineBase;
using chromeos::InputMethodEngine;
+using chromeos::InputMethodEngineBase;
+using ui::IMEEngineHandlerInterface;
namespace {
const char kErrorEngineNotAvailable[] = "The engine is not available.";
@@ -99,6 +102,43 @@ keyboard::KeyboardConfig GetKeyboardConfig() {
return ChromeKeyboardControllerClient::Get()->GetKeyboardConfig();
}
+ui::ime::AssistiveWindowType ConvertAssistiveWindowType(
+ input_ime::AssistiveWindowType type) {
+ switch (type) {
+ case input_ime::ASSISTIVE_WINDOW_TYPE_NONE:
+ return ui::ime::AssistiveWindowType::kNone;
+ case input_ime::ASSISTIVE_WINDOW_TYPE_UNDO:
+ return ui::ime::AssistiveWindowType::kUndoWindow;
+ }
+}
+
+input_ime::AssistiveWindowButton ConvertAssistiveWindowButton(
+ const ui::ime::ButtonId id) {
+ switch (id) {
+ case ui::ime::ButtonId::kNone:
+ case ui::ime::ButtonId::kSmartInputsSettingLink:
+ case ui::ime::ButtonId::kSuggestion:
+ case ui::ime::ButtonId::kLearnMore:
+ return input_ime::ASSISTIVE_WINDOW_BUTTON_NONE;
+ case ui::ime::ButtonId::kUndo:
+ return input_ime::ASSISTIVE_WINDOW_BUTTON_UNDO;
+ case ui::ime::ButtonId::kAddToDictionary:
+ return input_ime::ASSISTIVE_WINDOW_BUTTON_ADDTODICTIONARY;
+ }
+}
+
+input_ime::AssistiveWindowType ConvertAssistiveWindowType(
+ const ui::ime::AssistiveWindowType& type) {
+ switch (type) {
+ case ui::ime::AssistiveWindowType::kNone:
+ case ui::ime::AssistiveWindowType::kEmojiSuggestion:
+ case ui::ime::AssistiveWindowType::kPersonalInfoSuggestion:
+ return input_ime::AssistiveWindowType::ASSISTIVE_WINDOW_TYPE_NONE;
+ case ui::ime::AssistiveWindowType::kUndoWindow:
+ return input_ime::AssistiveWindowType::ASSISTIVE_WINDOW_TYPE_UNDO;
+ }
+}
+
class ImeObserverChromeOS : public ui::ImeObserver {
public:
ImeObserverChromeOS(const std::string& extension_id, Profile* profile)
@@ -106,7 +146,7 @@ class ImeObserverChromeOS : public ui::ImeObserver {
~ImeObserverChromeOS() override = default;
- // input_method::InputMethodEngineBase::Observer overrides.
+ // chromeos::InputMethodEngineBase::Observer overrides.
void OnInputContextUpdate(
const IMEEngineHandlerInterface::InputContext& context) override {
if (extension_id_.empty() ||
@@ -257,6 +297,33 @@ class ImeObserverChromeOS : public ui::ImeObserver {
ImeObserver::OnFocus(context);
}
+ void OnAssistiveWindowButtonClicked(
+ const ui::ime::AssistiveWindowButton& button) override {
+ if (extension_id_.empty() ||
+ !HasListener(input_ime::OnAssistiveWindowButtonClicked::kEventName)) {
+ return;
+ }
+ input_ime::OnAssistiveWindowButtonClicked::Details details;
+ details.button_id = ConvertAssistiveWindowButton(button.id);
+ details.window_type = ConvertAssistiveWindowType(button.window_type);
+
+ std::unique_ptr<base::ListValue> args(
+ input_ime::OnAssistiveWindowButtonClicked::Create(details));
+ DispatchEventToExtension(
+ extensions::events::INPUT_IME_ON_ASSISTIVE_WINDOW_BUTTON_CLICKED,
+ input_ime::OnAssistiveWindowButtonClicked::kEventName, std::move(args));
+ }
+
+ void OnSuggestionsChanged(
+ const std::vector<std::string>& suggestions) override {
+ std::unique_ptr<base::ListValue> args(
+ input_method_private::OnSuggestionsChanged::Create(suggestions));
+ DispatchEventToExtension(
+ extensions::events::INPUT_IME_ON_SUGGESTIONS_CHANGED,
+ input_method_private::OnSuggestionsChanged::kEventName,
+ std::move(args));
+ }
+
private:
// ui::ImeObserver overrides.
void DispatchEventToExtension(
@@ -588,6 +655,33 @@ ExtensionFunction::ResponseAction InputImeHideInputViewFunction::Run() {
}
ExtensionFunction::ResponseAction
+InputImeSetAssistiveWindowPropertiesFunction::Run() {
+ std::string error;
+ InputMethodEngine* engine = GetEngineIfActive(
+ Profile::FromBrowserContext(browser_context()), extension_id(), &error);
+ if (!engine) {
+ return RespondNow(Error(InformativeError(error, function_name())));
+ }
+ std::unique_ptr<SetAssistiveWindowProperties::Params> parent_params(
+ SetAssistiveWindowProperties::Params::Create(*args_));
+ const SetAssistiveWindowProperties::Params::Parameters& params =
+ parent_params->parameters;
+ const input_ime::AssistiveWindowProperties& window = params.properties;
+ chromeos::AssistiveWindowProperties assistive_window;
+
+ assistive_window.visible = window.visible;
+ assistive_window.type = ConvertAssistiveWindowType(window.type);
+ if (window.announce_string)
+ assistive_window.announce_string = *window.announce_string;
+
+ engine->SetAssistiveWindowProperties(params.context_id, assistive_window,
+ &error);
+ if (!error.empty())
+ return RespondNow(Error(InformativeError(error, function_name())));
+ return RespondNow(OneArgument(std::make_unique<base::Value>(true)));
+}
+
+ExtensionFunction::ResponseAction
InputImeSetCandidateWindowPropertiesFunction::Run() {
std::unique_ptr<SetCandidateWindowProperties::Params> parent_params(
SetCandidateWindowProperties::Params::Create(*args_));
diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h
index 36c279aba15..aa03b45186b 100644
--- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h
+++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h
@@ -68,6 +68,18 @@ class InputImeSetCursorPositionFunction : public ExtensionFunction {
ResponseAction Run() override;
};
+class InputImeSetAssistiveWindowPropertiesFunction : public ExtensionFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("input.ime.setAssistiveWindowProperties",
+ INPUT_IME_SETASSISTIVEWINDOWPROPERTIES)
+
+ protected:
+ ~InputImeSetAssistiveWindowPropertiesFunction() override = default;
+
+ // ExtensionFunction:
+ ResponseAction Run() override;
+};
+
class InputImeSetMenuItemsFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("input.ime.setMenuItems", INPUT_IME_SETMENUITEMS)
@@ -176,7 +188,7 @@ class InputImeEventRouter : public InputImeEventRouterBase {
void UnregisterAllImes(const std::string& extension_id);
chromeos::InputMethodEngine* GetEngine(const std::string& extension_id);
- input_method::InputMethodEngineBase* GetEngineIfActive(
+ chromeos::InputMethodEngineBase* GetEngineIfActive(
const std::string& extension_id,
std::string* error) override;
diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc
deleted file mode 100644
index 64c0f13ffe2..00000000000
--- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc
+++ /dev/null
@@ -1,416 +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 file is for non-chromeos (win & linux) functions, such as
-// chrome.input.ime.activate, chrome.input.ime.createWindow and
-// chrome.input.ime.onSelectionChanged.
-// TODO(azurewei): May refactor the code structure by using delegate or
-// redesign the API to remove this platform-specific file in the future.
-
-#include "chrome/browser/extensions/api/input_ime/input_ime_api.h"
-
-#include <memory>
-
-#include "base/bind.h"
-#include "base/macros.h"
-#include "base/values.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/browser/ui/browser_finder.h"
-#include "chrome/browser/ui/browser_window.h"
-#include "chrome/browser/ui/input_method/input_method_engine.h"
-#include "chrome/common/extensions/api/input_ime.h"
-#include "extensions/browser/extension_prefs.h"
-#include "ui/base/ime/ime_bridge.h"
-#include "ui/gfx/geometry/rect.h"
-
-namespace input_ime = extensions::api::input_ime;
-namespace OnCompositionBoundsChanged =
- extensions::api::input_ime::OnCompositionBoundsChanged;
-using ui::IMEEngineHandlerInterface;
-using input_method::InputMethodEngine;
-using input_method::InputMethodEngineBase;
-
-namespace input_ime = extensions::api::input_ime;
-
-namespace {
-
-const char kErrorEngineNotActive[] = "The engine is not active.";
-const char kErrorRouterNotAvailable[] = "The router is not available.";
-const char kErrorPermissionDenied[] = "User denied permission.";
-const char kErrorCouldNotFindActiveBrowser[] =
- "Cannot find the active browser.";
-const char kErrorNotCalledFromUserAction[] =
- "This API is only allowed to be called from a user action.";
-
-// A preference determining whether to hide the warning bubble next time.
-// Not used for now.
-const char kPrefWarningBubbleNeverShow[] = "skip_ime_warning_bubble";
-
-// A preference to see whether the API has never been called, or it's the first
-// time to call since loaded the extension.
-// This is used from make an exception for user_gesture checking: no need the
-// check when restarting chrome.
-const char kPrefNeverActivatedSinceLoaded[] = "never_activated_since_loaded";
-
-// A preference to see whether the extension is the last active extension.
-const char kPrefLastActiveEngine[] = "last_activated_ime_engine";
-
-class ImeBridgeObserver : public ui::IMEBridgeObserver {
- public:
- void OnRequestSwitchEngine() override {
- Browser* browser = chrome::FindLastActive();
- if (!browser)
- return;
- extensions::InputImeEventRouter* router =
- extensions::GetInputImeEventRouter(browser->profile());
- if (!router)
- return;
- ui::IMEBridge::Get()->SetCurrentEngineHandler(router->active_engine());
- }
- void OnInputContextHandlerChanged() override {}
-};
-
-class ImeObserverNonChromeOS : public ui::ImeObserver {
- public:
- ImeObserverNonChromeOS(const std::string& extension_id, Profile* profile)
- : ImeObserver(extension_id, profile) {}
-
- ~ImeObserverNonChromeOS() override = default;
-
- void OnCompositionBoundsChanged(
- const std::vector<gfx::Rect>& bounds) override {
- if (extension_id_.empty() || bounds.empty() ||
- !HasListener(OnCompositionBoundsChanged::kEventName))
- return;
-
- std::vector<input_ime::Bounds> bounds_list;
- for (const auto& bound : bounds) {
- input_ime::Bounds bounds_value;
- bounds_value.left = bound.x();
- bounds_value.top = bound.y();
- bounds_value.width = bound.width();
- bounds_value.height = bound.height();
- bounds_list.push_back(std::move(bounds_value));
- }
-
- std::unique_ptr<base::ListValue> args(
- OnCompositionBoundsChanged::Create(bounds_list));
-
- DispatchEventToExtension(
- extensions::events::INPUT_IME_ON_COMPOSITION_BOUNDS_CHANGED,
- OnCompositionBoundsChanged::kEventName, std::move(args));
- }
-
- private:
- // ImeObserver overrides.
- void DispatchEventToExtension(
- extensions::events::HistogramValue histogram_value,
- const std::string& event_name,
- std::unique_ptr<base::ListValue> args) override {
- auto event = std::make_unique<extensions::Event>(
- histogram_value, event_name, std::move(args), profile_);
- extensions::EventRouter::Get(profile_)
- ->DispatchEventToExtension(extension_id_, std::move(event));
- }
-
- std::string GetCurrentScreenType() override { return "normal"; }
-
- DISALLOW_COPY_AND_ASSIGN(ImeObserverNonChromeOS);
-};
-
-} // namespace
-
-namespace extensions {
-
-InputMethodEngine* GetEngineIfActive(content::BrowserContext* browser_context,
- const std::string& extension_id,
- std::string* error) {
- Profile* profile = Profile::FromBrowserContext(browser_context);
- InputImeEventRouter* event_router = GetInputImeEventRouter(profile);
- DCHECK(event_router) << kErrorRouterNotAvailable;
- InputMethodEngine* engine = static_cast<InputMethodEngine*>(
- event_router->GetEngineIfActive(extension_id, error));
- return engine;
-}
-
-void InputImeAPI::OnExtensionLoaded(content::BrowserContext* browser_context,
- const Extension* extension) {
- // No-op if called multiple times.
- ui::IMEBridge::Initialize();
- if (!observer_) {
- observer_ = std::make_unique<ImeBridgeObserver>();
- ui::IMEBridge::Get()->AddObserver(observer_.get());
- }
-
- // Set the preference kPrefNeverActivatedSinceLoaded true to indicate
- // input.ime.activate API has been never called since loaded.
- Profile* profile = Profile::FromBrowserContext(browser_context);
- ExtensionPrefs::Get(profile)->UpdateExtensionPref(
- extension->id(), kPrefNeverActivatedSinceLoaded,
- std::make_unique<base::Value>(true));
-}
-
-void InputImeAPI::OnExtensionUnloaded(content::BrowserContext* browser_context,
- const Extension* extension,
- UnloadedExtensionReason reason) {
- InputImeEventRouter* event_router =
- GetInputImeEventRouter(Profile::FromBrowserContext(browser_context));
- if (event_router) {
- // Records the extension is not the last active IME engine.
- ExtensionPrefs::Get(Profile::FromBrowserContext(browser_context))
- ->UpdateExtensionPref(extension->id(), kPrefLastActiveEngine,
- std::make_unique<base::Value>(false));
- event_router->DeleteInputMethodEngine(extension->id());
- }
-}
-
-void InputImeAPI::OnListenerAdded(const EventListenerInfo& details) {}
-
-InputImeEventRouter::InputImeEventRouter(Profile* profile)
- : InputImeEventRouterBase(profile), active_engine_(nullptr) {}
-
-InputImeEventRouter::~InputImeEventRouter() {
- if (active_engine_)
- DeleteInputMethodEngine(active_engine_->GetExtensionId());
-}
-
-InputMethodEngineBase* InputImeEventRouter::GetEngineIfActive(
- const std::string& extension_id,
- std::string* error) {
- if (ui::IMEBridge::Get()->GetCurrentEngineHandler() && active_engine_ &&
- active_engine_->GetExtensionId() == extension_id) {
- return active_engine_;
- } else {
- LOG(WARNING) << kErrorEngineNotActive << " extension id: " << extension_id;
- *error = kErrorEngineNotActive;
- return nullptr;
- }
-}
-
-void InputImeEventRouter::SetActiveEngine(const std::string& extension_id) {
- // Records the extension is the last active IME engine.
- ExtensionPrefs::Get(GetProfile())
- ->UpdateExtensionPref(extension_id, kPrefLastActiveEngine,
- std::make_unique<base::Value>(true));
- if (active_engine_) {
- if (active_engine_->GetExtensionId() == extension_id) {
- active_engine_->Enable(std::string());
- ui::IMEBridge::Get()->SetCurrentEngineHandler(active_engine_);
- return;
- }
- // Records the extension is not the last active IME engine.
- ExtensionPrefs::Get(GetProfile())
- ->UpdateExtensionPref(active_engine_->GetExtensionId(),
- kPrefLastActiveEngine,
- std::make_unique<base::Value>(false));
- DeleteInputMethodEngine(active_engine_->GetExtensionId());
- }
-
- std::unique_ptr<input_method::InputMethodEngine> engine(
- new input_method::InputMethodEngine());
- std::unique_ptr<InputMethodEngineBase::Observer> observer(
- new ImeObserverNonChromeOS(extension_id, GetProfile()));
- engine->Initialize(std::move(observer), extension_id.c_str(), GetProfile());
- engine->Enable(std::string());
- active_engine_ = engine.release();
- ui::IMEBridge::Get()->SetCurrentEngineHandler(active_engine_);
-}
-
-void InputImeEventRouter::DeleteInputMethodEngine(
- const std::string& extension_id) {
- if (active_engine_ && active_engine_->GetExtensionId() == extension_id) {
- active_engine_->Disable();
- ui::IMEBridge::Get()->SetCurrentEngineHandler(nullptr);
- delete active_engine_;
- active_engine_ = nullptr;
- }
-}
-
-// static
-bool InputImeActivateFunction::disable_bubble_for_testing_ = false;
-
-ExtensionFunction::ResponseAction InputImeActivateFunction::Run() {
- Profile* profile = Profile::FromBrowserContext(browser_context());
- InputImeEventRouter* event_router = GetInputImeEventRouter(profile);
- if (!event_router)
- return RespondNow(
- Error(InformativeError(kErrorEngineNotActive, function_name())));
-
- ExtensionPrefs* prefs = ExtensionPrefs::Get(profile);
-
- bool never_activated_since_loaded = false;
- bool last_active_ime_engine = false;
-
- if (prefs->ReadPrefAsBoolean(extension_id(), kPrefNeverActivatedSinceLoaded,
- &never_activated_since_loaded) &&
- never_activated_since_loaded &&
- prefs->ReadPrefAsBoolean(extension_id(), kPrefLastActiveEngine,
- &last_active_ime_engine) &&
- last_active_ime_engine) {
- // If the extension is the last active IME engine, and the API is called at
- // loading the extension, we can tell the API is called from restarting
- // chrome. No need for user gesture checking.
- event_router->SetActiveEngine(extension_id());
- ExtensionPrefs::Get(profile)->UpdateExtensionPref(
- extension_id(), kPrefNeverActivatedSinceLoaded,
- std::make_unique<base::Value>(false));
- return RespondNow(NoArguments());
- }
- // The API has already been called at least once.
- ExtensionPrefs::Get(profile)->UpdateExtensionPref(
- extension_id(), kPrefNeverActivatedSinceLoaded,
- std::make_unique<base::Value>(false));
-
- // Otherwise, this API is only allowed to be called from a user action.
- if (!user_gesture())
- return RespondNow(Error(
- InformativeError(kErrorNotCalledFromUserAction, function_name())));
-
- // Disable using the warning bubble for testing.
- if (disable_bubble_for_testing_) {
- event_router->SetActiveEngine(extension_id());
- return RespondNow(NoArguments());
- }
-
- // Disables the warning bubble since we don't need run-time checking anymore.
- bool warning_bubble_never_show = true;
- if (warning_bubble_never_show) {
- // If user allows to activate the extension without showing the warning
- // bubble, sets the active engine directly.
- // Otherwise, the extension will be activated when the user presses the 'OK'
- // button on the warning bubble.
- event_router->SetActiveEngine(extension_id());
- return RespondNow(NoArguments());
- }
-
- // TODO(azurewei): Remove the warning bubble related codes.
- Browser* browser = chrome::FindLastActiveWithProfile(profile);
- if (!browser)
- return RespondNow(Error(
- InformativeError(kErrorCouldNotFindActiveBrowser, function_name())));
-
- // Creates and shows the warning bubble. The ImeWarningBubble is self-owned,
- // it deletes itself when closed.
- browser->window()->ShowImeWarningBubble(
- extension(),
- base::Bind(&InputImeActivateFunction::OnPermissionBubbleFinished, this));
- return RespondLater();
-}
-
-void InputImeActivateFunction::OnPermissionBubbleFinished(
- ImeWarningBubblePermissionStatus status) {
- if (status == ImeWarningBubblePermissionStatus::DENIED ||
- status == ImeWarningBubblePermissionStatus::ABORTED) {
- // Fails to activate the extension.
- Respond(Error(InformativeError(kErrorPermissionDenied, function_name())));
- return;
- }
-
- DCHECK(status == ImeWarningBubblePermissionStatus::GRANTED ||
- status == ImeWarningBubblePermissionStatus::GRANTED_AND_NEVER_SHOW);
-
- // Activates this extension if user presses the 'OK' button.
- Profile* profile = Profile::FromBrowserContext(browser_context());
- InputImeEventRouter* event_router = GetInputImeEventRouter(profile);
- if (!event_router) {
- Respond(Error(InformativeError(kErrorEngineNotActive, function_name())));
- return;
- }
- event_router->SetActiveEngine(extension_id());
-
- if (status == ImeWarningBubblePermissionStatus::GRANTED_AND_NEVER_SHOW) {
- // Updates the extension preference if user checks the 'Never show this
- // again' check box. So we can activate the extension directly next time.
- ExtensionPrefs::Get(profile)->UpdateExtensionPref(
- extension_id(), kPrefWarningBubbleNeverShow,
- std::make_unique<base::Value>(true));
- }
-
- Respond(NoArguments());
-}
-
-ExtensionFunction::ResponseAction InputImeDeactivateFunction::Run() {
- std::string error;
- InputMethodEngine* engine =
- GetEngineIfActive(browser_context(), extension_id(), &error);
- if (!engine) {
- return RespondNow(Error(InformativeError(error, function_name())));
- }
- ui::IMEBridge::Get()->SetCurrentEngineHandler(nullptr);
- if (engine)
- engine->CloseImeWindows();
- return RespondNow(NoArguments());
-}
-
-ExtensionFunction::ResponseAction InputImeCreateWindowFunction::Run() {
- // Using input_ime::CreateWindow::Params::Create() causes the link errors on
- // Windows, only if the method name is 'createWindow'.
- // So doing the by-hand parameter unpacking here.
- // TODO(shuchen,rdevlin.cronin): investigate the root cause for the link
- // errors.
- const base::DictionaryValue* params = nullptr;
- args_->GetDictionary(0, &params);
- EXTENSION_FUNCTION_VALIDATE(params);
- input_ime::CreateWindowOptions options;
- input_ime::CreateWindowOptions::Populate(*params, &options);
-
- gfx::Rect bounds(0, 0, 100, 100); // Default bounds.
- if (options.bounds.get()) {
- bounds.set_x(options.bounds->left);
- bounds.set_y(options.bounds->top);
- bounds.set_width(options.bounds->width);
- bounds.set_height(options.bounds->height);
- }
-
- std::string error;
- InputMethodEngine* engine =
- GetEngineIfActive(browser_context(), extension_id(), &error);
- if (!engine)
- return RespondNow(Error(InformativeError(error, function_name())));
-
- int frame_id = engine->CreateImeWindow(
- extension(), render_frame_host(),
- options.url.get() ? *options.url : url::kAboutBlankURL,
- options.window_type == input_ime::WINDOW_TYPE_FOLLOWCURSOR
- ? ui::ImeWindow::FOLLOW_CURSOR
- : ui::ImeWindow::NORMAL,
- bounds, &error);
- if (!frame_id)
- return RespondNow(Error(InformativeError(error, function_name())));
-
- std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue());
- result->Set("frameId", std::make_unique<base::Value>(frame_id));
-
- return RespondNow(OneArgument(std::move(result)));
-}
-
-ExtensionFunction::ResponseAction InputImeShowWindowFunction::Run() {
- std::string error;
- InputMethodEngine* engine =
- GetEngineIfActive(browser_context(), extension_id(), &error);
- if (!engine)
- return RespondNow(Error(InformativeError(error, function_name())));
-
- std::unique_ptr<api::input_ime::ShowWindow::Params> params(
- api::input_ime::ShowWindow::Params::Create(*args_));
- EXTENSION_FUNCTION_VALIDATE(params.get());
- engine->ShowImeWindow(params->window_id);
- return RespondNow(NoArguments());
-}
-
-ExtensionFunction::ResponseAction InputImeHideWindowFunction::Run() {
- std::string error;
- InputMethodEngine* engine =
- GetEngineIfActive(browser_context(), extension_id(), &error);
- if (!engine)
- return RespondNow(Error(InformativeError(error, function_name())));
-
- std::unique_ptr<api::input_ime::HideWindow::Params> params(
- api::input_ime::HideWindow::Params::Create(*args_));
- EXTENSION_FUNCTION_VALIDATE(params.get());
- engine->HideImeWindow(params->window_id);
- return RespondNow(NoArguments());
-}
-
-} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h
deleted file mode 100644
index ff9a920c06b..00000000000
--- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h
+++ /dev/null
@@ -1,126 +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_EXTENSIONS_API_INPUT_IME_INPUT_IME_API_NONCHROMEOS_H_
-#define CHROME_BROWSER_EXTENSIONS_API_INPUT_IME_INPUT_IME_API_NONCHROMEOS_H_
-
-#include "chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h"
-#include "chrome/browser/profiles/profile.h"
-#include "extensions/browser/extension_function.h"
-
-class Profile;
-
-namespace input_method {
-class InputMethodEngine;
-} // namespace input_method
-
-// The status indicates whether the permission has been granted or denied when
-// the IME warning bubble has been closed.
-enum class ImeWarningBubblePermissionStatus {
- GRANTED,
- GRANTED_AND_NEVER_SHOW,
- DENIED,
- ABORTED
-};
-
-namespace extensions {
-
-class InputImeEventRouterBase;
-
-class InputImeEventRouter : public InputImeEventRouterBase {
- public:
- explicit InputImeEventRouter(Profile* profile);
- ~InputImeEventRouter() override;
-
- // Gets the input method engine if the extension is active.
- input_method::InputMethodEngineBase* GetEngineIfActive(
- const std::string& extension_id,
- std::string* error) override;
-
- // Actives the extension with new input method engine, and deletes the
- // previous engine if another extension was active.
- void SetActiveEngine(const std::string& extension_id);
-
- input_method::InputMethodEngine* active_engine() {
- return active_engine_;
- }
-
- // Deletes the current input method engine of the specific extension.
- void DeleteInputMethodEngine(const std::string& extension_id);
-
- private:
- // The active input method engine.
- input_method::InputMethodEngine* active_engine_;
-
- DISALLOW_COPY_AND_ASSIGN(InputImeEventRouter);
-};
-
-class InputImeCreateWindowFunction : public ExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("input.ime.createWindow", INPUT_IME_CREATEWINDOW)
-
- protected:
- ~InputImeCreateWindowFunction() override = default;
-
- // ExtensionFunction:
- ExtensionFunction::ResponseAction Run() override;
-};
-
-class InputImeShowWindowFunction : public ExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("input.ime.showWindow", INPUT_IME_SHOWWINDOW)
-
- protected:
- ~InputImeShowWindowFunction() override = default;
-
- // ExtensionFunction:
- ExtensionFunction::ResponseAction Run() override;
-};
-
-class InputImeHideWindowFunction : public ExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("input.ime.hideWindow", INPUT_IME_HIDEWINDOW)
-
- protected:
- ~InputImeHideWindowFunction() override = default;
-
- // ExtensionFunction:
- ExtensionFunction::ResponseAction Run() override;
-};
-
-class InputImeActivateFunction : public ExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("input.ime.activate", INPUT_IME_ACTIVATE)
-
- // During testing we can disable showing a warning bubble by setting this flag
- // to true, so that the extension can be activated directly.
- static bool disable_bubble_for_testing_;
-
- protected:
- ~InputImeActivateFunction() override = default;
-
- // ExtensionFunction:
- ResponseAction Run() override;
-
- private:
- // Called when the user finishes interacting with the warning bubble.
- // |status| indicates whether the user allows or denies to activate the
- // extension.
- void OnPermissionBubbleFinished(ImeWarningBubblePermissionStatus status);
-};
-
-class InputImeDeactivateFunction : public ExtensionFunction {
- public:
- DECLARE_EXTENSION_FUNCTION("input.ime.deactivate", INPUT_IME_DEACTIVATE)
-
- protected:
- ~InputImeDeactivateFunction() override = default;
-
- // ExtensionFunction:
- ResponseAction Run() override;
-};
-
-} // namespace extensions
-
-#endif // CHROME_BROWSER_EXTENSIONS_API_INPUT_IME_INPUT_IME_API_NONCHROMEOS_H_
diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h
index 3d832e8e3a9..6d3edec518b 100644
--- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h
+++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h
@@ -10,8 +10,8 @@
#include <utility>
#include "base/macros.h"
+#include "chrome/browser/chromeos/input_method/input_method_engine_base.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/input_method/input_method_engine_base.h"
#include "ui/base/ime/ime_engine_handler_interface.h"
namespace extensions {
@@ -22,7 +22,7 @@ class InputImeEventRouterBase {
virtual ~InputImeEventRouterBase();
// Gets the input method engine if the extension is active.
- virtual input_method::InputMethodEngineBase* GetEngineIfActive(
+ virtual chromeos::InputMethodEngineBase* GetEngineIfActive(
const std::string& extension_id,
std::string* error) = 0;
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 340c2c0f3c6..5cc290e45f8 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
@@ -188,7 +188,8 @@ std::vector<std::string> GetSortedThirdPartyIMEs(
LanguageSettingsPrivateGetLanguageListFunction::
LanguageSettingsPrivateGetLanguageListFunction()
- : chrome_details_(this) {}
+ : chrome_details_(this),
+ language_list_(std::make_unique<base::ListValue>()) {}
LanguageSettingsPrivateGetLanguageListFunction::
~LanguageSettingsPrivateGetLanguageListFunction() = default;
@@ -212,7 +213,7 @@ LanguageSettingsPrivateGetLanguageListFunction::Run() {
std::move(spellcheck_languages));
// Build the language list.
- std::unique_ptr<base::ListValue> language_list(new base::ListValue);
+ language_list_->Clear();
#if defined(OS_CHROMEOS)
const std::unordered_set<std::string> allowed_ui_locales(
GetAllowedLanguages(chrome_details_.GetProfile()->GetPrefs()));
@@ -243,7 +244,7 @@ LanguageSettingsPrivateGetLanguageListFunction::Run() {
}
#endif // defined(OS_CHROMEOS)
- language_list->Append(language.ToValue());
+ language_list_->Append(language.ToValue());
}
#if defined(OS_CHROMEOS)
@@ -255,13 +256,54 @@ LanguageSettingsPrivateGetLanguageListFunction::Run() {
language.code = chromeos::extension_ime_util::kArcImeLanguage;
language.display_name =
l10n_util::GetStringUTF8(IDS_SETTINGS_LANGUAGES_KEYBOARD_APPS);
- language_list->Append(language.ToValue());
+ language_list_->Append(language.ToValue());
}
#endif // defined(OS_CHROMEOS)
- return RespondNow(OneArgument(std::move(language_list)));
+#if defined(OS_WIN)
+ if (spellcheck::UseBrowserSpellChecker()) {
+ if (!base::FeatureList::IsEnabled(
+ spellcheck::kWinDelaySpellcheckServiceInit)) {
+ // Platform dictionary support already determined at browser startup.
+ UpdateSupportedPlatformDictionaries();
+ } else {
+ // Asynchronously load the dictionaries to determine platform support.
+ SpellcheckService* service =
+ SpellcheckServiceFactory::GetForContext(browser_context());
+ AddRef(); // Balanced in OnDictionariesInitialized
+ service->InitializeDictionaries(
+ base::BindOnce(&LanguageSettingsPrivateGetLanguageListFunction::
+ OnDictionariesInitialized,
+ base::Unretained(this)));
+ return RespondLater();
+ }
+ }
+#endif // defined(OS_WIN)
+
+ return RespondNow(OneArgument(std::move(language_list_)));
}
+#if defined(OS_WIN)
+void LanguageSettingsPrivateGetLanguageListFunction::
+ OnDictionariesInitialized() {
+ UpdateSupportedPlatformDictionaries();
+ Respond(OneArgument(std::move(language_list_)));
+ // Matches the AddRef in Run().
+ Release();
+}
+
+void LanguageSettingsPrivateGetLanguageListFunction::
+ UpdateSupportedPlatformDictionaries() {
+ SpellcheckService* service =
+ SpellcheckServiceFactory::GetForContext(browser_context());
+ for (auto& language_val : language_list_->GetList()) {
+ if (service->UsesWindowsDictionary(*language_val.FindStringKey("code"))) {
+ language_val.SetBoolKey("supportsSpellcheck", new bool(true));
+ }
+ }
+}
+#endif // defined(OS_WIN)
+
LanguageSettingsPrivateEnableLanguageFunction::
LanguageSettingsPrivateEnableLanguageFunction()
: chrome_details_(this) {}
@@ -291,7 +333,6 @@ LanguageSettingsPrivateEnableLanguageFunction::Run() {
}
translate_prefs->AddToLanguageList(language_code, /*force_blocked=*/false);
- translate_prefs->ResetRecentTargetLanguage();
return RespondNow(NoArguments());
}
@@ -325,7 +366,9 @@ LanguageSettingsPrivateDisableLanguageFunction::Run() {
}
translate_prefs->RemoveFromLanguageList(language_code);
- translate_prefs->ResetRecentTargetLanguage();
+ if (language_code == translate_prefs->GetRecentTargetLanguage()) {
+ translate_prefs->ResetRecentTargetLanguage();
+ }
return RespondNow(NoArguments());
}
@@ -355,7 +398,6 @@ LanguageSettingsPrivateSetEnableTranslationForLanguageFunction::Run() {
} else {
translate_prefs->BlockLanguage(language_code);
}
- translate_prefs->ResetRecentTargetLanguage();
return RespondNow(NoArguments());
}
@@ -408,7 +450,6 @@ LanguageSettingsPrivateMoveLanguageFunction::Run() {
const int offset = 1;
translate_prefs->RearrangeLanguage(language_code, where, offset,
supported_language_codes);
- translate_prefs->ResetRecentTargetLanguage();
return RespondNow(NoArguments());
}
@@ -450,8 +491,8 @@ LanguageSettingsPrivateGetSpellcheckWordsFunction::Run() {
return RespondLater();
}
-void
-LanguageSettingsPrivateGetSpellcheckWordsFunction::OnCustomDictionaryLoaded() {
+void LanguageSettingsPrivateGetSpellcheckWordsFunction::
+ OnCustomDictionaryLoaded() {
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context());
service->GetCustomDictionary()->RemoveObserver(this);
@@ -459,9 +500,9 @@ LanguageSettingsPrivateGetSpellcheckWordsFunction::OnCustomDictionaryLoaded() {
Release();
}
-void
-LanguageSettingsPrivateGetSpellcheckWordsFunction::OnCustomDictionaryChanged(
- const SpellcheckCustomDictionary::Change& dictionary_change) {
+void LanguageSettingsPrivateGetSpellcheckWordsFunction::
+ OnCustomDictionaryChanged(
+ const SpellcheckCustomDictionary::Change& dictionary_change) {
NOTREACHED() << "SpellcheckCustomDictionary::Observer: "
"OnCustomDictionaryChanged() called before "
"OnCustomDictionaryLoaded()";
@@ -536,8 +577,7 @@ LanguageSettingsPrivateRemoveSpellcheckWordFunction::Run() {
LanguageSettingsPrivateGetTranslateTargetLanguageFunction::
LanguageSettingsPrivateGetTranslateTargetLanguageFunction()
- : chrome_details_(this) {
-}
+ : chrome_details_(this) {}
LanguageSettingsPrivateGetTranslateTargetLanguageFunction::
~LanguageSettingsPrivateGetTranslateTargetLanguageFunction() = default;
@@ -615,8 +655,7 @@ LanguageSettingsPrivateGetInputMethodListsFunction::Run() {
InputMethodDescriptors ext_ime_descriptors;
ime_state->GetInputMethodExtensions(&ext_ime_descriptors);
PopulateInputMethodListFromDescriptors(
- ext_ime_descriptors,
- &input_method_lists.third_party_extension_imes);
+ ext_ime_descriptors, &input_method_lists.third_party_extension_imes);
}
return RespondNow(OneArgument(input_method_lists.ToValue()));
diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h
index 2e745eb503b..4a8a64b7004 100644
--- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h
+++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h
@@ -6,6 +6,7 @@
#define CHROME_BROWSER_EXTENSIONS_API_LANGUAGE_SETTINGS_PRIVATE_LANGUAGE_SETTINGS_PRIVATE_API_H_
#include "base/macros.h"
+#include "build/build_config.h"
#include "chrome/browser/extensions/chrome_extension_function_details.h"
#include "chrome/browser/spellchecker/spellcheck_custom_dictionary.h"
#include "extensions/browser/extension_function.h"
@@ -26,9 +27,16 @@ class LanguageSettingsPrivateGetLanguageListFunction
// ExtensionFunction overrides.
ResponseAction Run() override;
+#if defined(OS_WIN)
+ void OnDictionariesInitialized();
+ void UpdateSupportedPlatformDictionaries();
+#endif // defined(OS_WIN)
+
private:
ChromeExtensionFunctionDetails chrome_details_;
+ std::unique_ptr<base::ListValue> language_list_;
+
DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateGetLanguageListFunction);
};
diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api_unittest.cc
index 6ba4543a9a5..e073c83c7ba 100644
--- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api_unittest.cc
@@ -9,16 +9,21 @@
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_refptr.h"
+#include "base/test/scoped_feature_list.h"
+#include "build/build_config.h"
#include "chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h"
#include "chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.h"
#include "chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_factory.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_service_test_base.h"
+#include "chrome/browser/spellchecker/spellcheck_factory.h"
+#include "chrome/browser/spellchecker/spellcheck_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/test_browser_window.h"
#include "chrome/test/base/testing_profile.h"
#include "components/crx_file/id_util.h"
#include "components/language/core/browser/pref_names.h"
+#include "components/spellcheck/common/spellcheck_features.h"
#include "extensions/browser/event_router_factory.h"
#include "extensions/browser/extension_prefs.h"
@@ -82,6 +87,11 @@ std::unique_ptr<KeyedService> BuildLanguageSettingsPrivateDelegate(
return std::make_unique<MockLanguageSettingsPrivateDelegate>(profile);
}
+std::unique_ptr<KeyedService> BuildSpellcheckService(
+ content::BrowserContext* profile) {
+ return std::make_unique<SpellcheckService>(static_cast<Profile*>(profile));
+}
+
} // namespace
class LanguageSettingsPrivateApiTest : public ExtensionServiceTestBase {
@@ -89,6 +99,27 @@ class LanguageSettingsPrivateApiTest : public ExtensionServiceTestBase {
LanguageSettingsPrivateApiTest() = default;
~LanguageSettingsPrivateApiTest() override = default;
+ protected:
+ void RunGetLanguageListTest();
+
+ virtual void InitFeatures() {
+#if defined(OS_WIN)
+ // Force Windows hybrid spellcheck to be enabled.
+ feature_list_.InitAndEnableFeature(spellcheck::kWinUseBrowserSpellChecker);
+#endif // defined(OS_WIN)
+ }
+
+#if defined(OS_WIN)
+ virtual void AddSpellcheckLanguagesForTesting(
+ const std::vector<std::string>& spellcheck_languages_for_testing) {
+ SpellcheckServiceFactory::GetInstance()
+ ->GetForContext(profile())
+ ->InitWindowsDictionaryLanguages(spellcheck_languages_for_testing);
+ }
+
+ base::test::ScopedFeatureList feature_list_;
+#endif // defined(OS_WIN)
+
private:
void SetUp() override {
ExtensionServiceTestBase::SetUp();
@@ -96,8 +127,14 @@ class LanguageSettingsPrivateApiTest : public ExtensionServiceTestBase {
EventRouterFactory::GetInstance()->SetTestingFactory(
profile(), base::BindRepeating(&BuildEventRouter));
+ InitFeatures();
+
LanguageSettingsPrivateDelegateFactory::GetInstance()->SetTestingFactory(
profile(), base::BindRepeating(&BuildLanguageSettingsPrivateDelegate));
+
+ // Use SetTestingFactoryAndUse to force creation and initialization.
+ SpellcheckServiceFactory::GetInstance()->SetTestingFactoryAndUse(
+ profile(), base::BindRepeating(&BuildSpellcheckService));
}
std::unique_ptr<TestBrowserWindow> browser_window_;
@@ -146,6 +183,121 @@ TEST_F(LanguageSettingsPrivateApiTest, GetSpellcheckDictionaryStatusesTest) {
EXPECT_EQ(expected, *actual);
}
+TEST_F(LanguageSettingsPrivateApiTest, GetLanguageListTest) {
+ RunGetLanguageListTest();
+}
+
+void LanguageSettingsPrivateApiTest::RunGetLanguageListTest() {
+ struct LanguageToTest {
+ std::string accept_language;
+ std::string windows_dictionary_name; // Empty string indicates to not use
+ // fake Windows dictionary
+ bool is_preferred_language;
+ bool is_spellcheck_support_expected;
+ };
+
+ std::vector<LanguageToTest> languages_to_test = {
+ // Languages with both Windows and Hunspell spellcheck support.
+ // GetLanguageList should always report spellchecking to be supported for
+ // these languages, regardless of whether a language pack is installed or
+ // if it is a preferred language.
+ {"fr", "fr-FR", true, true},
+ {"de", "de-DE", false, true},
+ {"es-MX", "", true, true},
+ {"fa", "", false, true},
+ {"gl", "", true, false},
+ {"zu", "", false, false},
+ // Finnish with Filipino language pack (string in string).
+ {"fi", "fil", true, false},
+ // Sesotho with Asturian language pack (string in string).
+ {"st", "ast", true, false},
+ };
+
+ // A few more test cases for non-Hunspell languages. These languages do have
+ // Windows spellcheck support depending on the OS version. GetLanguageList
+ // only reports spellchecking is supported for these languages if the language
+ // pack is installed.
+#if defined(OS_WIN)
+ if (spellcheck::WindowsVersionSupportsSpellchecker()) {
+ languages_to_test.push_back({"ar", "ar-SA", true, true});
+ languages_to_test.push_back({"bn", "bn-IN", false, true});
+ } else {
+ languages_to_test.push_back({"ar", "ar-SA", true, false});
+ languages_to_test.push_back({"bn", "bn-IN", false, false});
+ }
+#else
+ languages_to_test.push_back({"ar", "ar-SA", true, false});
+ languages_to_test.push_back({"bn", "bn-IN", false, false});
+#endif // defined(OS_WIN)
+
+ // Initialize accept languages prefs.
+ std::vector<std::string> accept_languages;
+ for (auto& language_to_test : languages_to_test) {
+ if (language_to_test.is_preferred_language) {
+ accept_languages.push_back(language_to_test.accept_language);
+ }
+ }
+
+ std::string accept_languages_string = base::JoinString(accept_languages, ",");
+ DVLOG(2) << "Setting accept languages preferences to: "
+ << accept_languages_string;
+ profile()->GetPrefs()->SetString(language::prefs::kAcceptLanguages,
+ accept_languages_string);
+
+#if defined(OS_WIN)
+ // Add fake Windows dictionaries using InitWindowsDictionaryLanguages.
+ std::vector<std::string> windows_spellcheck_languages_for_testing;
+ for (auto& language_to_test : languages_to_test) {
+ if (!language_to_test.windows_dictionary_name.empty()) {
+ windows_spellcheck_languages_for_testing.push_back(
+ language_to_test.windows_dictionary_name);
+ DVLOG(2) << "Will set fake Windows spellcheck dictionary for testing: "
+ << language_to_test.windows_dictionary_name;
+ }
+ }
+
+ AddSpellcheckLanguagesForTesting(windows_spellcheck_languages_for_testing);
+#endif // defined(OS_WIN)
+
+ auto function =
+ base::MakeRefCounted<LanguageSettingsPrivateGetLanguageListFunction>();
+
+ std::unique_ptr<base::Value> result =
+ api_test_utils::RunFunctionAndReturnSingleResult(function.get(), "[]",
+ profile());
+
+ ASSERT_NE(nullptr, result) << function->GetError();
+ EXPECT_TRUE(result->is_list());
+
+ size_t languages_to_test_found_count = 0;
+ for (auto& language_val : result->GetList()) {
+ EXPECT_TRUE(language_val.is_dict());
+ std::string* language_code_ptr = language_val.FindStringKey("code");
+ ASSERT_NE(nullptr, language_code_ptr);
+ std::string language_code = *language_code_ptr;
+ EXPECT_FALSE(language_code.empty());
+
+ const base::Optional<bool> maybe_supports_spellcheck =
+ language_val.FindBoolKey("supportsSpellcheck");
+ const bool supports_spellcheck = maybe_supports_spellcheck.has_value()
+ ? maybe_supports_spellcheck.value()
+ : false;
+
+ for (auto& language_to_test : languages_to_test) {
+ if (language_to_test.accept_language == language_code) {
+ DVLOG(2) << "*** Found language code being tested=" << language_code
+ << ", supportsSpellcheck=" << supports_spellcheck << " ***";
+ EXPECT_EQ(language_to_test.is_spellcheck_support_expected,
+ supports_spellcheck);
+ languages_to_test_found_count++;
+ break;
+ }
+ }
+ }
+
+ EXPECT_EQ(languages_to_test.size(), languages_to_test_found_count);
+}
+
#if defined(OS_CHROMEOS)
namespace {
@@ -337,4 +489,34 @@ TEST_F(LanguageSettingsPrivateApiTest, RemoveInputMethodTest) {
#endif // OS_CHROMEOS
+#if defined(OS_WIN)
+class LanguageSettingsPrivateApiTestDelayInit
+ : public LanguageSettingsPrivateApiTest {
+ public:
+ LanguageSettingsPrivateApiTestDelayInit() = default;
+
+ protected:
+ void InitFeatures() override {
+ // Force Windows hybrid spellcheck and delayed initialization of the
+ // spellcheck service to be enabled.
+ feature_list_.InitWithFeatures(
+ /*enabled_features=*/{spellcheck::kWinUseBrowserSpellChecker,
+ spellcheck::kWinDelaySpellcheckServiceInit},
+ /*disabled_features=*/{});
+ }
+
+ void AddSpellcheckLanguagesForTesting(
+ const std::vector<std::string>& spellcheck_languages_for_testing)
+ override {
+ SpellcheckServiceFactory::GetInstance()
+ ->GetForContext(profile())
+ ->AddSpellcheckLanguagesForTesting(spellcheck_languages_for_testing);
+ }
+};
+
+TEST_F(LanguageSettingsPrivateApiTestDelayInit, GetLanguageListTest) {
+ RunGetLanguageListTest();
+}
+#endif // defined(OS_WIN)
+
} // namespace extensions
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 a35e419d0e0..5a581df3758 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
@@ -5,12 +5,15 @@
#include "chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.h"
#include "base/bind.h"
+#include "base/test/scoped_feature_list.h"
+#include "build/build_config.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/extension_service_test_base.h"
#include "chrome/browser/spellchecker/spellcheck_factory.h"
#include "chrome/browser/spellchecker/spellcheck_service.h"
#include "chrome/test/base/testing_profile.h"
#include "components/spellcheck/browser/pref_names.h"
+#include "components/spellcheck/common/spellcheck_features.h"
#include "components/spellcheck/spellcheck_buildflags.h"
#include "content/public/browser/notification_service.h"
#include "extensions/browser/event_router_factory.h"
@@ -45,6 +48,12 @@ class LanguageSettingsPrivateDelegateTest
EventRouterFactory::GetInstance()->SetTestingFactory(
profile(), base::BindRepeating(&BuildEventRouter));
+#if defined(OS_WIN)
+ // Tests were designed assuming Hunspell dictionary used and may fail when
+ // Windows spellcheck is enabled by default.
+ feature_list_.InitAndDisableFeature(spellcheck::kWinUseBrowserSpellChecker);
+#endif // defined(OS_WIN)
+
base::ListValue language_codes;
language_codes.AppendString("fr");
profile()->GetPrefs()->Set(spellcheck::prefs::kSpellCheckDictionaries,
@@ -89,6 +98,9 @@ class LanguageSettingsPrivateDelegateTest
run_loop_->Quit();
}
+#if defined(OS_WIN)
+ base::test::ScopedFeatureList feature_list_;
+#endif // defined(OS_WIN)
std::unique_ptr<LanguageSettingsPrivateDelegate> delegate_;
std::unique_ptr<base::RunLoop> run_loop_;
};
diff --git a/chromium/chrome/browser/extensions/api/management/DEPS b/chromium/chrome/browser/extensions/api/management/DEPS
new file mode 100644
index 00000000000..bd0ce11d35b
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/management/DEPS
@@ -0,0 +1,10 @@
+specific_include_rules = {
+ # This DEPS violation snuck in while there was a bug in the checkdeps tool.
+ # https://crbug.com/1084826
+ "chrome_management_api_delegate\.cc": [
+ "+chrome/browser/apps/app_service/app_launch_params.h",
+ "+chrome/browser/apps/app_service/app_service_proxy.h",
+ "+chrome/browser/apps/app_service/app_service_proxy_factory.h",
+ "+chrome/browser/apps/app_service/browser_app_launcher.h",
+ ],
+}
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 b5b0ab58441..75ecb26f2e2 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
@@ -282,7 +282,8 @@ class ChromeAppForLinkDelegate : public extensions::AppForLinkDelegate {
info.icons->reserve(icon_infos.size());
for (const WebApplicationIconInfo& web_app_icon_info : icon_infos) {
extensions::api::management::IconInfo icon_info;
- icon_info.size = web_app_icon_info.square_size_px;
+ if (web_app_icon_info.square_size_px)
+ icon_info.size = *web_app_icon_info.square_size_px;
icon_info.url = web_app_icon_info.url.spec();
info.icons->push_back(std::move(icon_info));
}
diff --git a/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc b/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc
index c3f1fe7ff40..05567b35bde 100644
--- a/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc
@@ -45,7 +45,6 @@
#include "chrome/browser/supervised_user/supervised_user_service.h"
#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
#include "chrome/browser/supervised_user/supervised_user_test_util.h"
-#include "components/web_modal/web_contents_modal_dialog_manager.h"
#include "content/public/browser/gpu_data_manager.h"
#endif
@@ -843,64 +842,87 @@ class TestManagementAPIDelegate : public ManagementAPIDelegate {
// A delegate that allows a child to try to install an extension and tracks
// whether the parent permission dialog would have opened.
-class TestSupervisedUserServiceDelegate : public SupervisedUserServiceDelegate {
+class TestSupervisedUserExtensionsDelegate
+ : public SupervisedUserExtensionsDelegate {
public:
- TestSupervisedUserServiceDelegate() = default;
- ~TestSupervisedUserServiceDelegate() override = default;
+ TestSupervisedUserExtensionsDelegate() = default;
+ ~TestSupervisedUserExtensionsDelegate() override = default;
- // SupervisedUserServiceDelegate:
+ // SupervisedUserExtensionsDelegate:
bool IsChild(content::BrowserContext* context) const override { return true; }
- bool IsSupervisedChildWhoMayInstallExtensions(
- content::BrowserContext* context) const override {
- return is_supervised_child_who_may_install_extensions_;
- }
bool IsExtensionAllowedByParent(
const extensions::Extension& extension,
content::BrowserContext* context) const override {
- return false;
+ SupervisedUserService* supervised_user_service =
+ SupervisedUserServiceFactory::GetForBrowserContext(context);
+ return supervised_user_service->IsExtensionAllowed(extension);
+ }
+
+ void PromptForParentPermissionOrShowError(
+ const extensions::Extension& extension,
+ content::BrowserContext* context,
+ content::WebContents* contents,
+ ParentPermissionDialogDoneCallback parent_permission_callback,
+ base::OnceClosure error_callback) override {
+ // Preconditions.
+ DCHECK(IsChild(context));
+ DCHECK(!IsExtensionAllowedByParent(extension, context));
+
+ if (CanInstallExtensions(context)) {
+ ShowParentPermissionDialogForExtension(
+ extension, context, contents, std::move(parent_permission_callback));
+ } else {
+ ShowExtensionEnableBlockedByParentDialogForExtension(
+ extension, contents, std::move(error_callback));
+ }
+ }
+
+ void set_next_parent_permission_dialog_result(
+ ParentPermissionDialogResult result) {
+ dialog_result_ = result;
}
+
+ int show_dialog_count() const { return show_dialog_count_; }
+ int show_block_dialog_count() const { return show_block_dialog_count_; }
+
+ private:
+ // Returns true if |context| represents a supervised child account who may
+ // install extensions with parent permission.
+ bool CanInstallExtensions(content::BrowserContext* context) const {
+ SupervisedUserService* supervised_user_service =
+ SupervisedUserServiceFactory::GetForBrowserContext(context);
+ return supervised_user_service->CanInstallExtensions();
+ }
+
+ // Shows a parent permission dialog for |extension| and call |done_callback|
+ // when it completes.
void ShowParentPermissionDialogForExtension(
const extensions::Extension& extension,
content::BrowserContext* context,
content::WebContents* contents,
- ParentPermissionDialogDoneCallback done_callback) override {
+ ParentPermissionDialogDoneCallback done_callback) {
++show_dialog_count_;
std::move(done_callback).Run(dialog_result_);
}
+ // Shows a dialog indicating that |extension| has been blocked and call
+ // |done_callback| when it completes.
void ShowExtensionEnableBlockedByParentDialogForExtension(
- const extensions::Extension* extension,
+ const extensions::Extension& extension,
content::WebContents* contents,
- base::OnceClosure done_callback) override {
+ base::OnceClosure done_callback) {
show_block_dialog_count_++;
- std::move(done_callback).Run();
- }
-
- void RecordExtensionEnableBlockedByParentDialogUmaMetric() override {
SupervisedUserExtensionsMetricsRecorder::RecordEnablementUmaMetrics(
SupervisedUserExtensionsMetricsRecorder::EnablementState::
kFailedToEnable);
+ std::move(done_callback).Run();
}
- void set_next_parent_permission_dialog_result(
- ParentPermissionDialogResult result) {
- dialog_result_ = result;
- }
-
- void set_is_supervised_child_who_may_install_extensions(bool value) {
- is_supervised_child_who_may_install_extensions_ = value;
- }
-
- int show_dialog_count() const { return show_dialog_count_; }
- int show_block_dialog_count() const { return show_block_dialog_count_; }
-
- private:
ParentPermissionDialogResult dialog_result_ =
ParentPermissionDialogResult::kParentPermissionFailed;
int show_dialog_count_ = 0;
int show_block_dialog_count_ = 0;
- bool is_supervised_child_who_may_install_extensions_ = true;
};
// Tests for supervised users (child accounts). Supervised users are not allowed
@@ -940,15 +962,15 @@ class ManagementApiSupervisedUserTest : public ManagementApiUnitTest {
management_api_ = ManagementAPI::GetFactoryInstance()->Get(profile());
- // Install a SupervisedUserServiceDelegate to sense the dialog state.
- supervised_user_delegate_ = new TestSupervisedUserServiceDelegate;
- management_api_->set_supervised_user_service_delegate_for_test(
+ // Install a SupervisedUserExtensionsDelegate to sense the dialog state.
+ supervised_user_delegate_ = new TestSupervisedUserExtensionsDelegate;
+ management_api_->set_supervised_user_extensions_delegate_for_test(
base::WrapUnique(supervised_user_delegate_));
}
std::unique_ptr<content::WebContents> web_contents_;
ManagementAPI* management_api_ = nullptr;
- TestSupervisedUserServiceDelegate* supervised_user_delegate_ = nullptr;
+ TestSupervisedUserExtensionsDelegate* supervised_user_delegate_ = nullptr;
};
TEST_F(ManagementApiSupervisedUserTest, SetEnabled_BlockedByParent) {
@@ -974,11 +996,8 @@ TEST_F(ManagementApiSupervisedUserTest, SetEnabled_BlockedByParent) {
// Simulate disabling Permissions for sites, apps and extensions
// in the testing supervised user service delegate used by the Management API.
- supervised_user_delegate_->set_is_supervised_child_who_may_install_extensions(
- false);
- // Ensure that the web contents can be used to create a modal dialog.
- web_modal::WebContentsModalDialogManager::CreateForWebContents(
- web_contents_.get());
+ GetSupervisedUserService()
+ ->SetSupervisedUserExtensionsMayRequestPermissionsPrefForTesting(false);
// The supervised user trying to enable while Permissions for sites, apps and
// extensions is disabled should fail.
@@ -1007,61 +1026,6 @@ TEST_F(ManagementApiSupervisedUserTest, SetEnabled_BlockedByParent) {
SupervisedUserExtensionsMetricsRecorder::kFailedToEnableActionName));
}
-TEST_F(ManagementApiSupervisedUserTest,
- SetEnabled_BlockedByParentNoDialogWhenNoDialogManagerAvailable) {
- // Preconditions.
- ASSERT_TRUE(profile()->IsChild());
-
- base::HistogramTester histogram_tester;
- base::UserActionTester user_action_tester;
-
- base::FilePath base_path = data_dir().AppendASCII("permissions_increase");
- base::FilePath pem_path = base_path.AppendASCII("permissions.pem");
-
- base::FilePath path = base_path.AppendASCII("v1");
- const Extension* extension =
- PackAndInstallCRX(path, pem_path, INSTALL_WITHOUT_LOAD);
- ASSERT_TRUE(extension);
- // The extension should be installed but disabled.
- EXPECT_TRUE(registry()->disabled_extensions().Contains(extension->id()));
- const std::string extension_id = extension->id();
- ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
- EXPECT_TRUE(prefs->HasDisableReason(
- extension_id, disable_reason::DISABLE_CUSTODIAN_APPROVAL_REQUIRED));
-
- // Simulate disabling Permissions for sites, apps and extensions
- // in the testing supervised user service delegate used by the Management API.
- supervised_user_delegate_->set_is_supervised_child_who_may_install_extensions(
- false);
-
- // The supervised user trying to enable while Permissions for sites, apps and
- // extensions is disabled should fail.
- {
- std::string error;
-
- bool success = RunSetEnabledFunction(web_contents_.get(), extension_id,
- /*use_user_gesture=*/true,
- /*accept_dialog=*/true, &error);
- EXPECT_FALSE(success);
- EXPECT_FALSE(error.empty());
- EXPECT_TRUE(registry()->disabled_extensions().Contains(extension_id));
-
- // The block dialog should not have been shown.
- EXPECT_EQ(supervised_user_delegate_->show_block_dialog_count(), 0);
- }
-
- histogram_tester.ExpectUniqueSample(
- SupervisedUserExtensionsMetricsRecorder::kEnablementHistogramName,
- SupervisedUserExtensionsMetricsRecorder::EnablementState::kFailedToEnable,
- 1);
- histogram_tester.ExpectTotalCount(
- SupervisedUserExtensionsMetricsRecorder::kEnablementHistogramName, 1);
- EXPECT_EQ(
- 1,
- user_action_tester.GetActionCount(
- SupervisedUserExtensionsMetricsRecorder::kFailedToEnableActionName));
-}
-
// Tests enabling an extension via management API after it was disabled due to
// permission increase for supervised users.
// Prevents a regression to crbug/1068660.
@@ -1295,7 +1259,7 @@ TEST_F(ManagementApiSupervisedUserTest,
// Now try again with parent approval, and this should succeed.
{
supervised_user_delegate_->set_next_parent_permission_dialog_result(
- SupervisedUserServiceDelegate::ParentPermissionDialogResult::
+ SupervisedUserExtensionsDelegate::ParentPermissionDialogResult::
kParentPermissionReceived);
std::string error;
bool success = RunSetEnabledFunction(web_contents_.get(), extension_id,
@@ -1347,7 +1311,7 @@ TEST_F(ManagementApiSupervisedUserTest, SetEnabled_UnsupportedRequirement) {
// Parent approval should fail because of the unsupported requirements.
{
supervised_user_delegate_->set_next_parent_permission_dialog_result(
- SupervisedUserServiceDelegate::ParentPermissionDialogResult::
+ SupervisedUserExtensionsDelegate::ParentPermissionDialogResult::
kParentPermissionReceived);
std::string error;
bool success = RunSetEnabledFunction(web_contents_.get(), extension->id(),
@@ -1382,7 +1346,7 @@ TEST_F(ManagementApiSupervisedUserTest, SetEnabledDisabled_UmaMetrics) {
// The parent will approve.
supervised_user_delegate_->set_next_parent_permission_dialog_result(
- SupervisedUserServiceDelegate::ParentPermissionDialogResult::
+ SupervisedUserExtensionsDelegate::ParentPermissionDialogResult::
kParentPermissionReceived);
RunSetEnabledFunction(web_contents_.get(), extension->id(),
@@ -1469,7 +1433,7 @@ TEST_F(ManagementApiSupervisedUserTestWithSetup, SetEnabled_ParentApproves) {
// The parent will approve.
supervised_user_delegate_->set_next_parent_permission_dialog_result(
- SupervisedUserServiceDelegate::ParentPermissionDialogResult::
+ SupervisedUserExtensionsDelegate::ParentPermissionDialogResult::
kParentPermissionReceived);
// Simulate a call to chrome.management.setEnabled(). It should succeed.
@@ -1494,7 +1458,7 @@ TEST_F(ManagementApiSupervisedUserTestWithSetup, SetEnabled_ParentDenies) {
// The parent will deny the next dialog.
supervised_user_delegate_->set_next_parent_permission_dialog_result(
- SupervisedUserServiceDelegate::ParentPermissionDialogResult::
+ SupervisedUserExtensionsDelegate::ParentPermissionDialogResult::
kParentPermissionCanceled);
// Simulate a call to chrome.management.setEnabled(). It should not succeed.
@@ -1520,7 +1484,7 @@ TEST_F(ManagementApiSupervisedUserTestWithSetup, SetEnabled_DialogFails) {
// The next dialog will close due to a failure (e.g. network failure while
// looking up parent information).
supervised_user_delegate_->set_next_parent_permission_dialog_result(
- SupervisedUserServiceDelegate::ParentPermissionDialogResult::
+ SupervisedUserExtensionsDelegate::ParentPermissionDialogResult::
kParentPermissionFailed);
// Simulate a call to chrome.management.setEnabled(). It should not succeed.
diff --git a/chromium/chrome/browser/extensions/api/management/management_apitest.cc b/chromium/chrome/browser/extensions/api/management/management_apitest.cc
index aded1d518db..7804dcad939 100644
--- a/chromium/chrome/browser/extensions/api/management/management_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/management/management_apitest.cc
@@ -18,6 +18,7 @@
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/web_applications/components/app_registrar.h"
#include "chrome/browser/web_applications/components/app_shortcut_manager.h"
+#include "chrome/browser/web_applications/components/install_finalizer.h"
#include "chrome/browser/web_applications/components/web_app_helpers.h"
#include "chrome/browser/web_applications/components/web_app_provider_base.h"
#include "chrome/browser/web_applications/test/test_web_app_ui_manager.h"
@@ -36,6 +37,7 @@
#include "extensions/test/result_catcher.h"
#include "extensions/test/test_extension_dir.h"
#include "net/dns/mock_host_resolver.h"
+#include "testing/gtest/include/gtest/gtest.h"
using extensions::Extension;
using extensions::Manifest;
@@ -241,9 +243,12 @@ class InstallReplacementWebAppApiTest : public ExtensionManagementApiTest {
chrome::SetAutoAcceptPWAInstallConfirmationForTesting(true);
const GURL start_url = https_test_server_.GetURL(web_app_start_url);
web_app::AppId web_app_id = web_app::GenerateAppIdFromURL(start_url);
-
auto* provider =
web_app::WebAppProviderBase::GetProviderBase(browser()->profile());
+ // Async legacy finalizer install was causing this test to be flaky (see
+ // crbug.com/1094616).
+ provider->install_finalizer().RemoveLegacyInstallFinalizerForTesting();
+
EXPECT_FALSE(provider->registrar().IsLocallyInstalled(start_url));
EXPECT_EQ(0, static_cast<int>(
provider->ui_manager().GetNumWindowsForApp(web_app_id)));
diff --git a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc
index 68ecb30c5ed..ec72a41d2d6 100644
--- a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc
@@ -87,8 +87,7 @@ class ExtensionHostDestructionObserver
}
// ExtensionHostObserver:
- void OnExtensionHostDestroyed(
- const extensions::ExtensionHost* host) override {
+ void OnExtensionHostDestroyed(extensions::ExtensionHost* host) override {
if (host == host_) {
extension_host_observer_.Remove(host_);
run_loop_.Quit();
diff --git a/chromium/chrome/browser/extensions/api/mdns/mdns_apitest.cc b/chromium/chrome/browser/extensions/api/mdns/mdns_apitest.cc
index 914c9eb0467..b7f9bde94a7 100644
--- a/chromium/chrome/browser/extensions/api/mdns/mdns_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/mdns/mdns_apitest.cc
@@ -49,15 +49,8 @@ class MDnsAPITest : public extensions::ExtensionApiTest {
} // namespace
-// TODO(justinlin): Win Dbg has a workaround that makes RunExtensionSubtest
-// always return true without actually running the test. Remove when fixed.
-#if defined(OS_WIN) && !defined(NDEBUG)
-#define MAYBE_RegisterListener DISABLED_RegisterListener
-#else
-#define MAYBE_RegisterListener RegisterListener
-#endif
// Test loading extension, registering an MDNS listener and dispatching events.
-IN_PROC_BROWSER_TEST_F(MDnsAPITest, MAYBE_RegisterListener) {
+IN_PROC_BROWSER_TEST_F(MDnsAPITest, RegisterListener) {
const std::string& service_type = "_googlecast._tcp.local";
SetUpTestDnsSdRegistry();
@@ -86,15 +79,8 @@ IN_PROC_BROWSER_TEST_F(MDnsAPITest, MAYBE_RegisterListener) {
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
-// TODO(justinlin): Win Dbg has a workaround that makes RunExtensionSubtest
-// always return true without actually running the test. Remove when fixed.
-#if defined(OS_WIN) && !defined(NDEBUG)
-#define MAYBE_ForceDiscovery DISABLED_ForceDiscovery
-#else
-#define MAYBE_ForceDiscovery ForceDiscovery
-#endif
// Test loading extension, registering an MDNS listener and dispatching events.
-IN_PROC_BROWSER_TEST_F(MDnsAPITest, MAYBE_ForceDiscovery) {
+IN_PROC_BROWSER_TEST_F(MDnsAPITest, ForceDiscovery) {
const std::string& service_type = "_googlecast._tcp.local";
SetUpTestDnsSdRegistry();
@@ -120,15 +106,8 @@ IN_PROC_BROWSER_TEST_F(MDnsAPITest, MAYBE_ForceDiscovery) {
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
-// TODO(justinlin): Win Dbg has a workaround that makes RunExtensionSubtest
-// always return true without actually running the test. Remove when fixed.
-#if defined(OS_WIN) && !defined(NDEBUG)
-#define MAYBE_RegisterMultipleListeners DISABLED_RegisterMultipleListeners
-#else
-#define MAYBE_RegisterMultipleListeners RegisterMultipleListeners
-#endif
// Test loading extension and registering multiple listeners.
-IN_PROC_BROWSER_TEST_F(MDnsAPITest, MAYBE_RegisterMultipleListeners) {
+IN_PROC_BROWSER_TEST_F(MDnsAPITest, RegisterMultipleListeners) {
const std::string& service_type = "_googlecast._tcp.local";
const std::string& test_service_type = "_testing._tcp.local";
SetUpTestDnsSdRegistry();
@@ -161,15 +140,8 @@ IN_PROC_BROWSER_TEST_F(MDnsAPITest, MAYBE_RegisterMultipleListeners) {
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
-// TODO(justinlin): Win Dbg has a workaround that makes RunExtensionSubtest
-// always return true without actually running the test. Remove when fixed.
-#if defined(OS_WIN) && !defined(NDEBUG)
-#define MAYBE_RegisterTooManyListeners DISABLED_RegisterTooManyListeners
-#else
-#define MAYBE_RegisterTooManyListeners RegisterTooManyListeners
-#endif
// Test loading extension and registering multiple listeners.
-IN_PROC_BROWSER_TEST_F(MDnsAPITest, MAYBE_RegisterTooManyListeners) {
+IN_PROC_BROWSER_TEST_F(MDnsAPITest, RegisterTooManyListeners) {
SetUpTestDnsSdRegistry();
EXPECT_CALL(*dns_sd_registry_, RegisterDnsSdListener(_)).Times(10);
@@ -182,16 +154,8 @@ IN_PROC_BROWSER_TEST_F(MDnsAPITest, MAYBE_RegisterTooManyListeners) {
<< message_;
}
-// TODO(justinlin): Win Dbg has a workaround that makes RunExtensionSubtest
-// always return true without actually running the test. Remove when fixed.
-#if defined(OS_WIN) && !defined(NDEBUG)
-#define MAYBE_MaxServiceInstancesPerEventConst \
- DISABLED_MaxServiceInstancesPerEventConst
-#else
-#define MAYBE_MaxServiceInstancesPerEventConst MaxServiceInstancesPerEventConst
-#endif
// Test loading extension and registering multiple listeners.
-IN_PROC_BROWSER_TEST_F(MDnsAPITest, MAYBE_MaxServiceInstancesPerEventConst) {
+IN_PROC_BROWSER_TEST_F(MDnsAPITest, MaxServiceInstancesPerEventConst) {
EXPECT_TRUE(RunExtensionSubtest("mdns/api",
"get_max_service_instances.html"));
}
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 ccfb4199428..a3422c55d05 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
@@ -15,7 +15,6 @@
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
-#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
@@ -99,8 +98,7 @@ struct BuiltInHost {
std::unique_ptr<NativeMessageHost> CreateIt2MeHost(
content::BrowserContext* browser_context) {
return remoting::CreateIt2MeNativeMessagingHostForChromeOS(
- base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}),
- base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}),
+ content::GetIOThreadTaskRunner({}), content::GetUIThreadTaskRunner({}),
g_browser_process->policy_service());
}
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 8d1911b6118..d1d51bfa74d 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
@@ -13,7 +13,6 @@
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/process/kill.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h"
@@ -60,7 +59,7 @@ NativeMessageProcessHost::NativeMessageProcessHost(
const std::string& source_extension_id,
const std::string& native_host_name,
std::unique_ptr<NativeProcessLauncher> launcher)
- : client_(NULL),
+ : client_(nullptr),
source_extension_id_(source_extension_id),
native_host_name_(native_host_name),
launcher_(std::move(launcher)),
@@ -72,8 +71,7 @@ NativeMessageProcessHost::NativeMessageProcessHost(
write_pending_(false) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- task_runner_ =
- base::CreateSingleThreadTaskRunner({content::BrowserThread::IO});
+ task_runner_ = content::GetIOThreadTaskRunner({});
}
NativeMessageProcessHost::~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 428ba272fc3..3acc436a7ea 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
@@ -27,7 +27,6 @@
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
@@ -59,8 +58,6 @@
#include <unistd.h>
#endif
-using content::BrowserThread;
-
namespace {
const char kTestMessage[] = "{\"text\": \"Hello.\"}";
@@ -125,8 +122,8 @@ class NativeMessagingTest : public ::testing::Test,
void TearDown() override {
if (native_message_host_) {
- base::DeleteSoon(FROM_HERE, {BrowserThread::IO},
- native_message_host_.release());
+ content::GetIOThreadTaskRunner({})->DeleteSoon(
+ FROM_HERE, native_message_host_.release());
}
base::RunLoop().RunUntilIdle();
}
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 f25164371e1..7b83c3a74ff 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc
@@ -23,11 +23,14 @@
#include "components/keep_alive_registry/keep_alive_types.h"
#include "content/public/test/browser_test.h"
#include "extensions/browser/process_manager.h"
+#include "extensions/common/scoped_worker_based_extensions_channel.h"
#include "extensions/test/result_catcher.h"
namespace extensions {
namespace {
+using ContextType = ExtensionApiTest::ContextType;
+
class NativeMessagingApiTest : public ExtensionApiTest {
protected:
extensions::ScopedTestNativeMessagingHost test_host_;
@@ -43,6 +46,48 @@ IN_PROC_BROWSER_TEST_F(NativeMessagingApiTest, UserLevelNativeMessaging) {
ASSERT_TRUE(RunExtensionTest("native_messaging")) << message_;
}
+// TODO(crbug.com/1094027): Clean up duplicate test coverage.
+class NativeMessagingLazyApiTest
+ : public NativeMessagingApiTest,
+ public testing::WithParamInterface<ContextType> {
+ public:
+ void SetUp() override {
+ NativeMessagingApiTest::SetUp();
+ // Service Workers are currently only available on certain channels, so set
+ // the channel for those tests.
+ if (GetParam() == ContextType::kServiceWorker)
+ current_channel_ = std::make_unique<ScopedWorkerBasedExtensionsChannel>();
+ }
+
+ protected:
+ bool RunLazyTest(const std::string& extension_name) {
+ if (GetParam() == ContextType::kEventPage) {
+ return RunExtensionTest(extension_name);
+ }
+ return RunExtensionTestWithFlags(
+ extension_name, kFlagRunAsServiceWorkerBasedExtension, kFlagNone);
+ }
+
+ std::unique_ptr<ScopedWorkerBasedExtensionsChannel> current_channel_;
+};
+
+INSTANTIATE_TEST_SUITE_P(EventPage,
+ NativeMessagingLazyApiTest,
+ ::testing::Values(ContextType::kEventPage));
+INSTANTIATE_TEST_SUITE_P(ServiceWorker,
+ NativeMessagingLazyApiTest,
+ ::testing::Values(ContextType::kServiceWorker));
+
+IN_PROC_BROWSER_TEST_P(NativeMessagingLazyApiTest, NativeMessagingBasic) {
+ ASSERT_NO_FATAL_FAILURE(test_host_.RegisterTestHost(false));
+ ASSERT_TRUE(RunLazyTest("native_messaging_lazy")) << message_;
+}
+
+IN_PROC_BROWSER_TEST_P(NativeMessagingLazyApiTest, UserLevelNativeMessaging) {
+ ASSERT_NO_FATAL_FAILURE(test_host_.RegisterTestHost(true));
+ ASSERT_TRUE(RunLazyTest("native_messaging_lazy")) << message_;
+}
+
#if !defined(OS_CHROMEOS)
class TestProcessManagerObserver : public ProcessManagerObserver {
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
index 967ebb848e4..f675d66c911 100644
--- 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
@@ -11,7 +11,6 @@
#include "base/bind_helpers.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
-#include "base/task/post_task.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/timer/timer.h"
#include "chrome/browser/browser_process.h"
@@ -75,8 +74,8 @@ class NativeMessagingHostErrorReporter : public NativeMessageHost::Client {
MovableScopedKeepAlive keep_alive(
new ScopedKeepAlive(KeepAliveOrigin::NATIVE_MESSAGING_HOST_ERROR_REPORT,
KeepAliveRestartOption::DISABLED));
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&NativeMessagingHostErrorReporter::ReportOnIoThread,
std::move(host), std::move(keep_alive)));
}
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 5b5b39a5567..439e74947e0 100644
--- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc
+++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc
@@ -23,7 +23,6 @@
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/values.h"
#include "build/build_config.h"
@@ -313,8 +312,8 @@ void NativeProcessLauncherImpl::Core::CallCallbackOnIOThread(
void NativeProcessLauncherImpl::Core::PostErrorResult(
const LaunchedCallback& callback,
LaunchResult error) {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&NativeProcessLauncherImpl::Core::CallCallbackOnIOThread,
this, callback, error, base::Process(), base::File(),
base::File()));
@@ -325,8 +324,8 @@ void NativeProcessLauncherImpl::Core::PostResult(
base::Process process,
base::File read_file,
base::File write_file) {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&NativeProcessLauncherImpl::Core::CallCallbackOnIOThread,
this, callback, RESULT_SUCCESS, std::move(process),
std::move(read_file), std::move(write_file)));
diff --git a/chromium/chrome/browser/extensions/api/notifications/DEPS b/chromium/chrome/browser/extensions/api/notifications/DEPS
new file mode 100644
index 00000000000..bdbc70d13b0
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/notifications/DEPS
@@ -0,0 +1,10 @@
+specific_include_rules = {
+ # This DEPS violation snuck in while there was a bug in the checkdeps tool.
+ # https://crbug.com/1084826
+ "notifications_apitest\.cc": [
+ "+chrome/browser/apps/app_service/app_launch_params.h",
+ "+chrome/browser/apps/app_service/app_service_proxy.h",
+ "+chrome/browser/apps/app_service/app_service_proxy_factory.h",
+ "+chrome/browser/apps/app_service/browser_app_launcher.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 ba017b4199d..31905b3349a 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
@@ -11,7 +11,6 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_util.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_tab_util.h"
@@ -76,8 +75,8 @@ PageCaptureSaveAsMHTMLFunction::PageCaptureSaveAsMHTMLFunction() {
PageCaptureSaveAsMHTMLFunction::~PageCaptureSaveAsMHTMLFunction() {
if (mhtml_file_.get()) {
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&ClearFileReferenceOnIOThread, std::move(mhtml_file_)));
}
}
@@ -200,8 +199,8 @@ void PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest(
void PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile() {
bool success = base::CreateTemporaryFile(&mhtml_path_);
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnIO,
this, success));
}
@@ -226,8 +225,8 @@ void PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnIO(bool success) {
base::TaskShutdownBehavior::BLOCK_SHUTDOWN})
.get());
}
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnUI,
this, success));
}
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.cc b/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.cc
index 413965efe9b..54808bfd323 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.cc
+++ b/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.cc
@@ -36,7 +36,7 @@
#include "components/password_manager/core/browser/compromised_credentials_table.h"
#include "components/password_manager/core/browser/leak_detection/bulk_leak_check.h"
#include "components/password_manager/core/browser/leak_detection/encryption_utils.h"
-#include "components/password_manager/core/browser/ui/compromised_credentials_provider.h"
+#include "components/password_manager/core/browser/ui/compromised_credentials_manager.h"
#include "components/password_manager/core/browser/ui/credential_utils.h"
#include "components/password_manager/core/browser/ui/saved_passwords_presenter.h"
#include "components/password_manager/core/common/password_manager_pref_names.h"
@@ -54,21 +54,17 @@ namespace {
using autofill::PasswordForm;
using password_manager::CanonicalizeUsername;
-using password_manager::CompromiseType;
+using password_manager::CompromiseTypeFlags;
using password_manager::CredentialWithPassword;
using password_manager::LeakCheckCredential;
-using password_manager::PasswordCredentialLess;
using ui::TimeFormat;
using CompromisedCredentialsView =
- password_manager::CompromisedCredentialsProvider::CredentialsView;
+ password_manager::CompromisedCredentialsManager::CredentialsView;
using SavedPasswordsView =
password_manager::SavedPasswordsPresenter::SavedPasswordsView;
using State = password_manager::BulkLeakCheckService::State;
-using CompromisedCredentialSet =
- base::flat_set<CredentialWithPassword, PasswordCredentialLess>;
-
} // namespace
// Key used to attach UserData to a LeakCheckCredential.
@@ -165,35 +161,6 @@ api::passwords_private::PasswordCheckState ConvertPasswordCheckState(
return api::passwords_private::PASSWORD_CHECK_STATE_NONE;
}
-// Computes a map that matches compromised credentials with corresponding saved
-// passwords in the store. This is needed to reflect changes to the underlying
-// password store when a compromised credential gets modified or removed through
-// the UI. Also it allows to inject affiliation information to be displayed in
-// the UI.
-PasswordCheckDelegate::CredentialPasswordsMap
-MapCompromisedCredentialsToSavedPasswords(
- CompromisedCredentialsView compromised_credentials_view,
- SavedPasswordsView saved_passwords) {
- // Create a set to turn queries to look up a matching credential from O(n) to
- // O(log n).
- CompromisedCredentialSet compromised_credentials(
- compromised_credentials_view.begin(), compromised_credentials_view.end());
-
- // Populate the map. The values are vectors, because it is possible that
- // multiple saved passwords match to the same compromised credential. In most
- // cases there should be a 1-1 relationship, though.
- PasswordCheckDelegate::CredentialPasswordsMap passwords_map;
- for (const auto& saved_password : saved_passwords) {
- auto it = compromised_credentials.find(
- password_manager::CredentialView(saved_password));
- if (it != compromised_credentials.end()) {
- passwords_map[*it].push_back(saved_password);
- }
- }
-
- return passwords_map;
-}
-
std::string FormatElapsedTime(base::Time time) {
const base::TimeDelta elapsed_time = base::Time::Now() - time;
if (elapsed_time < base::TimeDelta::FromMinutes(1))
@@ -204,9 +171,7 @@ std::string FormatElapsedTime(base::Time time) {
}
// Helper struct that bundles a CredentialWithPassword with a corresponding
-// passwords_private::CompromiseType. This is necessary to support the both
-// PHISHED_AND_LEAKED case, which does not exists in password_manager's
-// CompromiseType.
+// passwords_private::CompromiseType.
struct CompromisedCredentialAndType {
CredentialWithPassword credential;
api::passwords_private::CompromiseType type;
@@ -214,65 +179,24 @@ struct CompromisedCredentialAndType {
// Orders |compromised_credentials| in such a way that phished credentials
// precede leaked credentials, and that credentials of the same compromise type
-// are ordered by recency. Furthermore it de-duplicates credentials that are
-// both phished and leaked, making sure they only appear once in the final list.
+// are ordered by recency.
std::vector<CompromisedCredentialAndType> OrderCompromisedCredentials(
- CompromisedCredentialsView compromised_credentials) {
- // Partition the compromised credentials into phished and leaked.
- std::vector<CredentialWithPassword> phished_storage;
- std::vector<CredentialWithPassword> leaked_storage;
- std::partition_copy(
- compromised_credentials.begin(), compromised_credentials.end(),
- std::back_inserter(phished_storage), std::back_inserter(leaked_storage),
- [](const auto& credential) {
- return credential.compromise_type == CompromiseType::kPhished;
- });
-
- // Perform a set intersection to find credentials that are both phished and
- // leaked. Operate on flat_sets, since they provide a more convenient API.
- CompromisedCredentialSet phished = std::move(phished_storage);
- CompromisedCredentialSet leaked = std::move(leaked_storage);
- CompromisedCredentialSet phished_and_leaked;
- std::set_intersection(
- phished.begin(), phished.end(), leaked.begin(), leaked.end(),
- std::inserter(phished_and_leaked, phished_and_leaked.end()),
- PasswordCredentialLess());
-
- // Iterate through the phished and leaked credentials and update their
- // timestamp to be the most recent compromise event.
- for (auto& phished_and_leaked : phished_and_leaked) {
- phished_and_leaked.create_time =
- std::max(phished.find(phished_and_leaked)->create_time,
- leaked.find(phished_and_leaked)->create_time);
- }
-
- // Erase phished and leaked credentials from the other two sets.
- auto is_phished_and_leaked = [&](const auto& credential) {
- return phished_and_leaked.contains(credential);
- };
- base::EraseIf(phished, is_phished_and_leaked);
- base::EraseIf(leaked, is_phished_and_leaked);
-
- // Finally move all credentials into a single list, associating with the
+ std::vector<CredentialWithPassword> compromised_credentials) {
+ // Move all credentials into a single list, associating with the
// corresponding CompromiseType.
- const size_t num_phished = phished.size() + phished_and_leaked.size();
std::vector<CompromisedCredentialAndType> results;
results.reserve(compromised_credentials.size());
- for (auto& credential : std::move(phished).extract()) {
- results.push_back({std::move(credential),
- api::passwords_private::COMPROMISE_TYPE_PHISHED});
- }
-
- for (auto& credential : std::move(phished_and_leaked).extract()) {
- results.push_back(
- {std::move(credential),
- api::passwords_private::COMPROMISE_TYPE_PHISHED_AND_LEAKED});
- }
-
- for (auto& credential : std::move(leaked).extract()) {
- results.push_back({std::move(credential),
- api::passwords_private::COMPROMISE_TYPE_LEAKED});
+ for (auto& credential : compromised_credentials) {
+ auto type = static_cast<api::passwords_private::CompromiseType>(
+ credential.compromise_type);
+ results.push_back({std::move(credential), type});
}
+ // Reordering phished credential to the beginning.
+ auto last_phished = std::partition(
+ results.begin(), results.end(), [](const auto& credential) {
+ return credential.type !=
+ api::passwords_private::COMPROMISE_TYPE_LEAKED;
+ });
// By construction the phished credentials precede the leaked credentials in
// |results|. Now sort both groups by their creation date so that most recent
@@ -280,8 +204,8 @@ std::vector<CompromisedCredentialAndType> OrderCompromisedCredentials(
auto create_time_cmp = [](const auto& lhs, const auto& rhs) {
return lhs.credential.create_time > rhs.credential.create_time;
};
- std::sort(results.begin(), results.begin() + num_phished, create_time_cmp);
- std::sort(results.begin() + num_phished, results.end(), create_time_cmp);
+ std::sort(results.begin(), last_phished, create_time_cmp);
+ std::sort(last_phished, results.end(), create_time_cmp);
return results;
}
@@ -293,25 +217,24 @@ PasswordCheckDelegate::PasswordCheckDelegate(Profile* profile)
profile,
ServiceAccessType::EXPLICIT_ACCESS)),
saved_passwords_presenter_(password_store_),
- compromised_credentials_provider_(password_store_,
- &saved_passwords_presenter_),
+ compromised_credentials_manager_(password_store_,
+ &saved_passwords_presenter_),
bulk_leak_check_service_adapter_(
&saved_passwords_presenter_,
BulkLeakCheckServiceFactory::GetForProfile(profile_),
profile_->GetPrefs()) {
observed_saved_passwords_presenter_.Add(&saved_passwords_presenter_);
- observed_compromised_credentials_provider_.Add(
- &compromised_credentials_provider_);
+ observed_compromised_credentials_manager_.Add(
+ &compromised_credentials_manager_);
observed_bulk_leak_check_service_.Add(
BulkLeakCheckServiceFactory::GetForProfile(profile_));
// Instructs the presenter and provider to initialize and built their caches.
- // This will soon after invoke OnCompromisedCredentialsChanged(), which then
- // initializes |credentials_to_forms_| as well. Calls to
+ // This will soon after invoke OnCompromisedCredentialsChanged(). Calls to
// GetCompromisedCredentials() that might happen until then will return an
// empty list.
saved_passwords_presenter_.Init();
- compromised_credentials_provider_.Init();
+ compromised_credentials_manager_.Init();
}
PasswordCheckDelegate::~PasswordCheckDelegate() = default;
@@ -320,7 +243,7 @@ std::vector<api::passwords_private::CompromisedCredential>
PasswordCheckDelegate::GetCompromisedCredentials() {
std::vector<CompromisedCredentialAndType>
ordered_compromised_credential_and_types = OrderCompromisedCredentials(
- compromised_credentials_provider_.GetCompromisedCredentials());
+ compromised_credentials_manager_.GetCompromisedCredentials());
std::vector<api::passwords_private::CompromisedCredential>
compromised_credentials;
@@ -338,7 +261,7 @@ PasswordCheckDelegate::GetCompromisedCredentials() {
// special handling for Android. Here we use affiliation information
// instead of the signon_realm.
const PasswordForm& android_form =
- credentials_to_forms_.at(credential).at(0);
+ compromised_credentials_manager_.GetSavedPasswordsFor(credential)[0];
if (!android_form.app_display_name.empty()) {
api_credential.formatted_origin = android_form.app_display_name;
api_credential.detailed_origin = android_form.app_display_name;
@@ -401,52 +324,26 @@ PasswordCheckDelegate::GetPlaintextCompromisedPassword(
bool PasswordCheckDelegate::ChangeCompromisedCredential(
const api::passwords_private::CompromisedCredential& credential,
base::StringPiece new_password) {
- // Try to obtain the original CredentialWithPassword and try to find it in
- // |credentials_to_forms_|. Return false if either one fails.
+ // Try to obtain the original CredentialWithPassword. Return false if fails.
const CredentialWithPassword* compromised_credential =
FindMatchingCompromisedCredential(credential);
if (!compromised_credential)
return false;
- auto it = credentials_to_forms_.find(*compromised_credential);
- if (it == credentials_to_forms_.end())
- return false;
-
- // Make sure there are matching password forms. Also erase duplicates if there
- // are any.
- const auto& forms = it->second;
- if (forms.empty())
- return false;
-
- for (size_t i = 1; i < forms.size(); ++i)
- password_store_->RemoveLogin(forms[i]);
-
- // Note: We Invoke EditPassword on the presenter rather than UpdateLogin() on
- // the store, so that observers of the presenter get notified of this event.
- return saved_passwords_presenter_.EditPassword(
- forms[0], base::UTF8ToUTF16(new_password));
+ return compromised_credentials_manager_.UpdateCompromisedCredentials(
+ *compromised_credential, new_password);
}
bool PasswordCheckDelegate::RemoveCompromisedCredential(
const api::passwords_private::CompromisedCredential& credential) {
- // Try to obtain the original CredentialWithPassword and try to find it in
- // |credentials_to_forms_|. Return false if either one fails.
+ // Try to obtain the original CredentialWithPassword. Return false if fails.
const CredentialWithPassword* compromised_credential =
FindMatchingCompromisedCredential(credential);
if (!compromised_credential)
return false;
- auto it = credentials_to_forms_.find(*compromised_credential);
- if (it == credentials_to_forms_.end())
- return false;
-
- // Erase all matching credentials from the store. Return whether any
- // credentials were deleted.
- SavedPasswordsView saved_passwords = it->second;
- for (const PasswordForm& saved_password : saved_passwords)
- password_store_->RemoveLogin(saved_password);
-
- return !saved_passwords.empty();
+ return compromised_credentials_manager_.RemoveCompromisedCredential(
+ *compromised_credential);
}
void PasswordCheckDelegate::StartPasswordCheck(
@@ -547,8 +444,6 @@ void PasswordCheckDelegate::OnSavedPasswordsChanged(SavedPasswordsView) {
void PasswordCheckDelegate::OnCompromisedCredentialsChanged(
CompromisedCredentialsView credentials) {
- credentials_to_forms_ = MapCompromisedCredentialsToSavedPasswords(
- credentials, saved_passwords_presenter_.GetSavedPasswords());
if (auto* event_router =
PasswordsPrivateEventRouterFactory::GetForProfile(profile_)) {
event_router->OnCompromisedCredentialsChanged(GetCompromisedCredentials());
@@ -584,24 +479,7 @@ void PasswordCheckDelegate::OnCredentialDone(
const LeakCheckCredential& credential,
password_manager::IsLeaked is_leaked) {
if (is_leaked) {
- // In case the credential is leaked, iterate over all currently saved
- // credentials and mark those as compromised that have the same
- // canonicalized username and password.
- const base::string16 canocalized_username =
- CanonicalizeUsername(credential.username());
- for (const PasswordForm& saved_password :
- saved_passwords_presenter_.GetSavedPasswords()) {
- if (saved_password.password_value == credential.password() &&
- CanonicalizeUsername(saved_password.username_value) ==
- canocalized_username) {
- password_store_->AddCompromisedCredentials({
- .signon_realm = saved_password.signon_realm,
- .username = saved_password.username_value,
- .create_time = base::Time::Now(),
- .compromise_type = CompromiseType::kLeaked,
- });
- }
- }
+ compromised_credentials_manager_.SaveCompromisedCredential(credential);
}
// Update the progress in case there is one.
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.h b/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.h
index c2ec8b18e99..a615f879ae8 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.h
+++ b/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.h
@@ -18,7 +18,7 @@
#include "components/password_manager/core/browser/leak_detection/leak_detection_delegate_interface.h"
#include "components/password_manager/core/browser/password_store.h"
#include "components/password_manager/core/browser/ui/bulk_leak_check_service_adapter.h"
-#include "components/password_manager/core/browser/ui/compromised_credentials_provider.h"
+#include "components/password_manager/core/browser/ui/compromised_credentials_manager.h"
#include "components/password_manager/core/browser/ui/credential_utils.h"
#include "components/password_manager/core/browser/ui/saved_passwords_presenter.h"
@@ -38,17 +38,12 @@ class PasswordCheckProgress;
// with the bulk password check feature.
class PasswordCheckDelegate
: public password_manager::SavedPasswordsPresenter::Observer,
- public password_manager::CompromisedCredentialsProvider::Observer,
- public password_manager::BulkLeakCheckService::Observer {
+ public password_manager::CompromisedCredentialsManager::Observer,
+ public password_manager::BulkLeakCheckServiceInterface::Observer {
public:
using StartPasswordCheckCallback =
PasswordsPrivateDelegate::StartPasswordCheckCallback;
- using CredentialPasswordsMap =
- std::map<password_manager::CredentialWithPassword,
- std::vector<autofill::PasswordForm>,
- password_manager::PasswordCredentialLess>;
-
explicit PasswordCheckDelegate(Profile* profile);
PasswordCheckDelegate(const PasswordCheckDelegate&) = delete;
PasswordCheckDelegate& operator=(const PasswordCheckDelegate&) = delete;
@@ -98,7 +93,7 @@ class PasswordCheckDelegate
// Invokes PasswordsPrivateEventRouter::OnCompromisedCredentialsChanged if
// a valid pointer can be obtained.
void OnCompromisedCredentialsChanged(
- password_manager::CompromisedCredentialsProvider::CredentialsView
+ password_manager::CompromisedCredentialsManager::CredentialsView
credentials) override;
// password_manager::BulkLeakCheckService::Observer:
@@ -126,16 +121,16 @@ class PasswordCheckDelegate
Profile* profile_ = nullptr;
// Handle to the password store, powering both |saved_passwords_presenter_|
- // and |compromised_credentials_provider_|.
+ // and |compromised_credentials_manager_|.
scoped_refptr<password_manager::PasswordStore> password_store_;
- // Used by |compromised_credentials_provider_| to obtain the list of saved
+ // Used by |compromised_credentials_manager_| to obtain the list of saved
// passwords.
password_manager::SavedPasswordsPresenter saved_passwords_presenter_;
// Used to obtain the list of compromised credentials.
- password_manager::CompromisedCredentialsProvider
- compromised_credentials_provider_;
+ password_manager::CompromisedCredentialsManager
+ compromised_credentials_manager_;
// Adapter used to start, monitor and stop a bulk leak check.
password_manager::BulkLeakCheckServiceAdapter
@@ -162,22 +157,16 @@ class PasswordCheckDelegate
password_manager::SavedPasswordsPresenter::Observer>
observed_saved_passwords_presenter_{this};
- // A scoped observer for |compromised_credentials_provider_|.
- ScopedObserver<password_manager::CompromisedCredentialsProvider,
- password_manager::CompromisedCredentialsProvider::Observer>
- observed_compromised_credentials_provider_{this};
+ // A scoped observer for |compromised_credentials_manager_|.
+ ScopedObserver<password_manager::CompromisedCredentialsManager,
+ password_manager::CompromisedCredentialsManager::Observer>
+ observed_compromised_credentials_manager_{this};
// A scoped observer for the BulkLeakCheckService.
- ScopedObserver<password_manager::BulkLeakCheckService,
- password_manager::BulkLeakCheckService::Observer>
+ ScopedObserver<password_manager::BulkLeakCheckServiceInterface,
+ password_manager::BulkLeakCheckServiceInterface::Observer>
observed_bulk_leak_check_service_{this};
- // A map that matches CredentialWithPasswords to corresponding PasswordForms.
- // This is required to inject affiliation information into Android
- // credentials, as well as being able to reflect edits and removals of
- // compromised credentials in the underlying password store.
- CredentialPasswordsMap credentials_to_forms_;
-
// An id generator for compromised credentials. Required to match
// api::passwords_private::CompromisedCredential instances passed to the UI
// with the underlying CredentialWithPassword they are based on.
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate_unittest.cc b/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate_unittest.cc
index 067b79f09b7..ef4fb104178 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate_unittest.cc
@@ -74,6 +74,7 @@ using password_manager::BulkLeakCheckDelegateInterface;
using password_manager::BulkLeakCheckService;
using password_manager::CompromisedCredentials;
using password_manager::CompromiseType;
+using password_manager::CompromiseTypeFlags;
using password_manager::IsLeaked;
using password_manager::LeakCheckCredential;
using password_manager::TestPasswordStore;
@@ -248,6 +249,27 @@ class PasswordCheckDelegateTest : public ::testing::Test {
} // namespace
+TEST_F(PasswordCheckDelegateTest, VerifyCastingOfCompromisedCredentialTypes) {
+ static_assert(
+ static_cast<int>(api::passwords_private::COMPROMISE_TYPE_NONE) ==
+ static_cast<int>(CompromiseTypeFlags::kNotCompromised),
+ "");
+ static_assert(
+ static_cast<int>(api::passwords_private::COMPROMISE_TYPE_LEAKED) ==
+ static_cast<int>(CompromiseTypeFlags::kCredentialLeaked),
+ "");
+ static_assert(
+ static_cast<int>(api::passwords_private::COMPROMISE_TYPE_PHISHED) ==
+ static_cast<int>(CompromiseTypeFlags::kCredentialPhished),
+ "");
+ static_assert(
+ static_cast<int>(
+ api::passwords_private::COMPROMISE_TYPE_PHISHED_AND_LEAKED) ==
+ static_cast<int>(CompromiseTypeFlags::kCredentialLeaked |
+ CompromiseTypeFlags::kCredentialPhished),
+ "");
+}
+
// Sets up the password store with a couple of passwords and compromised
// credentials. Verifies that the result is ordered in such a way that phished
// credentials are before leaked credentials and that within each group
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc
index 15df0b1ca92..c66d3306367 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc
@@ -77,7 +77,16 @@ ResponseAction PasswordsPrivateRemoveSavedPasswordFunction::Run() {
auto parameters =
api::passwords_private::RemoveSavedPassword::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(parameters);
- GetDelegate(browser_context())->RemoveSavedPassword(parameters->id);
+ GetDelegate(browser_context())->RemoveSavedPasswords({parameters->id});
+ return RespondNow(NoArguments());
+}
+
+// PasswordsPrivateRemoveSavedPasswordsFunction
+ResponseAction PasswordsPrivateRemoveSavedPasswordsFunction::Run() {
+ auto parameters =
+ api::passwords_private::RemoveSavedPasswords::Params::Create(*args_);
+ EXTENSION_FUNCTION_VALIDATE(parameters);
+ GetDelegate(browser_context())->RemoveSavedPasswords(parameters->ids);
return RespondNow(NoArguments());
}
@@ -86,7 +95,16 @@ ResponseAction PasswordsPrivateRemovePasswordExceptionFunction::Run() {
auto parameters =
api::passwords_private::RemovePasswordException::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(parameters);
- GetDelegate(browser_context())->RemovePasswordException(parameters->id);
+ GetDelegate(browser_context())->RemovePasswordExceptions({parameters->id});
+ return RespondNow(NoArguments());
+}
+
+// PasswordsPrivateRemovePasswordExceptionsFunction
+ResponseAction PasswordsPrivateRemovePasswordExceptionsFunction::Run() {
+ auto parameters =
+ api::passwords_private::RemovePasswordExceptions::Params::Create(*args_);
+ EXTENSION_FUNCTION_VALIDATE(parameters);
+ GetDelegate(browser_context())->RemovePasswordExceptions(parameters->ids);
return RespondNow(NoArguments());
}
@@ -176,6 +194,16 @@ void PasswordsPrivateGetPasswordExceptionListFunction::GotList(
entries)));
}
+// PasswordsPrivateMovePasswordToAccountFunction
+ResponseAction PasswordsPrivateMovePasswordToAccountFunction::Run() {
+ auto parameters =
+ api::passwords_private::MovePasswordToAccount::Params::Create(*args_);
+ EXTENSION_FUNCTION_VALIDATE(parameters);
+ GetDelegate(browser_context())
+ ->MovePasswordToAccount(parameters->id, GetSenderWebContents());
+ return RespondNow(NoArguments());
+}
+
// PasswordsPrivateImportPasswordsFunction
ResponseAction PasswordsPrivateImportPasswordsFunction::Run() {
GetDelegate(browser_context())->ImportPasswords(GetSenderWebContents());
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h
index b374835ffa2..3505216b22a 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h
+++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h
@@ -54,6 +54,18 @@ class PasswordsPrivateRemoveSavedPasswordFunction : public ExtensionFunction {
ResponseAction Run() override;
};
+class PasswordsPrivateRemoveSavedPasswordsFunction : public ExtensionFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("passwordsPrivate.removeSavedPasswords",
+ PASSWORDSPRIVATE_REMOVESAVEDPASSWORDS)
+
+ protected:
+ ~PasswordsPrivateRemoveSavedPasswordsFunction() override = default;
+
+ // ExtensionFunction overrides.
+ ResponseAction Run() override;
+};
+
class PasswordsPrivateRemovePasswordExceptionFunction
: public ExtensionFunction {
public:
@@ -67,6 +79,19 @@ class PasswordsPrivateRemovePasswordExceptionFunction
ResponseAction Run() override;
};
+class PasswordsPrivateRemovePasswordExceptionsFunction
+ : public ExtensionFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("passwordsPrivate.removePasswordExceptions",
+ PASSWORDSPRIVATE_REMOVEPASSWORDEXCEPTIONS)
+
+ protected:
+ ~PasswordsPrivateRemovePasswordExceptionsFunction() override = default;
+
+ // ExtensionFunction overrides.
+ ResponseAction Run() override;
+};
+
class PasswordsPrivateUndoRemoveSavedPasswordOrExceptionFunction
: public ExtensionFunction {
public:
@@ -131,6 +156,18 @@ class PasswordsPrivateGetPasswordExceptionListFunction
void GotList(const PasswordsPrivateDelegate::ExceptionEntries& entries);
};
+class PasswordsPrivateMovePasswordToAccountFunction : public ExtensionFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("passwordsPrivate.movePasswordToAccount",
+ PASSWORDSPRIVATE_MOVEPASSWORDTOACCOUNT)
+
+ protected:
+ ~PasswordsPrivateMovePasswordToAccountFunction() override = default;
+
+ // ExtensionFunction overrides.
+ ResponseAction Run() override;
+};
+
class PasswordsPrivateImportPasswordsFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("passwordsPrivate.importPasswords",
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc
index eba6dbddfd3..45337a9fd68 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc
@@ -108,6 +108,10 @@ class PasswordsPrivateApiTest : public ExtensionApiTest {
s_test_delegate_->AddCompromisedCredential(id);
}
+ base::Optional<int> last_moved_password() const {
+ return s_test_delegate_->last_moved_password();
+ }
+
private:
TestPasswordsPrivateDelegate* s_test_delegate_ = nullptr;
@@ -127,11 +131,23 @@ IN_PROC_BROWSER_TEST_F(PasswordsPrivateApiTest,
}
IN_PROC_BROWSER_TEST_F(PasswordsPrivateApiTest,
+ RemoveAndUndoRemoveSavedPasswordsBatch) {
+ EXPECT_TRUE(RunPasswordsSubtest("removeAndUndoRemoveSavedPasswordsBatch"))
+ << message_;
+}
+
+IN_PROC_BROWSER_TEST_F(PasswordsPrivateApiTest,
RemoveAndUndoRemovePasswordException) {
EXPECT_TRUE(RunPasswordsSubtest("removeAndUndoRemovePasswordException"))
<< message_;
}
+IN_PROC_BROWSER_TEST_F(PasswordsPrivateApiTest,
+ RemoveAndUndoRemovePasswordExceptionsBatch) {
+ EXPECT_TRUE(RunPasswordsSubtest("removeAndUndoRemovePasswordExceptionsBatch"))
+ << message_;
+}
+
IN_PROC_BROWSER_TEST_F(PasswordsPrivateApiTest, RequestPlaintextPassword) {
EXPECT_TRUE(RunPasswordsSubtest("requestPlaintextPassword")) << message_;
}
@@ -259,4 +275,10 @@ IN_PROC_BROWSER_TEST_F(PasswordsPrivateApiTest, GetPasswordCheckStatus) {
EXPECT_TRUE(RunPasswordsSubtest("getPasswordCheckStatus")) << message_;
}
+IN_PROC_BROWSER_TEST_F(PasswordsPrivateApiTest, MovePasswordToAccount) {
+ EXPECT_FALSE(last_moved_password().has_value());
+ EXPECT_TRUE(RunPasswordsSubtest("movePasswordToAccount")) << message_;
+ EXPECT_EQ(42, last_moved_password());
+}
+
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h
index b1c9d8c20f1..edb030dfe12 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h
+++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h
@@ -65,15 +65,13 @@ class PasswordsPrivateDelegate : public KeyedService {
base::string16 new_username,
base::Optional<base::string16> new_password) = 0;
- // Removes the saved password entry corresponding to the |id| generated for
- // each entry of the password list.
- // |id| the id created when going over the list of saved passwords.
- virtual void RemoveSavedPassword(int id) = 0;
+ // Removes the saved password entries corresponding to the |ids| generated for
+ // each entry of the password list. Any invalid id will be ignored.
+ virtual void RemoveSavedPasswords(const std::vector<int>& ids) = 0;
- // Removes the saved password exception entry corresponding set in the
- // given |id|
- // |id| The id for the exception url entry being removed.
- virtual void RemovePasswordException(int id) = 0;
+ // Removes the password exceptions entries corresponding corresponding to
+ // |ids|. Any invalid id will be ignored.
+ virtual void RemovePasswordExceptions(const std::vector<int>& ids) = 0;
// Undoes the last removal of a saved password or exception.
virtual void UndoRemoveSavedPasswordOrException() = 0;
@@ -92,6 +90,14 @@ class PasswordsPrivateDelegate : public KeyedService {
PlaintextPasswordCallback callback,
content::WebContents* web_contents) = 0;
+ // Moves a password currently stored on the device to being stored in the
+ // signed-in, non-syncing Google Account. The result is a no-op if any of
+ // these is true: |id| is invalid; |id| corresponds to a password already
+ // stored in the account; or the user is not using the account-scoped password
+ // storage.
+ virtual void MovePasswordToAccount(int id,
+ content::WebContents* web_contents) = 0;
+
// Trigger the password import procedure, allowing the user to select a file
// containing passwords to import.
virtual void ImportPasswords(content::WebContents* web_contents) = 0;
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 2aaf4ec2863..b23254c66fc 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
@@ -29,6 +29,7 @@
#include "components/password_manager/core/browser/ui/plaintext_reason.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "components/prefs/pref_service.h"
+#include "components/signin/public/base/signin_metrics.h"
#include "content/public/browser/web_contents.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "ui/base/l10n/l10n_util.h"
@@ -122,6 +123,20 @@ password_manager::PlaintextReason ConvertPlaintextReason(
return password_manager::PlaintextReason::kView;
}
+// Gets all the existing keys in |generator| corresponding to |ids|. If no key
+// is found for an id, it is simply ignored.
+std::vector<std::string> GetSortKeys(
+ const extensions::IdGenerator<std::string>& generator,
+ const std::vector<int> ids) {
+ std::vector<std::string> sort_keys;
+ sort_keys.reserve(ids.size());
+ for (int id : ids) {
+ if (const std::string* sort_key = generator.TryGetKey(id))
+ sort_keys.emplace_back(*sort_key);
+ }
+ return sort_keys;
+}
+
} // namespace
namespace extensions {
@@ -197,28 +212,30 @@ void PasswordsPrivateDelegateImpl::ChangeSavedPassword(
*sort_key, std::move(new_username), std::move(new_password));
}
-void PasswordsPrivateDelegateImpl::RemoveSavedPassword(int id) {
+void PasswordsPrivateDelegateImpl::RemoveSavedPasswords(
+ const std::vector<int>& ids) {
ExecuteFunction(
- base::Bind(&PasswordsPrivateDelegateImpl::RemoveSavedPasswordInternal,
- base::Unretained(this), id));
+ base::Bind(&PasswordsPrivateDelegateImpl::RemoveSavedPasswordsInternal,
+ base::Unretained(this), ids));
}
-void PasswordsPrivateDelegateImpl::RemoveSavedPasswordInternal(int id) {
- const std::string* sort_key = password_id_generator_.TryGetKey(id);
- if (sort_key)
- password_manager_presenter_->RemoveSavedPassword(*sort_key);
+void PasswordsPrivateDelegateImpl::RemoveSavedPasswordsInternal(
+ const std::vector<int>& ids) {
+ password_manager_presenter_->RemoveSavedPasswords(
+ GetSortKeys(password_id_generator_, ids));
}
-void PasswordsPrivateDelegateImpl::RemovePasswordException(int id) {
- ExecuteFunction(
- base::Bind(&PasswordsPrivateDelegateImpl::RemovePasswordExceptionInternal,
- base::Unretained(this), id));
+void PasswordsPrivateDelegateImpl::RemovePasswordExceptions(
+ const std::vector<int>& ids) {
+ ExecuteFunction(base::Bind(
+ &PasswordsPrivateDelegateImpl::RemovePasswordExceptionsInternal,
+ base::Unretained(this), ids));
}
-void PasswordsPrivateDelegateImpl::RemovePasswordExceptionInternal(int id) {
- const std::string* sort_key = exception_id_generator_.TryGetKey(id);
- if (sort_key)
- password_manager_presenter_->RemovePasswordException(*sort_key);
+void PasswordsPrivateDelegateImpl::RemovePasswordExceptionsInternal(
+ const std::vector<int>& ids) {
+ password_manager_presenter_->RemovePasswordExceptions(
+ GetSortKeys(exception_id_generator_, ids));
}
void PasswordsPrivateDelegateImpl::UndoRemoveSavedPasswordOrException() {
@@ -267,8 +284,10 @@ void PasswordsPrivateDelegateImpl::RequestPlaintextPassword(
std::move(callback).Run(base::nullopt);
return;
}
- ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste)
- .WriteText(*password);
+ ui::ScopedClipboardWriter clipboard_writer(
+ ui::ClipboardBuffer::kCopyPaste);
+ clipboard_writer.WriteText(*password);
+ clipboard_writer.MarkAsConfidential();
std::move(callback).Run(base::string16());
},
std::move(callback));
@@ -325,6 +344,9 @@ void PasswordsPrivateDelegateImpl::SetPasswordList(
entry.username = base::UTF16ToUTF8(form->username_value);
entry.id = password_id_generator_.GenerateId(
password_manager::CreateSortKey(*form));
+ entry.frontend_id = password_frontend_id_generator_.GenerateId(
+ password_manager::CreateSortKey(*form,
+ password_manager::IgnoreStore(true)));
if (!form->federation_origin.opaque()) {
entry.federation_text.reset(new std::string(l10n_util::GetStringFUTF8(
@@ -360,6 +382,10 @@ void PasswordsPrivateDelegateImpl::SetPasswordExceptionList(
current_exception_entry.urls = CreateUrlCollectionFromForm(*form);
current_exception_entry.id = exception_id_generator_.GenerateId(
password_manager::CreateSortKey(*form));
+ current_exception_entry.frontend_id =
+ exception_frontend_id_generator_.GenerateId(
+ password_manager::CreateSortKey(
+ *form, password_manager::IgnoreStore(true)));
current_exception_entry.from_account_store = form->IsUsingAccountStore();
current_exceptions_.push_back(std::move(current_exception_entry));
@@ -378,6 +404,18 @@ void PasswordsPrivateDelegateImpl::SetPasswordExceptionList(
get_password_exception_list_callbacks_.clear();
}
+void PasswordsPrivateDelegateImpl::MovePasswordToAccount(
+ int id,
+ content::WebContents* web_contents) {
+ auto* client = ChromePasswordManagerClient::FromWebContents(web_contents);
+ // TODO(victorvianna): Use a DCHECK instead.
+ if (!client)
+ return;
+
+ if (const std::string* sort_key = password_id_generator_.TryGetKey(id))
+ password_manager_presenter_->MovePasswordToAccountStore(*sort_key, client);
+}
+
void PasswordsPrivateDelegateImpl::ImportPasswords(
content::WebContents* web_contents) {
password_manager_porter_->set_web_contents(web_contents);
@@ -434,7 +472,8 @@ void PasswordsPrivateDelegateImpl::SetAccountStorageOptIn(
return;
}
// The opt in pref is automatically set upon successful reauth.
- client->TriggerReauthForPrimaryAccount(base::DoNothing());
+ client->TriggerReauthForPrimaryAccount(
+ signin_metrics::ReauthAccessPoint::kPasswordSettings, base::DoNothing());
}
std::vector<api::passwords_private::CompromisedCredential>
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h
index 5e37007baf2..10de06d47d2 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h
+++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h
@@ -53,13 +53,15 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate,
int id,
base::string16 new_username,
base::Optional<base::string16> new_password) override;
- void RemoveSavedPassword(int id) override;
- void RemovePasswordException(int id) override;
+ void RemoveSavedPasswords(const std::vector<int>& ids) override;
+ void RemovePasswordExceptions(const std::vector<int>& ids) override;
void UndoRemoveSavedPasswordOrException() override;
void RequestPlaintextPassword(int id,
api::passwords_private::PlaintextReason reason,
PlaintextPasswordCallback callback,
content::WebContents* web_contents) override;
+ void MovePasswordToAccount(int id,
+ content::WebContents* web_contents) override;
void ImportPasswords(content::WebContents* web_contents) override;
void ExportPasswords(base::OnceCallback<void(const std::string&)> accepted,
content::WebContents* web_contents) override;
@@ -123,8 +125,8 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate,
void SendSavedPasswordsList();
void SendPasswordExceptionsList();
- void RemoveSavedPasswordInternal(int id);
- void RemovePasswordExceptionInternal(int id);
+ void RemoveSavedPasswordsInternal(const std::vector<int>& ids);
+ void RemovePasswordExceptionsInternal(const std::vector<int>& ids);
void UndoRemoveSavedPasswordOrExceptionInternal();
// Callback for when the password list has been written to the destination.
@@ -162,7 +164,9 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate,
// Generators that map between sort keys used by |password_manager_presenter_|
// and ids used by the JavaScript front end.
IdGenerator<std::string> password_id_generator_;
+ IdGenerator<std::string> password_frontend_id_generator_;
IdGenerator<std::string> exception_id_generator_;
+ IdGenerator<std::string> exception_frontend_id_generator_;
// Whether SetPasswordList and SetPasswordExceptionList have been called, and
// whether this class has been initialized, meaning both have been called.
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc
index 015feb23ab7..7871953f2e6 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc
@@ -36,6 +36,7 @@
#include "components/password_manager/core/browser/password_manager_test_utils.h"
#include "components/password_manager/core/browser/reauth_purpose.h"
#include "components/password_manager/core/browser/test_password_store.h"
+#include "components/signin/public/base/signin_metrics.h"
#include "content/public/browser/browser_context.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_renderer_host.h"
@@ -49,9 +50,11 @@ using MockReauthCallback = base::MockCallback<
using PasswordFormList = std::vector<std::unique_ptr<autofill::PasswordForm>>;
using password_manager::ReauthPurpose;
using password_manager::TestPasswordStore;
+using ::testing::_;
using ::testing::Eq;
using ::testing::Ne;
using ::testing::Return;
+using ::testing::SizeIs;
using ::testing::StrictMock;
namespace extensions {
@@ -84,7 +87,8 @@ class MockPasswordManagerClient : public ChromePasswordManagerClient {
// ChromePasswordManagerClient overrides.
MOCK_METHOD(void,
TriggerReauthForPrimaryAccount,
- (base::OnceCallback<void(ReauthSucceeded)>),
+ (signin_metrics::ReauthAccessPoint,
+ base::OnceCallback<void(ReauthSucceeded)>),
(override));
const password_manager::MockPasswordFeatureManager*
GetPasswordFeatureManager() const override {
@@ -168,7 +172,7 @@ std::unique_ptr<KeyedService> BuildPasswordsPrivateEventRouter(
autofill::PasswordForm CreateSampleForm() {
autofill::PasswordForm form;
form.signon_realm = "http://abc1.com";
- form.origin = GURL("http://abc1.com");
+ form.url = GURL("http://abc1.com");
form.username_value = base::ASCIIToUTF16("test@gmail.com");
form.password_value = base::ASCIIToUTF16("test");
return form;
@@ -247,6 +251,34 @@ TEST_F(PasswordsPrivateDelegateImplTest, GetSavedPasswordsList) {
delegate.GetSavedPasswordsList(callback.Get());
}
+TEST_F(PasswordsPrivateDelegateImplTest,
+ PasswordsDuplicatedInStoresHaveSameFrontendId) {
+ PasswordsPrivateDelegateImpl delegate(&profile_);
+
+ auto account_password = std::make_unique<autofill::PasswordForm>();
+ account_password->in_store = autofill::PasswordForm::Store::kAccountStore;
+ auto profile_password = std::make_unique<autofill::PasswordForm>();
+ profile_password->in_store = autofill::PasswordForm::Store::kProfileStore;
+
+ PasswordFormList list;
+ list.push_back(std::move(account_password));
+ list.push_back(std::move(profile_password));
+
+ delegate.SetPasswordList(list);
+
+ base::MockCallback<PasswordsPrivateDelegate::UiEntriesCallback> callback;
+ int first_frontend_id, second_frontend_id;
+ EXPECT_CALL(callback, Run(SizeIs(2)))
+ .WillOnce([&](const PasswordsPrivateDelegate::UiEntries& passwords) {
+ first_frontend_id = passwords[0].frontend_id;
+ second_frontend_id = passwords[1].frontend_id;
+ });
+
+ delegate.GetSavedPasswordsList(callback.Get());
+
+ EXPECT_EQ(first_frontend_id, second_frontend_id);
+}
+
TEST_F(PasswordsPrivateDelegateImplTest, GetPasswordExceptionsList) {
PasswordsPrivateDelegateImpl delegate(&profile_);
@@ -265,6 +297,38 @@ TEST_F(PasswordsPrivateDelegateImplTest, GetPasswordExceptionsList) {
delegate.GetPasswordExceptionsList(callback.Get());
}
+TEST_F(PasswordsPrivateDelegateImplTest,
+ ExceptionsDuplicatedInStoresHaveSameFrontendId) {
+ PasswordsPrivateDelegateImpl delegate(&profile_);
+
+ auto account_exception = std::make_unique<autofill::PasswordForm>();
+ account_exception->blacklisted_by_user = true;
+ account_exception->in_store = autofill::PasswordForm::Store::kAccountStore;
+ auto profile_exception = std::make_unique<autofill::PasswordForm>();
+ profile_exception->blacklisted_by_user = true;
+ profile_exception->in_store = autofill::PasswordForm::Store::kProfileStore;
+
+ PasswordFormList list;
+ list.push_back(std::move(account_exception));
+ list.push_back(std::move(profile_exception));
+
+ delegate.SetPasswordExceptionList(list);
+
+ base::MockCallback<PasswordsPrivateDelegate::ExceptionEntriesCallback>
+ callback;
+ int first_frontend_id, second_frontend_id;
+ EXPECT_CALL(callback, Run(SizeIs(2)))
+ .WillOnce(
+ [&](const PasswordsPrivateDelegate::ExceptionEntries& exceptions) {
+ first_frontend_id = exceptions[0].frontend_id;
+ second_frontend_id = exceptions[1].frontend_id;
+ });
+
+ delegate.GetPasswordExceptionsList(callback.Get());
+
+ EXPECT_EQ(first_frontend_id, second_frontend_id);
+}
+
TEST_F(PasswordsPrivateDelegateImplTest, ChangeSavedPassword) {
autofill::PasswordForm sample_form = CreateSampleForm();
SetUpPasswordStore({sample_form});
@@ -348,7 +412,9 @@ TEST_F(PasswordsPrivateDelegateImplTest, TestShouldReauthForOptIn) {
ON_CALL(*(client->GetPasswordFeatureManager()), IsOptedInForAccountStorage)
.WillByDefault(Return(false));
- EXPECT_CALL(*client, TriggerReauthForPrimaryAccount);
+ EXPECT_CALL(*client,
+ TriggerReauthForPrimaryAccount(
+ signin_metrics::ReauthAccessPoint::kPasswordSettings, _));
PasswordsPrivateDelegateImpl delegate(&profile_);
delegate.SetAccountStorageOptIn(true, web_contents.get());
@@ -368,7 +434,10 @@ TEST_F(PasswordsPrivateDelegateImplTest,
ON_CALL(*feature_manager, IsOptedInForAccountStorage)
.WillByDefault(Return(true));
- EXPECT_CALL(*client, TriggerReauthForPrimaryAccount).Times(0);
+ EXPECT_CALL(*client,
+ TriggerReauthForPrimaryAccount(
+ signin_metrics::ReauthAccessPoint::kPasswordSettings, _))
+ .Times(0);
EXPECT_CALL(*feature_manager, OptOutOfAccountStorageAndClearSettings);
PasswordsPrivateDelegateImpl delegate(&profile_);
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_utils_unittest.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_utils_unittest.cc
index 574cac203aa..bca700f8a15 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_utils_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_utils_unittest.cc
@@ -13,8 +13,8 @@ namespace extensions {
TEST(CreateUrlCollectionFromFormTest, UrlsFromHtmlForm) {
autofill::PasswordForm html_form;
- html_form.origin = GURL("http://example.com/LoginAuth");
- html_form.signon_realm = html_form.origin.GetOrigin().spec();
+ html_form.url = GURL("http://example.com/LoginAuth");
+ html_form.signon_realm = html_form.url.GetOrigin().spec();
api::passwords_private::UrlCollection html_urls =
CreateUrlCollectionFromForm(html_form);
@@ -26,7 +26,7 @@ TEST(CreateUrlCollectionFromFormTest, UrlsFromHtmlForm) {
TEST(CreateUrlCollectionFromFormTest, UrlsFromFederatedForm) {
autofill::PasswordForm federated_form;
federated_form.signon_realm = "federation://example.com/google.com";
- federated_form.origin = GURL("https://example.com/");
+ federated_form.url = GURL("https://example.com/");
federated_form.federation_origin =
url::Origin::Create(GURL("https://google.com/"));
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.cc b/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.cc
index 6f0005f6cf9..593c0d9a140 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.cc
+++ b/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.cc
@@ -26,6 +26,7 @@ api::passwords_private::PasswordUiEntry CreateEntry(int id) {
entry.urls.link = entry.urls.origin;
entry.username = "testName" + base::NumberToString(id);
entry.id = id;
+ entry.frontend_id = id;
return entry;
}
@@ -35,6 +36,7 @@ api::passwords_private::ExceptionEntry CreateException(int id) {
exception.urls.origin = "http://" + exception.urls.shown + "/login";
exception.urls.link = exception.urls.origin;
exception.id = id;
+ exception.frontend_id = id;
return exception;
}
} // namespace
@@ -72,36 +74,55 @@ void TestPasswordsPrivateDelegate::ChangeSavedPassword(
SendSavedPasswordsList();
}
-void TestPasswordsPrivateDelegate::RemoveSavedPassword(int id) {
+void TestPasswordsPrivateDelegate::RemoveSavedPasswords(
+ const std::vector<int>& ids) {
if (current_entries_.empty())
return;
- // Since this is just mock data, remove the first entry regardless of
- // the data contained.
- last_deleted_entry_ = std::move(current_entries_.front());
- current_entries_.erase(current_entries_.begin());
+ // Since this is just mock data, remove the first |ids.size()| elements
+ // regardless of the data contained.
+ auto first_remaining = (ids.size() <= current_entries_.size())
+ ? current_entries_.begin() + ids.size()
+ : current_entries_.end();
+ last_deleted_entries_batch_.assign(
+ std::make_move_iterator(current_entries_.begin()),
+ std::make_move_iterator(first_remaining));
+ current_entries_.erase(current_entries_.begin(), first_remaining);
SendSavedPasswordsList();
}
-void TestPasswordsPrivateDelegate::RemovePasswordException(int id) {
- // Since this is just mock data, remove the first entry regardless of
- // the data contained.
- last_deleted_exception_ = std::move(current_exceptions_.front());
- current_exceptions_.erase(current_exceptions_.begin());
+void TestPasswordsPrivateDelegate::RemovePasswordExceptions(
+ const std::vector<int>& ids) {
+ if (current_exceptions_.empty())
+ return;
+
+ // Since this is just mock data, remove the first |ids.size()| elements
+ // regardless of the data contained.
+ auto first_remaining = (ids.size() <= current_exceptions_.size())
+ ? current_exceptions_.begin() + ids.size()
+ : current_exceptions_.end();
+ last_deleted_exceptions_batch_.assign(
+ std::make_move_iterator(current_exceptions_.begin()),
+ std::make_move_iterator(first_remaining));
+ current_exceptions_.erase(current_exceptions_.begin(), first_remaining);
SendPasswordExceptionsList();
}
// Simplified version of undo logic, only use for testing.
void TestPasswordsPrivateDelegate::UndoRemoveSavedPasswordOrException() {
- if (last_deleted_entry_) {
- current_entries_.insert(current_entries_.begin(),
- std::move(*last_deleted_entry_));
- last_deleted_entry_ = base::nullopt;
+ if (!last_deleted_entries_batch_.empty()) {
+ current_entries_.insert(
+ current_entries_.begin(),
+ std::make_move_iterator(last_deleted_entries_batch_.begin()),
+ std::make_move_iterator(last_deleted_entries_batch_.end()));
+ last_deleted_entries_batch_.clear();
SendSavedPasswordsList();
- } else if (last_deleted_exception_) {
- current_exceptions_.insert(current_exceptions_.begin(),
- std::move(*last_deleted_exception_));
- last_deleted_exception_ = base::nullopt;
+ } else if (!last_deleted_exceptions_batch_.empty()) {
+ current_exceptions_.insert(
+ current_exceptions_.begin(),
+ std::make_move_iterator(last_deleted_exceptions_batch_.begin()),
+ std::make_move_iterator(last_deleted_exceptions_batch_.end()));
+ last_deleted_exceptions_batch_.clear();
SendPasswordExceptionsList();
}
}
@@ -115,6 +136,12 @@ void TestPasswordsPrivateDelegate::RequestPlaintextPassword(
std::move(callback).Run(plaintext_password_);
}
+void TestPasswordsPrivateDelegate::MovePasswordToAccount(
+ int id,
+ content::WebContents* web_contents) {
+ last_moved_password_ = id;
+}
+
void TestPasswordsPrivateDelegate::ImportPasswords(
content::WebContents* web_contents) {
// The testing of password importing itself should be handled via
diff --git a/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.h b/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.h
index 639c9092fc4..3b88cedf525 100644
--- a/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.h
+++ b/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.h
@@ -5,6 +5,7 @@
#ifndef CHROME_BROWSER_EXTENSIONS_API_PASSWORDS_PRIVATE_TEST_PASSWORDS_PRIVATE_DELEGATE_H_
#define CHROME_BROWSER_EXTENSIONS_API_PASSWORDS_PRIVATE_TEST_PASSWORDS_PRIVATE_DELEGATE_H_
+#include "base/optional.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h"
#include "chrome/browser/profiles/profile.h"
@@ -25,14 +26,16 @@ class TestPasswordsPrivateDelegate : public PasswordsPrivateDelegate {
void ChangeSavedPassword(int id,
base::string16 username,
base::Optional<base::string16> password) override;
- void RemoveSavedPassword(int id) override;
- void RemovePasswordException(int id) override;
+ void RemoveSavedPasswords(const std::vector<int>& id) override;
+ void RemovePasswordExceptions(const std::vector<int>& ids) override;
// Simplified version of undo logic, only use for testing.
void UndoRemoveSavedPasswordOrException() override;
void RequestPlaintextPassword(int id,
api::passwords_private::PlaintextReason reason,
PlaintextPasswordCallback callback,
content::WebContents* web_contents) override;
+ void MovePasswordToAccount(int id,
+ content::WebContents* web_contents) override;
void ImportPasswords(content::WebContents* web_contents) override;
void ExportPasswords(base::OnceCallback<void(const std::string&)> callback,
content::WebContents* web_contents) override;
@@ -84,6 +87,10 @@ class TestPasswordsPrivateDelegate : public PasswordsPrivateDelegate {
start_password_check_state_ = state;
}
+ base::Optional<int> last_moved_password() const {
+ return last_moved_password_;
+ }
+
private:
void SendSavedPasswordsList();
void SendPasswordExceptionsList();
@@ -93,11 +100,15 @@ class TestPasswordsPrivateDelegate : public PasswordsPrivateDelegate {
// having to request them from |password_manager_presenter_| again.
std::vector<api::passwords_private::PasswordUiEntry> current_entries_;
std::vector<api::passwords_private::ExceptionEntry> current_exceptions_;
- // Simplified version of a undo manager that only allows undoing and redoing
- // the very last deletion.
- base::Optional<api::passwords_private::PasswordUiEntry> last_deleted_entry_;
- base::Optional<api::passwords_private::ExceptionEntry>
- last_deleted_exception_;
+
+ // Simplified version of an undo manager that only allows undoing and redoing
+ // the very last deletion. When the batches are *empty*, this means there is
+ // no previous deletion to undo.
+ std::vector<api::passwords_private::PasswordUiEntry>
+ last_deleted_entries_batch_;
+ std::vector<api::passwords_private::ExceptionEntry>
+ last_deleted_exceptions_batch_;
+
base::Optional<base::string16> plaintext_password_ =
base::ASCIIToUTF16("plaintext");
@@ -118,6 +129,9 @@ class TestPasswordsPrivateDelegate : public PasswordsPrivateDelegate {
bool stop_password_check_triggered_ = false;
password_manager::BulkLeakCheckService::State start_password_check_state_ =
password_manager::BulkLeakCheckService::State::kRunning;
+
+ // Records the id of the last password that was moved.
+ base::Optional<int> last_moved_password_ = base::nullopt;
};
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc
index be4e536005b..366ae43ac65 100644
--- a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc
+++ b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc
@@ -11,6 +11,7 @@
#include "base/bind.h"
#include "base/logging.h"
#include "base/stl_util.h"
+#include "base/strings/string_piece.h"
#include "base/values.h"
#include "chrome/browser/chromeos/platform_keys/extension_platform_keys_service.h"
#include "chrome/browser/chromeos/platform_keys/extension_platform_keys_service_factory.h"
@@ -37,6 +38,8 @@ const char kErrorInteractiveCallFromBackground[] =
"Interactive calls must happen in the context of a browser tab or a "
"window.";
+const char kWebCryptoEcdsa[] = "ECDSA";
+const char kWebCryptoNamedCurveP256[] = "P-256";
const char kWebCryptoRSASSA_PKCS1_v1_5[] = "RSASSA-PKCS1-v1_5";
struct PublicKeyInfo {
@@ -58,7 +61,7 @@ struct PublicKeyInfo {
void BuildWebCryptoRSAAlgorithmDictionary(const PublicKeyInfo& key_info,
base::DictionaryValue* algorithm) {
CHECK_EQ(net::X509Certificate::kPublicKeyTypeRSA, key_info.key_type);
- algorithm->SetKey("name", base::Value(kWebCryptoRSASSA_PKCS1_v1_5));
+ algorithm->SetStringKey("name", kWebCryptoRSASSA_PKCS1_v1_5);
algorithm->SetKey("modulusLength",
base::Value(static_cast<int>(key_info.key_size_bits)));
@@ -71,6 +74,15 @@ void BuildWebCryptoRSAAlgorithmDictionary(const PublicKeyInfo& key_info,
base::size(defaultPublicExponent)));
}
+void BuildWebCryptoEcdsaAlgorithmDictionary(const PublicKeyInfo& key_info,
+ base::DictionaryValue* algorithm) {
+ CHECK_EQ(net::X509Certificate::kPublicKeyTypeECDSA, key_info.key_type);
+ algorithm->SetStringKey("name", kWebCryptoEcdsa);
+
+ // Only P-256 named curve is supported.
+ algorithm->SetStringKey("namedCurve", kWebCryptoNamedCurveP256);
+}
+
const struct NameValuePair {
const char* const name;
const int value;
@@ -84,6 +96,7 @@ const struct NameValuePair {
namespace platform_keys {
+const char kErrorInvalidSpki[] = "The SubjectPublicKeyInfo is not valid.";
const char kErrorInvalidToken[] = "The token is not valid.";
const char kErrorInvalidX509Cert[] =
"Certificate is not a valid X.509 certificate.";
@@ -145,25 +158,85 @@ PlatformKeysInternalGetPublicKeyFunction::Run() {
chromeos::platform_keys::GetSubjectPublicKeyInfo(cert_x509);
if (!chromeos::platform_keys::GetPublicKey(cert_x509, &key_info.key_type,
&key_info.key_size_bits) ||
+ (key_info.key_type != net::X509Certificate::kPublicKeyTypeRSA &&
+ key_info.key_type != net::X509Certificate::kPublicKeyTypeECDSA)) {
+ return RespondNow(Error(kErrorAlgorithmNotSupported));
+ }
+
+ // Currently, the only supported combinations are:
+ // 1- A certificate declaring rsaEncryption in the SubjectPublicKeyInfo used
+ // with the RSASSA-PKCS1-v1.5 algorithm.
+ // 2- A certificate declaring id-ecPublicKey in the SubjectPublicKeyInfo used
+ // with the ECDSA algorithm.
+ if (params->algorithm_name == kWebCryptoRSASSA_PKCS1_v1_5) {
+ if (key_info.key_type != net::X509Certificate::kPublicKeyTypeRSA) {
+ return RespondNow(Error(kErrorAlgorithmNotPermittedByCertificate));
+ }
+
+ api_pki::GetPublicKey::Results::Algorithm algorithm;
+ BuildWebCryptoRSAAlgorithmDictionary(key_info,
+ &algorithm.additional_properties);
+
+ return RespondNow(ArgumentList(api_pki::GetPublicKey::Results::Create(
+ std::vector<uint8_t>(key_info.public_key_spki_der.begin(),
+ key_info.public_key_spki_der.end()),
+ algorithm)));
+ }
+
+ if (params->algorithm_name == kWebCryptoEcdsa) {
+ if (key_info.key_type != net::X509Certificate::kPublicKeyTypeECDSA) {
+ return RespondNow(Error(kErrorAlgorithmNotPermittedByCertificate));
+ }
+
+ api_pki::GetPublicKey::Results::Algorithm algorithm;
+ BuildWebCryptoEcdsaAlgorithmDictionary(key_info,
+ &algorithm.additional_properties);
+
+ return RespondNow(ArgumentList(api_pki::GetPublicKey::Results::Create(
+ std::vector<uint8_t>(key_info.public_key_spki_der.begin(),
+ key_info.public_key_spki_der.end()),
+ algorithm)));
+ }
+
+ return RespondNow(Error(kErrorAlgorithmNotPermittedByCertificate));
+}
+
+PlatformKeysInternalGetPublicKeyBySpkiFunction::
+ ~PlatformKeysInternalGetPublicKeyBySpkiFunction() = default;
+
+ExtensionFunction::ResponseAction
+PlatformKeysInternalGetPublicKeyBySpkiFunction::Run() {
+ std::unique_ptr<api_pki::GetPublicKeyBySpki::Params> params(
+ api_pki::GetPublicKeyBySpki::Params::Create(*args_));
+ EXTENSION_FUNCTION_VALIDATE(params);
+
+ const auto& public_key_spki_der = params->public_key_spki_der;
+ if (public_key_spki_der.empty())
+ return RespondNow(Error(platform_keys::kErrorInvalidSpki));
+
+ PublicKeyInfo key_info;
+ key_info.public_key_spki_der.assign(std::begin(public_key_spki_der),
+ std::end(public_key_spki_der));
+
+ if (!chromeos::platform_keys::GetPublicKeyBySpki(key_info.public_key_spki_der,
+ &key_info.key_type,
+ &key_info.key_size_bits) ||
key_info.key_type != net::X509Certificate::kPublicKeyTypeRSA) {
return RespondNow(Error(kErrorAlgorithmNotSupported));
}
// Currently, the only supported combination is:
- // A certificate declaring rsaEncryption in the SubjectPublicKeyInfo used
- // with the RSASSA-PKCS1-v1.5 algorithm.
+ // A SPKI declaring rsaEncryption used with the RSASSA-PKCS1-v1.5 algorithm.
if (params->algorithm_name != kWebCryptoRSASSA_PKCS1_v1_5) {
- return RespondNow(Error(kErrorAlgorithmNotPermittedByCertificate));
+ return RespondNow(Error(kErrorAlgorithmNotSupported));
}
- api_pki::GetPublicKey::Results::Algorithm algorithm;
+ api_pki::GetPublicKeyBySpki::Results::Algorithm algorithm;
BuildWebCryptoRSAAlgorithmDictionary(key_info,
&algorithm.additional_properties);
- return RespondNow(ArgumentList(api_pki::GetPublicKey::Results::Create(
- std::vector<uint8_t>(key_info.public_key_spki_der.begin(),
- key_info.public_key_spki_der.end()),
- algorithm)));
+ return RespondNow(ArgumentList(api_pki::GetPublicKeyBySpki::Results::Create(
+ public_key_spki_der, algorithm)));
}
PlatformKeysInternalSelectClientCertificatesFunction::
@@ -305,7 +378,7 @@ ExtensionFunction::ResponseAction PlatformKeysInternalSignFunction::Run() {
if (params->hash_algorithm_name == "none") {
// Signing without digesting is only supported for RSASSA-PKCS1-v1_5.
- if (params->algorithm_name != "RSASSA-PKCS1-v1_5")
+ if (params->algorithm_name != kWebCryptoRSASSA_PKCS1_v1_5)
return RespondNow(Error(kErrorAlgorithmNotSupported));
service->SignRSAPKCS1Raw(
@@ -329,9 +402,9 @@ ExtensionFunction::ResponseAction PlatformKeysInternalSignFunction::Run() {
}
chromeos::platform_keys::KeyType key_type;
- if (params->algorithm_name == "RSASSA-PKCS1-v1_5") {
+ if (params->algorithm_name == kWebCryptoRSASSA_PKCS1_v1_5) {
key_type = chromeos::platform_keys::KeyType::kRsassaPkcs1V15;
- } else if (params->algorithm_name == "ECDSA") {
+ } else if (params->algorithm_name == kWebCryptoEcdsa) {
key_type = chromeos::platform_keys::KeyType::kEcdsa;
} else {
return RespondNow(Error(kErrorAlgorithmNotSupported));
diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h
index 4d1ece03673..fe503135b62 100644
--- a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h
+++ b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h
@@ -56,6 +56,16 @@ class PlatformKeysInternalGetPublicKeyFunction : public ExtensionFunction {
PLATFORMKEYSINTERNAL_GETPUBLICKEY)
};
+class PlatformKeysInternalGetPublicKeyBySpkiFunction
+ : public ExtensionFunction {
+ private:
+ ~PlatformKeysInternalGetPublicKeyBySpkiFunction() override;
+ ResponseAction Run() override;
+
+ DECLARE_EXTENSION_FUNCTION("platformKeysInternal.getPublicKeyBySpki",
+ PLATFORMKEYSINTERNAL_GETPUBLICKEYBYSPKI)
+};
+
class PlatformKeysInternalSignFunction : public ExtensionFunction {
private:
~PlatformKeysInternalSignFunction() override;
diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc
index 1b2bcb7417a..c5b730978bb 100644
--- a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc
+++ b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc
@@ -12,7 +12,6 @@
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
-#include "base/task/post_task.h"
#include "chrome/browser/chromeos/platform_keys/extension_platform_keys_service.h"
#include "chrome/browser/chromeos/platform_keys/extension_platform_keys_service_factory.h"
#include "chrome/browser/extensions/api/platform_keys/platform_keys_test_base.h"
@@ -21,6 +20,7 @@
#include "chrome/browser/profiles/profile.h"
#include "components/policy/policy_constants.h"
#include "content/public/browser/browser_task_traits.h"
+#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_test.h"
#include "crypto/nss_util_internal.h"
#include "crypto/scoped_nss_types.h"
@@ -53,8 +53,8 @@ class PlatformKeysTest : public PlatformKeysTestBase {
// |PlatformKeysTestBase::SetUpOnMainThread| triggers the user sign-in.
ASSERT_TRUE(user_private_slot_db_.is_open());
base::RunLoop loop;
- base::PostTaskAndReply(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTaskAndReply(
+ FROM_HERE,
base::BindOnce(&PlatformKeysTest::SetPrivateSoftwareSlotOnIO,
base::Unretained(this),
crypto::ScopedPK11Slot(
diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc
index 166d76a626f..b1847d07f98 100644
--- a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc
+++ b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc
@@ -7,7 +7,6 @@
#include "base/bind.h"
#include "base/path_service.h"
#include "base/run_loop.h"
-#include "base/task/post_task.h"
#include "chrome/browser/chromeos/policy/affiliation_test_helper.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/ui/browser.h"
@@ -155,8 +154,8 @@ void PlatformKeysTestBase::SetUpOnMainThread() {
if (system_token_status() == SystemTokenStatus::EXISTS) {
base::RunLoop loop;
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PlatformKeysTestBase::SetUpTestSystemSlotOnIO,
base::Unretained(this), loop.QuitClosure()));
loop.Run();
@@ -170,8 +169,8 @@ void PlatformKeysTestBase::TearDownOnMainThread() {
if (system_token_status() == SystemTokenStatus::EXISTS) {
base::RunLoop loop;
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PlatformKeysTestBase::TearDownTestSystemSlotOnIO,
base::Unretained(this), loop.QuitClosure()));
loop.Run();
@@ -211,14 +210,14 @@ void PlatformKeysTestBase::SetUpTestSystemSlotOnIO(
PrepareTestSystemSlotOnIO(test_system_slot_.get());
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- std::move(done_callback));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ std::move(done_callback));
}
void PlatformKeysTestBase::TearDownTestSystemSlotOnIO(
base::OnceClosure done_callback) {
test_system_slot_.reset();
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- std::move(done_callback));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ std::move(done_callback));
}
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 6f382e521ba..1daf379593b 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
@@ -12,7 +12,6 @@
#include "base/lazy_instance.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
-#include "base/task/post_task.h"
#include "chrome/browser/extensions/api/platform_keys/platform_keys_api.h"
#include "chrome/common/extensions/api/platform_keys_internal.h"
#include "content/public/browser/browser_task_traits.h"
@@ -113,8 +112,8 @@ void VerifyTrustAPI::Verify(std::unique_ptr<Params> params,
&CallBackOnUI, base::Bind(&VerifyTrustAPI::FinishedVerificationOnUI,
weak_factory_.GetWeakPtr(), ui_callback)));
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&IOPart::Verify, base::Unretained(io_part_.get()),
std::move(params), extension_id, finish_callback));
}
@@ -123,8 +122,8 @@ void VerifyTrustAPI::OnExtensionUnloaded(
content::BrowserContext* browser_context,
const Extension* extension,
UnloadedExtensionReason reason) {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&IOPart::OnExtensionUnloaded,
base::Unretained(io_part_.get()), extension->id()));
}
@@ -143,8 +142,8 @@ void VerifyTrustAPI::CallBackOnUI(const VerifyCallback& ui_callback,
const std::string& error,
int return_value,
int cert_status) {
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(ui_callback, error, return_value, cert_status));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(ui_callback, error, return_value, cert_status));
}
VerifyTrustAPI::IOPart::~IOPart() {
diff --git a/chromium/chrome/browser/extensions/api/preference/preference_apitest.cc b/chromium/chrome/browser/extensions/api/preference/preference_apitest.cc
index 3dfd9b014ce..e11e90a7f90 100644
--- a/chromium/chrome/browser/extensions/api/preference/preference_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/preference/preference_apitest.cc
@@ -42,7 +42,7 @@
class ExtensionPreferenceApiTest : public extensions::ExtensionApiTest {
protected:
- ExtensionPreferenceApiTest() : profile_(NULL) {}
+ ExtensionPreferenceApiTest() : profile_(nullptr) {}
void CheckPreferencesSet() {
PrefService* prefs = profile_->GetPrefs();
@@ -168,7 +168,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, Standard) {
const char kExtensionPath[] = "preference/standard";
- EXPECT_TRUE(RunExtensionSubtest(kExtensionPath, "test.html")) << message_;
+ EXPECT_TRUE(RunExtensionTest(kExtensionPath)) << message_;
CheckPreferencesSet();
// The settings should not be reset when the extension is reloaded.
diff --git a/chromium/chrome/browser/extensions/api/processes/processes_api.cc b/chromium/chrome/browser/extensions/api/processes/processes_api.cc
index bd0417665c3..112a293b669 100644
--- a/chromium/chrome/browser/extensions/api/processes/processes_api.cc
+++ b/chromium/chrome/browser/extensions/api/processes/processes_api.cc
@@ -17,7 +17,6 @@
#include "base/process/process.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "chrome/browser/extensions/api/tabs/tabs_constants.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/profiles/profile.h"
@@ -512,8 +511,8 @@ ExtensionFunction::ResponseAction ProcessesTerminateFunction::Run() {
// This could be a non-renderer child process like a plugin or a nacl
// process. Try to get its handle from the BrowserChildProcessHost on the
// IO thread.
- base::PostTaskAndReplyWithResult(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTaskAndReplyWithResult(
+ FROM_HERE,
base::BindOnce(&ProcessesTerminateFunction::GetProcessHandleOnIO, this,
child_process_host_id_),
base::BindOnce(&ProcessesTerminateFunction::OnProcessHandleOnUI, this));
diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc
index 153d46d923d..1a56cf910e8 100644
--- a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc
+++ b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc
@@ -18,6 +18,7 @@
#include <utility>
#include "base/base64.h"
+#include "base/notreached.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
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 24faa7952af..a3597241802 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
@@ -10,21 +10,15 @@
#include "base/values.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/ui/webui/webui_util.h"
#include "chrome/common/extensions/api/resources_private.h"
#include "chrome/grit/generated_resources.h"
-#include "components/strings/grit/components_strings.h"
-#include "components/zoom/page_zoom_constants.h"
#include "pdf/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
#if BUILDFLAG(ENABLE_PDF)
-#include "pdf/pdf_features.h"
-#if defined(OS_CHROMEOS)
-#include "chrome/browser/chromeos/login/ui/login_display_host.h"
-#endif // defined(OS_CHROMEOS)
+#include "chrome/browser/pdf/pdf_extension_util.h"
#endif // BUILDFLAG(ENABLE_PDF)
// To add a new component to this API, simply:
@@ -42,109 +36,6 @@ void AddStringsForIdentity(base::DictionaryValue* dict) {
l10n_util::GetStringUTF16(IDS_EXTENSION_CONFIRM_PERMISSIONS));
}
-void AddStringsForPdf(base::DictionaryValue* dict) {
-#if BUILDFLAG(ENABLE_PDF)
- static constexpr webui::LocalizedString kPdfResources[] = {
- {"passwordDialogTitle", IDS_PDF_PASSWORD_DIALOG_TITLE},
- {"passwordPrompt", IDS_PDF_NEED_PASSWORD},
- {"passwordSubmit", IDS_PDF_PASSWORD_SUBMIT},
- {"passwordInvalid", IDS_PDF_PASSWORD_INVALID},
- {"pageLoading", IDS_PDF_PAGE_LOADING},
- {"pageLoadFailed", IDS_PDF_PAGE_LOAD_FAILED},
- {"errorDialogTitle", IDS_PDF_ERROR_DIALOG_TITLE},
- {"pageReload", IDS_PDF_PAGE_RELOAD_BUTTON},
- {"bookmarks", IDS_PDF_BOOKMARKS},
- {"labelPageNumber", IDS_PDF_LABEL_PAGE_NUMBER},
- {"tooltipRotateCW", IDS_PDF_TOOLTIP_ROTATE_CW},
- {"tooltipDownload", IDS_PDF_TOOLTIP_DOWNLOAD},
- {"tooltipPrint", IDS_PDF_TOOLTIP_PRINT},
- {"tooltipFitToPage", IDS_PDF_TOOLTIP_FIT_PAGE},
- {"tooltipFitToWidth", IDS_PDF_TOOLTIP_FIT_WIDTH},
- {"tooltipTwoUpViewEnable", IDS_PDF_TOOLTIP_TWO_UP_VIEW_ENABLE},
- {"tooltipTwoUpViewDisable", IDS_PDF_TOOLTIP_TWO_UP_VIEW_DISABLE},
- {"tooltipZoomIn", IDS_PDF_TOOLTIP_ZOOM_IN},
- {"tooltipZoomOut", IDS_PDF_TOOLTIP_ZOOM_OUT},
-#if defined(OS_CHROMEOS)
- {"tooltipAnnotate", IDS_PDF_ANNOTATION_ANNOTATE},
- {"annotationDocumentTooLarge", IDS_PDF_ANNOTATION_DOCUMENT_TOO_LARGE},
- {"annotationDocumentProtected", IDS_PDF_ANNOTATION_DOCUMENT_PROTECTED},
- {"annotationDocumentRotated", IDS_PDF_ANNOTATION_DOCUMENT_ROTATED},
- {"annotationPen", IDS_PDF_ANNOTATION_PEN},
- {"annotationHighlighter", IDS_PDF_ANNOTATION_HIGHLIGHTER},
- {"annotationEraser", IDS_PDF_ANNOTATION_ERASER},
- {"annotationUndo", IDS_PDF_ANNOTATION_UNDO},
- {"annotationRedo", IDS_PDF_ANNOTATION_REDO},
- {"annotationExpand", IDS_PDF_ANNOTATION_EXPAND},
- {"annotationColorBlack", IDS_PDF_ANNOTATION_COLOR_BLACK},
- {"annotationColorRed", IDS_PDF_ANNOTATION_COLOR_RED},
- {"annotationColorYellow", IDS_PDF_ANNOTATION_COLOR_YELLOW},
- {"annotationColorGreen", IDS_PDF_ANNOTATION_COLOR_GREEN},
- {"annotationColorCyan", IDS_PDF_ANNOTATION_COLOR_CYAN},
- {"annotationColorPurple", IDS_PDF_ANNOTATION_COLOR_PURPLE},
- {"annotationColorBrown", IDS_PDF_ANNOTATION_COLOR_BROWN},
- {"annotationColorWhite", IDS_PDF_ANNOTATION_COLOR_WHITE},
- {"annotationColorCrimson", IDS_PDF_ANNOTATION_COLOR_CRIMSON},
- {"annotationColorAmber", IDS_PDF_ANNOTATION_COLOR_AMBER},
- {"annotationColorAvocadoGreen", IDS_PDF_ANNOTATION_COLOR_AVOCADO_GREEN},
- {"annotationColorCobaltBlue", IDS_PDF_ANNOTATION_COLOR_COBALT_BLUE},
- {"annotationColorDeepPurple", IDS_PDF_ANNOTATION_COLOR_DEEP_PURPLE},
- {"annotationColorDarkBrown", IDS_PDF_ANNOTATION_COLOR_DARK_BROWN},
- {"annotationColorDarkGrey", IDS_PDF_ANNOTATION_COLOR_DARK_GREY},
- {"annotationColorHotPink", IDS_PDF_ANNOTATION_COLOR_HOT_PINK},
- {"annotationColorOrange", IDS_PDF_ANNOTATION_COLOR_ORANGE},
- {"annotationColorLime", IDS_PDF_ANNOTATION_COLOR_LIME},
- {"annotationColorBlue", IDS_PDF_ANNOTATION_COLOR_BLUE},
- {"annotationColorViolet", IDS_PDF_ANNOTATION_COLOR_VIOLET},
- {"annotationColorTeal", IDS_PDF_ANNOTATION_COLOR_TEAL},
- {"annotationColorLightGrey", IDS_PDF_ANNOTATION_COLOR_LIGHT_GREY},
- {"annotationColorLightPink", IDS_PDF_ANNOTATION_COLOR_LIGHT_PINK},
- {"annotationColorLightOrange", IDS_PDF_ANNOTATION_COLOR_LIGHT_ORANGE},
- {"annotationColorLightGreen", IDS_PDF_ANNOTATION_COLOR_LIGHT_GREEN},
- {"annotationColorLightBlue", IDS_PDF_ANNOTATION_COLOR_LIGHT_BLUE},
- {"annotationColorLavender", IDS_PDF_ANNOTATION_COLOR_LAVENDER},
- {"annotationColorLightTeal", IDS_PDF_ANNOTATION_COLOR_LIGHT_TEAL},
- {"annotationSize1", IDS_PDF_ANNOTATION_SIZE1},
- {"annotationSize2", IDS_PDF_ANNOTATION_SIZE2},
- {"annotationSize3", IDS_PDF_ANNOTATION_SIZE3},
- {"annotationSize4", IDS_PDF_ANNOTATION_SIZE4},
- {"annotationSize8", IDS_PDF_ANNOTATION_SIZE8},
- {"annotationSize12", IDS_PDF_ANNOTATION_SIZE12},
- {"annotationSize16", IDS_PDF_ANNOTATION_SIZE16},
- {"annotationSize20", IDS_PDF_ANNOTATION_SIZE20},
- {"annotationFormWarningTitle", IDS_PDF_DISCARD_FORM_CHANGES},
- {"annotationFormWarningDetail", IDS_PDF_DISCARD_FORM_CHANGES_DETAIL},
- {"annotationFormWarningKeepEditing", IDS_PDF_KEEP_EDITING},
- {"annotationFormWarningDiscard", IDS_PDF_DISCARD},
-#endif // defined(OS_CHROMEOS)
- };
- for (const auto& resource : kPdfResources)
- dict->SetString(resource.name, l10n_util::GetStringUTF16(resource.id));
-
- dict->SetString("presetZoomFactors", zoom::GetPresetZoomFactorsAsJSON());
-#endif // BUILDFLAG(ENABLE_PDF)
-}
-
-void AddAdditionalDataForPdf(base::DictionaryValue* dict) {
-#if BUILDFLAG(ENABLE_PDF)
- dict->SetKey("pdfFormSaveEnabled",
- base::Value(base::FeatureList::IsEnabled(
- chrome_pdf::features::kSaveEditedPDFForm)));
- dict->SetKey("pdfAnnotationsEnabled",
- base::Value(base::FeatureList::IsEnabled(
- chrome_pdf::features::kPDFAnnotations)));
- dict->SetKey("pdfTwoUpViewEnabled",
- base::Value(base::FeatureList::IsEnabled(
- chrome_pdf::features::kPDFTwoUpView)));
-
- 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)
-}
-
} // namespace
namespace get_strings = api::resources_private::GetStrings;
@@ -164,10 +55,13 @@ ExtensionFunction::ResponseAction ResourcesPrivateGetStringsFunction::Run() {
case api::resources_private::COMPONENT_IDENTITY:
AddStringsForIdentity(dict.get());
break;
- case api::resources_private::COMPONENT_PDF:
- AddStringsForPdf(dict.get());
- AddAdditionalDataForPdf(dict.get());
- break;
+#if BUILDFLAG(ENABLE_PDF)
+ case api::resources_private::COMPONENT_PDF: {
+ pdf_extension_util::AddStrings(pdf_extension_util::PdfViewerContext::kAll,
+ dict.get());
+ pdf_extension_util::AddAdditionalData(dict.get());
+ } break;
+#endif // BUILDFLAG(ENABLE_PDF)
case api::resources_private::COMPONENT_NONE:
NOTREACHED();
}
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 a8d41b78f10..ead182f7275 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
@@ -94,7 +94,7 @@ class DownloaderTestDelegate : public ExtensionDownloaderTestDelegate {
no_updates_.erase(id);
DownloadFinishedArgs args;
args.path = path;
- args.version = version;
+ args.version = base::Version(version);
updates_[id] = std::move(args);
}
@@ -107,7 +107,7 @@ class DownloaderTestDelegate : public ExtensionDownloaderTestDelegate {
// expecting a synchronous reply (the real code has to go do at least one
// network request before getting a response, so this is is a reasonable
// expectation by delegates).
- for (const std::string& id : fetch_data->extension_ids()) {
+ for (const std::string& id : fetch_data->GetExtensionIds()) {
auto no_update = no_updates_.find(id);
if (no_update != no_updates_.end()) {
no_updates_.erase(no_update);
@@ -147,7 +147,7 @@ class DownloaderTestDelegate : public ExtensionDownloaderTestDelegate {
// Simple holder for the data passed in AddUpdateResponse calls.
struct DownloadFinishedArgs {
base::FilePath path;
- std::string version;
+ base::Version version;
};
// These keep track of what response we should give for update checks, keyed
@@ -206,7 +206,8 @@ class ChromeRuntimeAPIDelegateTest : public ExtensionServiceTestWithInstall {
// Setup the ExtensionService so that extension updates won't complete
// installation until the extension is idle.
- update_install_gate_ = std::make_unique<UpdateInstallGate>(service());
+ update_install_gate_ =
+ std::make_unique<UpdateInstallGate>(service()->profile());
service()->RegisterInstallGate(ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
update_install_gate_.get());
static_cast<TestExtensionSystem*>(ExtensionSystem::Get(browser_context()))
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 e0dbf81759b..6c34804f9dc 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
@@ -18,17 +18,8 @@
#include "base/time/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_content_browser_client.h"
-#include "chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service_factory.h"
-#include "components/safe_browsing/content/web_ui/safe_browsing_ui.h"
-#if defined(OS_CHROMEOS)
-#include "chrome/browser/browser_process_platform_part_chromeos.h"
-#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
-#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
-#include "chrome/browser/chromeos/profiles/profile_helper.h"
-#else
-#include "chrome/browser/policy/browser_dm_token_storage.h"
-#include "chrome/browser/policy/chrome_browser_cloud_management_controller.h"
-#endif
+#include "chrome/browser/enterprise/connectors/common.h"
+#include "chrome/browser/enterprise/connectors/connectors_manager.h"
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
@@ -36,6 +27,8 @@
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/reporting_util.h"
#include "chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service.h"
+#include "chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service_factory.h"
+#include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_utils.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/common/extensions/api/safe_browsing_private.h"
@@ -45,18 +38,27 @@
#include "components/policy/core/common/cloud/machine_level_user_cloud_policy_manager.h"
#include "components/policy/core/common/cloud/realtime_reporting_job_configuration.h"
#include "components/prefs/pref_service.h"
+#include "components/safe_browsing/content/web_ui/safe_browsing_ui.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/safe_browsing/core/proto/webprotect.pb.h"
#include "components/signin/public/identity_manager/identity_manager.h"
-#if defined(OS_CHROMEOS)
-#include "components/user_manager/user.h"
-#include "components/user_manager/user_manager.h"
-#endif
#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"
+#if defined(OS_CHROMEOS)
+#include "chrome/browser/browser_process_platform_part_chromeos.h"
+#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
+#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#include "components/user_manager/user.h"
+#include "components/user_manager/user_manager.h"
+#else
+#include "chrome/browser/policy/browser_dm_token_storage.h"
+#include "chrome/browser/policy/chrome_browser_cloud_management_controller.h"
+#endif
+
namespace {
#if defined(OS_CHROMEOS)
@@ -68,46 +70,29 @@ const char kChromeBrowserCloudManagementClientDescription[] =
"a machine-level user";
#endif
-void AddDlpVerdictToEvent(const safe_browsing::DlpDeepScanningVerdict& verdict,
- base::Value* event) {
+void AddAnalysisConnectorVerdictToEvent(
+ const safe_browsing::ContentAnalysisScanResult& result,
+ base::Value* event) {
DCHECK(event);
base::ListValue triggered_rule_info;
- for (const auto& rule : verdict.triggered_rules()) {
+ for (const auto& trigger : result.triggers) {
base::Value triggered_rule(base::Value::Type::DICTIONARY);
- triggered_rule.SetIntKey(
- extensions::SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleId,
- rule.rule_id());
+ int64_t rule_id;
+ if (base::StringToInt64(trigger.id, &rule_id)) {
+ triggered_rule.SetIntKey(
+ extensions::SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleId,
+ rule_id);
+ } else {
+ triggered_rule.SetIntKey(
+ extensions::SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleId, 0);
+ }
+
triggered_rule.SetStringKey(
extensions::SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleName,
- rule.rule_name());
- triggered_rule.SetStringKey(extensions::SafeBrowsingPrivateEventRouter::
- kKeyTriggeredRuleResourceName,
- rule.rule_resource_name());
- triggered_rule.SetStringKey(
- extensions::SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleSeverity,
- rule.rule_severity());
+ trigger.name);
triggered_rule.SetIntKey(
extensions::SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleAction,
- rule.action());
-
- base::ListValue matched_detectors;
- for (const auto& detector : rule.matched_detectors()) {
- base::Value matched_detector(base::Value::Type::DICTIONARY);
- matched_detector.SetStringKey(
- extensions::SafeBrowsingPrivateEventRouter::kKeyMatchedDetectorId,
- detector.detector_id());
- matched_detector.SetStringKey(
- extensions::SafeBrowsingPrivateEventRouter::kKeyMatchedDetectorName,
- detector.display_name());
- matched_detector.SetStringKey(
- extensions::SafeBrowsingPrivateEventRouter::kKeyMatchedDetectorType,
- detector.detector_type());
-
- matched_detectors.Append(std::move(matched_detector));
- }
- triggered_rule.SetKey(
- extensions::SafeBrowsingPrivateEventRouter::kKeyMatchedDetectors,
- std::move(matched_detectors));
+ trigger.action);
triggered_rule_info.Append(std::move(triggered_rule));
}
@@ -116,12 +101,22 @@ void AddDlpVerdictToEvent(const safe_browsing::DlpDeepScanningVerdict& verdict,
std::move(triggered_rule_info));
}
+std::string MalwareRuleToThreatType(const std::string& rule_name) {
+ if (rule_name == "UWS") {
+ return "POTENTIALLY_UNWANTED";
+ } else if (rule_name == "MALWARE") {
+ return "DANGEROUS";
+ } else {
+ return "UNKNOWN";
+ }
+}
+
} // namespace
namespace extensions {
const base::Feature SafeBrowsingPrivateEventRouter::kRealtimeReportingFeature{
- "SafeBrowsingRealtimeReporting", base::FEATURE_ENABLED_BY_DEFAULT};
+ "SafeBrowsingRealtimeReporting", base::FEATURE_DISABLED_BY_DEFAULT};
// Key names used with when building the dictionary to pass to the real-time
// reporting API.
@@ -140,19 +135,7 @@ const char SafeBrowsingPrivateEventRouter::kKeyClickedThrough[] =
"clickedThrough";
const char SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleId[] = "ruleId";
const char SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleName[] = "ruleName";
-const char SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleResourceName[] =
- "ruleResourceName";
-const char SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleSeverity[] =
- "severity";
const char SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleAction[] = "action";
-const char SafeBrowsingPrivateEventRouter::kKeyMatchedDetectors[] =
- "matchedDetectors";
-const char SafeBrowsingPrivateEventRouter::kKeyMatchedDetectorId[] =
- "detectorId";
-const char SafeBrowsingPrivateEventRouter::kKeyMatchedDetectorName[] =
- "displayName";
-const char SafeBrowsingPrivateEventRouter::kKeyMatchedDetectorType[] =
- "detectorType";
const char SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleInfo[] =
"triggeredRuleInfo";
const char SafeBrowsingPrivateEventRouter::kKeyThreatType[] = "threatType";
@@ -172,6 +155,8 @@ const char SafeBrowsingPrivateEventRouter::kKeySensitiveDataEvent[] =
"sensitiveDataEvent";
const char SafeBrowsingPrivateEventRouter::kKeyUnscannedFileEvent[] =
"unscannedFileEvent";
+const char SafeBrowsingPrivateEventRouter::kKeyUnscannedReason[] =
+ "unscannedReason";
const char SafeBrowsingPrivateEventRouter::kTriggerFileDownload[] =
"FILE_DOWNLOAD";
@@ -183,18 +168,6 @@ SafeBrowsingPrivateEventRouter::SafeBrowsingPrivateEventRouter(
content::BrowserContext* context)
: context_(context) {
event_router_ = EventRouter::Get(context_);
-
- // g_browser_process and/or g_browser_process->local_state() may be null
- // in tests.
- if (g_browser_process && g_browser_process->local_state()) {
- RealtimeReportingPrefChanged(std::string());
- registrar_.Init(g_browser_process->local_state());
- registrar_.Add(
- prefs::kUnsafeEventsReportingEnabled,
- base::BindRepeating(
- &SafeBrowsingPrivateEventRouter::RealtimeReportingPrefChanged,
- base::Unretained(this)));
- }
}
SafeBrowsingPrivateEventRouter::~SafeBrowsingPrivateEventRouter() {}
@@ -418,6 +391,30 @@ void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialProceeded(
params.url, params.reason, net_error_code, params.user_name));
}
+void SafeBrowsingPrivateEventRouter::OnAnalysisConnectorResult(
+ const GURL& url,
+ const std::string& file_name,
+ const std::string& download_digest_sha256,
+ const std::string& mime_type,
+ const std::string& trigger,
+ safe_browsing::DeepScanAccessPoint /* access_point */,
+ const safe_browsing::ContentAnalysisScanResult& result,
+ const int64_t content_size) {
+ if (!IsRealtimeReportingEnabled())
+ return;
+
+ if (result.tag == "malware") {
+ DCHECK_EQ(1u, result.triggers.size());
+ OnDangerousDeepScanningResult(
+ url, file_name, download_digest_sha256,
+ MalwareRuleToThreatType(result.triggers[0].name), mime_type, trigger,
+ content_size);
+ } else if (result.tag == "dlp") {
+ OnSensitiveDataEvent(url, file_name, download_digest_sha256, mime_type,
+ trigger, result, content_size);
+ }
+}
+
void SafeBrowsingPrivateEventRouter::OnDangerousDeepScanningResult(
const GURL& url,
const std::string& file_name,
@@ -459,12 +456,12 @@ void SafeBrowsingPrivateEventRouter::OnDangerousDeepScanningResult(
}
void SafeBrowsingPrivateEventRouter::OnSensitiveDataEvent(
- const safe_browsing::DlpDeepScanningVerdict& verdict,
const GURL& url,
const std::string& file_name,
const std::string& download_digest_sha256,
const std::string& mime_type,
const std::string& trigger,
+ const safe_browsing::ContentAnalysisScanResult& result,
const int64_t content_size) {
if (!IsRealtimeReportingEnabled())
return;
@@ -472,7 +469,7 @@ void SafeBrowsingPrivateEventRouter::OnSensitiveDataEvent(
ReportRealtimeEvent(
kKeySensitiveDataEvent,
base::BindOnce(
- [](const safe_browsing::DlpDeepScanningVerdict& verdict,
+ [](const safe_browsing::ContentAnalysisScanResult& result,
const std::string& url, const std::string& file_name,
const std::string& download_digest_sha256,
const std::string& profile_user_name, const std::string& mime_type,
@@ -493,33 +490,38 @@ void SafeBrowsingPrivateEventRouter::OnSensitiveDataEvent(
event.SetStringKey(kKeyTrigger, trigger);
event.SetBoolKey(kKeyClickedThrough, false);
- AddDlpVerdictToEvent(verdict, &event);
+ AddAnalysisConnectorVerdictToEvent(result, &event);
return event;
},
- verdict, url.spec(), file_name, download_digest_sha256,
+ result, url.spec(), file_name, download_digest_sha256,
GetProfileUserName(), mime_type, trigger, content_size));
}
-void SafeBrowsingPrivateEventRouter::OnSensitiveDataWarningBypassed(
- const safe_browsing::DlpDeepScanningVerdict& verdict,
+void SafeBrowsingPrivateEventRouter::OnAnalysisConnectorWarningBypassed(
const GURL& url,
const std::string& file_name,
const std::string& download_digest_sha256,
const std::string& mime_type,
const std::string& trigger,
+ safe_browsing::DeepScanAccessPoint access_point,
+ const safe_browsing::ContentAnalysisScanResult& result,
const int64_t content_size) {
if (!IsRealtimeReportingEnabled())
return;
+ DCHECK_EQ("dlp", result.tag);
+
ReportRealtimeEvent(
kKeySensitiveDataEvent,
base::BindOnce(
- [](const safe_browsing::DlpDeepScanningVerdict& verdict,
+ [](const safe_browsing::ContentAnalysisScanResult& result,
const std::string& url, const std::string& file_name,
const std::string& download_digest_sha256,
const std::string& profile_user_name, const std::string& mime_type,
- const std::string& trigger, const int64_t content_size) {
+ const std::string& trigger,
+ safe_browsing::DeepScanAccessPoint /* access_point */,
+ const int64_t content_size) {
// Create a real-time event dictionary from the arguments and
// report it.
base::Value event(base::Value::Type::DICTIONARY);
@@ -536,12 +538,13 @@ void SafeBrowsingPrivateEventRouter::OnSensitiveDataWarningBypassed(
event.SetStringKey(kKeyTrigger, trigger);
event.SetBoolKey(kKeyClickedThrough, true);
- AddDlpVerdictToEvent(verdict, &event);
+ AddAnalysisConnectorVerdictToEvent(result, &event);
return event;
},
- verdict, url.spec(), file_name, download_digest_sha256,
- GetProfileUserName(), mime_type, trigger, content_size));
+ result, url.spec(), file_name, download_digest_sha256,
+ GetProfileUserName(), mime_type, trigger, access_point,
+ content_size));
}
void SafeBrowsingPrivateEventRouter::OnUnscannedFileEvent(
@@ -550,6 +553,7 @@ void SafeBrowsingPrivateEventRouter::OnUnscannedFileEvent(
const std::string& download_digest_sha256,
const std::string& mime_type,
const std::string& trigger,
+ safe_browsing::DeepScanAccessPoint access_point,
const std::string& reason,
const int64_t content_size) {
if (!IsRealtimeReportingEnabled())
@@ -561,8 +565,9 @@ void SafeBrowsingPrivateEventRouter::OnUnscannedFileEvent(
[](const std::string& url, const std::string& file_name,
const std::string& download_digest_sha256,
const std::string& profile_user_name, const std::string& mime_type,
- const std::string& trigger, const std::string& reason,
- const int64_t content_size) {
+ const std::string& trigger,
+ safe_browsing::DeepScanAccessPoint access_point,
+ const std::string& reason, const int64_t content_size) {
// Create a real-time event dictionary from the arguments and
// report it.
base::Value event(base::Value::Type::DICTIONARY);
@@ -572,7 +577,7 @@ void SafeBrowsingPrivateEventRouter::OnUnscannedFileEvent(
download_digest_sha256);
event.SetStringKey(kKeyProfileUserName, profile_user_name);
event.SetStringKey(kKeyContentType, mime_type);
- event.SetStringKey(kKeyReason, reason);
+ event.SetStringKey(kKeyUnscannedReason, reason);
// |content_size| can be set to -1 to indicate an unknown size, in
// which case the field is not set.
if (content_size >= 0)
@@ -581,7 +586,7 @@ void SafeBrowsingPrivateEventRouter::OnUnscannedFileEvent(
return event;
},
url.spec(), file_name, download_digest_sha256, GetProfileUserName(),
- mime_type, trigger, reason, content_size));
+ mime_type, trigger, access_point, reason, content_size));
}
void SafeBrowsingPrivateEventRouter::OnDangerousDownloadWarning(
@@ -664,7 +669,9 @@ void SafeBrowsingPrivateEventRouter::OnDangerousDownloadWarningBypassed(
// static
bool SafeBrowsingPrivateEventRouter::ShouldInitRealtimeReportingClient() {
- if (!base::FeatureList::IsEnabled(kRealtimeReportingFeature)) {
+ if (!base::FeatureList::IsEnabled(kRealtimeReportingFeature) &&
+ !base::FeatureList::IsEnabled(
+ enterprise_connectors::kEnterpriseConnectorsEnabled)) {
DVLOG(2) << "Safe browsing real-time reporting is not enabled.";
return false;
}
@@ -687,6 +694,11 @@ void SafeBrowsingPrivateEventRouter::SetBinaryUploadServiceForTesting(
binary_upload_service_ = binary_upload_service;
}
+void SafeBrowsingPrivateEventRouter::SetIdentityManagerForTesting(
+ signin::IdentityManager* identity_manager) {
+ identity_manager_ = identity_manager;
+}
+
void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClient() {
// If already initialized, do nothing.
if (client_) {
@@ -719,26 +731,6 @@ void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClient() {
return;
}
- if (g_browser_process) {
- binary_upload_service_ =
- safe_browsing::BinaryUploadServiceFactory::GetForProfile(
- Profile::FromBrowserContext(context_));
- IfAuthorized(base::BindOnce(
- &SafeBrowsingPrivateEventRouter::InitRealtimeReportingClientCallback,
- weak_ptr_factory_.GetWeakPtr(), device_management_service));
- }
-}
-
-void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClientCallback(
- policy::DeviceManagementService* device_management_service,
- bool authorized) {
- // Don't initialize the client if the browser cannot upload data.
- if (!authorized) {
- LOG(WARNING) << "The client is not authorized to do safe browsing "
- "real-time event reporting.";
- return;
- }
-
policy::CloudPolicyClient* client = nullptr;
std::string policy_client_desc;
@@ -791,6 +783,11 @@ void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClientCallback(
policy::CloudPolicyClient::DeviceDMTokenCallback());
client = private_client_.get();
+ // TODO(crbug.com/1069049): when we decide to add the extra URL parameters to
+ // the uploaded reports, do the following:
+ // client->add_connector_url_params(base::FeatureList::IsEnabled(
+ // enterprise_connectors::kEnterpriseConnectorsEnabled));
+
if (!client->is_registered()) {
client->SetupRegistration(
dm_token.value(), client_id,
@@ -815,25 +812,24 @@ void SafeBrowsingPrivateEventRouter::OnCloudPolicyClientAvailable(
}
bool SafeBrowsingPrivateEventRouter::IsRealtimeReportingEnabled() {
- // g_browser_process and/or g_browser_process->local_state() may be null
- // in tests.
- return g_browser_process && g_browser_process->local_state() &&
- g_browser_process->local_state()->GetBoolean(
- prefs::kUnsafeEventsReportingEnabled);
-}
-
-void SafeBrowsingPrivateEventRouter::RealtimeReportingPrefChanged(
- const std::string& pref) {
- // If the reporting policy has been turned on, try to initialized now.
- if (IsRealtimeReportingEnabled())
- InitRealtimeReportingClient();
+ auto settings =
+ enterprise_connectors::ConnectorsManager::GetInstance()
+ ->GetReportingSettings(
+ enterprise_connectors::ReportingConnector::SECURITY_EVENT);
+ return settings.has_value();
}
void SafeBrowsingPrivateEventRouter::IfAuthorized(
base::OnceCallback<void(bool)> cont) {
- if (binary_upload_service_) {
- binary_upload_service_->IsAuthorized(std::move(cont));
+ if (!binary_upload_service_ && g_browser_process) {
+ binary_upload_service_ =
+ safe_browsing::BinaryUploadServiceFactory::GetForProfile(
+ Profile::FromBrowserContext(context_));
}
+
+ // TODO(crbug/1069049): Use reporting URL.
+ if (binary_upload_service_)
+ binary_upload_service_->IsAuthorized(GURL(), std::move(cont));
}
void SafeBrowsingPrivateEventRouter::ReportRealtimeEvent(
@@ -854,8 +850,10 @@ void SafeBrowsingPrivateEventRouter::ReportRealtimeEventCallback(
return;
}
- // |client_| should be set when authorized is true.
- DCHECK(client_);
+ // Make sure real-time reporting is initialized.
+ InitRealtimeReportingClient();
+ if (!client_)
+ return;
// Format the current time (UTC) in RFC3339 format.
base::Time::Exploded now_exploded;
@@ -884,10 +882,18 @@ void SafeBrowsingPrivateEventRouter::ReportRealtimeEventCallback(
}
std::string SafeBrowsingPrivateEventRouter::GetProfileUserName() const {
- // |identity_manager_| may be null is some tests.
- return identity_manager_ && identity_manager_->HasPrimaryAccount()
- ? identity_manager_->GetPrimaryAccountInfo().email
- : std::string();
+ // |identity_manager_| may be null in some tests.
+ if (!identity_manager_)
+ return std::string();
+
+ if (!identity_manager_->HasPrimaryAccount(
+ signin::ConsentLevel::kNotRequired)) {
+ return std::string();
+ }
+
+ return identity_manager_
+ ->GetPrimaryAccountInfo(signin::ConsentLevel::kNotRequired)
+ .email;
}
#if defined(OS_CHROMEOS)
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 dc0ceea0b29..da76717180d 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
@@ -14,7 +14,6 @@
#include "base/memory/weak_ptr.h"
#include "base/values.h"
#include "components/keyed_service/core/keyed_service.h"
-#include "components/prefs/pref_change_registrar.h"
namespace content {
class BrowserContext;
@@ -37,7 +36,8 @@ class DeviceManagementService;
namespace safe_browsing {
class BinaryUploadService;
-class DlpDeepScanningVerdict;
+enum class DeepScanAccessPoint;
+struct ContentAnalysisScanResult;
}
#if defined(OS_CHROMEOS)
@@ -71,13 +71,7 @@ class SafeBrowsingPrivateEventRouter : public KeyedService {
static const char kKeyClickedThrough[];
static const char kKeyTriggeredRuleId[];
static const char kKeyTriggeredRuleName[];
- static const char kKeyTriggeredRuleResourceName[];
- static const char kKeyTriggeredRuleSeverity[];
static const char kKeyTriggeredRuleAction[];
- static const char kKeyMatchedDetectors[];
- static const char kKeyMatchedDetectorId[];
- static const char kKeyMatchedDetectorName[];
- static const char kKeyMatchedDetectorType[];
static const char kKeyTriggeredRuleInfo[];
static const char kKeyThreatType[];
static const char kKeyContentType[];
@@ -90,8 +84,10 @@ class SafeBrowsingPrivateEventRouter : public KeyedService {
static const char kKeyInterstitialEvent[];
static const char kKeySensitiveDataEvent[];
static const char kKeyUnscannedFileEvent[];
+ static const char kKeyUnscannedReason[];
- // String constants for the "trigger" event field.
+ // String constants for the "trigger" event field. This corresponds to
+ // an enterprise connector.
static const char kTriggerFileDownload[];
static const char kTriggerFileUpload[];
static const char kTriggerWebContentUpload[];
@@ -126,33 +122,26 @@ class SafeBrowsingPrivateEventRouter : public KeyedService {
const std::string& reason,
int net_error_code);
- // Notifies listeners that deep scanning detected a dangerous download.
- void OnDangerousDeepScanningResult(const GURL& url,
- const std::string& file_name,
- const std::string& download_digest_sha256,
- const std::string& threat_type,
- const std::string& mime_type,
- const std::string& trigger,
- const int64_t content_size);
-
- // Notifies listeners that scanning for sensitive data detected a violation.
- void OnSensitiveDataEvent(
- const safe_browsing::DlpDeepScanningVerdict& verdict,
+ // Notifies listeners that the analysis connector detected a violation.
+ void OnAnalysisConnectorResult(
const GURL& url,
const std::string& file_name,
const std::string& download_digest_sha256,
const std::string& mime_type,
const std::string& trigger,
+ safe_browsing::DeepScanAccessPoint access_point,
+ const safe_browsing::ContentAnalysisScanResult& result,
const int64_t content_size);
- // Notifies listeners that scanning for sensitive data detected a violation.
- void OnSensitiveDataWarningBypassed(
- const safe_browsing::DlpDeepScanningVerdict& verdict,
+ // Notifies listeners that an analysis connector violation was bypassed.
+ void OnAnalysisConnectorWarningBypassed(
const GURL& url,
const std::string& file_name,
const std::string& download_digest_sha256,
const std::string& mime_type,
const std::string& trigger,
+ safe_browsing::DeepScanAccessPoint access_point,
+ const safe_browsing::ContentAnalysisScanResult& result,
const int64_t content_size);
// Notifies listeners that deep scanning failed, for the given |reason|.
@@ -161,6 +150,7 @@ class SafeBrowsingPrivateEventRouter : public KeyedService {
const std::string& download_digest_sha256,
const std::string& mime_type,
const std::string& trigger,
+ safe_browsing::DeepScanAccessPoint access_point,
const std::string& reason,
const int64_t content_size);
@@ -199,6 +189,8 @@ class SafeBrowsingPrivateEventRouter : public KeyedService {
void SetBinaryUploadServiceForTesting(
safe_browsing::BinaryUploadService* binary_upload_service);
+ void SetIdentityManagerForTesting(signin::IdentityManager* identity_manager);
+
protected:
// Callback to report safe browsing event through real-time reporting channel,
// if the browser is authorized to do so. Declared as protected to be called
@@ -215,12 +207,6 @@ class SafeBrowsingPrivateEventRouter : public KeyedService {
// with CBCM and the appropriate policies are enabled.
void InitRealtimeReportingClient();
- // Initialize DeviceManagementService and |client_| after validating the
- // browser can upload data.
- void InitRealtimeReportingClientCallback(
- policy::DeviceManagementService* device_management_service,
- bool authorized);
-
// Continues execution if the client is authorized to do so.
void IfAuthorized(base::OnceCallback<void(bool)> cont);
@@ -261,6 +247,25 @@ class SafeBrowsingPrivateEventRouter : public KeyedService {
// an empty string if the profile is not signed in.
std::string GetProfileUserName() const;
+ // Notifies listeners that deep scanning detected a dangerous download.
+ void OnDangerousDeepScanningResult(const GURL& url,
+ const std::string& file_name,
+ const std::string& download_digest_sha256,
+ const std::string& threat_type,
+ const std::string& mime_type,
+ const std::string& trigger,
+ const int64_t content_size);
+
+ // Notifies listeners that the analysis connector detected a violation.
+ void OnSensitiveDataEvent(
+ const GURL& url,
+ const std::string& file_name,
+ const std::string& download_digest_sha256,
+ const std::string& mime_type,
+ const std::string& trigger,
+ const safe_browsing::ContentAnalysisScanResult& result,
+ const int64_t content_size);
+
content::BrowserContext* context_;
signin::IdentityManager* identity_manager_ = nullptr;
EventRouter* event_router_ = nullptr;
@@ -271,7 +276,6 @@ class SafeBrowsingPrivateEventRouter : public KeyedService {
// The |private_client_| is used on platforms where we cannot just get a
// client and we create our own (used through |client_|).
std::unique_ptr<policy::CloudPolicyClient> private_client_;
- PrefChangeRegistrar registrar_;
base::WeakPtrFactory<SafeBrowsingPrivateEventRouter> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateEventRouter);
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 3b5e213a364..4685fb42d13 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
@@ -3,9 +3,11 @@
// found in the LICENSE file.
#include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h"
+#include <memory>
#include <utility>
#include "base/bind.h"
+#include "base/json/json_reader.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/mock_callback.h"
@@ -13,7 +15,10 @@
#include "base/values.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
+#include "chrome/browser/enterprise/connectors/common.h"
+#include "chrome/browser/enterprise/connectors/connectors_manager.h"
#include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.h"
+#include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_utils.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/api/safe_browsing_private.h"
#include "chrome/test/base/testing_browser_process.h"
@@ -22,7 +27,9 @@
#include "components/policy/core/common/cloud/mock_cloud_policy_client.h"
#include "components/policy/core/common/cloud/realtime_reporting_job_configuration.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
+#include "components/safe_browsing/core/features.h"
#include "components/safe_browsing/core/proto/webprotect.pb.h"
+#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "content/public/test/browser_task_environment.h"
#include "extensions/browser/test_event_router.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -40,6 +47,7 @@
using ::testing::_;
using ::testing::Mock;
+using ::testing::Return;
using ::testing::SaveArg;
namespace extensions {
@@ -50,6 +58,12 @@ ACTION_P(CaptureArg, wrapper) {
*wrapper = arg0.Clone();
}
+constexpr char kConnectorsPrefValue[] = R"([
+ {
+ "service_provider": "google"
+ }
+])";
+
} // namespace
class FakeAuthorizedSafeBrowsingPrivateEventRouter
@@ -175,41 +189,31 @@ class SafeBrowsingPrivateEventRouterTest : public testing::Test {
}
void TriggerOnSensitiveDataEvent() {
- safe_browsing::DlpDeepScanningVerdict verdict;
- verdict.set_status(safe_browsing::DlpDeepScanningVerdict::SUCCESS);
- safe_browsing::DlpDeepScanningVerdict::TriggeredRule* rule =
- verdict.add_triggered_rules();
- rule->set_action(
- safe_browsing::DlpDeepScanningVerdict::TriggeredRule::BLOCK);
- rule->set_rule_name("fake rule");
- rule->set_rule_id(12345);
- rule->set_rule_resource_name("fake resource name");
- rule->set_rule_severity("fake severity");
-
- safe_browsing::DlpDeepScanningVerdict::MatchedDetector* detector =
- rule->add_matched_detectors();
- detector->set_detector_id("fake id");
- detector->set_display_name("fake name");
- detector->set_detector_type("fake type");
-
- detector = rule->add_matched_detectors();
- detector->set_detector_id("fake id2");
- detector->set_display_name("fake name2");
- detector->set_detector_type("fake type2");
+ safe_browsing::ContentAnalysisScanResult result;
+ result.tag = "dlp";
+ result.status = 1;
+ safe_browsing::ContentAnalysisTrigger trigger;
+ trigger.action = 3;
+ trigger.name = "fake rule";
+ trigger.id = "12345";
+ result.triggers.push_back(std::move(trigger));
SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_)
- ->OnSensitiveDataEvent(verdict,
- GURL("https://evil.com/sensitive_data.txt"),
- "sensitive_data.txt", "sha256_of_data",
- "text/plain", "FILE_UPLOAD", 12345);
+ ->OnAnalysisConnectorResult(
+ GURL("https://evil.com/sensitive_data.txt"), "sensitive_data.txt",
+ "sha256_of_data", "text/plain",
+ SafeBrowsingPrivateEventRouter::kTriggerFileUpload,
+ safe_browsing::DeepScanAccessPoint::UPLOAD, result, 12345);
}
void TriggerOnUnscannedFileEvent() {
SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_)
- ->OnUnscannedFileEvent(GURL("https://evil.com/sensitive_data.txt"),
- "sensitive_data.txt", "sha256_of_data",
- "text/plain", "FILE_DOWNLOAD",
- "filePasswordProtected", 12345);
+ ->OnUnscannedFileEvent(
+ GURL("https://evil.com/sensitive_data.txt"), "sensitive_data.txt",
+ "sha256_of_data", "text/plain",
+ SafeBrowsingPrivateEventRouter::kTriggerFileDownload,
+ safe_browsing::DeepScanAccessPoint::DOWNLOAD,
+ "filePasswordProtected", 12345);
}
void SetReportingPolicy(bool enabled) {
@@ -714,7 +718,7 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSensitiveDataEvent) {
EXPECT_EQ(
"sensitive_data.txt",
*event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyFileName));
- EXPECT_EQ("FILE_UPLOAD",
+ EXPECT_EQ(SafeBrowsingPrivateEventRouter::kTriggerFileUpload,
*event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyTrigger));
base::Value* triggered_rule_info =
@@ -729,27 +733,6 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSensitiveDataEvent) {
EXPECT_EQ("fake rule",
*triggered_rule.FindStringKey(
SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleName));
- EXPECT_EQ("fake resource name",
- *triggered_rule.FindStringKey(
- SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleResourceName));
- EXPECT_EQ("fake severity",
- *triggered_rule.FindStringKey(
- SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleSeverity));
-
- base::Value* matched_detectors = triggered_rule.FindKey(
- SafeBrowsingPrivateEventRouter::kKeyMatchedDetectors);
- ASSERT_NE(nullptr, matched_detectors);
- ASSERT_EQ(2u, matched_detectors->GetList().size());
- base::Value detector = std::move(matched_detectors->GetList()[0]);
- EXPECT_EQ("fake id",
- *detector.FindStringKey(
- SafeBrowsingPrivateEventRouter::kKeyMatchedDetectorId));
- EXPECT_EQ("fake type",
- *detector.FindStringKey(
- SafeBrowsingPrivateEventRouter::kKeyMatchedDetectorType));
- EXPECT_EQ("fake name",
- *detector.FindStringKey(
- SafeBrowsingPrivateEventRouter::kKeyMatchedDetectorName));
}
TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnUnscannedFileEvent) {
@@ -786,10 +769,48 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnUnscannedFileEvent) {
EXPECT_EQ(
"sensitive_data.txt",
*event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyFileName));
- EXPECT_EQ("FILE_DOWNLOAD",
+ EXPECT_EQ(SafeBrowsingPrivateEventRouter::kTriggerFileDownload,
*event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyTrigger));
EXPECT_EQ("filePasswordProtected",
- *event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyReason));
+ *event->FindStringKey(
+ SafeBrowsingPrivateEventRouter::kKeyUnscannedReason));
+}
+
+TEST_F(SafeBrowsingPrivateEventRouterTest, TestProfileUsername) {
+ SetUpRouters();
+ SafeBrowsingEventObserver event_observer(
+ api::safe_browsing_private::OnSecurityInterstitialShown::kEventName);
+ event_router_->AddEventObserver(&event_observer);
+
+ signin::IdentityTestEnvironment identity_test_environment;
+ SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_)
+ ->SetIdentityManagerForTesting(
+ identity_test_environment.identity_manager());
+
+ EXPECT_CALL(*client_, UploadRealtimeReport_(_, _)).WillRepeatedly(Return());
+
+ // With no primary account, we should not set the username.
+ TriggerOnSecurityInterstitialShownEvent();
+ base::RunLoop().RunUntilIdle();
+ auto captured_args = event_observer.PassEventArgs().GetList()[0].Clone();
+ EXPECT_EQ("", captured_args.FindKey("userName")->GetString());
+
+ // With an unconsented primary account, we should set the username.
+ identity_test_environment.MakeUnconsentedPrimaryAccountAvailable(
+ "profile@example.com");
+ TriggerOnSecurityInterstitialShownEvent();
+ base::RunLoop().RunUntilIdle();
+ captured_args = event_observer.PassEventArgs().GetList()[0].Clone();
+ EXPECT_EQ("profile@example.com",
+ captured_args.FindKey("userName")->GetString());
+
+ // With a consented primary account, we should set the username.
+ identity_test_environment.MakePrimaryAccountAvailable("profile@example.com");
+ TriggerOnSecurityInterstitialShownEvent();
+ base::RunLoop().RunUntilIdle();
+ captured_args = event_observer.PassEventArgs().GetList()[0].Clone();
+ EXPECT_EQ("profile@example.com",
+ captured_args.FindKey("userName")->GetString());
}
// Tests to make sure the feature flag and policy control real-time reporting
@@ -799,22 +820,42 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnUnscannedFileEvent) {
// bool: whether the browser is manageable.
// bool: whether the policy is enabled.
// bool: whether the server has authorized this browser instance.
+// bool: whether to use new connectors or old legacy code.
class SafeBrowsingIsRealtimeReportingEnabledTest
: public SafeBrowsingPrivateEventRouterTest,
public testing::WithParamInterface<
- testing::tuple<bool, bool, bool, bool>> {
+ testing::tuple<bool, bool, bool, bool, bool>> {
public:
SafeBrowsingIsRealtimeReportingEnabledTest()
: is_feature_flag_enabled_(testing::get<0>(GetParam())),
is_manageable_(testing::get<1>(GetParam())),
is_policy_enabled_(testing::get<2>(GetParam())),
- is_authorized_(testing::get<3>(GetParam())) {
- if (is_feature_flag_enabled_) {
- scoped_feature_list_.InitAndEnableFeature(
- SafeBrowsingPrivateEventRouter::kRealtimeReportingFeature);
+ is_authorized_(testing::get<3>(GetParam())),
+ use_new_connectors_(testing::get<4>(GetParam())) {
+ if (use_new_connectors_) {
+ if (is_feature_flag_enabled_) {
+ scoped_feature_list_.InitWithFeatures(
+ {enterprise_connectors::kEnterpriseConnectorsEnabled},
+ {extensions::SafeBrowsingPrivateEventRouter::
+ kRealtimeReportingFeature});
+ } else {
+ scoped_feature_list_.InitWithFeatures(
+ {}, {enterprise_connectors::kEnterpriseConnectorsEnabled,
+ extensions::SafeBrowsingPrivateEventRouter::
+ kRealtimeReportingFeature});
+ }
} else {
- scoped_feature_list_.InitAndDisableFeature(
- SafeBrowsingPrivateEventRouter::kRealtimeReportingFeature);
+ if (is_feature_flag_enabled_) {
+ scoped_feature_list_.InitWithFeatures(
+ {extensions::SafeBrowsingPrivateEventRouter::
+ kRealtimeReportingFeature},
+ {enterprise_connectors::kEnterpriseConnectorsEnabled});
+ } else {
+ scoped_feature_list_.InitWithFeatures(
+ {}, {enterprise_connectors::kEnterpriseConnectorsEnabled,
+ extensions::SafeBrowsingPrivateEventRouter::
+ kRealtimeReportingFeature});
+ }
}
// In chrome branded desktop builds, the browser is always manageable.
@@ -825,8 +866,17 @@ class SafeBrowsingIsRealtimeReportingEnabledTest
}
#endif
- TestingBrowserProcess::GetGlobal()->local_state()->SetBoolean(
- prefs::kUnsafeEventsReportingEnabled, is_policy_enabled_);
+ if (use_new_connectors_) {
+ if (is_policy_enabled_) {
+ scoped_connector_pref_ = std::make_unique<ScopedConnectorPref>(
+ ConnectorPref(
+ enterprise_connectors::ReportingConnector::SECURITY_EVENT),
+ kConnectorsPrefValue);
+ }
+ } else {
+ TestingBrowserProcess::GetGlobal()->local_state()->SetBoolean(
+ prefs::kUnsafeEventsReportingEnabled, is_policy_enabled_);
+ }
#if defined(OS_CHROMEOS)
auto user_manager = std::make_unique<chromeos::FakeChromeUserManager>();
@@ -847,6 +897,15 @@ class SafeBrowsingIsRealtimeReportingEnabledTest
#endif
}
+ void SetUp() override {
+ enterprise_connectors::ConnectorsManager::GetInstance()->SetUpForTesting();
+ }
+
+ void TearDown() override {
+ enterprise_connectors::ConnectorsManager::GetInstance()
+ ->TearDownForTesting();
+ }
+
bool should_init() {
#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && !defined(OS_CHROMEOS)
return is_feature_flag_enabled_;
@@ -856,11 +915,32 @@ class SafeBrowsingIsRealtimeReportingEnabledTest
}
protected:
+ class ScopedConnectorPref {
+ public:
+ ScopedConnectorPref(const char* pref, const char* pref_value)
+ : pref_(pref) {
+ auto maybe_pref_value =
+ base::JSONReader::Read(pref_value, base::JSON_ALLOW_TRAILING_COMMAS);
+ EXPECT_TRUE(maybe_pref_value.has_value());
+ TestingBrowserProcess::GetGlobal()->local_state()->Set(
+ pref, maybe_pref_value.value());
+ }
+
+ ~ScopedConnectorPref() {
+ TestingBrowserProcess::GetGlobal()->local_state()->ClearPref(pref_);
+ }
+
+ private:
+ const char* pref_;
+ };
+
base::test::ScopedFeatureList scoped_feature_list_;
+ std::unique_ptr<ScopedConnectorPref> scoped_connector_pref_;
const bool is_feature_flag_enabled_;
const bool is_manageable_;
const bool is_policy_enabled_;
const bool is_authorized_;
+ const bool use_new_connectors_;
#if defined(OS_CHROMEOS)
private:
@@ -918,6 +998,7 @@ INSTANTIATE_TEST_SUITE_P(All,
testing::Combine(testing::Bool(),
testing::Bool(),
testing::Bool(),
+ testing::Bool(),
testing::Bool()));
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc
index f130eced5de..fa30a4353f0 100644
--- a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc
+++ b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc
@@ -207,7 +207,7 @@ ExtensionFunction::ResponseAction SessionsGetRecentlyClosedFunction::Run() {
TabRestoreServiceFactory::GetForProfile(
Profile::FromBrowserContext(browser_context()));
- // TabRestoreServiceFactory::GetForProfile() can return NULL (i.e., when in
+ // TabRestoreServiceFactory::GetForProfile() can return nullptr (i.e., when in
// incognito mode)
if (!tab_restore_service) {
DCHECK(browser_context()->IsOffTheRecord())
@@ -521,7 +521,7 @@ ExtensionFunction::ResponseValue SessionsRestoreFunction::RestoreForeignSession(
if (!open_tabs)
return Error(kSessionSyncError);
- const sessions::SessionTab* tab = NULL;
+ const sessions::SessionTab* tab = nullptr;
if (open_tabs->GetForeignTab(session_id.session_tag(),
SessionID::FromSerializedValue(session_id.id()),
&tab)) {
@@ -583,7 +583,7 @@ ExtensionFunction::ResponseAction SessionsRestoreFunction::Run() {
SessionsEventRouter::SessionsEventRouter(Profile* profile)
: profile_(profile),
tab_restore_service_(TabRestoreServiceFactory::GetForProfile(profile)) {
- // TabRestoreServiceFactory::GetForProfile() can return NULL (i.e., when in
+ // TabRestoreServiceFactory::GetForProfile() can return nullptr (i.e., when in
// incognito mode)
if (tab_restore_service_) {
tab_restore_service_->LoadTabsFromLastSession();
@@ -606,7 +606,7 @@ void SessionsEventRouter::TabRestoreServiceChanged(
void SessionsEventRouter::TabRestoreServiceDestroyed(
sessions::TabRestoreService* service) {
- tab_restore_service_ = NULL;
+ tab_restore_service_ = nullptr;
}
SessionsAPI::SessionsAPI(content::BrowserContext* context)
diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc b/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc
index 36e74916715..71097a37fc8 100644
--- a/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc
@@ -297,9 +297,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesListEmpty) {
EXPECT_EQ(0u, devices->GetSize());
}
-// Flaky timeout: http://crbug.com/278372
-IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest,
- DISABLED_RestoreForeignSessionWindow) {
+IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionWindow) {
CreateSessionModels();
std::unique_ptr<base::DictionaryValue> restored_window_session(
diff --git a/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.cc b/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.cc
index 18323cfb6a8..dbaadf5b940 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.cc
@@ -69,7 +69,7 @@ SetPrefResult GeneratedResolveTimezoneByGeolocationMethodShort::SetPref(
// Check if preference is policy or primary-user controlled.
if (chromeos::system::TimeZoneResolverManager::
IsTimeZoneResolutionPolicyControlled() ||
- !profile_->IsSameProfile(ProfileManager::GetPrimaryUserProfile())) {
+ !profile_->IsSameOrParent(ProfileManager::GetPrimaryUserProfile())) {
return SetPrefResult::PREF_NOT_MODIFIABLE;
}
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 3eec3a7ea37..edd89c470e1 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
@@ -73,7 +73,7 @@ SetPrefResult GeneratedResolveTimezoneByGeolocationOnOff::SetPref(
// cannot deactivate automatic timezone.
if (chromeos::system::TimeZoneResolverManager::
IsTimeZoneResolutionPolicyControlled() ||
- !profile_->IsSameProfile(ProfileManager::GetPrimaryUserProfile())) {
+ !profile_->IsSameOrParent(ProfileManager::GetPrimaryUserProfile())) {
return SetPrefResult::PREF_NOT_MODIFIABLE;
}
diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_pref.cc b/chromium/chrome/browser/extensions/api/settings_private/generated_pref.cc
index b0308f67c07..4fd337bf131 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/generated_pref.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/generated_pref.cc
@@ -4,6 +4,10 @@
#include "chrome/browser/extensions/api/settings_private/generated_pref.h"
+#include "chrome/common/extensions/api/settings_private.h"
+
+namespace settings_api = extensions::api::settings_private;
+
namespace extensions {
namespace settings_private {
@@ -26,5 +30,30 @@ void GeneratedPref::NotifyObservers(const std::string& pref_name) {
observer.OnGeneratedPrefChanged(pref_name);
}
+/* static */
+void GeneratedPref::ApplyControlledByFromPref(
+ api::settings_private::PrefObject* pref_object,
+ const PrefService::Preference* pref) {
+ if (pref->IsManaged()) {
+ pref_object->controlled_by =
+ settings_api::ControlledBy::CONTROLLED_BY_DEVICE_POLICY;
+ return;
+ }
+
+ if (pref->IsExtensionControlled()) {
+ pref_object->controlled_by =
+ settings_api::ControlledBy::CONTROLLED_BY_EXTENSION;
+ return;
+ }
+
+ if (pref->IsManagedByCustodian()) {
+ pref_object->controlled_by =
+ settings_api::ControlledBy::CONTROLLED_BY_CHILD_RESTRICTION;
+ return;
+ }
+
+ NOTREACHED();
+}
+
} // namespace settings_private
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_pref.h b/chromium/chrome/browser/extensions/api/settings_private/generated_pref.h
index 3222055de56..00264766f61 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/generated_pref.h
+++ b/chromium/chrome/browser/extensions/api/settings_private/generated_pref.h
@@ -10,6 +10,7 @@
#include "base/macros.h"
#include "base/observer_list.h"
#include "chrome/browser/extensions/api/settings_private/prefs_util_enums.h"
+#include "components/prefs/pref_service.h"
namespace base {
class Value;
@@ -62,6 +63,12 @@ class GeneratedPref {
// Call this when the pref value changes.
void NotifyObservers(const std::string& pref_name);
+ // Sets controlled_by for |pref_object| based on provided |pref| for a limited
+ // subset of controlled_by sources relevant to generated pref use cases.
+ static void ApplyControlledByFromPref(
+ api::settings_private::PrefObject* pref_object,
+ const PrefService::Preference* pref);
+
private:
base::ObserverList<Observer>::Unchecked observers_;
diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_pref_test_base.cc b/chromium/chrome/browser/extensions/api/settings_private/generated_pref_test_base.cc
new file mode 100644
index 00000000000..505519b2c08
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/settings_private/generated_pref_test_base.cc
@@ -0,0 +1,16 @@
+// Copyright 2020 The Chromium 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/settings_private/generated_pref_test_base.h"
+
+namespace extensions {
+namespace settings_private {
+
+void TestGeneratedPrefObserver::OnGeneratedPrefChanged(
+ const std::string& pref_name) {
+ updated_pref_name_ = pref_name;
+}
+
+} // namespace settings_private
+} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_pref_test_base.h b/chromium/chrome/browser/extensions/api/settings_private/generated_pref_test_base.h
new file mode 100644
index 00000000000..7036ad4ea2f
--- /dev/null
+++ b/chromium/chrome/browser/extensions/api/settings_private/generated_pref_test_base.h
@@ -0,0 +1,66 @@
+// Copyright 2020 The Chromium 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_SETTINGS_PRIVATE_GENERATED_PREF_TEST_BASE_H_
+#define CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_GENERATED_PREF_TEST_BASE_H_
+
+#include "chrome/browser/extensions/api/settings_private/generated_pref.h"
+#include "chrome/common/extensions/api/settings_private.h"
+#include "chrome/test/base/testing_profile.h"
+#include "content/public/test/browser_task_environment.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace settings_api = extensions::api::settings_private;
+
+namespace extensions {
+namespace settings_private {
+
+// All of the possible managed states for a boolean preference that can be
+// both enforced and recommended.
+enum class PrefSetting {
+ kEnforcedOff,
+ kEnforcedOn,
+ kRecommendedOff,
+ kRecommendedOn,
+ kNotSet,
+};
+
+// Possible preference sources supported by TestingPrefService.
+// TODO(crbug.com/1063281): Extend TestingPrefService to support prefs set for
+// supervised users.
+enum class PrefSource {
+ kExtension,
+ kDevicePolicy,
+ kRecommended,
+ kNone,
+};
+
+class TestGeneratedPrefObserver : public GeneratedPref::Observer {
+ public:
+ void OnGeneratedPrefChanged(const std::string& pref_name) override;
+
+ void Reset() { updated_pref_name_ = ""; }
+ std::string GetUpdatedPrefName() { return updated_pref_name_; }
+
+ protected:
+ std::string updated_pref_name_;
+};
+
+class GeneratedPrefTestBase : public testing::Test {
+ protected:
+ TestingProfile* profile() { return &profile_; }
+
+ sync_preferences::TestingPrefServiceSyncable* prefs() {
+ return profile()->GetTestingPrefService();
+ }
+
+ private:
+ content::BrowserTaskEnvironment task_environment_;
+ TestingProfile profile_;
+};
+
+} // namespace settings_private
+} // namespace extensions
+
+#endif // CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_GENERATED_PREF_TEST_BASE_H_
diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_prefs.cc b/chromium/chrome/browser/extensions/api/settings_private/generated_prefs.cc
index dff08441a4e..708717077ca 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/generated_prefs.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/generated_prefs.cc
@@ -6,9 +6,12 @@
#include "base/callback.h"
#include "build/build_config.h"
+#include "chrome/browser/content_settings/generated_cookie_prefs.h"
#include "chrome/browser/extensions/api/settings_private/generated_pref.h"
#include "chrome/browser/extensions/api/settings_private/prefs_util_enums.h"
+#include "chrome/browser/safe_browsing/generated_safe_browsing_pref.h"
#include "chrome/common/extensions/api/settings_private.h"
+#include "components/content_settings/core/common/pref_names.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.h"
@@ -25,6 +28,14 @@ GeneratedPrefs::GeneratedPrefs(Profile* profile) {
prefs_[kResolveTimezoneByGeolocationMethodShort] =
CreateGeneratedResolveTimezoneByGeolocationMethodShort(profile);
#endif
+ prefs_[content_settings::kCookiePrimarySetting] =
+ std::make_unique<content_settings::GeneratedCookiePrimarySettingPref>(
+ profile);
+ prefs_[content_settings::kCookieSessionOnly] =
+ std::make_unique<content_settings::GeneratedCookieSessionOnlyPref>(
+ profile);
+ prefs_[safe_browsing::kGeneratedSafeBrowsingPref] =
+ std::make_unique<safe_browsing::GeneratedSafeBrowsingPref>(profile);
}
GeneratedPrefs::~GeneratedPrefs() = default;
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 92dd63b50f5..b6838f04b5c 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
@@ -51,7 +51,7 @@ void GeneratedTimeZonePrefBase::UpdateTimeZonePrefControlledBy(
} else {
out_pref->enforcement = settings_api::ENFORCEMENT_ENFORCED;
}
- } else if (!profile_->IsSameProfile(
+ } else if (!profile_->IsSameOrParent(
ProfileManager::GetPrimaryUserProfile())) {
out_pref->controlled_by = settings_api::CONTROLLED_BY_PRIMARY_USER;
out_pref->controlled_by_name = std::make_unique<std::string>(
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 ea48a66ba88..a6d8479abd9 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc
@@ -9,9 +9,11 @@
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
+#include "chrome/browser/content_settings/generated_cookie_prefs.h"
#include "chrome/browser/extensions/api/settings_private/generated_prefs.h"
#include "chrome/browser/extensions/api/settings_private/generated_prefs_factory.h"
#include "chrome/browser/extensions/settings_api_helpers.h"
+#include "chrome/browser/nearby_sharing/nearby_sharing_prefs.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
@@ -286,13 +288,29 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
#if defined(OS_CHROMEOS)
(*s_whitelist)[::prefs::kLanguageImeMenuActivated] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[chromeos::prefs::kAssistPersonalInfoEnabled] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[chromeos::prefs::kEmojiSuggestionEnabled] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[::prefs::kLanguageInputMethodSpecificSettings] =
+ settings_api::PrefType::PREF_TYPE_DICTIONARY;
#endif
+ // Nearby Share.
+ (*s_whitelist)[::prefs::kNearbySharingEnabledPrefName] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[::prefs::kNearbySharingActiveProfilePrefName] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
+
// Search page.
(*s_whitelist)[DefaultSearchManager::kDefaultSearchProviderDataPrefName] =
settings_api::PrefType::PREF_TYPE_DICTIONARY;
// Site Settings prefs.
+ (*s_whitelist)[::content_settings::kCookiePrimarySetting] =
+ settings_api::PrefType::PREF_TYPE_NUMBER;
+ (*s_whitelist)[::content_settings::kCookieSessionOnly] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[::prefs::kBlockThirdPartyCookies] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[::prefs::kCookieControlsMode] =
@@ -355,6 +373,10 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
(*s_whitelist)[::prefs::kLiveCaptionEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
#endif
+#if !defined(OS_CHROMEOS)
+ (*s_whitelist)[::prefs::kAccessibilityFocusHighlightEnabled] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
+#endif
#if defined(OS_CHROMEOS)
// Accounts / Users / People.
@@ -407,6 +429,10 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[ash::prefs::kAccessibilityLargeCursorDipSize] =
settings_api::PrefType::PREF_TYPE_NUMBER;
+ (*s_whitelist)[ash::prefs::kAccessibilityCursorColorEnabled] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[ash::prefs::kAccessibilityCursorColor] =
+ settings_api::PrefType::PREF_TYPE_NUMBER;
(*s_whitelist)[ash::prefs::kAccessibilityScreenMagnifierEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[ash::prefs::kAccessibilityScreenMagnifierScale] =
@@ -471,8 +497,6 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[plugin_vm::prefs::kPluginVmPrintersAllowed] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[plugin_vm::prefs::kPluginVmCameraSharing] =
- settings_api::PrefType::PREF_TYPE_BOOLEAN;
// Android Apps.
(*s_whitelist)[arc::prefs::kArcEnabled] =
@@ -511,12 +535,12 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() {
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[chromeos::kStatsReportingPref] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
+ (*s_whitelist)[::chromeos::prefs::kSuggestedContentEnabled] =
+ settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[chromeos::kAttestationForContentProtectionEnabled] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[prefs::kRestoreLastLockScreenNote] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
- (*s_whitelist)[::prefs::kSettingsShowBrowserBanner] =
- settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_whitelist)[::prefs::kSettingsShowOSBanner] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_apitest.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_apitest.cc
index bca4048309d..47c59642146 100644
--- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_apitest.cc
@@ -11,11 +11,15 @@
#include "base/run_loop.h"
#include "base/values.h"
#include "build/build_config.h"
+#include "chrome/browser/content_settings/host_content_settings_map_factory.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/extension_apitest.h"
#include "chrome/common/extensions/api/settings_private.h"
#include "chrome/common/pref_names.h"
+#include "components/content_settings/core/browser/host_content_settings_map.h"
+#include "components/content_settings/core/test/content_settings_mock_provider.h"
+#include "components/content_settings/core/test/content_settings_test_utils.h"
#include "components/keyed_service/core/keyed_service.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
@@ -102,6 +106,25 @@ IN_PROC_BROWSER_TEST_F(SettingsPrivateApiTest, GetRecommendedPref) {
EXPECT_TRUE(RunSettingsSubtest("getRecommendedPref")) << message_;
}
+IN_PROC_BROWSER_TEST_F(SettingsPrivateApiTest, GetDisabledPref) {
+ HostContentSettingsMapFactory::GetForProfile(profile())
+ ->SetDefaultContentSetting(ContentSettingsType::COOKIES,
+ ContentSetting::CONTENT_SETTING_BLOCK);
+ EXPECT_TRUE(RunSettingsSubtest("getDisabledPref")) << message_;
+}
+
+IN_PROC_BROWSER_TEST_F(SettingsPrivateApiTest, GetPartiallyManagedPref) {
+ auto provider = std::make_unique<content_settings::MockProvider>();
+ provider->SetWebsiteSetting(
+ ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(),
+ ContentSettingsType::COOKIES, std::string(),
+ std::make_unique<base::Value>(ContentSetting::CONTENT_SETTING_ALLOW));
+ content_settings::TestUtils::OverrideProvider(
+ HostContentSettingsMapFactory::GetForProfile(profile()),
+ std::move(provider), HostContentSettingsMap::POLICY_PROVIDER);
+ EXPECT_TRUE(RunSettingsSubtest("getPartiallyManagedPref")) << message_;
+}
+
IN_PROC_BROWSER_TEST_F(SettingsPrivateApiTest, GetAllPrefs) {
EXPECT_TRUE(RunSettingsSubtest("getAllPrefs")) << message_;
}
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 beb1efb4780..bd741debea0 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
@@ -15,7 +15,6 @@
#include "base/memory/weak_ptr.h"
#include "base/one_shot_event.h"
#include "base/scoped_observer.h"
-#include "base/task/post_task.h"
#include "chrome/browser/extensions/api/storage/policy_value_store.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/policy/schema_registry_service.h"
@@ -203,8 +202,8 @@ void ManagedValueStoreCache::ExtensionTracker::LoadSchemasOnFileTaskRunner(
(*components)[(*it)->id()] = schema;
}
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&ExtensionTracker::Register, self,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&ExtensionTracker::Register, self,
base::Owned(components.release())));
}
diff --git a/chromium/chrome/browser/extensions/api/storage/policy_value_store.cc b/chromium/chrome/browser/extensions/api/storage/policy_value_store.cc
index 51b4e2fb2cb..264828c2308 100644
--- a/chromium/chrome/browser/extensions/api/storage/policy_value_store.cc
+++ b/chromium/chrome/browser/extensions/api/storage/policy_value_store.cc
@@ -43,7 +43,7 @@ void PolicyValueStore::SetCurrentPolicy(const policy::PolicyMap& policy) {
for (auto it = policy.begin(); it != policy.end(); ++it) {
if (it->second.level == policy::POLICY_LEVEL_MANDATORY) {
current_policy.SetWithoutPathExpansion(
- it->first, it->second.value->CreateDeepCopy());
+ it->first, it->second.value()->CreateDeepCopy());
}
}
diff --git a/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc b/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc
index 7ab45ab303f..6c17d73a9ed 100644
--- a/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc
@@ -339,9 +339,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest,
EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}
-// Disabled, see crbug.com/101110
IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest,
- DISABLED_OnChangedNotificationsFromSync) {
+ OnChangedNotificationsFromSync) {
// We need 2 ResultCatchers because we'll be running the same test in both
// regular and incognito mode.
ResultCatcher catcher, catcher_incognito;
@@ -381,12 +380,10 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest,
EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}
-// Disabled, see crbug.com/101110
-//
// TODO: boring test, already done in the unit tests. What we really should be
// be testing is that the areas don't overlap.
IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest,
- DISABLED_OnChangedNotificationsFromSyncNotSentToLocal) {
+ OnChangedNotificationsFromSyncNotSentToLocal) {
// We need 2 ResultCatchers because we'll be running the same test in both
// regular and incognito mode.
ResultCatcher catcher, catcher_incognito;
@@ -517,6 +514,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, ManagedStorage) {
extensions::DictionaryBuilder()
.Set("string-policy", "value")
.Set("string-enum-policy", "value-1")
+ .Set("another-string-policy", 123) // Test invalid policy value.
.Set("int-policy", -123)
.Set("int-enum-policy", 1)
.Set("double-policy", 456e7)
@@ -544,8 +542,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, ManagedStorage) {
ASSERT_TRUE(RunExtensionTest("settings/managed_storage")) << message_;
}
-IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest,
- DISABLED_PRE_ManagedStorageEvents) {
+IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, PRE_ManagedStorageEvents) {
ResultCatcher catcher;
// This test starts without any test extensions installed.
@@ -579,8 +576,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest,
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
-IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest,
- DISABLED_ManagedStorageEvents) {
+IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, ManagedStorageEvents) {
// This test runs after PRE_ManagedStorageEvents without having deleted the
// profile, so the extension is still around. While the browser restarted the
// policy went back to the empty default, and so the extension should receive
diff --git a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.cc b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.cc
index 576c14641c4..4947eede0b4 100644
--- a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.cc
+++ b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.cc
@@ -39,8 +39,10 @@ ExtensionFunction::ResponseAction SystemIndicatorSetIconFunction::Run() {
if (const base::Value* canvas_set = set_icon_details.FindKeyOfType(
"imageData", base::Value::Type::DICTIONARY)) {
gfx::ImageSkia icon;
- EXTENSION_FUNCTION_VALIDATE(ExtensionAction::ParseIconFromCanvasDictionary(
- static_cast<const base::DictionaryValue&>(*canvas_set), &icon));
+ EXTENSION_FUNCTION_VALIDATE(
+ ExtensionAction::ParseIconFromCanvasDictionary(
+ static_cast<const base::DictionaryValue&>(*canvas_set), &icon) ==
+ ExtensionAction::IconParseResult::kSuccess);
if (icon.isNull())
return RespondNow(Error("Icon invalid."));
diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc
index f4d183ab977..38c40a7e868 100644
--- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc
@@ -919,7 +919,7 @@ ExtensionFunction::ResponseAction TabsQueryFunction::Run() {
Browser* current_browser =
ChromeExtensionFunctionDetails(this).GetCurrentBrowser();
for (auto* browser : *BrowserList::GetInstance()) {
- if (!profile->IsSameProfile(browser->profile()))
+ if (!profile->IsSameOrParent(browser->profile()))
continue;
if (!browser->window())
@@ -1211,8 +1211,7 @@ bool TabsHighlightFunction::HighlightTab(TabStripModel* tabstrip,
return true;
}
-TabsUpdateFunction::TabsUpdateFunction() : web_contents_(NULL) {
-}
+TabsUpdateFunction::TabsUpdateFunction() : web_contents_(nullptr) {}
ExtensionFunction::ResponseAction TabsUpdateFunction::Run() {
std::unique_ptr<tabs::Update::Params> params(
@@ -1580,20 +1579,10 @@ ExtensionFunction::ResponseAction TabsReloadFunction::Run() {
}
}
- if (web_contents->ShowingInterstitialPage()) {
- // This does as same as Browser::ReloadInternal.
- NavigationEntry* entry = web_contents->GetController().GetVisibleEntry();
- GURL reload_url = entry ? entry->GetURL() : GURL(url::kAboutBlankURL);
- OpenURLParams params(reload_url, Referrer(),
- WindowOpenDisposition::CURRENT_TAB,
- ui::PAGE_TRANSITION_RELOAD, false);
- current_browser->OpenURL(params);
- } else {
- web_contents->GetController().Reload(
- bypass_cache ? content::ReloadType::BYPASSING_CACHE
- : content::ReloadType::NORMAL,
- true);
- }
+ web_contents->GetController().Reload(
+ bypass_cache ? content::ReloadType::BYPASSING_CACHE
+ : content::ReloadType::NORMAL,
+ true);
return RespondNow(NoArguments());
}
diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc
index fd2ff75a3af..517e299ae20 100644
--- a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc
@@ -177,7 +177,7 @@ TabsEventRouter::~TabsEventRouter() {
}
bool TabsEventRouter::ShouldTrackBrowser(Browser* browser) {
- return profile_->IsSameProfile(browser->profile()) &&
+ return profile_->IsSameOrParent(browser->profile()) &&
ExtensionTabUtil::BrowserSupportsTabs(browser);
}
@@ -571,7 +571,7 @@ void TabsEventRouter::DispatchEvent(
std::unique_ptr<base::ListValue> args,
EventRouter::UserGestureState user_gesture) {
EventRouter* event_router = EventRouter::Get(profile);
- if (!profile_->IsSameProfile(profile) || !event_router)
+ if (!profile_->IsSameOrParent(profile) || !event_router)
return;
auto event = std::make_unique<Event>(histogram_value, event_name,
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 5f41fa24c34..05b785e9ac0 100644
--- a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc
+++ b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc
@@ -180,14 +180,14 @@ WindowsEventRouter::~WindowsEventRouter() {
}
void WindowsEventRouter::OnAppWindowAdded(extensions::AppWindow* app_window) {
- if (!profile_->IsSameProfile(
+ if (!profile_->IsSameOrParent(
Profile::FromBrowserContext(app_window->browser_context())))
return;
AddAppWindow(app_window);
}
void WindowsEventRouter::OnAppWindowRemoved(extensions::AppWindow* app_window) {
- if (!profile_->IsSameProfile(
+ if (!profile_->IsSameOrParent(
Profile::FromBrowserContext(app_window->browser_context())))
return;
@@ -206,7 +206,7 @@ void WindowsEventRouter::OnWindowControllerAdded(
WindowController* window_controller) {
if (!HasEventListener(windows::OnCreated::kEventName))
return;
- if (!profile_->IsSameProfile(window_controller->profile()))
+ if (!profile_->IsSameOrParent(window_controller->profile()))
return;
// Ignore any windows without an associated browser (e.g., AppWindows).
if (!window_controller->GetBrowser())
@@ -228,7 +228,7 @@ void WindowsEventRouter::OnWindowControllerRemoved(
WindowController* window_controller) {
if (!HasEventListener(windows::OnRemoved::kEventName))
return;
- if (!profile_->IsSameProfile(window_controller->profile()))
+ if (!profile_->IsSameOrParent(window_controller->profile()))
return;
// Ignore any windows without an associated browser (e.g., AppWindows).
if (!window_controller->GetBrowser())
@@ -263,7 +263,7 @@ void WindowsEventRouter::OnActiveWindowChanged(
Profile* window_profile = nullptr;
int window_id = extension_misc::kUnknownWindowId;
if (window_controller &&
- profile_->IsSameProfile(window_controller->profile())) {
+ profile_->IsSameOrParent(window_controller->profile())) {
window_profile = window_controller->profile();
window_id = window_controller->GetWindowId();
}
diff --git a/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.cc b/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.cc
index e7d31651cd9..46b9d08c181 100644
--- a/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.cc
+++ b/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.cc
@@ -12,7 +12,6 @@
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
-#include "base/task/post_task.h"
#include "base/time/time.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/dbus/util/version_loader.h"
@@ -79,8 +78,8 @@ void CrostiniStartupStatus::ShowProgressAtInterval() {
PrintProgress();
}
++spinner_index_;
- base::PostDelayedTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostDelayedTask(
+ FROM_HERE,
base::BindOnce(&CrostiniStartupStatus::ShowProgressAtInterval,
weak_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(300));
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 f17fccee02c..e2d7220cd38 100644
--- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc
+++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc
@@ -17,7 +17,6 @@
#include "base/memory/scoped_refptr.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
-#include "base/task/post_task.h"
#include "base/values.h"
#include "chrome/browser/chromeos/crostini/crostini_features.h"
#include "chrome/browser/chromeos/crostini/crostini_manager.h"
@@ -93,8 +92,8 @@ void NotifyProcessOutput(content::BrowserContext* browser_context,
const std::string& output_type,
const std::string& output) {
if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&NotifyProcessOutput, browser_context, tab_id,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&NotifyProcessOutput, browser_context, tab_id,
terminal_id, output_type, output));
return;
}
@@ -249,12 +248,10 @@ TerminalPrivateOpenTerminalProcessFunction::OpenProcess(
GetSwitch(&params_args, &vmshell_cmd, kSwitchTargetContainer,
crostini::kCrostiniDefaultContainerName);
std::string startup_id = params_args.GetSwitchValueASCII(kSwitchStartupId);
+ crostini::ContainerId container_id(vm_name, container_name);
auto* mgr = crostini::CrostiniManager::GetForProfile(profile);
- bool verbose =
- !mgr->GetContainerInfo(crostini::kCrostiniDefaultVmName,
- crostini::kCrostiniDefaultContainerName)
- .has_value();
+ bool verbose = !mgr->GetContainerInfo(container_id).has_value();
auto observer = std::make_unique<CrostiniStartupStatus>(
base::BindRepeating(&NotifyProcessOutput, browser_context(), tab_id,
startup_id,
@@ -265,7 +262,7 @@ TerminalPrivateOpenTerminalProcessFunction::OpenProcess(
CrostiniStartupStatus* observer_ptr = observer.get();
observer->ShowProgressAtInterval();
mgr->RestartCrostini(
- vm_name, container_name,
+ container_id,
base::BindOnce(
&TerminalPrivateOpenTerminalProcessFunction::OnCrostiniRestarted,
this, std::move(observer), user_id_hash, tab_id,
@@ -331,8 +328,8 @@ void TerminalPrivateOpenTerminalProcessFunction::OpenOnRegistryTaskRunner(
bool success = registry->OpenProcess(cmdline, user_id_hash, output_callback,
&terminal_id);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(callback, success, terminal_id));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(callback, success, terminal_id));
}
TerminalPrivateOpenVmshellProcessFunction::
@@ -379,8 +376,8 @@ void TerminalPrivateSendInputFunction::SendInputOnRegistryTaskRunner(
bool success =
chromeos::ProcessProxyRegistry::Get()->SendInput(terminal_id, text);
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&TerminalPrivateSendInputFunction::RespondOnUIThread, this,
success));
}
@@ -412,8 +409,8 @@ void TerminalPrivateCloseTerminalProcessFunction::CloseOnRegistryTaskRunner(
bool success =
chromeos::ProcessProxyRegistry::Get()->CloseProcess(terminal_id);
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&TerminalPrivateCloseTerminalProcessFunction::RespondOnUIThread, this,
success));
@@ -450,8 +447,8 @@ void TerminalPrivateOnTerminalResizeFunction::OnResizeOnRegistryTaskRunner(
bool success = chromeos::ProcessProxyRegistry::Get()->OnTerminalResize(
terminal_id, width, height);
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&TerminalPrivateOnTerminalResizeFunction::RespondOnUIThread, this,
success));
@@ -537,8 +534,8 @@ void TerminalPrivateGetCroshSettingsFunction::AsyncRunWithStorage(
ExtensionFunction::ResponseValue response =
result.status().ok() ? OneArgument(result.PassSettings())
: Error(result.status().message);
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&TerminalPrivateGetCroshSettingsFunction::Respond, this,
std::move(response)));
}
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 906e695f21f..dccb0b244d9 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
@@ -34,8 +34,8 @@
#include "media/audio/audio_system.h"
#include "ui/aura/event_injector.h"
#include "ui/aura/window_tree_host.h"
+#include "ui/base/ime/chromeos/ime_bridge.h"
#include "ui/base/ime/constants.h"
-#include "ui/base/ime/ime_bridge.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/base/ui_base_features.h"
@@ -409,10 +409,9 @@ void ChromeVirtualKeyboardDelegate::OnHasInputDevices(
features->AppendString(GenerateFeatureFlag(
"mozcinputlogic",
base::FeatureList::IsEnabled(chromeos::features::kImeInputLogicMozc)));
- // Flag used to enable decoder Mojo APIs instead of NaCl APIs.
+ // Flag used to enable UIL Mojo APIs instead of NaCl APIs.
features->AppendString(GenerateFeatureFlag(
- "usemojodecoder", base::FeatureList::IsEnabled(
- chromeos::features::kImeDecoderWithSandbox)));
+ "usemojodecoder", chromeos::features::IsImeSandboxEnabled()));
features->AppendString(GenerateFeatureFlag(
"borderedkey", base::FeatureList::IsEnabled(
chromeos::features::kVirtualKeyboardBorderedKey)));
diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc
index edd6f2da449..34bc26bb443 100644
--- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc
+++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc
@@ -80,7 +80,7 @@ WebNavigationEventRouter::WebNavigationEventRouter(Profile* profile)
WebNavigationEventRouter::~WebNavigationEventRouter() = default;
bool WebNavigationEventRouter::ShouldTrackBrowser(Browser* browser) {
- return profile_->IsSameProfile(browser->profile());
+ return profile_->IsSameOrParent(browser->profile());
}
void WebNavigationEventRouter::OnTabStripModelChanged(
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 c0ad861dd45..2d5c8d6d994 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
@@ -46,6 +46,7 @@
#include "extensions/browser/api/web_request/web_request_api_constants.h"
#include "extensions/browser/api/web_request/web_request_api_helpers.h"
#include "extensions/browser/api/web_request/web_request_info.h"
+#include "extensions/common/api/declarative_net_request.h"
#include "extensions/common/api/web_request.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_messages.h"
@@ -746,6 +747,8 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses4) {
EXPECT_EQ(GURL(), effective_new_url);
}
+// TODO(crbug.com/1099066): Separate this test into subtests to improve
+// readability.
TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
net::HttpRequestHeaders base_headers;
base_headers.SetHeader("key1", "value 1");
@@ -766,9 +769,10 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
WebRequestInfoInitParams info_params;
WebRequestInfo info(std::move(info_params));
info.dnr_actions = std::vector<DNRRequestAction>();
- MergeOnBeforeSendHeadersResponses(info, deltas, &headers0, &ignored_actions,
- &ignore1, &ignore2,
- &request_headers_modified0);
+ std::vector<const DNRRequestAction*> matched_dnr_actions;
+ MergeOnBeforeSendHeadersResponses(
+ info, deltas, &headers0, &ignored_actions, &ignore1, &ignore2,
+ &request_headers_modified0, &matched_dnr_actions);
ASSERT_TRUE(headers0.GetHeader("key1", &header_value));
EXPECT_EQ("value 1", header_value);
ASSERT_TRUE(headers0.GetHeader("key2", &header_value));
@@ -791,9 +795,9 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
bool request_headers_modified1;
net::HttpRequestHeaders headers1;
headers1.MergeFrom(base_headers);
- MergeOnBeforeSendHeadersResponses(info, deltas, &headers1, &ignored_actions,
- &ignore1, &ignore2,
- &request_headers_modified1);
+ MergeOnBeforeSendHeadersResponses(
+ info, deltas, &headers1, &ignored_actions, &ignore1, &ignore2,
+ &request_headers_modified1, &matched_dnr_actions);
EXPECT_FALSE(headers1.HasHeader("key1"));
ASSERT_TRUE(headers1.GetHeader("key2", &header_value));
EXPECT_EQ("value 3", header_value);
@@ -818,9 +822,9 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
bool request_headers_modified2;
net::HttpRequestHeaders headers2;
headers2.MergeFrom(base_headers);
- MergeOnBeforeSendHeadersResponses(info, deltas, &headers2, &ignored_actions,
- &ignore1, &ignore2,
- &request_headers_modified2);
+ MergeOnBeforeSendHeadersResponses(
+ info, deltas, &headers2, &ignored_actions, &ignore1, &ignore2,
+ &request_headers_modified2, &matched_dnr_actions);
EXPECT_FALSE(headers2.HasHeader("key1"));
ASSERT_TRUE(headers2.GetHeader("key2", &header_value));
EXPECT_EQ("value 3", header_value);
@@ -849,9 +853,9 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
bool request_headers_modified3;
net::HttpRequestHeaders headers3;
headers3.MergeFrom(base_headers);
- MergeOnBeforeSendHeadersResponses(info, deltas, &headers3, &ignored_actions,
- &ignore1, &ignore2,
- &request_headers_modified3);
+ MergeOnBeforeSendHeadersResponses(
+ info, deltas, &headers3, &ignored_actions, &ignore1, &ignore2,
+ &request_headers_modified3, &matched_dnr_actions);
EXPECT_FALSE(headers3.HasHeader("key1"));
ASSERT_TRUE(headers3.GetHeader("key2", &header_value));
EXPECT_EQ("value 3", header_value);
@@ -864,6 +868,157 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
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();
+ ignore1.clear();
+ ignore2.clear();
+ bool request_headers_modified4 = false;
+ net::HttpRequestHeaders headers4;
+ headers4.MergeFrom(base_headers);
+
+ DNRRequestAction modify_headers_action =
+ CreateRequestActionForTesting(DNRRequestAction::Type::MODIFY_HEADERS);
+ modify_headers_action.request_headers_to_modify = {
+ DNRRequestAction::HeaderInfo(
+ "key5", api::declarative_net_request::HEADER_OPERATION_REMOVE,
+ base::nullopt)};
+ info.dnr_actions = std::vector<DNRRequestAction>();
+ info.dnr_actions->push_back(std::move(modify_headers_action));
+
+ MergeOnBeforeSendHeadersResponses(
+ info, deltas, &headers4, &ignored_actions, &ignore1, &ignore2,
+ &request_headers_modified4, &matched_dnr_actions);
+ // Deleted by |d1|.
+ EXPECT_FALSE(headers4.HasHeader("key1"));
+ // Added by |d1|.
+ ASSERT_TRUE(headers4.GetHeader("key2", &header_value));
+ EXPECT_EQ("value 3", header_value);
+ // Removed by Declarative Net Request API.
+ EXPECT_FALSE(headers4.HasHeader("key5"));
+
+ EXPECT_EQ(2u, ignored_actions.size());
+ EXPECT_TRUE(
+ HasIgnoredAction(ignored_actions, "extid2",
+ web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
+ EXPECT_TRUE(
+ HasIgnoredAction(ignored_actions, "extid3",
+ web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
+ EXPECT_TRUE(request_headers_modified4);
+
+ // Check that headers set by Declarative Net Request API can't be further
+ // modified and result in a conflict.
+ ignored_actions.clear();
+ ignore1.clear();
+ ignore2.clear();
+ bool request_headers_modified5 = false;
+ net::HttpRequestHeaders headers5;
+ headers5.MergeFrom(base_headers);
+
+ DNRRequestAction set_headers_action =
+ CreateRequestActionForTesting(DNRRequestAction::Type::MODIFY_HEADERS);
+
+ // Since key2 is set to "value 3" by both |set_headers_action| and
+ // |extid1|, |extid1| should not be ignored.
+ // Conversely, |set_headers_action| and |extid3| set different values for
+ // key5, therefore |extid4| should be ignored.
+ set_headers_action.request_headers_to_modify = {
+ DNRRequestAction::HeaderInfo(
+ "key2", api::declarative_net_request::HEADER_OPERATION_SET,
+ "value 3"),
+ DNRRequestAction::HeaderInfo(
+ "key5", api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_value")};
+ info.dnr_actions = std::vector<DNRRequestAction>();
+ info.dnr_actions->push_back(std::move(set_headers_action));
+
+ MergeOnBeforeSendHeadersResponses(
+ info, deltas, &headers5, &ignored_actions, &ignore1, &ignore2,
+ &request_headers_modified5, &matched_dnr_actions);
+ // Deleted by |d1|.
+ EXPECT_FALSE(headers5.HasHeader("key1"));
+ // Added by |d1| (same value as added by Declarative Net Request API).
+ ASSERT_TRUE(headers5.GetHeader("key2", &header_value));
+ EXPECT_EQ("value 3", header_value);
+ // Set by Declarative Net Request API.
+ ASSERT_TRUE(headers5.GetHeader("key5", &header_value));
+ EXPECT_EQ("dnr_value", header_value);
+
+ EXPECT_EQ(2u, ignored_actions.size());
+ EXPECT_TRUE(
+ HasIgnoredAction(ignored_actions, "extid2",
+ web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
+ EXPECT_TRUE(
+ HasIgnoredAction(ignored_actions, "extid3",
+ web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
+ EXPECT_TRUE(request_headers_modified4);
+}
+
+// Test conflict resolution for declarative net request actions from the same
+// extension modifying the same request header.
+TEST(ExtensionWebRequestHelpersTest,
+ TestMergeOnBeforeSendHeadersResponses_DeclarativeNetRequest) {
+ DNRRequestAction action_1 =
+ CreateRequestActionForTesting(DNRRequestAction::Type::MODIFY_HEADERS);
+ action_1.request_headers_to_modify = {
+ DNRRequestAction::HeaderInfo(
+ "key1", api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_action_1"),
+ DNRRequestAction::HeaderInfo(
+ "key2", api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_action_1"),
+ DNRRequestAction::HeaderInfo(
+ "key3", api::declarative_net_request::HEADER_OPERATION_REMOVE,
+ base::nullopt)};
+
+ DNRRequestAction action_2 =
+ CreateRequestActionForTesting(DNRRequestAction::Type::MODIFY_HEADERS);
+ action_2.request_headers_to_modify = {
+ DNRRequestAction::HeaderInfo(
+ "key1", api::declarative_net_request::HEADER_OPERATION_REMOVE,
+ base::nullopt),
+ DNRRequestAction::HeaderInfo(
+ "key2", api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_action_2"),
+ DNRRequestAction::HeaderInfo(
+ "key3", api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_action_2")};
+
+ WebRequestInfoInitParams info_params;
+ WebRequestInfo info(std::move(info_params));
+ info.dnr_actions = std::vector<DNRRequestAction>();
+ info.dnr_actions->push_back(std::move(action_1));
+ info.dnr_actions->push_back(std::move(action_2));
+
+ net::HttpRequestHeaders base_headers;
+ base_headers.SetHeader("key3", "value 3");
+ helpers::IgnoredActions ignored_actions;
+ std::string header_value;
+ EventResponseDeltas deltas;
+ bool request_headers_modified;
+ std::set<std::string> ignore1, ignore2;
+ std::vector<const DNRRequestAction*> matched_dnr_actions;
+
+ // Header modifications specified by |action1| are processed before those
+ // specified by |action2|.
+ MergeOnBeforeSendHeadersResponses(
+ info, deltas, &base_headers, &ignored_actions, &ignore1, &ignore2,
+ &request_headers_modified, &matched_dnr_actions);
+ // Header set by a prior action cannot be removed by a subsequent action.
+ ASSERT_TRUE(base_headers.GetHeader("key1", &header_value));
+ EXPECT_EQ("dnr_action_1", header_value);
+
+ // Header set by a prior action cannot be set to a different value by a
+ // subsequent action.
+ ASSERT_TRUE(base_headers.GetHeader("key2", &header_value));
+ EXPECT_EQ("dnr_action_1", header_value);
+
+ // Header removed by a prior action cannot be set by a subsequent action.
+ EXPECT_FALSE(base_headers.HasHeader("key3"));
+
+ EXPECT_EQ(0u, ignored_actions.size());
+ EXPECT_TRUE(request_headers_modified);
}
// Ensure conflicts between different extensions are handled correctly with
@@ -897,9 +1052,10 @@ TEST(ExtensionWebRequestHelpersTest,
net::HttpRequestHeaders headers;
headers.SetHeader("key1", "value 1");
- MergeOnBeforeSendHeadersResponses(info, deltas, &headers, &ignored_actions,
- &removed_headers, &set_headers,
- &request_headers_modified);
+ std::vector<const DNRRequestAction*> matched_dnr_actions;
+ MergeOnBeforeSendHeadersResponses(
+ info, deltas, &headers, &ignored_actions, &removed_headers, &set_headers,
+ &request_headers_modified, &matched_dnr_actions);
std::string header_value;
ASSERT_TRUE(headers.GetHeader("key1", &header_value));
@@ -962,9 +1118,11 @@ TEST(ExtensionWebRequestHelpersTest,
WebRequestInfoInitParams info_params;
WebRequestInfo info(std::move(info_params));
- MergeOnBeforeSendHeadersResponses(info, deltas, &headers1, &ignored_actions,
- &ignore1, &ignore2,
- &request_headers_modified1);
+ info.dnr_actions = std::vector<DNRRequestAction>();
+ std::vector<const DNRRequestAction*> matched_dnr_actions;
+ MergeOnBeforeSendHeadersResponses(
+ info, deltas, &headers1, &ignored_actions, &ignore1, &ignore2,
+ &request_headers_modified1, &matched_dnr_actions);
EXPECT_TRUE(headers1.HasHeader("Cookie"));
ASSERT_TRUE(headers1.GetHeader("Cookie", &header_value));
EXPECT_EQ("name=new value; name2=new value; name4=\"value 4\"", header_value);
@@ -1217,6 +1375,7 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
"HTTP/1.0 200 OK\r\n"
"Key1: Value1\r\n"
"Key2: Value2, Foo\r\n"
+ "Key4: Value4\r\n"
"\r\n";
auto base_headers = base::MakeRefCounted<net::HttpResponseHeaders>(
net::HttpUtil::AssembleRawHeaders(base_headers_string));
@@ -1233,11 +1392,12 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
info_params.url = GURL(kExampleUrl);
WebRequestInfo info(std::move(info_params));
info.dnr_actions = std::vector<DNRRequestAction>();
+ std::vector<const DNRRequestAction*> matched_dnr_actions;
MergeOnHeadersReceivedResponses(
info, deltas, base_headers.get(), &new_headers0,
&preserve_fragment_on_redirect_url0, &ignored_actions,
- &response_headers_modified0);
+ &response_headers_modified0, &matched_dnr_actions);
EXPECT_FALSE(new_headers0.get());
EXPECT_TRUE(preserve_fragment_on_redirect_url0.is_empty());
EXPECT_EQ(0u, ignored_actions.size());
@@ -1260,12 +1420,13 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
MergeOnHeadersReceivedResponses(
info, deltas, base_headers.get(), &new_headers1,
&preserve_fragment_on_redirect_url1, &ignored_actions,
- &response_headers_modified1);
+ &response_headers_modified1, &matched_dnr_actions);
ASSERT_TRUE(new_headers1.get());
EXPECT_TRUE(preserve_fragment_on_redirect_url1.is_empty());
std::multimap<std::string, std::string> expected1;
- expected1.insert(std::pair<std::string, std::string>("Key2", "Value3"));
- expected1.insert(std::pair<std::string, std::string>("Key3", "Foo"));
+ expected1.emplace("Key2", "Value3");
+ expected1.emplace("Key3", "Foo");
+ expected1.emplace("Key4", "Value4");
size_t iter = 0;
std::string name;
std::string value;
@@ -1295,7 +1456,7 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
MergeOnHeadersReceivedResponses(
info, deltas, base_headers.get(), &new_headers2,
&preserve_fragment_on_redirect_url2, &ignored_actions,
- &response_headers_modified2);
+ &response_headers_modified2, &matched_dnr_actions);
ASSERT_TRUE(new_headers2.get());
EXPECT_TRUE(preserve_fragment_on_redirect_url2.is_empty());
iter = 0;
@@ -1309,6 +1470,108 @@ TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_RESPONSE_HEADERS));
EXPECT_TRUE(response_headers_modified2);
+
+ // Ensure headers removed by Declarative Net Request API can't be added by web
+ // request extensions and result in a conflict.
+ DNRRequestAction modify_headers_action =
+ CreateRequestActionForTesting(DNRRequestAction::Type::MODIFY_HEADERS);
+ modify_headers_action.response_headers_to_modify = {
+ DNRRequestAction::HeaderInfo(
+ "key3", api::declarative_net_request::HEADER_OPERATION_REMOVE,
+ base::nullopt)};
+
+ info.dnr_actions = std::vector<DNRRequestAction>();
+ info.dnr_actions->push_back(std::move(modify_headers_action));
+
+ ignored_actions.clear();
+ bool response_headers_modified3 = false;
+ scoped_refptr<net::HttpResponseHeaders> new_headers3;
+ GURL preserve_fragment_on_redirect_url3;
+ MergeOnHeadersReceivedResponses(
+ info, deltas, base_headers.get(), &new_headers3,
+ &preserve_fragment_on_redirect_url3, &ignored_actions,
+ &response_headers_modified3, &matched_dnr_actions);
+ ASSERT_TRUE(new_headers3.get());
+ EXPECT_TRUE(preserve_fragment_on_redirect_url3.is_empty());
+ iter = 0;
+ std::multimap<std::string, std::string> actual3;
+ while (new_headers3->EnumerateHeaderLines(&iter, &name, &value))
+ actual3.emplace(name, value);
+ std::multimap<std::string, std::string> expected3;
+ expected3.emplace("Key2", "Value4");
+ expected3.emplace("Key1", "Value1");
+ expected3.emplace("Key4", "Value4");
+ EXPECT_EQ(expected3, actual3);
+ EXPECT_EQ(1u, ignored_actions.size());
+
+ // The action specified by extid1 is ignored since it conflicted with
+ // |modify_headers_action| for the key3 header.
+ EXPECT_TRUE(
+ HasIgnoredAction(ignored_actions, "extid1",
+ web_request::IGNORED_ACTION_TYPE_RESPONSE_HEADERS));
+ EXPECT_TRUE(response_headers_modified3);
+
+ // Ensure headers appended by Declarative Net Request API can't be removed by
+ // web request extensions and result in a conflict, but can be further
+ // appended by web request extensions.
+ {
+ EventResponseDelta d3("extid3", base::Time::FromInternalValue(1000));
+ d3.deleted_response_headers.push_back(ResponseHeader("Key4", "Value4"));
+ deltas.push_back(std::move(d3));
+ }
+ deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
+
+ modify_headers_action =
+ CreateRequestActionForTesting(DNRRequestAction::Type::MODIFY_HEADERS);
+ modify_headers_action.response_headers_to_modify = {
+ DNRRequestAction::HeaderInfo(
+ "key3", api::declarative_net_request::HEADER_OPERATION_APPEND,
+ "dnr_value_3"),
+ DNRRequestAction::HeaderInfo(
+ "key4", api::declarative_net_request::HEADER_OPERATION_APPEND,
+ "dnr_value_4")};
+
+ info.dnr_actions = std::vector<DNRRequestAction>();
+ info.dnr_actions->push_back(std::move(modify_headers_action));
+
+ ignored_actions.clear();
+ bool response_headers_modified4 = false;
+ scoped_refptr<net::HttpResponseHeaders> new_headers4;
+ GURL preserve_fragment_on_redirect_url4;
+ MergeOnHeadersReceivedResponses(
+ info, deltas, base_headers.get(), &new_headers4,
+ &preserve_fragment_on_redirect_url4, &ignored_actions,
+ &response_headers_modified4, &matched_dnr_actions);
+ ASSERT_TRUE(new_headers4.get());
+ EXPECT_TRUE(preserve_fragment_on_redirect_url4.is_empty());
+
+ iter = 0;
+ std::multimap<std::string, std::string> actual4;
+ while (new_headers4->EnumerateHeaderLines(&iter, &name, &value))
+ actual4.emplace(name, value);
+ std::multimap<std::string, std::string> expected4;
+
+ expected4.emplace("Key2", "Value3");
+ expected4.emplace("Key3", "Foo");
+ expected4.emplace("key3", "dnr_value_3");
+ expected4.emplace("Key4", "Value4");
+ expected4.emplace("key4", "dnr_value_4");
+ EXPECT_EQ(expected4, actual4);
+ EXPECT_EQ(2u, ignored_actions.size());
+
+ // The action specified by extid1 is not ignored since it adds to the same
+ // header that the Declarative Net Request appends. The action specified by
+ // extid2 is ignored since it tries to replace the same header replaced by
+ // extid1.
+ EXPECT_TRUE(
+ HasIgnoredAction(ignored_actions, "extid2",
+ web_request::IGNORED_ACTION_TYPE_RESPONSE_HEADERS));
+ // The action specified by extid3 is ignored since it tries to remove Key4,
+ // which was appended by the Declarative Net Request API.
+ EXPECT_TRUE(
+ HasIgnoredAction(ignored_actions, "extid3",
+ web_request::IGNORED_ACTION_TYPE_RESPONSE_HEADERS));
+ EXPECT_TRUE(response_headers_modified4);
}
// Check that we do not delete too much
@@ -1341,11 +1604,12 @@ TEST(ExtensionWebRequestHelpersTest,
info_params.url = GURL(kExampleUrl);
WebRequestInfo info(std::move(info_params));
info.dnr_actions = std::vector<DNRRequestAction>();
+ std::vector<const DNRRequestAction*> matched_dnr_actions;
MergeOnHeadersReceivedResponses(
info, deltas, base_headers.get(), &new_headers1,
&preserve_fragment_on_redirect_url1, &ignored_actions,
- &response_headers_modified1);
+ &response_headers_modified1, &matched_dnr_actions);
ASSERT_TRUE(new_headers1.get());
EXPECT_TRUE(preserve_fragment_on_redirect_url1.is_empty());
std::multimap<std::string, std::string> expected1;
@@ -1390,11 +1654,13 @@ TEST(ExtensionWebRequestHelpersTest,
WebRequestInfoInitParams info_params;
info_params.url = GURL(kExampleUrl);
WebRequestInfo info(std::move(info_params));
+ info.dnr_actions = std::vector<DNRRequestAction>();
+ std::vector<const DNRRequestAction*> matched_dnr_actions;
MergeOnHeadersReceivedResponses(
info, deltas, base_headers.get(), &new_headers0,
&preserve_fragment_on_redirect_url0, &ignored_actions,
- &response_headers_modified0);
+ &response_headers_modified0, &matched_dnr_actions);
EXPECT_FALSE(new_headers0.get());
EXPECT_TRUE(preserve_fragment_on_redirect_url0.is_empty());
EXPECT_EQ(0u, ignored_actions.size());
@@ -1415,7 +1681,7 @@ TEST(ExtensionWebRequestHelpersTest,
MergeOnHeadersReceivedResponses(
info, deltas, base_headers.get(), &new_headers1,
&preserve_fragment_on_redirect_url1, &ignored_actions,
- &response_headers_modified1);
+ &response_headers_modified1, &matched_dnr_actions);
EXPECT_TRUE(new_headers1.get());
EXPECT_TRUE(new_headers1->HasHeaderValue("Location", new_url_1.spec()));
@@ -1424,6 +1690,143 @@ TEST(ExtensionWebRequestHelpersTest,
EXPECT_FALSE(response_headers_modified1);
}
+// Test conflict resolution for declarative net request actions modifying the
+// same response header.
+TEST(ExtensionWebRequestHelpersTest,
+ TestMergeOnHeadersReceivedResponses_DeclarativeNetRequest) {
+ using HeaderInfo = DNRRequestAction::HeaderInfo;
+ const ExtensionId ext_1 = "ext_1";
+ const ExtensionId ext_2 = "ext_2";
+
+ // Test every combination of operations for two RequestActions from different
+ // extensions modifying the same header.
+ DNRRequestAction action_1 =
+ CreateRequestActionForTesting(DNRRequestAction::Type::MODIFY_HEADERS);
+ action_1.extension_id = ext_1;
+ action_1.response_headers_to_modify = {
+ HeaderInfo("key1", api::declarative_net_request::HEADER_OPERATION_APPEND,
+ "dnr_action_1"),
+ HeaderInfo("key2", api::declarative_net_request::HEADER_OPERATION_APPEND,
+ "dnr_action_1"),
+ HeaderInfo("key3", api::declarative_net_request::HEADER_OPERATION_APPEND,
+ "dnr_action_1"),
+
+ HeaderInfo("key4", api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_action_1"),
+ HeaderInfo("key5", api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_action_1"),
+ HeaderInfo("key6", api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_action_1"),
+
+ HeaderInfo("key7", api::declarative_net_request::HEADER_OPERATION_REMOVE,
+ base::nullopt),
+ HeaderInfo("key8", api::declarative_net_request::HEADER_OPERATION_REMOVE,
+ base::nullopt),
+
+ HeaderInfo("same_ext_key",
+ api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_action_1")};
+
+ DNRRequestAction action_2 =
+ CreateRequestActionForTesting(DNRRequestAction::Type::MODIFY_HEADERS);
+ action_2.extension_id = ext_1;
+ action_2.response_headers_to_modify = {HeaderInfo(
+ "same_ext_key", api::declarative_net_request::HEADER_OPERATION_APPEND,
+ "dnr_action_2")};
+
+ DNRRequestAction action_3 =
+ CreateRequestActionForTesting(DNRRequestAction::Type::MODIFY_HEADERS);
+ action_3.extension_id = ext_2;
+ action_3.response_headers_to_modify = {
+ HeaderInfo("key1", api::declarative_net_request::HEADER_OPERATION_APPEND,
+ "dnr_action_3"),
+ HeaderInfo("key2", api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_action_3"),
+ HeaderInfo("key3", api::declarative_net_request::HEADER_OPERATION_REMOVE,
+ base::nullopt),
+
+ HeaderInfo("key4", api::declarative_net_request::HEADER_OPERATION_APPEND,
+ "dnr_action_3"),
+ HeaderInfo("key5", api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_action_3"),
+ HeaderInfo("key6", api::declarative_net_request::HEADER_OPERATION_REMOVE,
+ base::nullopt),
+
+ HeaderInfo("key7", api::declarative_net_request::HEADER_OPERATION_APPEND,
+ "dnr_action_3"),
+ HeaderInfo("key8", api::declarative_net_request::HEADER_OPERATION_SET,
+ "dnr_action_3")};
+
+ WebRequestInfoInitParams info_params;
+ info_params.url = GURL(kExampleUrl);
+ WebRequestInfo info(std::move(info_params));
+
+ info.dnr_actions = std::vector<DNRRequestAction>();
+ info.dnr_actions->push_back(std::move(action_1));
+ info.dnr_actions->push_back(std::move(action_2));
+ info.dnr_actions->push_back(std::move(action_3));
+
+ helpers::IgnoredActions ignored_actions;
+ std::string header_value;
+ EventResponseDeltas deltas;
+
+ char base_headers_string[] =
+ "HTTP/1.0 200 OK\r\n"
+ "key1: Value1\r\n"
+ "key4: Value4\r\n"
+ "key7: Value7\r\n"
+ "key8: Value8\r\n"
+ "\r\n";
+ auto base_headers = base::MakeRefCounted<net::HttpResponseHeaders>(
+ net::HttpUtil::AssembleRawHeaders(base_headers_string));
+
+ bool response_headers_modified;
+ scoped_refptr<net::HttpResponseHeaders> new_headers;
+ GURL preserve_fragment_on_redirect_url;
+ std::vector<const DNRRequestAction*> matched_dnr_actions;
+
+ MergeOnHeadersReceivedResponses(
+ info, deltas, base_headers.get(), &new_headers,
+ &preserve_fragment_on_redirect_url, &ignored_actions,
+ &response_headers_modified, &matched_dnr_actions);
+ EXPECT_TRUE(new_headers.get());
+ EXPECT_TRUE(response_headers_modified);
+
+ size_t iter = 0;
+ std::string name;
+ std::string value;
+ std::multimap<std::string, std::string> actual_headers;
+ while (new_headers->EnumerateHeaderLines(&iter, &name, &value))
+ actual_headers.emplace(name, value);
+
+ std::multimap<std::string, std::string> expected_headers;
+ // An append operation should allow subsequent appends, but not any other
+ // operations.
+ expected_headers.emplace("key1", "Value1");
+ expected_headers.emplace("key1", "dnr_action_1");
+ expected_headers.emplace("key1", "dnr_action_3");
+ expected_headers.emplace("key2", "dnr_action_1");
+ expected_headers.emplace("key3", "dnr_action_1");
+
+ // A set operation should not allow any subsequent operations from a different
+ // extension.
+ expected_headers.emplace("key4", "dnr_action_1");
+ expected_headers.emplace("key5", "dnr_action_1");
+ expected_headers.emplace("key6", "dnr_action_1");
+
+ // A remove operation should not allow any subsequent operations
+ // (key7 and key8 headers were removed by |action_1|).
+
+ // A {set, append} sequence is allowed if both operations are specified by the
+ // same extension.
+ expected_headers.emplace("same_ext_key", "dnr_action_1");
+ expected_headers.emplace("same_ext_key", "dnr_action_2");
+ EXPECT_EQ(expected_headers, actual_headers);
+
+ EXPECT_TRUE(preserve_fragment_on_redirect_url.is_empty());
+ EXPECT_EQ(0u, ignored_actions.size());
+}
+
TEST(ExtensionWebRequestHelpersTest, TestMergeOnAuthRequiredResponses) {
helpers::IgnoredActions ignored_actions;
EventResponseDeltas deltas;
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 1a8cccf02eb..a39706af881 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
@@ -58,6 +58,7 @@
#include "chrome/test/base/search_test_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chromeos/login/login_state/scoped_test_public_session_login_state.h"
+#include "components/embedder_support/switches.h"
#include "components/google/core/common/google_switches.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
@@ -131,6 +132,11 @@ namespace extensions {
namespace {
+// This is the public key of tools/origin_trials/eftest.key, used to validate
+// origin trial tokens generated by tools/origin_trials/generate_token.py.
+constexpr char kOriginTrialPublicKeyForTesting[] =
+ "dRCs+TocuKkocNKa0AtZ4awrt9XKH2SQCI6o4FY6BNA=";
+
class CancelLoginDialog : public content::NotificationObserver {
public:
CancelLoginDialog() {
@@ -299,6 +305,8 @@ class ExtensionWebRequestApiTest : public ExtensionApiTest {
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kGaiaUrl, "http://gaia.com");
+ command_line->AppendSwitchASCII(embedder_support::kOriginTrialPublicKey,
+ kOriginTrialPublicKeyForTesting);
}
void RunPermissionTest(
@@ -2155,14 +2163,13 @@ IN_PROC_BROWSER_TEST_F(LocalNTPInterceptionWebRequestAPITest,
return result == "true";
};
- WebContents* web_contents =
- browser()->tab_strip_model()->GetActiveWebContents();
-
ASSERT_FALSE(GetAndResetOneGoogleBarRequestSeen());
ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
- ASSERT_TRUE(search::IsInstantNTP(web_contents));
- ASSERT_EQ(GURL(chrome::kChromeSearchLocalNtpUrl),
- web_contents->GetController().GetVisibleEntry()->GetURL());
+ ASSERT_EQ(local_ntp_test_utils::GetFinalNtpUrl(browser()->profile()),
+ browser()
+ ->tab_strip_model()
+ ->GetActiveWebContents()
+ ->GetLastCommittedURL());
WaitForOneGoogleBarDataUpdate();
ASSERT_TRUE(GetAndResetOneGoogleBarRequestSeen());
@@ -3084,11 +3091,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, AppCacheRequests) {
- embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
- ASSERT_TRUE(StartEmbeddedTestServer());
-
- GURL main_url = embedded_test_server()->GetURL(
- "/appcache/simple_page_with_manifest.html");
+ std::string origin = "http://127.0.0.1:8080";
+ std::unique_ptr<content::URLLoaderInterceptor> url_loader_interceptor =
+ content::URLLoaderInterceptor::ServeFilesFromDirectoryAtOrigin(
+ "content/test/data", GURL(origin));
+ GURL main_url(origin + "/appcache/simple_page_with_manifest.html");
base::string16 expected_title = base::ASCIIToUTF16("AppCache updated");
@@ -3139,11 +3146,16 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, AppCacheRequests) {
// Regression test for http://crbug.com/996940. Requests that redirected to an
// appcache handled URL could have request ID collisions.
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, RedirectToAppCacheRequest) {
- embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
+ // Use the embedded test server to support server-redirect, but serve
+ // appcache from a fixed port using the url loader interceptor below
+ // so that the appcache origin trial works.
ASSERT_TRUE(StartEmbeddedTestServer());
- GURL main_url = embedded_test_server()->GetURL(
- "/appcache/simple_page_with_manifest.html");
+ std::string origin = "http://127.0.0.1:8080";
+ auto interceptor =
+ content::URLLoaderInterceptor::ServeFilesFromDirectoryAtOrigin(
+ "content/test/data", GURL(origin));
+ GURL main_url(origin + "/appcache/simple_page_with_manifest.html");
base::string16 expected_title = base::ASCIIToUTF16("AppCache updated");
diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc
index 2cdf1e053f9..f9336578432 100644
--- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc
+++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc
@@ -80,3 +80,9 @@ IN_PROC_BROWSER_TEST_F(
<< message_;
}
#endif
+
+IN_PROC_BROWSER_TEST_F(WebrtcLoggingPrivateApiBrowserTest, TestStartStopStart) {
+ ASSERT_TRUE(
+ RunPlatformAppTest("api_test/webrtc_logging_private/start_stop_start"))
+ << message_;
+}
diff --git a/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status.cc b/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status.cc
index 8e3faa800be..2425cd15e51 100644
--- a/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status.cc
+++ b/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status.cc
@@ -16,18 +16,76 @@
#include "extensions/common/extension.h"
#include "extensions/common/extension_urls.h"
#include "extensions/common/manifest_constants.h"
+#include "extensions/common/permissions/permission_set.h"
namespace extensions {
+namespace {
+
+// A helper function to determine if an extension from web store with given
+// information should be blocked by enterprise policy. It checks extension's
+// installation mode, permission and manifest type.
+// Returns true if the extension |mode| is blocked, removed or allowed by
+// wildcard/update_url but blocked by |manifest type| or |required permissions|.
+bool IsExtensionInstallBlockedByPolicy(
+ ExtensionManagement* extension_management,
+ ExtensionManagement::InstallationMode mode,
+ const ExtensionId& extension_id,
+ const std::string& update_url,
+ Manifest::Type manifest_type,
+ const PermissionSet& required_permissions) {
+ switch (mode) {
+ case ExtensionManagement::INSTALLATION_BLOCKED:
+ case ExtensionManagement::INSTALLATION_REMOVED:
+ return true;
+ case ExtensionManagement::INSTALLATION_FORCED:
+ case ExtensionManagement::INSTALLATION_RECOMMENDED:
+ return false;
+ case ExtensionManagement::INSTALLATION_ALLOWED:
+ break;
+ }
+
+ if (extension_management->IsInstallationExplicitlyAllowed(extension_id))
+ return false;
+
+ // Extension is allowed by wildcard or update_url, checks required permissions
+ // and manifest type.
+ // TODO(crbug.com/1088021): Find out the right way to handle extension policy
+ // priority.
+ if (!extension_management->IsAllowedManifestType(manifest_type,
+ extension_id)) {
+ return true;
+ }
+
+ if (!extension_management->IsPermissionSetAllowed(extension_id, update_url,
+ required_permissions)) {
+ return true;
+ }
+
+ return false;
+}
+
+} // namespace
ExtensionInstallStatus GetWebstoreExtensionInstallStatus(
const ExtensionId& extension_id,
Profile* profile) {
+ return GetWebstoreExtensionInstallStatus(
+ extension_id, profile, Manifest::Type::TYPE_UNKNOWN, PermissionSet());
+}
+
+ExtensionInstallStatus GetWebstoreExtensionInstallStatus(
+ const ExtensionId& extension_id,
+ Profile* profile,
+ const Manifest::Type manifest_type,
+ const PermissionSet& required_permission_set) {
DCHECK(crx_file::id_util::IdIsValid(extension_id));
if (ExtensionPrefs::Get(profile)->HasDisableReason(
extension_id, disable_reason::DISABLE_CUSTODIAN_APPROVAL_REQUIRED)) {
return kCustodianApprovalRequired;
}
+
+ const GURL update_url = extension_urls::GetWebstoreUpdateUrl();
ExtensionManagement* extension_management =
ExtensionManagementFactory::GetForBrowserContext(profile);
// Always use webstore update url to check the installation mode because this
@@ -35,8 +93,8 @@ ExtensionInstallStatus GetWebstoreExtensionInstallStatus(
// |Extension| instance. Note that we don't handle the case where an offstore
// extension with an identical ID is installed.
ExtensionManagement::InstallationMode mode =
- extension_management->GetInstallationMode(
- extension_id, extension_urls::GetWebstoreUpdateUrl().spec());
+ extension_management->GetInstallationMode(extension_id,
+ update_url.spec());
if (mode == ExtensionManagement::INSTALLATION_FORCED ||
mode == ExtensionManagement::INSTALLATION_RECOMMENDED)
@@ -56,7 +114,9 @@ ExtensionInstallStatus GetWebstoreExtensionInstallStatus(
// kBlockedByPolicy, kCanRequest or kRequestPending instead of kDisabled.
// By doing so, user can still request an installed and policy blocked
// extension.
- if (mode == ExtensionManagement::INSTALLATION_ALLOWED) {
+ if (!IsExtensionInstallBlockedByPolicy(
+ extension_management, mode, extension_id, update_url.spec(),
+ manifest_type, required_permission_set)) {
if (registry->disabled_extensions().Contains(extension_id))
return kDisabled;
return kInstallable;
@@ -67,6 +127,8 @@ ExtensionInstallStatus GetWebstoreExtensionInstallStatus(
if (!profile->GetPrefs()->GetBoolean(prefs::kCloudExtensionRequestEnabled))
return kBlockedByPolicy;
+ // An extension which is explicitly blocked by enterprise policy can't be
+ // requested anymore.
if (extension_management->IsInstallationExplicitlyBlocked(extension_id))
return kBlockedByPolicy;
diff --git a/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status.h b/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status.h
index bdb89f3e109..8164ef616e1 100644
--- a/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status.h
+++ b/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status.h
@@ -6,11 +6,14 @@
#define CHROME_BROWSER_EXTENSIONS_API_WEBSTORE_PRIVATE_EXTENSION_INSTALL_STATUS_H_
#include "extensions/common/extension_id.h"
+#include "extensions/common/manifest.h"
class Profile;
namespace extensions {
+class PermissionSet;
+
enum ExtensionInstallStatus {
// Extension is blocked by policy but can be requested.
kCanRequest,
@@ -34,12 +37,24 @@ enum ExtensionInstallStatus {
kForceInstalled
};
-// Returns the Extension install status for an Chrome web store extension with
-// |extension_id| in |profile|.
+// Returns the Extension install status for a Chrome web store extension with
+// |extension_id| in |profile|. Note that this function won't check whether the
+// extension's manifest type or required permissions are blocked by enterprise
+// policy. type blocking or permission blocking. Please use this function only
+// if manifest file is not available.
ExtensionInstallStatus GetWebstoreExtensionInstallStatus(
const ExtensionId& extension_id,
Profile* profile);
+// Returns the Extension install status for a Chrome web store extension with
+// |extension_id| in |profile|. Also check if |manifest_type| or any permission
+// in |required_permission_set| is blocked by enterprise policy.
+ExtensionInstallStatus GetWebstoreExtensionInstallStatus(
+ const ExtensionId& extension_id,
+ Profile* profile,
+ const Manifest::Type manifest_type,
+ const PermissionSet& required_permission_set);
+
} // namespace extensions
#endif // CHROME_BROWSER_EXTENSIONS_API_WEBSTORE_PRIVATE_EXTENSION_INSTALL_STATUS_H_
diff --git a/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status_unittest.cc b/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status_unittest.cc
index d4cfc262b0a..9354e5382b6 100644
--- a/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status_unittest.cc
@@ -20,6 +20,8 @@
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/pref_names.h"
#include "extensions/common/extension_builder.h"
+#include "extensions/common/manifest.h"
+#include "extensions/common/permissions/permission_set.h"
namespace extensions {
namespace {
@@ -42,19 +44,6 @@ constexpr char kExtensionSettingsWithIdBlocked[] = R"({
}
})";
-constexpr char kExtensionSettingsWithIdAllowed[] = R"({
- "abcdefghijklmnopabcdefghijklmnop": {
- "installation_mode": "allowed"
- }
-})";
-
-constexpr char kExtensionSettingsWithIdForced[] = R"({
- "abcdefghijklmnopabcdefghijklmnop": {
- "installation_mode": "force_installed",
- "update_url":"https://clients2.google.com/service/update2/crx"
- }
-})";
-
} // namespace
class ExtensionInstallStatusTest : public BrowserWithTestWindowTest {
@@ -139,7 +128,12 @@ TEST_F(ExtensionInstallStatusTest, ExtensionAllowed) {
}
TEST_F(ExtensionInstallStatusTest, ExtensionForceInstalledByPolicy) {
- SetExtensionSettings(kExtensionSettingsWithIdForced);
+ SetExtensionSettings(R"({
+ "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "force_installed",
+ "update_url":"https://clients2.google.com/service/update2/crx"
+ }
+ })");
ExtensionRegistry::Get(profile())->AddEnabled(CreateExtension(kExtensionId));
EXPECT_EQ(ExtensionInstallStatus::kForceInstalled,
GetWebstoreExtensionInstallStatus(kExtensionId, profile()));
@@ -218,7 +212,11 @@ TEST_F(ExtensionInstallStatusTest, PendingExtenisonIsApproved) {
SetPolicy(prefs::kCloudExtensionRequestEnabled,
std::make_unique<base::Value>(true));
std::vector<ExtensionId> ids = {kExtensionId};
- SetExtensionSettings(kExtensionSettingsWithIdAllowed);
+ SetExtensionSettings(R"({
+ "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "allowed"
+ }
+ })");
EXPECT_EQ(ExtensionInstallStatus::kInstallable,
GetWebstoreExtensionInstallStatus(kExtensionId, profile()));
}
@@ -244,4 +242,282 @@ TEST_F(ExtensionInstallStatusTest, ExtensionCustodianApprovalRequired) {
GetWebstoreExtensionInstallStatus(kExtensionId, profile()));
}
+TEST_F(ExtensionInstallStatusTest, ExtensionBlockedByManifestType) {
+ // TYPE_EXTENSION is blocked by policy
+ // TYPE_THEME and TYPE_HOSTED_APP are allowed.
+ SetExtensionSettings(R"({
+ "*": {
+ "allowed_types": ["theme", "hosted_app"]
+ }
+ })");
+ EXPECT_EQ(ExtensionInstallStatus::kBlockedByPolicy,
+ GetWebstoreExtensionInstallStatus(kExtensionId, profile(),
+ Manifest::Type::TYPE_EXTENSION,
+ PermissionSet()));
+ EXPECT_EQ(ExtensionInstallStatus::kInstallable,
+ GetWebstoreExtensionInstallStatus(kExtensionId, profile(),
+ Manifest::Type::TYPE_THEME,
+ PermissionSet()));
+
+ SetPolicy(prefs::kCloudExtensionRequestEnabled,
+ std::make_unique<base::Value>(true));
+ EXPECT_EQ(ExtensionInstallStatus::kCanRequest,
+ GetWebstoreExtensionInstallStatus(kExtensionId, profile(),
+ Manifest::Type::TYPE_EXTENSION,
+ PermissionSet()));
+ EXPECT_EQ(ExtensionInstallStatus::kCanRequest,
+ GetWebstoreExtensionInstallStatus(kExtensionId, profile(),
+ Manifest::Type::TYPE_HOSTED_APP,
+ PermissionSet()));
+
+ // Request has been approved. Note that currently, manifest type blocking
+ // actually overrides per-id setup. We will find the right priority with
+ // crbug.com/1088016.
+ SetExtensionSettings(R"({
+ "*": {
+ "allowed_types": ["theme", "hosted_app"]
+ }, "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "allowed"
+ }
+ })");
+ EXPECT_EQ(ExtensionInstallStatus::kInstallable,
+ GetWebstoreExtensionInstallStatus(kExtensionId, profile(),
+ Manifest::Type::TYPE_EXTENSION,
+ PermissionSet()));
+ EXPECT_EQ(ExtensionInstallStatus::kInstallable,
+ GetWebstoreExtensionInstallStatus(kExtensionId, profile(),
+ Manifest::Type::TYPE_HOSTED_APP,
+ PermissionSet()));
+
+ // Request has been rejected.
+ SetExtensionSettings(R"({
+ "*": {
+ "allowed_types": ["theme", "hosted_app"]
+ }, "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "blocked"
+ }
+ })");
+ EXPECT_EQ(ExtensionInstallStatus::kBlockedByPolicy,
+ GetWebstoreExtensionInstallStatus(kExtensionId, profile(),
+ Manifest::Type::TYPE_EXTENSION,
+ PermissionSet()));
+ EXPECT_EQ(ExtensionInstallStatus::kBlockedByPolicy,
+ GetWebstoreExtensionInstallStatus(kExtensionId, profile(),
+ Manifest::Type::TYPE_HOSTED_APP,
+ PermissionSet()));
+
+ // Request has been forced installed.
+ SetExtensionSettings(R"({
+ "*": {
+ "allowed_types": ["theme", "hosted_app"]
+ }, "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "force_installed",
+ "update_url":"https://clients2.google.com/service/update2/crx"
+ }
+ })");
+ EXPECT_EQ(ExtensionInstallStatus::kForceInstalled,
+ GetWebstoreExtensionInstallStatus(kExtensionId, profile(),
+ Manifest::Type::TYPE_EXTENSION,
+ PermissionSet()));
+ EXPECT_EQ(ExtensionInstallStatus::kForceInstalled,
+ GetWebstoreExtensionInstallStatus(kExtensionId, profile(),
+ Manifest::Type::TYPE_HOSTED_APP,
+ PermissionSet()));
+}
+
+TEST_F(ExtensionInstallStatusTest, ExtensionBlockedByPermissions) {
+ // Block 'storage' for all extensions.
+ SetExtensionSettings(R"({
+ "*": {
+ "blocked_permissions": ["storage"]
+ }
+ })");
+
+ // Extension with audio permission is still installable but not with storage.
+ APIPermissionSet api_permissions;
+ api_permissions.insert(APIPermission::kAudio);
+ EXPECT_EQ(ExtensionInstallStatus::kInstallable,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+ api_permissions.insert(APIPermission::kStorage);
+ EXPECT_EQ(ExtensionInstallStatus::kBlockedByPolicy,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+
+ // And they can be requested,
+ SetPolicy(prefs::kCloudExtensionRequestEnabled,
+ std::make_unique<base::Value>(true));
+ EXPECT_EQ(ExtensionInstallStatus::kCanRequest,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+
+ // Request has been approved.
+ SetExtensionSettings(R"({
+ "*": {
+ "blocked_permissions": ["storage"]
+ }, "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "allowed"
+ }
+ })");
+ EXPECT_EQ(ExtensionInstallStatus::kInstallable,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+
+ // Request has been rejected.
+ SetExtensionSettings(R"({
+ "*": {
+ "blocked_permissions": ["storage"]
+ }, "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "blocked"
+ }
+ })");
+ EXPECT_EQ(ExtensionInstallStatus::kBlockedByPolicy,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+
+ // Request has been force installed.
+ SetExtensionSettings(R"({
+ "*": {
+ "blocked_permissions": ["storage"]
+ }, "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "force_installed",
+ "update_url":"https://clients2.google.com/service/update2/crx"
+ }
+ })");
+ EXPECT_EQ(ExtensionInstallStatus::kForceInstalled,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+}
+
+TEST_F(ExtensionInstallStatusTest, ExtensionBlockedByPermissionsWithUpdateUrl) {
+ // Block 'downloads' for all extensions from web store.
+ SetExtensionSettings(R"({
+ "update_url:https://clients2.google.com/service/update2/crx": {
+ "blocked_permissions": ["downloads"]
+ }
+ })");
+
+ APIPermissionSet api_permissions;
+ api_permissions.insert(APIPermission::kAudio);
+ EXPECT_EQ(ExtensionInstallStatus::kInstallable,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+ api_permissions.insert(APIPermission::kDownloads);
+ EXPECT_EQ(ExtensionInstallStatus::kBlockedByPolicy,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+
+ // And they can be requested,
+ SetPolicy(prefs::kCloudExtensionRequestEnabled,
+ std::make_unique<base::Value>(true));
+ EXPECT_EQ(ExtensionInstallStatus::kCanRequest,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+
+ // Request has been approved.
+ SetExtensionSettings(R"({
+ "update_url:https://clients2.google.com/service/update2/crx": {
+ "blocked_permissions": ["downloads"]
+ }, "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "allowed"
+ }
+ })");
+ EXPECT_EQ(ExtensionInstallStatus::kInstallable,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+
+ // Request has been rejected.
+ SetExtensionSettings(R"({
+ "update_url:https://clients2.google.com/service/update2/crx": {
+ "blocked_permissions": ["downloads"]
+ }, "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "blocked"
+ }
+ })");
+ EXPECT_EQ(ExtensionInstallStatus::kBlockedByPolicy,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+
+ // Request has been force-installed.
+ SetExtensionSettings(R"({
+ "update_url:https://clients2.google.com/service/update2/crx": {
+ "blocked_permissions": ["downloads"]
+ }, "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "force_installed",
+ "update_url":"https://clients2.google.com/service/update2/crx"
+ }
+ })");
+ EXPECT_EQ(ExtensionInstallStatus::kForceInstalled,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+}
+
+TEST_F(ExtensionInstallStatusTest,
+ ExtensionBlockedByPermissionButWhitelistById) {
+ SetExtensionSettings(R"({
+ "*": {
+ "blocked_permissions": ["storage"]
+ }, "abcdefghijklmnopabcdefghijklmnop": {
+ "installation_mode": "allowed"
+ }})");
+
+ // Per-id whitelisted has higher priority than blocked permissions.
+ APIPermissionSet api_permissions;
+ api_permissions.insert(APIPermission::kStorage);
+ EXPECT_EQ(ExtensionInstallStatus::kInstallable,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+}
+
+// Extension policies apply to non web store update url doesn't affect the
+// status here.
+TEST_F(ExtensionInstallStatusTest, NonWebstoreUpdateUrlPolicy) {
+ SetExtensionSettings(R"({
+ "update_url:https://other.extensions/webstore": {
+ "installation_mode": "blocked"
+ }
+ })");
+ EXPECT_EQ(ExtensionInstallStatus::kInstallable,
+ GetWebstoreExtensionInstallStatus(kExtensionId, profile()));
+
+ SetExtensionSettings(R"({
+ "update_url:https://other.extensions/webstore": {
+ "blocked_permissions": ["downloads"]
+ }
+ })");
+ APIPermissionSet api_permissions;
+ api_permissions.insert(APIPermission::kDownloads);
+ EXPECT_EQ(ExtensionInstallStatus::kInstallable,
+ GetWebstoreExtensionInstallStatus(
+ kExtensionId, profile(), Manifest::Type::TYPE_EXTENSION,
+ PermissionSet(api_permissions.Clone(), ManifestPermissionSet(),
+ URLPatternSet(), URLPatternSet())));
+}
+
} // namespace extensions
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 862650ef793..ebfeb3568a3 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
@@ -49,7 +49,10 @@
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/common/extension.h"
+#include "extensions/common/manifest.h"
#include "extensions/common/manifest_constants.h"
+#include "extensions/common/manifest_handlers/permissions_parser.h"
+#include "extensions/common/permissions/permission_set.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"
#include "ui/base/l10n/l10n_util.h"
@@ -118,7 +121,7 @@ std::unique_ptr<WebstoreInstaller::Approval> PendingApprovals::PopApproval(
const std::string& id) {
for (auto iter = approvals_.begin(); iter != approvals_.end(); ++iter) {
if (iter->get()->extension_id == id &&
- profile->IsSameProfile(iter->get()->profile)) {
+ profile->IsSameOrParent(iter->get()->profile)) {
std::unique_ptr<WebstoreInstaller::Approval> approval = std::move(*iter);
approvals_.erase(iter);
return approval;
@@ -267,6 +270,9 @@ ConvertExtensionInstallStatusForAPI(ExtensionInstallStatus status) {
// successfully. Otherwise, returns the initial extension install status.
ExtensionInstallStatus AddExtensionToPendingList(const ExtensionId& id,
Profile* profile) {
+ // There is no need to check whether the extension's required permissions or
+ // manifest type are blocked by the enterprise policy because extensions
+ // blocked by those are still requestable.
ExtensionInstallStatus status =
GetWebstoreExtensionInstallStatus(id, profile);
// We put the |id| into the pending request list if it can be requested.
@@ -447,8 +453,9 @@ void WebstorePrivateBeginInstallWithManifest3Function::OnWebstoreParseSuccess(
#endif // BUILDFLAG(ENABLE_SUPERVISED_USERS)
// Check the management policy before the installation process begins.
- ExtensionInstallStatus install_status =
- GetWebstoreExtensionInstallStatus(id, profile);
+ ExtensionInstallStatus install_status = GetWebstoreExtensionInstallStatus(
+ id, profile, dummy_extension_->manifest()->type(),
+ PermissionsParser::GetRequiredPermissions(dummy_extension_.get()));
if (install_status == kBlockedByPolicy) {
ShowBlockedByPolicyDialog(
dummy_extension_.get(), icon_, web_contents,
@@ -582,7 +589,7 @@ bool WebstorePrivateBeginInstallWithManifest3Function::
parent_permission_dialog_ =
ParentPermissionDialog::CreateParentPermissionDialogForExtension(
- profile, web_contents, web_contents->GetTopLevelNativeWindow(),
+ profile, web_contents->GetTopLevelNativeWindow(),
gfx::ImageSkia::CreateFrom1xBitmap(icon_), dummy_extension_.get(),
std::move(done_callback));
parent_permission_dialog_->ShowDialog();
@@ -697,12 +704,13 @@ void WebstorePrivateBeginInstallWithManifest3Function::HandleInstallAbort(
// The web store install histograms are a subset of the install histograms.
// We need to record both histograms here since CrxInstaller::InstallUIAbort
// is never called for web store install cancellations.
- std::string histogram_name = user_initiated ? "WebStoreInstallCancel"
- : "WebStoreInstallAbort";
- ExtensionService::RecordPermissionMessagesHistogram(dummy_extension_.get(),
- histogram_name.c_str());
+ if (user_initiated) {
+ ExtensionService::RecordPermissionMessagesHistogram(
+ dummy_extension_.get(), "WebStoreInstallCancel");
+ }
- histogram_name = user_initiated ? "InstallCancel" : "InstallAbort";
+ std::string histogram_name =
+ user_initiated ? "InstallCancel" : "InstallAbort";
ExtensionService::RecordPermissionMessagesHistogram(dummy_extension_.get(),
histogram_name.c_str());
@@ -1094,12 +1102,58 @@ WebstorePrivateGetExtensionStatusFunction::Run() {
return RespondNow(Error(kWebstoreInvalidIdError));
}
+ if (!params->manifest)
+ return RespondNow(BuildResponseWithoutManifest(extension_id, profile));
+
+ data_decoder::DataDecoder::ParseJsonIsolated(
+ *(params->manifest),
+ base::BindOnce(
+ &WebstorePrivateGetExtensionStatusFunction::OnManifestParsed, this,
+ extension_id));
+ return RespondLater();
+}
+
+ExtensionFunction::ResponseValue
+WebstorePrivateGetExtensionStatusFunction::BuildResponseWithoutManifest(
+ const ExtensionId& extension_id,
+ Profile* profile) {
ExtensionInstallStatus status =
GetWebstoreExtensionInstallStatus(extension_id, profile);
api::webstore_private::ExtensionInstallStatus api_status =
ConvertExtensionInstallStatusForAPI(status);
- return RespondNow(
- OneArgument(GetExtensionStatus::Results::Create(api_status)));
+ return ArgumentList(GetExtensionStatus::Results::Create(api_status));
+}
+
+void WebstorePrivateGetExtensionStatusFunction::OnManifestParsed(
+ const ExtensionId& extension_id,
+ data_decoder::DataDecoder::ValueOrError result) {
+ if (!result.value || !result.value->is_dict()) {
+ Respond(Error(kWebstoreInvalidManifestError));
+ return;
+ }
+
+ if (!g_browser_process->profile_manager()->IsValidProfile(
+ chrome_details_.GetProfile())) {
+ Respond(Error(kWebstoreUserCancelledError));
+ }
+
+ std::string error;
+ auto dummy_extension =
+ Extension::Create(base::FilePath(), Manifest::INTERNAL,
+ base::Value::AsDictionaryValue(*result.value),
+ Extension::FROM_WEBSTORE, extension_id, &error);
+
+ if (!dummy_extension) {
+ Respond(Error(kWebstoreInvalidManifestError));
+ return;
+ }
+
+ ExtensionInstallStatus status = GetWebstoreExtensionInstallStatus(
+ extension_id, chrome_details_.GetProfile(), dummy_extension->GetType(),
+ PermissionsParser::GetRequiredPermissions(dummy_extension.get()));
+ api::webstore_private::ExtensionInstallStatus api_status =
+ ConvertExtensionInstallStatusForAPI(status);
+ Respond(ArgumentList(GetExtensionStatus::Results::Create(api_status)));
}
WebstorePrivateRequestExtensionFunction::
@@ -1124,7 +1178,8 @@ WebstorePrivateRequestExtensionFunction::Run() {
api::webstore_private::ExtensionInstallStatus api_status =
ConvertExtensionInstallStatusForAPI(status);
- return RespondNow(OneArgument(RequestExtension::Results::Create(api_status)));
+ return RespondNow(
+ ArgumentList(RequestExtension::Results::Create(api_status)));
}
} // namespace extensions
diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h
index d1bbb96b944..b4b3e646698 100644
--- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h
+++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h
@@ -372,6 +372,12 @@ class WebstorePrivateGetExtensionStatusFunction : public ExtensionFunction {
private:
~WebstorePrivateGetExtensionStatusFunction() override;
+ ExtensionFunction::ResponseValue BuildResponseWithoutManifest(
+ const ExtensionId& extension_id,
+ Profile* profile);
+ void OnManifestParsed(const ExtensionId& extension_id,
+ data_decoder::DataDecoder::ValueOrError result);
+
// ExtensionFunction:
ExtensionFunction::ResponseAction Run() override;
diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc
index 09b988d79e9..4a1771a1d79 100644
--- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc
+++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc
@@ -55,7 +55,7 @@
#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
#include "chrome/browser/supervised_user/supervised_user_test_util.h"
#include "chrome/browser/ui/supervised_user/parent_permission_dialog.h"
-#include "chrome/browser/ui/views/parent_permission_dialog_view.h"
+#include "chrome/browser/ui/views/supervised_user/parent_permission_dialog_view.h"
#include "components/account_id/account_id.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "extensions/common/extension_builder.h"
diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc
index 49e6ebbb3dc..1bff22cebc1 100644
--- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc
+++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc
@@ -23,6 +23,7 @@
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/pref_names.h"
#include "extensions/common/extension_builder.h"
+#include "services/data_decoder/public/cpp/test_support/in_process_data_decoder.h"
namespace extensions {
namespace {
@@ -32,7 +33,10 @@ constexpr int kFakeTime = 12345;
constexpr char kExtensionManifest[] = R"({
\"name\" : \"Extension\",
\"manifest_version\": 3,
- \"version\": \"0.1\"})";
+ \"version\": \"0.1\",
+ \"permissions\": [ \"example.com\", \"downloads\"],
+ \"optional_permissions\" : [\"audio\"]})";
+
constexpr char kBlockAllExtensionSettings[] = R"({
"*": {
"installation_mode":"blocked",
@@ -57,6 +61,24 @@ constexpr char kBlockedExtensionSettings[] = R"({
}
})";
+constexpr char kBlockedManifestTypeExtensionSettings[] = R"({
+ "*": {
+ "allowed_types": ["theme", "hosted_app"]
+ }
+})";
+
+constexpr char kBlockedDownloadsPermissionsExtensionSettings[] = R"({
+ "*": {
+ "blocked_permissions": ["downloads"]
+ }
+})";
+
+constexpr char kBlockedAudioPermissionsExtensionSettings[] = R"({
+ "*": {
+ "blocked_permissions": ["audio"]
+ }
+})";
+
constexpr char kWebstoreUserCancelledError[] = "User cancelled install";
constexpr char kWebstoreBlockByPolicy[] =
"Extension installation is blocked by policy";
@@ -103,17 +125,18 @@ class WebstorePrivateExtensionInstallRequestBase : public ExtensionApiUnittest {
return base::StringPrintf(R"(["%s"])", id);
}
+ std::string GenerateArgs(const char* id, const char* manifest) {
+ return base::StringPrintf(R"(["%s", "%s"])", id, manifest);
+ }
+
scoped_refptr<const Extension> CreateExtension(const ExtensionId& id) {
return ExtensionBuilder("extension").SetID(id).Build();
}
void VerifyResponse(const ExtensionInstallStatus& expected_response,
const base::Value* actual_response) {
- ASSERT_TRUE(actual_response->is_list());
- const auto& actual_list = actual_response->GetList();
- ASSERT_EQ(1u, actual_list.size());
- ASSERT_TRUE(actual_list[0].is_string());
- EXPECT_EQ(ToString(expected_response), actual_list[0].GetString());
+ ASSERT_TRUE(actual_response->is_string());
+ EXPECT_EQ(ToString(expected_response), actual_response->GetString());
}
private:
@@ -121,7 +144,18 @@ class WebstorePrivateExtensionInstallRequestBase : public ExtensionApiUnittest {
};
class WebstorePrivateGetExtensionStatusTest
- : public WebstorePrivateExtensionInstallRequestBase {};
+ : public WebstorePrivateExtensionInstallRequestBase {
+ public:
+ void SetUp() override {
+ WebstorePrivateExtensionInstallRequestBase::SetUp();
+ in_process_data_decoder_ =
+ std::make_unique<data_decoder::test::InProcessDataDecoder>();
+ }
+
+ private:
+ std::unique_ptr<data_decoder::test::InProcessDataDecoder>
+ in_process_data_decoder_;
+};
TEST_F(WebstorePrivateGetExtensionStatusTest, InvalidExtensionId) {
auto function =
@@ -141,6 +175,49 @@ TEST_F(WebstorePrivateGetExtensionStatusTest, ExtensionEnabled) {
response.get());
}
+TEST_F(WebstorePrivateGetExtensionStatusTest, InvalidManifest) {
+ auto function =
+ base::MakeRefCounted<WebstorePrivateGetExtensionStatusFunction>();
+ EXPECT_EQ(
+ "Invalid manifest",
+ RunFunctionAndReturnError(
+ function.get(), GenerateArgs(kExtensionId, "invalid-manifest")));
+}
+
+TEST_F(WebstorePrivateGetExtensionStatusTest, ExtensionBlockdedByManifestType) {
+ SetExtensionSettings(kBlockedManifestTypeExtensionSettings, profile());
+ auto function =
+ base::MakeRefCounted<WebstorePrivateGetExtensionStatusFunction>();
+ std::unique_ptr<base::Value> response = RunFunctionAndReturnValue(
+ function.get(), GenerateArgs(kExtensionId, kExtensionManifest));
+ VerifyResponse(
+ ExtensionInstallStatus::EXTENSION_INSTALL_STATUS_BLOCKED_BY_POLICY,
+ response.get());
+}
+
+TEST_F(WebstorePrivateGetExtensionStatusTest, ExtensionBlockdedByPermission) {
+ SetExtensionSettings(kBlockedDownloadsPermissionsExtensionSettings,
+ profile());
+ auto function =
+ base::MakeRefCounted<WebstorePrivateGetExtensionStatusFunction>();
+ std::unique_ptr<base::Value> response = RunFunctionAndReturnValue(
+ function.get(), GenerateArgs(kExtensionId, kExtensionManifest));
+ VerifyResponse(
+ ExtensionInstallStatus::EXTENSION_INSTALL_STATUS_BLOCKED_BY_POLICY,
+ response.get());
+}
+
+TEST_F(WebstorePrivateGetExtensionStatusTest,
+ ExtensionNotBlockdedByOptionalPermission) {
+ SetExtensionSettings(kBlockedAudioPermissionsExtensionSettings, profile());
+ auto function =
+ base::MakeRefCounted<WebstorePrivateGetExtensionStatusFunction>();
+ std::unique_ptr<base::Value> response = RunFunctionAndReturnValue(
+ function.get(), GenerateArgs(kExtensionId, kExtensionManifest));
+ VerifyResponse(ExtensionInstallStatus::EXTENSION_INSTALL_STATUS_INSTALLABLE,
+ response.get());
+}
+
class WebstorePrivateRequestExtensionTest
: public WebstorePrivateExtensionInstallRequestBase {
public:
@@ -434,4 +511,57 @@ TEST_F(WebstorePrivateBeginInstallWithManifest3Test,
VerifyBlockedByPolicyFunctionResult(function.get(), base::string16());
}
+TEST_F(WebstorePrivateBeginInstallWithManifest3Test,
+ ExtensionBlockdedByManifestType) {
+ SetExtensionSettings(kBlockedManifestTypeExtensionSettings);
+
+ std::unique_ptr<content::WebContents> web_contents =
+ content::WebContentsTester::CreateTestWebContents(profile(), nullptr);
+ auto function =
+ base::MakeRefCounted<WebstorePrivateBeginInstallWithManifest3Function>();
+ function->SetRenderFrameHost(web_contents->GetMainFrame());
+ ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::ACCEPT);
+
+ api_test_utils::RunFunction(function.get(),
+ GenerateArgs(kExtensionId, kExtensionManifest),
+ profile());
+ VerifyBlockedByPolicyFunctionResult(function.get(), base::string16());
+}
+
+TEST_F(WebstorePrivateBeginInstallWithManifest3Test,
+ ExtensionBlockdedByPermission) {
+ SetExtensionSettings(kBlockedDownloadsPermissionsExtensionSettings);
+
+ std::unique_ptr<content::WebContents> web_contents =
+ content::WebContentsTester::CreateTestWebContents(profile(), nullptr);
+ auto function =
+ base::MakeRefCounted<WebstorePrivateBeginInstallWithManifest3Function>();
+ function->SetRenderFrameHost(web_contents->GetMainFrame());
+ ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::ACCEPT);
+
+ api_test_utils::RunFunction(function.get(),
+ GenerateArgs(kExtensionId, kExtensionManifest),
+ profile());
+ VerifyBlockedByPolicyFunctionResult(function.get(), base::string16());
+}
+
+TEST_F(WebstorePrivateBeginInstallWithManifest3Test,
+ ExtensionNotBlockdedByOptionalPermission) {
+ SetExtensionSettings(kBlockedAudioPermissionsExtensionSettings);
+
+ std::unique_ptr<content::WebContents> web_contents =
+ content::WebContentsTester::CreateTestWebContents(profile(), nullptr);
+ auto function =
+ base::MakeRefCounted<WebstorePrivateBeginInstallWithManifest3Function>();
+ function->SetRenderFrameHost(web_contents->GetMainFrame());
+ ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::ACCEPT);
+
+ std::unique_ptr<base::Value> response = RunFunctionAndReturnValue(
+ function.get(), GenerateArgs(kExtensionId, kExtensionManifest));
+ // The API returns empty string when extension is installed successfully.
+ ASSERT_TRUE(response);
+ ASSERT_TRUE(response->is_string());
+ EXPECT_EQ(std::string(), response->GetString());
+}
+
} // namespace extensions
diff --git a/chromium/chrome/browser/flags/BUILD.gn b/chromium/chrome/browser/flags/BUILD.gn
index a8481265fb3..d26786b7e9f 100644
--- a/chromium/chrome/browser/flags/BUILD.gn
+++ b/chromium/chrome/browser/flags/BUILD.gn
@@ -64,6 +64,7 @@ java_library("flags_junit_tests") {
"//base:base_junit_test_support",
"//base/test:test_support_java",
"//chrome/test/android:chrome_java_test_support",
+ "//third_party/junit",
]
}
diff --git a/chromium/chrome/browser/fullscreen/android/BUILD.gn b/chromium/chrome/browser/fullscreen/android/BUILD.gn
new file mode 100644
index 00000000000..7e6c8c1979e
--- /dev/null
+++ b/chromium/chrome/browser/fullscreen/android/BUILD.gn
@@ -0,0 +1,14 @@
+# Copyright 2020 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//build/config/android/rules.gni")
+
+android_library("java") {
+ sources = [
+ "java/src/org/chromium/chrome/browser/fullscreen/FullscreenManager.java",
+ "java/src/org/chromium/chrome/browser/fullscreen/FullscreenOptions.java",
+ ]
+
+ deps = [ "//chrome/browser/tab:java" ]
+}
diff --git a/chromium/chrome/browser/media/feeds/media_feeds_store.mojom b/chromium/chrome/browser/media/feeds/media_feeds_store.mojom
index ec77b81c049..bfb3795fb67 100644
--- a/chromium/chrome/browser/media/feeds/media_feeds_store.mojom
+++ b/chromium/chrome/browser/media/feeds/media_feeds_store.mojom
@@ -10,6 +10,7 @@ import "mojo/public/mojom/base/time.mojom";
import "url/mojom/origin.mojom";
import "ui/gfx/geometry/mojom/geometry.mojom";
import "url/mojom/url.mojom";
+import "mojo/public/mojom/base/unguessable_token.mojom";
struct MediaFeed {
// The ID of the field in storage.
@@ -67,13 +68,21 @@ struct MediaFeed {
// have been deleted and the feed status has been reset to default.
ResetReason reset_reason;
- // An associated origin is an origin associated with the feed. If the cookies
- // are deleted or expire on the origin then we will delete the feed items.
- // https://wicg.github.io/media-feeds/#dfn-associated-origin
- array<url.mojom.Origin> associated_origins;
+ // Token used to invalidate ongoing fetches for the feed. If there is a token
+ // mismatch when feed fetch data returns (the reset token when the fetch began
+ // does not match the feed's current reset token), the data is stale and
+ // shouldn't be stored because the feed has been reset.
+ mojo_base.mojom.UnguessableToken? reset_token;
// Contains details about the user signed into the website.
UserIdentifier? user_identifier;
+
+ // If set then changes to the cookie name provided on the feed origin or any
+ // associated origin will trigger the feed to be reset.
+ string cookie_name_filter;
+
+ // The result of safe search checking this media feed.
+ SafeSearchResult safe_search_result;
};
// Contains details about the user signed into the website.
@@ -345,10 +354,22 @@ struct MediaImage {
array<ContentAttribute> content_attributes;
};
+// Whether the feed item can be considered "family friendly". If this is not
+// specified then this will be |kUnknown|. This enum is committed to storage
+// so do not change the numbering.
+enum IsFamilyFriendly {
+ kUnknown = 0,
+ kYes = 1,
+ kNo = 2,
+};
+
// The Media Feed Item is an individual item stored in a Media Feed. It
// represents a single recommendation such as a video or TV show.
// https://wicg.github.io/media-feeds/index.html#media-feed-item
struct MediaFeedItem {
+ // The ID of the feed item in storage.
+ int64 id;
+
// The type of this feed item such as a video or TV show.
MediaFeedItemType type;
@@ -362,7 +383,7 @@ struct MediaFeedItem {
mojo_base.mojom.Time date_published;
// Whether the media item is considered "family friendly".
- bool is_family_friendly;
+ IsFamilyFriendly is_family_friendly;
// The action status for this feed item.
MediaFeedItemActionStatus action_status;
@@ -414,6 +435,12 @@ struct DebugInformation {
// The value of the Media Feeds Safe Search checking consent pref.
bool safe_search_pref_value;
+
+ // Whether the MediaFeedsBackgroundFetching feature is enabled.
+ bool background_fetching_feature_enabled;
+
+ // The value of the Media Feeds background fetching pref.
+ bool background_fetching_pref_value;
};
// MediaFeedStore allows the Media Feeds WebUI to access data from the Media
@@ -425,6 +452,9 @@ interface MediaFeedsStore {
// Updates the Safe Search checking enabled pref to |value|.
SetSafeSearchEnabledPref(bool value) => ();
+ // Updates the background fetching enabled pref to |value|.
+ SetBackgroundFetchingPref(bool value) => ();
+
// Gets all the discovered media feeds.
GetMediaFeeds() => (array<MediaFeed> feeds);
@@ -433,6 +463,7 @@ interface MediaFeedsStore {
// Fetch the details of a previously-discovered media feed and store them in
// media history. The feed ID is the unique ID for the feed from the Media
- // History store.
- FetchMediaFeed(int64 feed_id) => ();
+ // History store. The logs contain information about any problems fetching or
+ // parsing the feed.
+ FetchMediaFeed(int64 feed_id) => (string logs);
};
diff --git a/chromium/chrome/browser/media/kaleidoscope/BUILD.gn b/chromium/chrome/browser/media/kaleidoscope/BUILD.gn
new file mode 100644
index 00000000000..45446236046
--- /dev/null
+++ b/chromium/chrome/browser/media/kaleidoscope/BUILD.gn
@@ -0,0 +1,44 @@
+# Copyright 2020 The Chromium 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("//chrome/browser/buildflags.gni")
+import("//tools/grit/grit_rule.gni")
+
+# If the ENABLE_KALEIDOSCOPE flag is enabled and src-internal is available then
+# include the internal resources. Otherwise, empty resources are used.
+if (enable_kaleidoscope) {
+ grit("kaleidoscope_resources") {
+ source = "kaleidoscope_internal_resources.grd"
+ outputs = [
+ "grit/kaleidoscope_resources.h",
+ "kaleidoscope_resources.pak",
+ ]
+ grit_flags = [
+ "-E",
+ "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
+ ]
+ deps = [
+ "//chrome/browser/media/kaleidoscope/internal:kaleidoscope_strings",
+ "//chrome/browser/media/kaleidoscope/internal/resources:content",
+ "//chrome/browser/media/kaleidoscope/mojom:mojom_js",
+ "//url/mojom:url_mojom_gurl_js",
+ ]
+ }
+} else {
+ grit("kaleidoscope_resources") {
+ source = "kaleidoscope_resources.grd"
+ outputs = [
+ "grit/kaleidoscope_resources.h",
+ "kaleidoscope_resources.pak",
+ ]
+ grit_flags = [
+ "-E",
+ "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
+ ]
+ deps = [
+ "//chrome/browser/media/kaleidoscope/mojom:mojom_js",
+ "//url/mojom:url_mojom_gurl_js",
+ ]
+ }
+}
diff --git a/chromium/chrome/browser/media/kaleidoscope/kaleidoscope_internal_resources.grd b/chromium/chrome/browser/media/kaleidoscope/kaleidoscope_internal_resources.grd
new file mode 100644
index 00000000000..8ca771da653
--- /dev/null
+++ b/chromium/chrome/browser/media/kaleidoscope/kaleidoscope_internal_resources.grd
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<grit latest_public_release="0" current_release="1" output_all_resource_defines="false">
+ <outputs>
+ <output filename="grit/kaleidoscope_resources.h" type="rc_header">
+ <emit emit_type='prepend'></emit>
+ </output>
+ <output filename="kaleidoscope_resources.pak" type="data_package" />
+ </outputs>
+ <release seq="1">
+ <includes>
+ <include name="IDR_KALEIDOSCOPE_CONTENT_CSS" file="internal/resources/content.css" type="chrome_html" flattenhtml="true" compress="gzip" />
+ <include name="IDR_KALEIDOSCOPE_CONTENT_HTML" file="internal/resources/content.html" type="BINDATA" compress="gzip" />
+ <include name="IDR_KALEIDOSCOPE_CONTENT_JS" file="${root_gen_dir}/chrome/browser/media/kaleidoscope/internal/resources/ks-content.js" use_base_dir="false" type="BINDATA" compress="gzip" />
+ <include name="IDR_KALEIDOSCOPE_HTML" file="internal/resources/kaleidoscope.html" type="BINDATA" compress="gzip" />
+ <include name="IDR_KALEIDOSCOPE_JS" file="internal/resources/kaleidoscope.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_KALEIDOSCOPE_MESSAGES_JS" file="internal/resources/messages.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_KALEIDOSCOPE_UTILS_JS" file="internal/resources/utils.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_GEOMETRY_MOJOM_LITE_JS" file="${root_gen_dir}/ui/gfx/geometry/mojom/geometry.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
+ <include name="IDR_KALEIDOSCOPE_MOJOM_LITE_JS" file="${root_gen_dir}/chrome/browser/media/kaleidoscope/mojom/kaleidoscope.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
+
+ <!-- Strings -->
+ <include name="IDR_KALEIDOSCOPE_LOCALE_EN" file="${root_gen_dir}/chrome/browser/media/kaleidoscope/internal/resources/_locales/en/messages.json" use_base_dir="false" type="BINDATA" compress="gzip" />
+
+ <!-- Google Sans -->
+ <include name="IDR_GOOGLE_SANS_CSS" file="internal/resources/fonts/fonts.css" type="BINDATA" compress="gzip" />
+ <include name="IDR_GOOGLE_SANS_BOLD" file="internal/resources/fonts/GoogleSans-Bold.woff2" type="BINDATA" compress="gzip" />
+ <include name="IDR_GOOGLE_SANS_MEDIUM" file="internal/resources/fonts/GoogleSans-Medium.woff2" type="BINDATA" compress="gzip" />
+ <include name="IDR_GOOGLE_SANS_REGULAR" file="internal/resources/fonts/GoogleSans-Regular.woff2" type="BINDATA" compress="gzip" />
+ </includes>
+ </release>
+</grit>
diff --git a/chromium/chrome/browser/media/kaleidoscope/kaleidoscope_resources.grd b/chromium/chrome/browser/media/kaleidoscope/kaleidoscope_resources.grd
new file mode 100644
index 00000000000..72d8ab5339e
--- /dev/null
+++ b/chromium/chrome/browser/media/kaleidoscope/kaleidoscope_resources.grd
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<grit latest_public_release="0" current_release="1" output_all_resource_defines="false">
+ <outputs>
+ <output filename="grit/kaleidoscope_resources.h" type="rc_header">
+ <emit emit_type='prepend'></emit>
+ </output>
+ <output filename="kaleidoscope_resources.pak" type="data_package" />
+ </outputs>
+ <release seq="1">
+ <includes>
+ <!-- TODO: Add resources. -->
+ </includes>
+ </release>
+</grit>
diff --git a/chromium/chrome/browser/media/kaleidoscope/mojom/BUILD.gn b/chromium/chrome/browser/media/kaleidoscope/mojom/BUILD.gn
new file mode 100644
index 00000000000..e3ce1eb00b5
--- /dev/null
+++ b/chromium/chrome/browser/media/kaleidoscope/mojom/BUILD.gn
@@ -0,0 +1,11 @@
+# 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 = [ "kaleidoscope.mojom" ]
+
+ public_deps = [ "//chrome/browser/media/feeds:mojo_bindings" ]
+}
diff --git a/chromium/chrome/browser/media/kaleidoscope/mojom/kaleidoscope.mojom b/chromium/chrome/browser/media/kaleidoscope/mojom/kaleidoscope.mojom
new file mode 100644
index 00000000000..779ef7edf33
--- /dev/null
+++ b/chromium/chrome/browser/media/kaleidoscope/mojom/kaleidoscope.mojom
@@ -0,0 +1,30 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+module media.mojom;
+
+import "chrome/browser/media/feeds/media_feeds_store.mojom";
+
+// The credentials required to make Google API calls from JS.
+struct Credentials {
+ // Chrome's API Key.
+ string api_key;
+
+ // An OAuth access token scoped to the Kaleidoscope API for the currently
+ // logged in user. If the user is not signed in then this will be empty.
+ string? access_token;
+};
+
+// Provides data for the kaleidoscope page.
+interface KaleidoscopeDataProvider {
+ // Returns all the Media Feeds that Kaleidoscope might decide to show.
+ GetTopMediaFeeds() => (array<media_feeds.mojom.MediaFeed> feeds);
+
+ // Returns all the items from a Media Feed that Kaleidoscope might decide to
+ // show.
+ GetMediaFeedContents(int64 feed_id) => (array<media_feeds.mojom.MediaFeedItem> items);
+
+ // Retrieves the current credentials.
+ GetCredentials() => (Credentials credentials);
+};
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/lib/BUILD.gn b/chromium/chrome/browser/media/kaleidoscope/test/proto/BUILD.gn
index 67207741560..48dedc2a124 100644
--- a/chromium/chrome/browser/resources/chromeos/camera/src/js/lib/BUILD.gn
+++ b/chromium/chrome/browser/media/kaleidoscope/test/proto/BUILD.gn
@@ -3,11 +3,16 @@
# found in the LICENSE file.
import("//third_party/closure_compiler/compile_js.gni")
+import("//third_party/protobuf/proto_library.gni")
-js_library("comlink") {
- sources = [ "comlink.js" ]
+proto_library("proto") {
+ sources = [ "test.proto" ]
+
+ generate_javascript = true
}
-js_library("ffmpeg") {
- sources = [ "ffmpeg.js" ]
+js_library("test") {
+ sources = []
+
+ deps = [ ":proto_js" ]
}
diff --git a/chromium/chrome/browser/media/router/BUILD.gn b/chromium/chrome/browser/media/router/BUILD.gn
index 0a680d40f51..c6cfa9f6ac5 100644
--- a/chromium/chrome/browser/media/router/BUILD.gn
+++ b/chromium/chrome/browser/media/router/BUILD.gn
@@ -88,6 +88,8 @@ static_library("router") {
"//ui/base:buildflags",
]
+ public_deps += [ "//chrome/common/media_router/mojom:logger" ]
+
sources += [
"data_decoder_util.cc",
"data_decoder_util.h",
@@ -95,6 +97,8 @@ static_library("router") {
"event_page_request_manager.h",
"event_page_request_manager_factory.cc",
"event_page_request_manager_factory.h",
+ "logger_impl.cc",
+ "logger_impl.h",
"mojo/media_route_provider_util_win.cc",
"mojo/media_route_provider_util_win.h",
"mojo/media_router_desktop.cc",
@@ -202,6 +206,8 @@ static_library("test_support") {
"test/media_router_mojo_test.h",
"test/mock_dns_sd_registry.cc",
"test/mock_dns_sd_registry.h",
+ "test/mock_logger.cc",
+ "test/mock_logger.h",
"test/mock_mojo_media_router.cc",
"test/mock_mojo_media_router.h",
"test/noop_dual_media_sink_service.cc",
@@ -248,11 +254,14 @@ source_set("unittests") {
"discovery/mdns/dns_sd_registry_unittest.cc",
"discovery/media_sink_discovery_metrics_unittest.cc",
"event_page_request_manager_unittest.cc",
+ "logger_impl_unittest.cc",
"media_router_feature_unittest.cc",
"mojo/media_router_desktop_unittest.cc",
"mojo/media_router_mojo_impl_unittest.cc",
"mojo/media_router_mojo_metrics_unittest.cc",
"mojo/media_sink_service_status_unittest.cc",
+ "providers/cast/activity_record_test_base.cc",
+ "providers/cast/activity_record_test_base.h",
"providers/cast/cast_activity_manager_unittest.cc",
"providers/cast/cast_activity_record_unittest.cc",
"providers/cast/cast_app_availability_tracker_unittest.cc",
@@ -301,6 +310,7 @@ source_set("unittests") {
if (enable_openscreen) {
test("openscreen_unittests") {
deps = [
+ "//base/test:run_all_unittests",
"//base/test:test_support",
"//chrome/browser",
"//chrome/test:test_support",
diff --git a/chromium/chrome/browser/media/webrtc/DEPS b/chromium/chrome/browser/media/webrtc/DEPS
index e1fc475bafa..871f1948932 100644
--- a/chromium/chrome/browser/media/webrtc/DEPS
+++ b/chromium/chrome/browser/media/webrtc/DEPS
@@ -6,7 +6,6 @@ include_rules = [
]
specific_include_rules = {
- # TODO(mash): Fix these. https://crbug.com/723880
"desktop_capture_access_handler\.cc": [
"+ash/shell.h",
],
@@ -14,11 +13,9 @@ specific_include_rules = {
"+ash/shell.h",
"+ash/wm/desks/desks_util.h",
],
- # TODO(mash): Fix. https://crbug.com/855147
"media_capture_devices_dispatcher\.cc": [
"+ash/shell.h",
],
- # TODO(mash): Remove. https://crbug.com/723880
".*_unittest\.cc": [
"+ash/test/ash_test_base.h",
]
diff --git a/chromium/chrome/browser/media/webrtc/audio_debug_recordings_handler.cc b/chromium/chrome/browser/media/webrtc/audio_debug_recordings_handler.cc
index 11113830667..32f52e3fbf9 100644
--- a/chromium/chrome/browser/media/webrtc/audio_debug_recordings_handler.cc
+++ b/chromium/chrome/browser/media/webrtc/audio_debug_recordings_handler.cc
@@ -11,7 +11,6 @@
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/strings/string_number_conversions.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "components/webrtc_logging/browser/text_log_list.h"
@@ -123,8 +122,8 @@ void AudioDebugRecordingsHandler::DoStartAudioDebugRecordings(
}
const bool is_manual_stop = false;
- base::PostDelayedTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostDelayedTask(
+ FROM_HERE,
base::BindOnce(&AudioDebugRecordingsHandler::DoStopAudioDebugRecordings,
this, host, is_manual_stop,
current_audio_debug_recordings_id_, callback,
diff --git a/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.cc b/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.cc
index 428a1eb5304..a2a152cce0e 100644
--- a/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.cc
+++ b/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.cc
@@ -4,8 +4,13 @@
#include "chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.h"
+#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
+#include "chrome/browser/permissions/permission_manager_factory.h"
+#include "chrome/browser/profiles/profile.h"
+#include "components/permissions/permission_manager.h"
#include "components/permissions/permission_request_id.h"
#include "components/permissions/permissions_client.h"
+#include "content/public/browser/browser_thread.h"
#include "third_party/blink/public/mojom/feature_policy/feature_policy_feature.mojom-shared.h"
CameraPanTiltZoomPermissionContext::CameraPanTiltZoomPermissionContext(
@@ -22,26 +27,62 @@ CameraPanTiltZoomPermissionContext::~CameraPanTiltZoomPermissionContext() {
host_content_settings_map_->RemoveObserver(this);
}
-#if defined(OS_ANDROID)
-void CameraPanTiltZoomPermissionContext::DecidePermission(
+void CameraPanTiltZoomPermissionContext::RequestPermission(
content::WebContents* web_contents,
const permissions::PermissionRequestID& id,
- const GURL& requesting_origin,
- const GURL& embedding_origin,
+ const GURL& requesting_frame_origin,
bool user_gesture,
permissions::BrowserPermissionCallback callback) {
- // User should not be prompted on Android.
- NOTREACHED();
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+
+ if (HasAvailableCameraPtzDevices()) {
+ PermissionContextBase::RequestPermission(web_contents, id,
+ requesting_frame_origin,
+ user_gesture, std::move(callback));
+ return;
+ }
+
+ // If there is no camera with PTZ capabilities, let's request a "regular"
+ // camera permission instead.
+ content::RenderFrameHost* frame = content::RenderFrameHost::FromID(
+ id.render_process_id(), id.render_frame_id());
+ permissions::PermissionManager* permission_manager =
+ PermissionManagerFactory::GetForProfile(
+ Profile::FromBrowserContext(web_contents->GetBrowserContext()));
+ permission_manager->RequestPermission(ContentSettingsType::MEDIASTREAM_CAMERA,
+ frame, requesting_frame_origin,
+ user_gesture, std::move(callback));
+}
+
+bool CameraPanTiltZoomPermissionContext::IsRestrictedToSecureOrigins() const {
+ return true;
}
-#endif
void CameraPanTiltZoomPermissionContext::OnContentSettingChanged(
const ContentSettingsPattern& primary_pattern,
const ContentSettingsPattern& secondary_pattern,
ContentSettingsType content_type,
const std::string& resource_identifier) {
- if (content_type != ContentSettingsType::MEDIASTREAM_CAMERA)
+ if (content_type != ContentSettingsType::MEDIASTREAM_CAMERA &&
+ content_type != ContentSettingsType::CAMERA_PAN_TILT_ZOOM) {
+ return;
+ }
+
+ // Skip if the camera permission is currently being updated to match camera
+ // PTZ permission as OnContentSettingChanged would have been called again
+ // causing a reentrancy issue.
+ if (updating_mediastream_camera_permission_) {
+ updating_mediastream_camera_permission_ = false;
return;
+ }
+
+ // Skip if the camera PTZ permission is currently being reset when camera
+ // permission got blocked or reset as OnContentSettingChanged would have been
+ // called again causing a reentrancy issue.
+ if (updating_camera_ptz_permission_) {
+ updating_camera_ptz_permission_ = false;
+ return;
+ }
// TODO(crbug.com/1078272): We should not need to deduce the url from the
// primary pattern here. Modify the infrastructure to facilitate this
@@ -53,6 +94,18 @@ void CameraPanTiltZoomPermissionContext::OnContentSettingChanged(
ContentSetting camera_ptz_setting =
host_content_settings_map_->GetContentSetting(
url, url, content_settings_type(), resource_identifier);
+
+ if (content_type == ContentSettingsType::CAMERA_PAN_TILT_ZOOM) {
+ // Automatically update camera permission to camera PTZ permission as any
+ // change to camera PTZ should be reflected to camera.
+ updating_mediastream_camera_permission_ = true;
+ host_content_settings_map_->SetContentSettingCustomScope(
+ primary_pattern, secondary_pattern,
+ ContentSettingsType::MEDIASTREAM_CAMERA, resource_identifier,
+ camera_ptz_setting);
+ return;
+ }
+
// Don't reset camera PTZ permission if it is already blocked or in a
// "default" state.
if (camera_ptz_setting == CONTENT_SETTING_BLOCK ||
@@ -67,6 +120,7 @@ void CameraPanTiltZoomPermissionContext::OnContentSettingChanged(
mediastream_camera_setting == CONTENT_SETTING_ASK) {
// Automatically reset camera PTZ permission if camera permission
// gets blocked or reset.
+ updating_camera_ptz_permission_ = true;
host_content_settings_map_->SetContentSettingCustomScope(
primary_pattern, secondary_pattern,
ContentSettingsType::CAMERA_PAN_TILT_ZOOM, resource_identifier,
@@ -74,6 +128,16 @@ void CameraPanTiltZoomPermissionContext::OnContentSettingChanged(
}
}
-bool CameraPanTiltZoomPermissionContext::IsRestrictedToSecureOrigins() const {
- return true;
+bool CameraPanTiltZoomPermissionContext::HasAvailableCameraPtzDevices() const {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+
+ const std::vector<blink::MediaStreamDevice> devices =
+ MediaCaptureDevicesDispatcher::GetInstance()->GetVideoCaptureDevices();
+ for (const blink::MediaStreamDevice& device : devices) {
+ if (device.pan_tilt_zoom_supported.has_value() &&
+ device.pan_tilt_zoom_supported.value()) {
+ return true;
+ }
+ }
+ return false;
}
diff --git a/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.h b/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.h
index 71265b64b7a..14d4794f130 100644
--- a/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.h
+++ b/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.h
@@ -6,7 +6,6 @@
#define CHROME_BROWSER_MEDIA_WEBRTC_CAMERA_PAN_TILT_ZOOM_PERMISSION_CONTEXT_H_
#include "base/macros.h"
-#include "build/build_config.h"
#include "components/content_settings/core/browser/content_settings_observer.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/permissions/permission_context_base.h"
@@ -29,15 +28,12 @@ class CameraPanTiltZoomPermissionContext
private:
// PermissionContextBase
-#if defined(OS_ANDROID)
- void DecidePermission(
+ void RequestPermission(
content::WebContents* web_contents,
const permissions::PermissionRequestID& id,
- const GURL& requesting_origin,
- const GURL& embedding_origin,
+ const GURL& requesting_frame_origin,
bool user_gesture,
permissions::BrowserPermissionCallback callback) override;
-#endif
bool IsRestrictedToSecureOrigins() const override;
// content_settings::Observer
@@ -46,7 +42,14 @@ class CameraPanTiltZoomPermissionContext
ContentSettingsType content_type,
const std::string& resource_identifier) override;
+ // Returns true if at least one video capture device has PTZ capabilities.
+ // Otherwise returns false.
+ bool HasAvailableCameraPtzDevices() const;
+
HostContentSettingsMap* host_content_settings_map_;
+
+ bool updating_camera_ptz_permission_ = false;
+ bool updating_mediastream_camera_permission_ = false;
};
#endif // CHROME_BROWSER_MEDIA_WEBRTC_CAMERA_PAN_TILT_ZOOM_PERMISSION_CONTEXT_H_
diff --git a/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context_unittest.cc b/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context_unittest.cc
index 08a1421d1df..52375853fc6 100644
--- a/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context_unittest.cc
+++ b/chromium/chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context_unittest.cc
@@ -12,35 +12,23 @@
namespace {
-struct ContentSettingTestParams {
- const ContentSetting initial_camera_pan_tilt_zoom;
- const ContentSetting mediastream_camera;
- const ContentSetting expected_camera_pan_tilt_zoom;
-} kTestParams[] = {
- {CONTENT_SETTING_ALLOW, CONTENT_SETTING_BLOCK,
- CONTENT_SETTING_ASK}, // Granted permission is reset if camera is
- // blocked.
- {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK,
- CONTENT_SETTING_ASK}, // Granted permission is reset if camera is
- // reset.
- {CONTENT_SETTING_BLOCK, CONTENT_SETTING_ALLOW,
- CONTENT_SETTING_BLOCK}, // Blocked permission is not reset if camera
- // is granted.
- {CONTENT_SETTING_BLOCK, CONTENT_SETTING_BLOCK,
- CONTENT_SETTING_BLOCK}, // Blocked permission is not reset if camera
- // is blocked.
+struct TestConfig {
+ const ContentSetting first; // first content setting to be set
+ const ContentSetting second; // second content setting to be set
+ const ContentSetting result; // expected resulting content setting
};
} // namespace
-// Waits until a camera change is observed in content settings.
-class CameraContentSettingsChangeWaiter : public content_settings::Observer {
+// Waits until a change is observed for a specific content setting type.
+class ContentSettingsChangeWaiter : public content_settings::Observer {
public:
- explicit CameraContentSettingsChangeWaiter(Profile* profile)
- : profile_(profile) {
+ explicit ContentSettingsChangeWaiter(Profile* profile,
+ ContentSettingsType content_type)
+ : profile_(profile), content_type_(content_type) {
HostContentSettingsMapFactory::GetForProfile(profile)->AddObserver(this);
}
- ~CameraContentSettingsChangeWaiter() override {
+ ~ContentSettingsChangeWaiter() override {
HostContentSettingsMapFactory::GetForProfile(profile_)->RemoveObserver(
this);
}
@@ -50,7 +38,7 @@ class CameraContentSettingsChangeWaiter : public content_settings::Observer {
const ContentSettingsPattern& secondary_pattern,
ContentSettingsType content_type,
const std::string& resource_identifier) override {
- if (content_type == ContentSettingsType::MEDIASTREAM_CAMERA)
+ if (content_type == content_type_)
Proceed();
}
@@ -60,14 +48,15 @@ class CameraContentSettingsChangeWaiter : public content_settings::Observer {
void Proceed() { run_loop_.Quit(); }
Profile* profile_;
+ ContentSettingsType content_type_;
base::RunLoop run_loop_;
- DISALLOW_COPY_AND_ASSIGN(CameraContentSettingsChangeWaiter);
+ DISALLOW_COPY_AND_ASSIGN(ContentSettingsChangeWaiter);
};
class CameraPanTiltZoomPermissionContextTests
: public ChromeRenderViewHostTestHarness,
- public testing::WithParamInterface<ContentSettingTestParams> {
+ public testing::WithParamInterface<TestConfig> {
public:
CameraPanTiltZoomPermissionContextTests() = default;
@@ -91,21 +80,113 @@ class CameraPanTiltZoomPermissionContextTests
DISALLOW_COPY_AND_ASSIGN(CameraPanTiltZoomPermissionContextTests);
};
-TEST_P(CameraPanTiltZoomPermissionContextTests,
- TestResetPermissionOnCameraChange) {
+class CameraContentSettingTests
+ : public CameraPanTiltZoomPermissionContextTests {
+ public:
+ CameraContentSettingTests() = default;
+};
+
+TEST_P(CameraContentSettingTests, TestResetPermissionOnCameraChange) {
CameraPanTiltZoomPermissionContext permission_context(profile());
- CameraContentSettingsChangeWaiter waiter(profile());
+ ContentSettingsChangeWaiter waiter(profile(),
+ ContentSettingsType::MEDIASTREAM_CAMERA);
SetContentSetting(ContentSettingsType::CAMERA_PAN_TILT_ZOOM,
- GetParam().initial_camera_pan_tilt_zoom);
- SetContentSetting(ContentSettingsType::MEDIASTREAM_CAMERA,
- GetParam().mediastream_camera);
+ GetParam().first);
+ SetContentSetting(ContentSettingsType::MEDIASTREAM_CAMERA, GetParam().second);
waiter.Wait();
- EXPECT_EQ(GetParam().expected_camera_pan_tilt_zoom,
+ EXPECT_EQ(GetParam().result,
GetContentSetting(ContentSettingsType::CAMERA_PAN_TILT_ZOOM));
}
-INSTANTIATE_TEST_SUITE_P(ResetPermissionOnCameraChange,
- CameraPanTiltZoomPermissionContextTests,
- testing::ValuesIn(kTestParams));
+INSTANTIATE_TEST_SUITE_P(
+ ResetPermissionOnCameraChange,
+ CameraContentSettingTests,
+ testing::Values(
+ // Granted camera PTZ permission is reset if camera is blocked.
+ TestConfig{CONTENT_SETTING_ALLOW, CONTENT_SETTING_BLOCK,
+ CONTENT_SETTING_ASK},
+ // Granted camera PTZ permission is reset if camera is reset.
+ TestConfig{CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK,
+ CONTENT_SETTING_ASK},
+ // Blocked camera PTZ permission is not reset if camera is granted.
+ TestConfig{CONTENT_SETTING_BLOCK, CONTENT_SETTING_ALLOW,
+ CONTENT_SETTING_BLOCK},
+ // Blocked camera PTZ permission is not reset if camera is blocked.
+ TestConfig{CONTENT_SETTING_BLOCK, CONTENT_SETTING_BLOCK,
+ CONTENT_SETTING_BLOCK}));
+
+class CameraPanTiltZoomContentSettingTests
+ : public CameraPanTiltZoomPermissionContextTests {
+ public:
+ CameraPanTiltZoomContentSettingTests() = default;
+};
+
+TEST_P(CameraPanTiltZoomContentSettingTests,
+ TestCameraPermissionOnCameraPanTiltZoomChange) {
+ CameraPanTiltZoomPermissionContext permission_context(profile());
+ ContentSettingsChangeWaiter waiter(profile(),
+ ContentSettingsType::CAMERA_PAN_TILT_ZOOM);
+
+ SetContentSetting(ContentSettingsType::MEDIASTREAM_CAMERA, GetParam().first);
+ SetContentSetting(ContentSettingsType::CAMERA_PAN_TILT_ZOOM,
+ GetParam().second);
+
+ waiter.Wait();
+ EXPECT_EQ(GetParam().result,
+ GetContentSetting(ContentSettingsType::MEDIASTREAM_CAMERA));
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ CameraPermissionOnCameraPanTiltZoomChange,
+ CameraPanTiltZoomContentSettingTests,
+ testing::Values(
+ // Asked camera permission is blocked if camera PTZ is blocked.
+ TestConfig{CONTENT_SETTING_ASK, CONTENT_SETTING_BLOCK,
+ CONTENT_SETTING_BLOCK},
+ // Asked camera permission is granted if camera PTZ is granted.
+ TestConfig{CONTENT_SETTING_ASK, CONTENT_SETTING_ALLOW,
+ CONTENT_SETTING_ALLOW},
+ // Asked camera permission is unchanged if camera PTZ is reset.
+ TestConfig{CONTENT_SETTING_ASK, CONTENT_SETTING_DEFAULT,
+ CONTENT_SETTING_ASK},
+ // Asked camera permission is unchanged if camera PTZ is ask.
+ TestConfig{CONTENT_SETTING_ASK, CONTENT_SETTING_ASK,
+ CONTENT_SETTING_ASK},
+ // Allowed camera permission is blocked if camera PTZ is blocked.
+ TestConfig{CONTENT_SETTING_ALLOW, CONTENT_SETTING_BLOCK,
+ CONTENT_SETTING_BLOCK},
+ // Allowed camera permission is unchanged if camera PTZ is granted.
+ TestConfig{CONTENT_SETTING_ALLOW, CONTENT_SETTING_ALLOW,
+ CONTENT_SETTING_ALLOW},
+ // Allowed camera permission is ask if camera PTZ is reset.
+ TestConfig{CONTENT_SETTING_ALLOW, CONTENT_SETTING_DEFAULT,
+ CONTENT_SETTING_ASK},
+ // Allowed camera permission is reset if camera PTZ is ask.
+ TestConfig{CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK,
+ CONTENT_SETTING_ASK},
+ // Blocked camera permission is unchanged if camera PTZ is blocked.
+ TestConfig{CONTENT_SETTING_BLOCK, CONTENT_SETTING_BLOCK,
+ CONTENT_SETTING_BLOCK},
+ // Blocked camera permission is allowed if camera PTZ is granted.
+ TestConfig{CONTENT_SETTING_BLOCK, CONTENT_SETTING_ALLOW,
+ CONTENT_SETTING_ALLOW},
+ // Blocked camera permission is ask if camera PTZ is reset.
+ TestConfig{CONTENT_SETTING_BLOCK, CONTENT_SETTING_DEFAULT,
+ CONTENT_SETTING_ASK},
+ // Blocked camera permission is reset if camera PTZ is ask.
+ TestConfig{CONTENT_SETTING_BLOCK, CONTENT_SETTING_ASK,
+ CONTENT_SETTING_ASK},
+ // Default camera permission is blocked if camera PTZ is blocked.
+ TestConfig{CONTENT_SETTING_DEFAULT, CONTENT_SETTING_BLOCK,
+ CONTENT_SETTING_BLOCK},
+ // Default camera permission is allowed if camera PTZ is granted.
+ TestConfig{CONTENT_SETTING_DEFAULT, CONTENT_SETTING_ALLOW,
+ CONTENT_SETTING_ALLOW},
+ // Default camera permission is unchanged if camera PTZ is reset.
+ TestConfig{CONTENT_SETTING_DEFAULT, CONTENT_SETTING_DEFAULT,
+ CONTENT_SETTING_ASK},
+ // Default camera permission is ask if camera PTZ is ask.
+ TestConfig{CONTENT_SETTING_DEFAULT, CONTENT_SETTING_ASK,
+ CONTENT_SETTING_ASK}));
diff --git a/chromium/chrome/browser/media/webrtc/desktop_capture_access_handler.cc b/chromium/chrome/browser/media/webrtc/desktop_capture_access_handler.cc
index 2d9ab99f816..e3f7e784f03 100644
--- a/chromium/chrome/browser/media/webrtc/desktop_capture_access_handler.cc
+++ b/chromium/chrome/browser/media/webrtc/desktop_capture_access_handler.cc
@@ -296,6 +296,7 @@ void DesktopCaptureAccessHandler::HandleRequest(
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback,
const extensions::Extension* extension) {
+ DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
blink::MediaStreamDevices devices;
std::unique_ptr<content::MediaStreamUI> ui;
@@ -379,6 +380,17 @@ void DesktopCaptureAccessHandler::HandleRequest(
}
#endif
+ if (media_id.type == content::DesktopMediaID::TYPE_WEB_CONTENTS &&
+ !content::WebContents::FromRenderFrameHost(
+ content::RenderFrameHost::FromID(
+ media_id.web_contents_id.render_process_id,
+ media_id.web_contents_id.main_render_frame_id))) {
+ std::move(callback).Run(
+ devices, blink::mojom::MediaStreamRequestResult::TAB_CAPTURE_FAILURE,
+ std::move(ui));
+ return;
+ }
+
bool loopback_audio_supported = false;
#if defined(USE_CRAS) || defined(OS_WIN)
// Currently loopback audio capture is supported only on Windows and ChromeOS.
diff --git a/chromium/chrome/browser/media/webrtc/desktop_media_list_base.cc b/chromium/chrome/browser/media/webrtc/desktop_media_list_base.cc
index ba64a40697c..147d5be9f7f 100644
--- a/chromium/chrome/browser/media/webrtc/desktop_media_list_base.cc
+++ b/chromium/chrome/browser/media/webrtc/desktop_media_list_base.cc
@@ -8,13 +8,11 @@
#include <utility>
#include "base/bind.h"
-#include "base/task/post_task.h"
#include "chrome/browser/media/webrtc/desktop_media_list.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "ui/gfx/image/image.h"
-using content::BrowserThread;
using content::DesktopMediaID;
DesktopMediaListBase::DesktopMediaListBase(base::TimeDelta update_period)
@@ -179,8 +177,9 @@ void DesktopMediaListBase::ScheduleNextRefresh() {
DCHECK(!refresh_callback_);
refresh_callback_ = base::BindOnce(&DesktopMediaListBase::ScheduleNextRefresh,
weak_factory_.GetWeakPtr());
- base::PostDelayedTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&DesktopMediaListBase::Refresh,
- weak_factory_.GetWeakPtr(), true),
- update_period_);
+ content::GetUIThreadTaskRunner({})->PostDelayedTask(
+ FROM_HERE,
+ base::BindOnce(&DesktopMediaListBase::Refresh, weak_factory_.GetWeakPtr(),
+ true),
+ update_period_);
}
diff --git a/chromium/chrome/browser/media/webrtc/desktop_media_picker_factory_impl.cc b/chromium/chrome/browser/media/webrtc/desktop_media_picker_factory_impl.cc
index fa7d872810a..63ad845f1cc 100644
--- a/chromium/chrome/browser/media/webrtc/desktop_media_picker_factory_impl.cc
+++ b/chromium/chrome/browser/media/webrtc/desktop_media_picker_factory_impl.cc
@@ -52,9 +52,16 @@ DesktopMediaPickerFactoryImpl::CreateMediaList(
screen_list = std::make_unique<DesktopMediaListAsh>(
content::DesktopMediaID::TYPE_SCREEN);
#else // !defined(OS_CHROMEOS)
+ // If screen capture is not supported on the platform, then we should
+ // not attempt to create an instance of NativeDesktopMediaList. Doing so
+ // will hit a DCHECK.
+ std::unique_ptr<webrtc::DesktopCapturer> capturer =
+ content::desktop_capture::CreateScreenCapturer();
+ if (!capturer)
+ continue;
+
screen_list = std::make_unique<NativeDesktopMediaList>(
- content::DesktopMediaID::TYPE_SCREEN,
- content::desktop_capture::CreateScreenCapturer());
+ content::DesktopMediaID::TYPE_SCREEN, std::move(capturer));
#endif // !defined(OS_CHROMEOS)
have_screen_list = true;
source_lists.push_back(std::move(screen_list));
@@ -68,9 +75,15 @@ DesktopMediaPickerFactoryImpl::CreateMediaList(
window_list = std::make_unique<DesktopMediaListAsh>(
content::DesktopMediaID::TYPE_WINDOW);
#else // !defined(OS_CHROMEOS)
+ // If window capture is not supported on the platform, then we should
+ // not attempt to create an instance of NativeDesktopMediaList. Doing so
+ // will hit a DCHECK.
+ std::unique_ptr<webrtc::DesktopCapturer> capturer =
+ content::desktop_capture::CreateWindowCapturer();
+ if (!capturer)
+ continue;
window_list = std::make_unique<NativeDesktopMediaList>(
- content::DesktopMediaID::TYPE_WINDOW,
- content::desktop_capture::CreateWindowCapturer());
+ content::DesktopMediaID::TYPE_WINDOW, std::move(capturer));
#endif // !defined(OS_CHROMEOS)
have_window_list = true;
source_lists.push_back(std::move(window_list));
diff --git a/chromium/chrome/browser/media/webrtc/display_media_access_handler.cc b/chromium/chrome/browser/media/webrtc/display_media_access_handler.cc
index 4ca36f534dc..3c002920c1d 100644
--- a/chromium/chrome/browser/media/webrtc/display_media_access_handler.cc
+++ b/chromium/chrome/browser/media/webrtc/display_media_access_handler.cc
@@ -17,6 +17,7 @@
#include "chrome/browser/media/webrtc/native_desktop_media_list.h"
#include "chrome/browser/media/webrtc/tab_desktop_media_list.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/safe_browsing/user_interaction_observer.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/url_formatter/elide_url.h"
@@ -100,6 +101,21 @@ void DisplayMediaAccessHandler::HandleRequest(
return;
}
+ // SafeBrowsing Delayed Warnings experiment can delay some SafeBrowsing
+ // warnings until user interaction. If the current page has a delayed warning,
+ // it'll have a user interaction observer attached. Show the warning
+ // immediately in that case.
+ safe_browsing::SafeBrowsingUserInteractionObserver* observer =
+ safe_browsing::SafeBrowsingUserInteractionObserver::FromWebContents(
+ web_contents);
+ if (observer) {
+ std::move(callback).Run(
+ blink::MediaStreamDevices(),
+ blink::mojom::MediaStreamRequestResult::PERMISSION_DENIED, nullptr);
+ observer->OnDesktopCaptureRequest();
+ return;
+ }
+
#if defined(OS_MACOSX)
// Do not allow picker UI to be shown on a page that isn't in the foreground
// in Mac, because the UI implementation in Mac pops a window over any content
@@ -225,6 +241,14 @@ void DisplayMediaAccessHandler::OnPickerDialogResults(
blink::mojom::MediaStreamRequestResult::SYSTEM_PERMISSION_DENIED;
}
#endif
+ if (media_id.type == content::DesktopMediaID::TYPE_WEB_CONTENTS &&
+ !content::WebContents::FromRenderFrameHost(
+ content::RenderFrameHost::FromID(
+ media_id.web_contents_id.render_process_id,
+ media_id.web_contents_id.main_render_frame_id))) {
+ request_result =
+ blink::mojom::MediaStreamRequestResult::TAB_CAPTURE_FAILURE;
+ }
if (request_result == blink::mojom::MediaStreamRequestResult::OK) {
const auto& visible_url = url_formatter::FormatUrlForSecurityDisplay(
web_contents->GetLastCommittedURL(),
diff --git a/chromium/chrome/browser/media/webrtc/fake_desktop_media_list.cc b/chromium/chrome/browser/media/webrtc/fake_desktop_media_list.cc
index ee71126dc3e..3bc98e78b45 100644
--- a/chromium/chrome/browser/media/webrtc/fake_desktop_media_list.cc
+++ b/chromium/chrome/browser/media/webrtc/fake_desktop_media_list.cc
@@ -14,7 +14,7 @@
using content::DesktopMediaID;
FakeDesktopMediaList::FakeDesktopMediaList(DesktopMediaID::Type type)
- : observer_(NULL), type_(type) {}
+ : observer_(nullptr), type_(type) {}
FakeDesktopMediaList::~FakeDesktopMediaList() {}
void FakeDesktopMediaList::AddSource(int id) {
diff --git a/chromium/chrome/browser/media/webrtc/media_capture_devices_dispatcher.cc b/chromium/chrome/browser/media/webrtc/media_capture_devices_dispatcher.cc
index 00e2c25d5ea..1ff00413044 100644
--- a/chromium/chrome/browser/media/webrtc/media_capture_devices_dispatcher.cc
+++ b/chromium/chrome/browser/media/webrtc/media_capture_devices_dispatcher.cc
@@ -14,7 +14,6 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "build/build_config.h"
#include "chrome/browser/media/media_access_handler.h"
#include "chrome/browser/media/webrtc/media_stream_capture_indicator.h"
@@ -303,8 +302,8 @@ MediaCaptureDevicesDispatcher::GetMediaStreamCaptureIndicator() {
void MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&MediaCaptureDevicesDispatcher::NotifyAudioDevicesChangedOnUIThread,
base::Unretained(this)));
@@ -312,8 +311,8 @@ void MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged() {
void MediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&MediaCaptureDevicesDispatcher::NotifyVideoDevicesChangedOnUIThread,
base::Unretained(this)));
@@ -327,8 +326,8 @@ void MediaCaptureDevicesDispatcher::OnMediaRequestStateChanged(
blink::mojom::MediaStreamType stream_type,
content::MediaRequestState state) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&MediaCaptureDevicesDispatcher::UpdateMediaRequestStateOnUIThread,
base::Unretained(this), render_process_id, render_frame_id,
@@ -348,8 +347,8 @@ void MediaCaptureDevicesDispatcher::OnCreatingAudioStream(int render_process_id,
}
DCHECK_CURRENTLY_ON(BrowserThread::IO);
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&MediaCaptureDevicesDispatcher::OnCreatingAudioStreamOnUIThread,
base::Unretained(this), render_process_id, render_frame_id));
@@ -445,8 +444,8 @@ void MediaCaptureDevicesDispatcher::OnSetCapturingLinkSecured(
if (!blink::IsVideoScreenCaptureMediaType(stream_type))
return;
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&MediaCaptureDevicesDispatcher::UpdateVideoScreenCaptureStatus,
base::Unretained(this), render_process_id, render_frame_id,
diff --git a/chromium/chrome/browser/media/webrtc/media_capture_devices_dispatcher_unittest.cc b/chromium/chrome/browser/media/webrtc/media_capture_devices_dispatcher_unittest.cc
index 30d6696e3ba..62ac808bd29 100644
--- a/chromium/chrome/browser/media/webrtc/media_capture_devices_dispatcher_unittest.cc
+++ b/chromium/chrome/browser/media/webrtc/media_capture_devices_dispatcher_unittest.cc
@@ -6,6 +6,7 @@
#include <memory>
+#include "build/build_config.h"
#include "chrome/browser/media/media_access_handler.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -73,7 +74,8 @@ class MediaCaptureDevicesDispatcherTest
MediaCaptureDevicesDispatcher* dispatcher_;
};
-TEST_F(MediaCaptureDevicesDispatcherTest, LoopsAllMediaAccessHandlers) {
+TEST_F(MediaCaptureDevicesDispatcherTest,
+ DISABLED_LoopsAllMediaAccessHandlers) {
media_access_handlers().clear();
// Add two handlers.
diff --git a/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator.cc b/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator.cc
index aefe2a0905e..ce93d308a3d 100644
--- a/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator.cc
+++ b/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator.cc
@@ -54,7 +54,7 @@ const extensions::Extension* GetExtension(WebContents* web_contents) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!web_contents)
- return NULL;
+ return nullptr;
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(web_contents->GetBrowserContext());
@@ -338,45 +338,60 @@ void MediaStreamCaptureIndicator::ExecuteCommand(int command_id,
web_contents->GetDelegate()->ActivateContents(web_contents);
}
+bool MediaStreamCaptureIndicator::CheckUsage(
+ content::WebContents* web_contents,
+ const WebContentsDeviceUsagePredicate& pred) const {
+ auto it = usage_map_.find(web_contents);
+ if (it != usage_map_.end() && pred.Run(it->second.get()))
+ return true;
+
+ for (auto* inner_contents : web_contents->GetInnerWebContents()) {
+ if (CheckUsage(inner_contents, pred))
+ return true;
+ }
+
+ return false;
+}
+
bool MediaStreamCaptureIndicator::IsCapturingUserMedia(
content::WebContents* web_contents) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- auto it = usage_map_.find(web_contents);
- return it != usage_map_.end() &&
- (it->second->IsCapturingAudio() || it->second->IsCapturingVideo());
+ return CheckUsage(
+ web_contents,
+ base::BindRepeating([](const WebContentsDeviceUsage* usage) {
+ return usage->IsCapturingAudio() || usage->IsCapturingVideo();
+ }));
}
bool MediaStreamCaptureIndicator::IsCapturingVideo(
content::WebContents* web_contents) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- auto it = usage_map_.find(web_contents);
- return it != usage_map_.end() && it->second->IsCapturingVideo();
+ return CheckUsage(
+ web_contents,
+ base::BindRepeating(&WebContentsDeviceUsage::IsCapturingVideo));
}
bool MediaStreamCaptureIndicator::IsCapturingAudio(
content::WebContents* web_contents) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- auto it = usage_map_.find(web_contents);
- return it != usage_map_.end() && it->second->IsCapturingAudio();
+ return CheckUsage(
+ web_contents,
+ base::BindRepeating(&WebContentsDeviceUsage::IsCapturingAudio));
}
bool MediaStreamCaptureIndicator::IsBeingMirrored(
content::WebContents* web_contents) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- auto it = usage_map_.find(web_contents);
- return it != usage_map_.end() && it->second->IsMirroring();
+ return CheckUsage(web_contents,
+ base::BindRepeating(&WebContentsDeviceUsage::IsMirroring));
}
bool MediaStreamCaptureIndicator::IsCapturingDesktop(
content::WebContents* web_contents) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
-
- auto it = usage_map_.find(web_contents);
- return it != usage_map_.end() && it->second->IsCapturingDesktop();
+ return CheckUsage(
+ web_contents,
+ base::BindRepeating(&WebContentsDeviceUsage::IsCapturingDesktop));
}
void MediaStreamCaptureIndicator::NotifyStopped(
@@ -386,6 +401,9 @@ void MediaStreamCaptureIndicator::NotifyStopped(
auto it = usage_map_.find(web_contents);
DCHECK(it != usage_map_.end());
it->second->NotifyStopped();
+
+ for (auto* inner_contents : web_contents->GetInnerWebContents())
+ NotifyStopped(inner_contents);
}
void MediaStreamCaptureIndicator::UnregisterWebContents(
@@ -430,9 +448,9 @@ void MediaStreamCaptureIndicator::MaybeDestroyStatusTrayIcon() {
return;
StatusTray* status_tray = g_browser_process->status_tray();
- if (status_tray != NULL) {
+ if (status_tray != nullptr) {
status_tray->RemoveStatusIcon(status_icon_);
- status_icon_ = NULL;
+ status_icon_ = nullptr;
}
}
diff --git a/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator.h b/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator.h
index 86c2011caa4..323e065fb6d 100644
--- a/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator.h
+++ b/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator.h
@@ -135,6 +135,13 @@ class MediaStreamCaptureIndicator
gfx::ImageSkia* image,
base::string16* tool_tip);
+ // Checks if |web_contents| or any portal WebContents in its tree is using
+ // a device for capture. The type of capture is specified using |pred|.
+ using WebContentsDeviceUsagePredicate =
+ base::RepeatingCallback<bool(const WebContentsDeviceUsage*)>;
+ bool CheckUsage(content::WebContents* web_contents,
+ const WebContentsDeviceUsagePredicate& pred) const;
+
// Reference to our status icon - owned by the StatusTray. If null,
// the platform doesn't support status icons.
StatusIcon* status_icon_ = nullptr;
diff --git a/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator_unittest.cc b/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator_unittest.cc
index 1676ddeb1ea..a7a23f52c76 100644
--- a/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator_unittest.cc
+++ b/chromium/chrome/browser/media/webrtc/media_stream_capture_indicator_unittest.cc
@@ -7,6 +7,7 @@
#include "base/bind.h"
#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
+#include "content/public/test/web_contents_tester.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
@@ -74,15 +75,17 @@ class MediaStreamCaptureIndicatorTest : public ChromeRenderViewHostTestHarness {
void SetUp() override {
ChromeRenderViewHostTestHarness::SetUp();
+ content::WebContentsTester::For(web_contents())
+ ->NavigateAndCommit(GURL("https://www.example.com/"));
indicator_ = MediaCaptureDevicesDispatcher::GetInstance()
->GetMediaStreamCaptureIndicator();
observer_ = std::make_unique<MockObserver>();
indicator_->AddObserver(observer());
- contents_ = CreateTestWebContents();
+ portal_token_ = content::WebContentsTester::For(web_contents())
+ ->CreatePortal(CreateTestWebContents());
}
void TearDown() override {
- contents_.reset();
indicator_->RemoveObserver(observer());
observer_.reset();
indicator_.reset();
@@ -90,7 +93,10 @@ class MediaStreamCaptureIndicatorTest : public ChromeRenderViewHostTestHarness {
}
MediaStreamCaptureIndicator* indicator() { return indicator_.get(); }
- content::WebContents* contents() { return contents_.get(); }
+ content::WebContents* portal_contents() {
+ return content::WebContentsTester::For(web_contents())
+ ->GetPortalContents(portal_token_);
+ }
MockObserver* observer() { return observer_.get(); }
// Test a MediaStreamCaptureIndicator accessor and ensure that the
@@ -98,11 +104,15 @@ class MediaStreamCaptureIndicatorTest : public ChromeRenderViewHostTestHarness {
void TestObserverMethod(blink::mojom::MediaStreamType stream_type,
MockObserverSetExpectationsMethod observer_method,
AccessorMethod accessor_method);
+ void TestObserverMethodWithPortal(
+ blink::mojom::MediaStreamType stream_type,
+ MockObserverSetExpectationsMethod observer_method,
+ AccessorMethod accessor_method);
private:
std::unique_ptr<MockObserver> observer_;
- std::unique_ptr<content::WebContents> contents_;
scoped_refptr<MediaStreamCaptureIndicator> indicator_;
+ base::UnguessableToken portal_token_;
};
} // namespace
@@ -116,22 +126,50 @@ void MediaStreamCaptureIndicatorTest::TestObserverMethod(
blink::MediaStreamDevice(stream_type, "fake_device", "fake_device")};
// By default all accessors should return false as there's no stream device.
- EXPECT_FALSE((indicator()->*accessor_method)(contents()));
+ EXPECT_FALSE((indicator()->*accessor_method)(web_contents()));
+ std::unique_ptr<content::MediaStreamUI> ui =
+ indicator()->RegisterMediaStream(web_contents(), devices);
+
+ // Make sure that the observer gets called and that the corresponding accessor
+ // gets called when |OnStarted| is called.
+ (observer()->*observer_set_expectations_method)(web_contents(), true);
+ ui->OnStarted(base::OnceClosure(), content::MediaStreamUI::SourceCallback());
+ EXPECT_TRUE((indicator()->*accessor_method)(web_contents()));
+ ::testing::Mock::VerifyAndClear(observer());
+
+ // Removing the stream device should cause the observer to be notified that
+ // the observed property is now set to false.
+ (observer()->*observer_set_expectations_method)(web_contents(), false);
+ ui.reset();
+ EXPECT_FALSE((indicator()->*accessor_method)(web_contents()));
+ ::testing::Mock::VerifyAndClear(observer());
+}
+
+void MediaStreamCaptureIndicatorTest::TestObserverMethodWithPortal(
+ blink::mojom::MediaStreamType stream_type,
+ MockObserverSetExpectationsMethod observer_set_expectations_method,
+ AccessorMethod accessor_method) {
+ // Create the fake stream device.
+ blink::MediaStreamDevices devices{
+ blink::MediaStreamDevice(stream_type, "fake_device", "fake_device")};
+
+ // By default all accessors should return false as there's no stream device.
+ EXPECT_FALSE((indicator()->*accessor_method)(web_contents()));
std::unique_ptr<content::MediaStreamUI> ui =
- indicator()->RegisterMediaStream(contents(), devices);
+ indicator()->RegisterMediaStream(portal_contents(), devices);
// Make sure that the observer gets called and that the corresponding accessor
// gets called when |OnStarted| is called.
- (observer()->*observer_set_expectations_method)(contents(), true);
+ (observer()->*observer_set_expectations_method)(portal_contents(), true);
ui->OnStarted(base::OnceClosure(), content::MediaStreamUI::SourceCallback());
- EXPECT_TRUE((indicator()->*accessor_method)(contents()));
+ EXPECT_TRUE((indicator()->*accessor_method)(web_contents()));
::testing::Mock::VerifyAndClear(observer());
// Removing the stream device should cause the observer to be notified that
// the observed property is now set to false.
- (observer()->*observer_set_expectations_method)(contents(), false);
+ (observer()->*observer_set_expectations_method)(portal_contents(), false);
ui.reset();
- EXPECT_FALSE((indicator()->*accessor_method)(contents()));
+ EXPECT_FALSE((indicator()->*accessor_method)(web_contents()));
::testing::Mock::VerifyAndClear(observer());
}
@@ -141,20 +179,48 @@ TEST_F(MediaStreamCaptureIndicatorTest, IsCapturingVideo) {
&MediaStreamCaptureIndicator::IsCapturingVideo);
}
+TEST_F(MediaStreamCaptureIndicatorTest, IsCapturingVideo_Portal) {
+ TestObserverMethodWithPortal(
+ blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE,
+ &MockObserver::SetOnIsCapturingVideoChangedExpectation,
+ &MediaStreamCaptureIndicator::IsCapturingVideo);
+}
+
TEST_F(MediaStreamCaptureIndicatorTest, IsCapturingAudio) {
TestObserverMethod(blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE,
&MockObserver::SetOnIsCapturingAudioChangedExpectation,
&MediaStreamCaptureIndicator::IsCapturingAudio);
}
+TEST_F(MediaStreamCaptureIndicatorTest, IsCapturingAudio_Portal) {
+ TestObserverMethodWithPortal(
+ blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE,
+ &MockObserver::SetOnIsCapturingAudioChangedExpectation,
+ &MediaStreamCaptureIndicator::IsCapturingAudio);
+}
+
TEST_F(MediaStreamCaptureIndicatorTest, IsBeingMirrored) {
TestObserverMethod(blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE,
&MockObserver::SetOnIsBeingMirroredChangedExpectation,
&MediaStreamCaptureIndicator::IsBeingMirrored);
}
+TEST_F(MediaStreamCaptureIndicatorTest, IsBeingMirrored_Portal) {
+ TestObserverMethodWithPortal(
+ blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE,
+ &MockObserver::SetOnIsBeingMirroredChangedExpectation,
+ &MediaStreamCaptureIndicator::IsBeingMirrored);
+}
+
TEST_F(MediaStreamCaptureIndicatorTest, IsCapturingDesktop) {
TestObserverMethod(blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE,
&MockObserver::SetOnIsCapturingDesktopChangedExpectation,
&MediaStreamCaptureIndicator::IsCapturingDesktop);
}
+
+TEST_F(MediaStreamCaptureIndicatorTest, IsCapturingDesktop_Portal) {
+ TestObserverMethodWithPortal(
+ blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE,
+ &MockObserver::SetOnIsCapturingDesktopChangedExpectation,
+ &MediaStreamCaptureIndicator::IsCapturingDesktop);
+}
diff --git a/chromium/chrome/browser/media/webrtc/media_stream_devices_controller_browsertest.cc b/chromium/chrome/browser/media/webrtc/media_stream_devices_controller_browsertest.cc
index 2f46debbeb0..7d975a48e8c 100644
--- a/chromium/chrome/browser/media/webrtc/media_stream_devices_controller_browsertest.cc
+++ b/chromium/chrome/browser/media/webrtc/media_stream_devices_controller_browsertest.cc
@@ -10,11 +10,13 @@
#include "base/run_loop.h"
#include "base/stl_util.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
+#include "chrome/browser/media/webrtc/camera_pan_tilt_zoom_permission_context.h"
#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
#include "chrome/browser/media/webrtc/media_stream_capture_indicator.h"
#include "chrome/browser/media/webrtc/media_stream_device_permissions.h"
#include "chrome/browser/media/webrtc/permission_bubble_media_access_handler.h"
#include "chrome/browser/media/webrtc/webrtc_browsertest_base.h"
+#include "chrome/browser/permissions/permission_manager_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
@@ -24,6 +26,7 @@
#include "components/content_settings/browser/tab_specific_content_settings.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/permissions/permission_context_base.h"
+#include "components/permissions/permission_manager.h"
#include "components/permissions/permission_request.h"
#include "components/permissions/permission_request_manager.h"
#include "components/permissions/permission_util.h"
@@ -106,9 +109,10 @@ class MediaStreamDevicesControllerTest : public WebRtcTestBase {
prefs->SetBoolean(policy_name, access == ACCESS_ALLOWED);
}
- // Set the content settings for mic/cam.
+ // Set the content settings for mic/cam/ptz.
void SetContentSettings(ContentSetting mic_setting,
- ContentSetting cam_setting) {
+ ContentSetting cam_setting,
+ ContentSetting ptz_setting) {
HostContentSettingsMap* content_settings =
HostContentSettingsMapFactory::GetForProfile(
Profile::FromBrowserContext(GetWebContents()->GetBrowserContext()));
@@ -118,6 +122,9 @@ class MediaStreamDevicesControllerTest : public WebRtcTestBase {
content_settings->SetContentSettingDefaultScope(
example_url_, GURL(), ContentSettingsType::MEDIASTREAM_CAMERA,
std::string(), cam_setting);
+ content_settings->SetContentSettingDefaultScope(
+ example_url_, GURL(), ContentSettingsType::CAMERA_PAN_TILT_ZOOM,
+ std::string(), ptz_setting);
}
// Checks whether the devices returned in OnMediaStreamResponse contains a
@@ -140,6 +147,7 @@ class MediaStreamDevicesControllerTest : public WebRtcTestBase {
content::MediaStreamRequest CreateRequestWithType(
const std::string& audio_id,
const std::string& video_id,
+ bool request_pan_tilt_zoom_permission,
blink::MediaStreamRequestType request_type) {
blink::mojom::MediaStreamType audio_type =
audio_id.empty() ? blink::mojom::MediaStreamType::NO_SERVICE
@@ -155,13 +163,15 @@ class MediaStreamDevicesControllerTest : public WebRtcTestBase {
return content::MediaStreamRequest(
render_process_id, render_frame_id, 0, example_url(), false,
request_type, audio_id, video_id, audio_type, video_type,
- /*disable_local_echo=*/false,
- /*request_pan_tilt_zoom_permission=*/false);
+ /*disable_local_echo=*/false, request_pan_tilt_zoom_permission);
}
- content::MediaStreamRequest CreateRequest(const std::string& audio_id,
- const std::string& video_id) {
+ content::MediaStreamRequest CreateRequest(
+ const std::string& audio_id,
+ const std::string& video_id,
+ bool request_pan_tilt_zoom_permission) {
return CreateRequestWithType(audio_id, video_id,
+ request_pan_tilt_zoom_permission,
blink::MEDIA_DEVICE_ACCESS);
}
@@ -173,6 +183,8 @@ class MediaStreamDevicesControllerTest : public WebRtcTestBase {
GetContentSettings()->GetMicrophoneCameraState());
}
+ virtual bool IsPanTiltZoomSupported() const { return false; }
+
permissions::MockPermissionPromptFactory* prompt_factory() {
return prompt_factory_.get();
}
@@ -219,7 +231,8 @@ class MediaStreamDevicesControllerTest : public WebRtcTestBase {
blink::MediaStreamDevices video_devices;
blink::MediaStreamDevice fake_video_device(
blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE, example_video_id_,
- "Fake Video Device");
+ "Fake Video Device", media::MEDIA_VIDEO_FACING_NONE, base::nullopt,
+ IsPanTiltZoomSupported());
video_devices.push_back(fake_video_device);
MediaCaptureDevicesDispatcher::GetInstance()->SetTestVideoCaptureDevices(
video_devices);
@@ -247,6 +260,13 @@ class MediaStreamDevicesControllerTest : public WebRtcTestBase {
permission_bubble_media_access_handler_;
};
+class MediaStreamDevicesControllerPtzTest
+ : public MediaStreamDevicesControllerTest,
+ public ::testing::WithParamInterface<bool> {
+ protected:
+ bool IsPanTiltZoomSupported() const override { return GetParam(); }
+};
+
// Request and allow microphone access.
IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest, RequestAndAllowMic) {
InitWithUrl(embedded_test_server()->GetURL("/simple.html"));
@@ -256,7 +276,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest, RequestAndAllowMic) {
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), std::string()));
+ CreateRequest(example_audio_id(), std::string(), false));
EXPECT_TRUE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_MIC));
@@ -283,7 +303,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest, RequestAndAllowCam) {
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
RequestPermissions(GetWebContents(),
- CreateRequest(std::string(), example_video_id()));
+ CreateRequest(std::string(), example_video_id(), false));
EXPECT_TRUE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_CAMERA));
@@ -310,7 +330,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest, RequestAndBlockMic) {
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), std::string()));
+ CreateRequest(example_audio_id(), std::string(), false));
EXPECT_FALSE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_MIC));
@@ -338,7 +358,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest, RequestAndBlockCam) {
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
RequestPermissions(GetWebContents(),
- CreateRequest(std::string(), example_video_id()));
+ CreateRequest(std::string(), example_video_id(), false));
EXPECT_FALSE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_CAMERA));
@@ -367,8 +387,9 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
// settings are updated.
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
- RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), example_video_id()));
+ RequestPermissions(
+ GetWebContents(),
+ CreateRequest(example_audio_id(), example_video_id(), false));
EXPECT_TRUE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_MIC));
@@ -401,8 +422,9 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
// settings are updated.
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
- RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), example_video_id()));
+ RequestPermissions(
+ GetWebContents(),
+ CreateRequest(example_audio_id(), example_video_id(), false));
EXPECT_FALSE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_MIC));
@@ -438,8 +460,9 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
// settings are updated.
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
- RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), example_video_id()));
+ RequestPermissions(
+ GetWebContents(),
+ CreateRequest(example_audio_id(), example_video_id(), false));
EXPECT_FALSE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_MIC));
@@ -475,8 +498,9 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
// settings are updated.
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
- RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), example_video_id()));
+ RequestPermissions(
+ GetWebContents(),
+ CreateRequest(example_audio_id(), example_video_id(), false));
EXPECT_FALSE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_MIC));
@@ -513,7 +537,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), std::string()));
+ CreateRequest(example_audio_id(), std::string(), false));
EXPECT_FALSE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_MIC));
EXPECT_TRUE(GetContentSettings()->IsContentBlocked(
@@ -526,7 +550,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
// Request cam and allow
SetDevicePolicy(DEVICE_TYPE_VIDEO, ACCESS_ALLOWED);
RequestPermissions(GetWebContents(),
- CreateRequest(std::string(), example_video_id()));
+ CreateRequest(std::string(), example_video_id(), false));
EXPECT_TRUE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_CAMERA));
EXPECT_FALSE(GetContentSettings()->IsContentBlocked(
@@ -558,7 +582,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
RequestPermissions(GetWebContents(),
- CreateRequest(std::string(), example_video_id()));
+ CreateRequest(std::string(), example_video_id(), false));
EXPECT_TRUE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_CAMERA));
EXPECT_FALSE(GetContentSettings()->IsContentBlocked(
@@ -591,7 +615,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), std::string()));
+ CreateRequest(example_audio_id(), std::string(), false));
EXPECT_FALSE(GetContentSettings()->IsContentAllowed(
ContentSettingsType::MEDIASTREAM_MIC));
EXPECT_TRUE(GetContentSettings()->IsContentBlocked(
@@ -626,23 +650,30 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
// Stores the ContentSettings inputs for a particular test and has functions
// which return the expected outputs for that test.
struct ContentSettingsTestData {
- // The initial value of the mic/cam content settings.
+ // The initial value of the mic/cam/ptz content settings.
ContentSetting mic;
ContentSetting cam;
+ ContentSetting ptz;
// Whether the infobar should be accepted if it's shown.
bool accept_infobar;
- // Whether the infobar should be displayed to request mic/cam for the given
- // content settings inputs.
- bool ExpectMicInfobar() const {
- return mic == CONTENT_SETTING_ASK && cam != CONTENT_SETTING_BLOCK;
+ // Whether the infobar should be displayed to request mic/cam/ptz for the
+ // given content settings inputs.
+ bool ExpectMicInfobar(bool pan_tilt_zoom_supported) const {
+ return mic == CONTENT_SETTING_ASK && cam != CONTENT_SETTING_BLOCK &&
+ (!pan_tilt_zoom_supported || ptz != CONTENT_SETTING_BLOCK);
+ }
+ bool ExpectCamInfobar(bool pan_tilt_zoom_supported) const {
+ return cam == CONTENT_SETTING_ASK && mic != CONTENT_SETTING_BLOCK &&
+ (!pan_tilt_zoom_supported || ptz != CONTENT_SETTING_BLOCK);
}
- bool ExpectCamInfobar() const {
- return cam == CONTENT_SETTING_ASK && mic != CONTENT_SETTING_BLOCK;
+ bool ExpectPtzInfobar(bool pan_tilt_zoom_supported) const {
+ return pan_tilt_zoom_supported && ptz == CONTENT_SETTING_ASK &&
+ mic != CONTENT_SETTING_BLOCK && cam != CONTENT_SETTING_BLOCK;
}
- // Whether or not the mic/cam should be allowed after clicking accept/deny for
- // the given inputs.
+ // Whether or not the mic/cam/ptz should be allowed after clicking accept/deny
+ // for the given inputs.
bool ExpectMicAllowed() const {
return mic == CONTENT_SETTING_ALLOW ||
(mic == CONTENT_SETTING_ASK && accept_infobar);
@@ -651,47 +682,97 @@ struct ContentSettingsTestData {
return cam == CONTENT_SETTING_ALLOW ||
(cam == CONTENT_SETTING_ASK && accept_infobar);
}
+ bool ExpectPtzAllowed() const {
+ return ptz == CONTENT_SETTING_ALLOW ||
+ (ptz == CONTENT_SETTING_ASK && accept_infobar);
+ }
// The expected media stream result after clicking accept/deny for the given
// inputs.
- blink::mojom::MediaStreamRequestResult ExpectedMediaStreamResult() const {
- if (ExpectMicAllowed() && ExpectCamAllowed())
+ blink::mojom::MediaStreamRequestResult ExpectedMediaStreamResult(
+ bool pan_tilt_zoom_supported) const {
+ if (ExpectMicAllowed() && ExpectCamAllowed() &&
+ (!pan_tilt_zoom_supported || ptz != CONTENT_SETTING_BLOCK)) {
return blink::mojom::MediaStreamRequestResult::OK;
+ }
return blink::mojom::MediaStreamRequestResult::PERMISSION_DENIED;
}
};
// Test all combinations of cam/mic content settings. Then tests the result of
// clicking both accept/deny on the infobar. Both cam/mic are requested.
-IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest, ContentSettings) {
+IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerPtzTest, ContentSettings) {
InitWithUrl(embedded_test_server()->GetURL("/simple.html"));
static const ContentSettingsTestData tests[] = {
// Settings that won't result in an infobar.
- {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ALLOW, false},
- {CONTENT_SETTING_ALLOW, CONTENT_SETTING_BLOCK, false},
- {CONTENT_SETTING_BLOCK, CONTENT_SETTING_ALLOW, false},
- {CONTENT_SETTING_BLOCK, CONTENT_SETTING_BLOCK, false},
- {CONTENT_SETTING_BLOCK, CONTENT_SETTING_ASK, false},
- {CONTENT_SETTING_ASK, CONTENT_SETTING_BLOCK, false},
+ {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ALLOW, CONTENT_SETTING_ALLOW,
+ false},
+ {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ALLOW, CONTENT_SETTING_BLOCK,
+ false},
+ {CONTENT_SETTING_ALLOW, CONTENT_SETTING_BLOCK, CONTENT_SETTING_ALLOW,
+ false},
+ {CONTENT_SETTING_ALLOW, CONTENT_SETTING_BLOCK, CONTENT_SETTING_BLOCK,
+ false},
+ {CONTENT_SETTING_BLOCK, CONTENT_SETTING_ALLOW, CONTENT_SETTING_ALLOW,
+ false},
+ {CONTENT_SETTING_BLOCK, CONTENT_SETTING_ALLOW, CONTENT_SETTING_BLOCK,
+ false},
+ {CONTENT_SETTING_BLOCK, CONTENT_SETTING_BLOCK, CONTENT_SETTING_ALLOW,
+ false},
+ {CONTENT_SETTING_BLOCK, CONTENT_SETTING_BLOCK, CONTENT_SETTING_BLOCK,
+ false},
+ {CONTENT_SETTING_BLOCK, CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, false},
+ {CONTENT_SETTING_ASK, CONTENT_SETTING_BLOCK, CONTENT_SETTING_ASK, false},
+ {CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, CONTENT_SETTING_BLOCK, false},
// Settings that will result in an infobar. Test both accept and deny.
- {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, false},
- {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, true},
+ {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK,
+ false},
+ {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, true},
+
+ {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, CONTENT_SETTING_ALLOW,
+ false},
+ {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, CONTENT_SETTING_ALLOW, true},
- {CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, false},
- {CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, true},
+ {CONTENT_SETTING_ASK, CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, false},
+ {CONTENT_SETTING_ASK, CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, true},
- {CONTENT_SETTING_ASK, CONTENT_SETTING_ALLOW, false},
- {CONTENT_SETTING_ASK, CONTENT_SETTING_ALLOW, true},
+ {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, false},
+ {CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, true},
+
+ {CONTENT_SETTING_ASK, CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, false},
+ {CONTENT_SETTING_ASK, CONTENT_SETTING_ALLOW, CONTENT_SETTING_ASK, true},
+
+ {CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, CONTENT_SETTING_ALLOW, false},
+ {CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, CONTENT_SETTING_ALLOW, true},
+
+ {CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, false},
+ {CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, CONTENT_SETTING_ASK, true},
};
+ // Prevent automatic camera permission change when camera PTZ gets updated.
+ CameraPanTiltZoomPermissionContext* camera_pan_tilt_zoom_permission_context =
+ static_cast<CameraPanTiltZoomPermissionContext*>(
+ PermissionManagerFactory::GetForProfile(
+ Profile::FromBrowserContext(
+ GetWebContents()->GetBrowserContext()))
+ ->GetPermissionContextForTesting(
+ ContentSettingsType::CAMERA_PAN_TILT_ZOOM));
+ HostContentSettingsMap* content_settings =
+ HostContentSettingsMapFactory::GetForProfile(
+ Profile::FromBrowserContext(GetWebContents()->GetBrowserContext()));
+ content_settings->RemoveObserver(camera_pan_tilt_zoom_permission_context);
+
+ const bool pan_tilt_zoom_supported = IsPanTiltZoomSupported();
for (auto& test : tests) {
- SetContentSettings(test.mic, test.cam);
+ SetContentSettings(test.mic, test.cam, test.ptz);
prompt_factory()->ResetCounts();
// Accept or deny the infobar if it's showing.
- if (test.ExpectMicInfobar() || test.ExpectCamInfobar()) {
+ if (test.ExpectMicInfobar(pan_tilt_zoom_supported) ||
+ test.ExpectCamInfobar(pan_tilt_zoom_supported) ||
+ test.ExpectPtzInfobar(pan_tilt_zoom_supported)) {
if (test.accept_infobar) {
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
@@ -703,33 +784,45 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest, ContentSettings) {
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::NONE);
}
- RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), example_video_id()));
+ RequestPermissions(
+ GetWebContents(),
+ CreateRequest(example_audio_id(), example_video_id(), true));
- ASSERT_LE(prompt_factory()->TotalRequestCount(), 2);
- ASSERT_EQ(
- test.ExpectMicInfobar(),
+ ASSERT_LE(prompt_factory()->TotalRequestCount(), 3);
+ EXPECT_EQ(
+ test.ExpectMicInfobar(pan_tilt_zoom_supported),
prompt_factory()->RequestTypeSeen(
permissions::PermissionRequestType::PERMISSION_MEDIASTREAM_MIC));
- ASSERT_EQ(
- test.ExpectCamInfobar(),
+ EXPECT_EQ(
+ test.ExpectCamInfobar(pan_tilt_zoom_supported),
prompt_factory()->RequestTypeSeen(
permissions::PermissionRequestType::PERMISSION_MEDIASTREAM_CAMERA));
+ EXPECT_EQ(
+ test.ExpectPtzInfobar(pan_tilt_zoom_supported),
+ prompt_factory()->RequestTypeSeen(permissions::PermissionRequestType::
+ PERMISSION_CAMERA_PAN_TILT_ZOOM));
// Check the media stream result is expected and the devices returned are
// expected;
- VerifyResultState(test.ExpectedMediaStreamResult(),
- test.ExpectMicAllowed() && test.ExpectCamAllowed(),
- test.ExpectMicAllowed() && test.ExpectCamAllowed());
+ VerifyResultState(
+ test.ExpectedMediaStreamResult(pan_tilt_zoom_supported),
+ test.ExpectMicAllowed() && test.ExpectCamAllowed() &&
+ (!pan_tilt_zoom_supported || test.ptz != CONTENT_SETTING_BLOCK),
+ test.ExpectMicAllowed() && test.ExpectCamAllowed() &&
+ (!pan_tilt_zoom_supported || test.ptz != CONTENT_SETTING_BLOCK));
}
}
+INSTANTIATE_TEST_SUITE_P(All,
+ MediaStreamDevicesControllerPtzTest,
+ ::testing::Values(false, true));
+
// Request and allow camera access on WebUI pages without prompting.
IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
WebUIRequestAndAllowCam) {
InitWithUrl(GURL(chrome::kChromeUIVersionURL));
RequestPermissions(GetWebContents(),
- CreateRequest(std::string(), example_video_id()));
+ CreateRequest(std::string(), example_video_id(), false));
ASSERT_EQ(0, prompt_factory()->TotalRequestCount());
@@ -745,8 +838,9 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
// Test that a prompt is required.
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
- RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), example_video_id()));
+ RequestPermissions(
+ GetWebContents(),
+ CreateRequest(example_audio_id(), example_video_id(), false));
ASSERT_EQ(2, prompt_factory()->TotalRequestCount());
ASSERT_TRUE(prompt_factory()->RequestTypeSeen(
permissions::PermissionRequestType::PERMISSION_MEDIASTREAM_CAMERA));
@@ -757,8 +851,9 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
// Check that re-requesting allows without prompting.
prompt_factory()->ResetCounts();
- RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), example_video_id()));
+ RequestPermissions(
+ GetWebContents(),
+ CreateRequest(example_audio_id(), example_video_id(), false));
ASSERT_EQ(0, prompt_factory()->TotalRequestCount());
VerifyResultState(blink::mojom::MediaStreamRequestResult::OK, true, true);
@@ -773,7 +868,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
RequestPermissions(
GetWebContents(),
- CreateRequestWithType(example_audio_id(), example_video_id(),
+ CreateRequestWithType(example_audio_id(), example_video_id(), false,
blink::MEDIA_OPEN_DEVICE_PEPPER_ONLY));
ASSERT_EQ(0, prompt_factory()->TotalRequestCount());
@@ -788,7 +883,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest, WebContentsDestroyed) {
permissions::PermissionRequestManager::ACCEPT_ALL);
content::MediaStreamRequest request =
- CreateRequest(example_audio_id(), example_video_id());
+ CreateRequest(example_audio_id(), example_video_id(), false);
// Simulate a destroyed RenderFrameHost.
request.render_frame_id = 0;
request.render_process_id = 0;
@@ -818,7 +913,8 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
// Now request permissions, but before the callback is asynchronously called,
// destroy the tab.
permission_bubble_media_access_handler_->HandleRequest(
- prompt_contents, CreateRequest(example_audio_id(), example_video_id()),
+ prompt_contents,
+ CreateRequest(example_audio_id(), example_video_id(), false),
base::BindOnce([](const blink::MediaStreamDevices& devices,
blink::mojom::MediaStreamRequestResult result,
std::unique_ptr<content::MediaStreamUI> ui) {
@@ -857,8 +953,9 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
InitWithUrl(embedded_test_server()->GetURL("/simple.html"));
SetDevicePolicy(DEVICE_TYPE_AUDIO, ACCESS_ALLOWED);
SetDevicePolicy(DEVICE_TYPE_VIDEO, ACCESS_ALLOWED);
- RequestPermissions(GetWebContents(),
- CreateRequest(example_audio_id(), example_video_id()));
+ RequestPermissions(
+ GetWebContents(),
+ CreateRequest(example_audio_id(), example_video_id(), false));
ASSERT_EQ(0, prompt_factory()->TotalRequestCount());
VerifyResultState(blink::mojom::MediaStreamRequestResult::KILL_SWITCH_ON,
@@ -881,7 +978,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
ChildFrameAt(GetWebContents()->GetMainFrame(), 0);
content::MediaStreamRequest request =
- CreateRequest(example_audio_id(), example_video_id());
+ CreateRequest(example_audio_id(), example_video_id(), false);
// Make the child frame the source of the request.
request.render_process_id = child_frame->GetProcess()->GetID();
request.render_frame_id = child_frame->GetRoutingID();
@@ -911,7 +1008,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
ChildFrameAt(GetWebContents()->GetMainFrame(), 0);
content::MediaStreamRequest request =
- CreateRequest(std::string(), example_video_id());
+ CreateRequest(std::string(), example_video_id(), false);
// Make the child frame the source of the request.
request.render_process_id = child_frame->GetProcess()->GetID();
request.render_frame_id = child_frame->GetRoutingID();
@@ -931,7 +1028,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
InitWithUrl(GURL(chrome::kChromeUIVersionURL));
RequestPermissions(
GetWebContents(),
- CreateRequestWithType(example_audio_id(), std::string(),
+ CreateRequestWithType(example_audio_id(), std::string(), false,
blink::MEDIA_OPEN_DEVICE_PEPPER_ONLY));
VerifyResultState(blink::mojom::MediaStreamRequestResult::OK, true, false);
}
@@ -942,7 +1039,7 @@ IN_PROC_BROWSER_TEST_F(MediaStreamDevicesControllerTest,
InitWithUrl(GURL(chrome::kChromeUIVersionURL));
RequestPermissions(
GetWebContents(),
- CreateRequestWithType(std::string(), example_video_id(),
+ CreateRequestWithType(std::string(), example_video_id(), false,
blink::MEDIA_OPEN_DEVICE_PEPPER_ONLY));
VerifyResultState(blink::mojom::MediaStreamRequestResult::OK, false, true);
}
diff --git a/chromium/chrome/browser/media/webrtc/native_desktop_media_list.cc b/chromium/chrome/browser/media/webrtc/native_desktop_media_list.cc
index 224d52b8353..af3a6dab055 100644
--- a/chromium/chrome/browser/media/webrtc/native_desktop_media_list.cc
+++ b/chromium/chrome/browser/media/webrtc/native_desktop_media_list.cc
@@ -11,7 +11,6 @@
#include "base/message_loop/message_pump_type.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "chrome/browser/media/webrtc/desktop_media_list.h"
@@ -33,7 +32,6 @@
#include "ui/snapshot/snapshot_aura.h"
#endif
-using content::BrowserThread;
using content::DesktopMediaID;
namespace {
@@ -99,6 +97,8 @@ class NativeDesktopMediaList::Worker
private:
typedef std::map<DesktopMediaID, uint32_t> ImageHashesMap;
+ bool IsCurrentFrameValid() const;
+
// webrtc::DesktopCapturer::Callback interface.
void OnCaptureResult(webrtc::DesktopCapturer::Result result,
std::unique_ptr<webrtc::DesktopFrame> frame) override;
@@ -126,7 +126,9 @@ NativeDesktopMediaList::Worker::Worker(
: task_runner_(task_runner),
media_list_(media_list),
type_(type),
- capturer_(std::move(capturer)) {}
+ capturer_(std::move(capturer)) {
+ DCHECK(capturer_);
+}
NativeDesktopMediaList::Worker::~Worker() {
DCHECK(task_runner_->BelongsToCurrentThread());
@@ -178,8 +180,8 @@ void NativeDesktopMediaList::Worker::Refresh(
SourceDescription(DesktopMediaID(type_, sources[i].id), title));
}
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&NativeDesktopMediaList::RefreshForAuraWindows,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&NativeDesktopMediaList::RefreshForAuraWindows,
media_list_, result, update_thumnails));
}
@@ -198,7 +200,7 @@ void NativeDesktopMediaList::Worker::RefreshThumbnails(
// Expect that DesktopCapturer to always captures frames synchronously.
// |current_frame_| may be NULL if capture failed (e.g. because window has
// been closed).
- if (current_frame_) {
+ if (IsCurrentFrameValid()) {
uint32_t frame_hash = GetFrameHash(current_frame_.get());
new_image_hashes[id] = frame_hash;
@@ -207,8 +209,8 @@ void NativeDesktopMediaList::Worker::RefreshThumbnails(
if (it == image_hashes_.end() || it->second != frame_hash) {
gfx::ImageSkia thumbnail =
ScaleDesktopFrame(std::move(current_frame_), thumbnail_size);
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&NativeDesktopMediaList::UpdateSourceThumbnail,
media_list_, id, thumbnail));
}
@@ -217,12 +219,21 @@ void NativeDesktopMediaList::Worker::RefreshThumbnails(
image_hashes_.swap(new_image_hashes);
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&NativeDesktopMediaList::UpdateNativeThumbnailsFinished,
media_list_));
}
+bool NativeDesktopMediaList::Worker::IsCurrentFrameValid() const {
+ // These checks ensure invalid data isn't passed along, potentially leading to
+ // crashes, e.g. when we calculate the hash which assumes a positive height
+ // and stride.
+ // TODO(crbug.com/1085230): figure out why the height is sometimes negative.
+ return current_frame_ && current_frame_->data() &&
+ current_frame_->stride() >= 0 && current_frame_->size().height() >= 0;
+}
+
void NativeDesktopMediaList::Worker::OnCaptureResult(
webrtc::DesktopCapturer::Result result,
std::unique_ptr<webrtc::DesktopFrame> frame) {
@@ -309,8 +320,8 @@ void NativeDesktopMediaList::RefreshForAuraWindows(
#if defined(USE_AURA)
pending_native_thumbnail_capture_ = true;
#endif
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&NativeDesktopMediaList::UpdateNativeThumbnailsFinished,
weak_factory_.GetWeakPtr()));
return;
diff --git a/chromium/chrome/browser/media/webrtc/native_desktop_media_list.h b/chromium/chrome/browser/media/webrtc/native_desktop_media_list.h
index cfd8378fe93..77eca3d6a99 100644
--- a/chromium/chrome/browser/media/webrtc/native_desktop_media_list.h
+++ b/chromium/chrome/browser/media/webrtc/native_desktop_media_list.h
@@ -21,6 +21,7 @@ class DesktopCapturer;
// native windows.
class NativeDesktopMediaList : public DesktopMediaListBase {
public:
+ // |capturer| must exist.
NativeDesktopMediaList(content::DesktopMediaID::Type type,
std::unique_ptr<webrtc::DesktopCapturer> capturer);
~NativeDesktopMediaList() override;
diff --git a/chromium/chrome/browser/media/webrtc/native_desktop_media_list_unittest.cc b/chromium/chrome/browser/media/webrtc/native_desktop_media_list_unittest.cc
index 5de558d6eaf..c550d687356 100644
--- a/chromium/chrome/browser/media/webrtc/native_desktop_media_list_unittest.cc
+++ b/chromium/chrome/browser/media/webrtc/native_desktop_media_list_unittest.cc
@@ -211,6 +211,8 @@ class NativeDesktopMediaListTest : public ChromeViewsTestBase {
gfx::AcceleratedWidget widget = host->GetAcceleratedWidget();
#if defined(OS_WIN)
window.id = reinterpret_cast<DesktopMediaID::Id>(widget);
+#elif defined(USE_X11)
+ window.id = static_cast<uint32_t>(widget);
#else
window.id = widget;
#endif
@@ -232,6 +234,8 @@ class NativeDesktopMediaListTest : public ChromeViewsTestBase {
aura_window->GetHost()->GetAcceleratedWidget();
#if defined(OS_WIN)
int native_id = reinterpret_cast<DesktopMediaID::Id>(widget);
+#elif defined(USE_X11)
+ int native_id = static_cast<uint32_t>(widget);
#else
int native_id = widget;
#endif
diff --git a/chromium/chrome/browser/media/webrtc/permission_bubble_media_access_handler.cc b/chromium/chrome/browser/media/webrtc/permission_bubble_media_access_handler.cc
index dacacfb851b..9e580a8037a 100644
--- a/chromium/chrome/browser/media/webrtc/permission_bubble_media_access_handler.cc
+++ b/chromium/chrome/browser/media/webrtc/permission_bubble_media_access_handler.cc
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/metrics/field_trial.h"
-#include "base/task/post_task.h"
#include "build/build_config.h"
#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
#include "chrome/browser/media/webrtc/media_stream_capture_indicator.h"
@@ -417,8 +416,8 @@ void PermissionBubbleMediaAccessHandler::OnAccessRequestResponse(
// Post a task to process next queued request. It has to be done
// asynchronously to make sure that calling infobar is not destroyed until
// after this function returns.
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&PermissionBubbleMediaAccessHandler::ProcessQueuedAccessRequest,
base::Unretained(this), web_contents));
diff --git a/chromium/chrome/browser/media/webrtc/tab_desktop_media_list_unittest.cc b/chromium/chrome/browser/media/webrtc/tab_desktop_media_list_unittest.cc
index 71dc81b6968..20033251c03 100644
--- a/chromium/chrome/browser/media/webrtc/tab_desktop_media_list_unittest.cc
+++ b/chromium/chrome/browser/media/webrtc/tab_desktop_media_list_unittest.cc
@@ -25,6 +25,7 @@
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_task_environment.h"
+#include "content/public/test/navigation_simulator.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/web_contents_tester.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -123,19 +124,13 @@ class TabDesktopMediaListTest : public testing::Test {
WebContentsTester::For(contents.get())
->SetLastActiveTime(base::TimeTicks::Now());
- // Get or create the transient NavigationEntry and add a title and a
- // favicon to it.
+ // Get or create a NavigationEntry and add a title and a favicon to it.
content::NavigationEntry* entry =
- contents->GetController().GetTransientEntry();
+ contents->GetController().GetLastCommittedEntry();
if (!entry) {
- std::unique_ptr<content::NavigationEntry> entry_new =
- content::NavigationController::CreateNavigationEntry(
- GURL("chrome://blank"), content::Referrer(), base::nullopt,
- ui::PAGE_TRANSITION_LINK, false, std::string(), profile_,
- nullptr /* blob_url_loader_factory */);
-
- contents->GetController().SetTransientEntry(std::move(entry_new));
- entry = contents->GetController().GetTransientEntry();
+ content::NavigationSimulator::NavigateAndCommitFromBrowser(
+ contents.get(), GURL("chrome://blank"));
+ entry = contents->GetController().GetLastCommittedEntry();
}
contents->UpdateTitleForEntry(entry, base::ASCIIToUTF16("Test tab"));
@@ -336,7 +331,7 @@ TEST_F(TabDesktopMediaListTest, UpdateTitle) {
tab_strip_model->GetWebContentsAt(kDefaultSourceCount - 1);
ASSERT_TRUE(contents);
content::NavigationController& controller = contents->GetController();
- contents->UpdateTitleForEntry(controller.GetTransientEntry(),
+ contents->UpdateTitleForEntry(controller.GetLastCommittedEntry(),
base::ASCIIToUTF16("New test tab"));
EXPECT_CALL(observer_, OnSourceNameChanged(list_.get(), 0))
@@ -361,7 +356,8 @@ TEST_F(TabDesktopMediaListTest, UpdateThumbnail) {
content::FaviconStatus favicon_info;
favicon_info.image = CreateGrayscaleImage(gfx::Size(10, 10), 100);
- contents->GetController().GetTransientEntry()->GetFavicon() = favicon_info;
+ contents->GetController().GetLastCommittedEntry()->GetFavicon() =
+ favicon_info;
EXPECT_CALL(observer_, OnSourceThumbnailChanged(list_.get(), 0))
.WillOnce(QuitMessageLoop());
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_disable_encryption_flag_browsertest.cc b/chromium/chrome/browser/media/webrtc/webrtc_disable_encryption_flag_browsertest.cc
index ad67e37d4c3..599d2215327 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_disable_encryption_flag_browsertest.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_disable_encryption_flag_browsertest.cc
@@ -48,9 +48,10 @@ class WebRtcDisableEncryptionFlagBrowserTest : public WebRtcTestBase {
// Makes a call and checks that there's encryption or not in the SDP offer.
// TODO(crbug.com/910216): De-flake this for ChromeOs.
-// TODO(crbug.com/984879): De-flake this for MSAN Linux.
+// TODO(crbug.com/984879): De-flake this for ASAN/MSAN Linux.
#if defined(OS_CHROMEOS) || \
- (defined(OS_LINUX) && defined(MEMORY_SANITIZER)) || \
+ (defined(OS_LINUX) && (defined(MEMORY_SANITIZER) || \
+ defined(ADDRESS_SANITIZER))) || \
(defined(OS_WIN) && defined(ADDRESS_SANITIZER))
#define MAYBE_VerifyEncryption DISABLED_VerifyEncryption
#else
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_event_log_history.cc b/chromium/chrome/browser/media/webrtc/webrtc_event_log_history.cc
index 59f14e44920..98b9a55c054 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_event_log_history.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_event_log_history.cc
@@ -130,12 +130,11 @@ bool WebRtcEventLogHistoryFileWriter::Init() {
DCHECK(!valid_);
if (base::PathExists(path_)) {
- if (!base::DeleteFile(path_, /*recursive=*/false)) {
+ if (!base::DeleteFile(path_)) {
LOG(ERROR) << "History file already exists, and could not be deleted.";
return false;
- } else {
- LOG(WARNING) << "History file already existed; deleted.";
}
+ LOG(WARNING) << "History file already existed; deleted.";
}
// Attempt to create the file.
@@ -144,7 +143,7 @@ bool WebRtcEventLogHistoryFileWriter::Init() {
file_.Initialize(path_, file_flags);
if (!file_.IsValid() || !file_.created()) {
LOG(WARNING) << "Couldn't create history file.";
- if (!base::DeleteFile(path_, /*recursive=*/false)) {
+ if (!base::DeleteFile(path_)) {
LOG(ERROR) << "Failed to delete " << path_ << ".";
}
return false;
@@ -218,7 +217,7 @@ bool WebRtcEventLogHistoryFileWriter::WriteUploadId(
}
void WebRtcEventLogHistoryFileWriter::Delete() {
- if (!base::DeleteFile(path_, /*recursive=*/false)) {
+ if (!base::DeleteFile(path_)) {
LOG(ERROR) << "History file could not be deleted.";
}
@@ -301,7 +300,7 @@ bool WebRtcEventLogHistoryFileReader::Init() {
base::File file(path_, file_flags);
if (!file.IsValid()) {
LOG(WARNING) << "Couldn't read history file.";
- if (!base::DeleteFile(path_, /*recursive=*/false)) {
+ if (!base::DeleteFile(path_)) {
LOG(ERROR) << "Failed to delete " << path_ << ".";
}
return false;
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager.cc b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager.cc
index 08e960e8871..f17670feecb 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager.cc
@@ -40,8 +40,8 @@ class PeerConnectionTrackerProxyImpl
void EnableWebRtcEventLogging(const WebRtcEventLogPeerConnectionKey& key,
int output_period_ms) override {
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&PeerConnectionTrackerProxyImpl::EnableWebRtcEventLoggingInternal,
key, output_period_ms));
@@ -49,8 +49,8 @@ class PeerConnectionTrackerProxyImpl
void DisableWebRtcEventLogging(
const WebRtcEventLogPeerConnectionKey& key) override {
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
&PeerConnectionTrackerProxyImpl::DisableWebRtcEventLoggingInternal,
key));
@@ -412,8 +412,8 @@ void WebRtcEventLogManager::StartRemoteLogging(
}
if (error) {
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(std::move(reply), false, std::string(),
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(std::move(reply), false, std::string(),
std::string(error)));
return;
}
@@ -888,8 +888,8 @@ void WebRtcEventLogManager::StartRemoteLoggingInternal(
DCHECK_EQ(result, !log_id.empty());
DCHECK_EQ(!result, !error_message.empty());
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(std::move(reply), result, log_id, error_message));
}
@@ -935,7 +935,7 @@ void WebRtcEventLogManager::SetLocalLogsObserverInternal(
local_logs_observer_ = observer;
if (reply) {
- base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(reply));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(reply));
}
}
@@ -947,7 +947,7 @@ void WebRtcEventLogManager::SetRemoteLogsObserverInternal(
remote_logs_observer_ = observer;
if (reply) {
- base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(reply));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(reply));
}
}
@@ -960,7 +960,7 @@ void WebRtcEventLogManager::SetClockForTesting(base::Clock* clock,
base::OnceClosure reply) {
manager->local_logs_manager_.SetClockForTesting(clock);
- base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(reply));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(reply));
};
// |this| is destroyed by ~BrowserProcessImpl(), so base::Unretained(this)
@@ -980,7 +980,7 @@ void WebRtcEventLogManager::SetPeerConnectionTrackerProxyForTesting(
base::OnceClosure reply) {
manager->pc_tracker_proxy_ = std::move(pc_tracker_proxy);
- base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(reply));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(reply));
};
// |this| is destroyed by ~BrowserProcessImpl(), so base::Unretained(this)
@@ -1004,7 +1004,8 @@ void WebRtcEventLogManager::SetWebRtcEventLogUploaderFactoryForTesting(
remote_logs_manager.SetWebRtcEventLogUploaderFactoryForTesting(
std::move(uploader_factory));
- base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(reply));
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ std::move(reply));
};
// |this| is destroyed by ~BrowserProcessImpl(), so base::Unretained(this)
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc
index 12e076407cb..b11ec75be0c 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc
@@ -239,7 +239,7 @@ bool BaseLogFileWriter::Init() {
file_.Initialize(path_, file_flags);
if (!file_.IsValid() || !file_.created()) {
LOG(WARNING) << "Couldn't create remote-bound WebRTC event log file.";
- if (!base::DeleteFile(path_, /*recursive=*/false)) {
+ if (!base::DeleteFile(path_)) {
LOG(ERROR) << "Failed to delete " << path_ << ".";
}
SetState(State::ERRORED);
@@ -312,7 +312,7 @@ void BaseLogFileWriter::Delete() {
file_.Close();
}
- if (!base::DeleteFile(path_, /*recursive=*/false)) {
+ if (!base::DeleteFile(path_)) {
LOG(ERROR) << "Failed to delete " << path_ << ".";
}
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_common_unittest.cc b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_common_unittest.cc
index 3652333ba1f..440083173d3 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_common_unittest.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_common_unittest.cc
@@ -433,7 +433,7 @@ TEST_P(LogFileWriterTest, WriteDoesNotCrashIfFileRemovedExternally) {
auto writer = CreateWriter(kMaxRemoteLogFileSizeBytes);
ASSERT_TRUE(writer);
- ASSERT_TRUE(base::DeleteFile(path_, /*recursive=*/false));
+ ASSERT_TRUE(base::DeleteFile(path_));
ASSERT_FALSE(base::PathExists(path_)); // Sanity on the test itself.
// It's up to the OS whether this will succeed or fail, but it must not crash.
@@ -446,7 +446,7 @@ TEST_P(LogFileWriterTest, CloseDoesNotCrashIfFileRemovedExternally) {
auto writer = CreateWriter(kMaxRemoteLogFileSizeBytes);
ASSERT_TRUE(writer);
- ASSERT_TRUE(base::DeleteFile(path_, /*recursive=*/false));
+ ASSERT_TRUE(base::DeleteFile(path_));
ASSERT_FALSE(base::PathExists(path_)); // Sanity on the test itself.
// It's up to the OS whether this will succeed or fail, but it must not crash.
@@ -459,7 +459,7 @@ TEST_P(LogFileWriterTest, DeleteDoesNotCrashIfFileRemovedExternally) {
auto writer = CreateWriter(kMaxRemoteLogFileSizeBytes);
ASSERT_TRUE(writer);
- ASSERT_TRUE(base::DeleteFile(path_, /*recursive=*/false));
+ ASSERT_TRUE(base::DeleteFile(path_));
ASSERT_FALSE(base::PathExists(path_)); // Sanity on the test itself.
// It's up to the OS whether this will succeed or fail, but it must not crash.
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.cc b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.cc
index 5118eb322bc..5230c7e9959 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.cc
@@ -17,7 +17,6 @@
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
-#include "base/task/post_task.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
@@ -204,7 +203,7 @@ WebRtcRemoteEventLogManager::WebRtcRemoteEventLogManager(
uploading_supported_for_connection_type_(false),
scheduled_upload_tasks_(0),
uploader_factory_(
- std::make_unique<WebRtcEventLogUploaderImpl::Factory>()),
+ std::make_unique<WebRtcEventLogUploaderImpl::Factory>(task_runner)),
task_runner_(task_runner),
weak_ptr_factory_(
std::make_unique<base::WeakPtrFactory<WebRtcRemoteEventLogManager>>(
@@ -407,13 +406,14 @@ bool WebRtcRemoteEventLogManager::PeerConnectionSessionIdSet(
return false; // Unknown peer connection; already closed?
}
- if (!peer_connection->second.empty()) {
- LOG(ERROR) << "Session ID already set.";
+ if (peer_connection->second.empty()) {
+ peer_connection->second = session_id;
+ } else if (session_id != peer_connection->second) {
+ LOG(ERROR) << "Session ID already set to " << peer_connection->second
+ << ". Cannot change to " << session_id << ".";
return false;
}
- peer_connection->second = session_id;
-
return true;
}
@@ -544,9 +544,10 @@ void WebRtcRemoteEventLogManager::GetHistory(
std::vector<UploadList::UploadInfo> history;
if (!BrowserContextEnabled(browser_context_id)) {
- LOG(ERROR) << "Unknown |browser_context_id|.";
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(std::move(reply), history));
+ // Either the browser context is unknown, or more likely, it's not
+ // enabled for remote logging.
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(std::move(reply), history));
return;
}
@@ -594,8 +595,8 @@ void WebRtcRemoteEventLogManager::GetHistory(
};
std::sort(history.begin(), history.end(), cmp);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(std::move(reply), history));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(std::move(reply), history));
}
void WebRtcRemoteEventLogManager::RemovePendingLogsForNotEnabledBrowserContext(
@@ -667,16 +668,16 @@ void WebRtcRemoteEventLogManager::SetWebRtcEventLogUploaderFactoryForTesting(
void WebRtcRemoteEventLogManager::UploadConditionsHoldForTesting(
base::OnceCallback<void(bool)> callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(std::move(callback), UploadConditionsHold()));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(std::move(callback), UploadConditionsHold()));
}
void WebRtcRemoteEventLogManager::ShutDownForTesting(base::OnceClosure reply) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
weak_ptr_factory_->InvalidateWeakPtrs();
weak_ptr_factory_.reset();
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(std::move(reply)));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(std::move(reply)));
}
bool WebRtcRemoteEventLogManager::AreLogParametersValid(
@@ -748,7 +749,7 @@ WebRtcRemoteEventLogManager::CloseLogFile(LogFilesMap::iterator it,
DCHECK(emplace_result.second); // No pre-existing entry.
} else {
const base::FilePath log_file_path = it->second->path();
- if (!base::DeleteFile(log_file_path, /*recursive=*/false)) {
+ if (!base::DeleteFile(log_file_path)) {
LOG(ERROR) << "Failed to delete " << log_file_path << ".";
}
}
@@ -834,14 +835,14 @@ void WebRtcRemoteEventLogManager::LoadLogsDirectory(
}
// Remove the log file itself.
- if (!base::DeleteFile(log_file_path, /*recursive=*/false)) {
+ if (!base::DeleteFile(log_file_path)) {
LOG(ERROR) << "Failed to delete " << file_to_delete.first << ".";
}
}
// Remove expired history files.
for (const base::FilePath& history_file_path : history_files_to_delete) {
- if (!base::DeleteFile(history_file_path, /*recursive=*/false)) {
+ if (!base::DeleteFile(history_file_path)) {
LOG(ERROR) << "Failed to delete " << history_file_path << ".";
}
}
@@ -1188,18 +1189,9 @@ void WebRtcRemoteEventLogManager::MaybeCancelUpload(
return;
}
- // Cancel the upload.
- // * If the upload has asynchronously completed by now, the uploader would
- // have posted a task back to our queue to delete it and move on to the
- // next file; cancellation is reported as unsuccessful in that case. In that
- // case, we avoid resetting |uploader_| until that callback task executes.
- // * If the upload was still underway when we cancelled it, then we can
- // safely reset |uploader_| and move on to the next file the next time
- // ManageUploadSchedule() is called.
- const bool cancelled = uploader_->Cancel();
- if (cancelled) {
- uploader_.reset();
- }
+ // Cancel the upload. `uploader_` will be released when the callback,
+ // `OnWebRtcEventLogUploadComplete`, is posted back.
+ uploader_->Cancel();
}
bool WebRtcRemoteEventLogManager::MatchesFilter(
@@ -1319,6 +1311,7 @@ void WebRtcRemoteEventLogManager::MaybeStartUploading() {
// TODO(crbug.com/775415): Rename the file before uploading, so that we
// would not retry the upload after restarting Chrome, if the upload is
// interrupted.
+ currently_uploaded_file_ = pending_logs_.begin()->path;
uploader_ =
uploader_factory_->Create(*pending_logs_.begin(), std::move(callback));
pending_logs_.erase(pending_logs_.begin());
@@ -1332,7 +1325,20 @@ void WebRtcRemoteEventLogManager::OnWebRtcEventLogUploadComplete(
bool upload_successful) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
DCHECK(uploader_);
+
+ // Make sure this callback refers to the currently uploaded file. This might
+ // not be the case if the upload was cancelled right after succeeding, in
+ // which case we'll get two callbacks, one reporting success and one failure.
+ // It can also be that the uploader was cancelled more than once, e.g. if
+ // the user cleared cache while PrefService were changing.
+ if (!uploader_ ||
+ uploader_->GetWebRtcLogFileInfo().path != currently_uploaded_file_) {
+ return;
+ }
+
uploader_.reset();
+ currently_uploaded_file_.clear();
+
ManageUploadSchedule();
}
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.h b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.h
index ff1f93a93e6..c042e583469 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.h
+++ b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.h
@@ -443,6 +443,12 @@ class WebRtcRemoteEventLogManager final
// currently busy uploading it to a remote server.
std::unique_ptr<WebRtcEventLogUploader> uploader_;
+ // The path to the file which is currently being uploaded.
+ // Used to ensure a callback from the uploader refers to the current
+ // file, rather than a second callback from the previously uploaded file,
+ // e.g. when when Cancel() is called right after the upload finishes.
+ base::FilePath currently_uploaded_file_;
+
// Provides notifications of network changes.
network::NetworkConnectionTracker* network_connection_tracker_;
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc
index c4757115f34..0caf07db158 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc
@@ -69,7 +69,6 @@
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
-#include "chrome/test/base/testing_profile.h"
#include "components/account_id/account_id.h"
#include "components/user_manager/scoped_user_manager.h"
#endif
@@ -189,14 +188,9 @@ class NullWebRtcEventLogUploader : public WebRtcEventLogUploader {
return log_file_;
}
- bool Cancel() override {
+ void Cancel() override {
EXPECT_TRUE(cancellation_expected_);
- if (was_cancelled_) { // Should not be called more than once.
- EXPECT_TRUE(false);
- return false;
- }
was_cancelled_ = true;
- return true;
}
class Factory : public WebRtcEventLogUploader::Factory {
@@ -1202,14 +1196,14 @@ class WebRtcEventLogManagerTestIncognito
incognito_rph_.reset();
if (incognito_profile_) {
DCHECK(browser_context_);
- browser_context_->DestroyOffTheRecordProfile();
+ browser_context_->DestroyOffTheRecordProfile(incognito_profile_);
}
}
void SetUp() override {
WebRtcEventLogManagerTestBase::SetUp();
- incognito_profile_ = browser_context_->GetOffTheRecordProfile();
+ incognito_profile_ = browser_context_->GetPrimaryOTRProfile();
incognito_rph_ =
std::make_unique<MockRenderProcessHost>(incognito_profile_);
}
@@ -1311,7 +1305,7 @@ class FileListExpectingWebRtcEventLogUploader : public WebRtcEventLogUploader {
// we cannot verify |log_file.browser_context_id| is correct.
// This is unimportant to the test.
- base::DeleteFile(log_file.path, false);
+ base::DeleteFile(log_file.path);
expected_files_.pop_front();
}
@@ -1345,9 +1339,8 @@ class FileListExpectingWebRtcEventLogUploader : public WebRtcEventLogUploader {
return log_file_;
}
- bool Cancel() override {
+ void Cancel() override {
NOTREACHED() << "Incompatible with this kind of test.";
- return true;
}
private:
@@ -1408,19 +1401,19 @@ TEST_F(WebRtcEventLogManagerTest,
}
TEST_F(WebRtcEventLogManagerTest,
- PeerConnectionSessionIdSetReturnsFalseIfAlreadyCalledSameId) {
+ PeerConnectionSessionIdSetReturnsFalseIfPeerConnectionAlreadyRemoved) {
const auto key = GetPeerConnectionKey(rph_.get(), kLid);
ASSERT_TRUE(PeerConnectionAdded(key));
- ASSERT_TRUE(PeerConnectionSessionIdSet(key, kSessionId));
+ ASSERT_TRUE(PeerConnectionRemoved(key));
EXPECT_FALSE(PeerConnectionSessionIdSet(key, kSessionId));
}
TEST_F(WebRtcEventLogManagerTest,
- PeerConnectionSessionIdSetReturnsFalseIfPeerConnectionAlreadyRemoved) {
+ PeerConnectionSessionIdSetReturnsTrueIfAlreadyCalledSameId) {
const auto key = GetPeerConnectionKey(rph_.get(), kLid);
ASSERT_TRUE(PeerConnectionAdded(key));
- ASSERT_TRUE(PeerConnectionRemoved(key));
- EXPECT_FALSE(PeerConnectionSessionIdSet(key, kSessionId));
+ ASSERT_TRUE(PeerConnectionSessionIdSet(key, kSessionId));
+ EXPECT_TRUE(PeerConnectionSessionIdSet(key, kSessionId));
}
TEST_F(WebRtcEventLogManagerTest,
@@ -4357,7 +4350,7 @@ TEST_F(WebRtcEventLogManagerTestPolicy,
ASSERT_TRUE(base::PathExists(*log_file)); // Test sanity; exists before.
- allow_remote_logging = !allow_remote_logging;
+ allow_remote_logging = false;
profile->GetPrefs()->SetBoolean(prefs::kWebRtcEventLogCollectionAllowed,
allow_remote_logging);
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader.cc b/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader.cc
index b095a44da6c..9be22d20e36 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader.cc
@@ -8,8 +8,6 @@
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
-#include "base/task/post_task.h"
-#include "base/threading/sequenced_task_runner_handle.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "components/version_info/version_info.h"
@@ -125,11 +123,17 @@ void OnURLLoadUploadProgress(uint64_t current, uint64_t total) {
const char WebRtcEventLogUploaderImpl::kUploadURL[] =
"https://clients2.google.com/cr/report";
+WebRtcEventLogUploaderImpl::Factory::Factory(
+ scoped_refptr<base::SequencedTaskRunner> task_runner)
+ : task_runner_(std::move(task_runner)) {}
+
+WebRtcEventLogUploaderImpl::Factory::~Factory() = default;
+
std::unique_ptr<WebRtcEventLogUploader>
WebRtcEventLogUploaderImpl::Factory::Create(const WebRtcLogFileInfo& log_file,
UploadResultCallback callback) {
return std::make_unique<WebRtcEventLogUploaderImpl>(
- log_file, std::move(callback), kMaxRemoteLogFileSizeBytes);
+ task_runner_, log_file, std::move(callback), kMaxRemoteLogFileSizeBytes);
}
std::unique_ptr<WebRtcEventLogUploader>
@@ -138,17 +142,18 @@ WebRtcEventLogUploaderImpl::Factory::CreateWithCustomMaxSizeForTesting(
UploadResultCallback callback,
size_t max_log_file_size_bytes) {
return std::make_unique<WebRtcEventLogUploaderImpl>(
- log_file, std::move(callback), max_log_file_size_bytes);
+ task_runner_, log_file, std::move(callback), max_log_file_size_bytes);
}
WebRtcEventLogUploaderImpl::WebRtcEventLogUploaderImpl(
+ scoped_refptr<base::SequencedTaskRunner> task_runner,
const WebRtcLogFileInfo& log_file,
UploadResultCallback callback,
size_t max_log_file_size_bytes)
- : log_file_(log_file),
+ : task_runner_(std::move(task_runner)),
+ log_file_(log_file),
callback_(std::move(callback)),
- max_log_file_size_bytes_(max_log_file_size_bytes),
- io_task_runner_(base::SequencedTaskRunnerHandle::Get()) {
+ max_log_file_size_bytes_(max_log_file_size_bytes) {
history_file_writer_ = WebRtcEventLogHistoryFileWriter::Create(
GetWebRtcEventLogHistoryFilePath(log_file_.path));
if (!history_file_writer_) {
@@ -190,12 +195,12 @@ WebRtcEventLogUploaderImpl::~WebRtcEventLogUploaderImpl() {
// 3. The upload was never started, due to an early failure (e.g. file not
// found). In that case, |url_loader_| will not have been set.
// 4. Chrome shutdown.
- if (io_task_runner_->RunsTasksInCurrentSequence()) { // Scenarios 1-3.
+ if (task_runner_->RunsTasksInCurrentSequence()) { // Scenarios 1-3.
DCHECK(!url_loader_);
} else { // # Scenario #4 - Chrome shutdown.
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
bool will_delete =
- io_task_runner_->DeleteSoon(FROM_HERE, url_loader_.release());
+ task_runner_->DeleteSoon(FROM_HERE, url_loader_.release());
DCHECK(!will_delete)
<< "Task runners must have been stopped by this stage of shutdown.";
}
@@ -203,35 +208,33 @@ WebRtcEventLogUploaderImpl::~WebRtcEventLogUploaderImpl() {
const WebRtcLogFileInfo& WebRtcEventLogUploaderImpl::GetWebRtcLogFileInfo()
const {
- DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
+ DCHECK(task_runner_->RunsTasksInCurrentSequence());
return log_file_;
}
-bool WebRtcEventLogUploaderImpl::Cancel() {
- DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
+void WebRtcEventLogUploaderImpl::Cancel() {
+ DCHECK(task_runner_->RunsTasksInCurrentSequence());
- // The upload could already have been completed, or maybe was never properly
- // started (due to a file read failure, etc.).
- const bool upload_was_active = (url_loader_.get() != nullptr);
+ if (url_loader_.get() == nullptr) {
+ // Either the upload has already completed, or it never properly started.
+ return;
+ }
- // Note that in this case, it might still be that the last bytes hit the
- // wire right as we attempt to cancel the upload. OnURLFetchComplete, however,
- // will not be called.
+ // Stop the upload.
url_loader_.reset();
- DeleteLogFile();
- DeleteHistoryFile();
-
- if (upload_was_active) {
- UmaRecordWebRtcEventLoggingUpload(
- WebRtcEventLoggingUploadUma::kUploadCancelled);
- }
-
- return upload_was_active;
+ // Note edge case - the upload might on very rare occasions already have
+ // finished, with the on-complete callback pending on the queue.
+ // In those very rare occasions, we will record the UMA for cancellation
+ // as well as the success/failure of the upload. Also, we'll post to replies
+ // back to the owner of this WebRtcEventLogUploaderImpl object.
+ UmaRecordWebRtcEventLoggingUpload(
+ WebRtcEventLoggingUploadUma::kUploadCancelled);
+ ReportResult(/*upload_successful=*/false, /*delete_history_file=*/true);
}
bool WebRtcEventLogUploaderImpl::PrepareUploadData(std::string* upload_data) {
- DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
+ DCHECK(task_runner_->RunsTasksInCurrentSequence());
std::string log_file_contents;
if (!base::ReadFileToStringWithMaxSize(log_file_.path, &log_file_contents,
@@ -271,7 +274,7 @@ bool WebRtcEventLogUploaderImpl::PrepareUploadData(std::string* upload_data) {
}
void WebRtcEventLogUploaderImpl::StartUpload(const std::string& upload_data) {
- DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
+ DCHECK(task_runner_->RunsTasksInCurrentSequence());
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = GURL(kUploadURL);
@@ -282,8 +285,8 @@ void WebRtcEventLogUploaderImpl::StartUpload(const std::string& upload_data) {
// immediately, even though it needs to finish initialization on the UI
// thread.
mojo::Remote<network::mojom::URLLoaderFactory> url_loader_factory_remote;
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(BindURLLoaderFactoryReceiver,
url_loader_factory_remote.BindNewPipeAndPassReceiver()));
@@ -293,18 +296,16 @@ void WebRtcEventLogUploaderImpl::StartUpload(const std::string& upload_data) {
url_loader_->SetOnUploadProgressCallback(
base::BindRepeating(OnURLLoadUploadProgress));
- // See comment in destructor for an explanation about why using
- // base::Unretained(this) is safe here.
url_loader_->DownloadToString(
url_loader_factory_remote.get(),
base::BindOnce(&WebRtcEventLogUploaderImpl::OnURLLoadComplete,
- base::Unretained(this)),
+ weak_ptr_factory_.GetWeakPtr()),
kWebRtcEventLogMaxUploadIdBytes);
}
void WebRtcEventLogUploaderImpl::OnURLLoadComplete(
std::unique_ptr<std::string> response_body) {
- DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
+ DCHECK(task_runner_->RunsTasksInCurrentSequence());
DCHECK(url_loader_);
if (response_body.get() != nullptr && response_body->empty()) {
@@ -341,8 +342,9 @@ void WebRtcEventLogUploaderImpl::OnURLLoadComplete(
ReportResult(upload_successful);
}
-void WebRtcEventLogUploaderImpl::ReportResult(bool result) {
- DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
+void WebRtcEventLogUploaderImpl::ReportResult(bool upload_successful,
+ bool delete_history_file) {
+ DCHECK(task_runner_->RunsTasksInCurrentSequence());
// * If the upload was successful, the file is no longer needed.
// * If the upload failed, we don't want to retry, because we run the risk of
@@ -353,17 +355,21 @@ void WebRtcEventLogUploaderImpl::ReportResult(bool result) {
// TODO(crbug.com/775415): Provide refined retrial behavior.
DeleteLogFile();
+ if (delete_history_file) {
+ DeleteHistoryFile();
+ }
+
// Release hold of history file, allowing it to be read, moved or deleted.
history_file_writer_.reset();
- io_task_runner_->PostTask(
- FROM_HERE, base::BindOnce(std::move(callback_), log_file_.path, result));
+ task_runner_->PostTask(
+ FROM_HERE,
+ base::BindOnce(std::move(callback_), log_file_.path, upload_successful));
}
void WebRtcEventLogUploaderImpl::DeleteLogFile() {
- DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
- const bool deletion_successful =
- base::DeleteFile(log_file_.path, /*recursive=*/false);
+ DCHECK(task_runner_->RunsTasksInCurrentSequence());
+ const bool deletion_successful = base::DeleteFile(log_file_.path);
if (!deletion_successful) {
// This is a somewhat serious (though unlikely) error, because now we'll
// try to upload this file again next time Chrome launches.
@@ -372,7 +378,7 @@ void WebRtcEventLogUploaderImpl::DeleteLogFile() {
}
void WebRtcEventLogUploaderImpl::DeleteHistoryFile() {
- DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
+ DCHECK(task_runner_->RunsTasksInCurrentSequence());
if (!history_file_writer_) {
LOG(ERROR) << "Deletion of history file attempted after uploader "
<< "has relinquished ownership of it.";
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader.h b/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader.h
index f0699503180..d6d4f28abac 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader.h
+++ b/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader.h
@@ -37,12 +37,12 @@ class WebRtcEventLogUploader {
public:
virtual ~Factory() = default;
- // Creates uploaders. The observer is passed to each call of Create,
- // rather than be memorized by the factory's constructor, because factories
- // created by unit tests have no visibility into the real implementation's
- // observer (WebRtcRemoteEventLogManager).
+ // Creates uploaders.
// This takes ownership of the file. The caller must not attempt to access
- // the file after invoking Create().
+ // the file after invoking Create(). Even deleting the file due to
+ // the user clearing cache, is to be done through the uploader's Cancel,
+ // and not through direct access of the caller to the file. The file may
+ // be touched again only after |this| is destroyed.
virtual std::unique_ptr<WebRtcEventLogUploader> Create(
const WebRtcLogFileInfo& log_file,
UploadResultCallback callback) = 0;
@@ -55,10 +55,9 @@ class WebRtcEventLogUploader {
virtual const WebRtcLogFileInfo& GetWebRtcLogFileInfo() const = 0;
// Cancels the upload, then deletes the log file and its history file.
- // Returns true if the upload was cancelled due to this call, and false if
- // the upload was already completed or aborted before this call.
- // (Aborted uploads are ones where the file could not be read, etc.)
- virtual bool Cancel() = 0;
+ // (These files are deleted even if the upload has been completed by the time
+ // Cancel is called.)
+ virtual void Cancel() = 0;
};
// Primary implementation of WebRtcEventLogUploader. Uploads log files to crash.
@@ -67,7 +66,9 @@ class WebRtcEventLogUploaderImpl : public WebRtcEventLogUploader {
public:
class Factory : public WebRtcEventLogUploader::Factory {
public:
- ~Factory() override = default;
+ explicit Factory(scoped_refptr<base::SequencedTaskRunner> task_runner);
+
+ ~Factory() override;
std::unique_ptr<WebRtcEventLogUploader> Create(
const WebRtcLogFileInfo& log_file,
@@ -80,9 +81,13 @@ class WebRtcEventLogUploaderImpl : public WebRtcEventLogUploader {
const WebRtcLogFileInfo& log_file,
UploadResultCallback callback,
size_t max_remote_log_file_size_bytes);
+
+ private:
+ scoped_refptr<base::SequencedTaskRunner> task_runner_;
};
WebRtcEventLogUploaderImpl(
+ scoped_refptr<base::SequencedTaskRunner> task_runner,
const WebRtcLogFileInfo& log_file,
UploadResultCallback callback,
size_t max_remote_log_file_size_bytes);
@@ -90,7 +95,7 @@ class WebRtcEventLogUploaderImpl : public WebRtcEventLogUploader {
const WebRtcLogFileInfo& GetWebRtcLogFileInfo() const override;
- bool Cancel() override;
+ void Cancel() override;
private:
friend class WebRtcEventLogUploaderImplTest;
@@ -110,7 +115,7 @@ class WebRtcEventLogUploaderImpl : public WebRtcEventLogUploader {
void OnURLLoadComplete(std::unique_ptr<std::string> response_body);
// Cleanup and posting of the result callback.
- void ReportResult(bool result);
+ void ReportResult(bool upload_successful, bool delete_history_file = false);
// Remove the log file which is owned by |this|.
void DeleteLogFile();
@@ -121,6 +126,9 @@ class WebRtcEventLogUploaderImpl : public WebRtcEventLogUploader {
// The URL used for uploading the logs.
static const char kUploadURL[];
+ // The object lives on this IO-capable task runner.
+ scoped_refptr<base::SequencedTaskRunner> task_runner_;
+
// Housekeeping information about the uploaded file (path, time of last
// modification, associated BrowserContext).
const WebRtcLogFileInfo log_file_;
@@ -139,8 +147,8 @@ class WebRtcEventLogUploaderImpl : public WebRtcEventLogUploader {
// This object is in charge of the actual upload.
std::unique_ptr<network::SimpleURLLoader> url_loader_;
- // The object lives on this IO-capable task runner.
- scoped_refptr<base::SequencedTaskRunner> io_task_runner_;
+ // Allows releasing |this| while a task from |url_loader_| is still pending.
+ base::WeakPtrFactory<WebRtcEventLogUploaderImpl> weak_ptr_factory_{this};
};
} // namespace webrtc_event_logging
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader_impl_unittest.cc b/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader_impl_unittest.cc
index 853cc085998..5d341ccdebc 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader_impl_unittest.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_event_log_uploader_impl_unittest.cc
@@ -28,6 +28,7 @@
namespace webrtc_event_logging {
+using ::testing::_;
using ::testing::StrictMock;
using BrowserContextId = WebRtcEventLogPeerConnectionKey::BrowserContextId;
@@ -81,7 +82,8 @@ class WebRtcEventLogUploaderImplTest : public ::testing::Test {
EXPECT_TRUE(base::Time::FromString("30 Dec 1983", &kReasonableTime));
- uploader_factory_ = std::make_unique<WebRtcEventLogUploaderImpl::Factory>();
+ uploader_factory_ = std::make_unique<WebRtcEventLogUploaderImpl::Factory>(
+ base::SequencedTaskRunnerHandle::Get());
}
~WebRtcEventLogUploaderImplTest() override {
@@ -276,31 +278,34 @@ TEST_F(WebRtcEventLogUploaderImplTest, ExcessivelyLargeFilesNotUploaded) {
}
TEST_F(WebRtcEventLogUploaderImplTest,
- CancelBeforeUploadCompletionReturnsTrue) {
+ CancelBeforeUploadCompletionCallsCallbackWithFalse) {
const base::Time last_modified = base::Time::Now();
StartUploadThatWillNotTerminate(browser_context_id_, last_modified);
-
- EXPECT_TRUE(uploader_->Cancel());
+ EXPECT_CALL(observer_, CompletionCallback(log_file_, false)).Times(1);
+ uploader_->Cancel();
}
-TEST_F(WebRtcEventLogUploaderImplTest, CancelOnCancelledUploadReturnsFalse) {
+TEST_F(WebRtcEventLogUploaderImplTest, SecondCallToCancelHasNoEffect) {
const base::Time last_modified = base::Time::Now();
StartUploadThatWillNotTerminate(browser_context_id_, last_modified);
- ASSERT_TRUE(uploader_->Cancel());
- EXPECT_FALSE(uploader_->Cancel());
+ EXPECT_CALL(observer_, CompletionCallback(log_file_, _)).Times(1);
+
+ uploader_->Cancel();
+ uploader_->Cancel();
}
TEST_F(WebRtcEventLogUploaderImplTest,
- CancelAfterUploadCompletionReturnsFalse) {
+ CancelAfterUploadCompletionCallbackWasCalledHasNoEffect) {
SetURLLoaderResponse(net::HTTP_OK, net::OK);
EXPECT_CALL(observer_, CompletionCallback(log_file_, true)).Times(1);
StartAndWaitForUpload();
- EXPECT_FALSE(uploader_->Cancel());
+ EXPECT_CALL(observer_, CompletionCallback(_, _)).Times(0);
+ uploader_->Cancel();
}
-TEST_F(WebRtcEventLogUploaderImplTest, CancelOnAbortedUploadReturnsFalse) {
+TEST_F(WebRtcEventLogUploaderImplTest, CancelOnAbortedUploadHasNoEffect) {
// Show the failure was independent of the URLLoaderFactory's primed return
// value.
SetURLLoaderResponse(net::HTTP_OK, net::OK);
@@ -309,13 +314,17 @@ TEST_F(WebRtcEventLogUploaderImplTest, CancelOnAbortedUploadReturnsFalse) {
EXPECT_CALL(observer_, CompletionCallback(log_file_, false)).Times(1);
StartAndWaitForUpload();
- EXPECT_FALSE(uploader_->Cancel());
+ EXPECT_CALL(observer_, CompletionCallback(_, _)).Times(0);
+ uploader_->Cancel();
}
TEST_F(WebRtcEventLogUploaderImplTest, CancelOnOngoingUploadDeletesFile) {
const base::Time last_modified = base::Time::Now();
StartUploadThatWillNotTerminate(browser_context_id_, last_modified);
- ASSERT_TRUE(uploader_->Cancel());
+
+ EXPECT_CALL(observer_, CompletionCallback(log_file_, false)).Times(1);
+ uploader_->Cancel();
+ observer_run_loop_.Run();
EXPECT_FALSE(base::PathExists(log_file_));
}
@@ -331,7 +340,8 @@ TEST_F(WebRtcEventLogUploaderImplTest,
EXPECT_EQ(info.last_modified, last_modified);
// Test tear-down.
- ASSERT_TRUE(uploader_->Cancel());
+ EXPECT_CALL(observer_, CompletionCallback(log_file_, false)).Times(1);
+ uploader_->Cancel();
}
TEST_F(WebRtcEventLogUploaderImplTest,
@@ -352,7 +362,8 @@ TEST_F(WebRtcEventLogUploaderImplTest,
GetWebRtcLogFileInfoReturnsCorrectInfoWhenCalledOnCancelledUpload) {
const base::Time last_modified = base::Time::Now();
StartUploadThatWillNotTerminate(browser_context_id_, last_modified);
- ASSERT_TRUE(uploader_->Cancel());
+ EXPECT_CALL(observer_, CompletionCallback(log_file_, false)).Times(1);
+ uploader_->Cancel();
const WebRtcLogFileInfo info = uploader_->GetWebRtcLogFileInfo();
EXPECT_EQ(info.browser_context_id, browser_context_id_);
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_log_uploader_unittest.cc b/chromium/chrome/browser/media/webrtc/webrtc_log_uploader_unittest.cc
index 6aa2a76c11f..f7d57c8beb4 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_log_uploader_unittest.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_log_uploader_unittest.cc
@@ -203,7 +203,7 @@ TEST_F(WebRtcLogUploaderTest, AddLocallyStoredLogInfoToUploadListFile) {
// Get a temporary filename. We don't want the file to exist to begin with
// since that's the normal use case, hence the delete.
ASSERT_TRUE(base::CreateTemporaryFile(&test_list_path_));
- EXPECT_TRUE(base::DeleteFile(test_list_path_, false));
+ EXPECT_TRUE(base::DeleteFile(test_list_path_));
std::unique_ptr<WebRtcLogUploader> webrtc_log_uploader(
new WebRtcLogUploader());
@@ -241,7 +241,7 @@ TEST_F(WebRtcLogUploaderTest, AddUploadedLogInfoToUploadListFile) {
// Get a temporary filename. We don't want the file to exist to begin with
// since that's the normal use case, hence the delete.
ASSERT_TRUE(base::CreateTemporaryFile(&test_list_path_));
- EXPECT_TRUE(base::DeleteFile(test_list_path_, false));
+ EXPECT_TRUE(base::DeleteFile(test_list_path_));
std::unique_ptr<WebRtcLogUploader> webrtc_log_uploader(
new WebRtcLogUploader());
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_logging_controller.cc b/chromium/chrome/browser/media/webrtc/webrtc_logging_controller.cc
index 8caf1d7fe01..a2dc872f349 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_logging_controller.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_logging_controller.cc
@@ -85,7 +85,10 @@ void WebRtcLoggingController::StartLogging(
content::RenderProcessHost* host =
content::RenderProcessHost::FromID(render_process_id_);
- // OK for this to replace an existing logging_agent_ connection.
+ // OK to rebind existing |logging_agent_| and |receiver_| connections.
+ logging_agent_.reset();
+ receiver_.reset();
+
host->BindReceiver(logging_agent_.BindNewPipeAndPassReceiver());
logging_agent_.set_disconnect_handler(
base::BindOnce(&WebRtcLoggingController::OnAgentDisconnected, this));
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_pan_tilt_zoom_browsertest.cc b/chromium/chrome/browser/media/webrtc/webrtc_pan_tilt_zoom_browsertest.cc
index b8a3e81f925..71a1920071d 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_pan_tilt_zoom_browsertest.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_pan_tilt_zoom_browsertest.cc
@@ -5,6 +5,7 @@
#include <string>
#include "base/strings/stringprintf.h"
+#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
#include "chrome/browser/media/webrtc/webrtc_browsertest_base.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
@@ -70,34 +71,262 @@ INSTANTIATE_TEST_SUITE_P(
RequestPanTiltZoomPermission,
WebRtcPanTiltZoomBrowserTest,
testing::Values(
+ // no pan, tilt, zoom in audio and video constraints
TestConfig{"{ video: true }", "prompt", "granted", "prompt"},
TestConfig{"{ audio: true }", "granted", "prompt", "prompt"},
TestConfig{"{ audio: true, video: true }", "granted", "granted",
"prompt"},
- TestConfig{"{ video: { pan : {} } }", "prompt", "granted", "prompt"},
- TestConfig{"{ video: { tilt : {} } }", "prompt", "granted", "prompt"},
- TestConfig{"{ video: { zoom : {} } }", "prompt", "granted", "prompt"},
- TestConfig{"{ video: { advanced: [{ pan : {} }] } }", "prompt",
- "granted", "prompt"},
- TestConfig{"{ video: { advanced: [{ tilt : {} }] } }", "prompt",
- "granted", "prompt"},
- TestConfig{"{ video: { advanced: [{ zoom : {} }] } }", "prompt",
- "granted", "prompt"},
+ // pan, tilt, zoom in audio constraints
+ TestConfig{"{ audio: { pan : false } }", "granted", "prompt", "prompt"},
+ TestConfig{"{ audio: { tilt : false } }", "granted", "prompt",
+ "prompt"},
+ TestConfig{"{ audio: { zoom : false } }", "granted", "prompt",
+ "prompt"},
TestConfig{"{ audio: { pan : {} } }", "granted", "prompt", "prompt"},
TestConfig{"{ audio: { tilt : {} } }", "granted", "prompt", "prompt"},
TestConfig{"{ audio: { zoom : {} } }", "granted", "prompt", "prompt"},
+ TestConfig{"{ audio: { pan : 1 } }", "granted", "prompt", "prompt"},
+ TestConfig{"{ audio: { tilt : 1 } }", "granted", "prompt", "prompt"},
+ TestConfig{"{ audio: { zoom : 1 } }", "granted", "prompt", "prompt"},
+ TestConfig{"{ audio: { pan : true } }", "granted", "prompt", "prompt"},
+ TestConfig{"{ audio: { tilt : true } }", "granted", "prompt", "prompt"},
+ TestConfig{"{ audio: { zoom : true } }", "granted", "prompt", "prompt"},
+ // pan, tilt, zoom in basic video constraints if no audio
+ TestConfig{"{ video: { pan : false } }", "prompt", "granted", "prompt"},
+ TestConfig{"{ video: { tilt : false } }", "prompt", "granted",
+ "prompt"},
+ TestConfig{"{ video: { zoom : false } }", "prompt", "granted",
+ "prompt"},
+ TestConfig{"{ video: { pan : {} } }", "prompt", "granted", "granted"},
+ TestConfig{"{ video: { tilt : {} } }", "prompt", "granted", "granted"},
+ TestConfig{"{ video: { zoom : {} } }", "prompt", "granted", "granted"},
TestConfig{"{ video: { pan : 1 } }", "prompt", "granted", "granted"},
TestConfig{"{ video: { tilt : 1 } }", "prompt", "granted", "granted"},
TestConfig{"{ video: { zoom : 1 } }", "prompt", "granted", "granted"},
+ TestConfig{"{ video: { pan : true } }", "prompt", "granted", "granted"},
+ TestConfig{"{ video: { tilt : true } }", "prompt", "granted",
+ "granted"},
+ TestConfig{"{ video: { zoom : true } }", "prompt", "granted",
+ "granted"},
+ // pan, tilt, zoom in advanced video constraints if no audio
+ TestConfig{"{ video: { advanced: [{ pan : false }] } }", "prompt",
+ "granted", "prompt"},
+ TestConfig{"{ video: { advanced: [{ tilt : false }] } }", "prompt",
+ "granted", "prompt"},
+ TestConfig{"{ video: { advanced: [{ zoom : false }] } }", "prompt",
+ "granted", "prompt"},
+ TestConfig{"{ video: { advanced: [{ pan : {} }] } }", "prompt",
+ "granted", "granted"},
+ TestConfig{"{ video: { advanced: [{ tilt : {} }] } }", "prompt",
+ "granted", "granted"},
+ TestConfig{"{ video: { advanced: [{ zoom : {} }] } }", "prompt",
+ "granted", "granted"},
TestConfig{"{ video: { advanced: [{ pan : 1 }] } }", "prompt",
"granted", "granted"},
TestConfig{"{ video: { advanced: [{ tilt : 1 }] } }", "prompt",
"granted", "granted"},
TestConfig{"{ video: { advanced: [{ zoom : 1 }] } }", "prompt",
"granted", "granted"},
+ TestConfig{"{ video: { advanced: [{ pan : true }] } }", "prompt",
+ "granted", "granted"},
+ TestConfig{"{ video: { advanced: [{ tilt : true }] } }", "prompt",
+ "granted", "granted"},
+ TestConfig{"{ video: { advanced: [{ zoom : true }] } }", "prompt",
+ "granted", "granted"},
+ // pan, tilt, zoom in basic video constraints if audio
+ TestConfig{"{ audio: true, video: { pan : false } }", "granted",
+ "granted", "prompt"},
+ TestConfig{"{ audio: true, video: { tilt : false } }", "granted",
+ "granted", "prompt"},
+ TestConfig{"{ audio: true, video: { zoom : false } }", "granted",
+ "granted", "prompt"},
+ TestConfig{"{ audio: true, video: { pan : {} } }", "granted", "granted",
+ "granted"},
+ TestConfig{"{ audio: true, video: { tilt : {} } }", "granted",
+ "granted", "granted"},
+ TestConfig{"{ audio: true, video: { zoom : {} } }", "granted",
+ "granted", "granted"},
TestConfig{"{ audio: true, video: { pan : 1 } }", "granted", "granted",
"granted"},
TestConfig{"{ audio: true, video: { tilt : 1 } }", "granted", "granted",
"granted"},
TestConfig{"{ audio: true, video: { zoom : 1 } }", "granted", "granted",
- "granted"}));
+ "granted"},
+ TestConfig{"{ audio: true, video: { pan : true } }", "granted",
+ "granted", "granted"},
+ TestConfig{"{ audio: true, video: { tilt : true } }", "granted",
+ "granted", "granted"},
+ TestConfig{"{ audio: true, video: { zoom : true } }", "granted",
+ "granted", "granted"},
+ // pan, tilt, zoom in advanced video constraints if audio
+ TestConfig{"{ audio: true, video: { advanced: [{ pan : false }] } }",
+ "granted", "granted", "prompt"},
+ TestConfig{"{ audio: true, video: { advanced: [{ tilt : false }] } }",
+ "granted", "granted", "prompt"},
+ TestConfig{"{ audio: true, video: { advanced: [{ zoom : false }] } }",
+ "granted", "granted", "prompt"},
+ TestConfig{"{ audio: true, video: { advanced: [{ pan : {} }] } }",
+ "granted", "granted", "granted"},
+ TestConfig{"{ audio: true, video: { advanced: [{ tilt : {} }] } }",
+ "granted", "granted", "granted"},
+ TestConfig{"{ audio: true, video: { advanced: [{ zoom : {} }] } }",
+ "granted", "granted", "granted"},
+ TestConfig{"{ audio: true, video: { advanced: [{ pan : 1 }] } }",
+ "granted", "granted", "granted"},
+ TestConfig{"{ audio: true, video: { advanced: [{ tilt : 1 }] } }",
+ "granted", "granted", "granted"},
+ TestConfig{"{ audio: true, video: { advanced: [{ zoom : 1 }] } }",
+ "granted", "granted", "granted"},
+ TestConfig{"{ audio: true, video: { advanced: [{ pan : true }] } }",
+ "granted", "granted", "granted"},
+ TestConfig{"{ audio: true, video: { advanced: [{ tilt : true }] } }",
+ "granted", "granted", "granted"},
+ TestConfig{"{ audio: true, video: { advanced: [{ zoom : true }] } }",
+ "granted", "granted", "granted"}));
+
+class WebRtcPanTiltZoomPermissionRequestBrowserTest
+ : public WebRtcTestBase,
+ public ::testing::WithParamInterface<
+ bool /* IsPanTiltZoomSupported() */> {
+ public:
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ command_line->AppendSwitchASCII(
+ switches::kEnableBlinkFeatures,
+ "MediaCapturePanTilt,PermissionsRequestRevoke");
+ }
+
+ bool IsPanTiltZoomSupported() const { return GetParam(); }
+
+ void SetUpOnMainThread() override {
+ WebRtcTestBase::SetUpOnMainThread();
+
+ blink::MediaStreamDevices video_devices;
+ blink::MediaStreamDevice fake_video_device(
+ blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE, "fake_video_dev",
+ "Fake Video Device", media::MEDIA_VIDEO_FACING_NONE, base::nullopt,
+ IsPanTiltZoomSupported());
+ video_devices.push_back(fake_video_device);
+ MediaCaptureDevicesDispatcher::GetInstance()->SetTestVideoCaptureDevices(
+ video_devices);
+ }
+
+ void SetUpInProcessBrowserTestFixture() override {
+ DetectErrorsInJavaScript();
+ }
+};
+
+IN_PROC_BROWSER_TEST_P(WebRtcPanTiltZoomPermissionRequestBrowserTest,
+ TestRequestPanTiltZoomPermission) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage);
+
+ std::string result;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ tab->GetMainFrame(), "runRequestPanTiltZoom();", &result));
+ EXPECT_EQ(result, "runRequestPanTiltZoom-success");
+
+ std::string camera;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ tab->GetMainFrame(), "getCameraPermission();", &camera));
+ EXPECT_EQ(camera, "granted");
+
+ std::string pan_tilt_zoom;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ tab->GetMainFrame(), "getPanTiltZoomPermission();", &pan_tilt_zoom));
+ EXPECT_EQ(pan_tilt_zoom, IsPanTiltZoomSupported() ? "granted" : "prompt");
+}
+
+INSTANTIATE_TEST_SUITE_P(RequestPanTiltZoomPermission,
+ WebRtcPanTiltZoomPermissionRequestBrowserTest,
+ ::testing::Bool() /* IsPanTiltZoomSupported() */);
+
+class WebRtcPanTiltZoomCameraDevicesBrowserTest : public WebRtcTestBase {
+ public:
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ command_line->AppendSwitchASCII(
+ switches::kEnableBlinkFeatures,
+ "MediaCapturePanTilt,PermissionsRequestRevoke");
+ }
+
+ void SetVideoCaptureDevice(bool pan_tilt_zoom_supported) {
+ blink::MediaStreamDevices video_devices;
+ blink::MediaStreamDevice fake_video_device(
+ blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE, "fake_video_dev",
+ "Fake Video Device", media::MEDIA_VIDEO_FACING_NONE, base::nullopt,
+ pan_tilt_zoom_supported);
+ video_devices.push_back(fake_video_device);
+ MediaCaptureDevicesDispatcher::GetInstance()->SetTestVideoCaptureDevices(
+ video_devices);
+ }
+
+ void SetUpInProcessBrowserTestFixture() override {
+ DetectErrorsInJavaScript();
+ }
+};
+
+IN_PROC_BROWSER_TEST_F(WebRtcPanTiltZoomCameraDevicesBrowserTest,
+ TestCameraPanTiltZoomPermissionIsNotGrantedAfterCamera) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage);
+
+ // Simulate camera device with no PTZ support and request PTZ camera
+ // permission.
+ SetVideoCaptureDevice(false /* pan_tilt_zoom_supported */);
+ std::string result;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ tab->GetMainFrame(), "runRequestPanTiltZoom();", &result));
+ EXPECT_EQ(result, "runRequestPanTiltZoom-success");
+
+ // Camera permission should be granted.
+ std::string camera;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ tab->GetMainFrame(), "getCameraPermission();", &camera));
+ EXPECT_EQ(camera, "granted");
+
+ // Camera PTZ permission should not be granted.
+ std::string pan_tilt_zoom;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ tab->GetMainFrame(), "getPanTiltZoomPermission();", &pan_tilt_zoom));
+ EXPECT_EQ(pan_tilt_zoom, "prompt");
+
+ // Simulate camera device with PTZ support.
+ SetVideoCaptureDevice(true /* pan_tilt_zoom_supported */);
+
+ // Camera PTZ permission should still not be granted.
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ tab->GetMainFrame(), "getPanTiltZoomPermission();", &pan_tilt_zoom));
+ EXPECT_EQ(pan_tilt_zoom, "prompt");
+}
+
+IN_PROC_BROWSER_TEST_F(WebRtcPanTiltZoomCameraDevicesBrowserTest,
+ TestCameraPanTiltZoomPermissionPersists) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage);
+
+ // Simulate camera device with PTZ support and request PTZ camera permission.
+ SetVideoCaptureDevice(true /* pan_tilt_zoom_supported */);
+ std::string result;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ tab->GetMainFrame(), "runRequestPanTiltZoom();", &result));
+ EXPECT_EQ(result, "runRequestPanTiltZoom-success");
+
+ // Camera permission should be granted.
+ std::string camera;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ tab->GetMainFrame(), "getCameraPermission();", &camera));
+ EXPECT_EQ(camera, "granted");
+
+ // Camera PTZ permission should be granted.
+ std::string pan_tilt_zoom;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ tab->GetMainFrame(), "getPanTiltZoomPermission();", &pan_tilt_zoom));
+ EXPECT_EQ(pan_tilt_zoom, "granted");
+
+ // Simulate camera device with no PTZ support.
+ SetVideoCaptureDevice(false /* pan_tilt_zoom_supported */);
+
+ // Camera PTZ permission should still be granted.
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ tab->GetMainFrame(), "getPanTiltZoomPermission();", &pan_tilt_zoom));
+ EXPECT_EQ(pan_tilt_zoom, "granted");
+}
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.cc b/chromium/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.cc
index 1bc27e2a6d9..1216bac21f6 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_rtp_dump_handler.cc
@@ -64,15 +64,13 @@ WebRtcRtpDumpHandler::~WebRtcRtpDumpHandler() {
if (incoming_state_ != STATE_NONE && !incoming_dump_path_.empty()) {
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
- base::BindOnce(base::IgnoreResult(&base::DeleteFile),
- incoming_dump_path_, false));
+ base::BindOnce(base::GetDeleteFileCallback(), incoming_dump_path_));
}
if (outgoing_state_ != STATE_NONE && !outgoing_dump_path_.empty()) {
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
- base::BindOnce(base::IgnoreResult(&base::DeleteFile),
- outgoing_dump_path_, false));
+ base::BindOnce(base::GetDeleteFileCallback(), outgoing_dump_path_));
}
}
@@ -295,8 +293,7 @@ void WebRtcRtpDumpHandler::OnDumpEnded(const base::Closure& callback,
if (!incoming_success) {
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
- base::BindOnce(base::IgnoreResult(&base::DeleteFile),
- incoming_dump_path_, false));
+ base::BindOnce(base::GetDeleteFileCallback(), incoming_dump_path_));
DVLOG(2) << "Deleted invalid incoming dump "
<< incoming_dump_path_.value();
@@ -311,8 +308,7 @@ void WebRtcRtpDumpHandler::OnDumpEnded(const base::Closure& callback,
if (!outgoing_success) {
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
- base::BindOnce(base::IgnoreResult(&base::DeleteFile),
- outgoing_dump_path_, false));
+ base::BindOnce(base::GetDeleteFileCallback(), outgoing_dump_path_));
DVLOG(2) << "Deleted invalid outgoing dump "
<< outgoing_dump_path_.value();
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_rtp_dump_handler_unittest.cc b/chromium/chrome/browser/media/webrtc/webrtc_rtp_dump_handler_unittest.cc
index 01c742b0968..0be8f897037 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_rtp_dump_handler_unittest.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_rtp_dump_handler_unittest.cc
@@ -14,6 +14,7 @@
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/location.h"
+#include "base/logging.h"
#include "base/run_loop.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_simulcast_browsertest.cc b/chromium/chrome/browser/media/webrtc/webrtc_simulcast_browsertest.cc
deleted file mode 100644
index b98d937895c..00000000000
--- a/chromium/chrome/browser/media/webrtc/webrtc_simulcast_browsertest.cc
+++ /dev/null
@@ -1,66 +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/command_line.h"
-#include "base/files/file_path.h"
-#include "base/path_service.h"
-#include "build/build_config.h"
-#include "chrome/browser/media/webrtc/webrtc_browsertest_base.h"
-#include "chrome/browser/media/webrtc/webrtc_browsertest_common.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/browser/ui/browser_tabstrip.h"
-#include "chrome/browser/ui/tabs/tab_strip_model.h"
-#include "chrome/common/chrome_switches.h"
-#include "chrome/test/base/in_process_browser_test.h"
-#include "chrome/test/base/ui_test_utils.h"
-#include "content/public/browser/notification_service.h"
-#include "content/public/browser/render_process_host.h"
-#include "content/public/common/content_switches.h"
-#include "content/public/test/browser_test.h"
-#include "content/public/test/browser_test_utils.h"
-#include "media/base/media_switches.h"
-#include "net/test/embedded_test_server/embedded_test_server.h"
-#include "testing/perf/perf_test.h"
-#include "ui/gl/gl_switches.h"
-
-static const char kSimulcastTestPage[] = "/webrtc/webrtc-simulcast.html";
-
-// Simulcast integration test. This test ensures 'a=x-google-flag:conference'
-// is working and that Chrome is capable of sending simulcast streams.
-class WebRtcSimulcastBrowserTest : public WebRtcTestBase {
- public:
- // TODO(phoglund): Make it possible to enable DetectErrorsInJavaScript() here.
-
- void SetUpCommandLine(base::CommandLine* command_line) override {
- // Just answer 'allow' to GetUserMedia invocations.
- command_line->AppendSwitch(switches::kUseFakeUIForMediaStream);
-
- // The video playback will not work without a GPU, so force its use here.
- command_line->AppendSwitch(switches::kUseGpuInTests);
- }
-};
-
-// Fails/times out on Windows and Chrome OS. Flaky on Mac and Linux.
-// http://crbug.com/452623
-// http://crbug.com/1004546
-// MSan reports errors. http://crbug.com/452892
-#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \
- defined(MEMORY_SANITIZER)
-#define MAYBE_TestVgaReturnsTwoSimulcastStreams DISABLED_TestVgaReturnsTwoSimulcastStreams
-#else
-#define MAYBE_TestVgaReturnsTwoSimulcastStreams TestVgaReturnsTwoSimulcastStreams
-#endif
-IN_PROC_BROWSER_TEST_F(WebRtcSimulcastBrowserTest,
- MAYBE_TestVgaReturnsTwoSimulcastStreams) {
- ASSERT_TRUE(embedded_test_server()->Start());
-
- ui_test_utils::NavigateToURL(
- browser(), embedded_test_server()->GetURL(kSimulcastTestPage));
-
- content::WebContents* tab_contents =
- browser()->tab_strip_model()->GetActiveWebContents();
-
- ASSERT_EQ("OK", ExecuteJavascript("testVgaReturnsTwoSimulcastStreams()",
- tab_contents));
-}
diff --git a/chromium/chrome/browser/media/webrtc/webrtc_text_log_handler.cc b/chromium/chrome/browser/media/webrtc/webrtc_text_log_handler.cc
index dd27ecc5f0f..0185766cf85 100644
--- a/chromium/chrome/browser/media/webrtc/webrtc_text_log_handler.cc
+++ b/chromium/chrome/browser/media/webrtc/webrtc_text_log_handler.cc
@@ -19,7 +19,6 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
-#include "base/task/post_task.h"
#include "base/time/time.h"
#include "chrome/common/channel_info.h"
#include "chrome/common/media/webrtc_logging.mojom.h"
@@ -249,8 +248,8 @@ bool WebRtcTextLogHandler::StopLogging(const GenericDoneCallback& callback) {
stop_callback_ = callback;
logging_state_ = STOPPING;
- base::PostTask(FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&content::WebRtcLog::ClearLogMessageCallback,
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&content::WebRtcLog::ClearLogMessageCallback,
render_process_id_));
return true;
}
@@ -281,8 +280,8 @@ void WebRtcTextLogHandler::StopDone() {
void WebRtcTextLogHandler::ChannelClosing() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (logging_state_ == STARTING || logging_state_ == STARTED) {
- base::PostTask(FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&content::WebRtcLog::ClearLogMessageCallback,
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&content::WebRtcLog::ClearLogMessageCallback,
render_process_id_));
}
channel_is_closing_ = true;
@@ -528,8 +527,8 @@ void WebRtcTextLogHandler::OnGetNetworkInterfaceList(
&ForwardMessageViaTaskRunner, base::SequencedTaskRunnerHandle::Get(),
base::Bind(&WebRtcTextLogHandler::LogMessage,
weak_factory_.GetWeakPtr()));
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&content::WebRtcLog::SetLogMessageCallback,
render_process_id_, std::move(log_message_callback)));
}
diff --git a/chromium/chrome/browser/media/webrtc/window_icon_util_x11.cc b/chromium/chrome/browser/media/webrtc/window_icon_util_x11.cc
index 272d0109da6..ecc942559cd 100644
--- a/chromium/chrome/browser/media/webrtc/window_icon_util_x11.cc
+++ b/chromium/chrome/browser/media/webrtc/window_icon_util_x11.cc
@@ -13,29 +13,9 @@
gfx::ImageSkia GetWindowIcon(content::DesktopMediaID id) {
DCHECK(id.type == content::DesktopMediaID::TYPE_WINDOW);
- Display* display = gfx::GetXDisplay();
- Atom property = gfx::GetAtom("_NET_WM_ICON");
- Atom actual_type;
- int actual_format;
- unsigned long bytes_after; // NOLINT: type required by XGetWindowProperty
- unsigned long size;
- long* data;
-
- // The |error_tracker| essentially provides an empty X error handler for
- // the call of XGetWindowProperty. The motivation is to guard against crash
- // for any reason that XGetWindowProperty fails. For example, at the time that
- // XGetWindowProperty is called, the window handler (a.k.a |id.id|) may
- // already be invalid due to the fact that the end user has closed the
- // corresponding window, etc.
- std::unique_ptr<gfx::X11ErrorTracker> error_tracker(
- new gfx::X11ErrorTracker());
- int status = XGetWindowProperty(display, id.id, property, 0L, ~0L, x11::False,
- AnyPropertyType, &actual_type, &actual_format,
- &size, &bytes_after,
- reinterpret_cast<unsigned char**>(&data));
- error_tracker.reset();
-
- if (status != x11::Success) {
+ std::vector<uint32_t> data;
+ if (!ui::GetArrayProperty(static_cast<x11::Window>(id.id),
+ gfx::GetAtom("_NET_WM_ICON"), &data)) {
return gfx::ImageSkia();
}
@@ -45,10 +25,10 @@ gfx::ImageSkia GetWindowIcon(content::DesktopMediaID id) {
int width = 0;
int height = 0;
int start = 0;
- int i = 0;
- while (i + 1 < static_cast<int>(size)) {
+ size_t i = 0;
+ while (i + 1 < data.size()) {
if ((i == 0 || static_cast<int>(data[i] * data[i + 1]) > width * height) &&
- (i + 1 + data[i] * data[i + 1] < static_cast<int>(size))) {
+ (i + 1 + data[i] * data[i + 1] < data.size())) {
width = static_cast<int>(data[i]);
height = static_cast<int>(data[i + 1]);
start = i + 2;
@@ -69,6 +49,5 @@ gfx::ImageSkia GetWindowIcon(content::DesktopMediaID id) {
}
}
- XFree(data);
return gfx::ImageSkia::CreateFrom1xBitmap(result);
}
diff --git a/chromium/chrome/browser/metrics/BUILD.gn b/chromium/chrome/browser/metrics/BUILD.gn
index 52838754894..cf98ddb782d 100644
--- a/chromium/chrome/browser/metrics/BUILD.gn
+++ b/chromium/chrome/browser/metrics/BUILD.gn
@@ -22,6 +22,10 @@ source_set("test_support") {
if (!is_fuchsia) {
deps += [ "//chrome/test:sync_integration_test_support" ]
}
+
+ if (is_android) {
+ deps += [ "//content/public/browser" ]
+ }
}
generate_expired_histograms_array("expired_histograms_array") {
diff --git a/chromium/chrome/browser/nearby_sharing/certificates/BUILD.gn b/chromium/chrome/browser/nearby_sharing/certificates/BUILD.gn
new file mode 100644
index 00000000000..0ecdcfb35f9
--- /dev/null
+++ b/chromium/chrome/browser/nearby_sharing/certificates/BUILD.gn
@@ -0,0 +1,61 @@
+# Copyright (c) 2020 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+source_set("certificates") {
+ sources = [
+ "common.cc",
+ "common.h",
+ "constants.cc",
+ "constants.h",
+ "nearby_share_decrypted_public_certificate.cc",
+ "nearby_share_decrypted_public_certificate.h",
+ "nearby_share_encrypted_metadata_key.cc",
+ "nearby_share_encrypted_metadata_key.h",
+ "nearby_share_private_certificate.cc",
+ "nearby_share_private_certificate.h",
+ "nearby_share_visibility.h",
+ ]
+
+ deps = [
+ "//base",
+ "//chrome/browser/nearby_sharing/proto",
+ "//crypto",
+ ]
+}
+
+source_set("test_support") {
+ testonly = true
+
+ sources = [
+ "test_util.cc",
+ "test_util.h",
+ ]
+
+ deps = [
+ ":certificates",
+ "//base",
+ "//chrome/browser/nearby_sharing/proto",
+ "//crypto",
+ ]
+}
+
+source_set("unit_tests") {
+ testonly = true
+
+ sources = [
+ "common_unittest.cc",
+ "nearby_share_decrypted_public_certificate_unittest.cc",
+ "nearby_share_private_certificate_unittest.cc",
+ ]
+
+ deps = [
+ ":certificates",
+ ":test_support",
+ "//base",
+ "//base/test:test_support",
+ "//chrome/browser/nearby_sharing/proto",
+ "//crypto",
+ "//testing/gtest",
+ ]
+}
diff --git a/chromium/chrome/browser/nearby_sharing/logging/BUILD.gn b/chromium/chrome/browser/nearby_sharing/logging/BUILD.gn
new file mode 100644
index 00000000000..f8312772594
--- /dev/null
+++ b/chromium/chrome/browser/nearby_sharing/logging/BUILD.gn
@@ -0,0 +1,24 @@
+# Copyright 2020 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+source_set("logging") {
+ sources = [
+ "log_buffer.cc",
+ "log_buffer.h",
+ "logging.cc",
+ "logging.h",
+ ]
+ deps = [ "//base" ]
+}
+
+source_set("unit_tests") {
+ testonly = true
+ sources = [ "logging_unittest.cc" ]
+
+ deps = [
+ ":logging",
+ "//base/test:test_support",
+ "//testing/gtest",
+ ]
+}
diff --git a/chromium/chrome/browser/nearby_sharing/proto/BUILD.gn b/chromium/chrome/browser/nearby_sharing/proto/BUILD.gn
new file mode 100644
index 00000000000..a5be23229fc
--- /dev/null
+++ b/chromium/chrome/browser/nearby_sharing/proto/BUILD.gn
@@ -0,0 +1,17 @@
+# Copyright 2020 The Chromium 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 = [
+ "certificate_rpc.proto",
+ "contact_rpc.proto",
+ "device_rpc.proto",
+ "encrypted_metadata.proto",
+ "field_mask.proto",
+ "rpc_resources.proto",
+ "timestamp.proto",
+ ]
+}
diff --git a/chromium/chrome/browser/enterprise/connectors/BUILD.gn b/chromium/chrome/browser/nearby_sharing/tachyon/proto/BUILD.gn
index eaa74100bec..353a29773de 100644
--- a/chromium/chrome/browser/enterprise/connectors/BUILD.gn
+++ b/chromium/chrome/browser/nearby_sharing/tachyon/proto/BUILD.gn
@@ -4,6 +4,13 @@
import("//third_party/protobuf/proto_library.gni")
-proto_library("connectors_proto") {
- sources = [ "connectors.proto" ]
+group("proto_lite") {
+ public_deps = [
+ ":proto",
+ "//third_party/protobuf:protobuf_lite",
+ ]
+}
+
+proto_library("proto") {
+ sources = [ "tachyon.proto" ]
}
diff --git a/chromium/chrome/browser/net/BUILD.gn b/chromium/chrome/browser/net/BUILD.gn
index 0a05d7789d2..895aa8bb958 100644
--- a/chromium/chrome/browser/net/BUILD.gn
+++ b/chromium/chrome/browser/net/BUILD.gn
@@ -4,6 +4,16 @@
import("//third_party/protobuf/proto_library.gni")
+if (is_android) {
+ import("//build/config/android/rules.gni")
+}
+
proto_library("probe_message_proto") {
sources = [ "probe_message.proto" ]
}
+
+if (is_android) {
+ java_cpp_enum("secure_dns_management_mode_generated_enum") {
+ sources = [ "secure_dns_config.h" ]
+ }
+}
diff --git a/chromium/chrome/browser/net/cert_verify_proc_browsertest.cc b/chromium/chrome/browser/net/cert_verify_proc_browsertest.cc
index 9ff2548e2cc..e86c8251662 100644
--- a/chromium/chrome/browser/net/cert_verify_proc_browsertest.cc
+++ b/chromium/chrome/browser/net/cert_verify_proc_browsertest.cc
@@ -7,12 +7,14 @@
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_reader.h"
+#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/test/browser_test.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
+#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/network_switches.h"
#if defined(OS_ANDROID)
@@ -83,8 +85,20 @@ class NetLogPlatformBrowserTestBase : public PlatformBrowserTest {
// This is an integration test to ensure that CertVerifyProc netlog events
// continue to be logged once cert verification is moved out of the network
// service process. (See crbug.com/1015134 and crbug.com/1040681.)
-class CertVerifyProcNetLogBrowserTest : public NetLogPlatformBrowserTestBase {
+class CertVerifyProcNetLogBrowserTest
+ : public NetLogPlatformBrowserTestBase,
+ public testing::WithParamInterface<bool> {
public:
+ void SetUpInProcessBrowserTestFixture() override {
+ if (GetParam()) {
+ scoped_feature_list_.InitAndEnableFeature(
+ network::features::kCertVerifierService);
+ } else {
+ scoped_feature_list_.InitAndDisableFeature(
+ network::features::kCertVerifierService);
+ }
+ }
+
void SetUpOnMainThread() override {
PlatformBrowserTest::SetUpOnMainThread();
@@ -129,10 +143,11 @@ class CertVerifyProcNetLogBrowserTest : public NetLogPlatformBrowserTestBase {
const std::string kTestHost = "netlog-example.a.test";
protected:
+ base::test::ScopedFeatureList scoped_feature_list_;
net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS};
};
-IN_PROC_BROWSER_TEST_F(CertVerifyProcNetLogBrowserTest, Test) {
+IN_PROC_BROWSER_TEST_P(CertVerifyProcNetLogBrowserTest, Test) {
ASSERT_TRUE(https_server_.Start());
// Request using a unique host name to ensure that the cert verification wont
@@ -150,3 +165,7 @@ IN_PROC_BROWSER_TEST_F(CertVerifyProcNetLogBrowserTest, Test) {
base::RunLoop().RunUntilIdle();
content::FlushNetworkServiceInstanceForTesting();
}
+
+INSTANTIATE_TEST_SUITE_P(CertVerifierService,
+ CertVerifyProcNetLogBrowserTest,
+ ::testing::Bool());
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 1347508594b..99dfc4126b0 100644
--- a/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc
+++ b/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc
@@ -12,6 +12,7 @@
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
+#include "chrome/browser/service_sandbox_type.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"
@@ -24,10 +25,6 @@
#include "services/strings/grit/services_strings.h"
#endif
-#if defined(OS_WIN)
-#include "services/service_manager/sandbox/sandbox_type.h"
-#endif
-
namespace {
proxy_resolver::mojom::ProxyResolverFactory* GetProxyResolverFactory() {
@@ -47,9 +44,6 @@ proxy_resolver::mojom::ProxyResolverFactory* GetProxyResolverFactory() {
remote->BindNewPipeAndPassReceiver(),
content::ServiceProcessHost::Options()
.WithDisplayName(IDS_PROXY_RESOLVER_DISPLAY_NAME)
-#if defined(OS_WIN)
- .WithSandboxType(service_manager::SandboxType::kProxyResolver)
-#endif
.Pass());
// The service will report itself idle once there are no more bound
diff --git a/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory_browsertest.cc b/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory_browsertest.cc
index 0fee3b8c2fb..7c38448c971 100644
--- a/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory_browsertest.cc
+++ b/chromium/chrome/browser/net/chrome_mojo_proxy_resolver_factory_browsertest.cc
@@ -13,7 +13,6 @@
#include "base/process/process.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
-#include "base/task/post_task.h"
#include "base/test/bind_test_util.h"
#include "base/time/time.h"
#include "chrome/test/base/in_process_browser_test.h"
@@ -158,8 +157,8 @@ IN_PROC_BROWSER_TEST_F(ChromeMojoProxyResolverFactoryBrowserTest,
// Wait a little bit and check it's still running.
{
base::RunLoop run_loop;
- base::PostDelayedTask(FROM_HERE, {content::BrowserThread::UI},
- run_loop.QuitClosure(), kServiceShutdownTimeout);
+ content::GetUIThreadTaskRunner({})->PostDelayedTask(
+ FROM_HERE, run_loop.QuitClosure(), kServiceShutdownTimeout);
run_loop.Run();
}
@@ -202,8 +201,8 @@ IN_PROC_BROWSER_TEST_F(ChromeMojoProxyResolverFactoryBrowserTest,
// Wait a little bit and check it's still running.
{
base::RunLoop run_loop;
- base::PostDelayedTask(FROM_HERE, {content::BrowserThread::UI},
- run_loop.QuitClosure(), kServiceShutdownTimeout);
+ content::GetUIThreadTaskRunner({})->PostDelayedTask(
+ FROM_HERE, run_loop.QuitClosure(), kServiceShutdownTimeout);
run_loop.Run();
}
diff --git a/chromium/chrome/browser/net/chrome_network_service_browsertest.cc b/chromium/chrome/browser/net/chrome_network_service_browsertest.cc
index 9ecc8c269a7..9092b2ddb9f 100644
--- a/chromium/chrome/browser/net/chrome_network_service_browsertest.cc
+++ b/chromium/chrome/browser/net/chrome_network_service_browsertest.cc
@@ -16,6 +16,7 @@
#include "content/public/test/browser_test.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
+#include "net/cookies/cookie_inclusion_status.h"
#include "net/cookies/cookie_util.h"
#include "net/extras/sqlite/cookie_crypto_delegate.h"
#include "services/network/public/cpp/features.h"
@@ -53,9 +54,7 @@ void SetCookie(
cookie, net::cookie_util::SimulatedCookieSource(cookie, "https"),
net::CookieOptions(),
base::BindLambdaForTesting(
- [&](net::CanonicalCookie::CookieInclusionStatus status) {
- run_loop.Quit();
- }));
+ [&](net::CookieInclusionStatus status) { run_loop.Quit(); }));
run_loop.Run();
}
@@ -89,6 +88,8 @@ class ChromeNetworkServiceBrowserTest
context_params->enable_encrypted_cookies = enable_encrypted_cookies;
context_params->cookie_path =
browser()->profile()->GetPath().Append(FILE_PATH_LITERAL("cookies"));
+ context_params->cert_verifier_params = content::GetCertVerifierParams(
+ network::mojom::CertVerifierCreationParams::New());
GetNetworkService()->CreateNetworkContext(
network_context.InitWithNewPipeAndPassReceiver(),
std::move(context_params));
diff --git a/chromium/chrome/browser/net/cookie_policy_browsertest.cc b/chromium/chrome/browser/net/cookie_policy_browsertest.cc
index d00770b46bc..de6dc9dcba7 100644
--- a/chromium/chrome/browser/net/cookie_policy_browsertest.cc
+++ b/chromium/chrome/browser/net/cookie_policy_browsertest.cc
@@ -9,6 +9,7 @@
#include "base/strings/stringprintf.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/content_settings/cookie_settings_factory.h"
+#include "chrome/browser/net/storage_test_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
@@ -33,15 +34,6 @@ using content::BrowserThread;
namespace {
-const std::vector<std::string> kStorageTypes{
- "Cookie", "LocalStorage", "FileSystem", "SessionStorage", "IndexedDb",
- "WebSql", "CacheStorage", "ServiceWorker", "CookieStore"};
-
-const std::vector<std::string> kCrossTabCommunicationTypes{
- "SharedWorker",
- "WebLock",
-};
-
class CookiePolicyBrowserTest : public InProcessBrowserTest {
protected:
CookiePolicyBrowserTest()
@@ -64,6 +56,11 @@ class CookiePolicyBrowserTest : public InProcessBrowserTest {
"CookieStoreDocument");
}
+ GURL GetURL(const std::string& host) {
+ GURL url(https_server_.GetURL(host, "/"));
+ return url;
+ }
+
void SetBlockThirdPartyCookies(bool value) {
browser()->profile()->GetPrefs()->SetBoolean(prefs::kBlockThirdPartyCookies,
value);
@@ -89,12 +86,7 @@ class CookiePolicyBrowserTest : public InProcessBrowserTest {
}
void ExpectFrameContent(const std::string& expected) {
- std::string content;
- ASSERT_TRUE(ExecuteScriptAndExtractString(
- GetFrame(),
- "window.domAutomationController.send(document.body.textContent)",
- &content));
- EXPECT_EQ(expected, content);
+ storage::test::ExpectFrameContent(GetFrame(), expected);
}
void NavigateNestedFrameTo(const std::string& host, const std::string& path) {
@@ -110,55 +102,7 @@ class CookiePolicyBrowserTest : public InProcessBrowserTest {
}
void ExpectNestedFrameContent(const std::string& expected) {
- std::string content;
- ASSERT_TRUE(ExecuteScriptAndExtractString(
- GetNestedFrame(),
- "window.domAutomationController.send(document.body.textContent)",
- &content));
- EXPECT_EQ(expected, content);
- }
-
- void ExpectCookiesOnHost(const std::string& host,
- const std::string& expected) {
- EXPECT_EQ(expected, content::GetCookies(browser()->profile(),
- https_server_.GetURL(host, "/")));
- }
-
- void SetStorageForFrame(content::RenderFrameHost* frame) {
- for (const auto& data_type : kStorageTypes) {
- bool data;
- EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
- frame, "set" + data_type + "()", &data));
- EXPECT_TRUE(data) << data_type;
- }
- }
-
- void ExpectStorageForFrame(content::RenderFrameHost* frame, bool expected) {
- for (const auto& data_type : kStorageTypes) {
- bool data;
- EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
- frame, "has" + data_type + "();", &data));
- EXPECT_EQ(expected, data) << data_type;
- }
- }
-
- void SetCrossTabInfoForFrame(content::RenderFrameHost* frame) {
- for (const auto& data_type : kCrossTabCommunicationTypes) {
- bool data;
- EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
- frame, "set" + data_type + "()", &data));
- EXPECT_TRUE(data) << data_type;
- }
- }
-
- void ExpectCrossTabInfoForFrame(content::RenderFrameHost* frame,
- bool expected) {
- for (const auto& data_type : kCrossTabCommunicationTypes) {
- bool data;
- EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
- frame, "has" + data_type + "();", &data));
- EXPECT_EQ(expected, data) << data_type;
- }
+ storage::test::ExpectFrameContent(GetNestedFrame(), expected);
}
content::RenderFrameHost* GetFrame() {
@@ -230,12 +174,13 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
NavigateToPageWithFrame("a.com");
- ExpectCookiesOnHost("b.com", "");
+ storage::test::ExpectCookiesOnHost(browser()->profile(), GetURL("b.com"), "");
// Navigate iframe to a cross-site, cookie-setting endpoint, and verify that
// the cookie is set:
NavigateFrameTo("b.com", "/set-cookie?thirdparty=1;SameSite=None;Secure");
- ExpectCookiesOnHost("b.com", "thirdparty=1");
+ storage::test::ExpectCookiesOnHost(browser()->profile(), GetURL("b.com"),
+ "thirdparty=1");
// Navigate iframe to a cross-site frame with a frame, and navigate _that_
// frame to a cross-site, cookie-setting endpoint, and verify that the cookie
@@ -245,7 +190,8 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
// is still cross-site.
NavigateNestedFrameTo("b.com",
"/set-cookie?thirdparty=2;SameSite=None;Secure");
- ExpectCookiesOnHost("b.com", "thirdparty=2");
+ storage::test::ExpectCookiesOnHost(browser()->profile(), GetURL("b.com"),
+ "thirdparty=2");
// Navigate iframe to a cross-site frame with a frame, and navigate _that_
// frame to a cross-site, cookie-setting endpoint, and verify that the cookie
@@ -253,7 +199,8 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
NavigateFrameTo("c.com", "/iframe.html");
NavigateNestedFrameTo("b.com",
"/set-cookie?thirdparty=3;SameSite=None;Secure");
- ExpectCookiesOnHost("b.com", "thirdparty=3");
+ storage::test::ExpectCookiesOnHost(browser()->profile(), GetURL("b.com"),
+ "thirdparty=3");
}
// This test does the same navigations as the test above, so we can be assured
@@ -269,7 +216,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
// Navigate iframe to a cross-site, cookie-setting endpoint, and verify that
// the cookie is not set:
NavigateFrameTo("b.com", "/set-cookie?thirdparty=1;SameSite=None;Secure");
- ExpectCookiesOnHost("b.com", "");
+ storage::test::ExpectCookiesOnHost(browser()->profile(), GetURL("b.com"), "");
// Navigate iframe to a cross-site frame with a frame, and navigate _that_
// frame to a cross-site, cookie-setting endpoint, and verify that the cookie
@@ -277,7 +224,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("b.com",
"/set-cookie?thirdparty=2;SameSite=None;Secure");
- ExpectCookiesOnHost("b.com", "");
+ storage::test::ExpectCookiesOnHost(browser()->profile(), GetURL("b.com"), "");
// Navigate iframe to a cross-site frame with a frame, and navigate _that_
// frame to a cross-site, cookie-setting endpoint, and verify that the cookie
@@ -285,7 +232,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
NavigateFrameTo("c.com", "/iframe.html");
NavigateNestedFrameTo("b.com",
"/set-cookie?thirdparty=3;SameSite=None;Secure");
- ExpectCookiesOnHost("b.com", "");
+ storage::test::ExpectCookiesOnHost(browser()->profile(), GetURL("b.com"), "");
}
IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
@@ -295,7 +242,8 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
// Set a cookie on `b.com`.
content::SetCookie(browser()->profile(), https_server_.GetURL("b.com", "/"),
"thirdparty=1;SameSite=None;Secure");
- ExpectCookiesOnHost("b.com", "thirdparty=1");
+ storage::test::ExpectCookiesOnHost(browser()->profile(), GetURL("b.com"),
+ "thirdparty=1");
NavigateToPageWithFrame("a.com");
@@ -330,7 +278,8 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
// Set a cookie on `b.com`.
content::SetCookie(browser()->profile(), https_server_.GetURL("b.com", "/"),
"thirdparty=1;SameSite=None;Secure");
- ExpectCookiesOnHost("b.com", "thirdparty=1");
+ storage::test::ExpectCookiesOnHost(browser()->profile(), GetURL("b.com"),
+ "thirdparty=1");
NavigateToPageWithFrame("a.com");
@@ -361,13 +310,15 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
// Set a cookie on `b.com`.
content::SetCookie(browser()->profile(), https_server_.GetURL("b.com", "/"),
"thirdparty=1;SameSite=None;Secure");
- ExpectCookiesOnHost("b.com", "thirdparty=1");
+ storage::test::ExpectCookiesOnHost(browser()->profile(), GetURL("b.com"),
+ "thirdparty=1");
// Set a cookie on othersite.com.
content::SetCookie(browser()->profile(),
https_server_.GetURL("othersite.com", "/"),
"thirdparty=other;SameSite=None;Secure");
- ExpectCookiesOnHost("othersite.com", "thirdparty=other");
+ storage::test::ExpectCookiesOnHost(
+ browser()->profile(), GetURL("othersite.com"), "thirdparty=other");
// Allow all requests to b.com to have cookies.
// On the other hand, othersite.com does not have an exception set for it.
@@ -416,7 +367,8 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
// Set a cookie on `b.com`.
content::SetCookie(browser()->profile(), https_server_.GetURL("b.com", "/"),
"thirdparty=1;SameSite=None;Secure");
- ExpectCookiesOnHost("b.com", "thirdparty=1");
+ storage::test::ExpectCookiesOnHost(browser()->profile(), GetURL("b.com"),
+ "thirdparty=1");
// Allow all requests on the top frame domain a.com to have cookies.
auto cookie_settings =
@@ -473,15 +425,15 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest,
IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, ThirdPartyIFrameStorage) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetFrame(), false);
- SetStorageForFrame(GetFrame());
- ExpectStorageForFrame(GetFrame(), true);
+ storage::test::ExpectStorageForFrame(GetFrame(), false);
+ storage::test::SetStorageForFrame(GetFrame());
+ storage::test::ExpectStorageForFrame(GetFrame(), true);
SetBlockThirdPartyCookies(true);
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetFrame(), false);
+ storage::test::ExpectStorageForFrame(GetFrame(), false);
// Allow all requests to b.com to access storage.
auto cookie_settings =
@@ -493,14 +445,14 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, ThirdPartyIFrameStorage) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetFrame(), true);
+ storage::test::ExpectStorageForFrame(GetFrame(), true);
// Remove ALLOW setting.
cookie_settings->ResetCookieSetting(b_url);
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetFrame(), false);
+ storage::test::ExpectStorageForFrame(GetFrame(), false);
// Allow all third-parties on a.com to access storage.
cookie_settings->SetThirdPartyCookieSetting(
@@ -508,7 +460,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, ThirdPartyIFrameStorage) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetFrame(), true);
+ storage::test::ExpectStorageForFrame(GetFrame(), true);
}
IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, NestedThirdPartyIFrameStorage) {
@@ -516,16 +468,16 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, NestedThirdPartyIFrameStorage) {
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("c.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetNestedFrame(), false);
- SetStorageForFrame(GetNestedFrame());
- ExpectStorageForFrame(GetNestedFrame(), true);
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), false);
+ storage::test::SetStorageForFrame(GetNestedFrame());
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), true);
SetBlockThirdPartyCookies(true);
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("c.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetNestedFrame(), false);
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), false);
// Allow all requests to b.com to access storage.
auto cookie_settings =
@@ -538,7 +490,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, NestedThirdPartyIFrameStorage) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("c.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetNestedFrame(), true);
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), true);
// Remove ALLOW setting.
cookie_settings->ResetCookieSetting(c_url);
@@ -546,7 +498,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, NestedThirdPartyIFrameStorage) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("c.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetNestedFrame(), false);
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), false);
// Allow all third-parties on a.com to access storage.
cookie_settings->SetThirdPartyCookieSetting(
@@ -555,7 +507,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, NestedThirdPartyIFrameStorage) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("c.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetNestedFrame(), true);
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), true);
}
IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, NestedFirstPartyIFrameStorage) {
@@ -563,16 +515,16 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, NestedFirstPartyIFrameStorage) {
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("a.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetNestedFrame(), false);
- SetStorageForFrame(GetNestedFrame());
- ExpectStorageForFrame(GetNestedFrame(), true);
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), false);
+ storage::test::SetStorageForFrame(GetNestedFrame());
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), true);
SetBlockThirdPartyCookies(true);
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("a.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetNestedFrame(), false);
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), false);
// Allow all requests to b.com to access storage.
auto cookie_settings =
@@ -584,7 +536,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, NestedFirstPartyIFrameStorage) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("a.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetNestedFrame(), true);
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), true);
// Remove ALLOW setting.
cookie_settings->ResetCookieSetting(a_url);
@@ -592,7 +544,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, NestedFirstPartyIFrameStorage) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("a.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetNestedFrame(), false);
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), false);
// Allow all third-parties on a.com to access storage.
cookie_settings->SetThirdPartyCookieSetting(
@@ -601,7 +553,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, NestedFirstPartyIFrameStorage) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("a.com", "/browsing_data/site_data.html");
- ExpectStorageForFrame(GetNestedFrame(), true);
+ storage::test::ExpectStorageForFrame(GetNestedFrame(), true);
}
// Test third-party cookie blocking of features that allow to communicate
@@ -610,20 +562,20 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, MultiTabTest) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetFrame(), false);
- SetCrossTabInfoForFrame(GetFrame());
- ExpectCrossTabInfoForFrame(GetFrame(), true);
+ storage::test::ExpectCrossTabInfoForFrame(GetFrame(), false);
+ storage::test::SetCrossTabInfoForFrame(GetFrame());
+ storage::test::ExpectCrossTabInfoForFrame(GetFrame(), true);
// Create a second tab to test communication between tabs.
NavigateToNewTabWithFrame("a.com");
NavigateFrameTo("b.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetFrame(), true);
+ storage::test::ExpectCrossTabInfoForFrame(GetFrame(), true);
SetBlockThirdPartyCookies(true);
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetFrame(), false);
+ storage::test::ExpectCrossTabInfoForFrame(GetFrame(), false);
// Allow all requests to b.com to access cookies.
auto cookie_settings =
@@ -635,14 +587,14 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, MultiTabTest) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetFrame(), true);
+ storage::test::ExpectCrossTabInfoForFrame(GetFrame(), true);
// Remove ALLOW setting.
cookie_settings->ResetCookieSetting(b_url);
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetFrame(), false);
+ storage::test::ExpectCrossTabInfoForFrame(GetFrame(), false);
// Allow all third-parties on a.com to access cookies.
cookie_settings->SetThirdPartyCookieSetting(
@@ -650,7 +602,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, MultiTabTest) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetFrame(), true);
+ storage::test::ExpectCrossTabInfoForFrame(GetFrame(), true);
}
// Same as MultiTabTest but with a nested frame on a.com inside a b.com frame.
@@ -661,22 +613,22 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, MultiTabNestedTest) {
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("a.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetNestedFrame(), false);
- SetCrossTabInfoForFrame(GetNestedFrame());
- ExpectCrossTabInfoForFrame(GetNestedFrame(), true);
+ storage::test::ExpectCrossTabInfoForFrame(GetNestedFrame(), false);
+ storage::test::SetCrossTabInfoForFrame(GetNestedFrame());
+ storage::test::ExpectCrossTabInfoForFrame(GetNestedFrame(), true);
// Create a second tab to test communication between tabs.
NavigateToNewTabWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("a.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetNestedFrame(), true);
+ storage::test::ExpectCrossTabInfoForFrame(GetNestedFrame(), true);
SetBlockThirdPartyCookies(true);
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("a.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetNestedFrame(), false);
+ storage::test::ExpectCrossTabInfoForFrame(GetNestedFrame(), false);
// Allow all requests to a.com to access cookies.
auto cookie_settings =
@@ -688,7 +640,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, MultiTabNestedTest) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("a.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetNestedFrame(), true);
+ storage::test::ExpectCrossTabInfoForFrame(GetNestedFrame(), true);
// Remove ALLOW setting.
cookie_settings->ResetCookieSetting(a_url);
@@ -696,7 +648,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, MultiTabNestedTest) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("a.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetNestedFrame(), false);
+ storage::test::ExpectCrossTabInfoForFrame(GetNestedFrame(), false);
// Allow all third-parties on a.com to access cookies.
cookie_settings->SetThirdPartyCookieSetting(
@@ -705,7 +657,7 @@ IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, MultiTabNestedTest) {
NavigateToPageWithFrame("a.com");
NavigateFrameTo("b.com", "/iframe.html");
NavigateNestedFrameTo("a.com", "/browsing_data/site_data.html");
- ExpectCrossTabInfoForFrame(GetNestedFrame(), true);
+ storage::test::ExpectCrossTabInfoForFrame(GetNestedFrame(), true);
}
} // namespace
diff --git a/chromium/chrome/browser/net/dns_over_https_browsertest.cc b/chromium/chrome/browser/net/dns_over_https_browsertest.cc
index 4ae5b153e3e..0d4ce20c7d3 100644
--- a/chromium/chrome/browser/net/dns_over_https_browsertest.cc
+++ b/chromium/chrome/browser/net/dns_over_https_browsertest.cc
@@ -3,6 +3,9 @@
// found in the LICENSE file.
#include "base/test/scoped_feature_list.h"
+#include "chrome/browser/net/secure_dns_config.h"
+#include "chrome/browser/net/stub_resolver_config_reader.h"
+#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_features.h"
#include "chrome/test/base/in_process_browser_test.h"
@@ -10,7 +13,7 @@
#include "content/public/common/content_features.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_navigation_observer.h"
-#include "net/dns/public/doh_provider_list.h"
+#include "net/dns/public/doh_provider_entry.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
@@ -29,10 +32,9 @@ struct DohParameter {
std::vector<DohParameter> GetDohServerTestCases() {
std::vector<DohParameter> doh_test_cases;
- const auto& doh_providers = net::GetDohProviderList();
- for (const auto& doh_provider : doh_providers) {
- doh_test_cases.emplace_back(doh_provider.provider,
- doh_provider.dns_over_https_template, true);
+ for (const auto* entry : net::DohProviderEntry::GetList()) {
+ doh_test_cases.emplace_back(entry->provider, entry->dns_over_https_template,
+ true);
}
// Negative test-case
doh_test_cases.emplace_back("NegativeTestExampleCom",
@@ -64,6 +66,13 @@ class DohBrowserTest : public InProcessBrowserTest,
};
IN_PROC_BROWSER_TEST_P(DohBrowserTest, MANUAL_ExternalDohServers) {
+ SecureDnsConfig secure_dns_config =
+ SystemNetworkContextManager::GetStubResolverConfigReader()
+ ->GetSecureDnsConfiguration(
+ false /* force_check_parental_controls_for_automatic_mode */);
+ // Ensure that DoH is enabled in secure mode
+ EXPECT_EQ(net::DnsConfig::SecureDnsMode::SECURE, secure_dns_config.mode());
+
content::TestNavigationObserver nav_observer(
browser()->tab_strip_model()->GetActiveWebContents(), 1);
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url_));
diff --git a/chromium/chrome/browser/net/dns_probe_browsertest.cc b/chromium/chrome/browser/net/dns_probe_browsertest.cc
index b6f1bbf6687..c73735d92b3 100644
--- a/chromium/chrome/browser/net/dns_probe_browsertest.cc
+++ b/chromium/chrome/browser/net/dns_probe_browsertest.cc
@@ -8,7 +8,6 @@
#include "base/bind.h"
#include "base/path_service.h"
#include "base/run_loop.h"
-#include "base/task/post_task.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/default_tick_clock.h"
#include "build/build_config.h"
@@ -73,7 +72,7 @@ namespace {
// base::PostTask returns a bool, it can't directly be posted to
// another thread.
void RunClosureOnUIThread(const base::Closure& closure) {
- base::PostTask(FROM_HERE, {BrowserThread::UI}, closure);
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, closure);
}
// Wraps DnsProbeService and delays probes until someone calls
@@ -424,8 +423,8 @@ class DnsProbeBrowserTest : public InProcessBrowserTest {
DnsProbeBrowserTest::DnsProbeBrowserTest()
: helper_(new DnsProbeBrowserTestIOThreadHelper()),
- active_browser_(NULL),
- monitored_tab_helper_(NULL) {
+ active_browser_(nullptr),
+ monitored_tab_helper_(nullptr) {
NavigationCorrectionTabObserver::SetAllowEnableCorrectionsForTesting(true);
}
@@ -441,8 +440,8 @@ void DnsProbeBrowserTest::SetUpOnMainThread() {
browser()->profile()->GetPrefs()->SetBoolean(
embedder_support::kAlternateErrorPagesEnabled, true);
- base::PostTask(FROM_HERE, {BrowserThread::IO},
- BindOnce(&DnsProbeBrowserTestIOThreadHelper::SetUpOnIOThread,
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE, BindOnce(&DnsProbeBrowserTestIOThreadHelper::SetUpOnIOThread,
Unretained(helper_)));
ASSERT_TRUE(embedded_test_server()->Start());
@@ -455,8 +454,8 @@ void DnsProbeBrowserTest::SetUpOnMainThread() {
}
void DnsProbeBrowserTest::TearDownOnMainThread() {
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
BindOnce(
&DnsProbeBrowserTestIOThreadHelper::CleanUpOnIOThreadAndDeleteHelper,
Unretained(helper_)));
@@ -521,16 +520,16 @@ void DnsProbeBrowserTest::SetFakeHostResolverResults(
void DnsProbeBrowserTest::SetCorrectionServiceBroken(bool broken) {
int net_error = broken ? net::ERR_NAME_NOT_RESOLVED : net::OK;
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
BindOnce(&DnsProbeBrowserTestIOThreadHelper::SetCorrectionServiceNetError,
Unretained(helper_), net_error));
}
void DnsProbeBrowserTest::SetCorrectionServiceDelayRequests(
bool delay_requests) {
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
BindOnce(
&DnsProbeBrowserTestIOThreadHelper::SetCorrectionServiceDelayRequests,
Unretained(helper_), delay_requests));
@@ -538,8 +537,8 @@ void DnsProbeBrowserTest::SetCorrectionServiceDelayRequests(
void DnsProbeBrowserTest::WaitForDelayedRequestDestruction() {
base::RunLoop run_loop;
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
BindOnce(
&DnsProbeBrowserTestIOThreadHelper::SetRequestDestructionCallback,
Unretained(helper_),
diff --git a/chromium/chrome/browser/net/errorpage_browsertest.cc b/chromium/chrome/browser/net/errorpage_browsertest.cc
index d7f97d43a70..08da4073684 100644
--- a/chromium/chrome/browser/net/errorpage_browsertest.cc
+++ b/chromium/chrome/browser/net/errorpage_browsertest.cc
@@ -22,6 +22,8 @@
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
#include "base/task/post_task.h"
+#include "base/test/test_timeouts.h"
+#include "base/threading/platform_thread.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "build/build_config.h"
@@ -52,6 +54,7 @@
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/browsing_data_remover.h"
+#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
@@ -69,7 +72,6 @@
#include "net/base/filename_util.h"
#include "net/base/net_errors.h"
#include "net/dns/mock_host_resolver.h"
-#include "net/http/failing_http_transaction_factory.h"
#include "net/http/http_cache.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
@@ -343,8 +345,8 @@ class DNSErrorPageTest : public ErrorPageTest {
EXPECT_EQ(origin, "null");
// Send RequestCreated so that anyone blocking on
// WaitForRequests can continue.
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&DNSErrorPageTest::RequestCreated,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&DNSErrorPageTest::RequestCreated,
base::Unretained(owner)));
content::URLLoaderInterceptor::WriteResponse(
"chrome/test/data/mock-link-doctor.json",
@@ -1117,6 +1119,41 @@ IN_PROC_BROWSER_TEST_F(ErrorPageAutoReloadTest, IgnoresSameDocumentNavigation) {
EXPECT_EQ(3, interceptor_requests());
}
+// Make sure that an error page that is providing it's own HTML has auto-reloads
+// disabled.
+IN_PROC_BROWSER_TEST_F(ErrorPageAutoReloadTest,
+ CustomErrorPageDoesNotAutoReload) {
+ ASSERT_TRUE(embedded_test_server()->Start());
+ GURL test_url = embedded_test_server()->base_url();
+ // Navigate to the test site without installing the interceptor so it
+ // succeeds.
+ ui_test_utils::NavigateToURL(browser(), test_url);
+ // Install an interceptor so we can check there was no reload.
+ InstallInterceptor(test_url, 10);
+ // Trigger a custom error page and wait for it to load.
+ content::WebContents* web_contents =
+ browser()->tab_strip_model()->GetActiveWebContents();
+ content::TestNavigationObserver error_observer(web_contents);
+ web_contents->GetController().LoadPostCommitErrorPage(
+ web_contents->GetMainFrame(), test_url, "error html",
+ net::ERR_CONNECTION_RESET);
+ // Wait for the custom error page to load.
+ error_observer.Wait();
+ // Wait for a short time (since the first reload would happen immediately
+ // after the error loads), after that we should see no interceptor requests or
+ // failures for reloads, since this error page shouldn't reload.
+ base::PlatformThread::Sleep(TestTimeouts::tiny_timeout());
+ EXPECT_EQ(0, interceptor_failures());
+ EXPECT_EQ(0, interceptor_requests());
+
+ // Navigate to the page manually, this will trigger a regular error page, make
+ // sure autoreloads are enabled at this point.
+ ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), test_url,
+ 2);
+ EXPECT_EQ(2, interceptor_failures());
+ EXPECT_EQ(2, interceptor_requests());
+}
+
// A test fixture that returns ERR_ADDRESS_UNREACHABLE for all navigation
// correction requests. ERR_NAME_NOT_RESOLVED is more typical, but need to use
// a different error for the correction service and the original page to
diff --git a/chromium/chrome/browser/net/net_error_tab_helper.cc b/chromium/chrome/browser/net/net_error_tab_helper.cc
index 7f17b1aaa04..3477bb6fbec 100644
--- a/chromium/chrome/browser/net/net_error_tab_helper.cc
+++ b/chromium/chrome/browser/net/net_error_tab_helper.cc
@@ -71,19 +71,6 @@ void NetErrorTabHelper::RenderFrameCreated(
CanShowNetworkDiagnosticsDialog(web_contents()));
}
-void NetErrorTabHelper::DidStartNavigation(
- content::NavigationHandle* navigation_handle) {
- if (!navigation_handle->IsInMainFrame())
- return;
-
- if (navigation_handle->IsErrorPage() &&
- PageTransitionCoreTypeIs(navigation_handle->GetPageTransition(),
- ui::PAGE_TRANSITION_RELOAD)) {
- error_page::RecordEvent(
- error_page::NETWORK_ERROR_PAGE_BROWSER_INITIATED_RELOAD);
- }
-}
-
void NetErrorTabHelper::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame())
@@ -112,31 +99,33 @@ void NetErrorTabHelper::DidFinishNavigation(
}
}
-bool NetErrorTabHelper::OnMessageReceived(
- const IPC::Message& message,
- content::RenderFrameHost* render_frame_host) {
- if (render_frame_host != web_contents()->GetMainFrame())
- return false;
#if BUILDFLAG(ENABLE_OFFLINE_PAGES)
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(NetErrorTabHelper, message)
- IPC_MESSAGE_HANDLER(ChromeViewHostMsg_DownloadPageLater,
- OnDownloadPageLater)
- IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetIsShowingDownloadButtonInErrorPage,
- OnSetIsShowingDownloadButtonInErrorPage)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
-
- return handled;
-#else
- return false;
-#endif // BUILDFLAG(ENABLE_OFFLINE_PAGES)
+void NetErrorTabHelper::DownloadPageLater() {
+ // Makes sure that this is coming from an error page.
+ content::NavigationEntry* entry =
+ web_contents()->GetController().GetLastCommittedEntry();
+ if (!entry || entry->GetPageType() != content::PAGE_TYPE_ERROR)
+ return;
+
+ // Only download the page for HTTP/HTTPS URLs.
+ GURL url(entry->GetVirtualURL());
+ if (!url.SchemeIsHTTPOrHTTPS())
+ return;
+
+ DownloadPageLaterHelper(url);
}
+void NetErrorTabHelper::SetIsShowingDownloadButtonInErrorPage(
+ bool showing_download_button) {
+ is_showing_download_button_in_error_page_ = showing_download_button;
+}
+#endif // BUILDFLAG(ENABLE_OFFLINE_PAGES)
+
NetErrorTabHelper::NetErrorTabHelper(WebContents* contents)
: WebContentsObserver(contents),
network_diagnostics_receivers_(contents, this),
network_easter_egg_receivers_(contents, this),
+ net_error_page_support_(contents, this),
is_error_page_(false),
dns_error_active_(false),
dns_error_page_committed_(false),
@@ -190,28 +179,6 @@ void NetErrorTabHelper::OnDnsProbeFinished(DnsProbeStatus result) {
SendInfo();
}
-#if BUILDFLAG(ENABLE_OFFLINE_PAGES)
-void NetErrorTabHelper::OnDownloadPageLater() {
- // Makes sure that this is coming from an error page.
- content::NavigationEntry* entry =
- web_contents()->GetController().GetLastCommittedEntry();
- if (!entry || entry->GetPageType() != content::PAGE_TYPE_ERROR)
- return;
-
- // Only download the page for HTTP/HTTPS URLs.
- GURL url(entry->GetVirtualURL());
- if (!url.SchemeIsHTTPOrHTTPS())
- return;
-
- DownloadPageLaterHelper(url);
-}
-
-void NetErrorTabHelper::OnSetIsShowingDownloadButtonInErrorPage(
- bool is_showing_download_button) {
- is_showing_download_button_in_error_page_ = is_showing_download_button;
-}
-#endif // BUILDFLAG(ENABLE_OFFLINE_PAGES)
-
// static
void NetErrorTabHelper::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* prefs) {
diff --git a/chromium/chrome/browser/net/net_error_tab_helper.h b/chromium/chrome/browser/net/net_error_tab_helper.h
index 5ff174b969f..7062c1da29b 100644
--- a/chromium/chrome/browser/net/net_error_tab_helper.h
+++ b/chromium/chrome/browser/net/net_error_tab_helper.h
@@ -12,6 +12,7 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/net/dns_probe_service.h"
+#include "chrome/common/net/net_error_page_support.mojom.h"
#include "chrome/common/network_diagnostics.mojom.h"
#include "chrome/common/network_easter_egg.mojom.h"
#include "components/error_page/common/net_error_info.h"
@@ -34,6 +35,7 @@ namespace chrome_browser_net {
class NetErrorTabHelper
: public content::WebContentsObserver,
public content::WebContentsUserData<NetErrorTabHelper>,
+ public chrome::mojom::NetErrorPageSupport,
public chrome::mojom::NetworkDiagnostics,
public chrome::mojom::NetworkEasterEgg {
public:
@@ -68,12 +70,15 @@ class NetErrorTabHelper
// content::WebContentsObserver implementation.
void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override;
- void DidStartNavigation(
- content::NavigationHandle* navigation_handle) override;
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override;
- bool OnMessageReceived(const IPC::Message& message,
- content::RenderFrameHost* render_frame_host) override;
+
+ // chrome::mojom::NetErrorPageSupport:
+#if BUILDFLAG(ENABLE_OFFLINE_PAGES)
+ void DownloadPageLater() override;
+ void SetIsShowingDownloadButtonInErrorPage(
+ bool showing_download_button) override;
+#endif // BUILDFLAG(ENABLE_OFFLINE_PAGES)
protected:
// |contents| is the WebContents of the tab this NetErrorTabHelper is
@@ -92,11 +97,6 @@ class NetErrorTabHelper
return network_diagnostics_receivers_;
}
-#if BUILDFLAG(ENABLE_OFFLINE_PAGES)
- void OnDownloadPageLater();
- void OnSetIsShowingDownloadButtonInErrorPage(bool is_showing_download_button);
-#endif // BUILDFLAG(ENABLE_OFFLINE_PAGES)
-
private:
friend class content::WebContentsUserData<NetErrorTabHelper>;
@@ -126,6 +126,8 @@ class NetErrorTabHelper
network_diagnostics_receivers_;
content::WebContentsFrameReceiverSet<chrome::mojom::NetworkEasterEgg>
network_easter_egg_receivers_;
+ content::WebContentsFrameReceiverSet<chrome::mojom::NetErrorPageSupport>
+ net_error_page_support_;
// True if the last provisional load that started was for an error page.
bool is_error_page_;
diff --git a/chromium/chrome/browser/net/net_error_tab_helper_unittest.cc b/chromium/chrome/browser/net/net_error_tab_helper_unittest.cc
index fef66fcfe7f..cf5dc2537e6 100644
--- a/chromium/chrome/browser/net/net_error_tab_helper_unittest.cc
+++ b/chromium/chrome/browser/net/net_error_tab_helper_unittest.cc
@@ -45,7 +45,7 @@ class TestNetErrorTabHelper : public NetErrorTabHelper {
int mock_sent_count() const { return mock_sent_count_; }
#if BUILDFLAG(ENABLE_OFFLINE_PAGES)
- using NetErrorTabHelper::OnDownloadPageLater;
+ using NetErrorTabHelper::DownloadPageLater;
const GURL& download_page_later_url() const {
return download_page_later_url_;
@@ -169,7 +169,7 @@ class NetErrorTabHelperTest : public ChromeRenderViewHostTestHarness {
bool succeeded) {
GURL url(url_string);
LoadURL(url, succeeded);
- tab_helper()->OnDownloadPageLater();
+ tab_helper()->DownloadPageLater();
EXPECT_EQ(0, tab_helper()->times_download_page_later_invoked());
}
#endif // BUILDFLAG(ENABLE_OFFLINE_PAGES)
@@ -370,7 +370,7 @@ TEST_F(NetErrorTabHelperTest, NoDiagnosticsForNonHttpSchemes) {
TEST_F(NetErrorTabHelperTest, DownloadPageLater) {
GURL url("http://somewhere:123/");
LoadURL(url, false /*succeeded*/);
- tab_helper()->OnDownloadPageLater();
+ tab_helper()->DownloadPageLater();
EXPECT_EQ(url, tab_helper()->download_page_later_url());
EXPECT_EQ(1, tab_helper()->times_download_page_later_invoked());
}
@@ -378,7 +378,7 @@ TEST_F(NetErrorTabHelperTest, DownloadPageLater) {
TEST_F(NetErrorTabHelperTest, NoDownloadPageLaterOnNonErrorPage) {
GURL url("http://somewhere:123/");
LoadURL(url, true /*succeeded*/);
- tab_helper()->OnDownloadPageLater();
+ tab_helper()->DownloadPageLater();
EXPECT_EQ(0, tab_helper()->times_download_page_later_invoked());
}
diff --git a/chromium/chrome/browser/net/network_context_configuration_browsertest.cc b/chromium/chrome/browser/net/network_context_configuration_browsertest.cc
index e297441ad05..f40e582ca2c 100644
--- a/chromium/chrome/browser/net/network_context_configuration_browsertest.cc
+++ b/chromium/chrome/browser/net/network_context_configuration_browsertest.cc
@@ -434,7 +434,7 @@ class NetworkContextConfigurationBrowserTest
case NetworkContextType::kOnDiskAppWithIncognitoProfile:
// Incognito actually uses the non-incognito prefs, so this should end
// up being the same pref store as in the KProfile case.
- return browser()->profile()->GetOffTheRecordProfile()->GetPrefs();
+ return browser()->profile()->GetPrimaryOTRProfile()->GetPrefs();
}
}
@@ -463,7 +463,7 @@ class NetworkContextConfigurationBrowserTest
case NetworkContextType::kIncognitoProfile:
case NetworkContextType::kOnDiskAppWithIncognitoProfile:
ProfileNetworkContextServiceFactory::GetForContext(
- browser()->profile()->GetOffTheRecordProfile())
+ browser()->profile()->GetPrimaryOTRProfile())
->FlushProxyConfigMonitorForTesting();
break;
}
@@ -633,8 +633,8 @@ class NetworkContextConfigurationBrowserTest
url, net::CookieOptions::MakeAllInclusive(),
base::BindOnce(
[](std::string* cookies_out, base::RunLoop* run_loop,
- const net::CookieStatusList& cookies,
- const net::CookieStatusList& excluded_cookies) {
+ const net::CookieAccessResultList& cookies,
+ const net::CookieAccessResultList& excluded_cookies) {
*cookies_out = net::CanonicalCookie::BuildCookieLine(cookies);
run_loop->Quit();
},
@@ -1386,17 +1386,26 @@ IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest,
FlushNetworkInterface();
std::string accept_language2, user_agent2;
ASSERT_TRUE(FetchHeaderEcho("accept-language", &accept_language2));
- EXPECT_EQ(system ? kNoAcceptLanguage : "uk", accept_language2);
+ if (GetProfile()->IsOffTheRecord()) {
+ EXPECT_EQ(system ? kNoAcceptLanguage : "en-US,en;q=0.9", accept_language2);
+ } else {
+ EXPECT_EQ(system ? kNoAcceptLanguage : "uk", accept_language2);
+ }
ASSERT_TRUE(FetchHeaderEcho("user-agent", &user_agent2));
EXPECT_EQ(::GetUserAgent(), user_agent2);
// Try a more complicated one, with multiple languages.
browser()->profile()->GetPrefs()->SetString(language::prefs::kAcceptLanguages,
- "uk, en_US");
+ "uk, en-US");
FlushNetworkInterface();
std::string accept_language3, user_agent3;
ASSERT_TRUE(FetchHeaderEcho("accept-language", &accept_language3));
- EXPECT_EQ(system ? kNoAcceptLanguage : "uk,en_US;q=0.9", accept_language3);
+ if (GetProfile()->IsOffTheRecord()) {
+ EXPECT_EQ(system ? kNoAcceptLanguage : "en-US,en;q=0.9", accept_language3);
+ } else {
+ EXPECT_EQ(system ? kNoAcceptLanguage : "uk,en-US;q=0.9,en;q=0.8",
+ accept_language3);
+ }
ASSERT_TRUE(FetchHeaderEcho("user-agent", &user_agent3));
EXPECT_EQ(::GetUserAgent(), user_agent3);
}
diff --git a/chromium/chrome/browser/net/network_quality_estimator_prefs_browsertest.cc b/chromium/chrome/browser/net/network_quality_estimator_prefs_browsertest.cc
index d2b15b52a4e..dbebc7d6f1e 100644
--- a/chromium/chrome/browser/net/network_quality_estimator_prefs_browsertest.cc
+++ b/chromium/chrome/browser/net/network_quality_estimator_prefs_browsertest.cc
@@ -20,13 +20,13 @@
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_impl.h"
#include "chrome/browser/chrome_content_browser_client.h"
-#include "chrome/browser/metrics/subprocess_metrics_provider.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
+#include "components/metrics/content/subprocess_metrics_provider.h"
#include "components/prefs/json_pref_store.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h"
@@ -71,7 +71,7 @@ void RetryForHistogramUntilCountReached(base::HistogramTester* histogram_tester,
if (total_count >= count)
return;
content::FetchHistogramsFromChildProcesses();
- SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
+ metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
base::RunLoop().RunUntilIdle();
}
}
@@ -195,6 +195,8 @@ IN_PROC_BROWSER_TEST_F(NetworkQualityEstimatorPrefsBrowserTest,
mojo::PendingRemote<network::mojom::NetworkContext> network_context;
network::mojom::NetworkContextParamsPtr context_params =
network::mojom::NetworkContextParams::New();
+ context_params->cert_verifier_params = content::GetCertVerifierParams(
+ network::mojom::CertVerifierCreationParams::New());
context_params->http_server_properties_path =
browser()->profile()->GetPath().Append(
FILE_PATH_LITERAL("Temp Network Persistent State"));
diff --git a/chromium/chrome/browser/net/network_quality_tracker_browsertest.cc b/chromium/chrome/browser/net/network_quality_tracker_browsertest.cc
index b1bb02b14b0..64281e9daa9 100644
--- a/chromium/chrome/browser/net/network_quality_tracker_browsertest.cc
+++ b/chromium/chrome/browser/net/network_quality_tracker_browsertest.cc
@@ -7,7 +7,6 @@
#include "base/deferred_sequenced_task_runner.h"
#include "base/macros.h"
#include "base/run_loop.h"
-#include "base/task/post_task.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_impl.h"
@@ -17,6 +16,7 @@
#include "chrome/browser/ui/browser.h"
#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/browser/network_service_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/network_service_util.h"
@@ -122,7 +122,7 @@ class NetworkQualityTrackerBrowserTest : public InProcessBrowserTest {
void SimulateNetworkQualityChange(net::EffectiveConnectionType type) {
if (!content::IsOutOfProcessNetworkService()) {
scoped_refptr<base::SequencedTaskRunner> task_runner =
- base::CreateSequencedTaskRunner({content::BrowserThread::IO});
+ content::GetIOThreadTaskRunner({});
if (content::IsInProcessNetworkService())
task_runner = content::GetNetworkTaskRunner();
task_runner->PostTask(
diff --git a/chromium/chrome/browser/net/network_request_metrics_browsertest.cc b/chromium/chrome/browser/net/network_request_metrics_browsertest.cc
index ae08cdc870e..c002cd77d7e 100644
--- a/chromium/chrome/browser/net/network_request_metrics_browsertest.cc
+++ b/chromium/chrome/browser/net/network_request_metrics_browsertest.cc
@@ -17,7 +17,6 @@
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/download/download_prefs.h"
-#include "chrome/browser/metrics/subprocess_metrics_provider.h"
#include "chrome/browser/predictors/loading_predictor_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
@@ -26,6 +25,7 @@
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
+#include "components/metrics/content/subprocess_metrics_provider.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/test/browser_test.h"
@@ -181,7 +181,7 @@ class NetworkRequestMetricsBrowserTest
NetworkAccessed network_accessed) {
// Some metrics may come from the renderer. This call ensures that those
// metrics are available.
- SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
+ metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
if (GetParam() == RequestType::kMainFrame) {
histograms_->ExpectTotalCount("Net.ErrorCodesForImages2", 0);
@@ -268,7 +268,7 @@ class NetworkRequestMetricsBrowserTest
void CheckHistogramsAfterMainFrameInterruption() {
// Some metrics may come from the renderer. This call ensures that those
// metrics are available.
- SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
+ metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
if (GetParam() == RequestType::kMainFrame) {
// Can't check Net.ErrorCodesForSubresources3, due to the favicon, which
@@ -511,7 +511,7 @@ IN_PROC_BROWSER_TEST_P(NetworkRequestMetricsBrowserTest, Download) {
// Some metrics may come from the renderer. This call ensures that those
// metrics are available.
- SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
+ metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
if (GetParam() == RequestType::kMainFrame) {
histograms()->ExpectTotalCount("Net.ErrorCodesForImages2", 0);
diff --git a/chromium/chrome/browser/net/nss_context.cc b/chromium/chrome/browser/net/nss_context.cc
index 67aa6bf89ef..d328c9d82c4 100644
--- a/chromium/chrome/browser/net/nss_context.cc
+++ b/chromium/chrome/browser/net/nss_context.cc
@@ -7,7 +7,6 @@
#include "base/bind.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
-#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_task_traits.h"
@@ -52,8 +51,8 @@ void GetNSSCertDatabaseForProfile(
const base::Callback<void(net::NSSCertDatabase*)>& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&GetCertDBOnIOThread, profile->GetResourceContext(),
base::ThreadTaskRunnerHandle::Get(), callback));
}
diff --git a/chromium/chrome/browser/net/nss_context_chromeos_browsertest.cc b/chromium/chrome/browser/net/nss_context_chromeos_browsertest.cc
index 833a109b11d..beab33cf71b 100644
--- a/chromium/chrome/browser/net/nss_context_chromeos_browsertest.cc
+++ b/chromium/chrome/browser/net/nss_context_chromeos_browsertest.cc
@@ -8,7 +8,6 @@
#include "base/bind.h"
#include "base/run_loop.h"
-#include "base/task/post_task.h"
#include "chrome/browser/chromeos/login/login_manager_test.h"
#include "chrome/browser/chromeos/login/test/login_manager_mixin.h"
#include "chrome/browser/chromeos/login/ui/user_adding_screen.h"
@@ -39,8 +38,8 @@ class DBTester {
// Returns true if the database was retrieved successfully.
bool DoGetDBTests() {
base::RunLoop run_loop;
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&DBTester::GetDBAndDoTestsOnIOThread,
base::Unretained(this), profile_->GetResourceContext(),
run_loop.QuitClosure()));
@@ -51,8 +50,8 @@ class DBTester {
// Test retrieving the database again, should be called after DoGetDBTests.
void DoGetDBAgainTests() {
base::RunLoop run_loop;
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&DBTester::DoGetDBAgainTestsOnIOThread,
base::Unretained(this), profile_->GetResourceContext(),
run_loop.QuitClosure()));
@@ -92,7 +91,7 @@ class DBTester {
EXPECT_EQ(db->GetPublicSlot().get(), db->GetPrivateSlot().get());
}
- base::PostTask(FROM_HERE, {content::BrowserThread::UI}, done_callback);
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, done_callback);
}
void DoGetDBAgainTestsOnIOThread(content::ResourceContext* context,
@@ -104,7 +103,7 @@ class DBTester {
// Should return the same db as before.
EXPECT_EQ(db_, db);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI}, done_callback);
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, done_callback);
}
Profile* profile_;
diff --git a/chromium/chrome/browser/net/probe_message.cc b/chromium/chrome/browser/net/probe_message.cc
index 4ab7e3e28ee..597aee11228 100644
--- a/chromium/chrome/browser/net/probe_message.cc
+++ b/chromium/chrome/browser/net/probe_message.cc
@@ -8,6 +8,7 @@
#include <string>
+#include "base/check_op.h"
#include "base/logging.h"
namespace chrome_browser_net {
diff --git a/chromium/chrome/browser/net/profile_network_context_service.cc b/chromium/chrome/browser/net/profile_network_context_service.cc
index 75a5ee19235..b409f1bd146 100644
--- a/chromium/chrome/browser/net/profile_network_context_service.cc
+++ b/chromium/chrome/browser/net/profile_network_context_service.cc
@@ -7,14 +7,15 @@
#include <string>
#include "base/bind.h"
+#include "base/check_op.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
-#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_macros.h"
+#include "base/notreached.h"
#include "base/strings/string_split.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
@@ -35,6 +36,7 @@
#include "components/certificate_transparency/pref_names.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/language/core/browser/pref_names.h"
+#include "components/language/core/common/locale_util.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_registry_simple.h"
@@ -111,9 +113,7 @@ std::vector<std::string> TranslateStringArray(const base::ListValue* list) {
std::string ComputeAcceptLanguageFromPref(const std::string& language_pref) {
std::string accept_languages_str =
- base::FeatureList::IsEnabled(features::kUseNewAcceptLanguageHeader)
- ? net::HttpUtil::ExpandLanguageList(language_pref)
- : language_pref;
+ net::HttpUtil::ExpandLanguageList(language_pref);
return net::HttpUtil::GenerateAcceptLanguageHeader(accept_languages_str);
}
@@ -166,10 +166,16 @@ void InitializeCorsExtraSafelistedRequestHeaderNamesForProfile(
// TODO(https://crbug.com/458508): Currently, this is determined by OR of the
// feature flag and policy. Next steps would be changing the feature value to
// false after enough heads up and then removing the feature.
-bool IsAmbientAuthAllowedForProfile(const Profile* profile) {
+bool IsAmbientAuthAllowedForProfile(Profile* profile) {
if (profile->IsRegularProfile())
return true;
+ // Non-primary OTR profiles are not used to create browser windows and are
+ // only technical means for a task that does not need to leave state after
+ // it's completed.
+ if (!profile->IsPrimaryOTRProfile())
+ return true;
+
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
DCHECK(local_state->FindPreference(
@@ -197,6 +203,53 @@ bool IsAmbientAuthAllowedForProfile(const Profile* profile) {
return false;
}
+void UpdateCookieSettings(Profile* profile) {
+ ContentSettingsForOneType settings;
+ HostContentSettingsMapFactory::GetForProfile(profile)->GetSettingsForOneType(
+ ContentSettingsType::COOKIES, std::string(), &settings);
+ content::BrowserContext::ForEachStoragePartition(
+ profile, base::BindRepeating(
+ [](ContentSettingsForOneType settings,
+ content::StoragePartition* storage_partition) {
+ storage_partition->GetCookieManagerForBrowserProcess()
+ ->SetContentSettings(settings);
+ },
+ settings));
+}
+
+void UpdateLegacyCookieSettings(Profile* profile) {
+ ContentSettingsForOneType settings;
+ HostContentSettingsMapFactory::GetForProfile(profile)->GetSettingsForOneType(
+ ContentSettingsType::LEGACY_COOKIE_ACCESS, std::string(), &settings);
+ content::BrowserContext::ForEachStoragePartition(
+ profile, base::BindRepeating(
+ [](ContentSettingsForOneType settings,
+ content::StoragePartition* storage_partition) {
+ storage_partition->GetCookieManagerForBrowserProcess()
+ ->SetContentSettingsForLegacyCookieAccess(settings);
+ },
+ settings));
+}
+
+void UpdateStorageAccessSettings(Profile* profile) {
+ if (base::FeatureList::IsEnabled(blink::features::kStorageAccessAPI)) {
+ ContentSettingsForOneType settings;
+ HostContentSettingsMapFactory::GetForProfile(profile)
+ ->GetSettingsForOneType(ContentSettingsType::STORAGE_ACCESS,
+ std::string(), &settings);
+
+ content::BrowserContext::ForEachStoragePartition(
+ profile, base::BindRepeating(
+ [](ContentSettingsForOneType settings,
+ content::StoragePartition* storage_partition) {
+ storage_partition->GetCookieManagerForBrowserProcess()
+ ->SetStorageAccessGrantSettings(settings,
+ base::DoNothing());
+ },
+ settings));
+ }
+}
+
} // namespace
ProfileNetworkContextService::ProfileNetworkContextService(Profile* profile)
@@ -280,8 +333,8 @@ void ProfileNetworkContextService::ConfigureNetworkContextParams(
FROM_HERE,
{base::TaskPriority::BEST_EFFORT, base::MayBlock(),
base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
- base::BindOnce(base::IgnoreResult(&base::DeleteFile), media_cache_path,
- true /* recursive */));
+ base::BindOnce(base::GetDeletePathRecursivelyCallback(),
+ media_cache_path));
}
}
@@ -360,6 +413,10 @@ void ProfileNetworkContextService::OnThirdPartyCookieBlockingChanged(
}
std::string ProfileNetworkContextService::ComputeAcceptLanguage() const {
+ if (profile_->IsOffTheRecord()) {
+ return ComputeAcceptLanguageFromPref(
+ g_browser_process->GetApplicationLocale());
+ }
return ComputeAcceptLanguageFromPref(pref_accept_language_.GetValue());
}
@@ -474,6 +531,11 @@ ProfileNetworkContextService::CreateCookieManagerParams(
auto out = network::mojom::CookieManagerParams::New();
out->block_third_party_cookies =
cookie_settings.ShouldBlockThirdPartyCookies();
+ // This allows cookies to be sent on https requests from chrome:// pages,
+ // ignoring SameSite attribute rules. For example, this is needed for browser
+ // UI to interact with SameSite cookies on accounts.google.com, which are used
+ // for logging into Cloud Print from chrome://print, for displaying a list
+ // of available accounts on the NTP (chrome://new-tab-page), etc.
out->secure_origin_cookies_allowed_schemes.push_back(
content::kChromeUIScheme);
#if BUILDFLAG(ENABLE_EXTENSIONS)
@@ -855,41 +917,22 @@ void ProfileNetworkContextService::OnContentSettingChanged(
const ContentSettingsPattern& secondary_pattern,
ContentSettingsType content_type,
const std::string& resource_identifier) {
- if (content_type != ContentSettingsType::COOKIES &&
- content_type != ContentSettingsType::LEGACY_COOKIE_ACCESS &&
- content_type != ContentSettingsType::DEFAULT) {
- return;
- }
-
- if (content_type == ContentSettingsType::COOKIES ||
- content_type == ContentSettingsType::DEFAULT) {
- ContentSettingsForOneType cookies_settings;
- HostContentSettingsMapFactory::GetForProfile(profile_)
- ->GetSettingsForOneType(ContentSettingsType::COOKIES, std::string(),
- &cookies_settings);
- content::BrowserContext::ForEachStoragePartition(
- profile_, base::BindRepeating(
- [](ContentSettingsForOneType settings,
- content::StoragePartition* storage_partition) {
- storage_partition->GetCookieManagerForBrowserProcess()
- ->SetContentSettings(settings);
- },
- cookies_settings));
- }
-
- if (content_type == ContentSettingsType::LEGACY_COOKIE_ACCESS ||
- content_type == ContentSettingsType::DEFAULT) {
- ContentSettingsForOneType legacy_cookie_access_settings;
- HostContentSettingsMapFactory::GetForProfile(profile_)
- ->GetSettingsForOneType(ContentSettingsType::LEGACY_COOKIE_ACCESS,
- std::string(), &legacy_cookie_access_settings);
- content::BrowserContext::ForEachStoragePartition(
- profile_, base::BindRepeating(
- [](ContentSettingsForOneType settings,
- content::StoragePartition* storage_partition) {
- storage_partition->GetCookieManagerForBrowserProcess()
- ->SetContentSettingsForLegacyCookieAccess(settings);
- },
- legacy_cookie_access_settings));
+ switch (content_type) {
+ case ContentSettingsType::COOKIES:
+ UpdateCookieSettings(profile_);
+ break;
+ case ContentSettingsType::LEGACY_COOKIE_ACCESS:
+ UpdateLegacyCookieSettings(profile_);
+ break;
+ case ContentSettingsType::STORAGE_ACCESS:
+ UpdateStorageAccessSettings(profile_);
+ break;
+ case ContentSettingsType::DEFAULT:
+ UpdateCookieSettings(profile_);
+ UpdateLegacyCookieSettings(profile_);
+ UpdateStorageAccessSettings(profile_);
+ break;
+ default:
+ return;
}
}
diff --git a/chromium/chrome/browser/net/profile_network_context_service_browsertest.cc b/chromium/chrome/browser/net/profile_network_context_service_browsertest.cc
index 5bd46dd35db..0b5d8377d2a 100644
--- a/chromium/chrome/browser/net/profile_network_context_service_browsertest.cc
+++ b/chromium/chrome/browser/net/profile_network_context_service_browsertest.cc
@@ -3,12 +3,16 @@
// found in the LICENSE file.
#include <algorithm>
+#include <memory>
#include <string>
#include <vector>
+#include "base/bind.h"
+#include "base/check_op.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
+#include "base/optional.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
@@ -21,12 +25,13 @@
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/metrics/subprocess_metrics_provider.h"
#include "chrome/browser/net/profile_network_context_service.h"
#include "chrome/browser/net/profile_network_context_service_factory.h"
#include "chrome/browser/net/profile_network_context_service_test_utils.h"
+#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/policy/policy_test_utils.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_features.h"
@@ -35,13 +40,16 @@
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
+#include "components/metrics/content/subprocess_metrics_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_service.h"
+#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/content_features.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/simple_url_loader_test_helper.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/base/features.h"
#include "net/base/load_flags.h"
@@ -51,6 +59,8 @@
#include "net/test/embedded_test_server/http_response.h"
#include "net/test/embedded_test_server/request_handler_util.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
+#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h"
+#include "services/cert_verifier/test_cert_verifier_service_factory.h"
#include "services/network/public/cpp/cors/cors.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/network_context.mojom.h"
@@ -164,7 +174,7 @@ void CheckCacheResetStatus(base::HistogramTester* histograms, bool reset) {
// has been loaded prior to testing the histograms.
while (!histograms->GetBucketCount("HttpCache.HardReset", reset)) {
content::FetchHistogramsFromChildProcesses();
- SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
+ metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(5));
}
@@ -296,10 +306,14 @@ class AmbientAuthenticationTestWithPolicy
service->GetInteger(prefs::kAmbientAuthenticationInPrivateModesEnabled);
Profile* regular_profile = browser()->profile();
- Profile* incognito_profile = regular_profile->GetOffTheRecordProfile();
+ Profile* incognito_profile = regular_profile->GetPrimaryOTRProfile();
+ Profile* non_primary_otr_profile = regular_profile->GetOffTheRecordProfile(
+ Profile::OTRProfileID("Test::AmbientAuthentication"));
EXPECT_TRUE(AmbientAuthenticationTestHelper::IsAmbientAuthAllowedForProfile(
regular_profile));
+ EXPECT_TRUE(AmbientAuthenticationTestHelper::IsAmbientAuthAllowedForProfile(
+ non_primary_otr_profile));
EXPECT_EQ(AmbientAuthenticationTestHelper::IsAmbientAuthAllowedForProfile(
incognito_profile),
AmbientAuthenticationTestHelper::IsIncognitoAllowedInFeature(
@@ -440,19 +454,88 @@ IN_PROC_BROWSER_TEST_F(ProfileNetworkContextServiceDiskCacheBrowsertest,
}
#if BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED)
+namespace {
+void UnblockOnProfileCreation(base::RunLoop* run_loop,
+ Profile* profile,
+ Profile::CreateStatus status) {
+ if (status == Profile::CREATE_STATUS_INITIALIZED)
+ run_loop->Quit();
+}
+} // namespace
+
class ProfileNetworkContextServiceCertVerifierBuiltinFeaturePolicyTest
: public policy::PolicyTest,
public testing::WithParamInterface<bool> {
public:
void SetUpInProcessBrowserTestFixture() override {
- scoped_feature_list_.InitWithFeatureState(
- net::features::kCertVerifierBuiltinFeature,
- /*enabled=*/GetParam());
+ std::vector<base::Feature> enabled_features, disabled_features;
+ if (use_builtin_cert_verifier()) {
+ enabled_features.push_back(net::features::kCertVerifierBuiltinFeature);
+ } else {
+ disabled_features.push_back(net::features::kCertVerifierBuiltinFeature);
+ }
+ if (enable_cert_verifier_service()) {
+ enabled_features.push_back(network::features::kCertVerifierService);
+ test_cert_verifier_service_factory_.emplace();
+ content::SetCertVerifierServiceFactoryForTesting(
+ &test_cert_verifier_service_factory_.value());
+ } else {
+ disabled_features.push_back(network::features::kCertVerifierService);
+ }
+ scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features);
policy::PolicyTest::SetUpInProcessBrowserTestFixture();
}
+ void TearDownInProcessBrowserTestFixture() override {
+ content::SetCertVerifierServiceFactoryForTesting(nullptr);
+ }
+
+ void SetUpOnMainThread() override {
+ if (enable_cert_verifier_service()) {
+ test_cert_verifier_service_factory_->ReleaseAllCertVerifierParams();
+ }
+ }
+
+ void ExpectUseBuiltinCertVerifierCorrectUsingCertVerifierService(
+ network::mojom::CertVerifierCreationParams::CertVerifierImpl
+ use_builtin_cert_verifier) {
+ ASSERT_TRUE(enable_cert_verifier_service());
+ ASSERT_TRUE(test_cert_verifier_service_factory_);
+ EXPECT_EQ(1ul, test_cert_verifier_service_factory_->num_captured_params());
+ EXPECT_EQ(use_builtin_cert_verifier,
+ test_cert_verifier_service_factory_->GetParamsAtIndex(0)
+ ->creation_params->use_builtin_cert_verifier);
+ // Send it to the actual CertVerifierServiceFactory.
+ test_cert_verifier_service_factory_->ReleaseNextCertVerifierParams();
+ }
+
+ Profile* CreateNewProfile() {
+ ProfileManager* profile_manager = g_browser_process->profile_manager();
+ base::FilePath new_path =
+ profile_manager->GenerateNextProfileDirectoryPath();
+ base::RunLoop run_loop;
+ profile_manager->CreateProfileAsync(
+ new_path, base::BindRepeating(&UnblockOnProfileCreation, &run_loop),
+ base::string16(), std::string());
+ run_loop.Run();
+ return profile_manager->GetProfileByPath(new_path);
+ }
+
+ bool use_builtin_cert_verifier() const { return GetParam(); }
+ bool enable_cert_verifier_service() const {
+ return enable_cert_verifier_service_;
+ }
+ void set_enable_cert_verifier_service(bool enable_cv_service) {
+ enable_cert_verifier_service_ = enable_cv_service;
+ }
+
private:
base::test::ScopedFeatureList scoped_feature_list_;
+ bool enable_cert_verifier_service_ = false;
+
+ // Used if enable_cert_verifier_service() returns true.
+ base::Optional<cert_verifier::TestCertVerifierServiceFactoryImpl>
+ test_cert_verifier_service_factory_;
};
IN_PROC_BROWSER_TEST_P(
@@ -468,10 +551,11 @@ IN_PROC_BROWSER_TEST_P(
/*in_memory=*/false, empty_relative_partition_path,
&network_context_params, &cert_verifier_creation_params);
- EXPECT_EQ(GetParam() ? network::mojom::CertVerifierCreationParams::
- CertVerifierImpl::kBuiltin
- : network::mojom::CertVerifierCreationParams::
- CertVerifierImpl::kSystem,
+ EXPECT_EQ(use_builtin_cert_verifier()
+ ? network::mojom::CertVerifierCreationParams::
+ CertVerifierImpl::kBuiltin
+ : network::mojom::CertVerifierCreationParams::
+ CertVerifierImpl::kSystem,
cert_verifier_creation_params.use_builtin_cert_verifier);
}
@@ -515,6 +599,68 @@ INSTANTIATE_TEST_SUITE_P(
All,
ProfileNetworkContextServiceCertVerifierBuiltinFeaturePolicyTest,
::testing::Bool());
+
+class
+ ProfileNetworkContextServiceCertVerifierBuiltinFeaturePolicyTestWithService
+ : public ProfileNetworkContextServiceCertVerifierBuiltinFeaturePolicyTest {
+ public:
+ ProfileNetworkContextServiceCertVerifierBuiltinFeaturePolicyTestWithService() {
+ set_enable_cert_verifier_service(true);
+ }
+
+ ~ProfileNetworkContextServiceCertVerifierBuiltinFeaturePolicyTestWithService()
+ override = default;
+};
+
+IN_PROC_BROWSER_TEST_P(
+ ProfileNetworkContextServiceCertVerifierBuiltinFeaturePolicyTestWithService,
+ Test) {
+ {
+ content::BrowserContext::GetDefaultStoragePartition(CreateNewProfile())
+ ->GetNetworkContext();
+
+ ExpectUseBuiltinCertVerifierCorrectUsingCertVerifierService(
+ use_builtin_cert_verifier()
+ ? network::mojom::CertVerifierCreationParams::CertVerifierImpl::
+ kBuiltin
+ : network::mojom::CertVerifierCreationParams::CertVerifierImpl::
+ kSystem);
+ }
+
+#if BUILDFLAG(BUILTIN_CERT_VERIFIER_POLICY_SUPPORTED)
+ // If the BuiltinCertificateVerifierEnabled policy is set it should override
+ // the feature flag.
+ policy::PolicyMap policies;
+ SetPolicy(&policies, policy::key::kBuiltinCertificateVerifierEnabled,
+ std::make_unique<base::Value>(true));
+ UpdateProviderPolicy(policies);
+
+ {
+ content::BrowserContext::GetDefaultStoragePartition(CreateNewProfile())
+ ->GetNetworkContext();
+
+ ExpectUseBuiltinCertVerifierCorrectUsingCertVerifierService(
+ network::mojom::CertVerifierCreationParams::CertVerifierImpl::kBuiltin);
+ }
+
+ SetPolicy(&policies, policy::key::kBuiltinCertificateVerifierEnabled,
+ std::make_unique<base::Value>(false));
+ UpdateProviderPolicy(policies);
+
+ {
+ content::BrowserContext::GetDefaultStoragePartition(CreateNewProfile())
+ ->GetNetworkContext();
+
+ ExpectUseBuiltinCertVerifierCorrectUsingCertVerifierService(
+ network::mojom::CertVerifierCreationParams::CertVerifierImpl::kSystem);
+ }
+#endif // BUILDFLAG(BUILTIN_CERT_VERIFIER_POLICY_SUPPORTED)
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ All,
+ ProfileNetworkContextServiceCertVerifierBuiltinFeaturePolicyTestWithService,
+ ::testing::Bool());
#endif // BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED)
enum class CorsTestMode {
diff --git a/chromium/chrome/browser/net/referrer_policy_policy_handler_unittest.cc b/chromium/chrome/browser/net/referrer_policy_policy_handler_unittest.cc
index afad0b0a15c..60035614c07 100644
--- a/chromium/chrome/browser/net/referrer_policy_policy_handler_unittest.cc
+++ b/chromium/chrome/browser/net/referrer_policy_policy_handler_unittest.cc
@@ -20,8 +20,7 @@ namespace policy {
class ReferrerPolicyPolicyHandlerTest : public testing::Test {
protected:
- void SetPolicyValue(const std::string& policy,
- std::unique_ptr<base::Value> value) {
+ void SetPolicyValue(const std::string& policy, base::Value value) {
policies_.Set(policy, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
POLICY_SOURCE_PLATFORM, std::move(value), nullptr);
}
@@ -57,8 +56,7 @@ TEST_F(ReferrerPolicyPolicyHandlerTest, NotSet) {
// Sanity check tests to ensure the policy errors have the correct name.
TEST_F(ReferrerPolicyPolicyHandlerTest, WrongType) {
// Do anything that causes a policy error.
- SetPolicyValue(key::kForceLegacyDefaultReferrerPolicy,
- std::make_unique<base::Value>(1));
+ SetPolicyValue(key::kForceLegacyDefaultReferrerPolicy, base::Value(1));
CheckAndApplyPolicySettings();
@@ -68,16 +66,14 @@ TEST_F(ReferrerPolicyPolicyHandlerTest, WrongType) {
}
TEST_F(ReferrerPolicyPolicyHandlerTest, ValueTrue) {
- SetPolicyValue(key::kForceLegacyDefaultReferrerPolicy,
- std::make_unique<base::Value>(true));
+ SetPolicyValue(key::kForceLegacyDefaultReferrerPolicy, base::Value(true));
CheckAndApplyPolicySettings();
EXPECT_TRUE(content::Referrer::ShouldForceLegacyDefaultReferrerPolicy());
}
TEST_F(ReferrerPolicyPolicyHandlerTest, ValueFalse) {
- SetPolicyValue(key::kForceLegacyDefaultReferrerPolicy,
- std::make_unique<base::Value>(false));
+ SetPolicyValue(key::kForceLegacyDefaultReferrerPolicy, base::Value(false));
CheckAndApplyPolicySettings();
EXPECT_FALSE(content::Referrer::ShouldForceLegacyDefaultReferrerPolicy());
diff --git a/chromium/chrome/browser/net/secure_dns_config.h b/chromium/chrome/browser/net/secure_dns_config.h
index f9d4ca156a4..3a65827ad8f 100644
--- a/chromium/chrome/browser/net/secure_dns_config.h
+++ b/chromium/chrome/browser/net/secure_dns_config.h
@@ -18,6 +18,8 @@ struct DnsOverHttpsServerConfig;
// Representation of a complete Secure DNS configuration.
class SecureDnsConfig {
public:
+ // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chrome.browser.net
+ // GENERATED_JAVA_CLASS_NAME_OVERRIDE: SecureDnsManagementMode
// Forced management description types. We will check for the override cases
// in the order they are listed in the enum.
enum class ManagementMode {
diff --git a/chromium/chrome/browser/net/secure_dns_util.cc b/chromium/chrome/browser/net/secure_dns_util.cc
index e1c342e3a14..d34c70398b4 100644
--- a/chromium/chrome/browser/net/secure_dns_util.cc
+++ b/chromium/chrome/browser/net/secure_dns_util.cc
@@ -8,12 +8,15 @@
#include <string>
#include "base/feature_list.h"
+#include "base/metrics/histogram_macros.h"
#include "base/strings/string_split.h"
#include "chrome/common/chrome_features.h"
+#include "components/country_codes/country_codes.h"
#include "components/embedder_support/pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "net/dns/dns_config_overrides.h"
+#include "net/dns/public/doh_provider_entry.h"
#include "net/dns/public/util.h"
#include "net/third_party/uri_template/uri_template.h"
#include "url/gurl.h"
@@ -26,6 +29,37 @@ namespace {
const char kAlternateErrorPagesBackup[] = "alternate_error_pages.backup";
+void IncrementDropdownHistogram(net::DohProviderIdForHistogram id,
+ const std::string& doh_template,
+ base::StringPiece old_template,
+ base::StringPiece new_template) {
+ if (doh_template == old_template) {
+ UMA_HISTOGRAM_ENUMERATION("Net.DNS.UI.DropdownSelectionEvent.Unselected",
+ id);
+ } else if (doh_template == new_template) {
+ UMA_HISTOGRAM_ENUMERATION("Net.DNS.UI.DropdownSelectionEvent.Selected", id);
+ } else {
+ UMA_HISTOGRAM_ENUMERATION("Net.DNS.UI.DropdownSelectionEvent.Ignored", id);
+ }
+}
+
+bool EntryIsForCountry(const net::DohProviderEntry* entry, int country_id) {
+ if (entry->display_globally) {
+ return true;
+ }
+ const auto& countries = entry->display_countries;
+ bool matches = std::any_of(countries.begin(), countries.end(),
+ [country_id](const std::string& country_code) {
+ return country_codes::CountryStringToCountryID(
+ country_code) == country_id;
+ });
+ if (matches) {
+ DCHECK(!entry->ui_name.empty());
+ DCHECK(!entry->privacy_policy.empty());
+ }
+ return matches;
+}
+
} // namespace
void RegisterProbesSettingBackupPref(PrefRegistrySimple* registry) {
@@ -68,6 +102,35 @@ void MigrateProbesSettingToOrFromBackup(PrefService* prefs) {
}
}
+net::DohProviderEntry::List ProvidersForCountry(
+ const net::DohProviderEntry::List& providers,
+ int country_id) {
+ net::DohProviderEntry::List local_providers;
+ std::copy_if(providers.begin(), providers.end(),
+ std::back_inserter(local_providers),
+ [country_id](const auto* entry) {
+ return EntryIsForCountry(entry, country_id);
+ });
+ return local_providers;
+}
+
+std::vector<std::string> GetDisabledProviders() {
+ return SplitString(features::kDnsOverHttpsDisabledProvidersParam.Get(), ",",
+ base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
+}
+
+net::DohProviderEntry::List RemoveDisabledProviders(
+ const net::DohProviderEntry::List& providers,
+ const std::vector<string>& disabled_providers) {
+ net::DohProviderEntry::List filtered_providers;
+ std::copy_if(providers.begin(), providers.end(),
+ std::back_inserter(filtered_providers),
+ [&disabled_providers](const auto* entry) {
+ return !base::Contains(disabled_providers, entry->provider);
+ });
+ return filtered_providers;
+}
+
std::vector<base::StringPiece> SplitGroup(base::StringPiece group) {
// Templates in a group are whitespace-separated.
return SplitStringPiece(group, " ", base::TRIM_WHITESPACE,
@@ -83,6 +146,28 @@ bool IsValidGroup(base::StringPiece group) {
});
}
+void UpdateDropdownHistograms(
+ const std::vector<const net::DohProviderEntry*>& providers,
+ base::StringPiece old_template,
+ base::StringPiece new_template) {
+ for (const auto* entry : providers) {
+ IncrementDropdownHistogram(entry->provider_id_for_histogram.value(),
+ entry->dns_over_https_template, old_template,
+ new_template);
+ }
+ // An empty template indicates a custom provider.
+ IncrementDropdownHistogram(net::DohProviderIdForHistogram::kCustom,
+ std::string(), old_template, new_template);
+}
+
+void UpdateValidationHistogram(bool valid) {
+ UMA_HISTOGRAM_BOOLEAN("Net.DNS.UI.ValidationAttemptSuccess", valid);
+}
+
+void UpdateProbeHistogram(bool success) {
+ UMA_HISTOGRAM_BOOLEAN("Net.DNS.UI.ProbeAttemptSuccess", success);
+}
+
void ApplyTemplate(net::DnsConfigOverrides* overrides,
base::StringPiece server_template) {
std::string server_method;
diff --git a/chromium/chrome/browser/net/secure_dns_util.h b/chromium/chrome/browser/net/secure_dns_util.h
index 98ec18fe744..8e6509ffcaf 100644
--- a/chromium/chrome/browser/net/secure_dns_util.h
+++ b/chromium/chrome/browser/net/secure_dns_util.h
@@ -8,6 +8,7 @@
#include <vector>
#include "base/strings/string_piece.h"
+#include "net/dns/public/doh_provider_entry.h"
namespace net {
struct DnsConfigOverrides;
@@ -20,6 +21,22 @@ namespace chrome_browser_net {
namespace secure_dns {
+// Returns the subset of |providers| that are marked for use in the specified
+// country.
+net::DohProviderEntry::List ProvidersForCountry(
+ const net::DohProviderEntry::List& providers,
+ int country_id);
+
+// Returns the names of providers that have been remotely disabled, for use with
+// RemoveDisabledProviders().
+std::vector<std::string> GetDisabledProviders();
+
+// Returns the subset of |providers| for which |DohProviderEntry::provider| is
+// not listed in |disabled_providers|.
+net::DohProviderEntry::List RemoveDisabledProviders(
+ const net::DohProviderEntry::List& providers,
+ const std::vector<std::string>& disabled_providers);
+
// Implements the whitespace-delimited group syntax for DoH templates.
std::vector<base::StringPiece> SplitGroup(base::StringPiece group);
@@ -28,6 +45,16 @@ std::vector<base::StringPiece> SplitGroup(base::StringPiece group);
// stored preferences.
bool IsValidGroup(base::StringPiece group);
+// When the selected template changes, call this function to update the
+// Selected, Unselected, and Ignored histograms for all the included providers,
+// and also for the custom provider option. If the old or new selection is the
+// custom provider option, pass an empty string as the template.
+void UpdateDropdownHistograms(const net::DohProviderEntry::List& providers,
+ base::StringPiece old_template,
+ base::StringPiece new_template);
+void UpdateValidationHistogram(bool valid);
+void UpdateProbeHistogram(bool success);
+
// Modifies |overrides| to use the DoH server specified by |server_template|.
void ApplyTemplate(net::DnsConfigOverrides* overrides,
base::StringPiece server_template);
diff --git a/chromium/chrome/browser/net/secure_dns_util_unittest.cc b/chromium/chrome/browser/net/secure_dns_util_unittest.cc
index d99da3b6e93..b68a7206096 100644
--- a/chromium/chrome/browser/net/secure_dns_util_unittest.cc
+++ b/chromium/chrome/browser/net/secure_dns_util_unittest.cc
@@ -6,12 +6,15 @@
#include <memory>
+#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/common/chrome_features.h"
+#include "components/country_codes/country_codes.h"
#include "components/embedder_support/pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
#include "net/dns/dns_config_overrides.h"
+#include "net/dns/public/doh_provider_entry.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -27,7 +30,7 @@ const char kAlternateErrorPagesBackup[] = "alternate_error_pages.backup";
namespace secure_dns {
-class DNSUtilTest : public testing::Test {
+class SecureDnsUtilTest : public testing::Test {
public:
void SetUp() override { DisableRedesign(); }
@@ -37,13 +40,17 @@ class DNSUtilTest : public testing::Test {
features::kPrivacySettingsRedesign, base::FieldTrialParams());
}
- void DisableRedesign() { scoped_feature_list_.Reset(); }
+ void DisableRedesign() {
+ scoped_feature_list_.Reset();
+ scoped_feature_list_.InitAndDisableFeature(
+ features::kPrivacySettingsRedesign);
+ }
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
-TEST_F(DNSUtilTest, MigrateProbesPref) {
+TEST_F(SecureDnsUtilTest, MigrateProbesPref) {
TestingPrefServiceSimple prefs;
prefs.registry()->RegisterBooleanPref(
embedder_support::kAlternateErrorPagesEnabled, true);
@@ -150,14 +157,14 @@ TEST_F(DNSUtilTest, MigrateProbesPref) {
EXPECT_FALSE(backup_pref->HasUserSetting());
}
-TEST(DNSUtil, SplitGroup) {
+TEST(SecureDnsUtil, SplitGroup) {
EXPECT_THAT(SplitGroup("a"), ElementsAre("a"));
EXPECT_THAT(SplitGroup("a b"), ElementsAre("a", "b"));
EXPECT_THAT(SplitGroup("a \tb\nc"), ElementsAre("a", "b\nc"));
EXPECT_THAT(SplitGroup(" \ta b\n"), ElementsAre("a", "b"));
}
-TEST(DNSUtil, IsValidGroup) {
+TEST(SecureDnsUtil, IsValidGroup) {
EXPECT_TRUE(IsValidGroup(""));
EXPECT_TRUE(IsValidGroup("https://valid"));
EXPECT_TRUE(IsValidGroup("https://valid https://valid2"));
@@ -168,7 +175,7 @@ TEST(DNSUtil, IsValidGroup) {
EXPECT_FALSE(IsValidGroup("invalid invalid2"));
}
-TEST(DNSUtil, ApplyDohTemplatePost) {
+TEST(SecureDnsUtil, ApplyDohTemplatePost) {
std::string post_template("https://valid");
net::DnsConfigOverrides overrides;
ApplyTemplate(&overrides, post_template);
@@ -178,7 +185,7 @@ TEST(DNSUtil, ApplyDohTemplatePost) {
{post_template, true /* use_post */}))));
}
-TEST(DNSUtil, ApplyDohTemplateGet) {
+TEST(SecureDnsUtil, ApplyDohTemplateGet) {
std::string get_template("https://valid/{?dns}");
net::DnsConfigOverrides overrides;
ApplyTemplate(&overrides, get_template);
@@ -188,6 +195,105 @@ TEST(DNSUtil, ApplyDohTemplateGet) {
{get_template, false /* use_post */}))));
}
+net::DohProviderEntry::List GetProvidersForTesting() {
+ static const auto global1 = net::DohProviderEntry::ConstructForTesting(
+ "Provider_Global1", net::DohProviderIdForHistogram(-1), {} /*ip_strs */,
+ {} /* dot_hostnames */, "https://global1.provider/dns-query{?dns}",
+ "Global Provider 1" /* ui_name */,
+ "https://global1.provider/privacy_policy/" /* privacy_policy */,
+ true /* display_globally */, {} /* display_countries */);
+ static const auto no_display = net::DohProviderEntry::ConstructForTesting(
+ "Provider_NoDisplay", net::DohProviderIdForHistogram(-2), {} /*ip_strs */,
+ {} /* dot_hostnames */, "https://nodisplay.provider/dns-query{?dns}",
+ "No Display Provider" /* ui_name */,
+ "https://nodisplay.provider/privacy_policy/" /* privacy_policy */,
+ false /* display_globally */, {} /* display_countries */);
+ static const auto ee_fr = net::DohProviderEntry::ConstructForTesting(
+ "Provider_EE_FR", net::DohProviderIdForHistogram(-3), {} /*ip_strs */,
+ {} /* dot_hostnames */, "https://ee.fr.provider/dns-query{?dns}",
+ "EE/FR Provider" /* ui_name */,
+ "https://ee.fr.provider/privacy_policy/" /* privacy_policy */,
+ false /* display_globally */, {"EE", "FR"} /* display_countries */);
+ static const auto fr = net::DohProviderEntry::ConstructForTesting(
+ "Provider_FR", net::DohProviderIdForHistogram(-4), {} /*ip_strs */,
+ {} /* dot_hostnames */, "https://fr.provider/dns-query{?dns}",
+ "FR Provider" /* ui_name */,
+ "https://fr.provider/privacy_policy/" /* privacy_policy */,
+ false /* display_globally */, {"FR"} /* display_countries */);
+ static const auto global2 = net::DohProviderEntry::ConstructForTesting(
+ "Provider_Global2", net::DohProviderIdForHistogram(-5), {} /*ip_strs */,
+ {} /* dot_hostnames */, "https://global2.provider/dns-query{?dns}",
+ "Global Provider 2" /* ui_name */,
+ "https://global2.provider/privacy_policy/" /* privacy_policy */,
+ true /* display_globally */, {} /* display_countries */);
+ return {&global1, &no_display, &ee_fr, &fr, &global2};
+}
+
+TEST(SecureDnsUtil, LocalProviders) {
+ const auto providers = GetProvidersForTesting();
+
+ const auto fr_providers = ProvidersForCountry(
+ providers, country_codes::CountryStringToCountryID("FR"));
+ EXPECT_THAT(fr_providers, ElementsAre(providers[0], providers[2],
+ providers[3], providers[4]));
+
+ const auto ee_providers = ProvidersForCountry(
+ providers, country_codes::CountryStringToCountryID("EE"));
+ EXPECT_THAT(ee_providers,
+ ElementsAre(providers[0], providers[2], providers[4]));
+
+ const auto us_providers = ProvidersForCountry(
+ providers, country_codes::CountryStringToCountryID("US"));
+ EXPECT_THAT(us_providers, ElementsAre(providers[0], providers[4]));
+
+ const auto unknown_providers =
+ ProvidersForCountry(providers, country_codes::kCountryIDUnknown);
+ EXPECT_THAT(unknown_providers, ElementsAre(providers[0], providers[4]));
+}
+
+TEST(SecureDnsUtil, DisabledProviders) {
+ base::test::ScopedFeatureList scoped_features;
+ scoped_features.InitAndEnableFeatureWithParameters(
+ features::kDnsOverHttps,
+ {{"DisabledProviders", "Provider_Global2, , Provider_EE_FR,Unexpected"}});
+ EXPECT_THAT(GetDisabledProviders(),
+ ElementsAre("Provider_Global2", "Provider_EE_FR", "Unexpected"));
+}
+
+TEST(SecureDnsUtil, RemoveDisabled) {
+ const auto providers = GetProvidersForTesting();
+ const auto filtered_providers = RemoveDisabledProviders(
+ providers, {"Provider_Global2", "", "Provider_EE_FR", "Unexpected"});
+ EXPECT_THAT(filtered_providers,
+ ElementsAre(providers[0], providers[1], providers[3]));
+}
+
+TEST(SecureDnsUtil, UpdateDropdownHistograms) {
+ base::HistogramTester histograms;
+
+ const auto providers = GetProvidersForTesting();
+ UpdateDropdownHistograms(providers, providers[4]->dns_over_https_template,
+ providers[0]->dns_over_https_template);
+
+ const std::string kUmaBase = "Net.DNS.UI.DropdownSelectionEvent";
+ histograms.ExpectTotalCount(kUmaBase + ".Ignored", 4u);
+ histograms.ExpectTotalCount(kUmaBase + ".Selected", 1u);
+ histograms.ExpectTotalCount(kUmaBase + ".Unselected", 1u);
+}
+
+TEST(SecureDnsUtil, UpdateDropdownHistogramsCustom) {
+ base::HistogramTester histograms;
+
+ const auto providers = GetProvidersForTesting();
+ UpdateDropdownHistograms(providers, std::string(),
+ providers[2]->dns_over_https_template);
+
+ const std::string kUmaBase = "Net.DNS.UI.DropdownSelectionEvent";
+ histograms.ExpectTotalCount(kUmaBase + ".Ignored", 4u);
+ histograms.ExpectTotalCount(kUmaBase + ".Selected", 1u);
+ histograms.ExpectTotalCount(kUmaBase + ".Unselected", 1u);
+}
+
} // namespace secure_dns
} // namespace chrome_browser_net
diff --git a/chromium/chrome/browser/net/storage_test_utils.cc b/chromium/chrome/browser/net/storage_test_utils.cc
new file mode 100644
index 00000000000..d2a26814fc8
--- /dev/null
+++ b/chromium/chrome/browser/net/storage_test_utils.cc
@@ -0,0 +1,102 @@
+// Copyright (c) 2020 The Chromium 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/net/storage_test_utils.h"
+
+#include "content/public/test/browser_test_utils.h"
+
+namespace storage {
+namespace test {
+
+const std::vector<std::string> kStorageTypes{
+ "Cookie", "LocalStorage", "FileSystem", "SessionStorage", "IndexedDb",
+ "WebSql", "CacheStorage", "ServiceWorker", "CookieStore"};
+
+const std::vector<std::string> kCrossTabCommunicationTypes{
+ "SharedWorker",
+ "WebLock",
+};
+
+constexpr char kRequestStorageAccess[] =
+ "document.requestStorageAccess().then("
+ " () => { window.domAutomationController.send(true); },"
+ " () => { window.domAutomationController.send(false); },"
+ ");";
+
+constexpr char kHasStorageAccess[] =
+ "document.hasStorageAccess().then("
+ " (result) => { window.domAutomationController.send(result); },"
+ " () => { window.domAutomationController.send(false); },"
+ ");";
+
+void ExpectFrameContent(content::RenderFrameHost* frame,
+ const std::string& expected) {
+ std::string content;
+ ASSERT_TRUE(ExecuteScriptAndExtractString(
+ frame, "window.domAutomationController.send(document.body.textContent)",
+ &content));
+ EXPECT_EQ(expected, content);
+}
+
+void ExpectCookiesOnHost(content::BrowserContext* context,
+ const GURL& host_url,
+ const std::string& expected) {
+ EXPECT_EQ(expected, content::GetCookies(context, host_url));
+}
+
+void SetStorageForFrame(content::RenderFrameHost* frame) {
+ for (const auto& data_type : kStorageTypes) {
+ bool data = false;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
+ frame, "set" + data_type + "()", &data));
+ EXPECT_TRUE(data) << data_type;
+ }
+}
+
+void ExpectStorageForFrame(content::RenderFrameHost* frame, bool expected) {
+ for (const auto& data_type : kStorageTypes) {
+ bool data = false;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
+ frame, "has" + data_type + "();", &data));
+ EXPECT_EQ(expected, data) << data_type;
+ }
+}
+
+void SetCrossTabInfoForFrame(content::RenderFrameHost* frame) {
+ for (const auto& data_type : kCrossTabCommunicationTypes) {
+ bool data = false;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
+ frame, "set" + data_type + "()", &data));
+ EXPECT_TRUE(data) << data_type;
+ }
+}
+
+void ExpectCrossTabInfoForFrame(content::RenderFrameHost* frame,
+ bool expected) {
+ for (const auto& data_type : kCrossTabCommunicationTypes) {
+ bool data = false;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
+ frame, "has" + data_type + "();", &data));
+ EXPECT_EQ(expected, data) << data_type;
+ }
+}
+
+void RequestStorageAccessForFrame(content::RenderFrameHost* frame,
+ bool should_resolve) {
+ bool data = false;
+ EXPECT_TRUE(content::ExecuteScriptAndExtractBool(frame, kRequestStorageAccess,
+ &data));
+ EXPECT_EQ(should_resolve, data) << "document.requestStorageAccess()";
+}
+
+void CheckStorageAccessForFrame(content::RenderFrameHost* frame,
+ bool access_expected) {
+ bool data = false;
+ EXPECT_TRUE(
+ content::ExecuteScriptAndExtractBool(frame, kHasStorageAccess, &data));
+ EXPECT_EQ(access_expected, data) << "document.hasStorageAccess()";
+}
+
+} // namespace test
+} // namespace storage
diff --git a/chromium/chrome/browser/net/storage_test_utils.h b/chromium/chrome/browser/net/storage_test_utils.h
new file mode 100644
index 00000000000..b997843b400
--- /dev/null
+++ b/chromium/chrome/browser/net/storage_test_utils.h
@@ -0,0 +1,51 @@
+// Copyright 2020 The Chromium 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_NET_STORAGE_TEST_UTILS_H_
+#define CHROME_BROWSER_NET_STORAGE_TEST_UTILS_H_
+
+#include <string>
+
+class GURL;
+
+namespace content {
+class BrowserContext;
+class RenderFrameHost;
+} // namespace content
+
+namespace storage {
+namespace test {
+
+// Helper to validate a given frame contains the |expected| contents as their
+// document body.
+void ExpectFrameContent(content::RenderFrameHost* frame,
+ const std::string& expected);
+// Helper to validate a given for a given |context| and |host_url| that
+// |expected| cookies are present.
+void ExpectCookiesOnHost(content::BrowserContext* context,
+ const GURL& host_url,
+ const std::string& expected);
+
+// Helpers to set and check various types of storage on a given frame. Typically
+// used on page like //chrome/test/data/browsing_data/site_data.html
+void SetStorageForFrame(content::RenderFrameHost* frame);
+void ExpectStorageForFrame(content::RenderFrameHost* frame, bool expected);
+
+// Helpers to set and check various types of cross tab info for a given frame.
+// Typically used on page like //chrome/test/data/browsing_data/site_data.html
+void SetCrossTabInfoForFrame(content::RenderFrameHost* frame);
+void ExpectCrossTabInfoForFrame(content::RenderFrameHost* frame, bool expected);
+
+// Helper to request storage access for a frame using
+// document.requestStorageAccess()
+void RequestStorageAccessForFrame(content::RenderFrameHost* frame,
+ bool should_resolve);
+// Helper to validate if a frame currently has storage access using
+// document.hasStorageAccess()
+void CheckStorageAccessForFrame(content::RenderFrameHost* frame,
+ bool access_expected);
+
+} // namespace test
+} // namespace storage
+#endif // CHROME_BROWSER_NET_STORAGE_TEST_UTILS_H_
diff --git a/chromium/chrome/browser/net/stub_resolver_config_reader.cc b/chromium/chrome/browser/net/stub_resolver_config_reader.cc
index 37e70c07c4c..fd6f5bfa473 100644
--- a/chromium/chrome/browser/net/stub_resolver_config_reader.cc
+++ b/chromium/chrome/browser/net/stub_resolver_config_reader.cc
@@ -36,6 +36,7 @@
#if defined(OS_ANDROID)
#include "base/android/build_info.h"
+#include "chrome/browser/enterprise/util/android_enterprise_info.h"
#endif
#if defined(OS_WIN)
@@ -172,8 +173,17 @@ StubResolverConfigReader::StubResolverConfigReader(PrefService* local_state,
FROM_HERE, kParentalControlsCheckDelay,
base::BindOnce(&StubResolverConfigReader::OnParentalControlsDelayTimer,
base::Unretained(this)));
+
+#if defined(OS_ANDROID)
+ chrome::enterprise_util::AndroidEnterpriseInfo::GetInstance()
+ ->GetAndroidEnterpriseInfoState(base::BindOnce(
+ &StubResolverConfigReader::OnAndroidOwnedStateCheckComplete,
+ weak_factory_.GetWeakPtr()));
+#endif
}
+StubResolverConfigReader::~StubResolverConfigReader() = default;
+
// static
void StubResolverConfigReader::RegisterPrefs(PrefRegistrySimple* registry) {
// Register the DnsClient and DoH preferences. The feature list has not been
@@ -201,14 +211,25 @@ void StubResolverConfigReader::UpdateNetworkService(bool record_metrics) {
}
bool StubResolverConfigReader::ShouldDisableDohForManaged() {
-#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
- if (g_browser_process->browser_policy_connector()->HasMachineLevelPolicies())
+// This function ignores cloud policies which are loaded on a per-profile basis.
+#if defined(OS_ANDROID)
+ // Check for MDM/management/owner apps. android_has_owner_ is true if either a
+ // device or policy owner app is discovered by
+ // GetAndroidEnterpriseInfoState(). If android_has_owner_ is nullopt, take a
+ // value of false so that we don't disable DoH during the async check.
+
+ // Because Android policies can only be loaded with owner apps this is
+ // sufficient to check for the prescences of policies as well.
+ if (android_has_owner_.value_or(false))
return true;
-#endif
-#if defined(OS_WIN)
+#elif defined(OS_WIN)
if (base::IsMachineExternallyManaged())
return true;
#endif
+#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
+ if (g_browser_process->browser_policy_connector()->HasMachineLevelPolicies())
+ return true;
+#endif
return false;
}
@@ -242,6 +263,8 @@ SecureDnsConfig StubResolverConfigReader::GetAndUpdateConfiguration(
bool force_check_parental_controls_for_automatic_mode,
bool record_metrics,
bool update_network_service) {
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+
net::DnsConfig::SecureDnsMode secure_dns_mode;
SecureDnsModeDetailsForHistogram mode_details;
SecureDnsConfig::ManagementMode forced_management_mode =
@@ -367,3 +390,15 @@ SecureDnsConfig StubResolverConfigReader::GetAndUpdateConfiguration(
return SecureDnsConfig(secure_dns_mode, std::move(dns_over_https_servers),
forced_management_mode);
}
+
+#if defined(OS_ANDROID)
+void StubResolverConfigReader::OnAndroidOwnedStateCheckComplete(
+ bool has_profile_owner,
+ bool has_device_owner) {
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
+ android_has_owner_ = has_profile_owner || has_device_owner;
+ // update the network service if the actual result is "true" to save time.
+ if (android_has_owner_.value())
+ UpdateNetworkService(false /* record_metrics */);
+}
+#endif
diff --git a/chromium/chrome/browser/net/stub_resolver_config_reader.h b/chromium/chrome/browser/net/stub_resolver_config_reader.h
index 3aedabd184e..d69b3b301c7 100644
--- a/chromium/chrome/browser/net/stub_resolver_config_reader.h
+++ b/chromium/chrome/browser/net/stub_resolver_config_reader.h
@@ -6,11 +6,17 @@
#define CHROME_BROWSER_NET_STUB_RESOLVER_CONFIG_READER_H_
#include "base/optional.h"
+#include "base/sequence_checker.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
+#include "build/build_config.h"
#include "components/prefs/pref_change_registrar.h"
#include "services/network/public/mojom/host_resolver.mojom-forward.h"
+#if defined(OS_ANDROID)
+#include "base/memory/weak_ptr.h"
+#endif
+
class PrefRegistrySimple;
class PrefService;
class SecureDnsConfig;
@@ -28,7 +34,7 @@ class StubResolverConfigReader {
StubResolverConfigReader(const StubResolverConfigReader&) = delete;
StubResolverConfigReader& operator=(const StubResolverConfigReader&) = delete;
- virtual ~StubResolverConfigReader() = default;
+ virtual ~StubResolverConfigReader();
static void RegisterPrefs(PrefRegistrySimple* registry);
@@ -51,16 +57,23 @@ class StubResolverConfigReader {
// Updates the network service with the current configuration.
void UpdateNetworkService(bool record_metrics);
- // Returns true if there are any active machine level policies or if the
- // machine is domain joined. This special logic is used to disable DoH by
- // default for Desktop platforms (the enterprise policy field
- // default_for_enterprise_users only applies to ChromeOS). We don't attempt
- // enterprise detection on Android at this time.
+ // Returns true if there are any active machine level policies, if the
+ // machine is domain joined (Windows), or any device or profile owner apps are
+ // installed (Android). This special logic is used to disable DoH by default
+ // for Desktop platforms and Android. ChromeOS is handled by the enterprise
+ // policy field "default_for_enterprise_users".
virtual bool ShouldDisableDohForManaged();
// Returns true if there are parental controls detected on the device.
virtual bool ShouldDisableDohForParentalControls();
+#if defined(OS_ANDROID)
+ // Updates the android owned state and network service if the device/prfile is
+ // owned.
+ void OnAndroidOwnedStateCheckComplete(bool has_profile_owner,
+ bool has_device_owner);
+#endif
+
private:
void OnParentalControlsDelayTimer();
@@ -81,7 +94,20 @@ class StubResolverConfigReader {
// expiration of the delay timer or because of a forced check.
bool parental_controls_checked_ = false;
+ // This object lives on the UI thread, but it's possible for it to be created
+ // before BrowserMainLoop::CreateThreads() is called which would cause a
+ // DCHECK for the UI thread to fail (as the UI thread hasn't been
+ // named yet). Using a sequence checker works around this.
+ SEQUENCE_CHECKER(sequence_checker_);
+
PrefChangeRegistrar pref_change_registrar_;
+
+#if defined(OS_ANDROID)
+ // Whether or not an Android device or profile is owned.
+ // A nullopt indicates this value has not been determined yet.
+ base::Optional<bool> android_has_owner_ = base::nullopt;
+ base::WeakPtrFactory<StubResolverConfigReader> weak_factory_{this};
+#endif
};
#endif // CHROME_BROWSER_NET_STUB_RESOLVER_CONFIG_READER_H_
diff --git a/chromium/chrome/browser/net/system_network_context_manager.cc b/chromium/chrome/browser/net/system_network_context_manager.cc
index bb3b12d4667..2163341048b 100644
--- a/chromium/chrome/browser/net/system_network_context_manager.cc
+++ b/chromium/chrome/browser/net/system_network_context_manager.cc
@@ -46,7 +46,6 @@
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/cors_exempt_headers.h"
#include "content/public/browser/network_context_client_base.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/common/content_features.h"
@@ -56,14 +55,17 @@
#include "content/public/common/user_agent.h"
#include "crypto/sha2.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "net/base/features.h"
#include "net/net_buildflags.h"
#include "net/third_party/uri_template/uri_template.h"
+#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h"
#include "services/network/network_service.h"
#include "services/network/public/cpp/cross_thread_pending_shared_url_loader_factory.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
+#include "services/network/public/mojom/cert_verifier_service.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/proxy_resolver/public/mojom/proxy_resolver.mojom.h"
#include "third_party/blink/public/common/features.h"
@@ -273,6 +275,7 @@ SystemNetworkContextManager::GetURLLoaderFactory() {
params->process_id = network::mojom::kBrowserProcessId;
params->is_corb_enabled = false;
params->is_trusted = true;
+
url_loader_factory_.reset();
GetContext()->CreateURLLoaderFactory(
url_loader_factory_.BindNewPipeAndPassReceiver(), std::move(params));
@@ -473,8 +476,6 @@ void SystemNetworkContextManager::OnNetworkServiceCreated(
if (max_connections_per_proxy != -1)
network_service->SetMaxConnectionsPerProxy(max_connections_per_proxy);
- // The system NetworkContext must be created first, since it sets
- // |primary_network_context| to true.
network_service_network_context_.reset();
network_service->CreateNetworkContext(
network_service_network_context_.BindNewPipeAndPassReceiver(),
@@ -539,7 +540,6 @@ void SystemNetworkContextManager::AddSSLConfigToNetworkContextParams(
void SystemNetworkContextManager::ConfigureDefaultNetworkContextParams(
network::mojom::NetworkContextParams* network_context_params,
network::mojom::CertVerifierCreationParams* cert_verifier_creation_params) {
- content::UpdateCorsExemptHeader(network_context_params);
variations::UpdateCorsExemptHeaderForVariations(network_context_params);
GoogleURLLoaderThrottle::UpdateCorsExemptHeader(network_context_params);
@@ -648,8 +648,8 @@ SystemNetworkContextManager::CreateDefaultNetworkContextParams() {
network::mojom::CertVerifierCreationParams::New();
ConfigureDefaultNetworkContextParams(network_context_params.get(),
cert_verifier_creation_params.get());
- network_context_params->cert_verifier_creation_params =
- std::move(cert_verifier_creation_params);
+ network_context_params->cert_verifier_params =
+ content::GetCertVerifierParams(std::move(cert_verifier_creation_params));
return network_context_params;
}
@@ -710,8 +710,6 @@ SystemNetworkContextManager::CreateNetworkContextParams() {
base::FeatureList::IsEnabled(features::kFtpProtocol);
#endif
- network_context_params->primary_network_context = true;
-
proxy_config_monitor_.AddToNetworkContextParams(network_context_params.get());
return network_context_params;
diff --git a/chromium/chrome/browser/net/system_network_context_manager.h b/chromium/chrome/browser/net/system_network_context_manager.h
index 38ddec6c873..daaad39c801 100644
--- a/chromium/chrome/browser/net/system_network_context_manager.h
+++ b/chromium/chrome/browser/net/system_network_context_manager.h
@@ -9,6 +9,7 @@
#include <string>
#include <vector>
+#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/optional.h"
@@ -123,9 +124,12 @@ class SystemNetworkContextManager {
network::mojom::CertVerifierCreationParams*
cert_verifier_creation_params);
- // Same as ConfigureDefaultNetworkContextParams() but returns a newly
- // allocated network::mojom::NetworkContextParams with the
- // CertVerifierCreationParams already placed into the NetworkContextParams.
+ // Performs the same function as ConfigureDefaultNetworkContextParams(), and
+ // then returns a newly allocated network::mojom::NetworkContextParams with
+ // some modifications: if the CertVerifierService is enabled, the new
+ // NetworkContextParams will contain a CertVerifierServiceRemoteParams.
+ // Otherwise the newly configured CertVerifierCreationParams is placed
+ // directly into the NetworkContextParams.
network::mojom::NetworkContextParamsPtr CreateDefaultNetworkContextParams();
// Returns a shared global NetExportFileWriter instance, used by net-export.
@@ -160,6 +164,10 @@ class SystemNetworkContextManager {
}
private:
+ FRIEND_TEST_ALL_PREFIXES(
+ SystemNetworkContextServiceCertVerifierBuiltinFeaturePolicyTest,
+ Test);
+
class URLLoaderFactoryForSystem;
// Constructor. |pref_service| must out live this object.
diff --git a/chromium/chrome/browser/net/system_network_context_manager_browsertest.cc b/chromium/chrome/browser/net/system_network_context_manager_browsertest.cc
index f1b01f338ac..ae771b3c86e 100644
--- a/chromium/chrome/browser/net/system_network_context_manager_browsertest.cc
+++ b/chromium/chrome/browser/net/system_network_context_manager_browsertest.cc
@@ -21,8 +21,11 @@
#include "chrome/test/base/in_process_browser_test.h"
#include "components/prefs/pref_service.h"
#include "components/version_info/version_info.h"
+#include "content/public/browser/network_service_instance.h"
#include "content/public/common/user_agent.h"
#include "content/public/test/browser_test.h"
+#include "services/cert_verifier/test_cert_verifier_service_factory.h"
+#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/network_service_buildflags.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/network_service.mojom.h"
@@ -325,9 +328,9 @@ class SystemNetworkContextManagerReferrersFeatureBrowsertest
// value of the kEnableReferrers pref.
IN_PROC_BROWSER_TEST_P(SystemNetworkContextManagerReferrersFeatureBrowsertest,
TestDefaultReferrerReflectsFeatureValue) {
- ASSERT_TRUE(!!g_browser_process);
+ ASSERT_TRUE(g_browser_process);
PrefService* local_state = g_browser_process->local_state();
- ASSERT_TRUE(!!local_state);
+ ASSERT_TRUE(local_state);
EXPECT_NE(local_state->GetBoolean(prefs::kEnableReferrers), GetParam());
}
@@ -458,57 +461,136 @@ INSTANTIATE_TEST_SUITE_P(
#if BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED)
class SystemNetworkContextServiceCertVerifierBuiltinFeaturePolicyTest
: public policy::PolicyTest,
- public testing::WithParamInterface<bool> {
+ public testing::WithParamInterface<std::tuple<bool, bool>> {
public:
+ SystemNetworkContextServiceCertVerifierBuiltinFeaturePolicyTest() {
+ bool use_builtin_cert_verifier;
+ std::tie(use_builtin_cert_verifier, enable_cert_verification_service_) =
+ GetParam();
+ cert_verifier_impl_ = use_builtin_cert_verifier
+ ? network::mojom::CertVerifierCreationParams::
+ CertVerifierImpl::kBuiltin
+ : network::mojom::CertVerifierCreationParams::
+ CertVerifierImpl::kSystem;
+ }
+
void SetUpInProcessBrowserTestFixture() override {
- scoped_feature_list_.InitWithFeatureState(
- net::features::kCertVerifierBuiltinFeature,
- /*enabled=*/GetParam());
+ std::vector<base::Feature> enabled_features, disabled_features;
+ if (cert_verifier_impl_ == network::mojom::CertVerifierCreationParams::
+ CertVerifierImpl::kBuiltin) {
+ enabled_features.push_back(net::features::kCertVerifierBuiltinFeature);
+ } else {
+ disabled_features.push_back(net::features::kCertVerifierBuiltinFeature);
+ }
+ if (enable_cert_verification_service_) {
+ enabled_features.push_back(network::features::kCertVerifierService);
+ test_cert_verifier_service_factory_.emplace();
+ content::SetCertVerifierServiceFactoryForTesting(
+ &test_cert_verifier_service_factory_.value());
+ } else {
+ disabled_features.push_back(network::features::kCertVerifierService);
+ }
+ scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features);
policy::PolicyTest::SetUpInProcessBrowserTestFixture();
}
+ void TearDownInProcessBrowserTestFixture() override {
+ content::SetCertVerifierServiceFactoryForTesting(nullptr);
+ }
+
+ void SetUpOnMainThread() override {
+ if (enable_cert_verification_service_) {
+ test_cert_verifier_service_factory_->ReleaseAllCertVerifierParams();
+ }
+ }
+
+ void ExpectUseBuiltinCertVerifierCorrect(
+ network::mojom::NetworkContextParamsPtr& network_context_params_ptr,
+ network::mojom::CertVerifierCreationParams::CertVerifierImpl
+ use_builtin_cert_verifier) {
+ ASSERT_TRUE(network_context_params_ptr);
+ ASSERT_TRUE(network_context_params_ptr->cert_verifier_params);
+ if (enable_cert_verification_service_) {
+ EXPECT_TRUE(
+ network_context_params_ptr->cert_verifier_params->is_remote_params());
+ ASSERT_TRUE(test_cert_verifier_service_factory_);
+ ASSERT_EQ(1ul,
+ test_cert_verifier_service_factory_->num_captured_params());
+ ASSERT_TRUE(test_cert_verifier_service_factory_->GetParamsAtIndex(0)
+ ->creation_params);
+ EXPECT_EQ(use_builtin_cert_verifier,
+ test_cert_verifier_service_factory_->GetParamsAtIndex(0)
+ ->creation_params->use_builtin_cert_verifier);
+ // Send it to the actual CertVerifierServiceFactory.
+ test_cert_verifier_service_factory_->ReleaseNextCertVerifierParams();
+ } else {
+ ASSERT_TRUE(network_context_params_ptr->cert_verifier_params
+ ->is_creation_params());
+ EXPECT_EQ(use_builtin_cert_verifier,
+ network_context_params_ptr->cert_verifier_params
+ ->get_creation_params()
+ ->use_builtin_cert_verifier);
+ }
+ }
+
+ network::mojom::CertVerifierCreationParams::CertVerifierImpl
+ cert_verifier_impl() const {
+ return cert_verifier_impl_;
+ }
+
private:
+ network::mojom::CertVerifierCreationParams::CertVerifierImpl
+ cert_verifier_impl_;
+ bool enable_cert_verification_service_;
base::test::ScopedFeatureList scoped_feature_list_;
+
+ // Used if |enable_cert_verification_service_| set to true.
+ base::Optional<cert_verifier::TestCertVerifierServiceFactoryImpl>
+ test_cert_verifier_service_factory_;
};
IN_PROC_BROWSER_TEST_P(
SystemNetworkContextServiceCertVerifierBuiltinFeaturePolicyTest,
Test) {
+ network::mojom::NetworkContextParamsPtr network_context_params_ptr;
+
// If no BuiltinCertificateVerifierEnabled policy is set, the
// use_builtin_cert_verifier param should be set from the feature flag.
- EXPECT_EQ(GetParam() ? network::mojom::CertVerifierCreationParams::
- CertVerifierImpl::kBuiltin
- : network::mojom::CertVerifierCreationParams::
- CertVerifierImpl::kSystem,
- g_browser_process->system_network_context_manager()
- ->CreateDefaultNetworkContextParams()
- ->cert_verifier_creation_params->use_builtin_cert_verifier);
+ network_context_params_ptr =
+ g_browser_process->system_network_context_manager()
+ ->CreateDefaultNetworkContextParams();
+ ExpectUseBuiltinCertVerifierCorrect(network_context_params_ptr,
+ cert_verifier_impl());
#if BUILDFLAG(BUILTIN_CERT_VERIFIER_POLICY_SUPPORTED)
- // If the BuiltinCertificateVerifierEnabled policy is set it should override
- // the feature flag.
+ // If the BuiltinCertificateVerifierEnabled policy is set it should
+ // override the feature flag.
policy::PolicyMap policies;
SetPolicy(&policies, policy::key::kBuiltinCertificateVerifierEnabled,
std::make_unique<base::Value>(true));
UpdateProviderPolicy(policies);
- EXPECT_EQ(
- network::mojom::CertVerifierCreationParams::CertVerifierImpl::kBuiltin,
+
+ network_context_params_ptr =
g_browser_process->system_network_context_manager()
- ->CreateDefaultNetworkContextParams()
- ->cert_verifier_creation_params->use_builtin_cert_verifier);
+ ->CreateDefaultNetworkContextParams();
+ ExpectUseBuiltinCertVerifierCorrect(
+ network_context_params_ptr,
+ network::mojom::CertVerifierCreationParams::CertVerifierImpl::kBuiltin);
SetPolicy(&policies, policy::key::kBuiltinCertificateVerifierEnabled,
std::make_unique<base::Value>(false));
UpdateProviderPolicy(policies);
- EXPECT_EQ(
- network::mojom::CertVerifierCreationParams::CertVerifierImpl::kSystem,
+
+ network_context_params_ptr =
g_browser_process->system_network_context_manager()
- ->CreateDefaultNetworkContextParams()
- ->cert_verifier_creation_params->use_builtin_cert_verifier);
+ ->CreateDefaultNetworkContextParams();
+ ExpectUseBuiltinCertVerifierCorrect(
+ network_context_params_ptr,
+ network::mojom::CertVerifierCreationParams::CertVerifierImpl::kSystem);
#endif // BUILDFLAG(BUILTIN_CERT_VERIFIER_POLICY_SUPPORTED)
}
INSTANTIATE_TEST_SUITE_P(
All,
SystemNetworkContextServiceCertVerifierBuiltinFeaturePolicyTest,
- ::testing::Bool());
+ ::testing::Combine(::testing::Bool(), ::testing::Bool()));
#endif // BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED)
diff --git a/chromium/chrome/browser/net/trial_comparison_cert_verifier_browsertest.cc b/chromium/chrome/browser/net/trial_comparison_cert_verifier_browsertest.cc
index 1c431c79806..10ec923fc43 100644
--- a/chromium/chrome/browser/net/trial_comparison_cert_verifier_browsertest.cc
+++ b/chromium/chrome/browser/net/trial_comparison_cert_verifier_browsertest.cc
@@ -5,13 +5,13 @@
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
-#include "chrome/browser/metrics/subprocess_metrics_provider.h"
#include "chrome/browser/net/trial_comparison_cert_verifier_controller.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.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/metrics/content/subprocess_metrics_provider.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "content/public/test/browser_test.h"
#include "net/base/features.h"
@@ -33,7 +33,7 @@ IN_PROC_BROWSER_TEST_F(TrialComparisonCertVerifierTest, TrialDisabled) {
base::HistogramTester histograms;
ui_test_utils::NavigateToURL(browser(),
https_test_server_.GetURL("/title1.html"));
- SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
+ metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
histograms.ExpectTotalCount("Net.CertVerifier_Job_Latency", 1);
histograms.ExpectTotalCount("Net.CertVerifier_Job_Latency_TrialPrimary", 0);
}
@@ -65,21 +65,21 @@ IN_PROC_BROWSER_TEST_F(TrialComparisonCertVerifierFeatureEnabledTest,
base::HistogramTester histograms;
ui_test_utils::NavigateToURL(browser(),
https_test_server_.GetURL("/title1.html"));
- SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
+ metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
histograms.ExpectTotalCount("Net.CertVerifier_Job_Latency", 1);
histograms.ExpectTotalCount("Net.CertVerifier_Job_Latency_TrialPrimary", 0);
}
IN_PROC_BROWSER_TEST_F(TrialComparisonCertVerifierFeatureEnabledTest,
TrialEnabledPrefEnabled) {
- safe_browsing::SetExtendedReportingPref(browser()->profile()->GetPrefs(),
- true);
+ safe_browsing::SetExtendedReportingPrefForTests(
+ browser()->profile()->GetPrefs(), true);
ASSERT_TRUE(https_test_server_.Start());
base::HistogramTester histograms;
ui_test_utils::NavigateToURL(browser(),
https_test_server_.GetURL("/title1.html"));
- SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
+ metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
histograms.ExpectTotalCount("Net.CertVerifier_Job_Latency", 1);
#if BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED)
if (base::FeatureList::IsEnabled(
@@ -121,14 +121,14 @@ class TrialComparisonCertVerifierFeatureOverridenByBuiltinVerifierTest
IN_PROC_BROWSER_TEST_F(
TrialComparisonCertVerifierFeatureOverridenByBuiltinVerifierTest,
TrialEnabledPrefEnabledBuiltVerifierEnabled) {
- safe_browsing::SetExtendedReportingPref(browser()->profile()->GetPrefs(),
- true);
+ safe_browsing::SetExtendedReportingPrefForTests(
+ browser()->profile()->GetPrefs(), true);
ASSERT_TRUE(https_test_server_.Start());
base::HistogramTester histograms;
ui_test_utils::NavigateToURL(browser(),
https_test_server_.GetURL("/title1.html"));
- SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
+ metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
histograms.ExpectTotalCount("Net.CertVerifier_Job_Latency", 1);
// If both the dual cert verifier trial feature and the builtin verifier
// feature are enabled, the dual cert verifier trial should not be used.
diff --git a/chromium/chrome/browser/net/trial_comparison_cert_verifier_controller_unittest.cc b/chromium/chrome/browser/net/trial_comparison_cert_verifier_controller_unittest.cc
index 83417a3c335..8fa14070863 100644
--- a/chromium/chrome/browser/net/trial_comparison_cert_verifier_controller_unittest.cc
+++ b/chromium/chrome/browser/net/trial_comparison_cert_verifier_controller_unittest.cc
@@ -234,7 +234,7 @@ TEST_F(TrialComparisonCertVerifierControllerTest, NothingEnabled) {
// Enable the SBER pref, shouldn't matter since it's a non-official build and
// field trial isn't enabled.
- safe_browsing::SetExtendedReportingPref(pref_service(), true);
+ safe_browsing::SetExtendedReportingPrefForTests(pref_service(), true);
// Trial still not allowed, and OnTrialConfigUpdated should not be called
// either.
@@ -257,7 +257,7 @@ TEST_F(TrialComparisonCertVerifierControllerTest,
CreateController();
EXPECT_FALSE(trial_controller().IsAllowed());
- safe_browsing::SetExtendedReportingPref(pref_service(), true);
+ safe_browsing::SetExtendedReportingPrefForTests(pref_service(), true);
// Trial still not allowed, and OnTrialConfigUpdated should not be called
// either.
@@ -288,7 +288,7 @@ TEST_F(TrialComparisonCertVerifierControllerTest,
// In a real official build, expect the trial config to be updated.
EXPECT_CALL(mock_config_client(), OnTrialConfigUpdated(true)).Times(1);
#endif
- safe_browsing::SetExtendedReportingPref(pref_service(), true);
+ safe_browsing::SetExtendedReportingPrefForTests(pref_service(), true);
#if defined(OFFICIAL_BUILD) && BUILDFLAG(GOOGLE_CHROME_BRANDING)
// In a real official build, expect the trial to be allowed now. (Don't
@@ -326,7 +326,7 @@ TEST_F(TrialComparisonCertVerifierControllerTest, OfficialBuildTrialEnabled) {
// Enable the SBER pref, which should trigger the OnTrialConfigUpdated
// callback.
EXPECT_CALL(mock_config_client(), OnTrialConfigUpdated(true)).Times(1);
- safe_browsing::SetExtendedReportingPref(pref_service(), true);
+ safe_browsing::SetExtendedReportingPrefForTests(pref_service(), true);
// Trial should now be allowed.
EXPECT_TRUE(trial_controller().IsAllowed());
@@ -378,7 +378,7 @@ TEST_F(TrialComparisonCertVerifierControllerTest, OfficialBuildTrialEnabled) {
// Disable the SBER pref again, which should trigger the OnTrialConfigUpdated
// callback.
EXPECT_CALL(mock_config_client(), OnTrialConfigUpdated(false)).Times(1);
- safe_browsing::SetExtendedReportingPref(pref_service(), false);
+ safe_browsing::SetExtendedReportingPrefForTests(pref_service(), false);
// Not allowed now.
EXPECT_FALSE(trial_controller().IsAllowed());
@@ -422,7 +422,7 @@ TEST_F(TrialComparisonCertVerifierControllerTest,
// callback.
EXPECT_CALL(mock_config_client(), OnTrialConfigUpdated(true)).Times(1);
EXPECT_CALL(mock_config_client_2, OnTrialConfigUpdated(true)).Times(1);
- safe_browsing::SetExtendedReportingPref(pref_service(), true);
+ safe_browsing::SetExtendedReportingPrefForTests(pref_service(), true);
// Trial should now be allowed.
EXPECT_TRUE(trial_controller().IsAllowed());
@@ -482,7 +482,7 @@ TEST_F(TrialComparisonCertVerifierControllerTest,
// callback.
EXPECT_CALL(mock_config_client(), OnTrialConfigUpdated(false)).Times(1);
EXPECT_CALL(mock_config_client_2, OnTrialConfigUpdated(false)).Times(1);
- safe_browsing::SetExtendedReportingPref(pref_service(), false);
+ safe_browsing::SetExtendedReportingPrefForTests(pref_service(), false);
// Not allowed now.
EXPECT_FALSE(trial_controller().IsAllowed());
@@ -515,7 +515,7 @@ TEST_F(TrialComparisonCertVerifierControllerTest,
// Enable the SBER pref, which should trigger the OnTrialConfigUpdated
// callback.
EXPECT_CALL(mock_config_client(), OnTrialConfigUpdated(true)).Times(1);
- safe_browsing::SetExtendedReportingPref(pref_service(), true);
+ safe_browsing::SetExtendedReportingPrefForTests(pref_service(), true);
// Trial should now be allowed.
EXPECT_TRUE(trial_controller().IsAllowed());
@@ -544,12 +544,12 @@ TEST_F(TrialComparisonCertVerifierControllerTest,
scoped_feature_ = std::make_unique<base::test::ScopedFeatureList>();
scoped_feature_->InitAndEnableFeature(
features::kCertDualVerificationTrialFeature);
- CreateController(profile()->GetOffTheRecordProfile());
+ CreateController(profile()->GetPrimaryOTRProfile());
EXPECT_FALSE(trial_controller().IsAllowed());
// Enable the SBER pref, shouldn't matter since it's an incognito profile.
- safe_browsing::SetExtendedReportingPref(pref_service(), true);
+ safe_browsing::SetExtendedReportingPrefForTests(pref_service(), true);
// Trial still not allowed, and OnTrialConfigUpdated should not be called
// either.
diff --git a/chromium/chrome/browser/net/variations_http_headers_browsertest.cc b/chromium/chrome/browser/net/variations_http_headers_browsertest.cc
index 4b55712c322..d96eaa2a7a1 100644
--- a/chromium/chrome/browser/net/variations_http_headers_browsertest.cc
+++ b/chromium/chrome/browser/net/variations_http_headers_browsertest.cc
@@ -18,13 +18,19 @@
#include "chrome/browser/chrome_browser_main.h"
#include "chrome/browser/chrome_browser_main_extra_parts.h"
#include "chrome/browser/net/system_network_context_manager.h"
+#include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h"
+#include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h"
+#include "chrome/browser/predictors/predictors_features.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/browser_commands.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/network_session_configurator/common/network_switches.h"
+#include "components/optimization_guide/optimization_guide_features.h"
+#include "components/optimization_guide/proto/hints.pb.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/variations/net/variations_http_headers.h"
#include "components/variations/variations_http_header_provider.h"
@@ -134,6 +140,15 @@ class VariationsHttpHeadersBrowserTest : public InProcessBrowserTest {
GURL GetExampleUrl() const { return GetExampleUrlWithPath("/landing.html"); }
+ void WaitForRequest(const GURL& url) {
+ auto it = received_headers_.find(url);
+ if (it != received_headers_.end())
+ return;
+ base::RunLoop loop;
+ done_callbacks_.emplace(url, loop.QuitClosure());
+ loop.Run();
+ }
+
// Returns whether a given |header| has been received for a |url|. If
// |url| has not been observed, fails an EXPECT and returns false.
bool HasReceivedHeader(const GURL& url, const std::string& header) const {
@@ -282,6 +297,9 @@ class VariationsHttpHeadersBrowserTest : public InProcessBrowserTest {
// Stores the observed HTTP Request headers.
std::map<GURL, net::test_server::HttpRequest::HeaderMap> received_headers_;
+ // For waiting for requests.
+ std::map<GURL, base::OnceClosure> done_callbacks_;
+
DISALLOW_COPY_AND_ASSIGN(VariationsHttpHeadersBrowserTest);
};
@@ -304,6 +322,10 @@ VariationsHttpHeadersBrowserTest::RequestHandler(
// Memorize the request headers for this URL for later verification.
received_headers_[original_url] = request.headers;
+ auto iter = done_callbacks_.find(original_url);
+ if (iter != done_callbacks_.end()) {
+ std::move(iter->second).Run();
+ }
// Set up a test server that redirects according to the
// following redirect chain:
@@ -584,3 +606,83 @@ IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest,
WorkerScriptTest("/workers/create_dedicated_worker.html",
"/workers/import_scripts_dedicated_worker.js");
}
+
+namespace {
+
+// A test fixture for testing prefetches from the Loading Predictor.
+class VariationsHttpHeadersBrowserTestWithOptimizationGuide
+ : public VariationsHttpHeadersBrowserTest {
+ public:
+ VariationsHttpHeadersBrowserTestWithOptimizationGuide() {
+ std::vector<base::test::ScopedFeatureList::FeatureAndParams> enabled = {
+ {features::kLoadingPredictorPrefetch, {}},
+ {features::kLoadingPredictorUseOptimizationGuide,
+ {{"use_predictions_for_preconnect", "true"}}},
+ {optimization_guide::features::kOptimizationHints, {}}};
+ std::vector<base::Feature> disabled = {
+ features::kLoadingPredictorUseLocalPredictions};
+ feature_list_.InitWithFeaturesAndParameters(enabled, disabled);
+ }
+
+ std::unique_ptr<content::TestNavigationManager> NavigateToURLAsync(
+ const GURL& url) {
+ chrome::NewTab(browser());
+ content::WebContents* tab =
+ browser()->tab_strip_model()->GetActiveWebContents();
+ DCHECK(tab);
+ auto observer = std::make_unique<content::TestNavigationManager>(tab, url);
+ tab->GetController().LoadURL(url, content::Referrer(),
+ ui::PAGE_TRANSITION_TYPED, std::string());
+ return observer;
+ }
+
+ void SetUpOptimizationHint(
+ const GURL& url,
+ const std::vector<std::string>& predicted_subresource_urls) {
+ auto* optimization_guide_keyed_service =
+ OptimizationGuideKeyedServiceFactory::GetForProfile(
+ browser()->profile());
+ ASSERT_TRUE(optimization_guide_keyed_service);
+
+ optimization_guide::proto::LoadingPredictorMetadata
+ loading_predictor_metadata;
+ for (const auto& subresource_url : predicted_subresource_urls) {
+ loading_predictor_metadata.add_subresources()->set_url(subresource_url);
+ }
+
+ optimization_guide::OptimizationMetadata optimization_metadata;
+ optimization_metadata.set_loading_predictor_metadata(
+ loading_predictor_metadata);
+ optimization_guide_keyed_service->AddHintForTesting(
+ url, optimization_guide::proto::LOADING_PREDICTOR,
+ optimization_metadata);
+ }
+
+ private:
+ base::test::ScopedFeatureList feature_list_;
+};
+
+} // namespace
+
+// Verify in an integration test that that the variations header (X-Client-Data)
+// is correctly attached to prefetch requests from the Loading Predictor.
+IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTestWithOptimizationGuide,
+ Prefetch) {
+ GURL url = server()->GetURL("test.com", "/simple_page.html");
+ GURL google_url = GetGoogleSubresourceUrl();
+ GURL non_google_url = GetExampleUrl();
+
+ // Set up optimization hints.
+ std::vector<std::string> hints = {google_url.spec(), non_google_url.spec()};
+ SetUpOptimizationHint(url, hints);
+
+ // Navigate.
+ auto observer = NavigateToURLAsync(url);
+ EXPECT_TRUE(observer->WaitForRequestStart());
+ WaitForRequest(google_url);
+ WaitForRequest(non_google_url);
+
+ // Expect header on google urls only.
+ EXPECT_TRUE(HasReceivedHeader(google_url, "X-Client-Data"));
+ EXPECT_FALSE(HasReceivedHeader(non_google_url, "X-Client-Data"));
+}
diff --git a/chromium/chrome/browser/net/websocket_browsertest.cc b/chromium/chrome/browser/net/websocket_browsertest.cc
index e96355ca123..d6bd99c4b14 100644
--- a/chromium/chrome/browser/net/websocket_browsertest.cc
+++ b/chromium/chrome/browser/net/websocket_browsertest.cc
@@ -409,8 +409,6 @@ class ExpectInvalidUtf8Client : public network::mojom::WebSocketClient {
NOTREACHED();
}
- void AddSendFlowControlQuota(int64_t quota) override {}
-
void OnDropChannel(bool was_clean,
uint16_t code,
const std::string& reason) override {
diff --git a/chromium/chrome/browser/offline_pages/android/BUILD.gn b/chromium/chrome/browser/offline_pages/android/BUILD.gn
index a5b1a67f9c7..f455eb662eb 100644
--- a/chromium/chrome/browser/offline_pages/android/BUILD.gn
+++ b/chromium/chrome/browser/offline_pages/android/BUILD.gn
@@ -8,6 +8,7 @@ android_library("java") {
sources = [ "java/src/org/chromium/chrome/browser/offlinepages/prefetch/PrefetchConfiguration.java" ]
deps = [
+ "//base:jni_java",
"//chrome/browser/flags:java",
"//chrome/browser/profiles/android:java",
]
diff --git a/chromium/chrome/browser/optimization_guide/android/BUILD.gn b/chromium/chrome/browser/optimization_guide/android/BUILD.gn
index 2fecfe2845d..ff706ea4797 100644
--- a/chromium/chrome/browser/optimization_guide/android/BUILD.gn
+++ b/chromium/chrome/browser/optimization_guide/android/BUILD.gn
@@ -60,6 +60,8 @@ java_library("junit_tests") {
"//base:base_java_test_support",
"//base:base_junit_test_support",
"//chrome/android:chrome_test_util_java",
+ "//components/optimization_guide/proto:optimization_guide_proto_java",
+ "//content/public/android:content_java",
"//third_party/junit",
"//third_party/mockito:mockito_java",
]
diff --git a/chromium/chrome/browser/page_load_metrics/integration_tests/sources.gni b/chromium/chrome/browser/page_load_metrics/integration_tests/sources.gni
index 71d70117752..19c7463fbb7 100644
--- a/chromium/chrome/browser/page_load_metrics/integration_tests/sources.gni
+++ b/chromium/chrome/browser/page_load_metrics/integration_tests/sources.gni
@@ -4,6 +4,7 @@
metric_integration_sources = [
"//chrome/browser/page_load_metrics/integration_tests/first_input_delay_browsertest.cc",
+ "//chrome/browser/page_load_metrics/integration_tests/first_scroll_delay_browsertest.cc",
"//chrome/browser/page_load_metrics/integration_tests/largest_contentful_paint_browsertest.cc",
"//chrome/browser/page_load_metrics/integration_tests/layout_instability_browsertest.cc",
"//chrome/browser/page_load_metrics/integration_tests/metric_integration_test.cc",
diff --git a/chromium/chrome/browser/password_check/android/BUILD.gn b/chromium/chrome/browser/password_check/android/BUILD.gn
new file mode 100644
index 00000000000..2a0efaa0999
--- /dev/null
+++ b/chromium/chrome/browser/password_check/android/BUILD.gn
@@ -0,0 +1,23 @@
+# Copyright 2020 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//build/config/android/rules.gni")
+
+source_set("android") {
+ sources = [
+ "bulk_leak_check_controller_android.cc",
+ "bulk_leak_check_controller_android.h",
+ ]
+ deps = [ "//components/password_manager/core/browser" ]
+}
+
+source_set("unit_tests") {
+ testonly = true
+ sources = [ "bulk_leak_check_controller_android_unittest.cc" ]
+ deps = [
+ ":android",
+ "//testing/gmock",
+ "//testing/gtest",
+ ]
+}
diff --git a/chromium/chrome/browser/payments/BUILD.gn b/chromium/chrome/browser/payments/BUILD.gn
index 91e0bb1f831..d516062b28d 100644
--- a/chromium/chrome/browser/payments/BUILD.gn
+++ b/chromium/chrome/browser/payments/BUILD.gn
@@ -6,6 +6,7 @@ source_set("browsertests") {
testonly = true
sources = [
+ "abort_payment_handler_browsertest.cc",
"colocated_payment_manifests_browsertest.cc",
"empty_parameters_browsertest.cc",
"has_enrolled_instrument_browsertest.cc",
@@ -13,14 +14,17 @@ source_set("browsertests") {
"iframe_csp_browsertest.cc",
"ignore_payment_method_browsertest.cc",
"journey_logger_browsertest.cc",
+ "payment_handler_capabilities_browsertest.cc",
"payment_handler_change_shipping_address_option_browsertest.cc",
"payment_handler_enable_delegations_browsertest.cc",
"payment_handler_exploit_browsertest.cc",
"payment_handler_just_in_time_installation_browsertest.cc",
+ "payment_request_app_store_billing_browsertest.cc",
"payment_request_can_make_payment_browsertest.cc",
"payment_request_can_make_payment_event_browsertest.cc",
"payment_request_minimal_ui_browsertest.cc",
"sec_fetch_site_browsertest.cc",
+ "two_payment_requests_browsertest.cc",
]
defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ]
@@ -41,6 +45,7 @@ source_set("browsertests") {
"expandable_payment_handler_browsertest.cc",
"hybrid_request_skip_ui_browsertest.cc",
]
+ deps += [ "//components/payments/content/android" ]
}
if (!is_android) {
@@ -81,6 +86,7 @@ source_set("unittests") {
deps += [
"//chrome/android:native_j_unittests_jni_headers",
+ "//components/payments/content",
"//components/payments/content:utils",
]
}
diff --git a/chromium/chrome/browser/payments/android/BUILD.gn b/chromium/chrome/browser/payments/android/BUILD.gn
index c37f61f4a5f..03eb76b21c4 100644
--- a/chromium/chrome/browser/payments/android/BUILD.gn
+++ b/chromium/chrome/browser/payments/android/BUILD.gn
@@ -11,7 +11,6 @@ import("//build/config/android/rules.gni")
generate_jni("jni_headers") {
sources = [
"../../../android/java/src/org/chromium/chrome/browser/payments/CanMakePaymentQuery.java",
- "../../../android/java/src/org/chromium/chrome/browser/payments/JourneyLogger.java",
"../../../android/java/src/org/chromium/chrome/browser/payments/PaymentAppServiceBridge.java",
"../../../android/java/src/org/chromium/chrome/browser/payments/PaymentManifestWebDataService.java",
"../../../android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentAppBridge.java",
diff --git a/chromium/chrome/browser/preferences/BUILD.gn b/chromium/chrome/browser/preferences/BUILD.gn
index 5491897b9e5..aec7e103a89 100644
--- a/chromium/chrome/browser/preferences/BUILD.gn
+++ b/chromium/chrome/browser/preferences/BUILD.gn
@@ -21,7 +21,26 @@ android_library("java") {
"//base:jni_java",
]
annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ]
- srcjar_deps = [ ":java_enums_srcjar" ]
+ srcjar_deps = [ ":java_pref_names_srcjar" ]
+}
+
+# TODO(chouinard,estade): Consider breaking this target up into a different target for each pref file.
+java_cpp_strings("java_pref_names_srcjar") {
+ sources = [
+ "//chrome/common/pref_names.cc",
+ "//components/autofill/core/common/autofill_prefs.cc",
+ "//components/dom_distiller/core/pref_names.cc",
+ "//components/embedder_support/pref_names.cc",
+ "//components/feed/core/shared_prefs/pref_names.cc",
+ "//components/offline_pages/core/prefetch/prefetch_prefs.cc",
+ "//components/password_manager/core/common/password_manager_pref_names.cc",
+ "//components/payments/core/payment_prefs.cc",
+ "//components/safe_browsing/core/common/safe_browsing_prefs.cc",
+ "//components/signin/public/base/signin_pref_names.cc",
+ "//components/translate/core/browser/translate_pref_names.cc",
+ ]
+
+ template = "android/java_templates/Pref.java.tmpl"
}
generate_jni("jni_headers") {
@@ -31,10 +50,6 @@ generate_jni("jni_headers") {
]
}
-java_cpp_enum("java_enums_srcjar") {
- sources = [ "//chrome/browser/android/preferences/prefs.h" ]
-}
-
java_library("preferences_junit_tests") {
# Skip platform checks since Robolectric depends on requires_android targets.
bypass_platform_checks = true
@@ -51,5 +66,7 @@ java_library("preferences_junit_tests") {
"//base:base_java_test_support",
"//base:base_junit_test_support",
"//base/test:test_support_java",
+ "//third_party/junit:junit",
+ "//third_party/mockito:mockito_java",
]
}
diff --git a/chromium/chrome/browser/prefs/OWNERS b/chromium/chrome/browser/prefs/OWNERS
index 538512cd888..9a8b24b3e19 100644
--- a/chromium/chrome/browser/prefs/OWNERS
+++ b/chromium/chrome/browser/prefs/OWNERS
@@ -1,7 +1,7 @@
battre@chromium.org
gab@chromium.org
-per-file pref_service_incognito_whitelist.cc=rhalavati@chromium.org
+per-file pref_service_incognito_allowlist.cc=rhalavati@chromium.org
# COMPONENT: UI>Browser>Preferences
# TEAM: chromium-dev@chromium.org
diff --git a/chromium/chrome/browser/prefs/browser_prefs.cc b/chromium/chrome/browser/prefs/browser_prefs.cc
index 3d00fae9dc1..6dc80ff464e 100644
--- a/chromium/chrome/browser/prefs/browser_prefs.cc
+++ b/chromium/chrome/browser/prefs/browser_prefs.cc
@@ -17,9 +17,11 @@
#include "chrome/browser/browser_process_impl.h"
#include "chrome/browser/chrome_content_browser_client.h"
#include "chrome/browser/chromeos/policy/tpm_auto_update_mode_policy_handler.h"
+#include "chrome/browser/chromeos/printing/print_management/printing_manager_factory.h"
#include "chrome/browser/chromeos/scheduler_configuration_manager.h"
#include "chrome/browser/component_updater/component_updater_prefs.h"
#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
+#include "chrome/browser/data_use_measurement/chrome_data_use_measurement.h"
#include "chrome/browser/devtools/devtools_window.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/engagement/important_sites_util.h"
@@ -69,9 +71,9 @@
#include "chrome/browser/sharing/sharing_sync_preference.h"
#include "chrome/browser/ssl/ssl_config_service_manager.h"
#include "chrome/browser/storage/appcache_feature_prefs.h"
+#include "chrome/browser/subresource_redirect/https_image_compression_infobar_decider.h"
#include "chrome/browser/task_manager/task_manager_interface.h"
#include "chrome/browser/tracing/chrome_tracing_delegate.h"
-#include "chrome/browser/ui/blocked_content/safe_browsing_triggered_popup_blocker.h"
#include "chrome/browser/ui/browser_ui_prefs.h"
#include "chrome/browser/ui/hats/hats_service.h"
#include "chrome/browser/ui/navigation_correction_tab_observer.h"
@@ -88,11 +90,10 @@
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/webauthn/chrome_authenticator_request_delegate.h"
#include "chrome/common/buildflags.h"
-#include "chrome/common/chrome_ui_features_prefs.h"
#include "chrome/common/pref_names.h"
-#include "chrome/common/secure_origin_whitelist.h"
-#include "chrome/common/web_components_prefs.h"
+#include "chrome/common/secure_origin_allowlist.h"
#include "components/autofill/core/common/autofill_prefs.h"
+#include "components/blocked_content/safe_browsing_triggered_popup_blocker.h"
#include "components/browsing_data/core/pref_names.h"
#include "components/certificate_transparency/pref_names.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
@@ -103,6 +104,7 @@
#include "components/feature_engagement/buildflags.h"
#include "components/flags_ui/pref_service_flags_storage.h"
#include "components/image_fetcher/core/cache/image_cache.h"
+#include "components/invalidation/impl/fcm_invalidation_service.h"
#include "components/invalidation/impl/invalidator_registrar_with_memory.h"
#include "components/invalidation/impl/per_user_topic_subscription_manager.h"
#include "components/language/content/browser/geo_language_provider.h"
@@ -138,7 +140,6 @@
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/search_engines/template_url_prepopulate_data.h"
#include "components/security_interstitials/content/stateful_ssl_host_state_delegate.h"
-#include "components/security_state/core/security_state.h"
#include "components/sessions/core/session_id_generator.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/subresource_filter/content/browser/ruleset_service.h"
@@ -242,6 +243,7 @@
#include "chrome/browser/gcm/gcm_product_util.h"
#include "chrome/browser/media/unified_autoplay_config.h"
#include "chrome/browser/metrics/tab_stats_tracker.h"
+#include "chrome/browser/nearby_sharing/nearby_sharing_prefs.h"
#include "chrome/browser/search/instant_service.h"
#include "chrome/browser/search/promos/promo_service.h"
#include "chrome/browser/search/search_suggest/search_suggest_service.h"
@@ -283,6 +285,7 @@
#include "chrome/browser/chromeos/file_system_provider/registry.h"
#include "chrome/browser/chromeos/first_run/first_run.h"
#include "chrome/browser/chromeos/guest_os/guest_os_pref_names.h"
+#include "chrome/browser/chromeos/local_search_service/search_metrics_reporter.h"
#include "chrome/browser/chromeos/lock_screen_apps/state_controller.h"
#include "chrome/browser/chromeos/login/demo_mode/demo_mode_detector.h"
#include "chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover.h"
@@ -309,7 +312,10 @@
#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/dm_token_storage.h"
+#include "chrome/browser/chromeos/policy/enrollment_requisition_manager.h"
+#include "chrome/browser/chromeos/policy/extension_install_event_log_manager_wrapper.h"
#include "chrome/browser/chromeos/policy/external_data_handlers/device_wallpaper_image_external_data_handler.h"
+#include "chrome/browser/chromeos/policy/minimum_version_policy_handler.h"
#include "chrome/browser/chromeos/policy/policy_cert_service_factory.h"
#include "chrome/browser/chromeos/policy/status_collector/device_status_collector.h"
#include "chrome/browser/chromeos/policy/status_collector/status_collector.h"
@@ -350,7 +356,6 @@
#include "chromeos/services/multidevice_setup/multidevice_setup_service.h"
#include "chromeos/timezone/timezone_resolver.h"
#include "components/arc/arc_prefs.h"
-#include "components/invalidation/impl/fcm_invalidation_service.h"
#include "components/onc/onc_pref_names.h"
#include "components/quirks/quirks_manager.h"
#include "extensions/browser/api/lock_screen_data/lock_screen_item_storage.h"
@@ -398,6 +403,10 @@
#include "chrome/browser/media/feeds/media_feeds_service.h"
#endif
+#if defined(USE_X11)
+#include "ui/base/ui_base_features.h"
+#endif
+
namespace {
#if defined(OS_ANDROID)
@@ -547,6 +556,10 @@ const char kPreviewsLPROriginProbeCache[] =
const char kSupervisedUsersNextId[] = "LocallyManagedUsersNextId";
#endif // defined(OS_CHROMEOS)
+// Deprecated 6/2020
+const char kStricterMixedContentTreatmentEnabled[] =
+ "security_state.stricter_mixed_content_treatment_enabled";
+
// Register local state used only for migration (clearing or moving to a new
// key).
void RegisterLocalStatePrefsForMigration(PrefRegistrySimple* registry) {
@@ -610,7 +623,8 @@ void RegisterProfilePrefsForMigration(
registry->RegisterStringPref(kLastKnownGoogleURL, std::string());
registry->RegisterStringPref(kLastPromptedGoogleURL, std::string());
#if defined(USE_X11)
- registry->RegisterIntegerPref(kLocalProfileId, 0);
+ if (!features::IsUsingOzonePlatform())
+ registry->RegisterIntegerPref(kLocalProfileId, 0);
#endif
registry->RegisterBooleanPref(kInsecureExtensionUpdatesEnabled, false);
@@ -648,14 +662,19 @@ void RegisterProfilePrefsForMigration(
registry->RegisterDictionaryPref(kPreviewsLPRHostBlacklist);
registry->RegisterDictionaryPref(kPreviewsLPRProbeCache);
registry->RegisterDictionaryPref(kPreviewsLPROriginProbeCache);
+
+ registry->RegisterBooleanPref(kStricterMixedContentTreatmentEnabled, true);
}
} // namespace
void RegisterLocalState(PrefRegistrySimple* registry) {
- // Please keep this list alphabetized.
+ // Call outs to individual subsystems that register Local State (browser-wide)
+ // prefs en masse. See RegisterProfilePrefs for per-profile prefs. Please
+ // keep this list alphabetized.
browser_shutdown::RegisterPrefs(registry);
data_reduction_proxy::RegisterPrefs(registry);
+ data_use_measurement::ChromeDataUseMeasurement::RegisterPrefs(registry);
BrowserProcessImpl::RegisterPrefs(registry);
ChromeContentBrowserClient::RegisterLocalStatePrefs(registry);
ChromeMetricsServiceClient::RegisterPrefs(registry);
@@ -666,6 +685,7 @@ void RegisterLocalState(PrefRegistrySimple* registry) {
GpuModeManager::RegisterPrefs(registry);
signin::IdentityManager::RegisterLocalStatePrefs(registry);
IntranetRedirectDetector::RegisterPrefs(registry);
+ invalidation::FCMInvalidationService::RegisterPrefs(registry);
language::GeoLanguageProvider::RegisterLocalStatePrefs(registry);
language::UlpLanguageCodeLocator::RegisterLocalStatePrefs(registry);
memory::EnterpriseMemoryLimitPrefObserver::RegisterPrefs(registry);
@@ -682,10 +702,12 @@ void RegisterLocalState(PrefRegistrySimple* registry) {
rappor::RapporServiceImpl::RegisterPrefs(registry);
RegisterScreenshotPrefs(registry);
safe_browsing::RegisterLocalStatePrefs(registry);
- secure_origin_whitelist::RegisterPrefs(registry);
+ secure_origin_allowlist::RegisterPrefs(registry);
sessions::SessionIdGenerator::RegisterPrefs(registry);
SSLConfigServiceManager::RegisterPrefs(registry);
subresource_filter::IndexedRulesetVersion::RegisterPrefs(registry);
+ syncer::InvalidatorRegistrarWithMemory::RegisterPrefs(registry);
+ syncer::PerUserTopicSubscriptionManager::RegisterPrefs(registry);
SystemNetworkContextManager::RegisterPrefs(registry);
update_client::RegisterPrefs(registry);
variations::VariationsService::RegisterPrefs(registry);
@@ -694,6 +716,11 @@ void RegisterLocalState(PrefRegistrySimple* registry) {
// clearly be grouped together, please group them together into a helper
// function called above. Please keep this list alphabetized.
registry->RegisterBooleanPref(
+ policy::policy_prefs::kIntensiveWakeUpThrottlingEnabled, false);
+ registry->RegisterInt64Pref(kLastStartupTimestamp, 0);
+ registry->RegisterStringPref(kLastStartupVersion, std::string());
+ registry->RegisterIntegerPref(kSameVersionStartupCount, 0);
+ registry->RegisterBooleanPref(
policy::policy_prefs::kUserAgentClientHintsEnabled, true);
// Below this point is for platform-specific and compile-time conditional
@@ -717,9 +744,12 @@ void RegisterLocalState(PrefRegistrySimple* registry) {
media_router::RegisterLocalStatePrefs(registry);
metrics::TabStatsTracker::RegisterPrefs(registry);
RegisterBrowserPrefs(registry);
+ RegisterNearbySharingLocalPrefs(registry);
StartupBrowserCreator::RegisterLocalStatePrefs(registry);
task_manager::TaskManagerInterface::RegisterPrefs(registry);
UpgradeDetector::RegisterPrefs(registry);
+
+ registry->RegisterBooleanPref(kNtpActivateHideShortcutsFieldTrial, false);
#endif // !defined(OS_ANDROID)
#if defined(OS_CHROMEOS)
@@ -770,22 +800,23 @@ void RegisterLocalState(PrefRegistrySimple* registry) {
extensions::lock_screen_data::LockScreenItemStorage::RegisterLocalState(
registry);
extensions::login_api::RegisterLocalStatePrefs(registry);
- invalidation::FCMInvalidationService::RegisterPrefs(registry);
::onc::RegisterPrefs(registry);
+ local_search_service::SearchMetricsReporter::RegisterLocalStatePrefs(
+ registry);
policy::AutoEnrollmentClientImpl::RegisterPrefs(registry);
policy::BrowserPolicyConnectorChromeOS::RegisterPrefs(registry);
policy::DeviceCloudPolicyManagerChromeOS::RegisterPrefs(registry);
policy::DeviceStatusCollector::RegisterPrefs(registry);
policy::DeviceWallpaperImageExternalDataHandler::RegisterPrefs(registry);
policy::DMTokenStorage::RegisterPrefs(registry);
+ policy::EnrollmentRequisitionManager::RegisterPrefs(registry);
+ policy::MinimumVersionPolicyHandler::RegisterPrefs(registry);
policy::PolicyCertServiceFactory::RegisterPrefs(registry);
policy::TPMAutoUpdateModePolicyHandler::RegisterPrefs(registry);
policy::WebUsbAllowDevicesForUrlsPolicyHandler::RegisterPrefs(registry);
policy::SystemFeaturesDisableListPolicyHandler::RegisterPrefs(registry);
quirks::QuirksManager::RegisterPrefs(registry);
UpgradeDetectorChromeos::RegisterPrefs(registry);
- syncer::PerUserTopicSubscriptionManager::RegisterPrefs(registry);
- syncer::InvalidatorRegistrarWithMemory::RegisterPrefs(registry);
chromeos::cert_provisioning::RegisterLocalStatePrefs(registry);
#endif // defined(OS_CHROMEOS)
@@ -799,9 +830,6 @@ void RegisterLocalState(PrefRegistrySimple* registry) {
#if defined(OS_WIN)
OSCrypt::RegisterLocalPrefs(registry);
-#endif
-
-#if defined(OS_WIN)
registry->RegisterBooleanPref(prefs::kRendererCodeIntegrityEnabled, true);
registry->RegisterBooleanPref(
policy::policy_prefs::kNativeWindowOcclusionEnabled, true);
@@ -819,17 +847,11 @@ void RegisterLocalState(PrefRegistrySimple* registry) {
DeviceOAuth2TokenStoreDesktop::RegisterPrefs(registry);
#endif
-#if !defined(OS_ANDROID)
- registry->RegisterBooleanPref(kNtpActivateHideShortcutsFieldTrial, false);
-#endif // !defined(OS_ANDROID)
- registry->RegisterInt64Pref(kLastStartupTimestamp, 0);
- registry->RegisterStringPref(kLastStartupVersion, std::string());
- registry->RegisterIntegerPref(kSameVersionStartupCount, 0);
-
#if defined(TOOLKIT_VIEWS)
RegisterBrowserViewLocalPrefs(registry);
#endif
+ // This is intentionally last.
RegisterLocalStatePrefsForMigration(registry);
}
@@ -853,12 +875,12 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry,
chrome_browser_net::NetErrorTabHelper::RegisterProfilePrefs(registry);
chrome_browser_net::RegisterPredictionOptionsProfilePrefs(registry);
chrome_prefs::RegisterProfilePrefs(registry);
- chrome_ui_features_prefs::RegisterProfilePrefs(registry);
DocumentProvider::RegisterProfilePrefs(registry);
dom_distiller::DistilledPagePrefs::RegisterProfilePrefs(registry);
dom_distiller::RegisterProfilePrefs(registry);
DownloadPrefs::RegisterProfilePrefs(registry);
HostContentSettingsMap::RegisterProfilePrefs(registry);
+ HttpsImageCompressionInfoBarDecider::RegisterProfilePrefs(registry);
image_fetcher::ImageCache::RegisterProfilePrefs(registry);
ImportantSitesUtil::RegisterProfilePrefs(registry);
IncognitoModePrefs::RegisterProfilePrefs(registry);
@@ -896,8 +918,8 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry,
QuietNotificationPermissionUiState::RegisterProfilePrefs(registry);
RegisterBrowserUserPrefs(registry);
safe_browsing::RegisterProfilePrefs(registry);
- SafeBrowsingTriggeredPopupBlocker::RegisterProfilePrefs(registry);
- security_state::RegisterProfilePrefs(registry);
+ blocked_content::SafeBrowsingTriggeredPopupBlocker::RegisterProfilePrefs(
+ registry);
SessionStartupPref::RegisterProfilePrefs(registry);
SharingSyncPreference::RegisterProfilePrefs(registry);
sync_sessions::SessionSyncPrefs::RegisterProfilePrefs(registry);
@@ -905,7 +927,6 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry,
syncer::SyncPrefs::RegisterProfilePrefs(registry);
syncer::PerUserTopicSubscriptionManager::RegisterProfilePrefs(registry);
syncer::InvalidatorRegistrarWithMemory::RegisterProfilePrefs(registry);
- web_components_prefs::RegisterProfilePrefs(registry);
TemplateURLPrepopulateData::RegisterProfilePrefs(registry);
translate::TranslatePrefs::RegisterProfilePrefs(registry);
omnibox::RegisterProfilePrefs(registry);
@@ -1037,6 +1058,8 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry,
chromeos::quick_unlock::FingerprintStorage::RegisterProfilePrefs(registry);
chromeos::quick_unlock::PinStoragePrefs::RegisterProfilePrefs(registry);
chromeos::Preferences::RegisterProfilePrefs(registry);
+ chromeos::printing::print_management::PrintingManagerFactory ::
+ RegisterProfilePrefs(registry);
chromeos::PrintJobHistoryService::RegisterProfilePrefs(registry);
chromeos::EnterprisePrintersProvider::RegisterProfilePrefs(registry);
chromeos::parent_access::ParentAccessService::RegisterProfilePrefs(registry);
@@ -1060,6 +1083,8 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry,
plugin_vm::prefs::RegisterProfilePrefs(registry);
policy::AppInstallEventLogger::RegisterProfilePrefs(registry);
policy::AppInstallEventLogManagerWrapper::RegisterProfilePrefs(registry);
+ policy::ExtensionInstallEventLogManagerWrapper::RegisterProfilePrefs(
+ registry);
policy::StatusCollector::RegisterProfilePrefs(registry);
RegisterChromeLauncherUserPrefs(registry);
::onc::RegisterProfilePrefs(registry);
@@ -1233,7 +1258,8 @@ void MigrateObsoleteProfilePrefs(Profile* profile) {
// Added 7/2019.
#if defined(USE_X11)
- profile_prefs->ClearPref(kLocalProfileId);
+ if (!features::IsUsingOzonePlatform())
+ profile_prefs->ClearPref(kLocalProfileId);
#endif
// Added 8/2019
@@ -1286,4 +1312,7 @@ void MigrateObsoleteProfilePrefs(Profile* profile) {
profile_prefs->ClearPref(kPreviewsLPRHostBlacklist);
profile_prefs->ClearPref(kPreviewsLPRProbeCache);
profile_prefs->ClearPref(kPreviewsLPROriginProbeCache);
+
+ // Added 6/2020
+ profile_prefs->ClearPref(kStricterMixedContentTreatmentEnabled);
}
diff --git a/chromium/chrome/browser/prefs/chrome_command_line_pref_store_ssl_manager_unittest.cc b/chromium/chrome/browser/prefs/chrome_command_line_pref_store_ssl_manager_unittest.cc
index ba08fd05151..f2532d99821 100644
--- a/chromium/chrome/browser/prefs/chrome_command_line_pref_store_ssl_manager_unittest.cc
+++ b/chromium/chrome/browser/prefs/chrome_command_line_pref_store_ssl_manager_unittest.cc
@@ -13,6 +13,7 @@
#include "components/prefs/pref_service.h"
#include "components/prefs/testing_pref_store.h"
#include "components/sync_preferences/pref_service_mock_factory.h"
+#include "content/public/browser/network_service_instance.h"
#include "services/network/public/mojom/network_service.mojom.h"
#include "services/network/public/mojom/ssl_config.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -43,6 +44,8 @@ TEST_F(CommandLinePrefStoreSSLManagerTest, CommandLinePrefs) {
SSLConfigServiceManager::RegisterPrefs(registry.get());
network::mojom::NetworkContextParamsPtr context_params =
network::mojom::NetworkContextParams::New();
+ context_params->cert_verifier_params = content::GetCertVerifierParams(
+ network::mojom::CertVerifierCreationParams::New());
std::unique_ptr<SSLConfigServiceManager> config_manager(
SSLConfigServiceManager::CreateDefaultManager(local_state.get()));
config_manager->AddToNetworkContextParams(context_params.get());
diff --git a/chromium/chrome/browser/prefs/chrome_pref_service_factory.cc b/chromium/chrome/browser/prefs/chrome_pref_service_factory.cc
index 6186da7ed18..68b01b41f02 100644
--- a/chromium/chrome/browser/prefs/chrome_pref_service_factory.cc
+++ b/chromium/chrome/browser/prefs/chrome_pref_service_factory.cc
@@ -222,50 +222,14 @@ SettingsEnforcementGroup GetSettingsEnforcementGroup() {
}
#endif
- struct {
- const char* group_name;
- SettingsEnforcementGroup group;
- } static const kEnforcementLevelMap[] = {
- { chrome_prefs::internals::kSettingsEnforcementGroupNoEnforcement,
- GROUP_NO_ENFORCEMENT },
- { chrome_prefs::internals::kSettingsEnforcementGroupEnforceAlways,
- GROUP_ENFORCE_ALWAYS },
- { chrome_prefs::internals::
- kSettingsEnforcementGroupEnforceAlwaysWithDSE,
- GROUP_ENFORCE_ALWAYS_WITH_DSE },
- { chrome_prefs::internals::
- kSettingsEnforcementGroupEnforceAlwaysWithExtensionsAndDSE,
- GROUP_ENFORCE_ALWAYS_WITH_EXTENSIONS_AND_DSE },
- };
-
- // Use the strongest enforcement setting in the absence of a field trial
- // config on Windows and MacOS. Remember to update the OFFICIAL_BUILD section
- // of extension_startup_browsertest.cc and pref_hash_browsertest.cc when
- // updating the default value below.
- // TODO(gab): Enforce this on all platforms.
- SettingsEnforcementGroup enforcement_group =
+ // Use the strongest enforcement setting on Windows and MacOS. Remember to
+ // update the OFFICIAL_BUILD section of extension_startup_browsertest.cc and
+ // pref_hash_browsertest.cc when updating the default value below.
#if defined(OS_WIN) || defined(OS_MACOSX)
- GROUP_ENFORCE_DEFAULT;
+ return GROUP_ENFORCE_DEFAULT;
#else
- GROUP_NO_ENFORCEMENT;
+ return GROUP_NO_ENFORCEMENT;
#endif
- bool group_determined_from_trial = false;
- base::FieldTrial* trial =
- base::FieldTrialList::Find(
- chrome_prefs::internals::kSettingsEnforcementTrialName);
- if (trial) {
- const std::string& group_name = trial->group_name();
- for (size_t i = 0; i < base::size(kEnforcementLevelMap); ++i) {
- if (kEnforcementLevelMap[i].group_name == group_name) {
- enforcement_group = kEnforcementLevelMap[i].group;
- group_determined_from_trial = true;
- break;
- }
- }
- }
- UMA_HISTOGRAM_BOOLEAN("Settings.EnforcementGroupDeterminedFromTrial",
- group_determined_from_trial);
- return enforcement_group;
}
// Returns the effective preference tracking configuration.
diff --git a/chromium/chrome/browser/prefs/incognito_mode_prefs.cc b/chromium/chrome/browser/prefs/incognito_mode_prefs.cc
index 203efcee12a..98f6ab2937f 100644
--- a/chromium/chrome/browser/prefs/incognito_mode_prefs.cc
+++ b/chromium/chrome/browser/prefs/incognito_mode_prefs.cc
@@ -77,18 +77,15 @@ bool IncognitoModePrefs::ShouldLaunchIncognito(
// static
bool IncognitoModePrefs::CanOpenBrowser(Profile* profile) {
- if (profile->IsGuestSession())
- return true;
-
switch (GetAvailability(profile->GetPrefs())) {
case IncognitoModePrefs::ENABLED:
return true;
case IncognitoModePrefs::DISABLED:
- return !profile->IsOffTheRecord();
+ return !profile->IsIncognitoProfile();
case IncognitoModePrefs::FORCED:
- return profile->IsOffTheRecord();
+ return profile->IsIncognitoProfile();
default:
NOTREACHED();
diff --git a/chromium/chrome/browser/prefs/pref_service_incognito_whitelist.cc b/chromium/chrome/browser/prefs/pref_service_incognito_allowlist.cc
index 3cfc0bc885b..34a671cf0b3 100644
--- a/chromium/chrome/browser/prefs/pref_service_incognito_whitelist.cc
+++ b/chromium/chrome/browser/prefs/pref_service_incognito_allowlist.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "chrome/browser/prefs/pref_service_incognito_whitelist.h"
+#include "chrome/browser/prefs/pref_service_incognito_allowlist.h"
#include <vector>
@@ -50,6 +50,8 @@ const char* const kPersistentPrefNames[] = {
ash::prefs::kAccessibilityAutoclickMovementThreshold,
ash::prefs::kAccessibilityCaretHighlightEnabled,
ash::prefs::kAccessibilityCursorHighlightEnabled,
+ ash::prefs::kAccessibilityCursorColorEnabled,
+ ash::prefs::kAccessibilityCursorColor,
ash::prefs::kAccessibilityFocusHighlightEnabled,
ash::prefs::kAccessibilitySelectToSpeakEnabled,
ash::prefs::kAccessibilitySwitchAccessEnabled,
@@ -165,7 +167,7 @@ const char* const kPersistentPrefNames[] = {
namespace prefs {
-std::vector<const char*> GetIncognitoPersistentPrefsWhitelist() {
+std::vector<const char*> GetIncognitoPersistentPrefsAllowlist() {
std::vector<const char*> whitelist;
whitelist.insert(whitelist.end(), kPersistentPrefNames,
kPersistentPrefNames + base::size(kPersistentPrefNames));
diff --git a/chromium/chrome/browser/prefs/pref_service_incognito_whitelist.h b/chromium/chrome/browser/prefs/pref_service_incognito_allowlist.h
index 78123f6c04a..d9a12213347 100644
--- a/chromium/chrome/browser/prefs/pref_service_incognito_whitelist.h
+++ b/chromium/chrome/browser/prefs/pref_service_incognito_allowlist.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CHROME_BROWSER_PREFS_PREF_SERVICE_INCOGNITO_WHITELIST_H_
-#define CHROME_BROWSER_PREFS_PREF_SERVICE_INCOGNITO_WHITELIST_H_
+#ifndef CHROME_BROWSER_PREFS_PREF_SERVICE_INCOGNITO_ALLOWLIST_H_
+#define CHROME_BROWSER_PREFS_PREF_SERVICE_INCOGNITO_ALLOWLIST_H_
#include <vector>
@@ -12,8 +12,8 @@ namespace prefs {
// Populate a list of all preferences that are stored in user profile in
// incognito mode.
// Please refer to the comments in .cc file.
-std::vector<const char*> GetIncognitoPersistentPrefsWhitelist();
+std::vector<const char*> GetIncognitoPersistentPrefsAllowlist();
} // namespace prefs
-#endif // CHROME_BROWSER_PREFS_PREF_SERVICE_INCOGNITO_WHITELIST_H_
+#endif // CHROME_BROWSER_PREFS_PREF_SERVICE_INCOGNITO_ALLOWLIST_H_
diff --git a/chromium/chrome/browser/prefs/pref_service_syncable_util.cc b/chromium/chrome/browser/prefs/pref_service_syncable_util.cc
index 3008bb06f8d..b9e590838a8 100644
--- a/chromium/chrome/browser/prefs/pref_service_syncable_util.cc
+++ b/chromium/chrome/browser/prefs/pref_service_syncable_util.cc
@@ -6,7 +6,7 @@
#include <utility>
-#include "chrome/browser/prefs/pref_service_incognito_whitelist.h"
+#include "chrome/browser/prefs/pref_service_incognito_allowlist.h"
#include "chrome/browser/profiles/profile.h"
#include "components/sync_preferences/pref_service_syncable.h"
@@ -23,5 +23,5 @@ CreateIncognitoPrefServiceSyncable(
PrefStore* incognito_extension_pref_store) {
return pref_service->CreateIncognitoPrefService(
incognito_extension_pref_store,
- prefs::GetIncognitoPersistentPrefsWhitelist());
+ prefs::GetIncognitoPersistentPrefsAllowlist());
}
diff --git a/chromium/chrome/browser/prefs/tracked/pref_hash_browsertest.cc b/chromium/chrome/browser/prefs/tracked/pref_hash_browsertest.cc
index 5e192f0f61c..39a1d677fcc 100644
--- a/chromium/chrome/browser/prefs/tracked/pref_hash_browsertest.cc
+++ b/chromium/chrome/browser/prefs/tracked/pref_hash_browsertest.cc
@@ -84,6 +84,20 @@ base::string16 GetRegistryPathForTestProfile() {
base::FilePath profile_dir;
EXPECT_TRUE(base::PathService::Get(chrome::DIR_USER_DATA, &profile_dir));
+ // |DIR_USER_DATA| usually has format %TMP%\12345_6789012345\user_data
+ // (unless running with --single-process-tests, where the format is
+ // %TMP%\scoped_dir12345_6789012345). Use the parent directory name instead of
+ // the leaf directory name "user_data" to avoid conflicts in parallel tests,
+ // which would try to modify the same registry key otherwise.
+ if (profile_dir.BaseName().value() == L"user_data") {
+ profile_dir = profile_dir.DirName();
+ }
+ // Try to detect regressions when |DIR_USER_DATA| test location changes, which
+ // could cause this test to become flaky. See http://crbug/1091409 for more
+ // details.
+ DCHECK(profile_dir.BaseName().value().find_first_of(L"0123456789") !=
+ std::string::npos);
+
// Use a location under the real PreferenceMACs path so that the backup
// cleanup logic in ChromeTestLauncherDelegate::PreSharding() for interrupted
// tests covers this test key as well.
@@ -162,17 +176,9 @@ bool SupportsRegistryValidation() {
}
#define PREF_HASH_BROWSER_TEST(fixture, test_name) \
- IN_PROC_BROWSER_TEST_P(fixture, PRE_##test_name) { SetupPreferences(); } \
- IN_PROC_BROWSER_TEST_P(fixture, test_name) { VerifyReactionToPrefAttack(); } \
- INSTANTIATE_TEST_SUITE_P( \
- fixture##Instance, fixture, \
- testing::Values( \
- chrome_prefs::internals::kSettingsEnforcementGroupNoEnforcement, \
- chrome_prefs::internals::kSettingsEnforcementGroupEnforceAlways, \
- chrome_prefs::internals:: \
- kSettingsEnforcementGroupEnforceAlwaysWithDSE, \
- chrome_prefs::internals:: \
- kSettingsEnforcementGroupEnforceAlwaysWithExtensionsAndDSE))
+ IN_PROC_BROWSER_TEST_F(fixture, PRE_##test_name) { SetupPreferences(); } \
+ IN_PROC_BROWSER_TEST_F(fixture, test_name) { VerifyReactionToPrefAttack(); } \
+ static_assert(true, "")
// A base fixture designed such that implementations do two things:
// 1) Override all three pure-virtual methods below to setup, attack, and
@@ -180,9 +186,7 @@ bool SupportsRegistryValidation() {
// 2) Instantiate their test via the PREF_HASH_BROWSER_TEST macro above.
// Based on top of ExtensionBrowserTest to allow easy interaction with the
// ExtensionRegistry.
-class PrefHashBrowserTestBase
- : public extensions::ExtensionBrowserTest,
- public testing::WithParamInterface<std::string> {
+class PrefHashBrowserTestBase : public extensions::ExtensionBrowserTest {
public:
// List of potential protection levels for this test in strict increasing
// order of protection levels.
@@ -197,17 +201,10 @@ class PrefHashBrowserTestBase
PROTECTION_ENABLED_ALL
};
- PrefHashBrowserTestBase()
- : protection_level_(GetProtectionLevelFromTrialGroup(GetParam())) {
- }
+ PrefHashBrowserTestBase() : protection_level_(GetProtectionLevel()) {}
void SetUpCommandLine(base::CommandLine* command_line) override {
extensions::ExtensionBrowserTest::SetUpCommandLine(command_line);
- EXPECT_FALSE(command_line->HasSwitch(switches::kForceFieldTrials));
- command_line->AppendSwitchASCII(
- switches::kForceFieldTrials,
- std::string(chrome_prefs::internals::kSettingsEnforcementTrialName) +
- "/" + GetParam() + "/");
#if defined(OS_CHROMEOS)
command_line->AppendSwitch(
chromeos::switches::kIgnoreUserProfileMappingForTests);
@@ -414,15 +411,10 @@ class PrefHashBrowserTestBase
const SettingsProtectionLevel protection_level_;
private:
- SettingsProtectionLevel GetProtectionLevelFromTrialGroup(
- const std::string& trial_group) {
+ SettingsProtectionLevel GetProtectionLevel() {
if (!ProfilePrefStoreManager::kPlatformSupportsPreferenceTracking)
return PROTECTION_DISABLED_ON_PLATFORM;
-// Protection levels can't be adjusted via --force-fieldtrials in official
-// builds.
-#if defined(OFFICIAL_BUILD)
-
#if defined(OS_WIN) || defined(OS_MACOSX)
// The strongest mode is enforced on Windows and MacOS in the absence of a
// field trial.
@@ -430,23 +422,6 @@ class PrefHashBrowserTestBase
#else
return PROTECTION_DISABLED_FOR_GROUP;
#endif // defined(OS_WIN) || defined(OS_MACOSX)
-
-#else // defined(OFFICIAL_BUILD)
-
- namespace internals = chrome_prefs::internals;
- if (trial_group == internals::kSettingsEnforcementGroupNoEnforcement)
- return PROTECTION_DISABLED_FOR_GROUP;
- if (trial_group == internals::kSettingsEnforcementGroupEnforceAlways)
- return PROTECTION_ENABLED_BASIC;
- if (trial_group == internals::kSettingsEnforcementGroupEnforceAlwaysWithDSE)
- return PROTECTION_ENABLED_DSE;
- if (trial_group ==
- internals::kSettingsEnforcementGroupEnforceAlwaysWithExtensionsAndDSE) {
- return PROTECTION_ENABLED_EXTENSIONS;
- }
- ADD_FAILURE();
- return static_cast<SettingsProtectionLevel>(-1);
-#endif // defined(OFFICIAL_BUILD)
}
int num_tracked_prefs_;
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 85cbf0f6248..c95548a75d8 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_traffic_detector.cc
@@ -9,7 +9,6 @@
#include "base/bind.h"
#include "base/stl_util.h"
#include "base/sys_byteorder.h"
-#include "base/task/post_task.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/browser/browser_context.h"
@@ -51,8 +50,8 @@ void OnGetNetworkList(
"lo", "lo", 0, net::NetworkChangeNotifier::CONNECTION_UNKNOWN,
localhost_prefix, 8, net::IP_ADDRESS_ATTRIBUTE_NONE));
- base::PostTask(FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(std::move(callback), std::move(ip4_networks)));
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(std::move(callback), std::move(ip4_networks)));
}
void GetNetworkListOnUIThread(
@@ -85,22 +84,22 @@ PrivetTrafficDetector::PrivetTrafficDetector(
: helper_(new Helper(profile, on_traffic_detected)) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::GetNetworkConnectionTracker()->AddNetworkConnectionObserver(this);
- base::PostTask(FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&PrivetTrafficDetector::Helper::ScheduleRestart,
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&PrivetTrafficDetector::Helper::ScheduleRestart,
base::Unretained(helper_)));
}
PrivetTrafficDetector::~PrivetTrafficDetector() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::GetNetworkConnectionTracker()->RemoveNetworkConnectionObserver(this);
- base::DeleteSoon(FROM_HERE, {content::BrowserThread::IO}, helper_);
+ content::GetIOThreadTaskRunner({})->DeleteSoon(FROM_HERE, helper_);
}
void PrivetTrafficDetector::OnConnectionChanged(
network::mojom::ConnectionType type) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PrivetTrafficDetector::Helper::HandleConnectionChanged,
base::Unretained(helper_), type));
}
@@ -131,8 +130,8 @@ void PrivetTrafficDetector::Helper::ScheduleRestart() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
ResetConnection();
weak_ptr_factory_.InvalidateWeakPtrs();
- base::PostDelayedTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostDelayedTask(
+ FROM_HERE,
base::BindOnce(
&GetNetworkListOnUIThread,
base::BindOnce(&Helper::Restart, weak_ptr_factory_.GetWeakPtr())),
@@ -149,8 +148,8 @@ void PrivetTrafficDetector::Helper::Restart(
void PrivetTrafficDetector::Helper::Bind() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&CreateUDPSocketOnUIThread, profile_,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&CreateUDPSocketOnUIThread, profile_,
socket_.BindNewPipeAndPassReceiver(),
listener_receiver_.BindNewPipeAndPassRemote()));
@@ -251,8 +250,8 @@ void PrivetTrafficDetector::Helper::OnReceived(
recv_addr_ = src_addr.value();
if (IsPrivetPacket(data.value())) {
ResetConnection();
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- on_traffic_detected_);
+ content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
+ on_traffic_detected_);
} else {
socket_->ReceiveMoreWithBufferSize(1, net::dns_protocol::kMaxMulticastSize);
}
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 81207239a71..2e7c95f9bb6 100644
--- a/chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc
+++ b/chromium/chrome/browser/printing/cloud_print/privet_url_loader.cc
@@ -250,8 +250,8 @@ void PrivetURLLoader::OnDownloadedToString(
return;
}
- base::JSONReader json_reader(base::JSON_ALLOW_TRAILING_COMMAS);
- base::Optional<base::Value> value = json_reader.ReadToValue(*response_body);
+ base::Optional<base::Value> value =
+ base::JSONReader::Read(*response_body, base::JSON_ALLOW_TRAILING_COMMAS);
if (!value || !value->is_dict()) {
delegate_->OnError(0, JSON_PARSE_ERROR);
return;
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 130fac6497a..46d81158e7a 100644
--- a/chromium/chrome/browser/printing/pdf_to_emf_converter_browsertest.cc
+++ b/chromium/chrome/browser/printing/pdf_to_emf_converter_browsertest.cc
@@ -298,8 +298,13 @@ IN_PROC_BROWSER_TEST_F(PdfToEmfConverterBrowserTest, PostScriptLevel2Basic) {
for (int i = 0; i < kNumberOfPages; ++i) {
ASSERT_TRUE(GetPage(i));
// The output is PS encapsulated in EMF.
+#ifdef NTDDI_WIN10_VB // Windows 10.0.19041
+ ASSERT_TRUE(GetPageExpectedEmfData(
+ GetFileNameForPageNumber("pdf_converter_basic_ps_new_page_", i)));
+#else
ASSERT_TRUE(GetPageExpectedEmfData(
GetFileNameForPageNumber("pdf_converter_basic_ps_page_", i)));
+#endif
ComparePageEmfHeader();
ComparePageEmfPayload();
}
@@ -317,8 +322,13 @@ IN_PROC_BROWSER_TEST_F(PdfToEmfConverterBrowserTest, PostScriptLevel3Basic) {
for (int i = 0; i < kNumberOfPages; ++i) {
ASSERT_TRUE(GetPage(i));
// The output is PS encapsulated in EMF.
+#ifdef NTDDI_WIN10_VB // Windows 10.0.19041
+ ASSERT_TRUE(GetPageExpectedEmfData(
+ GetFileNameForPageNumber("pdf_converter_basic_ps_new_page_", i)));
+#else
ASSERT_TRUE(GetPageExpectedEmfData(
GetFileNameForPageNumber("pdf_converter_basic_ps_page_", i)));
+#endif
ComparePageEmfHeader();
ComparePageEmfPayload();
}
@@ -368,8 +378,13 @@ IN_PROC_BROWSER_TEST_F(PdfToEmfConverterBrowserTest,
kLetter200DpiRect, gfx::Point(0, 0), k200DpiSize,
/*autorotate=*/false, /*use_color=*/true,
PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2);
+#ifdef NTDDI_WIN10_VB // Windows 10.0.19041
+ RunSinglePagePdfToPostScriptConverterTest(pdf_settings, "bug_806746.pdf",
+ "bug_806746_new.emf");
+#else
RunSinglePagePdfToPostScriptConverterTest(pdf_settings, "bug_806746.pdf",
"bug_806746.emf");
+#endif
}
IN_PROC_BROWSER_TEST_F(PdfToEmfConverterBrowserTest,
@@ -378,8 +393,13 @@ IN_PROC_BROWSER_TEST_F(PdfToEmfConverterBrowserTest,
kLetter200DpiRect, gfx::Point(0, 0), k200DpiSize,
/*autorotate=*/false, /*use_color=*/true,
PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3);
+#ifdef NTDDI_WIN10_VB // Windows 10.0.19041
+ RunSinglePagePdfToPostScriptConverterTest(pdf_settings, "bug_806746.pdf",
+ "bug_806746_new.emf");
+#else
RunSinglePagePdfToPostScriptConverterTest(pdf_settings, "bug_806746.pdf",
"bug_806746.emf");
+#endif
}
IN_PROC_BROWSER_TEST_F(PdfToEmfConverterBrowserTest,
diff --git a/chromium/chrome/browser/printing/print_browsertest.cc b/chromium/chrome/browser/printing/print_browsertest.cc
index 3de2b60a683..cc9c1fde80c 100644
--- a/chromium/chrome/browser/printing/print_browsertest.cc
+++ b/chromium/chrome/browser/printing/print_browsertest.cc
@@ -27,6 +27,7 @@
#include "components/prefs/pref_service.h"
#include "components/printing/browser/print_composite_client.h"
#include "components/printing/browser/print_manager_utils.h"
+#include "components/printing/common/print.mojom-test-utils.h"
#include "components/printing/common/print.mojom.h"
#include "components/printing/common/print_messages.h"
#include "content/public/browser/browser_message_filter.h"
@@ -41,6 +42,7 @@
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
+#include "printing/mojom/print.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/scheduler/web_scheduler_tracked_feature.h"
@@ -78,6 +80,8 @@ class PrintPreviewObserver : PrintPreviewUI::TestDelegate {
}
}
+ content::WebContents* GetPrintPreviewDialog() { return preview_dialog_; }
+
private:
// PrintPreviewUI::TestDelegate:
void DidGetPreviewPageCount(int page_count) override {
@@ -90,6 +94,7 @@ class PrintPreviewObserver : PrintPreviewUI::TestDelegate {
CHECK(rendered_page_count_ <= total_page_count_);
if (rendered_page_count_ == total_page_count_ && run_loop_) {
run_loop_->Quit();
+ preview_dialog_ = preview_dialog;
if (queue_.has_value()) {
content::ExecuteScriptAsync(
@@ -106,6 +111,7 @@ class PrintPreviewObserver : PrintPreviewUI::TestDelegate {
base::Optional<content::DOMMessageQueue> queue_;
int total_page_count_ = 1;
int rendered_page_count_ = 0;
+ content::WebContents* preview_dialog_ = nullptr;
base::RunLoop* run_loop_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(PrintPreviewObserver);
@@ -129,8 +135,8 @@ class NupPrintingTestDelegate : public PrintingMessageFilter::TestDelegate {
params.dpi = gfx::Size(72, 72);
params.document_cookie = kDefaultDocumentCookie;
params.pages_per_sheet = 4;
- params.printed_doc_type =
- IsOopifEnabled() ? SkiaDocumentType::MSKP : SkiaDocumentType::PDF;
+ params.printed_doc_type = IsOopifEnabled() ? mojom::SkiaDocumentType::kMSKP
+ : mojom::SkiaDocumentType::kPDF;
return params;
}
@@ -138,66 +144,127 @@ class NupPrintingTestDelegate : public PrintingMessageFilter::TestDelegate {
DISALLOW_COPY_AND_ASSIGN(NupPrintingTestDelegate);
};
-class TestPrintFrameContentMsgFilter : public content::BrowserMessageFilter {
+class TestPrintRenderFrame
+ : public mojom::PrintRenderFrameInterceptorForTesting {
public:
- TestPrintFrameContentMsgFilter(int document_cookie,
- base::RepeatingClosure msg_callback)
- : content::BrowserMessageFilter(PrintMsgStart),
+ TestPrintRenderFrame(content::RenderFrameHost* frame_host,
+ content::WebContents* web_contents,
+ int document_cookie,
+ base::RepeatingClosure msg_callback)
+ : frame_host_(frame_host),
+ web_contents_(web_contents),
document_cookie_(document_cookie),
task_runner_(base::SequencedTaskRunnerHandle::Get()),
msg_callback_(msg_callback) {}
+ ~TestPrintRenderFrame() override = default;
- bool OnMessageReceived(const IPC::Message& message) override {
- // Only expect PrintHostMsg_DidPrintFrameContent message.
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(TestPrintFrameContentMsgFilter, message)
- IPC_MESSAGE_HANDLER(PrintHostMsg_DidPrintFrameContent, CheckMessage)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- EXPECT_TRUE(handled);
+ void OnDidPrintFrameContent(int document_cookie,
+ mojom::DidPrintContentParamsPtr param,
+ PrintFrameContentCallback callback) const {
+ EXPECT_EQ(document_cookie, document_cookie_);
+ ASSERT_TRUE(param->metafile_data_region.IsValid());
+ EXPECT_GT(param->metafile_data_region.GetSize(), 0U);
task_runner_->PostTask(FROM_HERE, msg_callback_);
- return true;
- }
-
- private:
- ~TestPrintFrameContentMsgFilter() override = default;
+ std::move(callback).Run(document_cookie, std::move(param));
+ }
+
+ void Bind(mojo::ScopedInterfaceEndpointHandle handle) {
+ receiver_.Bind(mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame>(
+ std::move(handle)));
+ }
+
+ // mojom::PrintRenderFrameInterceptorForTesting
+ mojom::PrintRenderFrame* GetForwardingInterface() override {
+ NOTREACHED();
+ return nullptr;
+ }
+ void PrintFrameContent(mojom::PrintFrameContentParamsPtr params,
+ PrintFrameContentCallback callback) override {
+ // Sends the printed result back.
+ mojom::DidPrintContentParamsPtr printed_frame_params =
+ mojom::DidPrintContentParams::New();
+ // Creates a small amount of region to avoid passing empty data to mojo.
+ constexpr size_t kSize = 10;
+ base::MappedReadOnlyRegion region_mapping =
+ base::ReadOnlySharedMemoryRegion::Create(kSize);
+ printed_frame_params->metafile_data_region =
+ std::move(region_mapping.region);
+ OnDidPrintFrameContent(params->document_cookie,
+ std::move(printed_frame_params),
+ std::move(callback));
+
+ auto* client = PrintCompositeClient::FromWebContents(web_contents_);
+ if (!client)
+ return;
- void CheckMessage(int document_cookie,
- const PrintHostMsg_DidPrintContent_Params& param) {
- EXPECT_EQ(document_cookie, document_cookie_);
- ASSERT_TRUE(param.metafile_data_region.IsValid());
- EXPECT_GT(param.metafile_data_region.GetSize(), 0U);
+ // Prints its children.
+ content::RenderFrameHost* child = ChildFrameAt(frame_host_, 0);
+ for (size_t i = 1; child; i++) {
+ if (child->GetSiteInstance() != frame_host_->GetSiteInstance()) {
+ client->PrintCrossProcessSubframe(gfx::Rect(), params->document_cookie,
+ child);
+ }
+ child = ChildFrameAt(frame_host_, i);
+ }
}
+ private:
+ content::RenderFrameHost* frame_host_;
+ content::WebContents* web_contents_;
const int document_cookie_;
scoped_refptr<base::SequencedTaskRunner> task_runner_;
base::RepeatingClosure msg_callback_;
+ mojo::AssociatedReceiver<mojom::PrintRenderFrame> receiver_{this};
};
-class KillPrintFrameContentMsgFilter : public content::BrowserMessageFilter {
+class KillPrintRenderFrame
+ : public mojom::PrintRenderFrameInterceptorForTesting {
public:
- explicit KillPrintFrameContentMsgFilter(content::RenderProcessHost* rph)
- : content::BrowserMessageFilter(PrintMsgStart), rph_(rph) {}
+ explicit KillPrintRenderFrame(content::RenderProcessHost* rph) : rph_(rph) {}
+ ~KillPrintRenderFrame() override = default;
- bool OnMessageReceived(const IPC::Message& message) override {
- // Only handle PrintHostMsg_DidPrintFrameContent message.
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(KillPrintFrameContentMsgFilter, message)
- IPC_MESSAGE_HANDLER(PrintHostMsg_DidPrintFrameContent, KillRenderProcess)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled;
+ void OverrideBinderForTesting(content::RenderFrameHost* render_frame_host) {
+ render_frame_host->GetRemoteAssociatedInterfaces()
+ ->OverrideBinderForTesting(
+ mojom::PrintRenderFrame::Name_,
+ base::BindRepeating(&KillPrintRenderFrame::Bind,
+ base::Unretained(this)));
}
- private:
- ~KillPrintFrameContentMsgFilter() override = default;
-
void KillRenderProcess(int document_cookie,
- const PrintHostMsg_DidPrintContent_Params& param) {
+ mojom::DidPrintContentParamsPtr param,
+ PrintFrameContentCallback callback) const {
+ std::move(callback).Run(document_cookie, std::move(param));
rph_->Shutdown(0);
}
- content::RenderProcessHost* rph_;
+ void Bind(mojo::ScopedInterfaceEndpointHandle handle) {
+ receiver_.Bind(mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame>(
+ std::move(handle)));
+ }
+
+ // mojom::PrintRenderFrameInterceptorForTesting
+ mojom::PrintRenderFrame* GetForwardingInterface() override {
+ NOTREACHED();
+ return nullptr;
+ }
+ void PrintFrameContent(mojom::PrintFrameContentParamsPtr params,
+ PrintFrameContentCallback callback) override {
+ // Sends the printed result back.
+ const size_t kSize = 10;
+ mojom::DidPrintContentParamsPtr printed_frame_params =
+ mojom::DidPrintContentParams::New();
+ base::MappedReadOnlyRegion region_mapping =
+ base::ReadOnlySharedMemoryRegion::Create(kSize);
+ printed_frame_params->metafile_data_region =
+ std::move(region_mapping.region);
+ KillRenderProcess(params->document_cookie, std::move(printed_frame_params),
+ std::move(callback));
+ }
+
+ private:
+ content::RenderProcessHost* const rph_;
+ mojo::AssociatedReceiver<mojom::PrintRenderFrame> receiver_{this};
};
} // namespace
@@ -210,7 +277,6 @@ class PrintBrowserTest : public InProcessBrowserTest {
void SetUp() override {
num_expected_messages_ = 1; // By default, only wait on one message.
num_received_messages_ = 0;
- run_loop_.reset();
InProcessBrowserTest::SetUp();
}
@@ -246,23 +312,27 @@ class PrintBrowserTest : public InProcessBrowserTest {
num_expected_messages_ = num;
}
- void WaitUntilMessagesReceived() {
- run_loop_ = std::make_unique<base::RunLoop>();
- run_loop_->Run();
+ void WaitUntilCallbackReceived() {
+ base::RunLoop run_loop;
+ quit_callback_ = run_loop.QuitClosure();
+ run_loop.Run();
}
void CheckForQuit() {
- if (++num_received_messages_ == num_expected_messages_) {
- run_loop_->QuitWhenIdle();
- }
+ if (++num_received_messages_ != num_expected_messages_)
+ return;
+ if (quit_callback_)
+ std::move(quit_callback_).Run();
}
- void AddFilterForFrame(content::RenderFrameHost* frame_host) {
- auto filter = base::MakeRefCounted<TestPrintFrameContentMsgFilter>(
- kDefaultDocumentCookie,
- base::BindRepeating(&PrintBrowserTest::CheckForQuit,
- base::Unretained(this)));
- frame_host->GetProcess()->AddFilter(filter.get());
+ void CreateTestPrintRenderFrame(content::RenderFrameHost* frame_host,
+ content::WebContents* web_contents) {
+ frame_content_.emplace(
+ frame_host, std::make_unique<TestPrintRenderFrame>(
+ frame_host, web_contents, kDefaultDocumentCookie,
+ base::BindRepeating(&PrintBrowserTest::CheckForQuit,
+ base::Unretained(this))));
+ OverrideBinderForTesting(frame_host);
}
static mojom::PrintFrameContentParamsPtr GetDefaultPrintFrameParams() {
@@ -270,17 +340,34 @@ class PrintBrowserTest : public InProcessBrowserTest {
kDefaultDocumentCookie);
}
- static const mojo::AssociatedRemote<mojom::PrintRenderFrame>
- GetPrintRenderFrame(content::RenderFrameHost* rfh) {
- mojo::AssociatedRemote<mojom::PrintRenderFrame> remote;
- rfh->GetRemoteAssociatedInterfaces()->GetInterface(&remote);
- return remote;
+ const mojo::AssociatedRemote<mojom::PrintRenderFrame>& GetPrintRenderFrame(
+ content::RenderFrameHost* rfh) {
+ if (!remote_)
+ rfh->GetRemoteAssociatedInterfaces()->GetInterface(&remote_);
+ return remote_;
}
private:
+ TestPrintRenderFrame* GetFrameContent(content::RenderFrameHost* host) const {
+ auto iter = frame_content_.find(host);
+ return iter != frame_content_.end() ? iter->second.get() : nullptr;
+ }
+
+ void OverrideBinderForTesting(content::RenderFrameHost* render_frame_host) {
+ render_frame_host->GetRemoteAssociatedInterfaces()
+ ->OverrideBinderForTesting(
+ mojom::PrintRenderFrame::Name_,
+ base::BindRepeating(
+ &TestPrintRenderFrame::Bind,
+ base::Unretained(GetFrameContent(render_frame_host))));
+ }
+
unsigned int num_expected_messages_;
unsigned int num_received_messages_;
- std::unique_ptr<base::RunLoop> run_loop_;
+ base::OnceClosure quit_callback_;
+ mojo::AssociatedRemote<mojom::PrintRenderFrame> remote_;
+ std::map<content::RenderFrameHost*, std::unique_ptr<TestPrintRenderFrame>>
+ frame_content_;
};
class SitePerProcessPrintBrowserTest : public PrintBrowserTest {
@@ -444,7 +531,7 @@ IN_PROC_BROWSER_TEST_F(PrintBrowserTest, SelectionContainsIframe) {
// Printing frame content for the main frame of a generic webpage.
// This test passes when the printed result is sent back and checked in
-// TestPrintFrameContentMsgFilter::CheckMessage().
+// TestPrintRenderFrame::OnDidPrintFrameContent().
IN_PROC_BROWSER_TEST_F(PrintBrowserTest, PrintFrameContent) {
ASSERT_TRUE(embedded_test_server()->Started());
GURL url(embedded_test_server()->GetURL("/printing/test1.html"));
@@ -453,18 +540,18 @@ IN_PROC_BROWSER_TEST_F(PrintBrowserTest, PrintFrameContent) {
content::WebContents* original_contents =
browser()->tab_strip_model()->GetActiveWebContents();
content::RenderFrameHost* rfh = original_contents->GetMainFrame();
- AddFilterForFrame(rfh);
-
- GetPrintRenderFrame(rfh)->PrintFrameContent(GetDefaultPrintFrameParams());
+ CreateTestPrintRenderFrame(rfh, original_contents);
+ GetPrintRenderFrame(rfh)->PrintFrameContent(GetDefaultPrintFrameParams(),
+ base::DoNothing());
// The printed result will be received and checked in
- // TestPrintFrameContentMsgFilter.
- WaitUntilMessagesReceived();
+ // TestPrintRenderFrame.
+ WaitUntilCallbackReceived();
}
// Printing frame content for a cross-site iframe.
// This test passes when the iframe responds to the print message.
-// The response is checked in TestPrintFrameContentMsgFilter::CheckMessage().
+// The response is checked in TestPrintRenderFrame::OnDidPrintFrameContent().
IN_PROC_BROWSER_TEST_F(PrintBrowserTest, PrintSubframeContent) {
ASSERT_TRUE(embedded_test_server()->Started());
GURL url(
@@ -477,21 +564,20 @@ IN_PROC_BROWSER_TEST_F(PrintBrowserTest, PrintSubframeContent) {
content::RenderFrameHost* test_frame = original_contents->GetAllFrames()[1];
ASSERT_TRUE(test_frame);
- AddFilterForFrame(test_frame);
-
+ CreateTestPrintRenderFrame(test_frame, original_contents);
GetPrintRenderFrame(test_frame)
- ->PrintFrameContent(GetDefaultPrintFrameParams());
+ ->PrintFrameContent(GetDefaultPrintFrameParams(), base::DoNothing());
// The printed result will be received and checked in
- // TestPrintFrameContentMsgFilter.
- WaitUntilMessagesReceived();
+ // TestPrintRenderFrame.
+ WaitUntilCallbackReceived();
}
// Printing frame content with a cross-site iframe which also has a cross-site
// iframe. The site reference chain is a.com --> b.com --> c.com.
// This test passes when both cross-site frames are printed and their
// responses which are checked in
-// TestPrintFrameContentMsgFilter::CheckMessage().
+// TestPrintRenderFrame::OnDidPrintFrameContent().
IN_PROC_BROWSER_TEST_F(PrintBrowserTest, PrintSubframeChain) {
ASSERT_TRUE(embedded_test_server()->Started());
GURL url(embedded_test_server()->GetURL(
@@ -518,19 +604,19 @@ IN_PROC_BROWSER_TEST_F(PrintBrowserTest, PrintSubframeChain) {
ASSERT_NE(grandchild_frame->GetProcess(), main_frame->GetProcess());
}
- AddFilterForFrame(main_frame);
+ CreateTestPrintRenderFrame(main_frame, original_contents);
if (oopif_enabled) {
- AddFilterForFrame(child_frame);
- AddFilterForFrame(grandchild_frame);
+ CreateTestPrintRenderFrame(child_frame, original_contents);
+ CreateTestPrintRenderFrame(grandchild_frame, original_contents);
}
GetPrintRenderFrame(main_frame)
- ->PrintFrameContent(GetDefaultPrintFrameParams());
+ ->PrintFrameContent(GetDefaultPrintFrameParams(), base::DoNothing());
// The printed result will be received and checked in
- // TestPrintFrameContentMsgFilter.
+ // TestPrintRenderFrame.
SetNumExpectedMessages(oopif_enabled ? 3 : 1);
- WaitUntilMessagesReceived();
+ WaitUntilCallbackReceived();
}
// Printing frame content with a cross-site iframe who also has a cross site
@@ -538,7 +624,7 @@ IN_PROC_BROWSER_TEST_F(PrintBrowserTest, PrintSubframeChain) {
// The site reference loop is a.com --> b.com --> a.com.
// This test passes when both cross-site frames are printed and send back
// responses which are checked in
-// TestPrintFrameContentMsgFilter::CheckMessage().
+// TestPrintRenderFrame::OnDidPrintFrameContent().
IN_PROC_BROWSER_TEST_F(PrintBrowserTest, PrintSubframeABA) {
ASSERT_TRUE(embedded_test_server()->Started());
GURL url(embedded_test_server()->GetURL(
@@ -564,17 +650,19 @@ IN_PROC_BROWSER_TEST_F(PrintBrowserTest, PrintSubframeABA) {
// enabled, they will be in the same process.
ASSERT_EQ(grandchild_frame->GetProcess(), main_frame->GetProcess());
- AddFilterForFrame(main_frame);
- if (oopif_enabled)
- AddFilterForFrame(child_frame);
+ CreateTestPrintRenderFrame(main_frame, original_contents);
+ if (oopif_enabled) {
+ CreateTestPrintRenderFrame(child_frame, original_contents);
+ CreateTestPrintRenderFrame(grandchild_frame, original_contents);
+ }
GetPrintRenderFrame(main_frame)
- ->PrintFrameContent(GetDefaultPrintFrameParams());
+ ->PrintFrameContent(GetDefaultPrintFrameParams(), base::DoNothing());
// The printed result will be received and checked in
- // TestPrintFrameContentMsgFilter.
+ // TestPrintRenderFrame.
SetNumExpectedMessages(oopif_enabled ? 3 : 1);
- WaitUntilMessagesReceived();
+ WaitUntilCallbackReceived();
}
// Printing preview a simple webpage when site per process is enabled.
@@ -635,10 +723,9 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessPrintBrowserTest,
ASSERT_TRUE(subframe);
auto* subframe_rph = subframe->GetProcess();
- auto filter =
- base::MakeRefCounted<KillPrintFrameContentMsgFilter>(subframe_rph);
+ KillPrintRenderFrame frame_content(subframe_rph);
+ frame_content.OverrideBinderForTesting(subframe);
content::ScopedAllowRendererCrashes allow_renderer_crashes(subframe_rph);
- subframe_rph->AddFilter(filter.get());
PrintAndWaitUntilPreviewIsReady(/*print_only_selection=*/false);
}
@@ -762,4 +849,57 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessPrintBrowserTest, MultipagePrint) {
PrintAndWaitUntilPreviewIsReadyAndLoaded(/*print_only_selection=*/false);
}
+IN_PROC_BROWSER_TEST_F(PrintBrowserTest, PDFPluginNotKeyboardFocusable) {
+ ASSERT_TRUE(embedded_test_server()->Started());
+ GURL url(embedded_test_server()->GetURL("/printing/multipage.html"));
+ ui_test_utils::NavigateToURL(browser(), url);
+
+ PrintPreviewObserver print_preview_observer(/*wait_for_loaded=*/true);
+ StartPrint(browser()->tab_strip_model()->GetActiveWebContents(),
+ /*print_renderer=*/mojo::NullAssociatedRemote(),
+ /*print_preview_disabled=*/false, /*print_only_selection=*/false);
+ print_preview_observer.WaitUntilPreviewIsReady();
+
+ content::WebContents* preview_dialog =
+ print_preview_observer.GetPrintPreviewDialog();
+ ASSERT_TRUE(preview_dialog);
+
+ // The script will ensure we return the id of <zoom-out-button> when
+ // focused. Focus the element after PDF plugin in tab order.
+ const char kScript[] = R"(
+ const button = document.getElementsByTagName('print-preview-app')[0]
+ .$['previewArea']
+ .$$('iframe')
+ .contentDocument.querySelector('pdf-viewer-pp')
+ .shadowRoot.querySelector('#zoom-toolbar')
+ .$['zoom-out-button'];
+ button.addEventListener('focus', (e) => {
+ window.domAutomationController.send(e.target.id);
+ });
+
+ const select_tag = document.getElementsByTagName('print-preview-app')[0]
+ .$['sidebar']
+ .$['destinationSettings']
+ .$['destinationSelect']
+ .$$('select');
+ select_tag.addEventListener('focus', () => {
+ window.domAutomationController.send(true);
+ });
+ select_tag.focus();)";
+ bool success = false;
+ ASSERT_TRUE(
+ content::ExecuteScriptAndExtractBool(preview_dialog, kScript, &success));
+ ASSERT_TRUE(success);
+
+ // Simulate a <shift-tab> press and wait for a focus message.
+ content::DOMMessageQueue msg_queue;
+ SimulateKeyPress(preview_dialog, ui::DomKey::TAB, ui::DomCode::TAB,
+ ui::VKEY_TAB, false, true, false, false);
+ std::string reply;
+ ASSERT_TRUE(msg_queue.WaitForMessage(&reply));
+ // Pressing <shift-tab> should focus the last toolbar element
+ // (zoom-out-button) instead of PDF plugin.
+ EXPECT_EQ("\"zoom-out-button\"", reply);
+}
+
} // namespace printing
diff --git a/chromium/chrome/browser/printing/print_error_dialog.cc b/chromium/chrome/browser/printing/print_error_dialog.cc
index 1f95636f43a..15ffdb16ed4 100644
--- a/chromium/chrome/browser/printing/print_error_dialog.cc
+++ b/chromium/chrome/browser/printing/print_error_dialog.cc
@@ -5,7 +5,6 @@
#include "chrome/browser/printing/print_error_dialog.h"
#include "base/bind.h"
-#include "base/task/post_task.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/simple_message_box.h"
@@ -28,6 +27,6 @@ void ShowPrintErrorDialogTask() {
void ShowPrintErrorDialog() {
// Nested loop may destroy caller.
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&ShowPrintErrorDialogTask));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&ShowPrintErrorDialogTask));
}
diff --git a/chromium/chrome/browser/printing/print_job.cc b/chromium/chrome/browser/printing/print_job.cc
index 806e3e3a72e..668a14bff46 100644
--- a/chromium/chrome/browser/printing/print_job.cc
+++ b/chromium/chrome/browser/printing/print_job.cc
@@ -248,8 +248,8 @@ bool PrintJob::FlushJob(base::TimeDelta timeout) {
base::RunLoop loop(base::RunLoop::Type::kNestableTasksAllowed);
quit_closure_ = loop.QuitClosure();
- base::PostDelayedTask(FROM_HERE, {content::BrowserThread::UI},
- loop.QuitClosure(), timeout);
+ content::GetUIThreadTaskRunner({})->PostDelayedTask(
+ FROM_HERE, loop.QuitClosure(), timeout);
loop.Run();
@@ -515,8 +515,8 @@ void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) {
}
case JobEventDetails::DOC_DONE: {
// This will call Stop() and broadcast a JOB_DONE message.
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&PrintJob::OnDocumentDone, this));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&PrintJob::OnDocumentDone, this));
break;
}
#if defined(OS_WIN)
@@ -573,9 +573,8 @@ void PrintJob::ControlledWorkerShutdown() {
// Delay shutdown until the worker terminates. We want this code path
// to wait on the thread to quit before continuing.
if (worker_->IsRunning()) {
- base::PostDelayedTask(
- FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&PrintJob::ControlledWorkerShutdown, this),
+ content::GetUIThreadTaskRunner({})->PostDelayedTask(
+ FROM_HERE, base::BindOnce(&PrintJob::ControlledWorkerShutdown, this),
base::TimeDelta::FromMilliseconds(100));
return;
}
diff --git a/chromium/chrome/browser/printing/print_job_manager.h b/chromium/chrome/browser/printing/print_job_manager.h
index e66e7f1ae21..bdeba8404b7 100644
--- a/chromium/chrome/browser/printing/print_job_manager.h
+++ b/chromium/chrome/browser/printing/print_job_manager.h
@@ -9,7 +9,6 @@
#include <set>
#include <vector>
-#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/lock.h"
diff --git a/chromium/chrome/browser/printing/print_job_worker.cc b/chromium/chrome/browser/printing/print_job_worker.cc
index 9122bbf4f15..52efa2037a3 100644
--- a/chromium/chrome/browser/printing/print_job_worker.cc
+++ b/chromium/chrome/browser/printing/print_job_worker.cc
@@ -14,7 +14,6 @@
#include "base/compiler_specific.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
-#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "build/build_config.h"
@@ -169,14 +168,14 @@ void PrintJobWorker::GetSettings(bool ask_user_for_settings,
// When we delegate to a destination, we don't ask the user for settings.
// TODO(mad): Ask the destination for settings.
if (ask_user_for_settings) {
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PrintJobWorker::GetSettingsWithUI,
base::Unretained(this), document_page_count,
has_selection, is_scripted, std::move(callback)));
} else {
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&PrintJobWorker::UseDefaultSettings,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&PrintJobWorker::UseDefaultSettings,
base::Unretained(this), std::move(callback)));
}
}
@@ -185,8 +184,8 @@ void PrintJobWorker::SetSettings(base::Value new_settings,
SettingsCallback callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&PrintJobWorker::UpdatePrintSettings,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&PrintJobWorker::UpdatePrintSettings,
base::Unretained(this), std::move(new_settings),
std::move(callback)));
}
@@ -197,8 +196,8 @@ void PrintJobWorker::SetSettingsFromPOD(
SettingsCallback callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&PrintJobWorker::UpdatePrintSettingsFromPOD,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&PrintJobWorker::UpdatePrintSettingsFromPOD,
base::Unretained(this), std::move(new_settings),
std::move(callback)));
}
@@ -222,6 +221,18 @@ void PrintJobWorker::UpdatePrintSettings(base::Value new_settings,
std::string printer_name = *new_settings.FindStringKey(kSettingDeviceName);
crash_key = std::make_unique<crash_keys::ScopedPrinterInfo>(
print_backend->GetPrinterDriverInfo(printer_name));
+
+#if defined(OS_LINUX) && defined(USE_CUPS) && !defined(OS_CHROMEOS)
+ PrinterBasicInfo basic_info;
+ if (print_backend->GetPrinterBasicInfo(printer_name, &basic_info)) {
+ base::Value advanced_settings(base::Value::Type::DICTIONARY);
+ for (const auto& pair : basic_info.options)
+ advanced_settings.SetStringKey(pair.first, pair.second);
+
+ new_settings.SetKey(kSettingAdvancedSettings,
+ std::move(advanced_settings));
+ }
+#endif // defined(OS_LINUX) && defined(USE_CUPS) && !defined(OS_CHROMEOS)
}
PrintingContext::Result result;
@@ -292,7 +303,15 @@ void PrintJobWorker::GetSettingsWithUI(int document_page_count,
}
void PrintJobWorker::UseDefaultSettings(SettingsCallback callback) {
- PrintingContext::Result result = printing_context_->UseDefaultSettings();
+ PrintingContext::Result result;
+ {
+#if defined(OS_WIN)
+ // Blocking is needed here because Windows printer drivers are oftentimes
+ // not thread-safe and have to be accessed on the UI thread.
+ base::ScopedAllowBlocking allow_blocking;
+#endif
+ result = printing_context_->UseDefaultSettings();
+ }
GetSettingsDone(std::move(callback), result);
}
diff --git a/chromium/chrome/browser/printing/print_preview_dialog_controller.cc b/chromium/chrome/browser/printing/print_preview_dialog_controller.cc
index 84818167bce..3fadaba3336 100644
--- a/chromium/chrome/browser/printing/print_preview_dialog_controller.cc
+++ b/chromium/chrome/browser/printing/print_preview_dialog_controller.cc
@@ -256,7 +256,7 @@ void PrintPreviewDialogController::PrintPreview(WebContents* initiator) {
ModuleDatabase::DisableThirdPartyBlocking();
#endif
- if (initiator->ShowingInterstitialPage() || initiator->IsCrashed())
+ if (initiator->IsCrashed())
return;
PrintPreviewDialogController* dialog_controller = GetInstance();
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 a76b50bba43..86b77391c64 100644
--- a/chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc
+++ b/chromium/chrome/browser/printing/print_preview_dialog_controller_browsertest.cc
@@ -206,16 +206,10 @@ class PrintPreviewDialogControllerBrowserTest : public InProcessBrowserTest {
DISALLOW_COPY_AND_ASSIGN(PrintPreviewDialogControllerBrowserTest);
};
-// Flaky on Linux: crbug.com/1021545
-#if defined(OS_LINUX)
-#define MAYBE_NavigateFromInitiatorTab DISABLED_NavigateFromInitiatorTab
-#else
-#define MAYBE_NavigateFromInitiatorTab NavigateFromInitiatorTab
-#endif
// Test to verify that when a initiator navigates, we can create a new preview
// dialog for the new tab contents.
IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest,
- MAYBE_NavigateFromInitiatorTab) {
+ NavigateFromInitiatorTab) {
// Print for the first time.
PrintPreview();
@@ -242,16 +236,10 @@ IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest,
EXPECT_TRUE(new_preview_dialog);
}
-// Flaky on Linux: crbug.com/1021545
-#if defined(OS_LINUX)
-#define MAYBE_ReloadInitiatorTab DISABLED_ReloadInitiatorTab
-#else
-#define MAYBE_ReloadInitiatorTab ReloadInitiatorTab
-#endif
// Test to verify that after reloading the initiator, it creates a new print
// preview dialog.
IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest,
- MAYBE_ReloadInitiatorTab) {
+ ReloadInitiatorTab) {
// Print for the first time.
PrintPreview();
@@ -282,16 +270,10 @@ IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest,
EXPECT_TRUE(new_preview_dialog);
}
-// Flaky on Linux: crbug.com/1021545
-#if defined(OS_LINUX)
-#define MAYBE_PdfPluginDisabled DISABLED_PdfPluginDisabled
-#else
-#define MAYBE_PdfPluginDisabled PdfPluginDisabled
-#endif
// Test to verify that after print preview works even when the PDF plugin is
// disabled for webpages.
IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest,
- MAYBE_PdfPluginDisabled) {
+ PdfPluginDisabled) {
// Make sure plugins are loaded.
{
base::RunLoop run_loop;
@@ -355,14 +337,8 @@ const std::vector<task_manager::WebContentsTag*>& GetTrackedTags() {
} // namespace
-// Flaky on Linux: crbug.com/1021545
-#if defined(OS_LINUX)
-#define MAYBE_TaskManagementTest DISABLED_TaskManagementTest
-#else
-#define MAYBE_TaskManagementTest TaskManagementTest
-#endif
IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest,
- MAYBE_TaskManagementTest) {
+ TaskManagementTest) {
// This test starts with two tabs open.
EXPECT_EQ(2U, GetTrackedTags().size());
@@ -403,14 +379,8 @@ IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest,
base::CompareCase::INSENSITIVE_ASCII));
}
-// Flaky on Linux: crbug.com/1021545
-#if defined(OS_LINUX)
-#define MAYBE_PrintPreviewPdfAccessibility DISABLED_PrintPreviewPdfAccessibility
-#else
-#define MAYBE_PrintPreviewPdfAccessibility PrintPreviewPdfAccessibility
-#endif
IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest,
- MAYBE_PrintPreviewPdfAccessibility) {
+ PrintPreviewPdfAccessibility) {
content::BrowserAccessibilityState::GetInstance()->EnableAccessibility();
ui_test_utils::NavigateToURL(browser(), GURL("data:text/html,HelloWorld"));
PrintPreview();
diff --git a/chromium/chrome/browser/printing/print_preview_dialog_controller_unittest.cc b/chromium/chrome/browser/printing/print_preview_dialog_controller_unittest.cc
index 674f46509eb..ed7636e0eee 100644
--- a/chromium/chrome/browser/printing/print_preview_dialog_controller_unittest.cc
+++ b/chromium/chrome/browser/printing/print_preview_dialog_controller_unittest.cc
@@ -199,7 +199,7 @@ TEST_F(PrintPreviewDialogControllerUnitTest, CloseDialogOnNavigation) {
// Two similar URLs (same webpage, different URL fragment/query)
// Gmail navigates from fragment to query when opening an email to print.
GURL tiger("https://www.google.com/#q=tiger");
- GURL tiger_barb("https://www.google.com/?q=tiger+barb");
+ GURL tiger_barb("https://www.google.com/#?q=tiger+barb");
// Set up by opening a new tab and getting web contents
EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
@@ -275,12 +275,13 @@ TEST_F(PrintPreviewDialogControllerUnitTest, CloseDialogOnNavigation) {
// Try to simulate Gmail navigation: Navigate to an existing page (via
// Forward) but modify the navigation type while pending to look like an
// address bar + typed transition (like Gmail auto navigation)
- content::NavigationController& nav_controller = web_contents->GetController();
- nav_controller.GoForward();
- nav_controller.GetPendingEntry()->SetTransitionType(ui::PageTransitionFromInt(
- ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR));
- CommitPendingLoad(&nav_controller);
-
+ std::unique_ptr<content::NavigationSimulator> forward_nav =
+ content::NavigationSimulator::CreateHistoryNavigation(1, web_contents);
+ forward_nav->Start();
+ web_contents->GetController().GetPendingEntry()->SetTransitionType(
+ ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED |
+ ui::PAGE_TRANSITION_FROM_ADDRESS_BAR));
+ forward_nav->Commit();
// Navigation successful
EXPECT_EQ(tiger_barb, web_contents->GetLastCommittedURL());
diff --git a/chromium/chrome/browser/printing/print_preview_message_handler.cc b/chromium/chrome/browser/printing/print_preview_message_handler.cc
index 124a5736168..2c7559cf28d 100644
--- a/chromium/chrome/browser/printing/print_preview_message_handler.cc
+++ b/chromium/chrome/browser/printing/print_preview_message_handler.cc
@@ -14,7 +14,6 @@
#include "base/memory/read_only_shared_memory_region.h"
#include "base/memory/ref_counted.h"
#include "base/memory/ref_counted_memory.h"
-#include "base/task/post_task.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/pdf_nup_converter_client.h"
#include "chrome/browser/printing/print_job_manager.h"
@@ -24,6 +23,7 @@
#include "chrome/browser/ui/webui/print_preview/print_preview_ui.h"
#include "components/printing/browser/print_composite_client.h"
#include "components/printing/browser/print_manager_utils.h"
+#include "components/printing/common/print.mojom.h"
#include "components/printing/common/print_messages.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
@@ -32,6 +32,7 @@
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
+#include "printing/mojom/print.mojom.h"
#include "printing/nup_parameters.h"
#include "printing/page_setup.h"
#include "printing/print_job_constants.h"
@@ -54,8 +55,8 @@ void StopWorker(int document_cookie) {
std::unique_ptr<PrinterQuery> printer_query =
queue->PopPrinterQuery(document_cookie);
if (printer_query) {
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query)));
}
}
@@ -109,7 +110,7 @@ void PrintPreviewMessageHandler::OnRequestPrintPreview(
}
void PrintPreviewMessageHandler::OnDidStartPreview(
- const PrintHostMsg_DidStartPreview_Params& params,
+ const mojom::DidStartPreviewParams& params,
const PrintHostMsg_PreviewIds& ids) {
if (params.page_count <= 0 || params.pages_to_render.empty()) {
NOTREACHED();
@@ -175,7 +176,7 @@ void PrintPreviewMessageHandler::OnDidPreviewPage(
const PrintHostMsg_DidPreviewPage_Params& params,
const PrintHostMsg_PreviewIds& ids) {
int page_number = params.page_number;
- const PrintHostMsg_DidPrintContent_Params& content = params.content;
+ const mojom::DidPrintContentParams& content = params.content;
if (page_number < FIRST_PAGE_INDEX || !content.metafile_data_region.IsValid())
return;
@@ -268,7 +269,7 @@ void PrintPreviewMessageHandler::OnMetafileReadyForPrinting(
}
void PrintPreviewMessageHandler::OnDidGetDefaultPageLayout(
- const PageSizeMargins& page_layout_in_points,
+ const mojom::PageSizeMargins& page_layout_in_points,
const gfx::Rect& printable_area_in_points,
bool has_custom_page_size_style,
const PrintHostMsg_PreviewIds& ids) {
@@ -281,29 +282,6 @@ void PrintPreviewMessageHandler::OnDidGetDefaultPageLayout(
has_custom_page_size_style, ids.request_id);
}
-void PrintPreviewMessageHandler::OnPrintPreviewCancelled(
- int document_cookie,
- const PrintHostMsg_PreviewIds& ids) {
- // Always need to stop the worker.
- StopWorker(document_cookie);
-
- // Notify UI
- PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(ids.ui_id);
- if (!print_preview_ui)
- return;
- print_preview_ui->OnPrintPreviewCancelled(ids.request_id);
-}
-
-void PrintPreviewMessageHandler::OnInvalidPrinterSettings(
- int document_cookie,
- const PrintHostMsg_PreviewIds& ids) {
- StopWorker(document_cookie);
- PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(ids.ui_id);
- if (!print_preview_ui)
- return;
- print_preview_ui->OnInvalidPrinterSettings(ids.request_id);
-}
-
void PrintPreviewMessageHandler::NotifyUIPreviewPageReady(
PrintPreviewUI* print_preview_ui,
int page_number,
@@ -342,6 +320,10 @@ void PrintPreviewMessageHandler::OnCompositePdfPageDone(
mojom::PrintCompositor::Status status,
base::ReadOnlySharedMemoryRegion region) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ if (PrintPreviewUI::ShouldCancelRequest(ids))
+ return;
+
PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(ids.ui_id);
if (status != mojom::PrintCompositor::Status::kSuccess) {
DLOG(ERROR) << "Compositing pdf failed with error " << status;
@@ -420,6 +402,10 @@ void PrintPreviewMessageHandler::OnCompositeToPdfDone(
mojom::PrintCompositor::Status status,
base::ReadOnlySharedMemoryRegion region) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ if (PrintPreviewUI::ShouldCancelRequest(ids))
+ return;
+
PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(ids.ui_id);
if (status != mojom::PrintCompositor::Status::kSuccess) {
DLOG(ERROR) << "Completion of document to pdf failed with error " << status;
@@ -460,6 +446,10 @@ void PrintPreviewMessageHandler::OnPrepareForDocumentToPdfDone(
const PrintHostMsg_PreviewIds& ids,
mojom::PrintCompositor::Status status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+ if (PrintPreviewUI::ShouldCancelRequest(ids))
+ return;
+
if (status != mojom::PrintCompositor::Status::kSuccess) {
PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(ids.ui_id);
if (print_preview_ui)
@@ -511,10 +501,6 @@ bool PrintPreviewMessageHandler::OnMessageReceived(
OnDidPrepareForDocumentToPdf)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetDefaultPageLayout,
OnDidGetDefaultPageLayout)
- IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewCancelled,
- OnPrintPreviewCancelled)
- IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewInvalidPrinterSettings,
- OnInvalidPrinterSettings)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
diff --git a/chromium/chrome/browser/printing/print_preview_message_handler.h b/chromium/chrome/browser/printing/print_preview_message_handler.h
index d1354decb3d..a2a0727e760 100644
--- a/chromium/chrome/browser/printing/print_preview_message_handler.h
+++ b/chromium/chrome/browser/printing/print_preview_message_handler.h
@@ -9,13 +9,14 @@
#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/printing/common/print.mojom-forward.h"
#include "components/services/print_compositor/public/mojom/print_compositor.mojom.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
+#include "printing/mojom/print.mojom-forward.h"
struct PrintHostMsg_DidPreviewDocument_Params;
struct PrintHostMsg_DidPreviewPage_Params;
-struct PrintHostMsg_DidStartPreview_Params;
struct PrintHostMsg_PreviewIds;
struct PrintHostMsg_RequestPrintPreview_Params;
@@ -35,7 +36,6 @@ class Rect;
namespace printing {
class PrintPreviewUI;
-struct PageSizeMargins;
// Manages the print preview handling for a WebContents.
class PrintPreviewMessageHandler
@@ -65,11 +65,12 @@ class PrintPreviewMessageHandler
void OnRequestPrintPreview(
content::RenderFrameHost* render_frame_host,
const PrintHostMsg_RequestPrintPreview_Params& params);
- void OnDidGetDefaultPageLayout(const PageSizeMargins& page_layout_in_points,
- const gfx::Rect& printable_area_in_points,
- bool has_custom_page_size_style,
- const PrintHostMsg_PreviewIds& ids);
- void OnDidStartPreview(const PrintHostMsg_DidStartPreview_Params& params,
+ void OnDidGetDefaultPageLayout(
+ const mojom::PageSizeMargins& page_layout_in_points,
+ const gfx::Rect& printable_area_in_points,
+ bool has_custom_page_size_style,
+ const PrintHostMsg_PreviewIds& ids);
+ void OnDidStartPreview(const mojom::DidStartPreviewParams& params,
const PrintHostMsg_PreviewIds& ids);
void OnDidPrepareForDocumentToPdf(int document_cookie,
const PrintHostMsg_PreviewIds& ids);
@@ -80,10 +81,6 @@ class PrintPreviewMessageHandler
content::RenderFrameHost* render_frame_host,
const PrintHostMsg_DidPreviewDocument_Params& params,
const PrintHostMsg_PreviewIds& ids);
- void OnPrintPreviewCancelled(int document_cookie,
- const PrintHostMsg_PreviewIds& ids);
- void OnInvalidPrinterSettings(int document_cookie,
- const PrintHostMsg_PreviewIds& ids);
void NotifyUIPreviewPageReady(
PrintPreviewUI* print_preview_ui,
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 84ff5278fb3..a5ac123c871 100644
--- a/chromium/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc
+++ b/chromium/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc
@@ -39,6 +39,7 @@
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
+#include "components/printing/common/print.mojom.h"
#include "components/printing/common/print_messages.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui_message_handler.h"
@@ -269,7 +270,7 @@ class PrintPreviewObserver : public WebContentsObserver {
// Called when the observer gets the IPC message with the preview document's
// properties.
- void OnDidStartPreview(const PrintHostMsg_DidStartPreview_Params& params,
+ void OnDidStartPreview(const mojom::DidStartPreviewParams& params,
const PrintHostMsg_PreviewIds& ids) {
WebContents* web_contents = GetDialog();
ASSERT_TRUE(web_contents);
diff --git a/chromium/chrome/browser/printing/print_view_manager.cc b/chromium/chrome/browser/printing/print_view_manager.cc
index d31f5ca49b4..7c28f751858 100644
--- a/chromium/chrome/browser/printing/print_view_manager.cc
+++ b/chromium/chrome/browser/printing/print_view_manager.cc
@@ -89,8 +89,8 @@ bool PrintViewManager::PrintForSystemDialogNow(
SetPrintingRFH(print_preview_rfh_);
- // Don't print / print preview interstitials or crashed tabs.
- if (IsInterstitialOrCrashed())
+ // Don't print / print preview crashed tabs.
+ if (IsCrashed())
return false;
GetPrintRenderFrame(print_preview_rfh_)->PrintForSystemDialog();
@@ -203,8 +203,8 @@ bool PrintViewManager::PrintPreview(
if (print_preview_state_ != NOT_PREVIEWING)
return false;
- // Don't print / print preview interstitials or crashed tabs.
- if (IsInterstitialOrCrashed())
+ // Don't print / print preview crashed tabs.
+ if (IsCrashed())
return false;
GetPrintRenderFrame(rfh)->InitiatePrintPreview(std::move(print_renderer),
diff --git a/chromium/chrome/browser/printing/print_view_manager_base.cc b/chromium/chrome/browser/printing/print_view_manager_base.cc
index a058d93622f..8a743d0dd74 100644
--- a/chromium/chrome/browser/printing/print_view_manager_base.cc
+++ b/chromium/chrome/browser/printing/print_view_manager_base.cc
@@ -17,7 +17,6 @@
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
@@ -36,6 +35,7 @@
#include "components/prefs/pref_service.h"
#include "components/printing/browser/print_composite_client.h"
#include "components/printing/browser/print_manager_utils.h"
+#include "components/printing/common/print.mojom.h"
#include "components/printing/common/print_messages.h"
#include "components/services/print_compositor/public/cpp/print_service_mojo_types.h"
#include "content/public/browser/browser_task_traits.h"
@@ -85,8 +85,8 @@ void OnPrintSettingsDoneWrapper(PrintSettingsCallback settings_callback,
std::unique_ptr<PrinterQuery> query) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(std::move(settings_callback), std::move(query)));
}
@@ -132,8 +132,8 @@ PrintViewManagerBase::~PrintViewManagerBase() {
bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) {
DisconnectFromCurrentPrintJob();
- // Don't print / print preview interstitials or crashed tabs.
- if (IsInterstitialOrCrashed())
+ // Don't print / print preview crashed tabs.
+ if (IsCrashed())
return false;
SetPrintingRFH(rfh);
@@ -153,8 +153,8 @@ void PrintViewManagerBase::PrintForPrintPreview(
weak_ptr_factory_.GetWeakPtr(), print_data,
job_settings.FindIntKey(kSettingPreviewPageCount).value(),
std::move(callback));
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(CreateQueryWithSettings, std::move(job_settings),
rfh->GetProcess()->GetID(), rfh->GetRoutingID(), queue_,
std::move(settings_callback)));
@@ -200,8 +200,8 @@ void PrintViewManagerBase::OnPrintSettingsDone(
if (printer_query->last_status() == PrintingContext::CANCEL) {
queue_->QueuePrinterQuery(std::move(printer_query));
#if defined(OS_WIN)
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&PrintViewManagerBase::SystemDialogCancelled,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&PrintViewManagerBase::SystemDialogCancelled,
weak_ptr_factory_.GetWeakPtr()));
#endif
std::move(callback).Run(base::Value());
@@ -209,8 +209,8 @@ void PrintViewManagerBase::OnPrintSettingsDone(
}
if (!printer_query->cookie() || !printer_query->settings().dpi()) {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query)));
std::move(callback).Run(base::Value("Update settings failed"));
return;
@@ -220,8 +220,8 @@ void PrintViewManagerBase::OnPrintSettingsDone(
// OnDidGetPrintedPagesCount().
int cookie = printer_query->cookie();
queue_->QueuePrinterQuery(std::move(printer_query));
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&PrintViewManagerBase::StartLocalPrintJob,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&PrintViewManagerBase::StartLocalPrintJob,
weak_ptr_factory_.GetWeakPtr(), print_data,
page_count, cookie, std::move(callback)));
}
@@ -323,7 +323,7 @@ void PrintViewManagerBase::OnDidPrintDocument(
if (!PrintJobHasDocument(params.document_cookie))
return;
- const PrintHostMsg_DidPrintContent_Params& content = params.content;
+ const mojom::DidPrintContentParams& content = params.content;
if (!content.metafile_data_region.IsValid()) {
NOTREACHED() << "invalid memory handle";
web_contents()->Stop();
@@ -703,16 +703,15 @@ bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) {
return true;
}
-bool PrintViewManagerBase::IsInterstitialOrCrashed() {
- return web_contents()->ShowingInterstitialPage() ||
- web_contents()->IsCrashed();
+bool PrintViewManagerBase::IsCrashed() {
+ return web_contents()->IsCrashed();
}
bool PrintViewManagerBase::PrintNowInternal(
content::RenderFrameHost* rfh,
std::unique_ptr<IPC::Message> message) {
- // Don't print / print preview interstitials or crashed tabs.
- if (IsInterstitialOrCrashed())
+ // Don't print / print preview crashed tabs.
+ if (IsCrashed())
return false;
return rfh->Send(message.release());
}
@@ -737,8 +736,8 @@ void PrintViewManagerBase::ReleasePrinterQuery() {
std::unique_ptr<PrinterQuery> printer_query = queue_->PopPrinterQuery(cookie);
if (!printer_query)
return;
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query)));
}
diff --git a/chromium/chrome/browser/printing/print_view_manager_base.h b/chromium/chrome/browser/printing/print_view_manager_base.h
index 3d434244927..94b65e85561 100644
--- a/chromium/chrome/browser/printing/print_view_manager_base.h
+++ b/chromium/chrome/browser/printing/print_view_manager_base.h
@@ -73,9 +73,8 @@ class PrintViewManagerBase : public content::NotificationObserver,
protected:
explicit PrintViewManagerBase(content::WebContents* web_contents);
- // Helper method for checking whether the WebContents is showing an
- // interstitial page or is crashed.
- bool IsInterstitialOrCrashed();
+ // Helper method for checking whether the WebContents is crashed.
+ bool IsCrashed();
// Helper method for Print*Now().
bool PrintNowInternal(content::RenderFrameHost* rfh,
diff --git a/chromium/chrome/browser/printing/print_view_manager_unittest.cc b/chromium/chrome/browser/printing/print_view_manager_unittest.cc
index 81d6a2c91a8..1040cf633da 100644
--- a/chromium/chrome/browser/printing/print_view_manager_unittest.cc
+++ b/chromium/chrome/browser/printing/print_view_manager_unittest.cc
@@ -42,8 +42,8 @@ class TestPrintViewManager : public PrintViewManagerBase {
// Mostly copied from PrintViewManager::PrintPreviewNow(). We can't override
// PrintViewManager since it is a user data class.
bool PrintPreviewNow(content::RenderFrameHost* rfh, bool has_selection) {
- // Don't print / print preview interstitials or crashed tabs.
- if (IsInterstitialOrCrashed())
+ // Don't print / print preview crashed tabs.
+ if (IsCrashed())
return false;
mojo::AssociatedRemote<mojom::PrintRenderFrame> print_render_frame;
diff --git a/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc b/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc
index 07d9dee216a..8515ec8a5ee 100644
--- a/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc
+++ b/chromium/chrome/browser/printing/printer_manager_dialog_linux.cc
@@ -9,6 +9,7 @@
#include "base/bind.h"
#include "base/environment.h"
#include "base/files/file_util.h"
+#include "base/logging.h"
#include "base/nix/xdg_util.h"
#include "base/process/kill.h"
#include "base/process/launch.h"
diff --git a/chromium/chrome/browser/printing/printer_query.cc b/chromium/chrome/browser/printing/printer_query.cc
index db7ee262b81..689a59232c6 100644
--- a/chromium/chrome/browser/printing/printer_query.cc
+++ b/chromium/chrome/browser/printing/printer_query.cc
@@ -58,8 +58,8 @@ void PrinterQuery::PostSettingsDoneToIO(
std::unique_ptr<PrintSettings> new_settings,
PrintingContext::Result result) {
// |this| is owned by |callback|, so |base::Unretained()| is safe.
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PrinterQuery::GetSettingsDone, base::Unretained(this),
std::move(callback), std::move(new_settings), result));
}
diff --git a/chromium/chrome/browser/printing/printing_message_filter.cc b/chromium/chrome/browser/printing/printing_message_filter.cc
index d105aae9c8b..fb5d48349ee 100644
--- a/chromium/chrome/browser/printing/printing_message_filter.cc
+++ b/chromium/chrome/browser/printing/printing_message_filter.cc
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/memory/singleton.h"
-#include "base/task/post_task.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
@@ -102,8 +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_.MoveToSequence(
- base::CreateSingleThreadTaskRunner({BrowserThread::IO}));
+ is_printing_enabled_.MoveToSequence(content::GetIOThreadTaskRunner({}));
}
PrintingMessageFilter::~PrintingMessageFilter() {
@@ -278,8 +276,8 @@ void PrintingMessageFilter::OnUpdatePrintSettingsReply(
#if defined(OS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW)
if (canceled) {
int routing_id = reply_msg->routing_id();
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PrintingMessageFilter::NotifySystemDialogCancelled,
this, routing_id));
}
diff --git a/chromium/chrome/browser/printing/printing_service.cc b/chromium/chrome/browser/printing/printing_service.cc
index 1c9e0853250..2b73b110049 100644
--- a/chromium/chrome/browser/printing/printing_service.cc
+++ b/chromium/chrome/browser/printing/printing_service.cc
@@ -5,7 +5,7 @@
#include "chrome/browser/printing/printing_service.h"
#include "base/no_destructor.h"
-#include "build/build_config.h"
+#include "chrome/browser/service_sandbox_type.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/service_process_host.h"
@@ -17,9 +17,6 @@ const mojo::Remote<printing::mojom::PrintingService>& GetPrintingService() {
remote->BindNewPipeAndPassReceiver(),
content::ServiceProcessHost::Options()
.WithDisplayName(IDS_UTILITY_PROCESS_PRINTING_SERVICE_NAME)
-#if defined(OS_WIN)
- .WithSandboxType(service_manager::SandboxType::kPdfConversion)
-#endif
.Pass());
// Ensure that if the interface is ever disconnected (e.g. the service
diff --git a/chromium/chrome/browser/privacy_budget/BUILD.gn b/chromium/chrome/browser/privacy_budget/BUILD.gn
new file mode 100644
index 00000000000..add31cacf06
--- /dev/null
+++ b/chromium/chrome/browser/privacy_budget/BUILD.gn
@@ -0,0 +1,41 @@
+# Copyright 2020 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+source_set("privacy_budget") {
+ sources = [
+ "identifiability_study_state.cc",
+ "identifiability_study_state.h",
+ "privacy_budget_prefs.cc",
+ "privacy_budget_prefs.h",
+ "privacy_budget_ukm_entry_filter.cc",
+ "privacy_budget_ukm_entry_filter.h",
+ ]
+
+ deps = [
+ "//base",
+ "//chrome/common/privacy_budget",
+ "//components/prefs",
+ "//components/ukm",
+ "//services/metrics/public/cpp:metrics_cpp",
+ "//services/metrics/public/cpp:ukm_builders",
+ "//services/metrics/public/mojom",
+ "//third_party/blink/public/common/privacy_budget",
+ ]
+}
+
+source_set("unit_tests") {
+ testonly = true
+
+ sources = [
+ "identifiability_study_state_unittest.cc",
+ "privacy_budget_ukm_entry_filter_unittest.cc",
+ ]
+
+ deps = [
+ ":privacy_budget",
+ "//chrome/common/privacy_budget:test_support",
+ "//chrome/test:test_support",
+ "//testing/gtest",
+ ]
+}
diff --git a/chromium/chrome/browser/renderer_host/chrome_extension_message_filter.cc b/chromium/chrome/browser/renderer_host/chrome_extension_message_filter.cc
index 228ad3adfbf..49ee403c03d 100644
--- a/chromium/chrome/browser/renderer_host/chrome_extension_message_filter.cc
+++ b/chromium/chrome/browser/renderer_host/chrome_extension_message_filter.cc
@@ -14,7 +14,6 @@
#include "base/notreached.h"
#include "base/stl_util.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/activity_log/activity_action_constants.h"
@@ -111,7 +110,7 @@ void ChromeExtensionMessageFilter::OnDestruct() const {
if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
delete this;
} else {
- base::DeleteSoon(FROM_HERE, {BrowserThread::UI}, this);
+ content::GetUIThreadTaskRunner({})->DeleteSoon(FROM_HERE, this);
}
}
diff --git a/chromium/chrome/browser/renderer_host/chrome_navigation_ui_data.h b/chromium/chrome/browser/renderer_host/chrome_navigation_ui_data.h
index f7c2f9f72ba..cd99296b042 100644
--- a/chromium/chrome/browser/renderer_host/chrome_navigation_ui_data.h
+++ b/chromium/chrome/browser/renderer_host/chrome_navigation_ui_data.h
@@ -8,9 +8,9 @@
#include <memory>
#include "base/macros.h"
-#include "chrome/common/prerender_types.h"
#include "components/offline_pages/buildflags/buildflags.h"
#include "components/offline_pages/core/request_header/offline_page_navigation_ui_data.h"
+#include "components/prerender/common/prerender_types.mojom.h"
#include "content/public/browser/navigation_ui_data.h"
#include "extensions/browser/extension_navigation_ui_data.h"
#include "extensions/buildflags/buildflags.h"
@@ -60,7 +60,9 @@ class ChromeNavigationUIData : public content::NavigationUIData {
}
#endif
WindowOpenDisposition window_open_disposition() const { return disposition_; }
- prerender::PrerenderMode prerender_mode() const { return prerender_mode_; }
+ prerender::mojom::PrerenderMode prerender_mode() const {
+ return prerender_mode_;
+ }
const std::string& prerender_histogram_prefix() {
return prerender_histogram_prefix_;
}
@@ -78,7 +80,8 @@ class ChromeNavigationUIData : public content::NavigationUIData {
#endif
WindowOpenDisposition disposition_;
- prerender::PrerenderMode prerender_mode_ = prerender::NO_PRERENDER;
+ prerender::mojom::PrerenderMode prerender_mode_ =
+ prerender::mojom::PrerenderMode::kNoPrerender;
std::string prerender_histogram_prefix_;
DISALLOW_COPY_AND_ASSIGN(ChromeNavigationUIData);
diff --git a/chromium/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_browsertest.mm b/chromium/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_browsertest.mm
index 6a030f43974..65482d03b19 100644
--- a/chromium/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_browsertest.mm
+++ b/chromium/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_browsertest.mm
@@ -798,8 +798,10 @@ IN_PROC_BROWSER_TEST_F(ChromeRenderWidgetHostViewMacHistorySwiperTest,
ExpectUrlAndOffset(url1_, 0);
}
-IN_PROC_BROWSER_TEST_F(ChromeRenderWidgetHostViewMacHistorySwiperTest,
- InnerScrollersOverscrollBehaviorPreventsNavigation) {
+// TODO(crbug.com/1070405): flaky.
+IN_PROC_BROWSER_TEST_F(
+ ChromeRenderWidgetHostViewMacHistorySwiperTest,
+ DISABLED_InnerScrollersOverscrollBehaviorPreventsNavigation) {
if (!IsHistorySwipingSupported())
return;
diff --git a/chromium/chrome/browser/renderer_host/pepper/device_id_fetcher.cc b/chromium/chrome/browser/renderer_host/pepper/device_id_fetcher.cc
index 93799f8adbf..892dbd660ea 100644
--- a/chromium/chrome/browser/renderer_host/pepper/device_id_fetcher.cc
+++ b/chromium/chrome/browser/renderer_host/pepper/device_id_fetcher.cc
@@ -8,7 +8,6 @@
#include "base/files/file_util.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
@@ -77,8 +76,8 @@ bool DeviceIDFetcher::Start(const IDCallback& callback) {
in_progress_ = true;
callback_ = callback;
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&DeviceIDFetcher::CheckPrefsOnUIThread, this));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&DeviceIDFetcher::CheckPrefsOnUIThread, this));
return true;
}
@@ -191,8 +190,8 @@ void DeviceIDFetcher::LegacyComputeAsync(const base::FilePath& profile_path,
}
// If we didn't find an ID, get the machine ID and call the new code path to
// generate an ID.
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&GetMachineIDAsync,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&GetMachineIDAsync,
base::Bind(&DeviceIDFetcher::ComputeOnUIThread,
this, salt)));
}
@@ -200,8 +199,8 @@ void DeviceIDFetcher::LegacyComputeAsync(const base::FilePath& profile_path,
void DeviceIDFetcher::RunCallbackOnIOThread(const std::string& id,
int32_t result) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
- base::PostTask(FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&DeviceIDFetcher::RunCallbackOnIOThread, this,
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&DeviceIDFetcher::RunCallbackOnIOThread, this,
id, result));
return;
}
diff --git a/chromium/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm b/chromium/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm
index 41f0611dbc2..e64fbfcfb06 100644
--- a/chromium/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm
+++ b/chromium/chrome/browser/renderer_host/pepper/monitor_finder_mac.mm
@@ -7,7 +7,6 @@
#import <Cocoa/Cocoa.h>
#include "base/bind.h"
-#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
@@ -30,8 +29,8 @@ int64_t MonitorFinder::GetMonitor() {
request_sent_ = true;
}
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&MonitorFinder::FetchMonitorFromWidget, this));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&MonitorFinder::FetchMonitorFromWidget, this));
return display_id_;
}
diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc b/chromium/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc
index d72a867594a..82fa5b7026e 100644
--- a/chromium/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc
+++ b/chromium/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc
@@ -6,7 +6,6 @@
#include <string>
-#include "base/task/post_task.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
@@ -37,7 +36,7 @@ PepperBrokerMessageFilter::~PepperBrokerMessageFilter() {}
scoped_refptr<base::SequencedTaskRunner>
PepperBrokerMessageFilter::OverrideTaskRunnerForMessage(
const IPC::Message& message) {
- return base::CreateSingleThreadTaskRunner({BrowserThread::UI});
+ return content::GetUIThreadTaskRunner({});
}
int32_t PepperBrokerMessageFilter::OnResourceMessageReceived(
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 c1fdd9dd86e..839b95e6a27 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
@@ -5,7 +5,6 @@
#include "chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h"
#include "base/bind.h"
-#include "base/task/post_task.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "chrome/browser/content_settings/cookie_settings_factory.h"
@@ -132,9 +131,8 @@ int32_t PepperFlashBrowserHost::OnGetLocalDataRestrictions(
plugin_url,
cookie_settings_);
} else {
- base::PostTaskAndReplyWithResult(
- FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&GetCookieSettings, render_process_id_),
+ content::GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult(
+ FROM_HERE, base::BindOnce(&GetCookieSettings, render_process_id_),
base::BindOnce(&PepperFlashBrowserHost::GetLocalDataRestrictions,
weak_factory_.GetWeakPtr(),
context->MakeReplyMessageContext(), document_url,
@@ -178,8 +176,8 @@ device::mojom::WakeLock* PepperFlashBrowserHost::GetWakeLock() {
return wake_lock_.get();
mojo::Remote<device::mojom::WakeLockProvider> wake_lock_provider;
- base::PostTask(
- FROM_HERE, {BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&BindWakeLockProviderOnUIThread,
wake_lock_provider.BindNewPipeAndPassReceiver()));
wake_lock_provider->GetWakeLockWithoutContext(
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 8147eb02d87..6ae4b9beee8 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
@@ -8,7 +8,6 @@
#include "base/pickle.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "build/build_config.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
@@ -23,8 +22,6 @@
#include "ppapi/proxy/resource_message_params.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
-using content::BrowserThread;
-
namespace {
const size_t kMaxClipboardWriteSize = 1000000;
@@ -106,16 +103,16 @@ PepperFlashClipboardMessageFilter::OverrideTaskRunnerForMessage(
// restrictions of various platform APIs. In general, the clipboard is not
// thread-safe, so all clipboard calls should be serviced from the UI thread.
if (msg.type() == PpapiHostMsg_FlashClipboard_WriteData::ID)
- return base::CreateSingleThreadTaskRunner({BrowserThread::UI});
+ return content::GetUIThreadTaskRunner({});
// Windows needs clipboard reads to be serviced from the IO thread because
// these are sync IPCs which can result in deadlocks with plugins if serviced
// from the UI thread. Note that Windows clipboard calls ARE thread-safe so it
// is ok for reads and writes to be serviced from different threads.
#if !defined(OS_WIN)
- return base::CreateSingleThreadTaskRunner({BrowserThread::UI});
+ return content::GetUIThreadTaskRunner({});
#else
- return base::CreateSingleThreadTaskRunner({BrowserThread::IO});
+ return content::GetIOThreadTaskRunner({});
#endif
}
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 7c8c292d6d4..7b774366e2e 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
@@ -13,7 +13,6 @@
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/notreached.h"
-#include "base/task/post_task.h"
#include "build/build_config.h"
#include "content/public/browser/browser_ppapi_host.h"
#include "content/public/browser/browser_task_traits.h"
@@ -62,8 +61,8 @@ class MonitorFinder : public base::RefCountedThreadSafe<MonitorFinder> {
// do this because we don't know how often our client is going
// to call and we can't cache the |monitor_| value.
if (InterlockedCompareExchange(&request_sent_, 1, 0) == 0) {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&MonitorFinder::FetchMonitorFromWidget, this));
}
return reinterpret_cast<int64_t>(monitor_);
diff --git a/chromium/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc b/chromium/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc
index c94e1947dc1..0a04a1e0ec5 100644
--- a/chromium/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc
+++ b/chromium/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc
@@ -7,7 +7,6 @@
#include <stddef.h>
#include "base/stl_util.h"
-#include "base/task/post_task.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
@@ -81,7 +80,7 @@ PepperIsolatedFileSystemMessageFilter::OverrideTaskRunnerForMessage(
const IPC::Message& msg) {
// In order to reach ExtensionSystem, we need to get ProfileManager first.
// ProfileManager lives in UI thread, so we need to do this in UI thread.
- return base::CreateSingleThreadTaskRunner({content::BrowserThread::UI});
+ return content::GetUIThreadTaskRunner({});
}
int32_t PepperIsolatedFileSystemMessageFilter::OnResourceMessageReceived(
diff --git a/chromium/chrome/browser/resource_coordinator/lifecycle_unit_state.mojom b/chromium/chrome/browser/resource_coordinator/lifecycle_unit_state.mojom
index 03e35133825..2beb0a6ce13 100644
--- a/chromium/chrome/browser/resource_coordinator/lifecycle_unit_state.mojom
+++ b/chromium/chrome/browser/resource_coordinator/lifecycle_unit_state.mojom
@@ -11,8 +11,8 @@ enum LifecycleUnitState {
ACTIVE = 0,
// The LifecycleUnit is currently being CPU throttled.
THROTTLED = 1,
- // The LifecycleUnit is currently transitioning to a FROZEN state.
- PENDING_FREEZE = 2,
+ // Deprecated: The LifecycleUnit is currently transitioning to a FROZEN state.
+ // PENDING_FREEZE = 2,
// The LifecycleUnit is frozen.
FROZEN = 3,
// Deprecated: The LifecycleUnit is currently transitioning to a DISCARDED
@@ -20,9 +20,9 @@ enum LifecycleUnitState {
// PENDING_DISCARD = 4,
// The LifecycleUnit is discarded, and is consuming no system resources.
DISCARDED = 5,
- // The LifecycleUnit is currently transitioning from the FROZEN state to the
- // ACTIVE state.
- PENDING_UNFREEZE = 6,
+ // Deprecated: The LifecycleUnit is currently transitioning from the FROZEN
+ // state to the ACTIVE state.
+ // PENDING_UNFREEZE = 6,
};
// Indicates the loading state of a lifecycle unit, orthogonal to the basic
diff --git a/chromium/chrome/browser/resources/BUILD.gn b/chromium/chrome/browser/resources/BUILD.gn
index c5f813e5c89..0f428df836e 100644
--- a/chromium/chrome/browser/resources/BUILD.gn
+++ b/chromium/chrome/browser/resources/BUILD.gn
@@ -6,12 +6,13 @@ import("//chrome/common/features.gni")
import("//chrome/test/base/js2gtest.gni")
import("//chrome/test/include_js_tests.gni")
import("//components/nacl/features.gni")
+import("//third_party/closure_compiler/compile_js.gni")
import("//tools/grit/grit_rule.gni")
import("//tools/grit/repack.gni")
assert(!is_ios, "Chromium/iOS shouldn't use anything in //chrome")
-if (closure_compile) {
+if (enable_js_type_check) {
group("closure_compile") {
deps = [
"components:closure_compile",
@@ -34,6 +35,8 @@ if (closure_compile) {
"local_state:closure_compile",
"management:closure_compile",
"media_router:closure_compile",
+ "nearby_internals:closure_compile",
+ "nearby_share:closure_compile",
"new_tab_page:closure_compile",
"ntp4:closure_compile",
"omnibox:closure_compile",
@@ -45,6 +48,7 @@ if (closure_compile) {
"signin:closure_compile",
"usb_internals:closure_compile",
"user_manager:closure_compile",
+ "web_app_internals:closure_compile",
"welcome:closure_compile",
]
}
@@ -67,6 +71,7 @@ if (closure_compile) {
deps += [
"explore_sites_internals:closure_compile",
"feed_internals:closure_compile",
+ "internals/query_tiles:closure_compile",
"offline_pages:closure_compile",
"snippets_internals:closure_compile",
"webapks:closure_compile",
@@ -121,7 +126,7 @@ if (!is_android) {
"root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
]
- deps = [ "//chrome/browser/resources/pdf/elements:web_components" ]
+ deps = [ "//chrome/browser/resources/pdf:web_components" ]
defines = chrome_grit_defines
if (enable_hangout_services_extension) {
@@ -192,6 +197,46 @@ if (!is_android) {
output_dir = "$root_gen_dir/chrome"
}
+ grit("nearby_internals_resources") {
+ source = "nearby_internals/nearby_internals_resources.grd"
+
+ grit_flags = [
+ "-E",
+ "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
+ ]
+
+ deps = [ "//chrome/browser/resources/nearby_internals:web_components" ]
+
+ defines = chrome_grit_defines
+ outputs = [
+ "grit/nearby_internals_resources.h",
+ "grit/nearby_internals_resources_map.cc",
+ "grit/nearby_internals_resources_map.h",
+ "nearby_internals_resources.pak",
+ ]
+ output_dir = "$root_gen_dir/chrome"
+ }
+
+ grit("nearby_share_dialog_resources") {
+ source = "nearby_share/nearby_share_dialog_resources.grd"
+
+ grit_flags = [
+ "-E",
+ "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
+ ]
+
+ deps = [ "//chrome/browser/resources/nearby_share:web_components" ]
+
+ defines = chrome_grit_defines
+ outputs = [
+ "grit/nearby_share_dialog_resources.h",
+ "grit/nearby_share_dialog_resources_map.cc",
+ "grit/nearby_share_dialog_resources_map.h",
+ "nearby_share_dialog_resources.pak",
+ ]
+ output_dir = "$root_gen_dir/chrome"
+ }
+
grit("new_tab_page_resources") {
if (optimize_webui) {
source = "new_tab_page/new_tab_page_resources_vulcanized.grd"
@@ -289,11 +334,16 @@ if (is_chromeos) {
enable_input_discovery_for_gn_analyze = false
source = "settings/os_settings_resources_vulcanized.grd"
- deps += [ "//chrome/browser/resources/settings/chromeos:build" ]
+ deps += [
+ "//chrome/browser/resources/settings/chromeos:build",
+ "//chrome/browser/resources/settings/chromeos:build_polymer3",
+ ]
} else {
source = "settings/os_settings_resources.grd"
- deps +=
- [ "//chrome/browser/resources/settings/chromeos:polymer3_elements" ]
+ deps += [
+ "//chrome/browser/resources/settings/chromeos:polymer3_elements",
+ "//chrome/browser/ui/webui/settings/chromeos/search:mojo_bindings_js",
+ ]
}
defines = chrome_grit_defines
@@ -305,6 +355,34 @@ if (is_chromeos) {
]
output_dir = "$root_gen_dir/chrome"
}
+
+ grit("bluetooth_pairing_dialog_resources") {
+ grit_flags = [
+ "-E",
+ "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
+ ]
+
+ if (optimize_webui) {
+ source = "chromeos/bluetooth_pairing_dialog/bluetooth_pairing_dialog_resources_vulcanized.grd"
+
+ deps = [
+ "//chrome/browser/resources/chromeos/bluetooth_pairing_dialog:build",
+ ]
+ } else {
+ source = "chromeos/bluetooth_pairing_dialog/bluetooth_pairing_dialog_resources.grd"
+
+ deps = [ "//chrome/browser/resources/chromeos/bluetooth_pairing_dialog:web_components" ]
+ }
+
+ defines = chrome_grit_defines
+ outputs = [
+ "grit/bluetooth_pairing_dialog_resources.h",
+ "grit/bluetooth_pairing_dialog_resources_map.cc",
+ "grit/bluetooth_pairing_dialog_resources_map.h",
+ "bluetooth_pairing_dialog_resources.pak",
+ ]
+ output_dir = "$root_gen_dir/chrome"
+ }
}
if (!is_android && !is_chromeos) {
@@ -330,6 +408,7 @@ if (!is_android && !is_chromeos) {
grit("profile_picker_resources") {
source = "signin/profile_picker/profile_picker_resources.grd"
+ deps = [ "//chrome/browser/resources/signin/profile_picker:web_components" ]
grit_flags = [
"-E",
"root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
@@ -393,16 +472,10 @@ if (enable_print_preview) {
if (optimize_webui) {
source = "print_preview/print_preview_resources_vulcanized.grd"
- deps = [
- "//chrome/browser/resources/pdf/elements:web_components",
- "//chrome/browser/resources/print_preview:build",
- ]
+ deps = [ "//chrome/browser/resources/print_preview:build" ]
} else {
source = "print_preview/print_preview_resources.grd"
- deps = [
- "//chrome/browser/resources/pdf/elements:web_components",
- "//chrome/browser/resources/print_preview/ui:web_components",
- ]
+ deps = [ "//chrome/browser/resources/print_preview/ui:web_components" ]
}
defines = chrome_grit_defines
@@ -414,6 +487,25 @@ if (enable_print_preview) {
]
output_dir = "$root_gen_dir/chrome"
}
+
+ grit("print_preview_pdf_resources") {
+ grit_flags = [
+ "-E",
+ "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
+ ]
+
+ source = "print_preview/print_preview_pdf_resources.grd"
+ deps = [ "//chrome/browser/resources/pdf:web_components" ]
+
+ defines = chrome_grit_defines
+ outputs = [
+ "grit/print_preview_pdf_resources.h",
+ "grit/print_preview_pdf_resources_map.cc",
+ "grit/print_preview_pdf_resources_map.h",
+ "print_preview_pdf_resources.pak",
+ ]
+ output_dir = "$root_gen_dir/chrome"
+ }
}
if (enable_webui_tab_strip) {
diff --git a/chromium/chrome/browser/resources/accessibility/accessibility.html b/chromium/chrome/browser/resources/accessibility/accessibility.html
index 1d9b645429c..6e77f7bbfe5 100644
--- a/chromium/chrome/browser/resources/accessibility/accessibility.html
+++ b/chromium/chrome/browser/resources/accessibility/accessibility.html
@@ -111,23 +111,6 @@ found in the LICENSE file.
<div id="label_images_secondary" class="secondary">
Automatically labels images.
</div>
-
- <h2>Command line options:</h2>
- <p>
- Accessibility features in Chrome are off by default and enabled
- automatically on-demand. Changes to these modes only take effect
- until the next time Chrome is restarted.
- </p>
- <p>
- To force accessibility to be enabled at launch, run Chrome with this
- flag:
- <pre>--force-renderer-accessibility</pre>
- </p>
- <p>
- To disable accessibility, run Chrome with this flag:
- <pre>--disable-renderer-accessibility</pre>
- </p>
-
</div>
<div class="column">
<h2>Accessibility tree viewing options:</h2>
@@ -181,14 +164,36 @@ found in the LICENSE file.
<div id="deny_secondary" class="secondary">
Exclude these attributes.
</div>
+ </div>
+ </div>
+ <div class="columns">
+ <div class="column">
+ <h2>Command line options:</h2>
+ <p>
+ Accessibility features in Chrome are off by default and enabled
+ automatically on-demand. Changes to these modes only take effect
+ until the next time Chrome is restarted.
+ </p>
+ <p>
+ To force accessibility to be enabled at launch, run Chrome with this
+ flag:
+ <pre>--force-renderer-accessibility</pre>
+ </p>
+ <p>
+ To disable accessibility, run Chrome with this flag:
+ <pre>--disable-renderer-accessibility</pre>
+ </p>
</div>
</div>
<h2>Chrome Native UI:</h2>
<div id="browsers" class="list">
- Set a delay, in milliseconds, before getting the native accessibility tree:
- <input type="number" value="0" id="native_ui_delay"> ms
+ <label for="native-ui-delay">
+ Set a delay, in milliseconds, before getting the native accessibility
+ tree:
+ </label>
+ <input id="native-ui-delay" type="number" value="0"> ms
</div>
<h2>Pages:</h2>
diff --git a/chromium/chrome/browser/resources/accessibility/accessibility.js b/chromium/chrome/browser/resources/accessibility/accessibility.js
index b6ac8513857..d0b0b7f9b92 100644
--- a/chromium/chrome/browser/resources/accessibility/accessibility.js
+++ b/chromium/chrome/browser/resources/accessibility/accessibility.js
@@ -6,7 +6,7 @@ cr.define('accessibility', function() {
'use strict';
// Note: keep these values in sync with the values in
- // content/common/accessibility_mode_enums.h
+ // ui/accessibility/ax_mode.h
const AXMode = {
kNativeAPIs: 1 << 0,
kWebContents: 1 << 1,
@@ -14,6 +14,7 @@ cr.define('accessibility', function() {
kScreenReader: 1 << 3,
kHTML: 1 << 4,
kLabelImages: 1 << 5,
+ kPDF: 1 << 6,
get kAXModeWebContentsOnly() {
return AXMode.kWebContents | AXMode.kInlineTextBoxes |
@@ -229,6 +230,7 @@ cr.define('accessibility', function() {
row.appendChild(createModeElement(AXMode.kHTML, data, 'web'));
row.appendChild(
createModeElement(AXMode.kLabelImages, data, 'labelImages'));
+ row.appendChild(createModeElement(AXMode.kPDF, data, 'pdf'));
} else {
const siteInfo = document.createElement('span');
siteInfo.appendChild(formatValue(data, 'name'));
@@ -313,6 +315,8 @@ cr.define('accessibility', function() {
return 'HTML';
case AXMode.kLabelImages:
return 'Label images';
+ case AXMode.kPDF:
+ return 'PDF';
}
return 'unknown';
}
diff --git a/chromium/chrome/browser/resources/bluetooth_internals/resources.grd b/chromium/chrome/browser/resources/bluetooth_internals/resources.grd
index 8285a4f76f3..7784acd724c 100644
--- a/chromium/chrome/browser/resources/bluetooth_internals/resources.grd
+++ b/chromium/chrome/browser/resources/bluetooth_internals/resources.grd
@@ -18,127 +18,98 @@
<includes>
<include name="IDR_BLUETOOTH_INTERNALS_ADAPTER_BROKER_JS"
file="adapter_broker.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_ADAPTER_MOJO_JS"
file="${root_gen_dir}\device\bluetooth\public\mojom\adapter.mojom-lite.js"
use_base_dir="false"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_ADAPTER_PAGE_JS"
file="adapter_page.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_DEBUG_LOG_PAGE_JS"
file="debug_log_page.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_CHARACTERISTIC_LIST_JS"
file="characteristic_list.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_CSS"
file="bluetooth_internals.css"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_DESCRIPTOR_LIST_JS"
file="descriptor_list.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_DEVICE_BROKER_JS"
file="device_broker.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_DEVICE_COLLECTION_JS"
file="device_collection.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_DEVICE_DETAILS_PAGE_JS"
file="device_details_page.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_DEVICE_MOJO_JS"
file="${root_gen_dir}\device\bluetooth\public\mojom\device.mojom-lite.js"
use_base_dir="false"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_DEVICE_TABLE_JS"
file="device_table.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_DEVICES_PAGE_JS"
file="devices_page.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_EXPANDABLE_LIST_JS"
file="expandable_list.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_HTML"
file="bluetooth_internals.html"
flattenhtml="true"
allowexternalscript="true"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_JS"
file="bluetooth_internals.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_MOJO_JS"
file="${root_gen_dir}\chrome\browser\ui\webui\bluetooth_internals\bluetooth_internals.mojom-lite.js"
use_base_dir="false"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_NODE_UTILS_HTML"
file="node_utils.html"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_NODE_UTILS_JS"
file="node_utils.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_OBJECT_FIELDSET_JS"
file="object_fieldset.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_PAGE_MANAGER_HTML"
file="page_manager.html"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_PAGE_MANAGER_JS"
file="page_manager.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_PAGE_HTML"
file="page.html"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_PAGE_JS"
file="page.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_SERVICE_LIST_JS"
file="service_list.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_SIDEBAR_JS"
file="sidebar.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_SNACKBAR_JS"
file="snackbar.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_UUID_MOJO_JS"
file="${root_gen_dir}\device\bluetooth\public\mojom\uuid.mojom-lite.js"
use_base_dir="false"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_BLUETOOTH_INTERNALS_VALUE_CONTROL_JS"
file="value_control.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/bookmarks/BUILD.gn b/chromium/chrome/browser/resources/bookmarks/BUILD.gn
index 3c241d44826..d85d90a82aa 100644
--- a/chromium/chrome/browser/resources/bookmarks/BUILD.gn
+++ b/chromium/chrome/browser/resources/bookmarks/BUILD.gn
@@ -101,7 +101,8 @@ js_library("actions") {
"//ui/webui/resources/js:cr.m",
"//ui/webui/resources/js/cr/ui:store.m",
]
- externs_list = [ "$externs_path/chrome_extensions.js" ]
+
+ externs_list = [ "$externs_path/bookmarks.js" ]
}
js_library("api_listener") {
@@ -115,7 +116,8 @@ js_library("api_listener") {
"//ui/webui/resources/js:cr.m",
"//ui/webui/resources/js/cr/ui:store.m",
]
- externs_list = [ "$externs_path/chrome_extensions.js" ]
+
+ externs_list = [ "$externs_path/bookmarks.js" ]
}
js_library("app") {
@@ -131,7 +133,10 @@ js_library("app") {
"//ui/webui/resources/js:find_shortcut_behavior.m",
"//ui/webui/resources/js:load_time_data.m",
]
- externs_list = [ "$externs_path/chrome_extensions.js" ]
+ externs_list = [
+ "$externs_path/bookmarks.js",
+ "$externs_path/metrics_private.js",
+ ]
}
js_library("browser_proxy") {
@@ -160,7 +165,10 @@ js_library("command_manager") {
"//ui/webui/resources/js:load_time_data.m",
"//ui/webui/resources/js/cr/ui:keyboard_shortcut_list.m",
]
- externs_list = [ "$externs_path/bookmark_manager_private.js" ]
+ externs_list = chrome_extension_public_externs + [
+ "$externs_path/bookmark_manager_private.js",
+ "$externs_path/bookmarks.js",
+ ]
}
js_library("constants") {
@@ -203,7 +211,7 @@ js_library("edit_dialog") {
"//ui/webui/resources/js:assert.m",
"//ui/webui/resources/js:load_time_data.m",
]
- externs_list = [ "$externs_path/chrome_extensions.js" ]
+ externs_list = [ "$externs_path/bookmarks.js" ]
}
js_library("folder_node") {
@@ -216,7 +224,6 @@ js_library("folder_node") {
":util",
"//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
]
- externs_list = [ "$externs_path/chrome_extensions.js" ]
}
js_library("item") {
@@ -233,7 +240,6 @@ js_library("item") {
"//ui/webui/resources/js:icon.m",
"//ui/webui/resources/js/cr/ui:focus_without_ink.m",
]
- externs_list = [ "$externs_path/chrome_extensions.js" ]
}
js_library("list") {
@@ -281,7 +287,6 @@ js_library("store") {
"//ui/webui/resources/js:cr.m",
"//ui/webui/resources/js/cr/ui:store.m",
]
- externs_list = [ "$externs_path/chrome_extensions.js" ]
}
js_library("store_client") {
@@ -306,18 +311,15 @@ js_library("toolbar") {
"//ui/webui/resources/js:assert.m",
"//ui/webui/resources/js:load_time_data.m",
]
- externs_list = [
- "$externs_path/bookmark_manager_private.js",
- "$externs_path/chrome_extensions.js",
- ]
}
js_library("types") {
deps = [ ":constants" ]
- externs_list = [ "$externs_path/chrome_extensions.js" ]
+ externs_list = [ "$externs_path/bookmarks.js" ]
}
js_library("util") {
deps = [ ":types" ]
- externs_list = [ "$externs_path/chrome_extensions.js" ]
+
+ externs_list = [ "$externs_path/bookmarks.js" ]
}
diff --git a/chromium/chrome/browser/resources/bookmarks/actions.js b/chromium/chrome/browser/resources/bookmarks/actions.js
index 54cfd79207a..a45cd123429 100644
--- a/chromium/chrome/browser/resources/bookmarks/actions.js
+++ b/chromium/chrome/browser/resources/bookmarks/actions.js
@@ -16,7 +16,7 @@ import {getDescendants, getDisplayedList, normalizeNode} from './util.js';
/**
* @param {string} id
- * @param {BookmarkTreeNode} treeNode
+ * @param {chrome.bookmarks.BookmarkTreeNode} treeNode
*/
export function createBookmark(id, treeNode) {
return {
diff --git a/chromium/chrome/browser/resources/bookmarks/api_listener.js b/chromium/chrome/browser/resources/bookmarks/api_listener.js
index bc6b075f315..13723908914 100644
--- a/chromium/chrome/browser/resources/bookmarks/api_listener.js
+++ b/chromium/chrome/browser/resources/bookmarks/api_listener.js
@@ -89,7 +89,7 @@ function onBookmarkChanged(id, changeInfo) {
/**
* @param {string} id
- * @param {BookmarkTreeNode} treeNode
+ * @param {chrome.bookmarks.BookmarkTreeNode} treeNode
*/
function onBookmarkCreated(id, treeNode) {
batchUIUpdates();
diff --git a/chromium/chrome/browser/resources/bookmarks/bookmarks.html b/chromium/chrome/browser/resources/bookmarks/bookmarks.html
index 5869e33b5cb..2b1fee2c9f2 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{a11yenhanced}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading">
<head>
<meta charset="utf8">
<base href="chrome://bookmarks">
diff --git a/chromium/chrome/browser/resources/bookmarks/bookmarks_resources_vulcanized.grd b/chromium/chrome/browser/resources/bookmarks/bookmarks_resources_vulcanized.grd
index b6881426042..8bca4369677 100644
--- a/chromium/chrome/browser/resources/bookmarks/bookmarks_resources_vulcanized.grd
+++ b/chromium/chrome/browser/resources/bookmarks/bookmarks_resources_vulcanized.grd
@@ -14,14 +14,12 @@
<includes>
<include name="IDR_BOOKMARKS_BOOKMARKS_HTML"
file="bookmarks.html"
- type="chrome_html"
- compress="gzip" />
+ type="chrome_html" />
<include name="IDR_BOOKMARKS_BOOKMARKS_ROLLUP_JS"
file="${root_gen_dir}\chrome\browser\resources\bookmarks\bookmarks.rollup.js"
use_base_dir="false"
preprocess="true"
- type="chrome_html"
- compress="gzip" />
+ type="chrome_html" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/bookmarks/command_manager.js b/chromium/chrome/browser/resources/bookmarks/command_manager.js
index 0326cdaa772..67e6e6a9645 100644
--- a/chromium/chrome/browser/resources/bookmarks/command_manager.js
+++ b/chromium/chrome/browser/resources/bookmarks/command_manager.js
@@ -471,8 +471,6 @@ export const CommandManager = Polymer({
if (shortcut.matchesEvent(e) && this.canExecute(command, itemIds)) {
this.handle(command, itemIds);
- this.recordCommandHistogram_(
- itemIds, 'BookmarkManager.CommandExecutedFromKeyboard', command);
e.stopPropagation();
e.preventDefault();
return true;
diff --git a/chromium/chrome/browser/resources/bookmarks/item.html b/chromium/chrome/browser/resources/bookmarks/item.html
index def6e11eb28..f65015195ed 100644
--- a/chromium/chrome/browser/resources/bookmarks/item.html
+++ b/chromium/chrome/browser/resources/bookmarks/item.html
@@ -15,10 +15,6 @@
background-color: var(--highlight-color);
}
- :host([is-selected-item_]) cr-icon-button {
- --cr-icon-button-fill-color-focus: var(--highlight-color);
- }
-
@media (prefers-color-scheme: dark) {
:host([is-selected-item_]),
:host([is-selected-item_]) .folder-icon {
diff --git a/chromium/chrome/browser/resources/bookmarks/toolbar.html b/chromium/chrome/browser/resources/bookmarks/toolbar.html
index 1f85ea820e2..764da792202 100644
--- a/chromium/chrome/browser/resources/bookmarks/toolbar.html
+++ b/chromium/chrome/browser/resources/bookmarks/toolbar.html
@@ -10,7 +10,6 @@
}
cr-icon-button {
- --cr-icon-button-fill-color-focus: var(--cr-toolbar-background-color);
justify-content: flex-end;
margin: 4px;
}
diff --git a/chromium/chrome/browser/resources/bookmarks/types.js b/chromium/chrome/browser/resources/bookmarks/types.js
index 1487eae9fb5..0031ae7c6c7 100644
--- a/chromium/chrome/browser/resources/bookmarks/types.js
+++ b/chromium/chrome/browser/resources/bookmarks/types.js
@@ -97,7 +97,7 @@ export class BookmarkElement extends HTMLElement {
export class DragData {
constructor() {
- /** @type {Array<BookmarkTreeNode>} */
+ /** @type {Array<chrome.bookmarks.BookmarkTreeNode>} */
this.elements = null;
/** @type {boolean} */
diff --git a/chromium/chrome/browser/resources/bookmarks/util.js b/chromium/chrome/browser/resources/bookmarks/util.js
index cbe9aa0c072..b0e1184e4d4 100644
--- a/chromium/chrome/browser/resources/bookmarks/util.js
+++ b/chromium/chrome/browser/resources/bookmarks/util.js
@@ -26,7 +26,7 @@ export function getDisplayedList(state) {
}
/**
- * @param {BookmarkTreeNode} treeNode
+ * @param {chrome.bookmarks.BookmarkTreeNode} treeNode
* @return {!BookmarkNode}
*/
export function normalizeNode(treeNode) {
@@ -46,7 +46,7 @@ export function normalizeNode(treeNode) {
}
/**
- * @param {BookmarkTreeNode} rootNode
+ * @param {chrome.bookmarks.BookmarkTreeNode} rootNode
* @return {NodeMap}
*/
export function normalizeNodes(rootNode) {
diff --git a/chromium/chrome/browser/resources/chromeos/BUILD.gn b/chromium/chrome/browser/resources/chromeos/BUILD.gn
index d4f57c718a8..675d9ee14d8 100644
--- a/chromium/chrome/browser/resources/chromeos/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/BUILD.gn
@@ -34,29 +34,6 @@ 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 = [
- "//components/arc/mojom:camera_intent_js",
- "//media/capture/video/chromeos/mojom:cros_camera_js",
- ]
-
- grit_flags = [
- "-E",
- "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
- ]
-}
-
group("closure_compile") {
deps = [
"accessibility/braille_ime:closure_compile",
@@ -64,7 +41,6 @@ group("closure_compile") {
"accessibility/switch_access:closure_compile",
"add_supervision:closure_compile",
"bluetooth_pairing_dialog:closure_compile",
- "camera/src/js:closure_compile",
"crostini_installer:closure_compile",
"edu_login:closure_compile",
"emulator:closure_compile",
diff --git a/chromium/chrome/browser/resources/chromeos/accessibility/BUILD.gn b/chromium/chrome/browser/resources/chromeos/accessibility/BUILD.gn
index 0f4967d66af..31961f1aae2 100644
--- a/chromium/chrome/browser/resources/chromeos/accessibility/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/accessibility/BUILD.gn
@@ -21,11 +21,13 @@ group("build") {
]
if (is_chromeos) {
deps += [
+ ":accessibility_common_guest_manifest",
+ ":accessibility_common_manifest",
":select_to_speak_guest_manifest",
":select_to_speak_manifest",
":switch_access_guest_manifest",
":switch_access_manifest",
- "autoclick:build",
+ "accessibility_common:build",
"select_to_speak:build",
"switch_access:build",
]
@@ -58,6 +60,20 @@ template("manifest") {
}
}
+manifest("accessibility_common_manifest") {
+ input_file = "accessibility_common_manifest.json.jinja2"
+ output_file = "$accessibility_out_dir/accessibility_common_manifest.json"
+ 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"
+}
+
+manifest("accessibility_common_guest_manifest") {
+ input_file = "accessibility_common_manifest.json.jinja2"
+ output_file =
+ "$accessibility_out_dir/accessibility_common_guest_manifest.json"
+ 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"
+ is_guest_manifest = true
+}
+
manifest("chromevox_manifest") {
input_file = "chromevox_manifest.json.jinja2"
output_file = "$accessibility_out_dir/chromevox_manifest.json"
@@ -105,7 +121,7 @@ group("browser_tests") {
testonly = true
if (is_chromeos) {
deps = [
- "autoclick:browser_tests",
+ "accessibility_common:browser_tests",
"chromevox:browser_tests",
"common:browser_tests",
"select_to_speak:browser_tests",
diff --git a/chromium/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn b/chromium/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn
new file mode 100644
index 00000000000..9cb8ce6e600
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/accessibility/accessibility_common/BUILD.gn
@@ -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.
+
+import("//build/config/features.gni")
+import(
+ "//chrome/browser/resources/chromeos/accessibility/common/run_jsbundler.gni")
+import("//chrome/test/base/js2gtest.gni")
+import("//testing/test.gni")
+import("//third_party/closure_compiler/compile_js.gni")
+
+assert(is_chromeos)
+
+accessibility_common_dir =
+ "$root_out_dir/resources/chromeos/accessibility/accessibility_common"
+
+group("build") {
+ deps = [ ":accessibility_common_copied_files" ]
+}
+
+# Instead of setting up copy targets, use a script to copy all files.
+run_jsbundler("accessibility_common_copied_files") {
+ mode = "copy"
+ dest_dir = accessibility_common_dir
+ sources = [
+ "accessibility_common_loader.js",
+ "autoclick/autoclick.js",
+ ]
+ rewrite_rules = [
+ rebase_path(".", root_build_dir) + ":",
+ rebase_path(closure_library_dir, root_build_dir) + ":closure",
+ ]
+}
+
+source_set("browser_tests") {
+ testonly = true
+ assert(enable_extensions)
+
+ deps = [ ":accessibility_common_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/accessibility/accessibility_common/",
+ "$root_out_dir/test_data/chrome/browser/resources/chromeos/accessibility/accessibility_common/",
+
+ # The test uses data from the original location, not the copied one.
+ "//chrome/browser/resources/chromeos/accessibility/accessibility_common/",
+ "//chrome/browser/resources/chromeos/accessibility/common/",
+ "//ui/webui/resources/js/cr.js",
+ ]
+ data += js2gtest_js_libraries
+}
+
+js2gtest("accessibility_common_extjs_tests") {
+ test_type = "extension"
+ sources = [ "autoclick_test.js" ]
+ gen_include_files = [
+ "../common/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 = [ ":accessibility_common" ]
+}
+
+js_library("accessibility_common") {
+ deps = []
+ externs_list = [
+ "$externs_path/accessibility_private.js",
+ "$externs_path/automation.js",
+ "$externs_path/accessibility_features.js",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/accessibility/autoclick/BUILD.gn b/chromium/chrome/browser/resources/chromeos/accessibility/autoclick/BUILD.gn
deleted file mode 100644
index f4cc2e8b078..00000000000
--- a/chromium/chrome/browser/resources/chromeos/accessibility/autoclick/BUILD.gn
+++ /dev/null
@@ -1,123 +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("//build/config/features.gni")
-import(
- "//chrome/browser/resources/chromeos/accessibility/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/accessibility/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/accessibility/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/accessibility/autoclick/",
- "$root_out_dir/test_data/chrome/browser/resources/chromeos/accessibility/autoclick/",
-
- # The test uses data from the original location, not the copied one.
- "//chrome/browser/resources/chromeos/accessibility/autoclick/",
- "//chrome/browser/resources/chromeos/accessibility/chromevox/",
- "//ui/webui/resources/js/cr.js",
- ]
- data += js2gtest_js_libraries
-}
-
-js2gtest("autoclick_extjs_tests") {
- test_type = "extension"
- sources = [ "autoclick_test.js" ]
- 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/accessibility/chromevox/BUILD.gn b/chromium/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn
index 7d16612e2df..4b6d105774b 100644
--- a/chromium/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/accessibility/chromevox/BUILD.gn
@@ -3,11 +3,15 @@
# found in the LICENSE file.
import("//build/config/features.gni")
+import(
+ "//chrome/browser/resources/chromeos/accessibility/common/run_jsbundler.gni")
import("//chrome/common/features.gni")
import("//chrome/test/base/js2gtest.gni")
import("//testing/test.gni")
import("//third_party/closure_compiler/compile_js.gni")
-import("run_jsbundler.gni")
+
+# Prevent Chromium source assignment filters from being inherited.
+set_sources_assignment_filter([])
declare_args() {
# Whether to compress the main Chromevox javascript files or load the
@@ -135,12 +139,17 @@ relative_closure_library_modules = [
closure_library_modules =
rebase_path(relative_closure_library_modules, ".", closure_library_dir)
+chromevox_gen_dir =
+ "$root_gen_dir/chrome/browser/resources/chromeos/accessibility/chromevox"
+
chromevox_out_dir = "$root_out_dir/resources/chromeos/accessibility/chromevox"
group("build") {
deps = [
":chromevox_copied_files",
":chromevox_phonetic_dictionaries_js",
+ ":lesson_component",
+ ":tutorial_component",
"//chrome/browser/resources/chromeos/accessibility/braille_ime:braille_ime_manifest",
"//third_party/chromevox:chromevox_third_party_resources",
"//third_party/liblouis",
@@ -182,6 +191,11 @@ run_jsbundler("chromevox_copied_files") {
"background/keymaps/default_keymap.json",
"background/logging/log.css",
"background/logging/log.html",
+ "i_tutorial/components/i_tutorial.js",
+ "i_tutorial/components/tutorial_lesson.js",
+ "i_tutorial/lessons/basic_navigation.html",
+ "i_tutorial/lessons/jump_commands.html",
+ "i_tutorial/lessons/text_fields.html",
"images/chromevox-128.png",
"images/chromevox-16.png",
"images/chromevox-19.png",
@@ -387,8 +401,8 @@ if (is_chromeos) {
"testing/mock_feedback_test.js",
]
gen_include_files = [
- "testing/assert_additions.js",
- "testing/callback_helper.js",
+ "../common/testing/assert_additions.js",
+ "../common/testing/callback_helper.js",
"testing/chromevox_unittest_base.js",
"testing/mock_feedback.js",
]
@@ -426,8 +440,8 @@ if (is_chromeos) {
"panel/panel_test.js",
]
gen_include_files = [
- "testing/assert_additions.js",
- "testing/callback_helper.js",
+ "../common/testing/assert_additions.js",
+ "../common/testing/callback_helper.js",
"testing/chromevox_e2e_test_base.js",
"testing/chromevox_next_e2e_test_base.js",
"testing/mock_feedback.js",
@@ -443,3 +457,22 @@ if (is_chromeos) {
defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ]
}
}
+
+copy("lesson_component") {
+ sources = [ "$chromevox_gen_dir/i_tutorial/components/tutorial_lesson.js" ]
+ outputs = [ "$chromevox_out_dir/i_tutorial/tutorial_lesson.js" ]
+ deps = [
+ "i_tutorial/components:closure_compile",
+ "i_tutorial/components:components",
+ ]
+}
+
+copy("tutorial_component") {
+ sources = [ "$chromevox_gen_dir/i_tutorial/components/i_tutorial.js" ]
+ outputs = [ "$chromevox_out_dir/i_tutorial/i_tutorial.js" ]
+
+ deps = [
+ "i_tutorial/components:closure_compile",
+ "i_tutorial/components:components",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/accessibility/chromevox/i_tutorial/components/BUILD.gn b/chromium/chrome/browser/resources/chromeos/accessibility/chromevox/i_tutorial/components/BUILD.gn
new file mode 100644
index 00000000000..679a3871583
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/accessibility/chromevox/i_tutorial/components/BUILD.gn
@@ -0,0 +1,33 @@
+# Copyright 2020 The Chromium 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")
+import("//tools/polymer/html_to_js.gni")
+
+html_to_js("components") {
+ js_files = [
+ "tutorial_lesson.js",
+ "i_tutorial.js",
+ ]
+}
+
+js_type_check("closure_compile") {
+ is_polymer3 = true
+ deps = [
+ ":i_tutorial",
+ ":tutorial_lesson",
+ ]
+}
+
+js_library("tutorial_lesson") {
+ deps = [
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ ]
+}
+
+js_library("i_tutorial") {
+ deps = [
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn b/chromium/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn
index 8f6bb71d6e2..af38f4fb21f 100644
--- a/chromium/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/accessibility/common/BUILD.gn
@@ -4,7 +4,7 @@
import("//build/config/features.gni")
import(
- "//chrome/browser/resources/chromeos/accessibility/chromevox/run_jsbundler.gni")
+ "//chrome/browser/resources/chromeos/accessibility/common/run_jsbundler.gni")
import("//chrome/common/features.gni")
import("//chrome/test/base/js2gtest.gni")
import("//testing/test.gni")
@@ -29,6 +29,7 @@ run_jsbundler("accessibility_common_copied_files") {
"automation_util.js",
"closure_shim.js",
"constants.js",
+ "repeated_event_handler.js",
"tree_walker.js",
]
rewrite_rules = [ rebase_path(".", root_build_dir) + ":" ]
@@ -78,6 +79,10 @@ js_library("automation_util") {
]
}
+js_library("repeated_event_handler") {
+ externs_list = [ "$externs_path/automation.js" ]
+}
+
source_set("browser_tests") {
testonly = true
assert(enable_extensions)
@@ -108,15 +113,16 @@ js2gtest("accessibility_tests") {
sources = [
"array_util_test.js",
"automation_util_test.js",
+ "repeated_event_handler_test.js",
"tree_walker_test.js",
]
gen_include_files = [
- "../chromevox/testing/assert_additions.js",
- "../chromevox/testing/callback_helper.js",
"../chromevox/testing/chromevox_e2e_test_base.js",
"../chromevox/testing/chromevox_next_e2e_test_base.js",
"../chromevox/testing/mock_feedback.js",
"array_util.js",
+ "testing/assert_additions.js",
+ "testing/callback_helper.js",
]
if (is_chromeos) {
diff --git a/chromium/chrome/browser/resources/chromeos/accessibility/chromevox/run_jsbundler.gni b/chromium/chrome/browser/resources/chromeos/accessibility/common/run_jsbundler.gni
index c68bb6df6fa..c68bb6df6fa 100644
--- a/chromium/chrome/browser/resources/chromeos/accessibility/chromevox/run_jsbundler.gni
+++ b/chromium/chrome/browser/resources/chromeos/accessibility/common/run_jsbundler.gni
diff --git a/chromium/chrome/browser/resources/chromeos/accessibility/select_to_speak/BUILD.gn b/chromium/chrome/browser/resources/chromeos/accessibility/select_to_speak/BUILD.gn
index e2cf38296ad..63356e98621 100644
--- a/chromium/chrome/browser/resources/chromeos/accessibility/select_to_speak/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/accessibility/select_to_speak/BUILD.gn
@@ -4,7 +4,7 @@
import("//build/config/features.gni")
import(
- "//chrome/browser/resources/chromeos/accessibility/chromevox/run_jsbundler.gni")
+ "//chrome/browser/resources/chromeos/accessibility/common/run_jsbundler.gni")
import("//chrome/common/features.gni")
import("//chrome/test/base/js2gtest.gni")
import("//testing/test.gni")
@@ -65,7 +65,7 @@ source_set("browser_tests") {
"$root_out_dir/test_data/chrome/browser/resources/chromeos/accessibility/select_to_speak/",
# The test uses data from the original location, not the copied one.
- "//chrome/browser/resources/chromeos/accessibility/chromevox/",
+ "//chrome/browser/resources/chromeos/accessibility/common/",
"//chrome/browser/resources/chromeos/accessibility/select_to_speak/",
"//ui/webui/resources/js/cr.js",
]
@@ -80,7 +80,7 @@ js2gtest("select_to_speak_extjs_tests") {
"select_to_speak_prefs_test.js",
]
gen_include_files = [
- "../chromevox/testing/callback_helper.js",
+ "../common/testing/callback_helper.js",
"mock_storage.js",
"mock_tts.js",
"select_to_speak_e2e_test_base.js",
diff --git a/chromium/chrome/browser/resources/chromeos/accessibility/strings/chromevox_strings.grdp b/chromium/chrome/browser/resources/chromeos/accessibility/strings/chromevox_strings.grdp
index 75c816257cb..c7bf4b862b0 100644
--- a/chromium/chrome/browser/resources/chromeos/accessibility/strings/chromevox_strings.grdp
+++ b/chromium/chrome/browser/resources/chromeos/accessibility/strings/chromevox_strings.grdp
@@ -380,7 +380,10 @@
Show Log
</message>
<message desc="Keyboard shortcut to show the ChromeVox log." name="IDS_CHROMEVOX_OPTIONS_SHOW_LOG_KEY">
- Search + O + W
+ Search + O, then W
+ </message>
+ <message desc="Keyboard shortcut to show the TTS settings page." name="IDS_CHROMEVOX_OPTIONS_SHOW_TTS_SETTINGS">
+ Search + O, then S. Use to install, manage, and customize voices.
</message>
<message desc="Show event stream filters options for event stream logging." name="IDS_CHROMEVOX_OPTIONS_SHOW_EVENT_STREAM_FILTERS">
Show event stream filters
@@ -2975,5 +2978,8 @@
<message desc="Describes a gesture to be performed on a touch screen." name="IDS_CHROMEVOX_CLICK_GESTURE">
Double tap with one finger
</message>
+ <message desc="The text label for the use pitch changes checkbox." name="IDS_CHROMEVOX_OPTIONS_USE_PITCH_CHANGES_CHECKBOX_LABEL">
+ Change pitch when speaking element types and quoted, deleted, bolded, parenthesized, or capitalized text.
+ </message>
</grit-part>
diff --git a/chromium/chrome/browser/resources/chromeos/accessibility/strings/select_to_speak_strings.grdp b/chromium/chrome/browser/resources/chromeos/accessibility/strings/select_to_speak_strings.grdp
index fa31306e16b..58a65969ce8 100644
--- a/chromium/chrome/browser/resources/chromeos/accessibility/strings/select_to_speak_strings.grdp
+++ b/chromium/chrome/browser/resources/chromeos/accessibility/strings/select_to_speak_strings.grdp
@@ -45,6 +45,9 @@
<message desc="Example of a word highlight on a light background in the Select-to-speak options dialog." name="IDS_SELECT_TO_SPEAK_OPTIONS_HIGHLIGHT_LIGHT">
Light background
</message>
+<message desc="Label for option to fade the background outside of the focus ring to improve focus on what is being spoken." name="IDS_SELECT_TO_SPEAK_OPTIONS_BACKGROUND_SHADING_DESCRIPTION">
+ Shade background content
+</message>
<message desc="Link to the Text-to-Speech settings page." name="IDS_SELECT_TO_SPEAK_OPTIONS_TEXT_TO_SPEECH_SETTINGS">
Personalize Text-to-Speech settings
</message>
@@ -72,4 +75,7 @@
<message desc="Description of a radio button that is selected" name="IDS_SELECT_TO_SPEAK_RADIOBUTTON_MIXED">
partially selected
</message>
+<message desc="Sample text around which will be drawn a Select to Speak visual preview. This should be less than one line long." name="IDS_SELECT_TO_SPEAK_OPTIONS_SAMPLE_TEXT">
+ The quick brown fox jumped over the lazy dog.
+</message>
</grit-part>
diff --git a/chromium/chrome/browser/resources/chromeos/accessibility/switch_access/BUILD.gn b/chromium/chrome/browser/resources/chromeos/accessibility/switch_access/BUILD.gn
index b930b96e57d..8f75b17ff43 100644
--- a/chromium/chrome/browser/resources/chromeos/accessibility/switch_access/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/accessibility/switch_access/BUILD.gn
@@ -4,7 +4,7 @@
import("//build/config/features.gni")
import(
- "//chrome/browser/resources/chromeos/accessibility/chromevox/run_jsbundler.gni")
+ "//chrome/browser/resources/chromeos/accessibility/common/run_jsbundler.gni")
import("//chrome/common/features.gni")
import("//chrome/test/base/js2gtest.gni")
import("//testing/test.gni")
@@ -58,21 +58,20 @@ run_jsbundler("switch_access_copied_files") {
"icons/textSelectionEnd.svg",
"icons/textSelectionStart.svg",
"menu_manager.js",
- "menu_panel.css",
- "menu_panel.html",
- "menu_panel.js",
- "menu_panel_interface.js",
"metrics.js",
"navigation_manager.js",
"nodes/back_button_node.js",
+ "nodes/combo_box_node.js",
"nodes/desktop_node.js",
"nodes/editable_text_node.js",
"nodes/group_node.js",
"nodes/keyboard_node.js",
+ "nodes/modal_dialog_node.js",
"nodes/node_wrapper.js",
+ "nodes/slider_node.js",
"nodes/switch_access_node.js",
- "nodes/system_menu_node.js",
"nodes/tab_node.js",
+ "nodes/window_node.js",
"preferences.js",
"rect_helper.js",
"switch_access.js",
@@ -93,7 +92,7 @@ source_set("browser_tests") {
deps = [ ":switch_access_extjs_tests" ]
data = [
- "//chrome/browser/resources/chromeos/accessibility/chromevox/",
+ "//chrome/browser/resources/chromeos/accessibility/common/",
"//chrome/browser/resources/chromeos/accessibility/switch_access/",
"//ui/webui/resources/js/cr.js",
]
@@ -112,7 +111,8 @@ js2gtest("switch_access_extjs_tests") {
"text_navigation_manager_test.js",
]
gen_include_files = [
- "../chromevox/testing/callback_helper.js",
+ "../common/testing/assert_additions.js",
+ "../common/testing/callback_helper.js",
"switch_access_e2e_test_base.js",
]
@@ -133,6 +133,7 @@ js_type_check("closure_compile") {
":auto_scan_manager",
":back_button_node",
":background",
+ ":combo_box_node",
":commands",
":desktop_node",
":editable_text_node",
@@ -142,22 +143,24 @@ js_type_check("closure_compile") {
":history",
":keyboard_node",
":menu_manager",
- ":menu_panel",
- ":menu_panel_interface",
":metrics",
+ ":modal_dialog_node",
":navigation_manager",
":node_wrapper",
":preferences",
":rect_helper",
+ ":slider_node",
":switch_access",
":switch_access_constants",
":switch_access_node",
":switch_access_predicate",
- ":system_menu_node",
":tab_node",
":text_navigation_manager",
+ ":window_node",
+ "../common:automation_predicate",
"../common:closure_shim",
"../common:constants",
+ "../common:repeated_event_handler",
"../common:tree_walker",
]
}
@@ -184,7 +187,22 @@ js_library("back_button_node") {
]
}
+js_library("combo_box_node") {
+ sources = [ "nodes/combo_box_node.js" ]
+ deps = [
+ ":event_helper",
+ ":node_wrapper",
+ ":switch_access_constants",
+ ]
+ externs_list = []
+}
+
js_library("commands") {
+ deps = [
+ ":auto_scan_manager",
+ ":menu_manager",
+ ":navigation_manager",
+ ]
externs_list = [ "$externs_path/accessibility_private.js" ]
}
@@ -213,8 +231,8 @@ js_library("event_helper") {
js_library("focus_ring_manager") {
deps = [
- ":menu_panel_interface",
":node_wrapper",
+ ":switch_access_constants",
":switch_access_node",
]
externs_list = [ "$externs_path/accessibility_private.js" ]
@@ -266,54 +284,46 @@ js_library("keyboard_node") {
js_library("menu_manager") {
deps = [
- ":event_helper",
- ":menu_panel_interface",
- ":metrics",
- ":node_wrapper",
- ":rect_helper",
":switch_access_constants",
":switch_access_node",
- ":switch_access_predicate",
- ":text_navigation_manager",
- "../common:constants",
- "../common:tree_walker",
+ "../common:array_util",
]
externs_list = [
"$externs_path/accessibility_private.js",
"$externs_path/automation.js",
- "$externs_path/clipboard.js",
]
}
-js_library("menu_panel") {
- deps = [
- ":menu_manager",
- ":switch_access_constants",
- ]
- externs_list = [ "$externs_path/chrome_extensions.js" ]
-}
-
-js_library("menu_panel_interface") {
-}
-
js_library("metrics") {
deps = [ ":switch_access_constants" ]
externs_list = [ "$externs_path/metrics_private.js" ]
}
+js_library("modal_dialog_node") {
+ sources = [ "nodes/modal_dialog_node.js" ]
+ deps = [
+ ":event_helper",
+ ":node_wrapper",
+ ":switch_access_constants",
+ ":switch_access_node",
+ ]
+ externs_list = [ "$externs_path/automation.js" ]
+}
+
js_library("navigation_manager") {
deps = [
":desktop_node",
":focus_ring_manager",
+ ":history",
":keyboard_node",
":menu_manager",
- ":menu_panel_interface",
":metrics",
+ ":modal_dialog_node",
":node_wrapper",
":switch_access_constants",
":switch_access_node",
":switch_access_predicate",
- ":system_menu_node",
+ "../common:repeated_event_handler",
]
externs_list = [
"$externs_path/accessibility_private.js",
@@ -328,7 +338,9 @@ js_library("node_wrapper") {
":switch_access_constants",
":switch_access_node",
":switch_access_predicate",
+ "../common:automation_predicate",
"../common:constants",
+ "../common:repeated_event_handler",
"../common:tree_walker",
]
externs_list = [
@@ -346,12 +358,21 @@ js_library("rect_helper") {
externs_list = [ "$externs_path/accessibility_private.js" ]
}
+js_library("slider_node") {
+ sources = [ "nodes/slider_node.js" ]
+ deps = [
+ ":event_helper",
+ ":node_wrapper",
+ ":switch_access_constants",
+ ]
+ externs_list = [ "$externs_path/automation.js" ]
+}
+
js_library("switch_access") {
deps = [
":auto_scan_manager",
":commands",
":menu_manager",
- ":menu_panel_interface",
":navigation_manager",
":preferences",
":switch_access_constants",
@@ -362,6 +383,7 @@ js_library("switch_access") {
"$externs_path/automation.js",
"$externs_path/command_line_private.js",
"$externs_path/metrics_private.js",
+ "$externs_path/virtual_keyboard_private.js",
]
}
@@ -381,17 +403,7 @@ js_library("switch_access_predicate") {
deps = [
":switch_access_constants",
":switch_access_node",
- ]
- externs_list = [ "$externs_path/automation.js" ]
-}
-
-js_library("system_menu_node") {
- sources = [ "nodes/system_menu_node.js" ]
- deps = [
- ":event_helper",
- ":node_wrapper",
- ":switch_access_constants",
- ":switch_access_node",
+ "../common:automation_predicate",
]
externs_list = [ "$externs_path/automation.js" ]
}
@@ -412,5 +424,16 @@ js_library("text_navigation_manager") {
externs_list = [
"$externs_path/accessibility_private.js",
"$externs_path/automation.js",
+ "$externs_path/clipboard.js",
]
}
+
+js_library("window_node") {
+ sources = [ "nodes/window_node.js" ]
+ deps = [
+ ":node_wrapper",
+ ":switch_access_constants",
+ ":switch_access_node",
+ ]
+ externs_list = [ "$externs_path/automation.js" ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/BUILD.gn b/chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/BUILD.gn
index e7e7cc85086..f0bd4bdd7bc 100644
--- a/chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/BUILD.gn
@@ -2,36 +2,77 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+import("//chrome/common/features.gni")
import("//third_party/closure_compiler/compile_js.gni")
+import("//tools/grit/grit_rule.gni")
+import("//tools/polymer/html_to_js.gni")
+import("//tools/polymer/polymer.gni")
+import("//ui/webui/resources/tools/js_modulizer.gni")
import("../../optimize_webui.gni")
-optimize_webui("build") {
- host = "bluetooth_pairing_dialog"
- html_in_files = [ "bluetooth_pairing_dialog.html" ]
- html_out_files = [ "vulcanized.html" ]
+if (optimize_webui) {
+ bluetooth_dialog_pak_file = "bluetooth_pairing_dialog_resources.pak"
+ unpak_folder = "bluetooth_pairing_dialog_resources.unpak"
- input = rebase_path(".", root_build_dir)
- js_out_files = [ "crisper.js" ]
+ optimize_webui("build") {
+ host = "bluetooth-pairing"
+ js_out_files = [ "bluetooth_pairing_dialog.rollup.js" ]
+ js_module_in_files = [ "bluetooth_pairing_dialog.js" ]
+ input = rebase_path("$target_gen_dir/$unpak_folder", root_build_dir)
- deps = []
+ deps = [
+ ":unpak",
+ "../../../../../ui/webui/resources:modulize",
+ ]
+ }
+
+ unpak("unpak") {
+ pak_file = bluetooth_dialog_pak_file
+ out_folder = unpak_folder
+
+ deps = [ ":flattened_resources" ]
+ }
+
+ grit("flattened_resources") {
+ source = "bluetooth_pairing_dialog_resources.grd"
+
+ deps = [ ":web_components" ]
+ defines = chrome_grit_defines
+ grit_flags = [
+ "-E",
+ "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
+ ]
+ outputs = [
+ "grit/bluetooth_pairing_dialog_resources.h",
+ "grit/bluetooth_pairing_dialog_resources_map.cc",
+ "grit/bluetooth_pairing_dialog_resources_map.h",
+ bluetooth_dialog_pak_file,
+ ]
+ output_dir = "$root_gen_dir/chrome/browser/resources/chromeos/bluetooth_pairing_dialog"
+ }
}
js_type_check("closure_compile") {
+ is_polymer3 = true
deps = [ ":bluetooth_pairing_dialog" ]
}
js_library("bluetooth_pairing_dialog") {
deps = [
- "//ui/webui/resources/cr_components/chromeos:bluetooth_dialog",
- "//ui/webui/resources/js:cr",
- "//ui/webui/resources/js:i18n_behavior",
- ]
- externs_list = [
- "$externs_path/bluetooth.js",
- "$externs_path/bluetooth_private.js",
+ "//ui/webui/resources/cr_components/chromeos/bluetooth:bluetooth_dialog.m",
+ "//ui/webui/resources/js:cr.m",
+ "//ui/webui/resources/js:i18n_behavior.m",
]
+ externs_list = chrome_extension_public_externs + [
+ "$externs_path/bluetooth.js",
+ "$externs_path/bluetooth_private.js",
+ ]
extra_sources = [
"$interfaces_path/bluetooth_interface.js",
"$interfaces_path/bluetooth_private_interface.js",
]
}
+
+html_to_js("web_components") {
+ js_files = [ "bluetooth_pairing_dialog.js" ]
+}
diff --git a/chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/bluetooth_pairing_dialog_resources.grd b/chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/bluetooth_pairing_dialog_resources.grd
new file mode 100644
index 00000000000..c345ebb020f
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/bluetooth_pairing_dialog_resources.grd
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<grit latest_public_release="0" current_release="1" output_all_resource_defines="false">
+ <outputs>
+ <output filename="grit/bluetooth_pairing_dialog_resources.h" type="rc_header">
+ <emit emit_type='prepend'></emit>
+ </output>
+ <output filename="grit/bluetooth_pairing_dialog_resources_map.cc"
+ type="resource_file_map_source" />
+ <output filename="grit/bluetooth_pairing_dialog_resources_map.h"
+ type="resource_map_header" />
+ <output filename="bluetooth_pairing_dialog_resources.pak" type="data_package" />
+ </outputs>
+ <release seq="1">
+ <includes>
+ <include name="IDR_BLUETOOTH_PAIRING_DIALOG_JS"
+ file="${root_gen_dir}/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/bluetooth_pairing_dialog.js"
+ use_base_dir="false"
+ compress="false"
+ type="chrome_html" />
+ </includes>
+ <structures>
+ <structure name="IDR_BLUETOOTH_PAIRING_DIALOG_CONTAINER_HTML"
+ file="bluetooth_pairing_dialog_container.html"
+ compress="false"
+ type="chrome_html" />
+ </structures>
+ </release>
+</grit> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/bluetooth_pairing_dialog_resources_vulcanized.grd b/chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/bluetooth_pairing_dialog_resources_vulcanized.grd
new file mode 100644
index 00000000000..8816618f277
--- /dev/null
+++ b/chromium/chrome/browser/resources/chromeos/bluetooth_pairing_dialog/bluetooth_pairing_dialog_resources_vulcanized.grd
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<grit latest_public_release="0" current_release="1" output_all_resource_defines="false">
+ <outputs>
+ <output filename="grit/bluetooth_pairing_dialog_resources.h" type="rc_header">
+ <emit emit_type='prepend'></emit>
+ </output>
+ <output filename="grit/bluetooth_pairing_dialog_resources_map.cc"
+ type="resource_map_source" />
+ <output filename="grit/bluetooth_pairing_dialog_resources_map.h"
+ type="resource_map_header" />
+ <output filename="bluetooth_pairing_dialog_resources.pak" type="data_package" />
+ </outputs>
+ <release seq="1">
+ <includes>
+ <include name="IDR_BLUETOOTH_PAIRING_DIALOG_CONTAINER_HTML"
+ file="bluetooth_pairing_dialog_container.html"
+ type="chrome_html" />
+ <include name="IDR_BLUETOOTH_PAIRING_DIALOG_ROLLUP_JS"
+ file="${root_gen_dir}\chrome\browser\resources\chromeos\bluetooth_pairing_dialog\bluetooth_pairing_dialog.rollup.js"
+ use_base_dir="false"
+ preprocess="true"
+ type="chrome_html" />
+ </includes>
+ </release>
+</grit>
diff --git a/chromium/chrome/browser/resources/chromeos/camera/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/BUILD.gn
deleted file mode 100644
index 2c90301b56a..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/BUILD.gn
+++ /dev/null
@@ -1,252 +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.
-
-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
- # the difficulty to diagnose.
- deps = [
- "//chrome/browser/resources/chromeos/camera/src/strings:camera_strings",
- ]
-
- data_deps = [
- ":chrome_camera_app_base",
- ":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_lib",
- ":chrome_camera_app_js_models",
- ":chrome_camera_app_js_mojo",
- ":chrome_camera_app_js_views",
- ":chrome_camera_app_js_views_camera",
- ":chrome_camera_app_mojo_generated",
- ":chrome_camera_app_sounds",
- ":chrome_camera_app_views",
- ]
-}
-
-copy("chrome_camera_app_base") {
- sources = [ "src/manifest.json" ]
-
- outputs = [ "$chrome_camera_app_dir/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_css") {
- sources = [ "src/css/main.css" ]
-
- outputs = [ "$chrome_camera_app_dir/css/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_images") {
- sources = [
- "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",
- "src/images/camera_button_mic_on.svg",
- "src/images/camera_button_mirror_off.svg",
- "src/images/camera_button_mirror_on.svg",
- "src/images/camera_button_settings.svg",
- "src/images/camera_button_switch_device.svg",
- "src/images/camera_button_switch_photo.svg",
- "src/images/camera_button_switch_video.svg",
- "src/images/camera_button_timer_off.svg",
- "src/images/camera_button_timer_on_10s.svg",
- "src/images/camera_button_timer_on_3s.svg",
- "src/images/camera_focus_aim.svg",
- "src/images/camera_intent_play_video.svg",
- "src/images/camera_intent_result_cancel.svg",
- "src/images/camera_intent_result_confirm.svg",
- "src/images/camera_mode_photo.svg",
- "src/images/camera_mode_portrait.svg",
- "src/images/camera_mode_square.svg",
- "src/images/camera_mode_video.svg",
- "src/images/camera_shutter_photo_start.svg",
- "src/images/camera_shutter_photo_start_active.svg",
- "src/images/camera_shutter_photo_start_hover.svg",
- "src/images/camera_shutter_photo_stop.svg",
- "src/images/camera_shutter_photo_stop_hover.svg",
- "src/images/settings_button_back.svg",
- "src/images/settings_button_expand.svg",
- "src/images/settings_feedback.svg",
- "src/images/settings_grid_type.svg",
- "src/images/settings_help.svg",
- "src/images/settings_resolution.svg",
- "src/images/settings_timer_duration.svg",
- "src/images/spinner.svg",
- ]
-
- outputs = [ "$chrome_camera_app_dir/images/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_js") {
- sources = [
- "src/js/background.js",
- "src/js/background_ops.js",
- "src/js/chrome_util.js",
- "src/js/error.js",
- "src/js/gallerybutton.js",
- "src/js/intent.js",
- "src/js/main.js",
- "src/js/metrics.js",
- "src/js/nav.js",
- "src/js/perf.js",
- "src/js/sound.js",
- "src/js/state.js",
- "src/js/toast.js",
- "src/js/tooltip.js",
- "src/js/type.js",
- "src/js/util.js",
- ]
-
- outputs = [ "$chrome_camera_app_dir/js/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_js_browser_proxy") {
- sources = [
- # TODO(b/129956426): Remove dependency used only in closure compiler check.
- "src/js/browser_proxy/browser_proxy.js",
- "src/js/browser_proxy/browser_proxy_interface.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",
- "src/js/device/error.js",
- ]
-
- outputs = [ "$chrome_camera_app_dir/js/device/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_js_lib") {
- sources = [
- "src/js/lib/analytics.js",
- "src/js/lib/comlink.js",
- "src/js/lib/ffmpeg.js",
- "src/js/lib/ffmpeg.wasm",
- ]
-
- outputs = [ "$chrome_camera_app_dir/js/lib/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_js_models") {
- sources = [
- "src/js/models/async_writer.js",
- "src/js/models/filenamer.js",
- "src/js/models/filesystem.js",
- "src/js/models/mp4_video_processor.js",
- "src/js/models/nop_video_processor.js",
- "src/js/models/result_saver.js",
- "src/js/models/video_saver.js",
- "src/js/models/waitable_event.js",
- ]
-
- outputs = [ "$chrome_camera_app_dir/js/models/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_js_mojo") {
- sources = [
- "src/js/mojo/chrome_helper.js",
- "src/js/mojo/device_operator.js",
- "src/js/mojo/image_capture.js",
- ]
-
- outputs = [ "$chrome_camera_app_dir/js/mojo/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_js_views") {
- sources = [
- "src/js/views/camera.js",
- "src/js/views/camera_intent.js",
- "src/js/views/dialog.js",
- "src/js/views/settings.js",
- "src/js/views/view.js",
- "src/js/views/warning.js",
- ]
-
- outputs = [ "$chrome_camera_app_dir/js/views/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_js_views_camera") {
- sources = [
- "src/js/views/camera/layout.js",
- "src/js/views/camera/modes.js",
- "src/js/views/camera/options.js",
- "src/js/views/camera/preview.js",
- "src/js/views/camera/recordtime.js",
- "src/js/views/camera/review_result.js",
- "src/js/views/camera/timertick.js",
- ]
-
- outputs = [ "$chrome_camera_app_dir/js/views/camera/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_sounds") {
- sources = [
- "src/sounds/record_end.ogg",
- "src/sounds/record_start.ogg",
- "src/sounds/shutter.ogg",
- "src/sounds/tick_final.ogg",
- "src/sounds/tick_inc.ogg",
- "src/sounds/tick_start.ogg",
- ]
-
- outputs = [ "$chrome_camera_app_dir/sounds/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_views") {
- sources = [
- "src/views/background.html",
- "src/views/main.html",
- ]
-
- outputs = [ "$chrome_camera_app_dir/views/{{source_file_part}}" ]
-}
-
-copy("chrome_camera_app_mojo_generated") {
- sources = [
- "$root_gen_dir/components/arc/mojom/camera_intent.mojom-lite.js",
- "$root_gen_dir/components/chromeos_camera/common/camera_app_helper.mojom-lite.js",
- "$root_gen_dir/media/capture/mojom/image_capture.mojom-lite.js",
- "$root_gen_dir/media/capture/video/chromeos/mojom/camera_app.mojom-lite.js",
- "$root_gen_dir/media/capture/video/chromeos/mojom/camera_common.mojom-lite.js",
- "$root_gen_dir/media/capture/video/chromeos/mojom/camera_metadata.mojom-lite.js",
- "$root_gen_dir/media/capture/video/chromeos/mojom/camera_metadata_tags.mojom-lite.js",
- "$root_gen_dir/mojo/public/js/mojo_bindings_lite.js",
- "$root_gen_dir/mojo/public/mojom/base/time.mojom-lite.js",
- "$root_gen_dir/third_party/blink/public/mojom/idle/idle_manager.mojom-lite.js",
- "$root_gen_dir/ui/gfx/geometry/mojom/geometry.mojom-lite.js",
- "$root_gen_dir/ui/gfx/range/mojom/range.mojom-lite.js",
- ]
-
- deps = [
- "//components/arc/mojom:camera_intent_js",
- "//components/arc/mojom:mojom_js",
- "//components/chromeos_camera/common:camera_app_helper_js",
- "//media/capture/mojom:image_capture_js",
- "//media/capture/video/chromeos/mojom:cros_camera_js",
- "//mojo/public/js:bindings_lite",
- "//third_party/blink/public/mojom:mojom_platform_js",
- "//ui/gfx/geometry/mojom:mojom_js",
- "//ui/gfx/range/mojom:mojom_js",
- ]
-
- outputs = [ "$chrome_camera_app_dir/js/mojo/{{source_file_part}}" ]
-}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd b/chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd
deleted file mode 100644
index ab78c3f7507..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/camera_resources.grd
+++ /dev/null
@@ -1,137 +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/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_ANALYTICS_JS" file="src/js/lib/analytics.js" type="chrome_html" />
- <structure name="IDR_CAMERA_ASYNC_WRITER_JS" file="src/js/models/async_writer.js" type="chrome_html" />
- <structure name="IDR_CAMERA_BACKGROUND_JS" file="src/js/background.js" type="chrome_html" />
- <structure name="IDR_CAMERA_BACKGROUND_OPS_JS" file="src/js/background_ops.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_INTENT_JS" file="src/js/views/camera_intent.js" type="chrome_html" />
- <structure name="IDR_CAMERA_CAMERA_JS" file="src/js/views/camera.js" type="chrome_html" />
- <structure name="IDR_CAMERA_CHROME_HELPER_JS" file="src/js/mojo/chrome_helper.js" type="chrome_html" />
- <structure name="IDR_CAMERA_CHROME_UTIL_JS" file="src/js/chrome_util.js" type="chrome_html" />
- <structure name="IDR_CAMERA_COMLINK_JS" file="src/js/lib/comlink.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_ERROR_JS" file="src/js/device/error.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_DEVICE_OPERATOR_JS" file="src/js/mojo/device_operator.js" type="chrome_html" />
- <structure name="IDR_CAMERA_DIALOG_JS" file="src/js/views/dialog.js" type="chrome_html" />
- <structure name="IDR_CAMERA_ERROR_JS" file="src/js/error.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_GALLERYBUTTON_JS" file="src/js/gallerybutton.js" type="chrome_html" />
- <structure name="IDR_CAMERA_IMAGECAPTURE_JS" file="src/js/mojo/image_capture.js" type="chrome_html" />
- <structure name="IDR_CAMERA_INTENT_JS" file="src/js/intent.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_MP4_VIDEO_PROCESSOR_JS" file="src/js/models/mp4_video_processor.js" type="chrome_html" />
- <structure name="IDR_CAMERA_NAV_JS" file="src/js/nav.js" type="chrome_html" />
- <structure name="IDR_CAMERA_NOP_VIDEO_PROCESSOR_JS" file="src/js/models/nop_video_processor.js" type="chrome_html" />
- <structure name="IDR_CAMERA_OPTIONS_JS" file="src/js/views/camera/options.js" type="chrome_html" />
- <structure name="IDR_CAMERA_PERF_JS" file="src/js/perf.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_RESULT_SAVER_JS" file="src/js/models/result_saver.js" type="chrome_html" />
- <structure name="IDR_CAMERA_REVIEW_RESULT_JS" file="src/js/views/camera/review_result.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_TYPE_JS" file="src/js/type.js" type="chrome_html" />
- <structure name="IDR_CAMERA_UTIL_JS" file="src/js/util.js" type="chrome_html" />
- <structure name="IDR_CAMERA_VIDEO_SAVER_JS" file="src/js/models/video_saver.js" type="chrome_html" />
- <structure name="IDR_CAMERA_VIEW_JS" file="src/js/views/view.js" type="chrome_html" />
- <structure name="IDR_CAMERA_WAITABLE_EVENT_JS" file="src/js/models/waitable_event.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_CAMERA_INTENT_MOJOM_LITE_JS"
- file="${root_gen_dir}/components/arc/mojom/camera_intent.mojom-lite.js"
- use_base_dir="false"
- type="BINDATA"/>
- <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/mojom/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/mojom/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/mojom/camera_metadata_tags.mojom-lite.js"
- use_base_dir="false"
- type="BINDATA"/>
- <include name="IDR_CAMERA_APP_MOJOM_LITE_JS"
- file="${root_gen_dir}/media/capture/video/chromeos/mojom/camera_app.mojom-lite.js"
- use_base_dir="false"
- type="BINDATA"/>
-
- <!-- TODO(crbug.com/980846): Add FFMpeg library here with comrpession enabled once video recording is ready to test in SWA -->
-
- <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_FINAL_OGG" file="src/sounds/tick_final.ogg" type="BINDATA" />
- <include name="IDR_CAMERA_TICK_INC_OGG" file="src/sounds/tick_inc.ogg" type="BINDATA" />
- <include name="IDR_CAMERA_TICK_START_OGG" file="src/sounds/tick_start.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_SPINNER_SVG" file="src/images/spinner.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_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_SETTINGS_RESOLUTION_SVG" file="src/images/settings_resolution.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_CAMERA_APP_ICONS_192_PNG" file="src/images/camera_app_icons_192.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_CAMERA_SHUTTER_PHOTO_START_SVG" file="src/images/camera_shutter_photo_start.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_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/src/js/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/BUILD.gn
deleted file mode 100644
index 4e76d7e52c3..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/src/js/BUILD.gn
+++ /dev/null
@@ -1,150 +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")
-
-group("closure_compile") {
- deps = [
- ":compile_resources",
- "browser_proxy:closure_compile",
- "device:closure_compile",
- "models:closure_compile",
- "mojo:closure_compile",
- "views:closure_compile",
- ]
-}
-
-js_type_check("compile_resources") {
- deps = [
- ":background",
- ":background_ops",
- ":chrome_util",
- ":error",
- ":gallerybutton",
- ":intent",
- ":main",
- ":metrics",
- ":nav",
- ":perf",
- ":sound",
- ":state",
- ":toast",
- ":tooltip",
- ":type",
- ":util",
- ]
-}
-
-js_library("chrome_util") {
-}
-
-js_library("error") {
- deps = [ ":metrics" ]
-}
-
-js_library("intent") {
- deps = [
- ":chrome_util",
- ":metrics",
- ":type",
- "mojo:chrome_helper",
- ]
-}
-
-js_library("gallerybutton") {
- deps = [
- ":chrome_util",
- "models:filesystem",
- "models:result_saver",
- "models:video_saver",
- ]
- externs_list = [
- "$externs_path/file_manager_private.js",
- "$externs_path/file_system_provider.js",
- ]
-}
-
-js_library("metrics") {
- deps = [
- ":state",
- "externs:universal_analytics_api",
- ]
-}
-
-js_library("sound") {
-}
-
-js_library("type") {
-}
-
-js_library("main") {
- deps = [
- ":background_ops",
- ":chrome_util",
- ":gallerybutton",
- ":intent",
- ":state",
- ":type",
- "device:constraints_preferrer",
- "device:device_info_updater",
- "views:camera",
- "views:camera_intent",
- "views:dialog",
- "views:settings",
- "views:warning",
- ]
-}
-
-js_library("nav") {
- deps = [
- "mojo:device_operator",
- "views:view",
- ]
-}
-
-js_library("perf") {
-}
-
-js_library("state") {
- deps = [
- ":perf",
- ":type",
- ]
-}
-
-js_library("background") {
- deps = [
- ":background_ops",
- ":intent",
- ]
-}
-
-js_library("background_ops") {
- deps = [
- ":chrome_util",
- ":error",
- ":intent",
- ":perf",
- ]
-}
-
-js_library("toast") {
- deps = [ ":util" ]
-}
-
-js_library("tooltip") {
- deps = [ ":chrome_util" ]
-}
-
-js_library("util") {
- deps = [
- ":state",
- ":tooltip",
- ":type",
- "browser_proxy:browser_proxy",
- "externs:w3c_api",
- "mojo:chrome_helper",
- ]
- 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
deleted file mode 100644
index 909b9b4aea2..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/src/js/browser_proxy/BUILD.gn
+++ /dev/null
@@ -1,28 +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 = [ ":browser_proxy" ]
-}
-
-js_library("browser_proxy") {
- deps = [
- "..:chrome_util",
- "../mojo:chrome_helper",
- ]
- sources = [
- "browser_proxy.js",
- "browser_proxy_interface.js",
- "webui_browser_proxy.js",
- ]
- externs_list = [
- "../externs/chrome.js",
- "$externs_path/chrome_extensions.js",
- "$externs_path/file_manager_private.js",
- "$externs_path/file_system_provider.js",
- "$externs_path/metrics_private.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
deleted file mode 100644
index f4b59b69732..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/src/js/device/BUILD.gn
+++ /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.
-
-import("//third_party/closure_compiler/compile_js.gni")
-
-js_type_check("closure_compile") {
- deps = [
- ":camera3_device_info",
- ":constraints_preferrer",
- ":device_info_updater",
- ":error",
- ]
-}
-
-js_library("camera3_device_info") {
- deps = [
- "..:type",
- "../mojo:image_capture",
- ]
-}
-
-js_library("constraints_preferrer") {
- deps = [
- ":camera3_device_info",
- "..:chrome_util",
- "..:state",
- "..:type",
- "../browser_proxy:browser_proxy",
- ]
-}
-
-js_library("device_info_updater") {
- deps = [
- ":camera3_device_info",
- ":constraints_preferrer",
- ":error",
- "..:state",
- "..:type",
- ]
-}
-
-js_library("error") {
-}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/externs/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/externs/BUILD.gn
deleted file mode 100644
index cae1c53cb2d..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/src/js/externs/BUILD.gn
+++ /dev/null
@@ -1,17 +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_library("universal_analytics_api") {
- sources = []
-
- externs_list = [ "universal_analytics_api.js" ]
-}
-
-js_library("w3c_api") {
- sources = []
-
- externs_list = [ "w3c_api.js" ]
-}
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
deleted file mode 100644
index e2c787dd54f..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/src/js/models/BUILD.gn
+++ /dev/null
@@ -1,43 +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 = [
- ":filenamer",
- ":filesystem",
- ":result_saver",
- ":video_saver",
- ]
-}
-
-js_library("filenamer") {
-}
-
-js_library("filesystem") {
- deps = [
- ":filenamer",
- "../browser_proxy:browser_proxy",
- ]
-}
-
-js_library("result_saver") {
-}
-
-js_library("video_saver") {
- sources = [
- "async_writer.js",
- "mp4_video_processor.js",
- "nop_video_processor.js",
- "video_saver.js",
- "waitable_event.js",
- ]
- deps = [
- "..:intent",
- "../externs:w3c_api",
- "../lib:comlink",
- "../lib:ffmpeg",
- ]
-}
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
deleted file mode 100644
index b1bdcd32ae1..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/src/js/mojo/BUILD.gn
+++ /dev/null
@@ -1,39 +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 = [
- ":chrome_helper",
- ":device_operator",
- ":image_capture",
- ]
-}
-
-js_library("chrome_helper") {
- deps = [
- "//components/arc/mojom:camera_intent_js_library_for_compile",
- "//components/chromeos_camera/common:camera_app_helper_js_library_for_compile",
- "//third_party/blink/public/mojom:mojom_platform_js_library_for_compile",
- ]
- externs_list = [ "$externs_path/pending.js" ]
-}
-
-js_library("device_operator") {
- deps = [
- "..:type",
- "//media/capture/video/chromeos/mojom:cros_camera_js_library_for_compile",
- ]
- externs_list = [ "$externs_path/pending.js" ]
-}
-
-js_library("image_capture") {
- deps = [
- ":device_operator",
- "..:util",
- "//media/capture/mojom:image_capture_js_library_for_compile",
- ]
- externs_list = [ "$externs_path/pending.js" ]
-}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/views/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/views/BUILD.gn
deleted file mode 100644
index 6cfbb72e337..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/src/js/views/BUILD.gn
+++ /dev/null
@@ -1,67 +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")
-
-group("closure_compile") {
- deps = [
- ":compile_resources",
- "camera:compile_resources",
- ]
-}
-
-js_type_check("compile_resources") {
- deps = [
- ":camera",
- ":camera_intent",
- ":dialog",
- ":settings",
- ":view",
- ":warning",
- ]
-}
-
-js_library("camera") {
- deps = [
- "..:background_ops",
- "..:chrome_util",
- "..:metrics",
- "..:type",
- "../models:result_saver",
- "camera:layout",
- "camera:modes",
- "camera:options",
- "camera:preview",
- "camera:timertick",
- ]
-}
-
-js_library("dialog") {
-}
-
-js_library("camera_intent") {
- deps = [
- ":camera",
- "..:chrome_util",
- "../models:video_saver",
- "camera:review_result",
- ]
-}
-
-js_library("settings") {
- deps = [
- ":view",
- "..:nav",
- "..:type",
- "../device:camera3_device_info",
- "../device:device_info_updater",
- ]
-}
-
-js_library("view") {
- deps = [ "..:toast" ]
-}
-
-js_library("warning") {
-}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/js/views/camera/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/js/views/camera/BUILD.gn
deleted file mode 100644
index 97fdd2dce89..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/src/js/views/camera/BUILD.gn
+++ /dev/null
@@ -1,77 +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")
-
-group("closure_compile") {
- deps = [ ":compile_resources" ]
-}
-
-js_type_check("compile_resources") {
- deps = [
- ":layout",
- ":modes",
- ":options",
- ":preview",
- ":recordtime",
- ":review_result",
- ":timertick",
- "../../mojo:device_operator",
- ]
-}
-
-js_library("layout") {
- deps = [
- "../..:chrome_util",
- "../..:type",
- ]
-}
-
-js_library("modes") {
- deps = [
- ":recordtime",
- "../..:sound",
- "../..:toast",
- "../..:type",
- "../..:util",
- "../../device:constraints_preferrer",
- "../../models:filenamer",
- "../../models:filesystem",
- "../../models:video_saver",
- "../../mojo:image_capture",
- "//media/capture/video/chromeos/mojom:cros_camera_js_library_for_compile",
- ]
-}
-
-js_library("options") {
- deps = [
- "../..:nav",
- "../..:type",
- "../..:util",
- "../../device:device_info_updater",
- "//components/chromeos_camera/common:camera_app_helper_js_library_for_compile",
- ]
-}
-
-js_library("preview") {
- deps = [
- "../..:chrome_util",
- "../..:nav",
- "../..:type",
- "//media/capture/video/chromeos/mojom:cros_camera_js_library_for_compile",
- ]
-}
-
-js_library("recordtime") {
-}
-
-js_library("review_result") {
- deps = [
- "../..:state",
- "../..:util",
- ]
-}
-
-js_library("timertick") {
-}
diff --git a/chromium/chrome/browser/resources/chromeos/camera/src/strings/BUILD.gn b/chromium/chrome/browser/resources/chromeos/camera/src/strings/BUILD.gn
deleted file mode 100644
index 6535e9e8673..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/src/strings/BUILD.gn
+++ /dev/null
@@ -1,71 +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("//chrome/common/features.gni")
-import("//tools/grit/grit_rule.gni")
-
-chrome_camera_app_dir = "$root_out_dir/resources/chromeos/camera"
-
-grit("camera_strings") {
- source = "camera_strings.grd"
- defines = chrome_grit_defines
- outputs = [
- "_locales/am/messages.json",
- "_locales/ar/messages.json",
- "_locales/bg/messages.json",
- "_locales/bn/messages.json",
- "_locales/ca/messages.json",
- "_locales/cs/messages.json",
- "_locales/da/messages.json",
- "_locales/de/messages.json",
- "_locales/el/messages.json",
- "_locales/en_GB/messages.json",
- "_locales/en/messages.json",
- "_locales/es/messages.json",
- "_locales/es_419/messages.json",
- "_locales/et/messages.json",
- "_locales/fa/messages.json",
- "_locales/fi/messages.json",
- "_locales/fil/messages.json",
- "_locales/fr/messages.json",
- "_locales/gu/messages.json",
- "_locales/he/messages.json",
- "_locales/hi/messages.json",
- "_locales/hr/messages.json",
- "_locales/hu/messages.json",
- "_locales/id/messages.json",
- "_locales/it/messages.json",
- "_locales/ja/messages.json",
- "_locales/kn/messages.json",
- "_locales/ko/messages.json",
- "_locales/lt/messages.json",
- "_locales/lv/messages.json",
- "_locales/ml/messages.json",
- "_locales/mr/messages.json",
- "_locales/ms/messages.json",
- "_locales/nl/messages.json",
- "_locales/nb/messages.json",
- "_locales/pl/messages.json",
- "_locales/pt_BR/messages.json",
- "_locales/pt_PT/messages.json",
- "_locales/ro/messages.json",
- "_locales/ru/messages.json",
- "_locales/sk/messages.json",
- "_locales/sl/messages.json",
- "_locales/sr/messages.json",
- "_locales/sv/messages.json",
- "_locales/sw/messages.json",
- "_locales/ta/messages.json",
- "_locales/te/messages.json",
- "_locales/th/messages.json",
- "_locales/tr/messages.json",
- "_locales/uk/messages.json",
- "_locales/vi/messages.json",
- "_locales/zh_CN/messages.json",
- "_locales/zh_TW/messages.json",
- ]
- output_dir = chrome_camera_app_dir
-
- resource_ids = ""
-}
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
deleted file mode 100644
index f22c312b325..00000000000
--- a/chromium/chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd
+++ /dev/null
@@ -1,366 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<grit base_dir="." current_release="1" latest_public_release="0"
- output_all_resource_defines="false" enc_check="möl" source_lang_id="en">
- <outputs>
- <output filename="_locales/am/messages.json" type="chrome_messages_json" lang="am"/>
- <output filename="_locales/ar/messages.json" type="chrome_messages_json" lang="ar"/>
- <output filename="_locales/bg/messages.json" type="chrome_messages_json" lang="bg"/>
- <output filename="_locales/bn/messages.json" type="chrome_messages_json" lang="bn"/>
- <output filename="_locales/ca/messages.json" type="chrome_messages_json" lang="ca"/>
- <output filename="_locales/cs/messages.json" type="chrome_messages_json" lang="cs"/>
- <output filename="_locales/da/messages.json" type="chrome_messages_json" lang="da"/>
- <output filename="_locales/de/messages.json" type="chrome_messages_json" lang="de"/>
- <output filename="_locales/el/messages.json" type="chrome_messages_json" lang="el"/>
- <output filename="_locales/en_GB/messages.json" type="chrome_messages_json" lang="en-GB"/>
- <output filename="_locales/en/messages.json" type="chrome_messages_json" lang="en"/>
- <output filename="_locales/es/messages.json" type="chrome_messages_json" lang="es"/>
- <output filename="_locales/es_419/messages.json" type="chrome_messages_json" lang="es-419"/>
- <output filename="_locales/et/messages.json" type="chrome_messages_json" lang="et"/>
- <output filename="_locales/fa/messages.json" type="chrome_messages_json" lang="fa"/>
- <output filename="_locales/fi/messages.json" type="chrome_messages_json" lang="fi"/>
- <output filename="_locales/fil/messages.json" type="chrome_messages_json" lang="fil"/>
- <output filename="_locales/fr/messages.json" type="chrome_messages_json" lang="fr"/>
- <output filename="_locales/gu/messages.json" type="chrome_messages_json" lang="gu"/>
- <output filename="_locales/he/messages.json" type="chrome_messages_json" lang="he"/>
- <output filename="_locales/hi/messages.json" type="chrome_messages_json" lang="hi"/>
- <output filename="_locales/hr/messages.json" type="chrome_messages_json" lang="hr"/>
- <output filename="_locales/hu/messages.json" type="chrome_messages_json" lang="hu"/>
- <output filename="_locales/id/messages.json" type="chrome_messages_json" lang="id"/>
- <output filename="_locales/it/messages.json" type="chrome_messages_json" lang="it"/>
- <output filename="_locales/ja/messages.json" type="chrome_messages_json" lang="ja"/>
- <output filename="_locales/kn/messages.json" type="chrome_messages_json" lang="kn"/>
- <output filename="_locales/ko/messages.json" type="chrome_messages_json" lang="ko"/>
- <output filename="_locales/lt/messages.json" type="chrome_messages_json" lang="lt"/>
- <output filename="_locales/lv/messages.json" type="chrome_messages_json" lang="lv"/>
- <output filename="_locales/ml/messages.json" type="chrome_messages_json" lang="ml"/>
- <output filename="_locales/mr/messages.json" type="chrome_messages_json" lang="mr"/>
- <output filename="_locales/ms/messages.json" type="chrome_messages_json" lang="ms"/>
- <output filename="_locales/nl/messages.json" type="chrome_messages_json" lang="nl"/>
- <output filename="_locales/nb/messages.json" type="chrome_messages_json" lang="no"/>
- <output filename="_locales/pl/messages.json" type="chrome_messages_json" lang="pl"/>
- <output filename="_locales/pt_BR/messages.json" type="chrome_messages_json" lang="pt-BR"/>
- <output filename="_locales/pt_PT/messages.json" type="chrome_messages_json" lang="pt-PT"/>
- <output filename="_locales/ro/messages.json" type="chrome_messages_json" lang="ro"/>
- <output filename="_locales/ru/messages.json" type="chrome_messages_json" lang="ru"/>
- <output filename="_locales/sk/messages.json" type="chrome_messages_json" lang="sk"/>
- <output filename="_locales/sl/messages.json" type="chrome_messages_json" lang="sl"/>
- <output filename="_locales/sr/messages.json" type="chrome_messages_json" lang="sr"/>
- <output filename="_locales/sv/messages.json" type="chrome_messages_json" lang="sv"/>
- <output filename="_locales/sw/messages.json" type="chrome_messages_json" lang="sw"/>
- <output filename="_locales/ta/messages.json" type="chrome_messages_json" lang="ta"/>
- <output filename="_locales/te/messages.json" type="chrome_messages_json" lang="te"/>
- <output filename="_locales/th/messages.json" type="chrome_messages_json" lang="th"/>
- <output filename="_locales/tr/messages.json" type="chrome_messages_json" lang="tr"/>
- <output filename="_locales/uk/messages.json" type="chrome_messages_json" lang="uk"/>
- <output filename="_locales/vi/messages.json" type="chrome_messages_json" lang="vi"/>
- <output filename="_locales/zh_CN/messages.json" type="chrome_messages_json" lang="zh-CN"/>
- <output filename="_locales/zh_TW/messages.json" type="chrome_messages_json" lang="zh-TW"/>
- </outputs>
- <translations>
- <file path="camera_strings_af.xtb" lang="af" />
- <file path="camera_strings_am.xtb" lang="am" />
- <file path="camera_strings_ar.xtb" lang="ar" />
- <file path="camera_strings_as.xtb" lang="as" />
- <file path="camera_strings_az.xtb" lang="az" />
- <file path="camera_strings_be.xtb" lang="be" />
- <file path="camera_strings_bg.xtb" lang="bg" />
- <file path="camera_strings_bn.xtb" lang="bn" />
- <file path="camera_strings_bs.xtb" lang="bs" />
- <file path="camera_strings_ca.xtb" lang="ca" />
- <file path="camera_strings_cs.xtb" lang="cs" />
- <file path="camera_strings_da.xtb" lang="da" />
- <file path="camera_strings_de.xtb" lang="de" />
- <file path="camera_strings_el.xtb" lang="el" />
- <file path="camera_strings_en-GB.xtb" lang="en-GB" />
- <file path="camera_strings_es.xtb" lang="es" />
- <file path="camera_strings_es-419.xtb" lang="es-419" />
- <file path="camera_strings_et.xtb" lang="et" />
- <file path="camera_strings_eu.xtb" lang="eu" />
- <file path="camera_strings_fa.xtb" lang="fa" />
- <file path="camera_strings_fi.xtb" lang="fi" />
- <file path="camera_strings_fil.xtb" lang="fil" />
- <file path="camera_strings_fr.xtb" lang="fr" />
- <file path="camera_strings_fr-CA.xtb" lang="fr-CA" />
- <file path="camera_strings_gl.xtb" lang="gl" />
- <file path="camera_strings_gu.xtb" lang="gu" />
- <file path="camera_strings_hi.xtb" lang="hi" />
- <file path="camera_strings_hr.xtb" lang="hr" />
- <file path="camera_strings_hu.xtb" lang="hu" />
- <file path="camera_strings_hy.xtb" lang="hy" />
- <file path="camera_strings_id.xtb" lang="id" />
- <file path="camera_strings_is.xtb" lang="is" />
- <file path="camera_strings_it.xtb" lang="it" />
- <!-- The translation console uses 'iw' for Hebrew, but we use 'he'. -->
- <file path="camera_strings_iw.xtb" lang="he" />
- <file path="camera_strings_ja.xtb" lang="ja" />
- <file path="camera_strings_ka.xtb" lang="ka" />
- <file path="camera_strings_kk.xtb" lang="kk" />
- <file path="camera_strings_km.xtb" lang="km" />
- <file path="camera_strings_kn.xtb" lang="kn" />
- <file path="camera_strings_ko.xtb" lang="ko" />
- <file path="camera_strings_ky.xtb" lang="ky" />
- <file path="camera_strings_lo.xtb" lang="lo" />
- <file path="camera_strings_lt.xtb" lang="lt" />
- <file path="camera_strings_lv.xtb" lang="lv" />
- <file path="camera_strings_mk.xtb" lang="mk" />
- <file path="camera_strings_ml.xtb" lang="ml" />
- <file path="camera_strings_mn.xtb" lang="mn" />
- <file path="camera_strings_mr.xtb" lang="mr" />
- <file path="camera_strings_ms.xtb" lang="ms" />
- <file path="camera_strings_my.xtb" lang="my" />
- <file path="camera_strings_ne.xtb" lang="ne" />
- <file path="camera_strings_nl.xtb" lang="nl" />
- <file path="camera_strings_no.xtb" lang="no" />
- <file path="camera_strings_or.xtb" lang="or" />
- <file path="camera_strings_pa.xtb" lang="pa" />
- <file path="camera_strings_pl.xtb" lang="pl" />
- <file path="camera_strings_pt-BR.xtb" lang="pt-BR" />
- <file path="camera_strings_pt-PT.xtb" lang="pt-PT" />
- <file path="camera_strings_ro.xtb" lang="ro" />
- <file path="camera_strings_ru.xtb" lang="ru" />
- <file path="camera_strings_si.xtb" lang="si" />
- <file path="camera_strings_sk.xtb" lang="sk" />
- <file path="camera_strings_sl.xtb" lang="sl" />
- <file path="camera_strings_sq.xtb" lang="sq" />
- <file path="camera_strings_sr.xtb" lang="sr" />
- <file path="camera_strings_sr-Latn.xtb" lang="sr-Latn" />
- <file path="camera_strings_sv.xtb" lang="sv" />
- <file path="camera_strings_sw.xtb" lang="sw" />
- <file path="camera_strings_ta.xtb" lang="ta" />
- <file path="camera_strings_te.xtb" lang="te" />
- <file path="camera_strings_th.xtb" lang="th" />
- <file path="camera_strings_tr.xtb" lang="tr" />
- <file path="camera_strings_uk.xtb" lang="uk" />
- <file path="camera_strings_ur.xtb" lang="ur" />
- <file path="camera_strings_uz.xtb" lang="uz" />
- <file path="camera_strings_vi.xtb" lang="vi" />
- <file path="camera_strings_zh-CN.xtb" lang="zh-CN" />
- <file path="camera_strings_zh-HK.xtb" lang="zh-HK" />
- <file path="camera_strings_zh-TW.xtb" lang="zh-TW" />
- <file path="camera_strings_zu.xtb" lang="zu" />
- </translations>
- <release allow_pseudo="false" seq="1">
- <messages fallback_to_english="true">
- <message desc="Label for timer-duration: 10 seconds." name="IDS_LABEL_TIMER_10S">
- 10 seconds
- </message>
- <message desc="Label for the help button." name="IDS_HELP_BUTTON">
- Help
- </message>
- <message desc="Label for the dismissing button in the dialog." name="IDS_DIALOG_CANCEL_BUTTON">
- Cancel
- </message>
- <message desc="Label for the printing button." name="IDS_PRINT_BUTTON">
- Print
- </message>
- <message desc="Label for the gallery button." name="IDS_GALLERY_BUTTON">
- Go to gallery
- </message>
- <message desc="Error message shown when saving/adding a image or video to the file system failed." name="IDS_ERROR_MSG_SAVE_FILE_FAILED">
- Unable to save the file
- </message>
- <message desc="Label for the exporting button." name="IDS_EXPORT_BUTTON">
- Export to disk
- </message>
- <message desc="Label for the checkbox to toggle the countdown timer." name="IDS_TOGGLE_TIMER_BUTTON">
- Timer
- </message>
- <message desc="Message shown before moving all photos and videos stored in the Camera App to the Downloads folder." name="IDS_MIGRATE_PICTURES_MSG">
- Photos and videos taken with the camera will be moved to the Downloads folder. You can access them in Files.
-
- Apps with storage permissions will have access to your photos and videos.
- </message>
- <message desc="Label for spoken feedback to read out grid-type: 3x3." name="IDS_ARIA_GRID_3X3">
- 3 by 3
- </message>
- <message desc="Label for the shutter button to start recording." name="IDS_RECORD_VIDEO_START_BUTTON">
- Start recording
- </message>
- <message desc="Label for the shutter button to stop recording." name="IDS_RECORD_VIDEO_STOP_BUTTON">
- Stop recording
- </message>
- <message desc="Label for the button to switch to next connected camera. Eg. switching from front facing to back facing, or a camera connected via USB. The button is shown only when more than one camera is connected." name="IDS_SWITCH_CAMERA_BUTTON">
- Switch to next camera
- </message>
- <message desc="Label for the button of timer-duration options." name="IDS_TIMER_DURATION_BUTTON">
- Timer duration
- </message>
- <message desc="Label for timer-duration: 3 seconds." name="IDS_LABEL_TIMER_3S">
- 3 seconds
- </message>
- <message desc="Status message for spoken feedback when video recording has been stopped." name="IDS_STATUS_MSG_RECORDING_STOPPED">
- Recording stopped
- </message>
- <message desc="Label for spoken feedback to read out grid-type: 4x4." name="IDS_ARIA_GRID_4X4">
- 4 by 4
- </message>
- <message desc="Label for for grid-type: 4x4." name="IDS_LABEL_GRID_4X4">
- 4 x 4
- </message>
- <message desc="Label for the button of camera-resolution options." name="IDS_CAMERA_RESOLUTION_BUTTON">
- Camera resolution
- </message>
- <message desc="Label for the button of photo-resolution options." name="IDS_PHOTO_RESOLUTION_BUTTON">
- Photo resolution
- </message>
- <message desc="Label for the button of video-resolution options." name="IDS_VIDEO_RESOLUTION_BUTTON">
- Video resolution
- </message>
- <message desc="Label for front camera." name="IDS_LABEL_FRONT_CAMERA">
- Front camera
- </message>
- <message desc="Label for back camera." name="IDS_LABEL_BACK_CAMERA">
- Back camera
- </message>
- <message desc="Label for external camera." name="IDS_LABEL_EXTERNAL_CAMERA">
- External camera
- </message>
- <message desc="Label for photo resolution options of specific resolution." name="IDS_LABEL_PHOTO_RESOLUTION">
- (<ph name="aspect_ratio_width">$1<ex>16</ex></ph>:<ph name="aspect_ratio_height">$2<ex>9</ex></ph>) <ph name="megapixel">$3<ex>0.9</ex></ph> mega pixel
- </message>
- <message desc="Label for detail photo resolution options of specific resolution." name="IDS_LABEL_DETAIL_PHOTO_RESOLUTION">
- (<ph name="aspect_ratio_width">$1<ex>16</ex></ph>:<ph name="aspect_ratio_height">$2<ex>9</ex></ph> - <ph name="width">$3<ex>1920</ex></ph>x<ph name="height">$4<ex>1080</ex></ph>) <ph name="megapixel">$5<ex>0.9</ex></ph> mega pixel
- </message>
- <message desc="Label for video resolution options of specific resolution." name="IDS_LABEL_VIDEO_RESOLUTION">
- HD <ph name="height">$1<ex>720</ex></ph>p (<ph name="width">$2<ex>1280</ex></ph>:<ph name="height">$1<ex>720</ex></ph>)
- </message>
- <message desc="Confirmation message before removing a selected item from the gallery. Expects a file name to be passed in." name="IDS_DELETE_CONFIRMATION_MSG">
- Do you really want to remove <ph name="file">$1<ex>IMG_20160520_000000.jpg</ex></ph>?
- </message>
- <message desc="Label for spoken feedback to read out switch to take photo mode button." name="IDS_SWITCH_TAKE_PHOTO_BUTTON">
- Switch to take photo
- </message>
- <message desc="Label for switch to take photo mode button." name="IDS_LABEL_SWITCH_TAKE_PHOTO_BUTTON">
- Photo
- </message>
- <message desc="Label for the checkbox to toggle the grid shown on preview." name="IDS_TOGGLE_GRID_BUTTON">
- Grid
- </message>
- <message desc="Label for the shutter button to take photo." name="IDS_TAKE_PHOTO_BUTTON">
- Take photo
- </message>
- <message desc="Error message shown when it was impossible to connect to the camera due to unavailability." name="IDS_ERROR_MSG_NO_CAMERA">
- Your camera is currently unavailable.
- Please check if the camera is properly connected.
- </message>
- <message desc="Error message shown when failing to start recording video." name="IDS_ERROR_MSG_RECORD_START_FAILED">
- Unable to start recording
- </message>
- <message desc="Label for the checkbox to toggle the microphone for recording video." name="IDS_TOGGLE_MIC_BUTTON">
- Microphone
- </message>
- <message desc="Label for the button of expert mode options." name="IDS_EXPERT_MODE_BUTTON">
- Expert mode
- </message>
- <message desc="Label for expert mode option: preview metadata." name="IDS_EXPERT_PREVIEW_METADATA">
- Preview metadata
- </message>
- <message desc="Label for expert mode option: save metadata." name="IDS_EXPERT_SAVE_METADATA">
- Save metadata
- </message>
- <message desc="Label for expert mode option: print performance logs." name="IDS_EXPERT_PRINT_PERFORMANCE_LOGS">
- Print performance logs
- </message>
- <message desc="Error message when the device does not support expert mode but tries to enable it." name="IDS_ERROR_MSG_EXPERT_MODE_NOT_SUPPORTED">
- Expert mode is not supported on this device
- </message>
- <message desc="Label for the feedback button." name="IDS_FEEDBACK_BUTTON">
- Send feedback
- </message>
- <message desc="Error message shown when failing to take photo." name="IDS_ERROR_MSG_TAKE_PHOTO_FAILED">
- Unable to take photo
- </message>
- <message desc="Error message shown when failing to take portrait photo." name="IDS_ERROR_MSG_TAKE_PORTRAIT_PHOTO_FAILED">
- Unable to take portrait photo
- </message>
- <message desc="Short description of the Camera App." name="IDS_DESCRIPTION">
- Take photos and record videos with your camera.
- </message>
- <message desc="Label for for grid-type: 3x3." name="IDS_LABEL_GRID_3X3">
- 3 x 3
- </message>
- <message desc="Label for the shutter button to cancel countdown timer and stop taking photo." name="IDS_TAKE_PHOTO_CANCEL_BUTTON">
- Stop taking photo
- </message>
- <message desc="Label for the delete button." name="IDS_DELETE_BUTTON">
- Delete
- </message>
- <message desc="Error message shown when no data is recorded for a recording and it won't be added to the gallery." name="IDS_ERROR_MSG_EMPTY_RECORDING">
- Nothing recorded
- </message>
- <message desc="Confirmation message before removing multiple selected items from the gallery. Expects a file count to be passed in." name="IDS_DELETE_MULTI_CONFIRMATION_MSG">
- Do you really want to remove <ph name="count">$1<ex>20</ex></ph> items?
- </message>
- <message desc="Text to speech label for the gallery list." name="IDS_GALLERY_IMAGES">
- Gallery images
- </message>
- <message desc="Error message shown when exporting to an external directory failed. Expects a file name to be passed in." name="IDS_ERROR_MSG_GALLERY_EXPORT_FAILED">
- Unable to export <ph name="file">$1<ex>IMG_20160520_000000.jpg</ex></ph>
- </message>
- <message desc="Status message for spoken feedback when switching over to another camera." name="IDS_STATUS_MSG_CAMERA_SWITCHED">
- <ph name="camera">$1<ex>USB WebCam (12ab:5678) User-facing</ex></ph> active
- </message>
- <message desc="Name of the Camera App." name="IDS_NAME">
- Camera
- </message>
- <message desc="Error message shown when failing to read or write the file system." name="IDS_ERROR_MSG_FILE_SYSTEM_FAILED">
- File system errors.
- </message>
- <message desc="Label for the settings button." name="IDS_SETTINGS_BUTTON">
- Settings
- </message>
- <message desc="Label for the accepting button in the dialog." name="IDS_DIALOG_OK_BUTTON">
- OK
- </message>
- <message desc="Label for grid-type: golden ratio." name="IDS_LABEL_GRID_GOLDEN">
- Golden ratio
- </message>
- <message desc="Label for spoken feedback to read out switch to record video mode button." name="IDS_SWITCH_RECORD_VIDEO_BUTTON">
- Switch to record video
- </message>
- <message desc="Label for switch to record video mode button." name="IDS_LABEL_SWITCH_RECORD_VIDEO_BUTTON">
- Video
- </message>
- <message desc="Label for the checkbox to toggle the preview mirroring. Eg. if mirroring is toggled on, preview will be flipped horizontally." name="IDS_TOGGLE_MIRROR_BUTTON">
- Mirroring
- </message>
- <message desc="Label for the button of grid-type options." name="IDS_GRID_TYPE_BUTTON">
- Grid type
- </message>
- <message desc="Label showing current state of 30 FPS on tooltip of toggle 60 FPS recording checkbox." name="IDS_LABEL_30FPS">
- 30 FPS
- </message>
- <message desc="Label showing current state of 60 FPS on tooltip of toggle 60 FPS recording checkbox." name="IDS_LABEL_60FPS">
- 60 FPS
- </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>
- <message desc="Label for spoken feedback to read out switch to take square photo mode button." name="IDS_SWITCH_TAKE_SQUARE_PHOTO_BUTTON">
- Switch to take square photo
- </message>
- <message desc="Label for switch to take square photo mode button." name="IDS_LABEL_SWITCH_TAKE_SQUARE_PHOTO_BUTTON">
- Square
- </message>
- <message desc="Label for spoken feedback to read out switch to take portrait photo mode button." name="IDS_SWITCH_TAKE_PORTRAIT_PHOTO_BUTTON">
- Switch to take portrait photo
- </message>
- <message desc="Label for switch to take portrait photo mode button." name="IDS_LABEL_SWITCH_TAKE_PORTRAIT_PHOTO_BUTTON">
- Portrait
- </message>
- <message desc="Label for the confirm button to confirm with the reviewed photo or video." name="IDS_CONFIRM_REVIEW_BUTTON">
- Confirm
- </message>
- <message desc="Label for the cancel button to cancel with the reviewed photo or video." name="IDS_CANCEL_REVIEW_BUTTON">
- Cancel
- </message>
- <message desc="Label for the button to play video." name="IDS_PLAY_RESULT_VIDEO_BUTTON">
- Play video
- </message>
- </messages>
- </release>
-</grit>
diff --git a/chromium/chrome/browser/resources/chromeos/internet_config_dialog/BUILD.gn b/chromium/chrome/browser/resources/chromeos/internet_config_dialog/BUILD.gn
index f899962417a..af80c45ce88 100644
--- a/chromium/chrome/browser/resources/chromeos/internet_config_dialog/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/internet_config_dialog/BUILD.gn
@@ -29,9 +29,9 @@ js_library("internet_config_dialog") {
"//ui/webui/resources/js:assert",
"//ui/webui/resources/js:i18n_behavior",
]
- externs_list = [
- "$externs_path/chrome_send.js",
- "$externs_path/networking_private.js",
- ]
+ externs_list = chrome_extension_public_externs + [
+ "$externs_path/chrome_send.js",
+ "$externs_path/networking_private.js",
+ ]
extra_sources = [ "$interfaces_path/networking_private_interface.js" ]
}
diff --git a/chromium/chrome/browser/resources/chromeos/login/BUILD.gn b/chromium/chrome/browser/resources/chromeos/login/BUILD.gn
index c453524aa61..6e02f0073a2 100644
--- a/chromium/chrome/browser/resources/chromeos/login/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/login/BUILD.gn
@@ -17,7 +17,6 @@ js_type_check("closure_compile") {
":gaia_buttons",
":gaia_card",
":gaia_header",
- ":gaia_input",
":gaia_input_form",
":gaia_password_changed",
":gesture_navigation",
@@ -141,11 +140,13 @@ js_library("gaia_header") {
js_library("gaia_input_form") {
}
-js_library("gaia_input") {
-}
-
js_library("gaia_password_changed") {
- deps = [ "components:oobe_i18n_behavior" ]
+ deps = [
+ "components:login_screen_behavior",
+ "components:multi_step_behavior",
+ "components:oobe_dialog_host_behavior",
+ "components:oobe_i18n_behavior",
+ ]
}
js_library("gesture_navigation") {
@@ -186,6 +187,15 @@ js_library("offline_gaia") {
js_library("oobe_a11y_option") {
}
+js_library("oobe_adb_sideloading_screen") {
+ deps = [
+ "components:login_screen_behavior",
+ "components:multi_step_behavior",
+ "components:oobe_dialog_host_behavior",
+ "components:oobe_i18n_behavior",
+ ]
+}
+
js_library("oobe_enable_kiosk") {
deps = [
"components:login_screen_behavior",
@@ -229,6 +239,7 @@ js_library("oobe_supervision_transition") {
js_library("oobe_update") {
deps = [
+ "components:login_screen_behavior",
"components:oobe_dialog_host_behavior",
"components:oobe_i18n_behavior",
]
@@ -236,13 +247,19 @@ js_library("oobe_update") {
js_library("recommend_apps") {
deps = [
+ "components:login_screen_behavior",
+ "components:multi_step_behavior",
"components:oobe_dialog_host_behavior",
"components:oobe_i18n_behavior",
+ "components:oobe_types",
]
}
js_library("saml_confirm_password") {
- deps = [ "components:oobe_i18n_behavior" ]
+ deps = [
+ "components:oobe_dialog_host_behavior",
+ "components:oobe_i18n_behavior",
+ ]
}
js_library("sync_consent") {
diff --git a/chromium/chrome/browser/resources/chromeos/login/components/BUILD.gn b/chromium/chrome/browser/resources/chromeos/login/components/BUILD.gn
index 59876172124..a104ef10d39 100644
--- a/chromium/chrome/browser/resources/chromeos/login/components/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/login/components/BUILD.gn
@@ -11,6 +11,7 @@ js_type_check("closure_compile") {
":hd-iron-icon",
":html-echo",
":login_screen_behavior",
+ ":multi_step_behavior",
":oobe_buttons",
":oobe_dialog",
":oobe_dialog_host_behavior",
@@ -49,6 +50,9 @@ js_library("login_screen_behavior") {
]
}
+js_library("multi_step_behavior") {
+}
+
js_library("oobe_buttons") {
deps = [ ":oobe_i18n_behavior" ]
}
@@ -56,9 +60,9 @@ js_library("oobe_buttons") {
js_library("oobe_dialog") {
deps = [
":fake_oobe",
- "//ui/webui/resources/cr_elements:cr_scrollable_behavior",
"//ui/webui/resources/cr_elements/cr_lazy_render:cr_lazy_render",
]
+ externs_list = [ "$externs_path/pending.js" ]
}
js_library("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 6060563b75e..85383abad38 100644
--- a/chromium/chrome/browser/resources/chromeos/network_ui/BUILD.gn
+++ b/chromium/chrome/browser/resources/chromeos/network_ui/BUILD.gn
@@ -5,18 +5,43 @@
import("//third_party/closure_compiler/compile_js.gni")
js_type_check("closure_compile") {
- deps = [ ":network_ui" ]
+ deps = [
+ ":network_logs_ui",
+ ":network_state_ui",
+ ":network_ui",
+ ":network_ui_browser_proxy",
+ ]
}
js_library("network_ui") {
deps = [
+ ":network_ui_browser_proxy",
+ "//ui/webui/resources/cr_components/chromeos/network:onc_mojo",
+ "//ui/webui/resources/js:i18n_behavior",
+ "//ui/webui/resources/js:load_time_data",
+ ]
+}
+
+js_library("network_logs_ui") {
+ deps = [
+ ":network_ui_browser_proxy",
+ "//ui/webui/resources/js:i18n_behavior",
+ ]
+}
+
+js_library("network_state_ui") {
+ deps = [
+ ":network_ui_browser_proxy",
"//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_components/chromeos/network:network_icon",
"//ui/webui/resources/cr_components/chromeos/network:network_list",
"//ui/webui/resources/cr_components/chromeos/network:onc_mojo",
- "//ui/webui/resources/js:load_time_data",
- "//ui/webui/resources/js:util",
]
- externs_list = [ "$externs_path/networking_private.js" ]
+ externs_list = chrome_extension_public_externs +
+ [ "$externs_path/networking_private.js" ]
+}
+
+js_library("network_ui_browser_proxy") {
+ deps = [ "//ui/webui/resources/js:cr" ]
}
diff --git a/chromium/chrome/browser/resources/component_extension_resources.grd b/chromium/chrome/browser/resources/component_extension_resources.grd
index cf1d5e9e58b..7989a4c8ebe 100644
--- a/chromium/chrome/browser/resources/component_extension_resources.grd
+++ b/chromium/chrome/browser/resources/component_extension_resources.grd
@@ -101,8 +101,10 @@
<include name="IDR_PDF_INDEX_HTML" file="pdf/index.html" type="BINDATA" preprocess="true" />
<include name="IDR_PDF_INDEX_CSS" file="pdf/index.css" type="BINDATA" />
<include name="IDR_PDF_MAIN_JS" file="pdf/main.js" type="BINDATA" preprocess="true" />
- <include name="IDR_PDF_MAIN_UTIL_JS" file="pdf/main_util.js" type="BINDATA" />
- <include name="IDR_PDF_PDF_VIEWER_JS" file="pdf/pdf_viewer.js" type="BINDATA" />
+ <include name="IDR_PDF_PDF_VIEWER_UTILS_JS" file="pdf/pdf_viewer_utils.js" type="BINDATA" />
+ <include name="IDR_PDF_PDF_VIEWER_BASE_JS" file="pdf/pdf_viewer_base.js" type="BINDATA" />
+ <include name="IDR_PDF_PDF_VIEWER_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/pdf_viewer.js" use_base_dir="false" type="BINDATA" preprocess="true" />
+ <include name="IDR_PDF_PDF_VIEWER_SHARED_STYLE_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/pdf_viewer_shared_style.js" use_base_dir="false" type="BINDATA" />
<include name="IDR_PDF_BOOKMARK_TYPE_JS" file="pdf/bookmark_type.js" type="BINDATA" />
<include name="IDR_PDF_CONSTANTS_JS" file="pdf/constants.js" type="BINDATA" />
<include name="IDR_PDF_CONTROLLER_JS" file="pdf/controller.js" type="BINDATA" />
@@ -122,6 +124,7 @@
<include name="IDR_PDF_VIEWER_BOOKMARK_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-bookmark.js" use_base_dir="false" type="BINDATA" />
<include name="IDR_PDF_VIEWER_ERROR_SCREEN_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-error-screen.js" use_base_dir="false" type="BINDATA" />
<if expr="chromeos">
+ <include name="IDR_PDF_VIEWER_INK_CONTROLLER_JS" file="pdf/ink_controller.js" type="BINDATA" />
<include name="IDR_PDF_VIEWER_INK_INDEX_HTML" file="pdf/ink/index.html" type="BINDATA" />
<include name="IDR_PDF_VIEWER_INK_INK_API_JS" file="pdf/ink/ink_api.js" type="BINDATA" />
<include name="IDR_PDF_VIEWER_INK_HOST_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-ink-host.js" use_base_dir="false" type="BINDATA" />
@@ -131,6 +134,7 @@
<include name="IDR_PDF_VIEWER_PAGE_SELECTOR_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-page-selector.js" use_base_dir="false" type="BINDATA" />
<include name="IDR_PDF_VIEWER_PASSWORD_SCREEN_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-password-screen.js" use_base_dir="false" type="BINDATA" />
<include name="IDR_PDF_VIEWER_PDF_TOOLBAR_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar.js" use_base_dir="false" type="BINDATA" preprocess="true"/>
+ <include name="IDR_PDF_VIEWER_PDF_TOOLBAR_NEW_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.js" use_base_dir="false" type="BINDATA" preprocess="true"/>
<include name="IDR_PDF_VIEWER_TOOLBAR_DROPDOWN_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown.js" use_base_dir="false" type="BINDATA" />
<include name="IDR_PDF_VIEWER_ZOOM_BUTTON_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-zoom-button.js" use_base_dir="false" type="BINDATA" />
<include name="IDR_PDF_VIEWER_ZOOM_SELECTOR_JS" file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar.js" use_base_dir="false" type="BINDATA" />
diff --git a/chromium/chrome/browser/resources/components/components.js b/chromium/chrome/browser/resources/components/components.js
index f50d4b36097..e761310541f 100644
--- a/chromium/chrome/browser/resources/components/components.js
+++ b/chromium/chrome/browser/resources/components/components.js
@@ -26,7 +26,7 @@ function renderTemplate(componentsData) {
// This is the javascript code that processes the template:
const input = new JsEvalContext(componentsData);
const output = $('component-template').cloneNode(true);
- $('component-placeholder').innerHTML = '';
+ $('component-placeholder').innerHTML = trustedTypes.emptyHTML;
$('component-placeholder').appendChild(output);
jstProcess(input, output);
output.removeAttribute('hidden');
diff --git a/chromium/chrome/browser/resources/conflicts/about_conflicts.html b/chromium/chrome/browser/resources/conflicts/about_conflicts.html
index 83c277a0bbe..855f25c63ff 100644
--- a/chromium/chrome/browser/resources/conflicts/about_conflicts.html
+++ b/chromium/chrome/browser/resources/conflicts/about_conflicts.html
@@ -208,7 +208,7 @@ html[dir=rtl] .clearing {
jsselect="moduleList" class="module">
<td valign="top" class="datacell">
<span dir="ltr"
- jsvalues=".innerHTML:description"
+ jsvalues=".textContent:description"
class="clearing nowrap"></span>
</td>
<td valign="top" class="datacell">
diff --git a/chromium/chrome/browser/resources/cryptotoken/enroller.js b/chromium/chrome/browser/resources/cryptotoken/enroller.js
index 4088338c9e8..12440488154 100644
--- a/chromium/chrome/browser/resources/cryptotoken/enroller.js
+++ b/chromium/chrome/browser/resources/cryptotoken/enroller.js
@@ -869,14 +869,10 @@ Enroller.prototype.doRegisterWebAuthn_ = function(appId, challenge, request) {
return;
}
- const attestationPreference =
- conveyancePreference(challenge) == ConveyancePreference.DIRECT ?
- WebAuthnAttestationConveyancePreference.DIRECT :
- WebAuthnAttestationConveyancePreference.NONE;
-
if (!chrome.cryptotokenPrivate) {
this.doRegisterWebAuthnContinue_(
- appId, encodedChallenge, request, attestationPreference);
+ appId, encodedChallenge, request,
+ WebAuthnAttestationConveyancePreference.DIRECT);
return;
}
@@ -887,7 +883,7 @@ Enroller.prototype.doRegisterWebAuthn_ = function(appId, challenge, request) {
appId, encodedChallenge, request,
enterprise_context ?
WebAuthnAttestationConveyancePreference.ENTERPRISE :
- attestationPreference);
+ WebAuthnAttestationConveyancePreference.DIRECT);
});
};
diff --git a/chromium/chrome/browser/resources/default_apps/external_extensions.json b/chromium/chrome/browser/resources/default_apps/external_extensions.json
index 59a0f9ad07f..9449bc103f2 100644
--- a/chromium/chrome/browser/resources/default_apps/external_extensions.json
+++ b/chromium/chrome/browser/resources/default_apps/external_extensions.json
@@ -7,8 +7,7 @@
{
"blpcfgokakmgnkcojhhkbfbldkacnbeo" : {
"external_crx": "youtube.crx",
- "external_version": "4.2.5",
- "is_bookmark_app": true
+ "external_version": "4.2.5"
},
"pjkljhegncpnkpknbcohdijeoejaedia" : {
"external_crx": "gmail.crx",
diff --git a/chromium/chrome/browser/resources/discards/OWNERS b/chromium/chrome/browser/resources/discards/OWNERS
index dcd54320481..6ef4e6df1e5 100644
--- a/chromium/chrome/browser/resources/discards/OWNERS
+++ b/chromium/chrome/browser/resources/discards/OWNERS
@@ -1 +1 @@
-file://services/resource_coordinator/OWNERS
+file://components/performance_manager/OWNERS
diff --git a/chromium/chrome/browser/resources/discards/discards_tab.html b/chromium/chrome/browser/resources/discards/discards_tab.html
index b91684d1b52..c4d1e25566a 100644
--- a/chromium/chrome/browser/resources/discards/discards_tab.html
+++ b/chromium/chrome/browser/resources/discards/discards_tab.html
@@ -206,11 +206,6 @@
</div>
</div>
</th>
- <th data-sort-key="canFreeze" on-click="onSortClick">
- <div class="header-cell-container">
- Can freeze?
- </div>
- </th>
<th data-sort-key="discardCount" on-click="onSortClick">
<div class="header-cell-container">
<div>
@@ -258,19 +253,6 @@
<td>[[visibilityToString_(item.visibility)]]</td>
<td>[[loadingStateToString_(item.loadingState)]]</td>
<td>[[getLifeCycleState_(item)]]</td>
- <td class="boolean-cell">
- <div>[[boolToString_(item.canFreeze)]]</div>
- <div is="action-link" class="tooltip-container"
- disabled$="[[!hasCannotFreezeReasons_(item)]]">
- [View Reason]
- <div class="tooltip">
- <template is="dom-repeat"
- items="[[item.cannotFreezeReasons]]">
- <div>[[item]]</div>
- </template>
- </div>
- </div>
- </td>
<td>[[item.discardCount]]</td>
<td class="boolean-cell">
<div>[[boolToString_(item.isAutoDiscardable)]]</div>
@@ -286,8 +268,6 @@
<div is="action-link" on-click="loadTab_"
disabled$="[[!canLoad_(item)]]">
[Load]</div>
- <div is="action-link" on-click="freezeTab_"
- disabled$="[[!canFreeze_(item)]]">[Freeze]</div>
<div is="action-link" on-click="urgentDiscardTab_"
disabled$="[[!canDiscard_(item)]]">
[Urgent Discard]
diff --git a/chromium/chrome/browser/resources/discards/discards_tab.js b/chromium/chrome/browser/resources/discards/discards_tab.js
index 2fef49056b5..963023218e5 100644
--- a/chromium/chrome/browser/resources/discards/discards_tab.js
+++ b/chromium/chrome/browser/resources/discards/discards_tab.js
@@ -37,7 +37,7 @@ export function compareTabDiscardsInfos(sortKey, a, b) {
}
// Compares boolean fields.
- if (['canFreeze', 'isAutoDiscardable'].includes(sortKey)) {
+ if (['isAutoDiscardable'].includes(sortKey)) {
if (val1 === val2) {
return 0;
}
@@ -219,10 +219,6 @@ Polymer({
return pageLifecycleStateFromVisibilityAndFocus();
case mojom.LifecycleUnitState.THROTTLED:
return pageLifecycleStateFromVisibilityAndFocus() + ' (throttled)';
- case mojom.LifecycleUnitState.PENDING_FREEZE:
- return pageLifecycleStateFromVisibilityAndFocus() + ' (pending frozen)';
- case mojom.LifecycleUnitState.FROZEN:
- return 'frozen';
case mojom.LifecycleUnitState.DISCARDED:
return 'discarded (' + this.discardReasonToString_(reason) + ')' +
((reason === mojom.LifecycleUnitDiscardReason.URGENT) ? ' at ' +
@@ -231,8 +227,6 @@ Polymer({
(new Date(stateChangeTime.microseconds / 1000))
.toLocaleString() :
'');
- case mojom.LifecycleUnitState.PENDING_UNFREEZE:
- return 'frozen (pending unfreeze)';
}
assertNotReached('Unknown lifecycle state: ' + state);
},
@@ -331,16 +325,6 @@ Polymer({
},
/**
- * Tests whether an item has reasons why it cannot be frozen.
- * @param {discards.mojom.TabDiscardsInfo} item The item in question.
- * @return {boolean} true iff there are reasons why the item cannot be
- * frozen.
- * @private
- */
- hasCannotFreezeReasons_(item) {
- return item.cannotFreezeReasons.length !== 0;
- },
- /**
* Tests whether an item has reasons why it cannot be discarded.
* @param {discards.mojom.TabDiscardsInfo} item The item in question.
* @return {boolean} true iff there are reasons why the item cannot be
@@ -362,27 +346,6 @@ Polymer({
},
/**
- * Tests whether an item can be frozen.
- * @param {discards.mojom.TabDiscardsInfo} item The item in question.
- * @return {boolean} true iff the item can be frozen.
- * @private
- */
- canFreeze_(item) {
- if (item.visibility === discards.mojom.LifecycleUnitVisibility.HIDDEN ||
- item.visibility === discards.mojom.LifecycleUnitVisibility.OCCLUDED) {
- // Only tabs that aren't visible can be frozen for now.
- switch (item.state) {
- case mojom.LifecycleUnitState.DISCARDED:
- case mojom.LifecycleUnitState.FROZEN:
- case mojom.LifecycleUnitState.PENDING_FREEZE:
- return false;
- }
- return true;
- }
- return false;
- },
-
- /**
* Tests whether an item can be discarded.
* @param {discards.mojom.TabDiscardsInfo} item The item in question.
* @return {boolean} true iff the item can be discarded.
@@ -423,15 +386,6 @@ Polymer({
},
/**
- * Event handler that freezes a tab.
- * @param {Event} e The event.
- * @private
- */
- freezeTab_(e) {
- this.discardsDetailsProvider_.freezeById(e.model.item.id);
- },
-
- /**
* Event handler that discards a given tab urgently.
* @param {Event} e The event.
* @private
diff --git a/chromium/chrome/browser/resources/discards/graph_doc.js b/chromium/chrome/browser/resources/discards/graph_doc.js
index 37b9bc7d46d..e3ce7e1d7f8 100644
--- a/chromium/chrome/browser/resources/discards/graph_doc.js
+++ b/chromium/chrome/browser/resources/discards/graph_doc.js
@@ -2,25 +2,42 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+// Radius of a node circle.
+const /** number */ kNodeRadius = 6;
+
// Target y position for page nodes.
-const kPageNodesTargetY = 20;
+const /** number */ kPageNodesTargetY = 20;
// Range occupied by page nodes at the top of the graph view.
-const kPageNodesYRange = 100;
+const /** number */ kPageNodesYRange = 100;
// Range occupied by process nodes at the bottom of the graph view.
-const kProcessNodesYRange = 100;
+const /** number */ kProcessNodesYRange = 100;
// Range occupied by worker nodes at the bottom of the graph view, above
// process nodes.
-const kWorkerNodesYRange = 200;
+const /** number */ kWorkerNodesYRange = 200;
// Target y position for frame nodes.
-const kFrameNodesTargetY = kPageNodesYRange + 50;
+const /** number */ kFrameNodesTargetY = kPageNodesYRange + 50;
// Range that frame nodes cannot enter at the top/bottom of the graph view.
-const kFrameNodesTopMargin = kPageNodesYRange;
-const kFrameNodesBottomMargin = kWorkerNodesYRange + 50;
+const /** number */ kFrameNodesTopMargin = kPageNodesYRange;
+const /** number */ kFrameNodesBottomMargin = kWorkerNodesYRange + 50;
+
+// The maximum strength of a boundary force.
+// According to https://github.com/d3/d3-force#positioning, strength values
+// outside the range [0,1] are "not recommended".
+const /** number */ kMaxBoundaryStrength = 1;
+
+// The strength of a high Y-force. This is appropriate for forces that
+// strongly pull towards an attractor, but can still be overridden by the
+// strongest force.
+const /** number */ kHighYStrength = 0.9;
+
+// The strength of a weak Y-force. This is appropriate for forces that exert
+// some influence but can be easily overridden.
+const /** number */ kWeakYStrength = 0.1;
class ToolTip {
/**
@@ -271,10 +288,18 @@ class GraphNode {
/**
* @return {number} The strength of the force that pulls the node towards
- * its target y position.
+ * its target y position.
+ */
+ get targetYPositionStrength() {
+ return kWeakYStrength;
+ }
+
+ /**
+ * @return {number} A scaling factor applied to the strength of links to this
+ * node.
*/
- targetYPositionStrength() {
- return 0.1;
+ get linkStrengthScalingFactor() {
+ return 1;
}
/**
@@ -287,12 +312,23 @@ class GraphNode {
}
/** @return {number} The strength of the repulsion force with other nodes. */
- manyBodyStrength() {
+ get manyBodyStrength() {
return -200;
}
- /** @return {!Array<number>} */
- linkTargets() {
+ /** @return {!Array<number>} an array of node ids. */
+ get linkTargets() {
+ return [];
+ }
+
+ /**
+ * Dashed links express ownership relationships. An object can own multiple
+ * things, but be owned by exactly one (per relationship type). As such, the
+ * relationship is expressed on the *owned* object. These links are drawn with
+ * an arrow at the beginning of the link, pointing to the owned object.
+ * @return {!Array<number>} an array of node ids.
+ */
+ get dashedLinkTargets() {
return [];
}
@@ -322,8 +358,18 @@ class PageNode extends GraphNode {
}
/** @override */
- targetYPositionStrength() {
- return 10;
+ get targetYPositionStrength() {
+ // Gravitate strongly towards the top of the graph. Can be overridden by
+ // the bounding force which uses kMaxBoundaryStrength.
+ return kHighYStrength;
+ }
+
+ /** @override */
+ get linkStrengthScalingFactor() {
+ // Give links from frame nodes to page nodes less weight than links between
+ // frame nodes, so the that Y forces pulling page nodes into their area can
+ // dominate over link forces pulling them towards frame nodes.
+ return 0.5;
}
/** override */
@@ -332,9 +378,17 @@ class PageNode extends GraphNode {
}
/** override */
- manyBodyStrength() {
+ get manyBodyStrength() {
return -600;
}
+
+ /** override */
+ get dashedLinkTargets() {
+ if (this.page.openerFrameId) {
+ return [this.page.openerFrameId];
+ }
+ return [];
+ }
}
class FrameNode extends GraphNode {
@@ -362,7 +416,7 @@ class FrameNode extends GraphNode {
}
/** override */
- linkTargets() {
+ get linkTargets() {
// Only link to the page if there isn't a parent frame.
return [
this.frame.parentFrameId || this.frame.pageId, this.frame.processId
@@ -386,8 +440,18 @@ class ProcessNode extends GraphNode {
}
/** @return {number} */
- targetYPositionStrength() {
- return 10;
+ get targetYPositionStrength() {
+ // Gravitate strongly towards the bottom of the graph. Can be overridden by
+ // the bounding force which uses kMaxBoundaryStrength.
+ return kHighYStrength;
+ }
+
+ /** @override */
+ get linkStrengthScalingFactor() {
+ // Give links to process nodes less weight than links between frame nodes,
+ // so the that Y forces pulling process nodes into their area can dominate
+ // over link forces pulling them towards frame nodes.
+ return 0.5;
}
/** override */
@@ -396,7 +460,7 @@ class ProcessNode extends GraphNode {
}
/** override */
- manyBodyStrength() {
+ get manyBodyStrength() {
return -600;
}
}
@@ -417,8 +481,10 @@ class WorkerNode extends GraphNode {
}
/** @return {number} */
- targetYPositionStrength() {
- return 10;
+ get targetYPositionStrength() {
+ // Gravitate strongly towards the worker area of the graph. Can be
+ // overridden by the bounding force which uses kMaxBoundaryStrength.
+ return kHighYStrength;
}
/** override */
@@ -429,12 +495,12 @@ class WorkerNode extends GraphNode {
}
/** override */
- manyBodyStrength() {
+ get manyBodyStrength() {
return -600;
}
/** override */
- linkTargets() {
+ get linkTargets() {
// Link the process, in addition to all the client and child workers.
return [
this.worker.processId, ...this.worker.clientFrameIds,
@@ -444,14 +510,19 @@ class WorkerNode extends GraphNode {
}
/**
- * A force that bounds GraphNodes |allowedYRange| in Y.
+ * A force that bounds GraphNodes |allowedYRange| in Y,
+ * as well as bounding them to stay in page bounds in X.
* @param {number} graphHeight
+ * @param {number} graphWidth
*/
-function boundingForce(graphHeight) {
+function boundingForce(graphHeight, graphWidth) {
/** @type {!Array<!GraphNode>} */
let nodes = [];
/** @type {!Array<!Array>} */
let bounds = [];
+ const xBounds = [2 * kNodeRadius, graphWidth - 2 * kNodeRadius];
+ const boundPosition = (pos, bound) =>
+ Math.max(bound[0], Math.min(pos, bound[1]));
/** @param {number} alpha */
function force(alpha) {
@@ -459,12 +530,23 @@ function boundingForce(graphHeight) {
for (let i = 0; i < n; ++i) {
const bound = bounds[i];
const node = nodes[i];
- const yOld = node.y;
- const yNew = Math.max(bound[0], Math.min(yOld, bound[1]));
- if (yOld !== yNew) {
- node.y = yNew;
- // Zero the velocity of clamped nodes.
- node.vy = 0;
+
+ // Calculate where the node will end up after movement. If it will be out
+ // of bounds apply a counter-force to bring it back in.
+ const yNextPosition = node.y + node.vy;
+ const yBoundedPosition = boundPosition(yNextPosition, bound);
+ if (yNextPosition !== yBoundedPosition) {
+ // Do not include alpha because we want to be strongly repelled from
+ // the boundary even if alpha has decayed.
+ node.vy += (yBoundedPosition - yNextPosition) * kMaxBoundaryStrength;
+ }
+
+ const xNextPosition = node.x + node.vx;
+ const xBoundedPosition = boundPosition(xNextPosition, xBounds);
+ if (xNextPosition !== xBoundedPosition) {
+ // Do not include alpha because we want to be strongly repelled from
+ // the boundary even if alpha has decayed.
+ node.vx += (xBoundedPosition - xNextPosition) * kMaxBoundaryStrength;
}
}
}
@@ -472,7 +554,13 @@ function boundingForce(graphHeight) {
/** @param {!Array<!GraphNode>} n */
force.initialize = function(n) {
nodes = n;
- bounds = nodes.map(node => node.allowedYRange(graphHeight));
+ bounds = nodes.map(node => {
+ const nodeBounds = node.allowedYRange(graphHeight);
+ // Leave space for the node circle plus a small border.
+ nodeBounds[0] += kNodeRadius * 2;
+ nodeBounds[1] -= kNodeRadius * 2;
+ return nodeBounds;
+ });
};
return force;
@@ -533,6 +621,12 @@ class Graph {
*/
this.linkGroup_ = null;
+ /**
+ * A selection for the top-level <g> node that contains all dashed edges.
+ * @private {d3.selection}
+ */
+ this.dashedLinkGroup_ = null;
+
/** @private {!Map<number, !GraphNode>} */
this.nodes_ = new Map();
@@ -543,6 +637,12 @@ class Graph {
this.links_ = [];
/**
+ * The dashed links.
+ * @private {!Array<!d3.ForceLink>}
+ */
+ this.dashedLinks_ = [];
+
+ /**
* The host window.
* @private {Window}
*/
@@ -575,7 +675,17 @@ class Graph {
simulation.on('tick', this.onTick_.bind(this));
const linkForce = d3.forceLink().id(d => d.id);
- simulation.force('link', linkForce);
+ const defaultStrength = linkForce.strength();
+
+ // Override the default link strength function to apply scaling factors
+ // from the source and target nodes to the link strength. This lets
+ // different node types balance link forces with other forces that act on
+ // them.
+ simulation.force(
+ 'link',
+ linkForce.strength(
+ l => defaultStrength(l) * l.source.linkStrengthScalingFactor *
+ l.target.linkStrengthScalingFactor));
// Sets the repulsion force between nodes (positive number is attraction,
// negative number is repulsion).
@@ -588,8 +698,9 @@ class Graph {
// Create the <g> elements that host nodes and links.
// The link groups are created first so that all links end up behind nodes.
const svg = d3.select(this.svg_);
- this.toolTipLinkGroup_ = svg.append('g').attr('class', 'toolTipLinks');
+ this.toolTipLinkGroup_ = svg.append('g').attr('class', 'tool-tip-links');
this.linkGroup_ = svg.append('g').attr('class', 'links');
+ this.dashedLinkGroup_ = svg.append('g').attr('class', 'dashed-links');
this.nodeGroup_ = svg.append('g').attr('class', 'nodes');
this.separatorGroup_ = svg.append('g').attr('class', 'separators');
@@ -630,7 +741,11 @@ class Graph {
/** @override */
pageChanged(page) {
const pageNode = /** @type {!PageNode} */ (this.nodes_.get(page.id));
+
+ // Page node dashed links may change dynamically, so account for that here.
+ this.removeDashedNodeLinks_(pageNode);
pageNode.page = page;
+ this.addDashedNodeLinks_(pageNode);
}
/** @override */
@@ -665,6 +780,7 @@ class Graph {
// Remove any links, and then the node itself.
this.removeNodeLinks_(node);
+ this.removeDashedNodeLinks_(node);
this.nodes_.delete(nodeId);
}
@@ -709,12 +825,22 @@ class Graph {
* @private
*/
removeNodeLinks_(node) {
- // Filter away any links to or from the deleted node.
+ // Filter away any links to or from the provided node.
this.links_ = this.links_.filter(
link => link.source !== node && link.target !== node);
}
/**
+ * @param {!GraphNode} node
+ * @private
+ */
+ removeDashedNodeLinks_(node) {
+ // Filter away any dashed links to or from the provided node.
+ this.dashedLinks_ = this.dashedLinks_.filter(
+ link => link.source !== node && link.target !== node);
+ }
+
+ /**
* @param {!Object<string>} nodeDescriptions
* @private
*/
@@ -848,10 +974,18 @@ class Graph {
// Select the links.
const link = this.linkGroup_.selectAll('line').data(this.links_);
// Add new links.
- link.enter().append('line').attr('stroke-width', 1);
+ link.enter().append('line');
// Remove dead links.
link.exit().remove();
+ // Select the dashed links.
+ const dashedLink =
+ this.dashedLinkGroup_.selectAll('line').data(this.dashedLinks_);
+ // Add new dashed links.
+ dashedLink.enter().append('line');
+ // Remove dead dashed links.
+ dashedLink.exit().remove();
+
// Select the nodes, except for any dead ones that are still transitioning.
const nodes = Array.from(this.nodes_.values());
const node =
@@ -863,8 +997,10 @@ class Graph {
.append('g')
.call(this.drag_)
.on('click', this.onGraphNodeClick_.bind(this));
- const circles = newNodes.append('circle').attr('r', 9).attr(
- 'fill', 'green'); // New nodes appear green.
+ const circles = newNodes.append('circle')
+ .attr('id', d => `circle-${d.id}`)
+ .attr('r', kNodeRadius * 1.5)
+ .attr('fill', 'green'); // New nodes appear green.
newNodes.append('image')
.attr('x', -8)
@@ -877,7 +1013,7 @@ class Graph {
circles.transition()
.duration(2000)
.attr('fill', d => d.color)
- .attr('r', 6);
+ .attr('r', kNodeRadius);
}
if (!node.exit().empty()) {
@@ -913,9 +1049,11 @@ class Graph {
// Update and restart the simulation if the graph changed.
if (!node.enter().empty() || !node.exit().empty() ||
- !link.enter().empty() || !link.exit().empty()) {
+ !link.enter().empty() || !link.exit().empty() ||
+ !dashedLink.enter().empty() || !dashedLink.exit().empty()) {
this.simulation_.nodes(nodes);
- this.simulation_.force('link').links(this.links_);
+ const links = this.links_.concat(this.dashedLinks_);
+ this.simulation_.force('link').links(links);
this.restartSimulation_();
}
@@ -932,6 +1070,12 @@ class Graph {
.attr('x2', d => d.target.x)
.attr('y2', d => d.target.y);
+ const dashedLines = this.dashedLinkGroup_.selectAll('line');
+ dashedLines.attr('x1', d => d.source.x)
+ .attr('y1', d => d.source.y)
+ .attr('x2', d => d.target.x)
+ .attr('y2', d => d.target.y);
+
this.updateToolTipLinks();
}
@@ -945,6 +1089,7 @@ class Graph {
addNode_(node) {
this.nodes_.set(node.id, node);
this.addNodeLinks_(node);
+ this.addDashedNodeLinks_(node);
node.setInitialPosition(this.width_, this.height_);
}
@@ -955,8 +1100,7 @@ class Graph {
* @private
*/
addNodeLinks_(node) {
- const linkTargets = node.linkTargets();
- for (const linkTarget of linkTargets) {
+ for (const linkTarget of node.linkTargets) {
const target = this.nodes_.get(linkTarget);
if (target) {
this.links_.push({source: node, target: target});
@@ -965,6 +1109,21 @@ class Graph {
}
/**
+ * Adds all the dashed links for a node to the graph.
+ *
+ * @param {!GraphNode} node
+ * @private
+ */
+ addDashedNodeLinks_(node) {
+ for (const dashedLinkTarget of node.dashedLinkTargets) {
+ const target = this.nodes_.get(dashedLinkTarget);
+ if (target) {
+ this.dashedLinks_.push({source: node, target: target});
+ }
+ }
+ }
+
+ /**
* @param {!GraphNode} d The dragged node.
* @private
*/
@@ -993,8 +1152,16 @@ class Graph {
if (!d3.event.active) {
this.simulation_.alphaTarget(0);
}
- d.fx = null;
- d.fy = null;
+ // Leave the node pinned where it was dropped. Return it to free
+ // positioning if it's dropped outside its designated area.
+ const bounds = d.allowedYRange(this.height_);
+ if (d3.event.y < bounds[0] || d3.event.y > bounds[1]) {
+ d.fx = null;
+ d.fy = null;
+ }
+
+ // Toggle the pinned class as appropriate for the circle backing this node.
+ d3.select(`#circle-${d.id}`).classed('pinned', d.fx != null);
}
/**
@@ -1010,7 +1177,7 @@ class Graph {
* @private
*/
getTargetYPositionStrength_(d) {
- return d.targetYPositionStrength();
+ return d.targetYPositionStrength;
}
/**
@@ -1018,7 +1185,7 @@ class Graph {
* @private
*/
getManyBodyStrength_(d) {
- return d.manyBodyStrength();
+ return d.manyBodyStrength;
}
/**
@@ -1093,7 +1260,7 @@ class Graph {
.strength(this.getTargetYPositionStrength_.bind(this));
this.simulation_.force('x_pos', xForce);
this.simulation_.force('y_pos', yForce);
- this.simulation_.force('y_bound', boundingForce(this.height_));
+ this.simulation_.force('y_bound', boundingForce(this.height_, this.width_));
if (!this.wasResized_) {
this.wasResized_ = true;
diff --git a/chromium/chrome/browser/resources/discards/graph_doc_template.html b/chromium/chrome/browser/resources/discards/graph_doc_template.html
index b9fdfb27c8d..bcdb842d0c0 100644
--- a/chromium/chrome/browser/resources/discards/graph_doc_template.html
+++ b/chromium/chrome/browser/resources/discards/graph_doc_template.html
@@ -21,6 +21,20 @@ URL. As result, this document needs to be self-contained, hence inline scripts.
.links line {
stroke: #999;
stroke-opacity: 0.6;
+ stroke-width: 1;
+ }
+
+ .dashed-links line {
+ marker-start: url(#arrowToSource);
+ stroke: #999;
+ stroke-dasharray: 3;
+ stroke-opacity: 0.6;
+ stroke-width: 1;
+ }
+
+ #arrowToSource {
+ fill: #999;
+ stroke: #999;
}
.nodes circle {
@@ -28,6 +42,10 @@ URL. As result, this document needs to be self-contained, hence inline scripts.
stroke-width: 1.5px;
}
+ .nodes circle.pinned {
+ stroke: red;
+ }
+
.dead image {
display: none;
}
@@ -70,6 +88,13 @@ ${javascript_file}
</head>
<body>
<div id="toolTips" width="100%" height="100%"></div>
- <svg id="graphBody" width="100%" height="100%"></svg>
+ <svg id="graphBody" width="100%" height="100%">
+ <defs>
+ <marker id="arrowToSource" viewBox="0 -5 10 10" refX="-12" refY="0"
+ markerWidth="9" markerHeight="6" orient="auto">
+ <path d="M15,-7 L0,0 L15,7" />
+ </marker>
+ </defs>
+ </svg>
</body>
</html>
diff --git a/chromium/chrome/browser/resources/downloads/BUILD.gn b/chromium/chrome/browser/resources/downloads/BUILD.gn
index b54a16fd160..905b771d0a8 100644
--- a/chromium/chrome/browser/resources/downloads/BUILD.gn
+++ b/chromium/chrome/browser/resources/downloads/BUILD.gn
@@ -32,6 +32,7 @@ if (optimize_webui) {
unpak("unpak") {
pak_file = downloads_pak_file
out_folder = unpak_folder
+ excludes = [ "../../ui/webui/downloads/downloads.mojom-lite.js" ]
deps = [ ":flattened_resources" ]
}
diff --git a/chromium/chrome/browser/resources/downloads/downloads.html b/chromium/chrome/browser/resources/downloads/downloads.html
index c7ad2c10bc1..4e1efc9f67b 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{a11yenhanced}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading">
<head>
<meta charset="utf-8">
<base href="chrome://downloads">
diff --git a/chromium/chrome/browser/resources/downloads/downloads_resources_vulcanized.grd b/chromium/chrome/browser/resources/downloads/downloads_resources_vulcanized.grd
index 70f3e213e2e..68cdc6946b9 100644
--- a/chromium/chrome/browser/resources/downloads/downloads_resources_vulcanized.grd
+++ b/chromium/chrome/browser/resources/downloads/downloads_resources_vulcanized.grd
@@ -21,18 +21,15 @@
<include name="IDR_DOWNLOADS_MOJO_LITE_JS"
file="${root_gen_dir}\chrome\browser\ui\webui\downloads\downloads.mojom-lite.js"
use_base_dir="false"
- compress="gzip"
type="BINDATA" />
<include name="IDR_DOWNLOADS_DOWNLOADS_HTML"
file="downloads.html"
preprocess="true"
- type="chrome_html"
- compress="gzip" />
+ type="chrome_html" />
<include name="IDR_DOWNLOADS_DOWNLOADS_ROLLUP_JS"
file="${root_gen_dir}\chrome\browser\resources\downloads\downloads.rollup.js"
use_base_dir="false"
preprocess="true"
- compress="gzip"
type="BINDATA" />
</includes>
</release>
diff --git a/chromium/chrome/browser/resources/downloads/toolbar.html b/chromium/chrome/browser/resources/downloads/toolbar.html
index 2220c953c17..b87845dcdde 100644
--- a/chromium/chrome/browser/resources/downloads/toolbar.html
+++ b/chromium/chrome/browser/resources/downloads/toolbar.html
@@ -10,7 +10,6 @@
}
cr-icon-button {
- --cr-icon-button-fill-color-focus: var(--cr-toolbar-background-color);
justify-content: flex-end;
margin: 4px;
}
diff --git a/chromium/chrome/browser/resources/extensions/BUILD.gn b/chromium/chrome/browser/resources/extensions/BUILD.gn
index 6ad3d269eb8..53ed19cc2b6 100644
--- a/chromium/chrome/browser/resources/extensions/BUILD.gn
+++ b/chromium/chrome/browser/resources/extensions/BUILD.gn
@@ -378,12 +378,12 @@ js_library("service") {
"//ui/webui/resources/js:assert.m",
"//ui/webui/resources/js:cr.m",
]
- externs_list = [
- "$externs_path/activity_log_private.js",
- "$externs_path/developer_private.js",
- "$externs_path/management.js",
- "$externs_path/metrics_private.js",
- ]
+ externs_list = chrome_extension_public_externs + [
+ "$externs_path/activity_log_private.js",
+ "$externs_path/developer_private.js",
+ "$externs_path/management.js",
+ "$externs_path/metrics_private.js",
+ ]
}
js_library("shortcut_input") {
diff --git a/chromium/chrome/browser/resources/extensions/detail_view.html b/chromium/chrome/browser/resources/extensions/detail_view.html
index 2e647218766..04c47dbf7cc 100644
--- a/chromium/chrome/browser/resources/extensions/detail_view.html
+++ b/chromium/chrome/browser/resources/extensions/detail_view.html
@@ -401,7 +401,7 @@
</div>
</div>
<cr-link-row class="hr" id="remove-extension"
- hidden="[[isControlled_(data.controlledInfo)]]"
+ hidden="[[data.mustRemainInstalled]]"
label="$i18n{itemRemoveExtension}" on-click="onRemoveTap_">
</cr-link-row>
</div>
diff --git a/chromium/chrome/browser/resources/extensions/detail_view.js b/chromium/chrome/browser/resources/extensions/detail_view.js
index eb337947210..fc461db137c 100644
--- a/chromium/chrome/browser/resources/extensions/detail_view.js
+++ b/chromium/chrome/browser/resources/extensions/detail_view.js
@@ -31,7 +31,7 @@ import {afterNextRender, html, Polymer} from 'chrome://resources/polymer/v3_0/po
import {ItemDelegate} from './item.js';
import {ItemBehavior} from './item_behavior.js';
-import {computeInspectableViewLabel, EnableControl, getEnableControl, getItemSource, getItemSourceString, isControlled, isEnabled, userCanChangeEnablement} from './item_util.js';
+import {computeInspectableViewLabel, EnableControl, getEnableControl, getItemSource, getItemSourceString, isEnabled, userCanChangeEnablement} from './item_util.js';
import {navigation, Page} from './navigation_helper.js';
Polymer({
@@ -132,14 +132,6 @@ Polymer({
* @return {boolean}
* @private
*/
- isControlled_() {
- return isControlled(this.data);
- },
-
- /**
- * @return {boolean}
- * @private
- */
isEnabled_() {
return isEnabled(this.data.state);
},
@@ -321,8 +313,6 @@ Polymer({
switch (type) {
case 'POLICY':
return 'cr20:domain';
- case 'SUPERVISED_USER_CUSTODIAN':
- return 'cr:supervisor-account';
default:
return '';
}
diff --git a/chromium/chrome/browser/resources/extensions/extensions.html b/chromium/chrome/browser/resources/extensions/extensions.html
index 087a92fd887..c5980f41fd1 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{a11yenhanced}>
+ class="loading $i18n{loadTimeClasses}">
<head>
<meta charset="utf8">
<title>$i18n{title}</title>
diff --git a/chromium/chrome/browser/resources/extensions/extensions_resources_vulcanized.grd b/chromium/chrome/browser/resources/extensions/extensions_resources_vulcanized.grd
index 3ebe27cf553..6ef33b79788 100644
--- a/chromium/chrome/browser/resources/extensions/extensions_resources_vulcanized.grd
+++ b/chromium/chrome/browser/resources/extensions/extensions_resources_vulcanized.grd
@@ -14,22 +14,18 @@
<includes>
<include name="IDR_EXTENSIONS_EXTENSIONS_HTML"
file="extensions.html"
- type="chrome_html"
- compress="gzip" />
+ type="chrome_html" />
<include name="IDR_EXTENSIONS_EXTENSIONS_ROLLUP_JS"
file="${root_gen_dir}\chrome\browser\resources\extensions\extensions.rollup.js"
use_base_dir="false"
preprocess="true"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_EXTENSIONS_CHECKUP_IMAGE"
file="checkup_image.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_EXTENSIONS_CHECKUP_IMAGE_DARK"
file="checkup_image_dark.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/extensions/item.html b/chromium/chrome/browser/resources/extensions/item.html
index 712997e330d..fb2f6d20bdb 100644
--- a/chromium/chrome/browser/resources/extensions/item.html
+++ b/chromium/chrome/browser/resources/extensions/item.html
@@ -279,7 +279,7 @@
</cr-button>
<cr-button id="remove-button" on-click="onRemoveTap_"
aria-describedby="a11yAssociation"
- hidden="[[isControlled_(data.controlledInfo)]]">
+ hidden="[[data.mustRemainInstalled]]">
$i18n{remove}
</cr-button>
<template is="dom-if" if="[[shouldShowErrorsButton_(data.*)]]">
diff --git a/chromium/chrome/browser/resources/extensions/item.js b/chromium/chrome/browser/resources/extensions/item.js
index fb88800bb62..51eb641791c 100644
--- a/chromium/chrome/browser/resources/extensions/item.js
+++ b/chromium/chrome/browser/resources/extensions/item.js
@@ -27,7 +27,7 @@ import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {flush, html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {ItemBehavior} from './item_behavior.js';
-import {computeInspectableViewLabel, EnableControl, getEnableControl, getItemSource, getItemSourceString, isControlled, isEnabled, SourceType, userCanChangeEnablement} from './item_util.js';
+import {computeInspectableViewLabel, EnableControl, getEnableControl, getItemSource, getItemSourceString, isEnabled, SourceType, userCanChangeEnablement} from './item_util.js';
import {navigation, Page} from './navigation_helper.js';
/** @interface */
@@ -276,14 +276,6 @@ Polymer({
* @return {boolean}
* @private
*/
- isControlled_() {
- return isControlled(this.data);
- },
-
- /**
- * @return {boolean}
- * @private
- */
isEnabled_() {
return isEnabled(this.data.state);
},
diff --git a/chromium/chrome/browser/resources/extensions/item_util.js b/chromium/chrome/browser/resources/extensions/item_util.js
index a1f91b53f7e..83e727c2641 100644
--- a/chromium/chrome/browser/resources/extensions/item_util.js
+++ b/chromium/chrome/browser/resources/extensions/item_util.js
@@ -44,14 +44,6 @@ export function isEnabled(state) {
}
/**
- * @param {!chrome.developerPrivate.ExtensionInfo} extensionInfo
- * @return {boolean} Whether the extension is controlled.
- */
-export function isControlled(extensionInfo) {
- return !!extensionInfo.controlledInfo;
-}
-
-/**
* Returns true if the user can change whether or not the extension is
* enabled.
* @param {!chrome.developerPrivate.ExtensionInfo} item
diff --git a/chromium/chrome/browser/resources/feedback/html/default.html b/chromium/chrome/browser/resources/feedback/html/default.html
index b7c50d54717..2cfa06d8d1a 100644
--- a/chromium/chrome/browser/resources/feedback/html/default.html
+++ b/chromium/chrome/browser/resources/feedback/html/default.html
@@ -1,24 +1,25 @@
<!doctype html>
<html i18n-values="dir:textdirection;lang:language">
<head>
-<meta charset="utf-8">
-<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
-<link rel="stylesheet" href="chrome://resources/css/apps/common.css"></link>
-<link rel="stylesheet" href="chrome://resources/css/apps/topbutton_bar.css">
-</link>
-<link rel="stylesheet" href="../css/feedback.css">
+ <title i18n-content="appTitle"> </title>
+ <meta charset="utf-8">
+ <link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
+ <link rel="stylesheet" href="chrome://resources/css/apps/common.css"></link>
+ <link rel="stylesheet" href="chrome://resources/css/apps/topbutton_bar.css">
+ </link>
+ <link rel="stylesheet" href="../css/feedback.css">
-<script src="chrome://resources/js/load_time_data.js"></script>
-<script src="chrome://resources/js/i18n_template_no_process.js"></script>
-<script src="chrome://resources/js/util.js"></script>
-<script src="../js/feedback_util.js"></script>
-<script src="../js/take_screenshot.js"></script>
-<script src="../js/topbar_handlers.js"></script>
-<script src="../js/feedback.js"></script>
+ <script src="chrome://resources/js/load_time_data.js"></script>
+ <script src="chrome://resources/js/i18n_template_no_process.js"></script>
+ <script src="chrome://resources/js/util.js"></script>
+ <script src="../js/feedback_util.js"></script>
+ <script src="../js/take_screenshot.js"></script>
+ <script src="../js/topbar_handlers.js"></script>
+ <script src="../js/feedback.js"></script>
</head>
<body>
<div id="title-bar" class="title-bar">
- <span id="page-title" i18n-content="page-title"></span>
+ <span id="page-title" i18n-content="pageTitle"></span>
<span class="topbutton-bar">
<button class="minimize-button" id="minimize-button" tabindex="-1"
i18n-values="aria-label:minimizeBtnLabel">
diff --git a/chromium/chrome/browser/resources/feedback/js/event_handler.js b/chromium/chrome/browser/resources/feedback/js/event_handler.js
index 5f9b2397257..ac5f433853d 100644
--- a/chromium/chrome/browser/resources/feedback/js/event_handler.js
+++ b/chromium/chrome/browser/resources/feedback/js/event_handler.js
@@ -21,11 +21,12 @@ const FEEDBACK_HEIGHT = 610;
*/
const FEEDBACK_DEFAULT_WINDOW_ID = 'default_window';
+// List of extension IDs that are permitted to invoke Feedback.
// To generate a hashed extension ID, use a sha-1 hash, all in lower case.
// Example:
// echo -n 'abcdefghijklmnopqrstuvwxyzabcdef' | sha1sum | \
// awk '{print toupper($1)}'
-const whitelistedExtensionIds = [
+const feedbackCallerExtensions = [
'12E618C3C6E97495AAECF2AC12DEB082353241C6', // QuickOffice
'3727DD3E564B6055387425027AD74C58784ACC15', // QuickOffice
'2FC374607C2DF285634B67C64A2E356C607091C3', // QuickOffice
@@ -221,16 +222,16 @@ class FeedbackRequest {
}
/**
- * Function to determine whether or not a given extension id is whitelisted to
- * invoke the feedback UI. If the extension is whitelisted, the callback to
- * start the Feedback UI will be called.
+ * Function to determine whether or not a given extension id is allowed to
+ * invoke the feedback UI. If it is, the callback to start the Feedback UI will
+ * be called.
* @param {string} id the id of the sender extension.
* @param {Function} startFeedbackCallback The callback function that will
* will start the feedback UI.
* @param {Object} feedbackInfo The feedback info object to pass to the
* start feedback UI callback.
*/
-function senderWhitelisted(id, startFeedbackCallback, feedbackInfo) {
+function invokeFeedbackIfPermitted(id, startFeedbackCallback, feedbackInfo) {
crypto.subtle.digest('SHA-1', new TextEncoder().encode(id))
.then(function(hashBuffer) {
let hashString = '';
@@ -240,7 +241,7 @@ function senderWhitelisted(id, startFeedbackCallback, feedbackInfo) {
hashString += n < 0x10 ? '0' : '';
hashString += n.toString(16);
}
- if (whitelistedExtensionIds.indexOf(hashString.toUpperCase()) != -1) {
+ if (feedbackCallerExtensions.indexOf(hashString.toUpperCase()) != -1) {
startFeedbackCallback(feedbackInfo);
}
});
@@ -267,7 +268,7 @@ function feedbackReadyHandler(request, sender, sendResponse) {
*/
function requestFeedbackHandler(request, sender, sendResponse) {
if (request.requestFeedback) {
- senderWhitelisted(sender.id, startFeedbackUI, request.feedbackInfo);
+ invokeFeedbackIfPermitted(sender.id, startFeedbackUI, request.feedbackInfo);
}
}
diff --git a/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js b/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js
index a450e1d88e7..c641a0302dc 100644
--- a/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js
+++ b/chromium/chrome/browser/resources/gaia_auth_host/authenticator.js
@@ -822,7 +822,7 @@ cr.define('cr.login', function() {
} else if (headerName == LOCATION_HEADER) {
// If the "choose what to sync" checkbox was clicked, then the
// continue URL will contain a source=3 field.
- assert(header.value);
+ assert(header.value !== undefined);
const location = decodeURIComponent(header.value);
this.chooseWhatToSync_ = !!location.match(/(\?|&)source=3($|&)/);
}
diff --git a/chromium/chrome/browser/resources/gaia_auth_host/gaia_auth_host_resources.grd b/chromium/chrome/browser/resources/gaia_auth_host/gaia_auth_host_resources.grd
index 52a9c5a1e7a..8e82e1235ab 100644
--- a/chromium/chrome/browser/resources/gaia_auth_host/gaia_auth_host_resources.grd
+++ b/chromium/chrome/browser/resources/gaia_auth_host/gaia_auth_host_resources.grd
@@ -15,38 +15,31 @@
<include name="IDR_GAIA_AUTH_AUTHENTICATOR_M_JS"
file="${root_gen_dir}/chrome/browser/resources/gaia_auth_host/authenticator.m.js"
use_base_dir="false"
- type ="BINDATA"
- compress="gzip" />
+ type ="BINDATA" />
<include name="IDR_GAIA_AUTH_SAML_HANDLER_M_JS"
file="${root_gen_dir}/chrome/browser/resources/gaia_auth_host/saml_handler.m.js"
use_base_dir="false"
- type ="BINDATA"
- compress="gzip" />
+ type ="BINDATA" />
<include name="IDR_GAIA_AUTH_CHANNEL_M_JS"
file="${root_gen_dir}/chrome/browser/resources/gaia_auth_host/channel.m.js"
use_base_dir="false"
- type ="BINDATA"
- compress="gzip" />
+ type ="BINDATA" />
<include name="IDR_GAIA_AUTH_POST_MESSAGE_CHANNEL_M_JS"
file="${root_gen_dir}/chrome/browser/resources/gaia_auth_host/post_message_channel.m.js"
use_base_dir="false"
- type ="BINDATA"
- compress="gzip" />
+ type ="BINDATA" />
<include name="IDR_GAIA_AUTH_WEBVIEW_EVENT_MANAGER_M_JS"
file="${root_gen_dir}/chrome/browser/resources/gaia_auth_host/webview_event_manager.m.js"
use_base_dir="false"
- type ="BINDATA"
- compress="gzip" />
+ type ="BINDATA" />
<include name="IDR_GAIA_AUTH_SAML_PASSWORD_ATTRIBUTES_M_JS"
file="${root_gen_dir}/chrome/browser/resources/gaia_auth_host/saml_password_attributes.m.js"
use_base_dir="false"
- type ="BINDATA"
- compress="gzip" />
+ type ="BINDATA" />
<include name="IDR_GAIA_AUTH_SAML_TIMESTAMPS_M_JS"
file="${root_gen_dir}/chrome/browser/resources/gaia_auth_host/saml_timestamps.m.js"
use_base_dir="false"
- type ="BINDATA"
- compress="gzip" />
+ type ="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/gaia_auth_host/password_change_authenticator.js b/chromium/chrome/browser/resources/gaia_auth_host/password_change_authenticator.js
index 00f17b5dab6..286b664860b 100644
--- a/chromium/chrome/browser/resources/gaia_auth_host/password_change_authenticator.js
+++ b/chromium/chrome/browser/resources/gaia_auth_host/password_change_authenticator.js
@@ -16,6 +16,12 @@ cr.define('cr.samlPasswordChange', function() {
const oktaInjectedScriptName = 'oktaInjected';
/**
+ * "SAML password change extension" which helps detect password change
+ * @type {string}
+ */
+ const extensionId = 'mkmjngkgbjeljoblnahkagdlcdeiiped';
+
+ /**
* The script to inject into Okta user settings page.
* @type {string}
*/
@@ -25,9 +31,26 @@ cr.define('cr.samlPasswordChange', function() {
const BLANK_PAGE_URL = 'about:blank';
+
+ /**
+ * @param {string} extensionId The ID of the extension to send the message to.
+ * @param {any} message The message to send. This message should be a
+ * JSON-ifiable object.
+ * @param {function} callback the response callback function
+ * @private
+ * @see: https://developer.chrome.com/extensions/runtime#method-sendMessage
+ */
+ function sendMessage_(extensionId, message, callback) {
+ // Sending message to extension and callback will be used to receive
+ // response from extension. This way is used to send one time request :
+ // https://developer.chrome.com/extensions/messaging#simple
+ chrome.runtime.sendMessage(extensionId, message, callback);
+ }
+
/**
* The different providers of password-change pages that we support, or are
* working on supporting.
+ * Should match the enum in SAML password change extension
* @enum {number}
*/
const PasswordChangePageProvider = {
@@ -309,10 +332,28 @@ cr.define('cr.samlPasswordChange', function() {
* @private
*/
onBeforeRedirect_(details) {
- if (details.method == 'POST' &&
- detectPasswordChangeSuccess(
- safeParseUrl_(details.url), safeParseUrl_(details.redirectUrl))) {
- this.onPasswordChangeSuccess_(false /* isOkta != OKTA */);
+ if (details.method == 'POST') {
+ const message = {
+ name: 'detectPasswordChangeSuccess',
+ url: details.url,
+ redirectUrl: details.redirectUrl
+ };
+ sendMessage_(extensionId, message, (passwordChangeSuccess) => {
+ // SAML change password extension will be used to detect the password
+ // change success from url passed.
+ // 'passwordChangeSuccess' will be equal to undefined in case
+ // extension isn't installed or disabled, In this case normal flow
+ // will be used.
+ // Otherwise 'passwordChangeSuccess' will indcate whether extension
+ // detected password change successfully.
+ if (passwordChangeSuccess ||
+ (typeof passwordChangeSuccess === 'undefined' &&
+ detectPasswordChangeSuccess(
+ safeParseUrl_(details.url),
+ safeParseUrl_(details.redirectUrl)))) {
+ this.onPasswordChangeSuccess_(false /* isOkta */);
+ }
+ });
}
}
@@ -339,10 +380,20 @@ cr.define('cr.samlPasswordChange', function() {
*/
onMessageReceived_(event) {
if (event.data == 'passwordChangeSuccess') {
- const pageProvider = detectProvider_(safeParseUrl_(event.origin));
- if (pageProvider == PasswordChangePageProvider.OKTA) {
- this.onPasswordChangeSuccess_(true /* isOkta == OKTA */);
- }
+ const message = {name: 'detectProvider', url: event.origin};
+ sendMessage_(extensionId, message, (provider) => {
+ // SAML change password extension will be used to detect provider
+ // from url passed.
+ // 'provider' will be equal to undefined in case
+ // extension isn't installed or disabled, In this case normal flow
+ // will be used.
+ if (provider == PasswordChangePageProvider.OKTA ||
+ (typeof provider === 'undefined' &&
+ detectProvider_(safeParseUrl_(event.origin)) ==
+ PasswordChangePageProvider.OKTA)) {
+ this.onPasswordChangeSuccess_(true /* isOkta */);
+ }
+ });
}
}
}
diff --git a/chromium/chrome/browser/resources/history/history.html b/chromium/chrome/browser/resources/history/history.html
index 506a68f4ff3..7f78155dfe5 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{a11yenhanced}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
<base href="chrome://history">
<meta charset="utf8">
diff --git a/chromium/chrome/browser/resources/history/history_resources_vulcanized.grd b/chromium/chrome/browser/resources/history/history_resources_vulcanized.grd
index c602d28c9c9..8873cf877a2 100644
--- a/chromium/chrome/browser/resources/history/history_resources_vulcanized.grd
+++ b/chromium/chrome/browser/resources/history/history_resources_vulcanized.grd
@@ -15,33 +15,27 @@
<include name="IDR_HISTORY_HISTORY_HTML"
file="history.html"
preprocess="true"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_HISTORY_IMAGES_SIGN_IN_PROMO_DARK_SVG"
file="images\sign_in_promo_dark.svg"
- compress="gzip"
type="BINDATA" />
<include name="IDR_HISTORY_IMAGES_SIGN_IN_PROMO_SVG"
file="images\sign_in_promo.svg"
- compress="gzip"
type="BINDATA" />
<include name="IDR_HISTORY_HISTORY_ROLLUP_JS"
file="${root_gen_dir}\chrome\browser\resources\history\history.rollup.js"
preprocess="true"
type="BINDATA"
- compress="gzip"
use_base_dir="false" />
<include name="IDR_HISTORY_LAZY_LOAD_ROLLUP_JS"
file="${root_gen_dir}\chrome\browser\resources\history\lazy_load.rollup.js"
preprocess="true"
type="BINDATA"
- compress="gzip"
use_base_dir="false" />
<include name="IDR_HISTORY_SHARED_ROLLUP_JS"
file="${root_gen_dir}\chrome\browser\resources\history\shared.rollup.js"
preprocess="true"
type="BINDATA"
- compress="gzip"
use_base_dir="false" />
</includes>
</release>
diff --git a/chromium/chrome/browser/resources/inline_login/inline_login.js b/chromium/chrome/browser/resources/inline_login/inline_login.js
index 44635972745..a0988731025 100644
--- a/chromium/chrome/browser/resources/inline_login/inline_login.js
+++ b/chromium/chrome/browser/resources/inline_login/inline_login.js
@@ -65,9 +65,8 @@ cr.define('inline.login', function() {
* Initialize the UI.
*/
function initialize() {
- $('navigation-button').addEventListener('click', navigationButtonClicked);
+ $('navigation-button').addEventListener('click', navigateBackInWebview);
cr.addWebUIListener('show-back-button', showBackButton);
- cr.addWebUIListener('navigate-back-in-webview', navigateBackInWebview);
cr.addWebUIListener('load-auth-extension', loadAuthExtension);
cr.addWebUIListener('close-dialog', closeDialog);
@@ -148,15 +147,12 @@ cr.define('inline.login', function() {
function navigateBackInWebview() {
if ($('signin-frame').canGoBack()) {
$('signin-frame').back();
+ $('signin-frame').focus();
} else {
closeDialog();
}
}
- function navigationButtonClicked() {
- chrome.send('navigationButtonClicked');
- }
-
return {
closeDialog: closeDialog,
sendLSTFetchResults: sendLSTFetchResults,
@@ -165,7 +161,6 @@ cr.define('inline.login', function() {
initialize: initialize,
isAuthReady: isAuthReady,
loadAuthExtension: loadAuthExtension,
- navigationButtonClicked: navigationButtonClicked,
showBackButton: showBackButton,
};
});
diff --git a/chromium/chrome/browser/resources/internals/query_tiles/BUILD.gn b/chromium/chrome/browser/resources/internals/query_tiles/BUILD.gn
new file mode 100644
index 00000000000..6d3f2cb3d6e
--- /dev/null
+++ b/chromium/chrome/browser/resources/internals/query_tiles/BUILD.gn
@@ -0,0 +1,25 @@
+# Copyright 2020 The Chromium 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") {
+ uses_js_modules = true
+ deps = [
+ ":query_tiles_internals",
+ ":query_tiles_internals_browser_proxy",
+ ]
+}
+
+js_library("query_tiles_internals") {
+ deps = [
+ ":query_tiles_internals_browser_proxy",
+ "//ui/webui/resources/js:cr.m",
+ "//ui/webui/resources/js:util.m",
+ ]
+}
+
+js_library("query_tiles_internals_browser_proxy") {
+ deps = [ "//ui/webui/resources/js:cr.m" ]
+}
diff --git a/chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals.html b/chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals.html
new file mode 100644
index 00000000000..5b037055148
--- /dev/null
+++ b/chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals.html
@@ -0,0 +1,31 @@
+<!doctype html>
+<html lang="en" dir="ltr">
+ <head>
+ <meta charset="utf-8">
+ <title>Query Tiles Internals</title>
+ <meta name="viewport" content="width=device-width">
+ <link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
+ </head>
+ <body>
+ <h1>Query Tiles Internals</h1>
+ <h4>Fetcher Controller</h4>
+ <div>
+ <button id="start-fetch">Start fetch</button>
+ </div>
+ <h4>Database Controller</h4>
+ <div>
+ <button id="purge-db">Purge database</button>
+ </div>
+ <h4>Service State</h4>
+ <div>
+ Fetcher status: <span id="fetcher-status"></span>
+ Database status: <span id="group-status"></span>
+ </div>
+ <h4>Tile data</h4>
+ Group info: <span id="group-info"></span>
+ Tile proto: <span id="tile-proto"></span>
+ <div>
+ </div>
+ <script type="module" src="query_tiles_internals.js"></script>
+ </body>
+</html>
diff --git a/chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals.js b/chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals.js
new file mode 100644
index 00000000000..3bb73548dc2
--- /dev/null
+++ b/chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals.js
@@ -0,0 +1,49 @@
+// Copyright 2020 The Chromium 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 {addWebUIListener} from 'chrome://resources/js/cr.m.js';
+import {$} from 'chrome://resources/js/util.m.js';
+
+import {QueryTilesInternalsBrowserProxy, QueryTilesInternalsBrowserProxyImpl, ServiceStatus, TileData} from './query_tiles_internals_browser_proxy.js';
+
+/**
+ * @param {!ServiceStatus} serviceStatus The current status of the tile
+ * service.
+ */
+function onServiceStatusChanged(serviceStatus) {
+ $('group-status').textContent = serviceStatus.groupStatus;
+ $('fetcher-status').textContent = serviceStatus.fetcherStatus;
+}
+
+/**
+ * @param {!TileData} tileData The raw data persisted in database.
+ */
+function onTileDataAvailable(tileData) {
+ $('group-info').textContent = tileData.groupInfo;
+ $('tile-proto').textContent = tileData.tilesProto;
+}
+
+function initialize() {
+ /** @type {!QueryTilesInternalsBrowserProxy} */
+ const browserProxy = QueryTilesInternalsBrowserProxyImpl.getInstance();
+
+ // Register all event listeners.
+ addWebUIListener('service-status-changed', onServiceStatusChanged);
+
+ addWebUIListener('tile-data-available', onTileDataAvailable);
+
+ $('start-fetch').onclick = function() {
+ browserProxy.startFetch();
+ };
+
+ $('purge-db').onclick = function() {
+ browserProxy.purgeDb();
+ };
+
+ // Kick off requests for the current system state.
+ browserProxy.getServiceStatus().then(onServiceStatusChanged);
+ browserProxy.getTileData().then(onTileDataAvailable);
+}
+
+document.addEventListener('DOMContentLoaded', initialize);
diff --git a/chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals_browser_proxy.js b/chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals_browser_proxy.js
new file mode 100644
index 00000000000..ded38b10374
--- /dev/null
+++ b/chromium/chrome/browser/resources/internals/query_tiles/query_tiles_internals_browser_proxy.js
@@ -0,0 +1,75 @@
+// Copyright 2020 The Chromium 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 {addSingletonGetter, sendWithPromise} from 'chrome://resources/js/cr.m.js';
+
+/**
+ * @typedef {{
+ * fetcherStatus: string,
+ * groupStatus: string,
+ * }}
+ */
+export let ServiceStatus;
+
+/**
+ * @typedef {{
+ * groupInfo: string,
+ * tilesProto: string,
+ * }}
+ */
+export let TileData;
+
+/** @interface */
+export class QueryTilesInternalsBrowserProxy {
+ /**
+ * Start fetch right now.
+ */
+ startFetch() {}
+
+ /**
+ * Delete everything in the database.
+ */
+ purgeDb() {}
+
+ /**
+ * Get the current status of the TileService.
+ * @return {!Promise<ServiceStatus>} A promise firing when the service
+ * status is fetched.
+ */
+ getServiceStatus() {}
+
+ /**
+ * Get raw data from TileService database.
+ * @return {!Promise<TileData>} A promise firing when the raw data
+ * is fetched.
+ */
+ getTileData() {}
+}
+
+/**
+ * @implements {QueryTilesInternalsBrowserProxy}
+ */
+export class QueryTilesInternalsBrowserProxyImpl {
+ /** @override */
+ startFetch() {
+ return chrome.send('startFetch');
+ }
+
+ /** @override */
+ purgeDb() {
+ return chrome.send('purgeDb');
+ }
+
+ /** @override */
+ getServiceStatus() {
+ return sendWithPromise('getServiceStatus');
+ }
+
+ /** @override */
+ getTileData() {
+ return sendWithPromise('getTileData');
+ }
+}
+
+addSingletonGetter(QueryTilesInternalsBrowserProxyImpl);
diff --git a/chromium/chrome/browser/resources/interventions_internals/index.css b/chromium/chrome/browser/resources/interventions_internals/index.css
index 1af46cd12f4..dec856074a3 100644
--- a/chromium/chrome/browser/resources/interventions_internals/index.css
+++ b/chromium/chrome/browser/resources/interventions_internals/index.css
@@ -26,7 +26,7 @@ body {
}
.previews-flag-value {
- margin-left: 10px;
+ margin-inline-start: 10px;
}
button {
@@ -138,7 +138,7 @@ table {
td {
border: 0;
padding: 10px;
- text-align: left;
+ text-align: start;
vertical-align: middle;
}
@@ -205,14 +205,14 @@ td.log-url .url-tooltip::after {
bottom: 100%;
content: ' ';
left: 50%;
- margin-left: -5px;
+ margin-inline-start: -5px;
position: absolute;
}
.expansion-row {
background: transparent;
border: 0;
- margin-left: 20px;
+ margin-inline-start: 20px;
padding: 0 0 0 15px;
width: 80%;
}
@@ -268,7 +268,7 @@ tr.expansion-row td:nth-child(odd) {
width: 60%;
}
- #blacklisted-hosts-table {
+ #blocklisted-hosts-table {
width: 60%;
}
@@ -354,7 +354,7 @@ i {
font-style: italic;
}
-#blacklist-ignored-status {
+#blocklist-ignored-status {
color: red;
font-style: italic;
font-weight: bold;
diff --git a/chromium/chrome/browser/resources/interventions_internals/index.html b/chromium/chrome/browser/resources/interventions_internals/index.html
index 4f171561365..dd5f3ad7a7d 100644
--- a/chromium/chrome/browser/resources/interventions_internals/index.html
+++ b/chromium/chrome/browser/resources/interventions_internals/index.html
@@ -26,8 +26,8 @@
<span>Logs</span>
</label>
<label class="inactive-tab">
- <input type="radio" id="blacklist-tab" name="tabs"
- value="blacklist-status">
+ <input type="radio" id="blocklist-tab" name="tabs"
+ value="blocklist-status">
<span>Blocklist Status</span>
</label>
<label class="inactive-tab">
@@ -74,26 +74,26 @@
</table>
</div>
- <div class="tab-content" id="blacklist-status">
- <div id="blacklist-ignored-status"></div>
- <button id="ignore-blacklist-button" type="button">
+ <div class="tab-content" id="blocklist-status">
+ <div id="blocklist-ignored-status"></div>
+ <button id="ignore-blocklist-button" type="button">
Ignore Blocklist
</button>
- <div id="user-blacklisted-status">
+ <div id="user-blocklisted-status">
User blocklisted status:
- <span id="user-blacklisted-status-value">N/A</span>
+ <span id="user-blocklisted-status-value">N/A</span>
</div>
- <div id="blacklist-cleared-status">
+ <div id="blocklist-cleared-status">
Last blocklist cleared:
- <span id="blacklist-last-cleared-time">N/A</span>
+ <span id="blocklist-last-cleared-time">N/A</span>
</div>
- <div id="blacklisted-hosts">
+ <div id="blocklisted-hosts">
<div class="table-name">Blocklisted hosts</div>
- <table id="blacklisted-hosts-table">
+ <table id="blocklisted-hosts-table">
<tr>
- <th id="blacklisted-host-header">Host</th>
- <th id="blacklisted-time-header">Time</th>
+ <th id="blocklisted-host-header">Host</th>
+ <th id="blocklisted-time-header">Time</th>
</tr>
</table>
</div>
diff --git a/chromium/chrome/browser/resources/interventions_internals/index.js b/chromium/chrome/browser/resources/interventions_internals/index.js
index 752d3913dac..d88edff3bf0 100644
--- a/chromium/chrome/browser/resources/interventions_internals/index.js
+++ b/chromium/chrome/browser/resources/interventions_internals/index.js
@@ -3,9 +3,9 @@
// found in the LICENSE file.
/** The columns that are used to find rows that contain the keyword. */
-const ENABLE_BLACKLIST_BUTTON = 'Enable Blacklist';
-const IGNORE_BLACKLIST_BUTTON = 'Ignore Blacklist';
-const IGNORE_BLACKLIST_MESSAGE = 'Blacklist decisions are ignored.';
+const ENABLE_BLOCKLIST_BUTTON = 'Enable Blocklist';
+const IGNORE_BLOCKLIST_BUTTON = 'Ignore Blocklist';
+const IGNORE_BLOCKLIST_MESSAGE = 'Blocklist decisions are ignored.';
const URL_THRESHOLD = 40; // Maximum URL length
window.logTableMap = {};
@@ -469,59 +469,59 @@ InterventionsInternalPageImpl.prototype = {
},
/**
- * Update new blacklisted host to the web page.
+ * Update new blocklisted host to the web page.
*
* @override
- * @param {!string} host The blacklisted host.
- * @param {number} time The time when the host was blacklisted in milliseconds
+ * @param {!string} host The blocklisted host.
+ * @param {number} time The time when the host was blocklisted in milliseconds
* since Unix epoch.
*/
- onBlacklistedHost(host, time) {
+ onBlocklistedHost(host, time) {
const row = document.createElement('tr');
- row.setAttribute('class', 'blacklisted-host-row');
+ row.setAttribute('class', 'blocklisted-host-row');
const hostTd = document.createElement('td');
- hostTd.setAttribute('class', 'host-blacklisted');
+ hostTd.setAttribute('class', 'host-blocklisted');
hostTd.textContent = host;
row.appendChild(hostTd);
const timeTd = document.createElement('td');
- timeTd.setAttribute('class', 'host-blacklisted-time');
+ timeTd.setAttribute('class', 'host-blocklisted-time');
timeTd.textContent = getTimeFormat(time);
row.appendChild(timeTd);
// TODO(thanhdle): Insert row at correct index. crbug.com/776105.
- $('blacklisted-hosts-table').appendChild(row);
+ $('blocklisted-hosts-table').appendChild(row);
},
/**
- * Update to the page that the user blacklisted status has changed.
+ * Update to the page that the user blocklisted status has changed.
*
* @override
- * @param {boolean} blacklisted The time of the event in milliseconds since
+ * @param {boolean} blocklisted The time of the event in milliseconds since
* Unix epoch.
*/
- onUserBlacklistedStatusChange(blacklisted) {
- const userBlacklistedStatus = $('user-blacklisted-status-value');
- userBlacklistedStatus.textContent =
- (blacklisted ? 'Blacklisted' : 'Not blacklisted');
+ onUserBlocklistedStatusChange(blocklisted) {
+ const userBlocklistedStatus = $('user-blocklisted-status-value');
+ userBlocklistedStatus.textContent =
+ (blocklisted ? 'Blocklisted' : 'Not blocklisted');
},
/**
- * Update the blacklist cleared status on the page.
+ * Update the blocklist cleared status on the page.
*
* @override
* @param {number} time The time of the event in milliseconds since Unix
* epoch.
*/
- onBlacklistCleared(time) {
- const blacklistClearedStatus = $('blacklist-last-cleared-time');
- blacklistClearedStatus.textContent = getTimeFormat(time);
+ onBlocklistCleared(time) {
+ const blocklistClearedStatus = $('blocklist-last-cleared-time');
+ blocklistClearedStatus.textContent = getTimeFormat(time);
// Remove hosts from table.
- const blacklistedHostsTable = $('blacklisted-hosts-table');
- for (let row = blacklistedHostsTable.rows.length - 1; row > 0; row--) {
- blacklistedHostsTable.deleteRow(row);
+ const blocklistedHostsTable = $('blocklisted-hosts-table');
+ for (let row = blocklistedHostsTable.rows.length - 1; row > 0; row--) {
+ blocklistedHostsTable.deleteRow(row);
}
// Remove log message from logs table.
@@ -529,24 +529,24 @@ InterventionsInternalPageImpl.prototype = {
// Log event message.
insertMessageRowToMessageLogTable(
- time, 'Blacklist', 'Blacklist Cleared', '' /* URL */, 0 /* pageId */);
+ time, 'Blocklist', 'Blocklist Cleared', '' /* URL */, 0 /* pageId */);
},
/**
- * Update the page with the new value of ignored blacklist decision status.
+ * Update the page with the new value of ignored blocklist decision status.
*
* @override
- * @param {boolean} ignored The new status of whether the previews blacklist
- * decisions is blacklisted or not.
+ * @param {boolean} ignored The new status of whether the previews blocklist
+ * decisions is blocklisted or not.
*/
- onIgnoreBlacklistDecisionStatusChanged(ignored) {
- const ignoreButton = $('ignore-blacklist-button');
+ onIgnoreBlocklistDecisionStatusChanged(ignored) {
+ const ignoreButton = $('ignore-blocklist-button');
ignoreButton.textContent =
- ignored ? ENABLE_BLACKLIST_BUTTON : IGNORE_BLACKLIST_BUTTON;
+ ignored ? ENABLE_BLOCKLIST_BUTTON : IGNORE_BLOCKLIST_BUTTON;
- // Update the status of blacklist ignored on the page.
- $('blacklist-ignored-status').textContent =
- ignored ? IGNORE_BLACKLIST_MESSAGE : '';
+ // Update the status of blocklist ignored on the page.
+ $('blocklist-ignored-status').textContent =
+ ignored ? IGNORE_BLOCKLIST_MESSAGE : '';
},
/**
@@ -601,12 +601,12 @@ cr.define('interventions_internals', () => {
getPreviewsEnabled();
getPreviewsFlagsDetails();
- const ignoreButton = $('ignore-blacklist-button');
+ const ignoreButton = $('ignore-blocklist-button');
ignoreButton.addEventListener('click', () => {
- // Whether the blacklist is currently ignored.
- const ignored = (ignoreButton.textContent == ENABLE_BLACKLIST_BUTTON);
+ // Whether the blocklist is currently ignored.
+ const ignored = (ignoreButton.textContent == ENABLE_BLOCKLIST_BUTTON);
// Try to reverse the ignore status.
- pageHandler.setIgnorePreviewsBlacklistDecision(!ignored);
+ pageHandler.setIgnorePreviewsBlocklistDecision(!ignored);
});
}
diff --git a/chromium/chrome/browser/resources/invalidations/about_invalidations.html b/chromium/chrome/browser/resources/invalidations/about_invalidations.html
index d49aa981879..e15459fd78c 100644
--- a/chromium/chrome/browser/resources/invalidations/about_invalidations.html
+++ b/chromium/chrome/browser/resources/invalidations/about_invalidations.html
@@ -4,7 +4,6 @@
<meta charset="utf-8">
<title>Invalidations</title>
<script src="chrome://resources/js/cr.js"></script>
- <script src="chrome://resources/js/parse_html_subset.js"></script>
<script src="chrome://resources/js/util.js"></script>
<script src="chrome://invalidations/about_invalidations.js"></script>
<link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
diff --git a/chromium/chrome/browser/resources/invalidations/invalidations_resources.grd b/chromium/chrome/browser/resources/invalidations/invalidations_resources.grd
index ee62de0daf7..8fdd278a0b7 100644
--- a/chromium/chrome/browser/resources/invalidations/invalidations_resources.grd
+++ b/chromium/chrome/browser/resources/invalidations/invalidations_resources.grd
@@ -8,9 +8,9 @@
</outputs>
<release seq="1">
<includes>
- <include name="IDR_ABOUT_INVALIDATIONS_HTML" file="about_invalidations.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_ABOUT_INVALIDATIONS_JS" file="about_invalidations.js" type="BINDATA" compress="gzip" />
- <include name="IDR_ABOUT_INVALIDATIONS_CSS" file="about_invalidations.css" type="BINDATA" compress="gzip" />
+ <include name="IDR_ABOUT_INVALIDATIONS_HTML" file="about_invalidations.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_ABOUT_INVALIDATIONS_JS" file="about_invalidations.js" type="BINDATA" />
+ <include name="IDR_ABOUT_INVALIDATIONS_CSS" file="about_invalidations.css" type="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/local_ntp/externs.js b/chromium/chrome/browser/resources/local_ntp/externs.js
index a23b3244f00..11ad0c32056 100644
--- a/chromium/chrome/browser/resources/local_ntp/externs.js
+++ b/chromium/chrome/browser/resources/local_ntp/externs.js
@@ -33,7 +33,6 @@ let MostVisitedData;
* realboxEnabled: boolean,
* realboxMatchOmniboxTheme: boolean,
* richerPicker: boolean,
- * suggestionTransparencyEnabled: boolean,
* translatedStrings: Object<string>}}
*/
let configData;
diff --git a/chromium/chrome/browser/resources/local_ntp/icons.grdp b/chromium/chrome/browser/resources/local_ntp/icons.grdp
index 23d21d00472..b009d3e158e 100644
--- a/chromium/chrome/browser/resources/local_ntp/icons.grdp
+++ b/chromium/chrome/browser/resources/local_ntp/icons.grdp
@@ -1,31 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<grit-part>
<include name="IDR_LOCAL_NTP_ICONS_BOOKMARK"
- file="resources/local_ntp/icons/bookmark.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/bookmark.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_CALCULATOR"
- file="resources/local_ntp/icons/calculator.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/calculator.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_CLOCK"
- file="resources/local_ntp/icons/clock.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/clock.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_DRIVE_DOCS"
- file="resources/local_ntp/icons/drive_docs.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/drive_docs.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_DRIVE_FOLDER"
- file="resources/local_ntp/icons/drive_folder.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/drive_folder.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_DRIVE_FORM"
- file="resources/local_ntp/icons/drive_form.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/drive_form.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_DRIVE_IMAGE"
- file="resources/local_ntp/icons/drive_image.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/drive_image.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_DRIVE_LOGO"
- file="resources/local_ntp/icons/drive_logo.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/drive_logo.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_DRIVE_PDF"
- file="resources/local_ntp/icons/drive_pdf.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/drive_pdf.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_DRIVE_SHEETS"
- file="resources/local_ntp/icons/drive_sheets.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/drive_sheets.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_DRIVE_SLIDES"
- file="resources/local_ntp/icons/drive_slides.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/drive_slides.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_DRIVE_VIDEO"
- file="resources/local_ntp/icons/drive_video.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/drive_video.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_EXTENSION_APP"
- file="resources/local_ntp/icons/extension_app.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/extension_app.svg" type="BINDATA" />
<include name="IDR_LOCAL_NTP_ICONS_PAGE"
- file="resources/local_ntp/icons/page.svg" type="BINDATA" compress="gzip" />
+ file="resources/local_ntp/icons/page.svg" type="BINDATA" />
</grit-part>
diff --git a/chromium/chrome/browser/resources/local_ntp/local_ntp.js b/chromium/chrome/browser/resources/local_ntp/local_ntp.js
index 15950635804..d9d58e1ddef 100644
--- a/chromium/chrome/browser/resources/local_ntp/local_ntp.js
+++ b/chromium/chrome/browser/resources/local_ntp/local_ntp.js
@@ -1686,29 +1686,25 @@ function renderAutocompleteMatches(matches, suggestionGroupsMap) {
* @param {!function()} callback
*/
function createActionButton(callback) {
- const icon = document.createElement('button');
+ const icon = document.createElement('div');
icon.classList.add(CLASSES.REMOVE_ICON);
- icon.tabIndex = -1;
- icon.onmousedown = e => {
+ const action = document.createElement('button');
+ action.classList.add(CLASSES.REMOVE_MATCH);
+ action.appendChild(icon);
+ action.onmousedown = e => {
e.preventDefault(); // Stops default browser action (focus)
};
- icon.onauxclick = e => {
+ action.onauxclick = e => {
if (e.button == 1) {
// Middle click on delete should just noop for now (matches omnibox).
e.preventDefault();
}
};
- icon.onclick = e => {
+ action.onclick = e => {
callback();
e.preventDefault(); // Stops default browser action (navigation)
};
- const action = document.createElement('div');
-
- action.classList.add(CLASSES.REMOVE_MATCH);
- action.tabIndex = 0;
- action.setAttribute('role', 'button');
- action.appendChild(icon);
return action;
}
@@ -1747,18 +1743,18 @@ function renderAutocompleteMatches(matches, suggestionGroupsMap) {
// preventing the popup from losing focus and closing as a result.
headerEl.tabIndex = -1;
headerEl.append(document.createTextNode(suggestionGroup.header));
- if (configData.suggestionTransparencyEnabled) {
- const toggle = createActionButton(() => {
- groupEl.classList.toggle(CLASSES.COLLAPSED);
- updateToggleButtonA11y(
- toggle, groupEl.classList.contains(CLASSES.COLLAPSED));
- window.chrome.embeddedSearch.searchBox
- .toggleSuggestionGroupIdVisibility(suggestionGroupId);
- });
- updateToggleButtonA11y(toggle, suggestionGroup.hidden);
- headerEl.appendChild(toggle);
- realboxMatchesEl.classList.add(CLASSES.REMOVABLE);
- }
+
+ const toggle = createActionButton(() => {
+ groupEl.classList.toggle(CLASSES.COLLAPSED);
+ updateToggleButtonA11y(
+ toggle, groupEl.classList.contains(CLASSES.COLLAPSED));
+ window.chrome.embeddedSearch.searchBox.toggleSuggestionGroupIdVisibility(
+ suggestionGroupId);
+ });
+ updateToggleButtonA11y(toggle, suggestionGroup.hidden);
+ headerEl.appendChild(toggle);
+ realboxMatchesEl.classList.add(CLASSES.REMOVABLE);
+
groupEl.appendChild(headerEl);
realboxMatchesEl.appendChild(groupEl);
suggestionGroupElsMap[suggestionGroupId] = groupEl;
@@ -1852,7 +1848,7 @@ function renderAutocompleteMatches(matches, suggestionGroupsMap) {
}
}
- if (match.supportsDeletion && configData.suggestionTransparencyEnabled) {
+ if (match.supportsDeletion) {
const remove = createActionButton(() => {
window.chrome.embeddedSearch.searchBox.deleteAutocompleteMatch(i);
});
diff --git a/chromium/chrome/browser/resources/local_ntp/voice.js b/chromium/chrome/browser/resources/local_ntp/voice.js
index bb8ce4fa6b6..7d88c54feb2 100644
--- a/chromium/chrome/browser/resources/local_ntp/voice.js
+++ b/chromium/chrome/browser/resources/local_ntp/voice.js
@@ -31,7 +31,7 @@ function getChromeUILanguage() {
*/
const LOG_TYPE = {
// Activated by clicking on the fakebox icon.
- ACTION_ACTIVATE_FAKEBOX: 13,
+ ACTION_ACTIVATE_SEARCH_BOX: 13,
// Activated by keyboard shortcut.
ACTION_ACTIVATE_KEYBOARD: 14,
// Close the voice overlay by a user's explicit action.
@@ -308,7 +308,7 @@ speech.init = function(
fakeboxMicrophoneElem.onclick = function(event) {
// If propagated, closes the overlay (click on the background).
event.stopPropagation();
- speech.logEvent(LOG_TYPE.ACTION_ACTIVATE_FAKEBOX);
+ speech.logEvent(LOG_TYPE.ACTION_ACTIVATE_SEARCH_BOX);
speech.start();
};
fakeboxMicrophoneElem.onkeydown = function(event) {
diff --git a/chromium/chrome/browser/resources/management/management_browser_proxy.js b/chromium/chrome/browser/resources/management/management_browser_proxy.js
index cf4a5a30586..4510d679e01 100644
--- a/chromium/chrome/browser/resources/management/management_browser_proxy.js
+++ b/chromium/chrome/browser/resources/management/management_browser_proxy.js
@@ -69,6 +69,7 @@ export const DeviceReportingType = {
STATISTIC: 'device statistics',
DEVICE: 'device',
CRASH_REPORT: 'crash report',
+ APP_INFO_AND_ACTIVITY: 'app info and activity',
LOGS: 'logs',
PRINT: 'print',
CROSTINI: 'crostini',
diff --git a/chromium/chrome/browser/resources/management/management_ui.html b/chromium/chrome/browser/resources/management/management_ui.html
index 0cb46863ce2..f2f414ce0e3 100644
--- a/chromium/chrome/browser/resources/management/management_ui.html
+++ b/chromium/chrome/browser/resources/management/management_ui.html
@@ -195,9 +195,9 @@
</div>
<table class="content-indented">
<tr>
- <th class="protection-name">$i18n{extensionName}</th>
+ <th class="protection-name">$i18n{connectorEvent}</th>
<th class="protection-permissions">
- $i18n{extensionPermissions}
+ $i18n{connectorVisibleData}
</th>
</tr>
<template is="dom-repeat"
diff --git a/chromium/chrome/browser/resources/management/management_ui.js b/chromium/chrome/browser/resources/management/management_ui.js
index 765261447a9..b928315c798 100644
--- a/chromium/chrome/browser/resources/management/management_ui.js
+++ b/chromium/chrome/browser/resources/management/management_ui.js
@@ -221,6 +221,8 @@ Polymer({
return 'cr:computer';
case DeviceReportingType.CRASH_REPORT:
return 'management:crash';
+ case DeviceReportingType.APP_INFO_AND_ACTIVITY:
+ return 'management:timelapse';
case DeviceReportingType.LOGS:
return 'management:report';
case DeviceReportingType.PRINT:
diff --git a/chromium/chrome/browser/resources/media/media_data_table.js b/chromium/chrome/browser/resources/media/media_data_table.js
index 758ace61120..96e21e7f814 100644
--- a/chromium/chrome/browser/resources/media/media_data_table.js
+++ b/chromium/chrome/browser/resources/media/media_data_table.js
@@ -44,7 +44,7 @@ cr.define('cr.ui', function() {
render() {
// Find the body of the table and clear it.
const body = this.table_.querySelectorAll('tbody')[0];
- body.innerHTML = '';
+ body.innerHTML = trustedTypes.emptyHTML;
// Get the sort key from the columns to determine which data should be in
// which column.
diff --git a/chromium/chrome/browser/resources/media/media_feeds.html b/chromium/chrome/browser/resources/media/media_feeds.html
index 74429bf95b2..e6919df0c4b 100644
--- a/chromium/chrome/browser/resources/media/media_feeds.html
+++ b/chromium/chrome/browser/resources/media/media_feeds.html
@@ -80,6 +80,10 @@
content: '▼';
position: absolute;
}
+
+ div#fetch-logs-content {
+ color: red;
+ }
</style>
</head>
<body>
@@ -147,8 +151,11 @@
<th sort-key="resetReason">
Reset Reason
</th>
- <th data-key="associatedOrigins">
- Associated Origins
+ <th data-key="cookieNameFilter">
+ Cookie Name Filter
+ </th>
+ <th data-key="safeSearchResult">
+ Safe Search Result
</th>
<th data-key="logos">
Logos
@@ -233,6 +240,10 @@
<tbody>
</tbody>
</table>
+ <div id="fetch-logs">
+ <h3>Fetch logs:</h3>
+ <div id="fetch-logs-content"></div>
+ </div>
</div>
</body>
</html>
diff --git a/chromium/chrome/browser/resources/media/media_feeds.js b/chromium/chrome/browser/resources/media/media_feeds.js
index 8ec4bee66af..09dd402294b 100644
--- a/chromium/chrome/browser/resources/media/media_feeds.js
+++ b/chromium/chrome/browser/resources/media/media_feeds.js
@@ -21,9 +21,16 @@ function whenConfigTableIsPopulatedForTest() {
return mediaFeedsConfigTableIsPopulatedResolver.promise;
}
-const mediaFeedsConfigTableIsUpdatedResolver = new PromiseResolver();
-function whenConfigTableIsUpdatedForTest() {
- return mediaFeedsConfigTableIsUpdatedResolver.promise;
+const mediaFeedsConfigTableSafeSearchPrefIsUpdatedResolver =
+ new PromiseResolver();
+function whenConfigTableSafeSearchPrefIsUpdatedForTest() {
+ return mediaFeedsConfigTableSafeSearchPrefIsUpdatedResolver.promise;
+}
+
+const mediaFeedsConfigTableBackgroundFetchingPrefIsUpdatedResolver =
+ new PromiseResolver();
+function whenConfigTableBackgroundFetchingPrefIsUpdatedForTest() {
+ return mediaFeedsConfigTableBackgroundFetchingPrefIsUpdatedResolver.promise;
}
(function() {
@@ -53,6 +60,10 @@ class MediaFeedsTableDelegate {
a.addEventListener('click', () => {
showFeedContents(dataRow);
+
+ // Clear old logs and hide the area from display.
+ $('fetch-logs').style.display = 'none';
+ $('fetch-logs-content').textContent = '';
});
td.appendChild(document.createElement('br'));
@@ -66,6 +77,9 @@ class MediaFeedsTableDelegate {
store.fetchMediaFeed(dataRow.id).then(response => {
updateFeedsTable();
showFeedContents(dataRow);
+
+ $('fetch-logs').style.display = 'block';
+ $('fetch-logs-content').textContent = response.logs;
});
});
}
@@ -155,7 +169,20 @@ class MediaFeedsTableDelegate {
td.textContent = 'Movie';
break;
}
- } else if (key == 'isFamilyFriendly' || key == 'clicked') {
+ } else if (key == 'isFamilyFriendly') {
+ // Format a IsFamilyFriendly.
+ switch (parseInt(data, 10)) {
+ case mediaFeeds.mojom.IsFamilyFriendly.kUnknown:
+ td.textContent = 'Unknown';
+ break;
+ case mediaFeeds.mojom.IsFamilyFriendly.kYes:
+ td.textContent = 'Yes';
+ break;
+ case mediaFeeds.mojom.IsFamilyFriendly.kNo:
+ td.textContent = 'No';
+ break;
+ }
+ } else if (key == 'clicked') {
// Format a boolean.
td.textContent = data ? 'Yes' : 'No';
} else if (key == 'actionStatus') {
@@ -291,16 +318,6 @@ class MediaFeedsTableDelegate {
td.textContent = 'Cache';
break;
}
- } else if (key === 'associatedOrigins') {
- // Format the array of origins.
- const origins = [];
-
- data.forEach((origin) => {
- const {scheme, host, port} = origin;
- origins.push(new URL(`${scheme}://${host}:${port}`).origin);
- });
-
- td.textContent = origins.join(', ');
} else if (key === 'userIdentifier') {
if (data) {
td.textContent = 'Name=' + data.name;
@@ -338,7 +355,7 @@ class MediaFeedsTableDelegate {
sortKey === 'fetchFailedCount' || sortKey === 'lastFetchItemCount' ||
sortKey === 'lastFetchPlayNextCount' ||
sortKey === 'lastFetchContentTypes' || sortKey === 'safeSearchResult' ||
- sortKey === 'type') {
+ sortKey === 'type' || sortKey === 'cookieNameFilter') {
return val1 > val2 ? 1 : -1;
} else if (
sortKey === 'lastDiscoveryTime' || sortKey === 'lastFetchTime' ||
@@ -541,7 +558,7 @@ function createConfigRowWithToggle(name, value, clickAction) {
* @param {!mediaFeeds.mojom.DebugInformation} info The debug info
*/
function renderConfigTable(info) {
- configTableBody.innerHTML = '';
+ configTableBody.innerHTML = trustedTypes.emptyHTML;
configTableBody.appendChild(createConfigRow(
'Safe Search Enabled (value)',
@@ -552,9 +569,26 @@ function renderConfigTable(info) {
() => {
store.setSafeSearchEnabledPref(!info.safeSearchPrefValue).then(() => {
updateConfigTable().then(
- () => mediaFeedsConfigTableIsUpdatedResolver.resolve());
+ () => mediaFeedsConfigTableSafeSearchPrefIsUpdatedResolver
+ .resolve());
});
}));
+
+ configTableBody.appendChild(createConfigRow(
+ 'Background Fetching Enabled (value)',
+ formatFeatureFlag(info.backgroundFetchingFeatureEnabled)));
+
+ configTableBody.appendChild(createConfigRowWithToggle(
+ 'Background Fetching Enabled (pref)',
+ formatFeatureFlag(info.backgroundFetchingPrefValue), () => {
+ store.setBackgroundFetchingPref(!info.backgroundFetchingPrefValue)
+ .then(() => {
+ updateConfigTable().then(
+ () =>
+ mediaFeedsConfigTableBackgroundFetchingPrefIsUpdatedResolver
+ .resolve());
+ });
+ }));
}
/**
diff --git a/chromium/chrome/browser/resources/media/media_history.js b/chromium/chrome/browser/resources/media/media_history.js
index 30c66de2df0..a0c2ad69f57 100644
--- a/chromium/chrome/browser/resources/media/media_history.js
+++ b/chromium/chrome/browser/resources/media/media_history.js
@@ -160,7 +160,7 @@ function decodeString16(arr) {
* History store.
*/
function renderStatsTable(stats) {
- statsTableBody.innerHTML = '';
+ statsTableBody.innerHTML = trustedTypes.emptyHTML;
Object.keys(stats.tableRowCounts).forEach((key) => {
statsTableBody.appendChild(createStatsRow(key, stats.tableRowCounts[key]));
diff --git a/chromium/chrome/browser/resources/media/webrtc_logs_resources.grd b/chromium/chrome/browser/resources/media/webrtc_logs_resources.grd
index d4620a3d4ad..030e50ffc1b 100644
--- a/chromium/chrome/browser/resources/media/webrtc_logs_resources.grd
+++ b/chromium/chrome/browser/resources/media/webrtc_logs_resources.grd
@@ -14,12 +14,10 @@
file="webrtc_logs.html"
flattenhtml="true"
allowexternalscript="true"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_WEBRTC_LOGS_JS"
file="webrtc_logs.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/nearby_internals/BUILD.gn b/chromium/chrome/browser/resources/nearby_internals/BUILD.gn
new file mode 100644
index 00000000000..71c035040b5
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_internals/BUILD.gn
@@ -0,0 +1,21 @@
+# Copyright 2020 The Chromium 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")
+import("//tools/polymer/html_to_js.gni")
+
+js_type_check("closure_compile") {
+ is_polymer3 = true
+ deps = [ ":nearby_internals" ]
+}
+
+js_library("nearby_internals") {
+ deps = [
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ ]
+}
+
+html_to_js("web_components") {
+ js_files = [ "nearby_internals.js" ]
+}
diff --git a/chromium/chrome/browser/resources/nearby_internals/OWNERS b/chromium/chrome/browser/resources/nearby_internals/OWNERS
new file mode 100644
index 00000000000..19414dc942a
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_internals/OWNERS
@@ -0,0 +1,4 @@
+file://chrome/browser/nearby_sharing/OWNERS
+khorimoto@chromium.org
+
+# COMPONENT: OS>Systems>Multidevice>Nearby
diff --git a/chromium/chrome/browser/resources/nearby_internals/index.html b/chromium/chrome/browser/resources/nearby_internals/index.html
new file mode 100644
index 00000000000..eb4fd150fc2
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_internals/index.html
@@ -0,0 +1,17 @@
+<!doctype html>
+<html dir="$i18n{textdirection}" lang="$i18n{language}">
+ <head>
+ <meta charset="utf-8">
+ <base href="chrome://nearby-internals">
+ <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
+ <style>
+ body {
+ margin: 0;
+ }
+ </style>
+ </head>
+ <body>
+ <nearby-internals></nearby-internals>
+ <script type="module" src="nearby_internals.js"></script>
+ </body>
+</html>
diff --git a/chromium/chrome/browser/resources/nearby_internals/nearby_internals.html b/chromium/chrome/browser/resources/nearby_internals/nearby_internals.html
new file mode 100644
index 00000000000..ff39aaf9aee
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_internals/nearby_internals.html
@@ -0,0 +1 @@
+<h1>Hello, world!!</h1>
diff --git a/chromium/chrome/browser/resources/nearby_internals/nearby_internals.js b/chromium/chrome/browser/resources/nearby_internals/nearby_internals.js
new file mode 100644
index 00000000000..a7f1da3568b
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_internals/nearby_internals.js
@@ -0,0 +1,11 @@
+// Copyright 2020 The Chromium 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 {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+Polymer({
+ is: 'nearby-internals',
+
+ _template: html`{__html_template__}`,
+});
diff --git a/chromium/chrome/browser/resources/nearby_internals/nearby_internals_resources.grd b/chromium/chrome/browser/resources/nearby_internals/nearby_internals_resources.grd
new file mode 100644
index 00000000000..d7477df60d6
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_internals/nearby_internals_resources.grd
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<grit latest_public_release="0" current_release="1" output_all_resource_defines="false">
+ <outputs>
+ <output filename="grit/nearby_internals_resources.h" type="rc_header">
+ <emit emit_type='prepend'></emit>
+ </output>
+ <output filename="grit/nearby_internals_resources_map.cc"
+ type="resource_file_map_source" />
+ <output filename="grit/nearby_internals_resources_map.h"
+ type="resource_map_header" />
+ <output filename="nearby_internals_resources.pak" type="data_package" />
+ </outputs>
+ <release seq="1">
+ <includes>
+ <include name="IDR_NEARBY_INTERNALS_INDEX_HTML"
+ file="index.html"
+ type="BINDATA"/>
+ <include name="IDR_NEARBY_INTERNALS_NEARBY_INTERNALS_JS"
+ file="${root_gen_dir}\chrome\browser\resources\nearby_internals\nearby_internals.js"
+ use_base_dir="false"
+ type="BINDATA"/>
+ </includes>
+ </release>
+</grit>
diff --git a/chromium/chrome/browser/resources/nearby_share/BUILD.gn b/chromium/chrome/browser/resources/nearby_share/BUILD.gn
new file mode 100644
index 00000000000..543394e5aaf
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_share/BUILD.gn
@@ -0,0 +1,35 @@
+# Copyright 2020 The Chromium 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")
+import("//tools/polymer/html_to_js.gni")
+
+js_type_check("closure_compile") {
+ is_polymer3 = true
+ deps = [
+ ":app",
+ ":nearby_discovery_page",
+ ]
+}
+
+js_library("app") {
+ deps = [
+ ":nearby_discovery_page",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/cr_elements/cr_view_manager:cr_view_manager.m",
+ ]
+}
+
+js_library("nearby_discovery_page") {
+ deps = [
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ ]
+}
+
+html_to_js("web_components") {
+ js_files = [
+ "app.js",
+ "nearby_discovery_page.js",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/nearby_share/OWNERS b/chromium/chrome/browser/resources/nearby_share/OWNERS
new file mode 100644
index 00000000000..72feb28bcca
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_share/OWNERS
@@ -0,0 +1,3 @@
+file://chrome/browser/nearby_sharing/OWNERS
+
+# COMPONENT: UI>Browser>Sharing>Nearby
diff --git a/chromium/chrome/browser/resources/nearby_share/app.html b/chromium/chrome/browser/resources/nearby_share/app.html
new file mode 100644
index 00000000000..e16336c4164
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_share/app.html
@@ -0,0 +1,4 @@
+<cr-view-manager id="viewManager">
+ <nearby-discovery-page id="[[Page.DISCOVERY]]" slot="view" class="active">
+ </nearby-discovery-page>
+</cr-view-manager>
diff --git a/chromium/chrome/browser/resources/nearby_share/app.js b/chromium/chrome/browser/resources/nearby_share/app.js
new file mode 100644
index 00000000000..fc77eb7ac2a
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_share/app.js
@@ -0,0 +1,34 @@
+// Copyright 2020 The Chromium 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 The 'nearby-share' component is the entry point for the Nearby
+ * Share flow. It is used as a standalone dialog via chrome://nearby and as part
+ * of the ChromeOS share sheet.
+ */
+
+import 'chrome://resources/cr_elements/cr_view_manager/cr_view_manager.m.js';
+import './nearby_discovery_page.js';
+import './strings.m.js';
+
+import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+/** @enum {string} */
+const Page = {
+ DISCOVERY: 'discovery',
+};
+
+Polymer({
+ is: 'nearby-share-app',
+
+ _template: html`{__html_template__}`,
+
+ properties: {
+ /** Mirroring the enum so that it can be used from HTML bindings. */
+ Page: {
+ type: Object,
+ value: Page,
+ },
+ },
+});
diff --git a/chromium/chrome/browser/resources/nearby_share/nearby_discovery_page.html b/chromium/chrome/browser/resources/nearby_share/nearby_discovery_page.html
new file mode 100644
index 00000000000..cea179efa55
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_share/nearby_discovery_page.html
@@ -0,0 +1 @@
+<h1>Nearby Discovery Page</h1>
diff --git a/chromium/chrome/browser/resources/nearby_share/nearby_discovery_page.js b/chromium/chrome/browser/resources/nearby_share/nearby_discovery_page.js
new file mode 100644
index 00000000000..9b3308669a4
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_share/nearby_discovery_page.js
@@ -0,0 +1,16 @@
+// Copyright 2020 The Chromium 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 The 'nearby-discovery-page' component shows the discovery UI of
+ * the Nearby Share flow. It shows a list of devices to select from.
+ */
+
+import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+Polymer({
+ is: 'nearby-discovery-page',
+
+ _template: html`{__html_template__}`,
+});
diff --git a/chromium/chrome/browser/resources/nearby_share/nearby_share_dialog.html b/chromium/chrome/browser/resources/nearby_share/nearby_share_dialog.html
new file mode 100644
index 00000000000..0417789bc2f
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_share/nearby_share_dialog.html
@@ -0,0 +1,17 @@
+<!doctype html>
+<html dir="$i18n{textdirection}" lang="$i18n{language}">
+ <head>
+ <meta charset="utf-8">
+ <base href="chrome://nearby">
+ <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
+ <style>
+ body {
+ margin: 0;
+ }
+ </style>
+ </head>
+ <body>
+ <nearby-share-app></nearby-share-app>
+ <script type="module" src="app.js"></script>
+ </body>
+</html>
diff --git a/chromium/chrome/browser/resources/nearby_share/nearby_share_dialog_resources.grd b/chromium/chrome/browser/resources/nearby_share/nearby_share_dialog_resources.grd
new file mode 100644
index 00000000000..96a629ef628
--- /dev/null
+++ b/chromium/chrome/browser/resources/nearby_share/nearby_share_dialog_resources.grd
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<grit latest_public_release="0" current_release="1" output_all_resource_defines="false">
+ <outputs>
+ <output filename="grit/nearby_share_dialog_resources.h" type="rc_header">
+ <emit emit_type='prepend'></emit>
+ </output>
+ <output filename="grit/nearby_share_dialog_resources_map.cc"
+ type="resource_file_map_source" />
+ <output filename="grit/nearby_share_dialog_resources_map.h"
+ type="resource_map_header" />
+ <output filename="nearby_share_dialog_resources.pak" type="data_package" />
+ </outputs>
+ <release seq="1">
+ <includes>
+ <include name="IDR_NEARBY_SHARE_NEARBY_SHARE_DIALOG_HTML"
+ file="nearby_share_dialog.html"
+ type="BINDATA"/>
+
+ <!-- Generated Polymer 3 elements -->
+ <include name="IDR_NEARBY_SHARE_APP_JS"
+ file="${root_gen_dir}/chrome/browser/resources/nearby_share/app.js"
+ use_base_dir="false" type="BINDATA"/>
+ <include name="IDR_NEARBY_SHARE_NEARBY_DISCOVERY_PAGE_JS"
+ file="${root_gen_dir}/chrome/browser/resources/nearby_share/nearby_discovery_page.js"
+ use_base_dir="false" type="BINDATA"/>
+ </includes>
+ </release>
+</grit>
diff --git a/chromium/chrome/browser/resources/net_internals/browser_bridge.js b/chromium/chrome/browser/resources/net_internals/browser_bridge.js
index fac5fb1d4d1..5c26ac203d6 100644
--- a/chromium/chrome/browser/resources/net_internals/browser_bridge.js
+++ b/chromium/chrome/browser/resources/net_internals/browser_bridge.js
@@ -18,8 +18,6 @@ const BrowserBridge = (function() {
// List of observers for various bits of browser state.
this.hstsObservers_ = [];
this.expectCTObservers_ = [];
- this.crosONCFileParseObservers_ = [];
- this.storeDebugLogsObservers_ = [];
this.setNetworkDebugModeObservers_ = [];
}
@@ -89,22 +87,6 @@ const BrowserBridge = (function() {
this.send('flushSocketPools');
},
- importONCFile(fileContent, passcode) {
- this.send('importONCFile', [fileContent, passcode]);
- },
-
- storeDebugLogs() {
- this.send('storeDebugLogs');
- },
-
- storeCombinedDebugLogs() {
- this.send('storeCombinedDebugLogs');
- },
-
- storeFeedbackSystemLogs() {
- this.send('storeFeedbackSystemLogs');
- },
-
setNetworkDebugMode(subsystem) {
this.send('setNetworkDebugMode', [subsystem]);
},
@@ -135,30 +117,6 @@ const BrowserBridge = (function() {
}
},
- receivedONCFileParse(error) {
- for (let i = 0; i < this.crosONCFileParseObservers_.length; i++) {
- this.crosONCFileParseObservers_[i].onONCFileParse(error);
- }
- },
-
- receivedStoreDebugLogs(status) {
- for (let i = 0; i < this.storeDebugLogsObservers_.length; i++) {
- this.storeDebugLogsObservers_[i].onStoreDebugLogs(status);
- }
- },
-
- receivedStoreCombinedDebugLogs(status) {
- for (let i = 0; i < this.storeDebugLogsObservers_.length; i++) {
- this.storeDebugLogsObservers_[i].onStoreCombinedDebugLogs(status);
- }
- },
-
- receivedStoreFeedbackSystemLogs(status) {
- for (let i = 0; i < this.storeDebugLogsObservers_.length; i++) {
- this.storeDebugLogsObservers_[i].onStoreFeedbackSystemLogs(status);
- }
- },
-
receivedSetNetworkDebugMode(status) {
for (let i = 0; i < this.setNetworkDebugModeObservers_.length; i++) {
this.setNetworkDebugModeObservers_[i].onSetNetworkDebugMode(status);
@@ -188,27 +146,6 @@ const BrowserBridge = (function() {
},
/**
- * Adds a listener for ONC file parse status. The observer will be called
- * back with:
- *
- * observer.onONCFileParse(error);
- */
- addCrosONCFileParseObserver(observer) {
- this.crosONCFileParseObservers_.push(observer);
- },
-
- /**
- * Adds a listener for storing log file status. The observer will be called
- * back with:
- *
- * observer.onStoreDebugLogs(status);
- * observer.onStoreCombinedDebugLogs(status);
- */
- addStoreDebugLogsObserver(observer) {
- this.storeDebugLogsObservers_.push(observer);
- },
-
- /**
* Adds a listener for network debugging mode status. The observer
* will be called back with:
*
diff --git a/chromium/chrome/browser/resources/net_internals/chromeos_view.html b/chromium/chrome/browser/resources/net_internals/chromeos_view.html
index ac4ae56ec08..71c81564e28 100644
--- a/chromium/chrome/browser/resources/net_internals/chromeos_view.html
+++ b/chromium/chrome/browser/resources/net_internals/chromeos_view.html
@@ -1,76 +1,19 @@
<div id="chromeos-view-tab-content" class=content-box>
<h4 style='margin-top:0'>Import ONC file</h4>
- <div id="chromeos-view-import-div">
- <label>Import ONC File
- <input type="file" id="chromeos-view-import-onc">
- </label>
+ <div>
+ Import ONC File has moved to
+ <a href="chrome://network#general">chrome://network#general</a>.
</div>
- <div id="chromeos-view-password-div" hidden>
- This onc file appears to be encrypted. Please provide the decryption key:
- <div>
- <input type="password" id="chromeos-view-onc-password">
- </div>
+
+ <h4>Store system logs</h4>
+ <div>
+ Store system logs has moved to
+ <a href="chrome://network#logs">chrome://network#logs</a>.
</div>
- <div id="chromeos-view-parse-status" hidden>
- </div>
- <div id="chromeos-view-store-debug-logs-div">
- <h4>Store system logs</h4>
- <div>
- <p>This stores system_logs_{date}-{time}.txt.zip to the Downloads
- directory. The archive contains a single file identical to the
- system_logs file attached to Feedback reports.</p>
- <p>Also writes a policies_{date}-{time}.json file for providing policy
- configurations when that might be a factor.</p>
- <p>Prefer this when uploading logs to issues or sending logs to developers
- (unless otherwise requested).</p>
- <input type="button"
- id="chromeos-view-store-feedback-system-logs"
- value="Store Feedback Report System Logs">
- <label id="chromeos-view-store-feedback-system-logs-status"></label>
- </div>
- <h4>Store debugd system logs</h4>
- <div>
- <p>This stores the logs collected by debugd as individual files in a
- single archive file in the Downloads directory:
- debug-logs_{date}-{time}.tgz.
- </p>
- <p>Also writes a policies_{date}-{time}.json file for providing policy
- configurations when that might be a factor.</p>
- <input type="button"
- id="chromeos-view-store-debug-logs"
- value="Store System Logs">
- <label id="chromeos-view-store-debug-logs-status"></label>
- </div>
- <div>
- <p>Identical to the above, but also incldes the Chrome user logs.
- The output file is named combined-logs_{date}-{time}.tgz.</p>
- <input type="button"
- id="chromeos-view-store-combined-debug-logs"
- value="Store System and User Logs">
- <label id="chromeos-view-store-combined-debug-logs-status"></label>
- </div>
- </div>
- <div id="chromeos-view-network-debugging-div">
- <h4>Network Debugging</h4>
- <dl>
- <dt>Select interface for debugging</dt>
- <dd>
- <input type="button"
- value="Wi-Fi"
- id="chromeos-view-network-debugging-wifi">
- <input type="button"
- value="Ethernet"
- id="chromeos-view-network-debugging-ethernet">
- <input type="button"
- value="Cellular"
- id="chromeos-view-network-debugging-cellular">
- <input type="button"
- name="subsystem"
- value="None"
- id="chromeos-view-network-debugging-none">
- </dd>
- </dl>
- <label id="chromeos-view-network-debugging-status">
- </label>
+
+ <h4>Network Debugging</h4>
+ <div>
+ Network Debugging has moved to
+ <a href="chrome://network#logs">chrome://network#logs</a>.
</div>
</div>
diff --git a/chromium/chrome/browser/resources/net_internals/chromeos_view.js b/chromium/chrome/browser/resources/net_internals/chromeos_view.js
index 07022b53664..253465ccd60 100644
--- a/chromium/chrome/browser/resources/net_internals/chromeos_view.js
+++ b/chromium/chrome/browser/resources/net_internals/chromeos_view.js
@@ -8,225 +8,6 @@
const CrosView = (function() {
'use strict';
- let fileContent;
- let passcode = '';
-
- /**
- * Clear file input div
- *
- * @private
- */
- function clearFileInput_() {
- $(CrosView.IMPORT_DIV_ID).innerHTML = $(CrosView.IMPORT_DIV_ID).innerHTML;
- $(CrosView.IMPORT_ONC_ID)
- .addEventListener('change', handleFileChangeEvent_, false);
- }
-
- /**
- * Send file contents and passcode to C++ cros network library.
- *
- * @private
- */
- function importONCFile_() {
- clearParseStatus_();
- if (fileContent) {
- g_browser.importONCFile(fileContent, passcode);
- } else {
- setParseStatus_('ONC file parse failed: cannot read file');
- }
- clearFileInput_();
- }
-
- /**
- * Set the passcode var, and trigger onc import.
- *
- * @param {string} value The passcode value.
- * @private
- */
- function setPasscode_(value) {
- passcode = value;
- if (passcode) {
- importONCFile_();
- }
- }
-
- /**
- * Unhide the passcode prompt input field and give it focus.
- *
- * @private
- */
- function promptForPasscode_() {
- $(CrosView.PASSCODE_ID).hidden = false;
- $(CrosView.PASSCODE_INPUT_ID).focus();
- $(CrosView.PASSCODE_INPUT_ID).select();
- }
-
- /**
- * Set the fileContent var, and trigger onc import if the file appears to
- * not be encrypted, or prompt for passcode if the file is encrypted.
- *
- * @private
- * @param {string} text contents of selected file.
- */
- function setFileContent_(result) {
- fileContent = result;
- // Parse the JSON to get at the top level "Type" property.
- let jsonObject;
- // Ignore any parse errors: they'll get handled in the C++ import code.
- try {
- jsonObject = JSON.parse(fileContent);
- } catch (error) {
- }
- // Check if file is encrypted.
- if (jsonObject && jsonObject.hasOwnProperty('Type') &&
- jsonObject.Type == 'EncryptedConfiguration') {
- promptForPasscode_();
- } else {
- importONCFile_();
- }
- }
-
- /**
- * Clear ONC file parse status. Clears and hides the parse status div.
- *
- * @private
- */
- function clearParseStatus_(error) {
- const parseStatus = $(CrosView.PARSE_STATUS_ID);
- parseStatus.hidden = true;
- parseStatus.textContent = '';
- }
-
- /**
- * Set ONC file parse status.
- *
- * @private
- */
- function setParseStatus_(error) {
- const parseStatus = $(CrosView.PARSE_STATUS_ID);
- parseStatus.hidden = false;
- parseStatus.textContent = error ? 'ONC file parse failed: ' + error :
- 'ONC file successfully parsed';
- reset_();
- }
-
- /**
- * Set storing debug logs status.
- *
- * @private
- */
- function setStoreDebugLogsStatus_(status) {
- $(CrosView.STORE_DEBUG_LOGS_STATUS_ID).innerText = status;
- }
-
-
- /**
- * Set storing combined debug logs status.
- *
- * @private
- */
- function setStoreCombinedDebugLogsStatus_(status) {
- $(CrosView.STORE_COMBINED_DEBUG_LOGS_STATUS_ID).innerText = status;
- }
-
- /**
- * Set storing combined debug logs status.
- *
- * @private
- */
- function setStoreFeedbackSystemLogsStatus_(status) {
- $(CrosView.STORE_FEEDBACK_SYSTEM_LOGS_STATUS_ID).innerText = status;
- }
-
- /**
- * Set status for current debug mode.
- *
- * @private
- */
- function setNetworkDebugModeStatus_(status) {
- $(CrosView.DEBUG_STATUS_ID).innerText = status;
- }
-
- /**
- * An event listener for the file selection field.
- *
- * @private
- */
- function handleFileChangeEvent_(event) {
- clearParseStatus_();
- const file = event.target.files[0];
- const reader = new FileReader();
- reader.onloadend = function(e) {
- setFileContent_(reader.result);
- };
- reader.readAsText(file);
- }
-
- /**
- * Add event listeners for the file selection, passcode input
- * fields, for the button for debug logs storing and for buttons
- * for debug mode selection.
- *
- * @private
- */
- function addEventListeners_() {
- $(CrosView.IMPORT_ONC_ID)
- .addEventListener('change', handleFileChangeEvent_, false);
-
- $(CrosView.PASSCODE_INPUT_ID).addEventListener('change', function(event) {
- setPasscode_(this.value);
- }, false);
-
- $(CrosView.STORE_DEBUG_LOGS_ID).addEventListener('click', function(event) {
- $(CrosView.STORE_DEBUG_LOGS_STATUS_ID).innerText = '';
- g_browser.storeDebugLogs();
- }, false);
- $(CrosView.STORE_COMBINED_DEBUG_LOGS_ID)
- .addEventListener('click', function(event) {
- $(CrosView.STORE_COMBINED_DEBUG_LOGS_STATUS_ID).innerText = '';
- g_browser.storeCombinedDebugLogs();
- }, false);
- $(CrosView.STORE_FEEDBACK_SYSTEM_LOGS_ID)
- .addEventListener('click', function(event) {
- $(CrosView.STORE_FEEDBACK_SYSTEM_LOGS_STATUS_ID).innerText = '';
- g_browser.storeFeedbackSystemLogs();
- }, false);
-
- $(CrosView.DEBUG_WIFI_ID).addEventListener('click', function(event) {
- setNetworkDebugMode_('wifi');
- }, false);
- $(CrosView.DEBUG_ETHERNET_ID).addEventListener('click', function(event) {
- setNetworkDebugMode_('ethernet');
- }, false);
- $(CrosView.DEBUG_CELLULAR_ID).addEventListener('click', function(event) {
- setNetworkDebugMode_('cellular');
- }, false);
- $(CrosView.DEBUG_NONE_ID).addEventListener('click', function(event) {
- setNetworkDebugMode_('none');
- }, false);
- }
-
- /**
- * Reset fileContent and passcode vars.
- *
- * @private
- */
- function reset_() {
- fileContent = undefined;
- passcode = '';
- $(CrosView.PASSCODE_ID).hidden = true;
- }
-
- /**
- * Enables or disables debug mode for a specified subsystem.
- *
- * @private
- */
- function setNetworkDebugMode_(subsystem) {
- $(CrosView.DEBUG_STATUS_ID).innerText = '';
- g_browser.setNetworkDebugMode(subsystem);
- }
-
/**
* @constructor
* @extends {DivView}
@@ -236,11 +17,6 @@ const CrosView = (function() {
// Call superclass's constructor.
DivView.call(this, CrosView.MAIN_BOX_ID);
-
- g_browser.addCrosONCFileParseObserver(this);
- g_browser.addStoreDebugLogsObserver(this);
- g_browser.addSetNetworkDebugModeObserver(this);
- addEventListeners_();
}
CrosView.TAB_ID = 'tab-handle-chromeos';
@@ -248,38 +24,12 @@ const CrosView = (function() {
CrosView.TAB_HASH = '#chromeos';
CrosView.MAIN_BOX_ID = 'chromeos-view-tab-content';
- CrosView.IMPORT_DIV_ID = 'chromeos-view-import-div';
- CrosView.IMPORT_ONC_ID = 'chromeos-view-import-onc';
- CrosView.PASSCODE_ID = 'chromeos-view-password-div';
- CrosView.PASSCODE_INPUT_ID = 'chromeos-view-onc-password';
- CrosView.PARSE_STATUS_ID = 'chromeos-view-parse-status';
- CrosView.STORE_DEBUG_LOGS_ID = 'chromeos-view-store-debug-logs';
- CrosView.STORE_DEBUG_LOGS_STATUS_ID = 'chromeos-view-store-debug-logs-status';
- CrosView.STORE_COMBINED_DEBUG_LOGS_ID =
- 'chromeos-view-store-combined-debug-logs';
- CrosView.STORE_COMBINED_DEBUG_LOGS_STATUS_ID =
- 'chromeos-view-store-combined-debug-logs-status';
- CrosView.STORE_FEEDBACK_SYSTEM_LOGS_ID =
- 'chromeos-view-store-feedback-system-logs';
- CrosView.STORE_FEEDBACK_SYSTEM_LOGS_STATUS_ID =
- 'chromeos-view-store-feedback-system-logs-status';
- CrosView.DEBUG_WIFI_ID = 'chromeos-view-network-debugging-wifi';
- CrosView.DEBUG_ETHERNET_ID = 'chromeos-view-network-debugging-ethernet';
- CrosView.DEBUG_CELLULAR_ID = 'chromeos-view-network-debugging-cellular';
- CrosView.DEBUG_NONE_ID = 'chromeos-view-network-debugging-none';
- CrosView.DEBUG_STATUS_ID = 'chromeos-view-network-debugging-status';
cr.addSingletonGetter(CrosView);
CrosView.prototype = {
// Inherit from DivView.
__proto__: DivView.prototype,
-
- onONCFileParse: setParseStatus_,
- onStoreDebugLogs: setStoreDebugLogsStatus_,
- onStoreCombinedDebugLogs: setStoreCombinedDebugLogsStatus_,
- onStoreFeedbackSystemLogs: setStoreFeedbackSystemLogsStatus_,
- onSetNetworkDebugMode: setNetworkDebugModeStatus_,
};
return CrosView;
diff --git a/chromium/chrome/browser/resources/net_internals/domain_security_policy_view.html b/chromium/chrome/browser/resources/net_internals/domain_security_policy_view.html
index aaac84b199c..746c4c63572 100644
--- a/chromium/chrome/browser/resources/net_internals/domain_security_policy_view.html
+++ b/chromium/chrome/browser/resources/net_internals/domain_security_policy_view.html
@@ -45,6 +45,13 @@
Transparency information. See
<a href="https://tools.ietf.org/html/draft-ietf-httpbis-expect-ct" target=_blank>https://tools.ietf.org/html/draft-ietf-httpbis-expect-ct</a>.</div>
+ <p>To protect against cross-site tracking, Expect-CT data will soon be keyed
+ on the site of the main frame and innermost frame when an Expect-CT
+ header is encountered. When that behavior is enabled, both adding and
+ querying an Expect-CT domain use the eTLD+1 of the provided domain as
+ the site for both frames. Deleting policies affects information stored
+ for that domain in the context of all sites, however.</p>
+
<h4>Add Expect-CT domain</h4>
<p>Input a domain name to add it to the Expect-CT set. Leave Enforce unchecked
diff --git a/chromium/chrome/browser/resources/net_internals/domain_security_policy_view.js b/chromium/chrome/browser/resources/net_internals/domain_security_policy_view.js
index 5e5bcd4ad09..67126e523a3 100644
--- a/chromium/chrome/browser/resources/net_internals/domain_security_policy_view.js
+++ b/chromium/chrome/browser/resources/net_internals/domain_security_policy_view.js
@@ -152,7 +152,7 @@ const DomainSecurityPolicyView = (function() {
onHSTSQueryResult(result) {
if (result.error != undefined) {
- this.queryStsOutputDiv_.innerHTML = '';
+ this.queryStsOutputDiv_.innerHTML = trustedTypes.emptyHTML;
const s = addNode(this.queryStsOutputDiv_, 'span');
s.textContent = result.error;
s.style.color = '#e00';
@@ -161,15 +161,21 @@ const DomainSecurityPolicyView = (function() {
}
if (result.result == false) {
- this.queryStsOutputDiv_.innerHTML = '<b>Not found</b>';
+ this.queryStsOutputDiv_.innerHTML = trustedTypes.emptyHTML;
+ const notFound = document.createElement('b');
+ notFound.textContent = 'Not found';
+ this.queryStsOutputDiv_.appendChild(notFound);
yellowFade(this.queryStsOutputDiv_);
return;
}
- this.queryStsOutputDiv_.innerHTML = '';
+ this.queryStsOutputDiv_.innerHTML = trustedTypes.emptyHTML;
const s = addNode(this.queryStsOutputDiv_, 'span');
- s.innerHTML = '<b>Found:</b><br/>';
+ const found = document.createElement('b');
+ found.textContent = 'Found:';
+ s.appendChild(found);
+ s.appendChild(document.createElement('br'));
const keys = [
'static_sts_domain',
@@ -244,7 +250,7 @@ const DomainSecurityPolicyView = (function() {
onExpectCTQueryResult(result) {
if (result.error != undefined) {
- this.queryExpectCTOutputDiv_.innerHTML = '';
+ this.queryExpectCTOutputDiv_.innerHTML = trustedTypes.emptyHTML;
const s = addNode(this.queryExpectCTOutputDiv_, 'span');
s.textContent = result.error;
s.style.color = '#e00';
@@ -253,15 +259,21 @@ const DomainSecurityPolicyView = (function() {
}
if (result.result == false) {
- this.queryExpectCTOutputDiv_.innerHTML = '<b>Not found</b>';
+ this.queryExpectCTOutputDiv_.innerHTML = trustedTypes.emptyHTML;
+ const notFound = document.createElement('b');
+ notFound.textContent = 'Not found';
+ this.queryExpectCTOutputDiv_.appendChild(notFound);
yellowFade(this.queryExpectCTOutputDiv_);
return;
}
- this.queryExpectCTOutputDiv_.innerHTML = '';
+ this.queryExpectCTOutputDiv_.innerHTML = trustedTypes.emptyHTML;
const s = addNode(this.queryExpectCTOutputDiv_, 'span');
- s.innerHTML = '<b>Found:</b><br/>';
+ const found = document.createElement('b');
+ found.textContent = 'Found:';
+ s.appendChild(found);
+ s.appendChild(document.createElement('br'));
const keys = [
'dynamic_expect_ct_domain',
diff --git a/chromium/chrome/browser/resources/net_internals/events_view.html b/chromium/chrome/browser/resources/net_internals/events_view.html
index 2b00d73bfa2..950e3ca8236 100644
--- a/chromium/chrome/browser/resources/net_internals/events_view.html
+++ b/chromium/chrome/browser/resources/net_internals/events_view.html
@@ -1,6 +1,6 @@
<!-- ================= Events view =================== -->
<div id=events-view-tab-content class=content-box>
The net-internals events viewer and related functionality has been removed.
- Please use <a href="chrome://net-export">chrome://net-export</a> to save netlogs and the external <a href="https://chromium.googlesource.com/catapult/+/master/netlog_viewer/">catapult netlog_viewer</a> to view them.
+ Please use <a href="chrome://net-export">chrome://net-export</a> to save netlogs and the external <a href="https://netlog-viewer.appspot.com/">netlog_viewer</a> to view them.
</div>
diff --git a/chromium/chrome/browser/resources/net_internals/index.html b/chromium/chrome/browser/resources/net_internals/index.html
index 56f50557873..cf44da3960d 100644
--- a/chromium/chrome/browser/resources/net_internals/index.html
+++ b/chromium/chrome/browser/resources/net_internals/index.html
@@ -30,6 +30,5 @@ found in the LICENSE file.
<include src="chromeos_view.html">
</div>
- <script src="chrome://resources/js/jstemplate_compiled.js"></script>
</body>
</html>
diff --git a/chromium/chrome/browser/resources/net_internals/net_internals_resources.grd b/chromium/chrome/browser/resources/net_internals/net_internals_resources.grd
index dddecdbee29..5dc7b0e4a8f 100644
--- a/chromium/chrome/browser/resources/net_internals/net_internals_resources.grd
+++ b/chromium/chrome/browser/resources/net_internals/net_internals_resources.grd
@@ -10,8 +10,8 @@
</outputs>
<release seq="1">
<includes>
- <include name="IDR_NET_INTERNALS_INDEX_HTML" file="index.html" flattenhtml="true" allowexternalscript="true" compress="gzip" type="BINDATA" />
- <include name="IDR_NET_INTERNALS_INDEX_JS" file="index.js" flattenhtml="true" compress="gzip" type="BINDATA" />
+ <include name="IDR_NET_INTERNALS_INDEX_HTML" file="index.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_NET_INTERNALS_INDEX_JS" file="index.js" flattenhtml="true" type="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/new_tab_page/BUILD.gn b/chromium/chrome/browser/resources/new_tab_page/BUILD.gn
index c8a9b38a86f..ded22388136 100644
--- a/chromium/chrome/browser/resources/new_tab_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/new_tab_page/BUILD.gn
@@ -6,6 +6,7 @@ import("//chrome/browser/resources/optimize_webui.gni")
import("//third_party/closure_compiler/compile_js.gni")
import("//tools/grit/grit_rule.gni")
import("//tools/polymer/html_to_js.gni")
+import("//ui/webui/webui_features.gni")
js_type_check("closure_compile") {
is_polymer3 = true
@@ -16,6 +17,7 @@ js_type_check("closure_compile") {
":doodle_share_dialog",
":fakebox",
":grid",
+ ":iframe",
":logo",
":realbox",
":realbox_button",
@@ -23,7 +25,6 @@ js_type_check("closure_compile") {
":realbox_icon",
":realbox_match",
":theme_icon",
- ":untrusted_iframe",
":utils",
":voice_search_overlay",
]
@@ -122,13 +123,15 @@ js_library("grid") {
js_library("voice_search_overlay") {
deps = [
"//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/cr_elements/cr_button:cr_button.m",
+ "//ui/webui/resources/cr_elements/cr_icon_button:cr_icon_button.m",
]
}
js_library("utils") {
}
-js_library("untrusted_iframe") {
+js_library("iframe") {
deps = [
"//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
]
@@ -226,7 +229,7 @@ html_to_js("web_components") {
"realbox_match.js",
"realbox.js",
"theme_icon.js",
- "untrusted_iframe.js",
+ "iframe.js",
"voice_search_overlay.js",
]
}
@@ -259,6 +262,12 @@ if (optimize_webui) {
pak_file = "new_tab_page_resources.pak"
out_folder = "unpak"
deps = [ ":unoptimized_resources" ]
+
+ excludes = [
+ "../../ui/webui/new_tab_page/new_tab_page.mojom-lite.js",
+ "../../../common/search/omnibox.mojom-lite.js",
+ "../../../../skia/public/mojom/skcolor.mojom-lite.js",
+ ]
}
optimize_webui("optimized_js") {
@@ -277,10 +286,10 @@ if (optimize_webui) {
"chrome://resources/mojo/mojo/public/mojom/base/string16.mojom-lite.js",
"chrome://resources/mojo/mojo/public/mojom/base/text_direction.mojom-lite.js",
"chrome://resources/mojo/mojo/public/mojom/base/time.mojom-lite.js",
+ "chrome://resources/mojo/skia/public/mojom/skcolor.mojom-lite.js",
"chrome://resources/mojo/url/mojom/url.mojom-lite.js",
"new_tab_page.mojom-lite.js",
"omnibox.mojom-lite.js",
- "skcolor.mojom-lite.js",
]
}
}
diff --git a/chromium/chrome/browser/resources/new_tab_page/app.html b/chromium/chrome/browser/resources/new_tab_page/app.html
index 381379df828..5758e8a6d49 100644
--- a/chromium/chrome/browser/resources/new_tab_page/app.html
+++ b/chromium/chrome/browser/resources/new_tab_page/app.html
@@ -18,12 +18,24 @@
}
#oneGoogleBar {
- clip-path: url(#oneGoogleBarClipPath);
height: 100%;
position: absolute;
top: 0;
width: 100%;
- z-index: 1000;
+ }
+
+ #oneGoogleBarOverlayBackdrop {
+ background: rgba(0, 0, 0, .6);
+ display: none;
+ height: 100%;
+ position: fixed;
+ top: 0;
+ width: 100%;
+ z-index: 999;
+ }
+
+ #oneGoogleBarOverlayBackdrop[show] {
+ display: block;
}
#content {
@@ -223,20 +235,19 @@
--ntp-theme-shortcut-background-color:
[[rgbaOrInherit_(theme_.shortcutBackgroundColor)]];
--ntp-logo-color: [[rgbaOrInherit_(logoColor_)]];">
- <dom-if if="[[showIframedOneGoogleBar_]]">
- <template>
- <ntp-untrusted-iframe id="oneGoogleBar" path="[[oneGoogleBarIframePath_]]"
- hidden$="[[!oneGoogleBarLoaded_]]">
- </ntp-untrusted-iframe>
- </template>
- </dom-if>
+ <template is="dom-if" if="[[showIframedOneGoogleBar_]]">
+ <ntp-iframe id="oneGoogleBar" src="[[oneGoogleBarIframePath_]]"
+ hidden$="[[!oneGoogleBarLoaded_]]">
+ </ntp-iframe>
+ </template>
<ntp-logo id="logo" doodle-allowed$="[[doodleAllowed_]]"
- single-colored$="[[singleColoredLogo_]]">
+ single-colored$="[[singleColoredLogo_]]" dark="[[theme_.isDark]]"
+ background-color="[[backgroundColor_]]">
</ntp-logo>
- <ntp-fakebox id="fakebox" on-open-voice-search="onVoiceSearchClick_"
+ <ntp-fakebox id="fakebox" on-open-voice-search="onOpenVoiceSearch_"
hidden$="[[realboxEnabled_]]">
</ntp-fakebox>
- <ntp-realbox id="realbox" on-open-voice-search="onVoiceSearchClick_"
+ <ntp-realbox id="realbox" on-open-voice-search="onOpenVoiceSearch_"
theme="[[theme_.searchBox]]" shown$="[[realboxShown_]]"
hidden$="[[!realboxEnabled_]]">
</ntp-realbox>
@@ -246,8 +257,9 @@
</ntp-most-visited>
<dom-if if="[[lazyRender_]]">
<template>
- <ntp-untrusted-iframe id="promo" path="promo" hidden$="[[!promoLoaded_]]">
- </ntp-untrusted-iframe>
+ <ntp-iframe id="promo" hidden$="[[!promoLoaded_]]"
+ src="chrome-untrusted://new-tab-page/promo">
+ </ntp-iframe>
<a id="backgroundImageAttribution"
href="[[backgroundImageAttributionUrl_]]"
hidden="[[!backgroundImageAttribution1_]]">
@@ -297,10 +309,9 @@
</ntp-customize-dialog>
</template>
</dom-if>
+<div id="oneGoogleBarOverlayBackdrop"></div>
<svg>
<defs>
- <clipPath id="oneGoogleBarClipPath">
- <rect x="0" y="0" width="100vw" height="56"></rect>
- </clipPath>
+ <clipPath id="oneGoogleBarClipPath"></clipPath>
</defs>
</svg>
diff --git a/chromium/chrome/browser/resources/new_tab_page/app.js b/chromium/chrome/browser/resources/new_tab_page/app.js
index 74dbea61053..121633a3d00 100644
--- a/chromium/chrome/browser/resources/new_tab_page/app.js
+++ b/chromium/chrome/browser/resources/new_tab_page/app.js
@@ -6,7 +6,7 @@ import './strings.m.js';
import './most_visited.js';
import './customize_dialog.js';
import './voice_search_overlay.js';
-import './untrusted_iframe.js';
+import './iframe.js';
import './fakebox.js';
import './realbox.js';
import './logo.js';
@@ -50,6 +50,13 @@ class AppElement extends PolymerElement {
},
/** @private */
+ oneGoogleBarModalOverlaysEnabled_: {
+ type: Boolean,
+ value: () =>
+ loadTimeData.getBoolean('oneGoogleBarModalOverlaysEnabled'),
+ },
+
+ /** @private */
oneGoogleBarIframePath_: {
type: String,
value: () => {
@@ -57,12 +64,13 @@ class AppElement extends PolymerElement {
params.set(
'paramsencoded',
btoa(window.location.search.replace(/^[?]/, '&')));
- return `one-google-bar?${params}`;
+ return `chrome-untrusted://new-tab-page/one-google-bar?${params}`;
},
},
/** @private */
oneGoogleBarLoaded_: {
+ observer: 'oneGoogleBarLoadedChange_',
type: Boolean,
value: false,
},
@@ -143,6 +151,12 @@ class AppElement extends PolymerElement {
type: Boolean,
},
+ /** @private {skia.mojom.SkColor} */
+ backgroundColor_: {
+ computed: 'computeBackgroundColor_(showBackgroundImage_, theme_)',
+ type: Object,
+ },
+
/** @private */
logoColor_: {
type: String,
@@ -181,6 +195,8 @@ class AppElement extends PolymerElement {
super();
/** @private {!newTabPage.mojom.PageCallbackRouter} */
this.callbackRouter_ = BrowserProxy.getInstance().callbackRouter;
+ /** @private {newTabPage.mojom.PageHandlerRemote} */
+ this.pageHandler_ = BrowserProxy.getInstance().handler;
/** @private {!BackgroundManager} */
this.backgroundManager_ = BackgroundManager.getInstance();
/** @private {?number} */
@@ -223,6 +239,7 @@ class AppElement extends PolymerElement {
}
}
});
+ this.eventTracker_.add(window, 'keydown', e => this.onWindowKeydown_(e));
if (this.shouldPrintPerformance_) {
// It is possible that the background image has already loaded by now.
// If it has, we request it to re-send the load time so that we can
@@ -292,9 +309,8 @@ class AppElement extends PolymerElement {
return;
}
- const {parts} =
- await BrowserProxy.getInstance().handler.getOneGoogleBarParts(
- window.location.search.replace(/^[?]/, '&'));
+ const {parts} = await this.pageHandler_.getOneGoogleBarParts(
+ window.location.search.replace(/^[?]/, '&'));
if (!parts) {
return;
}
@@ -327,8 +343,7 @@ class AppElement extends PolymerElement {
endOfBodyScript.appendChild(document.createTextNode(parts.endOfBodyScript));
document.body.appendChild(endOfBodyScript);
- BrowserProxy.getInstance().handler.onOneGoogleBarRendered(
- BrowserProxy.getInstance().now());
+ this.pageHandler_.onOneGoogleBarRendered(BrowserProxy.getInstance().now());
}
/** @private */
@@ -428,8 +443,10 @@ class AppElement extends PolymerElement {
}
/** @private */
- onVoiceSearchClick_() {
+ onOpenVoiceSearch_() {
this.showVoiceSearchOverlay_ = true;
+ this.pageHandler_.onVoiceSearchAction(
+ newTabPage.mojom.VoiceSearchAction.ACTIVATE_SEARCH_BOX);
}
/** @private */
@@ -448,6 +465,24 @@ class AppElement extends PolymerElement {
}
/**
+ * Handles <CTRL> + <SHIFT> + <.> (also <CMD> + <SHIFT> + <.> on mac) to open
+ * voice search.
+ * @param {KeyboardEvent} e
+ * @private
+ */
+ onWindowKeydown_(e) {
+ let ctrlKeyPressed = e.ctrlKey;
+ // <if expr="is_macosx">
+ ctrlKeyPressed = ctrlKeyPressed || e.metaKey;
+ // </if>
+ if (ctrlKeyPressed && e.code === 'Period' && e.shiftKey) {
+ this.showVoiceSearchOverlay_ = true;
+ this.pageHandler_.onVoiceSearchAction(
+ newTabPage.mojom.VoiceSearchAction.ACTIVATE_KEYBOARD);
+ }
+ }
+
+ /**
* @param {skia.mojom.SkColor} skColor
* @return {string}
* @private
@@ -547,7 +582,8 @@ class AppElement extends PolymerElement {
* @private
*/
computeDoodleAllowed_() {
- return !this.showBackgroundImage_ && this.theme_ &&
+ return loadTimeData.getBoolean('themeModeDoodlesEnabled') ||
+ !this.showBackgroundImage_ && this.theme_ &&
this.theme_.type === newTabPage.mojom.ThemeType.DEFAULT &&
!this.theme_.isDark;
}
@@ -556,6 +592,17 @@ class AppElement extends PolymerElement {
* @return {skia.mojom.SkColor}
* @private
*/
+ computeBackgroundColor_() {
+ if (this.showBackgroundImage_) {
+ return null;
+ }
+ return this.theme_ && this.theme_.backgroundColor;
+ }
+
+ /**
+ * @return {skia.mojom.SkColor}
+ * @private
+ */
computeLogoColor_() {
switch (this.backgroundSelection_.type) {
case BackgroundSelectionType.IMAGE:
@@ -589,31 +636,47 @@ class AppElement extends PolymerElement {
/**
* Handles messages from the OneGoogleBar iframe. The messages that are
* handled include show bar on load and overlay updates.
+ *
* 'overlaysUpdated' message includes the updated array of overlay rects that
* are shown.
+ *
+ * When modal overlays are enabled, activate/deactivate controls if the
+ * OneGoogleBar is layered on top of #content with a backdrop. This would
+ * happen when OneGoogleBar has an overlay open.
* @param {!Object} data
* @private
*/
handleOneGoogleBarMessage_(data) {
if (data.messageType === 'loaded') {
+ if (!this.oneGoogleBarModalOverlaysEnabled_) {
+ const oneGoogleBar = $$(this, '#oneGoogleBar');
+ oneGoogleBar.style.clipPath = 'url(#oneGoogleBarClipPath)';
+ oneGoogleBar.style.zIndex = '1000';
+ }
this.oneGoogleBarLoaded_ = true;
- BrowserProxy.getInstance().handler.onOneGoogleBarRendered(
+ this.pageHandler_.onOneGoogleBarRendered(
BrowserProxy.getInstance().now());
} else if (data.messageType === 'overlaysUpdated') {
- this.$.oneGoogleBarClipPath.querySelectorAll('rect:not(:first-child)')
- .forEach(el => {
- el.remove();
- });
+ this.$.oneGoogleBarClipPath.querySelectorAll('rect').forEach(el => {
+ el.remove();
+ });
const overlayRects = /** @type {!Array<!DOMRect>} */ (data.data);
overlayRects.forEach(({x, y, width, height}) => {
const rectElement =
document.createElementNS('http://www.w3.org/2000/svg', 'rect');
- rectElement.setAttribute('x', x);
- rectElement.setAttribute('y', y);
- rectElement.setAttribute('width', width);
- rectElement.setAttribute('height', height);
+ // Add 8px around every rect to ensure shadows are not cutoff.
+ rectElement.setAttribute('x', x - 8);
+ rectElement.setAttribute('y', y - 8);
+ rectElement.setAttribute('width', width + 16);
+ rectElement.setAttribute('height', height + 16);
this.$.oneGoogleBarClipPath.appendChild(rectElement);
});
+ } else if (data.messageType === 'activate') {
+ this.$.oneGoogleBarOverlayBackdrop.toggleAttribute('show', true);
+ $$(this, '#oneGoogleBar').style.zIndex = '1000';
+ } else if (data.messageType === 'deactivate') {
+ this.$.oneGoogleBarOverlayBackdrop.toggleAttribute('show', false);
+ $$(this, '#oneGoogleBar').style.zIndex = '0';
}
}
@@ -634,14 +697,64 @@ class AppElement extends PolymerElement {
};
this.eventTracker_.add(window, 'resize', onResize);
onResize();
- BrowserProxy.getInstance().handler.onPromoRendered(
- BrowserProxy.getInstance().now());
+ this.pageHandler_.onPromoRendered(BrowserProxy.getInstance().now());
} else if (data.messageType === 'link-clicked') {
- BrowserProxy.getInstance().handler.onPromoLinkClicked(
- BrowserProxy.getInstance().now());
+ this.pageHandler_.onPromoLinkClicked();
+ }
+ }
+
+ /** @private */
+ oneGoogleBarLoadedChange_() {
+ if (this.oneGoogleBarLoaded_ && this.iframeOneGoogleBarEnabled_ &&
+ this.oneGoogleBarModalOverlaysEnabled_) {
+ this.setupShortcutDragDropOneGoogleBarWorkaround_();
}
}
+ /**
+ * During a shortcut drag, an iframe behind ntp-most-visited will prevent
+ * 'dragover' events from firing. To workaround this, 'pointer-events: none'
+ * can be set on the iframe. When doing this after the 'dragstart' event is
+ * fired is too late. We can instead set 'pointer-events: none' when the
+ * pointer enters ntp-most-visited.
+ *
+ * 'pointerenter' and pointerleave' events fire during drag. The iframe
+ * 'pointer-events' needs to be reset to the original value when 'dragend'
+ * fires if the pointer has left ntp-most-visited.
+ * @private
+ */
+ setupShortcutDragDropOneGoogleBarWorkaround_() {
+ const iframe = $$(this, '#oneGoogleBar');
+ let resetAtDragEnd = false;
+ let dragging = false;
+ let originalPointerEvents;
+ this.eventTracker_.add(this.$.mostVisited, 'pointerenter', () => {
+ if (dragging) {
+ resetAtDragEnd = false;
+ return;
+ }
+ originalPointerEvents = getComputedStyle(iframe).pointerEvents;
+ iframe.style.pointerEvents = 'none';
+ });
+ this.eventTracker_.add(this.$.mostVisited, 'pointerleave', () => {
+ if (dragging) {
+ resetAtDragEnd = true;
+ return;
+ }
+ iframe.style.pointerEvents = originalPointerEvents;
+ });
+ this.eventTracker_.add(this.$.mostVisited, 'dragstart', () => {
+ dragging = true;
+ });
+ this.eventTracker_.add(this.$.mostVisited, 'dragend', () => {
+ dragging = false;
+ if (resetAtDragEnd) {
+ resetAtDragEnd = false;
+ iframe.style.pointerEvents = originalPointerEvents;
+ }
+ });
+ }
+
/** @private */
printPerformanceDatum_(name, time, auxTime = 0) {
if (!this.shouldPrintPerformance_) {
diff --git a/chromium/chrome/browser/resources/new_tab_page/browser_proxy.js b/chromium/chrome/browser/resources/new_tab_page/browser_proxy.js
index c91deaf6a0a..ea8db362e8a 100644
--- a/chromium/chrome/browser/resources/new_tab_page/browser_proxy.js
+++ b/chromium/chrome/browser/resources/new_tab_page/browser_proxy.js
@@ -7,10 +7,10 @@ import 'chrome://resources/mojo/mojo/public/mojom/base/big_buffer.mojom-lite.js'
import 'chrome://resources/mojo/mojo/public/mojom/base/string16.mojom-lite.js';
import 'chrome://resources/mojo/mojo/public/mojom/base/text_direction.mojom-lite.js';
import 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-lite.js';
+import 'chrome://resources/mojo/skia/public/mojom/skcolor.mojom-lite.js';
import 'chrome://resources/mojo/url/mojom/url.mojom-lite.js';
import './omnibox.mojom-lite.js';
-import './skcolor.mojom-lite.js';
import './new_tab_page.mojom-lite.js';
import {addSingletonGetter} from 'chrome://resources/js/cr.m.js';
@@ -59,11 +59,11 @@ export class BrowserProxy {
}
/**
- * @param {string} path
+ * @param {string} src
* @return {string}
*/
- createUntrustedIframeSrc(path) {
- return `chrome-untrusted://new-tab-page/${path}`;
+ createIframeSrc(src) {
+ return src;
}
/**
diff --git a/chromium/chrome/browser/resources/new_tab_page/customize_backgrounds.html b/chromium/chrome/browser/resources/new_tab_page/customize_backgrounds.html
index bd734769a8e..f7e131a8742 100644
--- a/chromium/chrome/browser/resources/new_tab_page/customize_backgrounds.html
+++ b/chromium/chrome/browser/resources/new_tab_page/customize_backgrounds.html
@@ -1,7 +1,6 @@
<style include="cr-hidden-style">
:host {
display: flex;
- height: -webkit-fill-available;
}
#container {
@@ -17,7 +16,7 @@
outline-width: 0;
}
- ntp-untrusted-iframe {
+ ntp-iframe {
pointer-events: none;
}
@@ -197,9 +196,9 @@
<template>
<div class="tile" tabindex="0" title="[[item.label]]" role="button"
on-click="onCollectionClick_">
- <ntp-untrusted-iframe class="image"
- path="background_image?[[item.previewImageUrl.url]]">
- </ntp-untrusted-iframe>
+ <ntp-iframe class="image"
+ src="chrome-untrusted://new-tab-page/background_image?[[item.previewImageUrl.url]]">
+ </ntp-iframe>
<div class="label">[[item.label]]</div>
</div>
</template>
@@ -213,9 +212,9 @@
[[getImageSelectedClass_(index, theme, backgroundSelection)]]"
tabindex="0" title="[[item.attribution1]]" role="button"
on-click="onImageClick_">
- <ntp-untrusted-iframe class="image"
- path="background_image?[[item.previewImageUrl.url]]">
- </ntp-untrusted-iframe>
+ <ntp-iframe class="image"
+ src="chrome-untrusted://new-tab-page/background_image?[[item.previewImageUrl.url]]">
+ </ntp-iframe>
<div class="selected-circle"></div>
<div class="selected-check"></div>
</div>
diff --git a/chromium/chrome/browser/resources/new_tab_page/customize_backgrounds.js b/chromium/chrome/browser/resources/new_tab_page/customize_backgrounds.js
index 75ccde66924..4f99d35e938 100644
--- a/chromium/chrome/browser/resources/new_tab_page/customize_backgrounds.js
+++ b/chromium/chrome/browser/resources/new_tab_page/customize_backgrounds.js
@@ -5,7 +5,7 @@
import 'chrome://resources/cr_elements/hidden_style_css.m.js';
import './grid.js';
import './mini_page.js';
-import './untrusted_iframe.js';
+import './iframe.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
diff --git a/chromium/chrome/browser/resources/new_tab_page/customize_dialog.html b/chromium/chrome/browser/resources/new_tab_page/customize_dialog.html
index 481090004be..231ac1f603c 100644
--- a/chromium/chrome/browser/resources/new_tab_page/customize_dialog.html
+++ b/chromium/chrome/browser/resources/new_tab_page/customize_dialog.html
@@ -1,10 +1,16 @@
<style include="cr-hidden-style cr-icons">
- ::part(dialog) {
+ cr-dialog::part(dialog) {
+ height: 100%;
+ max-height: 520px;
min-width: 800px;
}
- :host {
- --border-width: 1px;
+ cr-dialog::part(wrapper) {
+ height: 100%;
+ }
+
+ cr-dialog::part(body-container) {
+ flex-grow: 1;
}
div[slot=title] {
@@ -36,7 +42,6 @@
#menuContainer,
#pagesContainer {
- max-height: 395px;
overflow: hidden;
}
@@ -57,11 +62,7 @@
flex-grow: 1;
}
- #menu {
- height: calc(100% - 2 * var(--border-width));
- overflow: auto;
- }
-
+ #menu,
#pages {
height: 100%;
overflow: auto;
@@ -70,11 +71,10 @@
#pages > iron-pages {
/* Margin is for focus outline. */
margin: 2px;
- min-height: 389px;
}
div[scroll-border] {
- border-bottom: var(--border-width) solid transparent;
+ border-bottom: 1px solid transparent;
}
div[scroll-border][show-1],
@@ -97,11 +97,14 @@
flex-shrink: 0;
font-size: 14px;
height: 32px;
- margin-bottom: 16px;
outline: none;
width: 192px;
}
+ .menu-item + .menu-item {
+ margin-top: 16px;
+ }
+
:host-context([dir=rtl]) .menu-item {
border-radius: 16px 0 0 16px;
}
diff --git a/chromium/chrome/browser/resources/new_tab_page/customize_themes.html b/chromium/chrome/browser/resources/new_tab_page/customize_themes.html
index a0920f697b6..3fccbcba6b9 100644
--- a/chromium/chrome/browser/resources/new_tab_page/customize_themes.html
+++ b/chromium/chrome/browser/resources/new_tab_page/customize_themes.html
@@ -45,7 +45,6 @@
#themesContainer {
--ntp-grid-gap: 20px;
- padding: 3px;
}
#themesContainer > * {
diff --git a/chromium/chrome/browser/resources/new_tab_page/untrusted_iframe.html b/chromium/chrome/browser/resources/new_tab_page/iframe.html
index 212f6d13acb..212f6d13acb 100644
--- a/chromium/chrome/browser/resources/new_tab_page/untrusted_iframe.html
+++ b/chromium/chrome/browser/resources/new_tab_page/iframe.html
diff --git a/chromium/chrome/browser/resources/new_tab_page/untrusted_iframe.js b/chromium/chrome/browser/resources/new_tab_page/iframe.js
index f40c0cd58cc..14afd7b04a7 100644
--- a/chromium/chrome/browser/resources/new_tab_page/untrusted_iframe.js
+++ b/chromium/chrome/browser/resources/new_tab_page/iframe.js
@@ -5,9 +5,14 @@
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BrowserProxy} from './browser_proxy.js';
-class UntrustedIframeElement extends PolymerElement {
+/**
+ * @fileoverview Wrapper around <iframe> element that lets us mock out loading
+ * and postMessaging in tests.
+ */
+
+class IframeElement extends PolymerElement {
static get is() {
- return 'ntp-untrusted-iframe';
+ return 'ntp-iframe';
}
static get template() {
@@ -17,7 +22,7 @@ class UntrustedIframeElement extends PolymerElement {
static get properties() {
return {
/** @type {string} */
- path: {
+ src: {
reflectToAttribute: true,
type: String,
},
@@ -25,7 +30,7 @@ class UntrustedIframeElement extends PolymerElement {
/** @private */
src_: {
type: String,
- computed: 'computeSrc_(path)',
+ computed: 'computeSrc_(src)',
},
};
}
@@ -35,14 +40,17 @@ class UntrustedIframeElement extends PolymerElement {
* @param {*} message
*/
postMessage(message) {
- this.$.iframe.contentWindow.postMessage(
- message, 'chrome-untrusted://new-tab-page');
+ BrowserProxy.getInstance().postMessage(
+ this.$.iframe, message, new URL(this.src).origin);
}
- /** @private */
+ /**
+ * @return {string}
+ * @private
+ */
computeSrc_() {
- return BrowserProxy.getInstance().createUntrustedIframeSrc(this.path);
+ return BrowserProxy.getInstance().createIframeSrc(this.src);
}
}
-customElements.define(UntrustedIframeElement.is, UntrustedIframeElement);
+customElements.define(IframeElement.is, IframeElement);
diff --git a/chromium/chrome/browser/resources/new_tab_page/logo.html b/chromium/chrome/browser/resources/new_tab_page/logo.html
index ce8504f079c..f9f1fe7e008 100644
--- a/chromium/chrome/browser/resources/new_tab_page/logo.html
+++ b/chromium/chrome/browser/resources/new_tab_page/logo.html
@@ -24,22 +24,38 @@
background-image: url(chrome://resources/images/google_logo.svg);
}
- #imageContainer {
+ #doodle {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ justify-content: center;
+ }
+
+ :host([doodle-boxed_]) #doodle {
+ justify-content: flex-end;
+ }
+
+ #imageDoodle {
cursor: pointer;
- display: grid;
- height: fit-content;
outline: none;
- position: relative;
- width: fit-content;
}
- :host-context(.focus-outline-visible) #imageContainer:focus {
+ :host([doodle-boxed_]) #imageDoodle {
+ background-color: var(--ntp-logo-box-color);
+ border-radius: 20px;
+ margin-bottom: 30px;
+ padding: 16px 24px;
+ }
+
+ :host-context(.focus-outline-visible) #imageDoodle:focus {
box-shadow: 0 0 0 2px rgba(var(--google-blue-600-rgb), .4);
}
- #imageContainer > * {
- grid-column-start: 1;
- grid-row-start: 1;
+ #imageContainer {
+ display: flex;
+ height: fit-content;
+ position: relative;
+ width: fit-content;
}
#image {
@@ -47,32 +63,46 @@
max-width: 100%;
}
+ :host([doodle-boxed_]) #image {
+ max-height: 160px;
+ }
+
#animation {
height: 100%;
pointer-events: none;
+ position: absolute;
width: 100%;
}
#shareButton {
+ background-color: var(--ntp-logo-share-button-background-color, none);
border: none;
- height: 26px;
- min-width: 26px;
+ height: var(--ntp-logo-share-button-height, 0);
+ left: var(--ntp-logo-share-button-x, 0);
+ min-width: var(--ntp-logo-share-button-width, 0);
opacity: 0.8;
outline: initial;
padding: 2px;
position: absolute;
- width: 26px;
+ top: var(--ntp-logo-share-button-y, 0);
+ width: var(--ntp-logo-share-button-width, 0);
}
#shareButton:hover {
opacity: 1;
}
+ #shareButton img {
+ height: 100%;
+ width: 100%;
+ }
+
#iframe {
- height: var(--height);
+ border: none;
+ height: var(--height, --ntp-logo-height);
transition-duration: var(--duration, 100ms);
transition-property: height, width;
- width: var(--width);
+ width: var(--width, 100%);
}
</style>
<dom-if if="[[showLogo_]]" restamp>
@@ -86,32 +116,28 @@
<dom-if if="[[showDoodle_]]" restamp>
<template>
<div id="doodle" title="[[doodle_.description]]">
- <div id="imageContainer" hidden="[[!doodle_.content.imageDoodle]]"
- tabindex="1" on-click="onImageClick_" on-keydown="onImageKeydown_">
- <!-- The static image is always visible and the animated image is
- stacked on top of the static image so that there is no flicker when
- starting the animation. -->
- <img id="image" src="[[imageUrl_]]" on-load="onImageLoad_">
- </img>
- <ntp-untrusted-iframe id="animation" path="[[animationUrl_]]"
- hidden="[[!showAnimation_]]">
- </ntp-untrusted-iframe>
- <cr-button id="shareButton" title="$i18n{shareDoodle}"
- on-click="onShareButtonClick_"
- style="background-color: [[rgbaOrUnset_(doodle_.content.imageDoodle.shareButton.backgroundColor)]];
- left: [[doodle_.content.imageDoodle.shareButton.x]]px;
- top: [[doodle_.content.imageDoodle.shareButton.y]]px;">
- <img id="shareButtonImage"
- src="[[doodle_.content.imageDoodle.shareButton.iconUrl.url]]">
+ <div id="imageDoodle" hidden="[[!imageDoodle_]]"
+ tabindex="0" on-click="onImageClick_" on-keydown="onImageKeydown_">
+ <div id="imageContainer">
+ <!-- The static image is always visible and the animated image is
+ stacked on top of the static image so that there is no flicker
+ when starting the animation. -->
+ <img id="image" src="[[imageUrl_]]" on-load="onImageLoad_">
</img>
- </cr-button>
+ <ntp-iframe id="animation" src="[[animationUrl_]]"
+ hidden="[[!showAnimation_]]">
+ </ntp-iframe>
+ <cr-button id="shareButton" title="$i18n{shareDoodle}"
+ on-click="onShareButtonClick_">
+ <img id="shareButtonImage"
+ src="[[imageDoodle_.shareButton.iconUrl.url]]">
+ </img>
+ </cr-button>
+ </div>
</div>
- <ntp-untrusted-iframe id="iframe" path="[[iframeUrl_]]"
- hidden="[[!iframeUrl_]]"
- style="--duration: [[valueOrUnset_(duration_)]];
- --height: [[valueOrUnset_(height_)]];
- --width: [[valueOrUnset_(width_)]];">
- </ntp-untrusted-iframe>
+ <template is="dom-if" if="[[iframeUrl_]]" restamp>
+ <ntp-iframe id="iframe" src="[[iframeUrl_]]"></ntp-iframe>
+ </template>
</div>
</template>
</dom-if>
diff --git a/chromium/chrome/browser/resources/new_tab_page/logo.js b/chromium/chrome/browser/resources/new_tab_page/logo.js
index 41af57ef294..78987000940 100644
--- a/chromium/chrome/browser/resources/new_tab_page/logo.js
+++ b/chromium/chrome/browser/resources/new_tab_page/logo.js
@@ -4,14 +4,19 @@
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/hidden_style_css.m.js';
-import './untrusted_iframe.js';
+import './iframe.js';
import './doodle_share_dialog.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {EventTracker} from 'chrome://resources/js/event_tracker.m.js';
+import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
import {BrowserProxy} from './browser_proxy.js';
-import {skColorToRgba} from './utils.js';
+import {$$, skColorToRgba} from './utils.js';
+
+/** @type {number} */
+const SHARE_BUTTON_SIZE_PX = 26;
// Shows the Google logo or a doodle if available.
class LogoElement extends PolymerElement {
@@ -45,15 +50,38 @@ class LogoElement extends PolymerElement {
value: false,
},
+ /**
+ * If true displays the dark mode doodle if possible.
+ * @type {boolean}
+ */
+ dark: {
+ observer: 'onDarkChange_',
+ type: Boolean,
+ },
+
+ /**
+ * The NTP's background color. If null or undefined the NTP does not have
+ * a single background color, e.g. when a background image is set.
+ * @type {skia.mojom.SkColor}
+ */
+ backgroundColor: Object,
+
/** @private */
loaded_: Boolean,
/** @private {newTabPage.mojom.Doodle} */
doodle_: Object,
+ /** @private {newTabPage.mojom.ImageDoodle} */
+ imageDoodle_: {
+ observer: 'onImageDoodleChange_',
+ computed: 'computeImageDoodle_(dark, doodle_)',
+ type: Object,
+ },
+
/** @private */
canShowDoodle_: {
- computed: 'computeCanShowDoodle_(doodle_)',
+ computed: 'computeCanShowDoodle_(doodle_, imageDoodle_)',
type: Boolean,
},
@@ -70,8 +98,15 @@ class LogoElement extends PolymerElement {
},
/** @private */
+ doodleBoxed_: {
+ reflectToAttribute: true,
+ type: Boolean,
+ computed: 'computeDoodleBoxed_(backgroundColor, imageDoodle_)',
+ },
+
+ /** @private */
imageUrl_: {
- computed: 'computeImageUrl_(doodle_)',
+ computed: 'computeImageUrl_(imageDoodle_)',
type: String,
},
@@ -83,7 +118,7 @@ class LogoElement extends PolymerElement {
/** @private */
animationUrl_: {
- computed: 'computeAnimationUrl_(doodle_)',
+ computed: 'computeAnimationUrl_(imageDoodle_)',
type: String,
},
@@ -95,20 +130,20 @@ class LogoElement extends PolymerElement {
/** @private */
duration_: {
+ observer: 'onDurationHeightWidthChange_',
type: String,
- value: null,
},
/** @private */
height_: {
+ observer: 'onDurationHeightWidthChange_',
type: String,
- value: null,
},
/** @private */
width_: {
+ observer: 'onDurationHeightWidthChange_',
type: String,
- value: null,
},
/** @private */
@@ -132,24 +167,27 @@ class LogoElement extends PolymerElement {
}
});
/** @private {?string} */
- this.imageClickParams_;
+ this.imageClickParams_ = null;
/** @private {url.mojom.Url} */
- this.interactionLogUrl_;
+ this.interactionLogUrl_ = null;
/** @private {?string} */
- this.shareId_;
+ this.shareId_ = null;
}
/** @override */
connectedCallback() {
super.connectedCallback();
this.eventTracker_.add(window, 'message', ({data}) => {
- if (data['cmd'] !== 'resizeDoodle') {
- return;
+ if (data['cmd'] === 'resizeDoodle') {
+ this.duration_ = assert(data.duration);
+ this.height_ = assert(data.height);
+ this.width_ = assert(data.width);
+ } else if (data['cmd'] === 'sendMode') {
+ this.sendMode_();
}
- this.duration_ = assert(data.duration);
- this.height_ = assert(data.height);
- this.width_ = assert(data.width);
});
+ // Make sure the doodle gets the mode in case it has already requested it.
+ this.sendMode_();
}
/** @override */
@@ -164,15 +202,63 @@ class LogoElement extends PolymerElement {
performance.measure('logo-creation', 'logo-creation-start');
}
+ /** @private */
+ onImageDoodleChange_() {
+ if (this.imageDoodle_) {
+ const shareButton = this.imageDoodle_.shareButton;
+ const height = this.imageDoodle_.height;
+ const width = this.imageDoodle_.width;
+ this.updateStyles({
+ '--ntp-logo-share-button-background-color':
+ skColorToRgba(shareButton.backgroundColor),
+ '--ntp-logo-share-button-height':
+ `${SHARE_BUTTON_SIZE_PX / height * 100}%`,
+ '--ntp-logo-share-button-width':
+ `${SHARE_BUTTON_SIZE_PX / width * 100}%`,
+ '--ntp-logo-share-button-x': `${shareButton.x / width * 100}%`,
+ '--ntp-logo-share-button-y': `${shareButton.y / height * 100}%`,
+ '--ntp-logo-box-color':
+ skColorToRgba(this.imageDoodle_.backgroundColor),
+ });
+ } else {
+ this.updateStyles({
+ '--ntp-logo-share-button-background-color': null,
+ '--ntp-logo-share-button-height': null,
+ '--ntp-logo-share-button-width': null,
+ '--ntp-logo-share-button-x': null,
+ '--ntp-logo-share-button-y': null,
+ '--ntp-logo-box-color': null,
+ });
+ }
+ // Stop the animation (if it is running) and reset logging params since
+ // mode change constitutes a new doodle session.
+ this.showAnimation_ = false;
+ this.imageClickParams_ = null;
+ this.interactionLogUrl_ = null;
+ this.shareId_ = null;
+ }
+
+ /**
+ * @return {newTabPage.mojom.ImageDoodle}
+ * @private
+ */
+ computeImageDoodle_() {
+ return this.doodle_ && this.doodle_.content.imageDoodle &&
+ (this.dark ? this.doodle_.content.imageDoodle.dark :
+ this.doodle_.content.imageDoodle.light) ||
+ null;
+ }
+
/**
* @return {boolean}
* @private
*/
computeCanShowDoodle_() {
- return !!this.doodle_ &&
+ return !!this.imageDoodle_ ||
/* We hide interactive doodles when offline. Otherwise, the iframe
would show an ugly error page. */
- (!this.doodle_.content.interactiveDoodle || window.navigator.onLine);
+ !!this.doodle_ && !!this.doodle_.content.interactiveDoodle &&
+ window.navigator.onLine;
}
/**
@@ -192,6 +278,16 @@ class LogoElement extends PolymerElement {
}
/**
+ * @return {boolean}
+ * @private
+ */
+ computeDoodleBoxed_() {
+ return !this.backgroundColor ||
+ !!this.imageDoodle_ &&
+ this.imageDoodle_.backgroundColor.value !== this.backgroundColor.value;
+ }
+
+ /**
* Called when a simple or animated doodle was clicked. Starts animation if
* clicking preview image of animated doodle. Otherwise, opens
* doodle-associated URL in new tab/window.
@@ -211,7 +307,7 @@ class LogoElement extends PolymerElement {
this.logImageRendered_(
newTabPage.mojom.DoodleImageType.ANIMATION,
/** @type {!url.mojom.Url} */
- (this.doodle_.content.imageDoodle.animationImpressionLogUrl));
+ (this.imageDoodle_.animationImpressionLogUrl));
return;
}
@@ -233,7 +329,7 @@ class LogoElement extends PolymerElement {
this.logImageRendered_(
this.isCtaImageShown_() ? newTabPage.mojom.DoodleImageType.CTA :
newTabPage.mojom.DoodleImageType.STATIC,
- this.doodle_.content.imageDoodle.imageImpressionLogUrl);
+ this.imageDoodle_.imageImpressionLogUrl);
}
/**
@@ -278,58 +374,62 @@ class LogoElement extends PolymerElement {
* @private
*/
isCtaImageShown_() {
- return !this.showAnimation_ && !!this.doodle_ &&
- !!this.doodle_.content.imageDoodle.animationUrl;
+ return !this.showAnimation_ && !!this.imageDoodle_.animationUrl;
}
/**
- * @return {string}
+ * Sends a postMessage to the interactive doodle whether the current theme is
+ * dark or light. Won't do anything if we don't have an interactive doodle or
+ * we haven't been told yet whether the current theme is dark or light.
* @private
*/
- computeImageUrl_() {
- return (this.doodle_ && this.doodle_.content.imageDoodle &&
- this.doodle_.content.imageDoodle.imageUrl) ?
- this.doodle_.content.imageDoodle.imageUrl.url :
- '';
+ sendMode_() {
+ const iframe = $$(this, '#iframe');
+ if (!loadTimeData.getBoolean('themeModeDoodlesEnabled') ||
+ this.dark === undefined || !iframe) {
+ return;
+ }
+ iframe.postMessage({cmd: 'changeMode', dark: this.dark});
}
- /**
- * @return {string}
- * @private
- */
- computeAnimationUrl_() {
- return (this.doodle_ && this.doodle_.content.imageDoodle &&
- this.doodle_.content.imageDoodle.animationUrl) ?
- `image?${this.doodle_.content.imageDoodle.animationUrl.url}` :
- '';
+ /** @private */
+ onDarkChange_() {
+ this.sendMode_();
}
/**
* @return {string}
* @private
*/
- computeIframeUrl_() {
- return (this.doodle_ && this.doodle_.content.interactiveDoodle) ?
- `iframe?${this.doodle_.content.interactiveDoodle.url.url}` :
- '';
+ computeImageUrl_() {
+ return this.imageDoodle_ ? this.imageDoodle_.imageUrl.url : '';
}
/**
- * @param {string} value
* @return {string}
* @private
*/
- valueOrUnset_(value) {
- return value || 'unset';
+ computeAnimationUrl_() {
+ return this.imageDoodle_ && this.imageDoodle_.animationUrl ?
+ `chrome-untrusted://new-tab-page/image?${
+ this.imageDoodle_.animationUrl.url}` :
+ '';
}
/**
- * @param {skia.mojom.SkColor} skColor
* @return {string}
* @private
*/
- rgbaOrUnset_(skColor) {
- return skColor ? skColorToRgba(skColor) : 'unset';
+ computeIframeUrl_() {
+ if (this.doodle_ && this.doodle_.content.interactiveDoodle) {
+ const url = new URL(this.doodle_.content.interactiveDoodle.url.url);
+ if (loadTimeData.getBoolean('themeModeDoodlesEnabled')) {
+ url.searchParams.append('theme_messages', '0');
+ }
+ return url.href;
+ } else {
+ return '';
+ }
}
/**
@@ -345,6 +445,15 @@ class LogoElement extends PolymerElement {
onShareDialogClose_() {
this.showShareDialog_ = false;
}
+
+ /** @private */
+ onDurationHeightWidthChange_() {
+ this.updateStyles({
+ '--duration': this.duration_,
+ '--height': this.height_,
+ '--width': this.width_,
+ });
+ }
}
customElements.define(LogoElement.is, LogoElement);
diff --git a/chromium/chrome/browser/resources/new_tab_page/most_visited.html b/chromium/chrome/browser/resources/new_tab_page/most_visited.html
index 6054974dbde..0b16023d29a 100644
--- a/chromium/chrome/browser/resources/new_tab_page/most_visited.html
+++ b/chromium/chrome/browser/resources/new_tab_page/most_visited.html
@@ -144,6 +144,7 @@
cr-icon-button {
--cr-icon-button-fill-color: var(--icon-button-color);
--cr-icon-button-size: 28px;
+ --cr-icon-button-transition: none;
margin: 4px 2px;
opacity: 0;
position: absolute;
diff --git a/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources.grd b/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources.grd
index 35e62f674fc..ac16ff94bcf 100644
--- a/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources.grd
+++ b/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources.grd
@@ -16,7 +16,8 @@
file="new_tab_page.js" type="BINDATA" compress="false" />
<include name="IDR_NEW_TAB_PAGE_APP_JS"
file="${root_gen_dir}/chrome/browser/resources/new_tab_page/app.js"
- use_base_dir="false" type="BINDATA" compress="false" />
+ use_base_dir="false" type="BINDATA" compress="false"
+ preprocess="true" />
<include name="IDR_NEW_TAB_PAGE_MOST_VISITED_JS"
file="${root_gen_dir}/chrome/browser/resources/new_tab_page/most_visited.js"
use_base_dir="false" type="BINDATA" compress="false" />
@@ -41,8 +42,8 @@
<include name="IDR_NEW_TAB_PAGE_GRID_JS"
file="${root_gen_dir}/chrome/browser/resources/new_tab_page/grid.js"
use_base_dir="false" type="BINDATA" compress="false" />
- <include name="IDR_NEW_TAB_UNTRUSTED_IFRAME_JS"
- file="${root_gen_dir}/chrome/browser/resources/new_tab_page/untrusted_iframe.js"
+ <include name="IDR_NEW_TAB_IFRAME_JS"
+ file="${root_gen_dir}/chrome/browser/resources/new_tab_page/iframe.js"
use_base_dir="false" type="BINDATA" compress="false" />
<include name="IDR_NEW_TAB_PAGE_MINI_PAGE_JS"
file="${root_gen_dir}/chrome/browser/resources/new_tab_page/mini_page.js"
diff --git a/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources_common.grdp b/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources_common.grdp
index c8170087238..13fbac2c00f 100644
--- a/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources_common.grdp
+++ b/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources_common.grdp
@@ -1,70 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<grit-part>
- <include name="IDR_NEW_TAB_PAGE_SKCOLOR_MOJO_LITE_JS"
- file="${root_gen_dir}/skia/public/mojom/skcolor.mojom-lite.js"
- use_base_dir="false" type="BINDATA" compress="gzip" />
<include name="IDR_NEW_TAB_PAGE_MOJO_LITE_JS"
file="${root_gen_dir}/chrome/browser/ui/webui/new_tab_page/new_tab_page.mojom-lite.js"
- use_base_dir="false" type="BINDATA" compress="gzip" />
+ use_base_dir="false" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_OMNIBOX_MOJO_LITE_JS"
file="${root_gen_dir}/chrome/common/search/omnibox.mojom-lite.js"
- use_base_dir="false" type="BINDATA" compress="gzip" />
+ use_base_dir="false" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_ACCOUNT_CIRCLE_SVG"
- file="icons/account_circle.svg" type="BINDATA" compress="gzip" />
+ file="icons/account_circle.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_BRUSH_ICON_SVG"
- file="icons/brush.svg" type="BINDATA" compress="gzip" />
+ file="icons/brush.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_CHECK_CIRCLE_SVG"
- file="icons/check_circle.svg" type="BINDATA" compress="gzip" />
+ file="icons/check_circle.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_CHEVRON_SVG"
- file="icons/chevron.svg" type="BINDATA" compress="gzip" />
+ file="icons/chevron.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_GENERIC_GLOBE_SVG"
- file="icons/generic_globe.svg" type="BINDATA" compress="gzip" />
+ file="icons/generic_globe.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_PENCIL_ICON_SVG"
- file="icons/icon_pencil.svg" type="BINDATA" compress="gzip" />
+ file="icons/icon_pencil.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_LINK_ICON_SVG"
- file="icons/link.svg" type="BINDATA" compress="gzip" />
+ file="icons/link.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_BACKGROUNDS_ICON_SVG"
- file="icons/backgrounds.svg" type="BINDATA" compress="gzip" />
+ file="icons/backgrounds.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_COLORED_HEADER_SVG"
- file="icons/colored_header.svg" type="BINDATA" compress="gzip" />
+ file="icons/colored_header.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_COLORS_ICON_SVG"
- file="icons/colors.svg" type="BINDATA" compress="gzip" />
+ file="icons/colors.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_COLORIZE_ICON_SVG"
- file="icons/colorize.svg" type="BINDATA" compress="gzip" />
+ file="icons/colorize.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_SHORTCUT_CIRCLES_SVG"
- file="icons/shortcut_circles.svg" type="BINDATA" compress="gzip" />
+ file="icons/shortcut_circles.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_GOOGLE_MIC_SVG"
- file="icons/googlemic_clr_24px.svg" type="BINDATA" compress="gzip" />
+ file="icons/googlemic_clr_24px.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_MIC_SVG"
- file="icons/mic.svg" type="BINDATA" compress="gzip" />
+ file="icons/mic.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_COPY_SVG"
- file="icons/copy.svg" type="BINDATA" compress="gzip" />
+ file="icons/copy.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_FACEBOOK_SVG"
- file="icons/facebook.svg" type="BINDATA" compress="gzip" />
+ file="icons/facebook.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_TWITTER_SVG"
- file="icons/twitter.svg" type="BINDATA" compress="gzip" />
+ file="icons/twitter.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_MAIL_SVG"
- file="icons/mail.svg" type="BINDATA" compress="gzip" />
+ file="icons/mail.svg" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_UPLOAD_SVG" file="icons/upload.svg"
- type="BINDATA" compress="gzip" />
+ type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_NEW_TAB_PAGE_HTML"
- file="new_tab_page.html" type="BINDATA" compress="gzip" />
+ file="new_tab_page.html" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_SHARED_VARS_CSS"
- file="shared_vars.css" type="BINDATA" compress="gzip" />
+ file="shared_vars.css" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_UNTRUSTED_ONE_GOOGLE_BAR_HTML"
- file="untrusted/one_google_bar.html" type="BINDATA" compress="gzip" />
+ file="untrusted/one_google_bar.html" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_UNTRUSTED_ONE_GOOGLE_BAR_JS"
- file="untrusted/one_google_bar.js" type="BINDATA" compress="gzip" />
+ file="untrusted/one_google_bar.js" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_UNTRUSTED_PROMO_HTML"
- file="untrusted/promo.html" type="BINDATA" compress="gzip" />
+ file="untrusted/promo.html" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_UNTRUSTED_PROMO_JS"
- file="untrusted/promo.js" type="BINDATA" compress="gzip" />
+ file="untrusted/promo.js" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_UNTRUSTED_IMAGE_HTML"
- file="untrusted/image.html" type="BINDATA" compress="gzip" />
+ file="untrusted/image.html" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_UNTRUSTED_BACKGROUND_IMAGE_HTML"
- file="untrusted/background_image.html" type="BINDATA" compress="gzip" />
+ file="untrusted/background_image.html" type="BINDATA" />
<include name="IDR_NEW_TAB_PAGE_UNTRUSTED_BACKGROUND_IMAGE_JS"
- file="untrusted/background_image.js" type="BINDATA" compress="gzip" />
- <include name="IDR_NEW_TAB_PAGE_UNTRUSTED_IFRAME_HTML"
- file="untrusted/iframe.html" type="BINDATA" compress="gzip" />
+ file="untrusted/background_image.js" type="BINDATA" />
</grit-part>
diff --git a/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources_vulcanized.grd b/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources_vulcanized.grd
index dea0262271b..c92307069a4 100644
--- a/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources_vulcanized.grd
+++ b/chromium/chrome/browser/resources/new_tab_page/new_tab_page_resources_vulcanized.grd
@@ -14,7 +14,7 @@
<includes>
<include name="IDR_NEW_TAB_PAGE_NEW_TAB_PAGE_JS"
file="${root_gen_dir}/chrome/browser/resources/new_tab_page/new_tab_page.rollup.js"
- use_base_dir="false" type="BINDATA" compress="gzip"
+ use_base_dir="false" type="BINDATA"
preprocess="true" />
<part file="new_tab_page_resources_common.grdp" />
</includes>
diff --git a/chromium/chrome/browser/resources/new_tab_page/realbox.html b/chromium/chrome/browser/resources/new_tab_page/realbox.html
index 8d3acd17ac7..cd67dd14290 100644
--- a/chromium/chrome/browser/resources/new_tab_page/realbox.html
+++ b/chromium/chrome/browser/resources/new_tab_page/realbox.html
@@ -132,6 +132,6 @@
result="[[result_]]" selected-match-index="{{selectedMatchIndex_}}"
on-result-repaint="onResultRepaint_" on-match-focusin="onMatchFocusin_"
on-match-click="onMatchClick_" on-match-remove="onMatchRemove_"
- hidden$="[[!matchesAreVisible]]">
+ on-header-focusin="onHeaderFocusin_" hidden$="[[!matchesAreVisible]]">
</ntp-realbox-dropdown>
</div>
diff --git a/chromium/chrome/browser/resources/new_tab_page/realbox.js b/chromium/chrome/browser/resources/new_tab_page/realbox.js
index 9ab63767a23..aa9fc080dd0 100644
--- a/chromium/chrome/browser/resources/new_tab_page/realbox.js
+++ b/chromium/chrome/browser/resources/new_tab_page/realbox.js
@@ -315,6 +315,16 @@ class RealboxElement extends PolymerElement {
//============================================================================
/**
+ * @private
+ */
+ onHeaderFocusin_() {
+ // The header got focus. Unselect the selected match and clear the input.
+ assert(this.lastQueriedInput_ === '');
+ this.$.matches.unselect();
+ this.updateInput_({text: '', inline: ''});
+ }
+
+ /**
* @param {!Event} e
* @private
*/
diff --git a/chromium/chrome/browser/resources/new_tab_page/realbox_dropdown.html b/chromium/chrome/browser/resources/new_tab_page/realbox_dropdown.html
index f8fbddc2cb1..6c088c96d3a 100644
--- a/chromium/chrome/browser/resources/new_tab_page/realbox_dropdown.html
+++ b/chromium/chrome/browser/resources/new_tab_page/realbox_dropdown.html
@@ -26,16 +26,16 @@
justify-content: space-between;
margin-top: 8px;
outline: none;
- padding-bottom: 4px;
+ padding-bottom: 6px;
padding-inline-end: 16px;
padding-inline-start: 12px;
- padding-top: 4px;
+ padding-top: 6px;
}
.header .text {
color: var(--google-grey-refresh-700);
cursor: default;
- font-size: 13px;
+ font-size: 14px;
font-weight: 500;
line-height: 16px;
overflow: hidden;
diff --git a/chromium/chrome/browser/resources/new_tab_page/realbox_dropdown.js b/chromium/chrome/browser/resources/new_tab_page/realbox_dropdown.js
index 7d902a2cdfb..7d7ab9e272f 100644
--- a/chromium/chrome/browser/resources/new_tab_page/realbox_dropdown.js
+++ b/chromium/chrome/browser/resources/new_tab_page/realbox_dropdown.js
@@ -275,8 +275,10 @@ class RealboxDropdownElement extends PolymerElement {
* @private
*/
onHeaderFocusin_() {
- // The header got focus. Unselect the selected match, if any.
- this.unselect();
+ this.dispatchEvent(new CustomEvent('header-focusin', {
+ bubbles: true,
+ composed: true,
+ }));
}
/**
diff --git a/chromium/chrome/browser/resources/new_tab_page/realbox_match.html b/chromium/chrome/browser/resources/new_tab_page/realbox_match.html
index 52f59f29d20..cef7e228029 100644
--- a/chromium/chrome/browser/resources/new_tab_page/realbox_match.html
+++ b/chromium/chrome/browser/resources/new_tab_page/realbox_match.html
@@ -78,7 +78,7 @@
<ntp-realbox-icon id="icon" match="[[match]]"></ntp-realbox-icon>
<div id="container">
<span id="contents" inner-h-t-m-l="[[contentsHtml_]]"></span>
- <span id="separator">[[separatorText_]]</span>
+ <span id="separator" class="dim">[[separatorText_]]</span>
<span id="description" inner-h-t-m-l="[[descriptionHtml_]]"></span>
</div>
<ntp-realbox-button id="remove" tabindex="0" role="button"
diff --git a/chromium/chrome/browser/resources/new_tab_page/realbox_match.js b/chromium/chrome/browser/resources/new_tab_page/realbox_match.js
index 485ad83f65a..666cfb4e3bb 100644
--- a/chromium/chrome/browser/resources/new_tab_page/realbox_match.js
+++ b/chromium/chrome/browser/resources/new_tab_page/realbox_match.js
@@ -277,8 +277,7 @@ class RealboxMatchElement extends PolymerElement {
* @private
*/
computeRemoveButtonIsVisible_() {
- return this.match && this.match.supportsDeletion &&
- loadTimeData.getBoolean('suggestionTransparencyEnabled');
+ return this.match && this.match.supportsDeletion;
}
/**
diff --git a/chromium/chrome/browser/resources/new_tab_page/untrusted/iframe.html b/chromium/chrome/browser/resources/new_tab_page/untrusted/iframe.html
deleted file mode 100644
index 43ee39396d2..00000000000
--- a/chromium/chrome/browser/resources/new_tab_page/untrusted/iframe.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <style>
- html,
- body,
- iframe {
- height: 100%;
- width: 100%;
- }
-
- body {
- margin: 0
- }
-
- iframe {
- border: none;
- }
- </style>
- </head>
- <body>
- <iframe src="$i18nRaw{url}"></iframe>
- </body>
-</html>
diff --git a/chromium/chrome/browser/resources/new_tab_page/untrusted/one_google_bar.html b/chromium/chrome/browser/resources/new_tab_page/untrusted/one_google_bar.html
index 96d509ff436..20e4c9ecdeb 100644
--- a/chromium/chrome/browser/resources/new_tab_page/untrusted/one_google_bar.html
+++ b/chromium/chrome/browser/resources/new_tab_page/untrusted/one_google_bar.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html dir="$i18n{textdirection}">
+<html dir="$i18n{textdirection}" $i18n{modalOverlays}>
<head>
<meta charset="utf-8">
<style>
diff --git a/chromium/chrome/browser/resources/new_tab_page/untrusted/one_google_bar.js b/chromium/chrome/browser/resources/new_tab_page/untrusted/one_google_bar.js
index 416e82acdee..a6bbf5c0de2 100644
--- a/chromium/chrome/browser/resources/new_tab_page/untrusted/one_google_bar.js
+++ b/chromium/chrome/browser/resources/new_tab_page/untrusted/one_google_bar.js
@@ -2,25 +2,16 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-const oneGoogleBarHeightInPixels = 64;
-
-/**
- * @param {boolean} enabled
- * @return {!Promise}
- */
-async function enableDarkTheme(enabled) {
- if (!window.gbar) {
- return;
- }
- const ogb = await window.gbar.a.bf();
- ogb.pc.call(ogb, enabled ? 1 : 0);
-}
-
/**
* The following |messageType|'s are sent to the parent frame:
* - loaded: sent on initial load.
* - overlaysUpdated: sent when an overlay is updated. The overlay bounding
- * rects are included in the |data|.
+ * rects are included in the |data|.
+ * - activate/deactivate: When an overlay is open, 'activate' is sent to the
+ * to ntp-app so it can layer the OneGoogleBar over the NTP content. When
+ * no overlays are open, 'deactivate' is sent to ntp-app so the NTP
+ * content can be on top. The top bar of the OneGoogleBar is always on
+ * top.
* @param {string} messageType
* @param {Object} data
*/
@@ -33,91 +24,206 @@ function postMessage(messageType, data) {
'chrome://new-tab-page');
}
-const overlays = new Set();
+// Object that exposes:
+// - |getEnabled()|: returns whether dark theme is enabled.
+// - |setEnabled(value)|: updates whether dark theme is enabled using the
+// OneGoogleBar API.
+const darkTheme = (() => {
+ let enabled = false;
-function sendOverlayUpdate() {
- // Remove overlays detached from DOM or elements in a parent overlay.
- Array.from(overlays).forEach(overlay => {
- if (!overlay.parentElement) {
- overlays.delete(overlay);
+ /** @return {boolean} */
+ const getEnabled = () => enabled;
+
+ /**
+ * @param {boolean} value
+ * @return {!Promise}
+ */
+ const setEnabled = async value => {
+ if (!window.gbar) {
return;
}
- let parent = overlay.parentElement;
- while (parent) {
- if (overlays.has(parent)) {
- overlays.delete(overlay);
- return;
- }
- parent = parent.parentElement;
+ enabled = value;
+ const ogb = await window.gbar.a.bf();
+ ogb.pc.call(ogb, enabled ? 1 : 0);
+ };
+
+ return {getEnabled, setEnabled};
+})();
+
+// Object that exposes:
+// - |track()|: sets up MutationObserver to track element visibility changes.
+// - |update(potentialNewOverlays)|: determines visibility of tracked elements
+// and sends an update to the top frame about element visibility.
+const overlayUpdater = (() => {
+ const modalOverlays = document.documentElement.hasAttribute('modal-overlays');
+ let shouldUndoDarkTheme = false;
+
+ /** @type {!Set<!Element>} */
+ const overlays = new Set();
+ /** @type {!Array<!DOMRect>} */
+ let lastOverlayRects = [];
+ /** @type {number} */
+ let elementsTransitioningCount = 0;
+ /** @type {?number} */
+ let updateIntervalId = null;
+ /** @type {boolean} */
+ let initialElementsAdded = false;
+
+ const transitionStart = () => {
+ elementsTransitioningCount++;
+ if (!updateIntervalId) {
+ updateIntervalId = setInterval(() => {
+ update([]);
+ });
}
- });
- // Check if an overlay and its parents are visible.
- const overlayRects =
- Array.from(overlays)
- .filter(overlay => {
- if (window.getComputedStyle(overlay).visibility === 'hidden') {
- return false;
- }
- let current = overlay;
- while (current) {
- if (window.getComputedStyle(current).display === 'none') {
- return false;
- }
- current = current.parentElement;
- }
- return true;
- })
- .map(el => el.getBoundingClientRect());
- postMessage('overlaysUpdated', overlayRects);
-}
+ };
+
+ const transitionStop = () => {
+ if (elementsTransitioningCount > 0) {
+ elementsTransitioningCount--;
+ }
+ if (updateIntervalId && elementsTransitioningCount === 0) {
+ clearInterval(updateIntervalId);
+ updateIntervalId = null;
+ }
+ };
+
+ /** @param {!Element} potentialNewOverlays */
+ const addOverlay = overlay => {
+ // If an overlay starts a transition, the updated bounding rects need to
+ // be sent to the top frame during the transition. The MutationObserver
+ // will only handle new elements and changes to the element attributes.
+ overlay.addEventListener('animationstart', transitionStart);
+ overlay.addEventListener('animationend', transitionStop);
+ overlay.addEventListener('animationcancel', transitionStop);
+ overlay.addEventListener('transitionstart', transitionStart);
+ overlay.addEventListener('transitionend', transitionStop);
+ overlay.addEventListener('transitioncancel', transitionStop);
+ // Update links that are loaded dynamically to ensure target is "_blank"
+ // or "_top".
+ // TODO(crbug.com/1039913): remove after OneGoogleBar links are updated.
+ overlay.parentElement.querySelectorAll('a').forEach(el => {
+ if (el.target !== '_blank' && el.target !== '_top') {
+ el.target = '_top';
+ }
+ });
+ overlays.add(overlay);
+ };
-function trackOverlayState() {
- const observer = new MutationObserver(mutations => {
- // After loaded, there could exist overlays that are shown, but not mutated.
- // Add all elements that could be an overlay. The children of the actual
- // overlay element are removed before sending any overlay update message.
- if (overlays.size === 0) {
+ /** @param {!Array<!Element>} potentialNewOverlays */
+ const update = potentialNewOverlays => {
+ const barRect = document.body.querySelector('#gb').getBoundingClientRect();
+ if (barRect.bottom === 0) {
+ return;
+ }
+ // After loaded, there could exist overlays that are shown, but not
+ // mutated. Add all elements that could be an overlay. The children of the
+ // actual overlay element are removed before sending any overlay update
+ // message.
+ if (!modalOverlays && !initialElementsAdded) {
+ initialElementsAdded = true;
Array.from(document.body.querySelectorAll('*')).forEach(el => {
- if (el.offsetTop + el.offsetHeight > oneGoogleBarHeightInPixels) {
- overlays.add(el);
- }
+ potentialNewOverlays.push(el);
});
}
- // Add any mutated element that is an overlay to |overlays|.
- mutations.forEach(({target}) => {
- if (target.id === 'gb' || target.tagName === 'BODY' ||
- overlays.has(target)) {
- return;
+ Array.from(potentialNewOverlays).forEach(overlay => {
+ const rect = overlay.getBoundingClientRect();
+ if (overlay.parentElement && rect.width > 0 &&
+ rect.bottom > barRect.bottom) {
+ addOverlay(overlay);
}
- if (target.offsetTop + target.offsetHeight > oneGoogleBarHeightInPixels) {
- overlays.add(target);
+ });
+ // Remove overlays detached from DOM.
+ Array.from(overlays).forEach(overlay => {
+ if (!overlay.parentElement) {
+ overlays.delete(overlay);
}
- // Update links that are loaded dynamically to ensure target is "_blank"
- // or "_top".
- // TODO(crbug.com/1039913): remove after OneGoogleBar links are updated.
- if (target.parentElement) {
- target.parentElement.querySelectorAll('a').forEach(el => {
- if (el.target !== '_blank' && el.target !== '_top') {
- el.target = '_top';
- }
- });
+ });
+ // Check if an overlay and its parents are visible.
+ const overlayRects = [];
+ overlays.forEach(overlay => {
+ const {display, visibility} = window.getComputedStyle(overlay);
+ const rect = overlay.getBoundingClientRect();
+ if (display !== 'none' && visibility !== 'hidden' &&
+ rect.bottom > barRect.bottom) {
+ overlayRects.push(rect);
}
});
- sendOverlayUpdate();
- });
- observer.observe(
- document, {attributes: true, childList: true, subtree: true});
-}
+ if (!modalOverlays) {
+ overlayRects.push(barRect);
+ const noChange = overlayRects.length === lastOverlayRects.length &&
+ lastOverlayRects.every((rect, i) => {
+ const newRect = overlayRects[i];
+ return newRect.left === rect.left && newRect.top === rect.top &&
+ newRect.right === rect.right && newRect.bottom === rect.bottom;
+ });
+ lastOverlayRects = overlayRects;
+ if (noChange) {
+ return;
+ }
+ postMessage('overlaysUpdated', overlayRects);
+ return;
+ }
+ const overlayShown = overlayRects.length > 0;
+ postMessage(overlayShown ? 'activate' : 'deactivate');
+ // If the overlays are modal, a dark backdrop is displayed below the
+ // OneGoogleBar iframe. The dark theme for the OneGoogleBar is then enabled
+ // for better visibility.
+ if (overlayShown) {
+ if (!darkTheme.getEnabled()) {
+ shouldUndoDarkTheme = true;
+ darkTheme.setEnabled(true);
+ }
+ } else if (shouldUndoDarkTheme) {
+ shouldUndoDarkTheme = false;
+ darkTheme.setEnabled(false);
+ }
+ };
+
+ const track = () => {
+ const observer = new MutationObserver(mutations => {
+ const potentialNewOverlays = [];
+ // Add any mutated element that is an overlay to |overlays|.
+ mutations.forEach(({target}) => {
+ if (overlays.has(target) || !target.parentElement) {
+ return;
+ }
+ // When overlays are modal, the tooltips should not be treated like an
+ // overlay.
+ if (modalOverlays && target.parentElement.tagName === 'BODY') {
+ return;
+ }
+ potentialNewOverlays.push(target);
+ });
+ update(potentialNewOverlays);
+ });
+ observer.observe(document.body, {
+ attributes: true,
+ childList: true,
+ subtree: true,
+ });
+ };
+
+ return {track, update};
+})();
window.addEventListener('message', ({data}) => {
if (data.type === 'enableDarkTheme') {
- enableDarkTheme(data.enabled);
+ darkTheme.setEnabled(data.enabled);
}
});
// Need to send overlay updates on resize because overlay bounding rects are
// absolutely positioned.
-window.addEventListener('resize', sendOverlayUpdate);
+window.addEventListener('resize', () => {
+ overlayUpdater.update([]);
+});
+
+// When the account overlay is shown, it does not close on blur. It does close
+// when clicking the body.
+window.addEventListener('blur', () => {
+ document.body.click();
+});
document.addEventListener('DOMContentLoaded', () => {
// TODO(crbug.com/1039913): remove after OneGoogleBar links are updated.
@@ -127,6 +233,7 @@ document.addEventListener('DOMContentLoaded', () => {
el.target = '_top';
}
});
+ modalOverlays = document.documentElement.hasAttribute('modal-overlays');
postMessage('loaded');
- trackOverlayState();
+ overlayUpdater.track();
});
diff --git a/chromium/chrome/browser/resources/new_tab_page/voice_search_overlay.html b/chromium/chrome/browser/resources/new_tab_page/voice_search_overlay.html
index 20e0a48c862..bd8484300bc 100644
--- a/chromium/chrome/browser/resources/new_tab_page/voice_search_overlay.html
+++ b/chromium/chrome/browser/resources/new_tab_page/voice_search_overlay.html
@@ -1,4 +1,4 @@
-<style>
+<style include="cr-icons">
:host {
--receiving-audio-color: var(--google-red-refresh-500);
--speak-shown-duration: 2s;
@@ -28,27 +28,10 @@
}
#closeButton {
- background: none;
- border: none;
- color: var(--ntp-secondary-text-color);
- cursor: pointer;
- font-family: inherit;
- font-size: 26px;
- height: 15px;
- line-height: 0;
- outline: none;
- padding: 0;
+ --cr-icon-button-fill-color: var(--ntp-secondary-text-color);
+ margin: 0;
position: absolute;
top: 16px;
- width: 15px;
- }
-
- #closeButton:hover {
- color: var(--ntp-secondary-text-hover-color);
- }
-
- :host-context(.focus-outline-visible) #closeButton:focus {
- box-shadow: var(--ntp-focus-shadow);
}
:host-context([dir='ltr']) #closeButton {
@@ -188,8 +171,12 @@
background-color: white;
}
</style>
-<dialog id="dialog" on-close="onOverlayClose_" on-click="onOverlayClick_">
- <button id="closeButton" tabindex="0" title="$i18n{close}">×</button>
+<dialog id="dialog" on-close="onOverlayClose_" on-click="onOverlayClick_"
+ on-keydown="onOverlayKeydown_">
+ <!-- Purely exists to capture focus upon opening the dialog. -->
+ <div tabindex="-1"></div>
+ <cr-icon-button id="closeButton" class="icon-clear" title="$i18n{close}">
+ </cr-icon-button>
<div id="content">
<iron-selector id="texts" selected="[[getText_(state_)]]"
attr-for-selected="text" fallback-selection="none" aria-live="polite"
@@ -200,32 +187,34 @@
<div id="speak">$i18n{speak}</div>
<div id="listening">$i18n{listening}</div>
</div>
- <div text="result">
+ <div text="result" aria-hidden="true">
<span id="finalResult">[[finalResult_]]</span>
<span>[[interimResult_]]</span>
</div>
<div text="error">
- <iron-pages id="errors" selected="[[error_]]" attr-for-selected="error"
- fallback-selection="7">
- <span error="1">$i18n{noVoice}</span>
- <span error="2">$i18n{audioError}</span>
- <span error="3">$i18n{networkError}</span>
- <span error="4">$i18n{permissionError}</span>
- <span error="5">$i18n{languageError}</span>
- <span error="6">$i18n{noTranslation}</span>
- <span error="7">$i18n{otherError}</span>
+ <iron-pages id="errors" selected="[[getErrorText_(error_)]]"
+ attr-for-selected="error" fallback-selection="other">
+ <span error="no-speech">$i18n{noVoice}</span>
+ <span error="audio-capture">$i18n{audioError}</span>
+ <span error="network">$i18n{networkError}</span>
+ <span error="not-allowed">$i18n{permissionError}</span>
+ <span error="language-not-supported">$i18n{languageError}</span>
+ <span error="no-match">$i18n{noTranslation}</span>
+ <span error="other">$i18n{otherError}</span>
</iron-pages>
<iron-pages id="errorLinks" selected="[[getErrorLink_(error_)]]"
attr-for-selected="link" fallback-selection="none">
<span link="none"></span>
- <a link="learn-more" target="_blank" href="[[helpUrl_]]"><!--
+ <a link="learn-more" target="_blank" href="[[helpUrl_]]"
+ on-click="onLearnMoreClick_" on-keydown="onLinkKeydown_"><!--
-->$i18n{learnMore}
</a>
- <a link="details" target="_blank" href="[[helpUrl_]]"><!--
+ <a link="details" target="_blank" href="[[helpUrl_]]"
+ on-keydown="onLinkKeydown_"><!--
-->$i18n{details}
</a>
<a link="try-again" id="retryLink" href="#"
- on-click="onRetryClick_"><!--
+ on-click="onTryAgainClick_" on-keydown="onLinkKeydown_"><!--
-->$i18n{tryAgain}
</a>
</iron-pages>
@@ -238,7 +227,7 @@
<div id="micVolumeCutout">
</div>
</div>
- <cr-button id="micButton" on-click="onRetryClick_">
+ <cr-button id="micButton" on-click="onMicClick_">
<div id="micIcon"></div>
</cr-button>
</div>
diff --git a/chromium/chrome/browser/resources/new_tab_page/voice_search_overlay.js b/chromium/chrome/browser/resources/new_tab_page/voice_search_overlay.js
index 278fac75e41..6db0f40b9ea 100644
--- a/chromium/chrome/browser/resources/new_tab_page/voice_search_overlay.js
+++ b/chromium/chrome/browser/resources/new_tab_page/voice_search_overlay.js
@@ -5,6 +5,7 @@
import 'chrome://resources/polymer/v3_0/iron-pages/iron-pages.js';
import 'chrome://resources/polymer/v3_0/iron-selector/iron-selector.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
+import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
@@ -90,20 +91,9 @@ const State = {
RESULT_FINAL: 5,
};
-/**
- * The set of possible recognition errors.
- * @enum {!number}
- */
-const Error = {
- ABORTED: 0,
- NO_SPEECH: 1,
- AUDIO_CAPTURE: 2,
- NETWORK: 3,
- NOT_ALLOWED: 4,
- LANGUAGE_NOT_SUPPORTED: 5,
- NO_MATCH: 6,
- OTHER: 7,
-};
+
+/** @typedef {newTabPage.mojom.VoiceSearchError} */
+const Error = newTabPage.mojom.VoiceSearchError;
/**
* Returns the error type based on the error string received from the webkit
@@ -125,8 +115,11 @@ function toError(webkitError) {
case 'no-speech':
return Error.NO_SPEECH;
case 'not-allowed':
- case 'service-not-allowed':
return Error.NOT_ALLOWED;
+ case 'service-not-allowed':
+ return Error.SERVICE_NOT_ALLOWED;
+ case 'bad-grammar':
+ return Error.BAD_GRAMMAR;
default:
return Error.OTHER;
}
@@ -201,6 +194,8 @@ class VoiceSearchOverlayElement extends PolymerElement {
constructor() {
super();
+ /** @private {newTabPage.mojom.PageHandlerRemote} */
+ this.pageHandler_ = BrowserProxy.getInstance().handler;
/** @private {webkitSpeechRecognition} */
this.voiceRecognition_ = new webkitSpeechRecognition();
this.voiceRecognition_.continuous = false;
@@ -243,19 +238,71 @@ class VoiceSearchOverlayElement extends PolymerElement {
/** @private */
onOverlayClick_() {
this.$.dialog.close();
+ this.pageHandler_.onVoiceSearchAction(
+ newTabPage.mojom.VoiceSearchAction.CLOSE_OVERLAY);
+ }
+
+ /**
+ * Handles <ENTER> or <SPACE> to trigger a query if we have recognized speech.
+ * @param {KeyboardEvent} e
+ * @private
+ */
+ onOverlayKeydown_(e) {
+ if (['Enter', ' '].includes(e.key) && this.finalResult_) {
+ this.onFinalResult_();
+ } else if (e.key === 'Escape') {
+ this.onOverlayClick_();
+ }
+ }
+
+ /**
+ * Handles <ENTER> or <SPACE> to simulate click.
+ * @param {KeyboardEvent} e
+ * @private
+ */
+ onLinkKeydown_(e) {
+ if (!['Enter', ' '].includes(e.key)) {
+ return;
+ }
+ // Otherwise, we may trigger overlay-wide keyboard shortcuts.
+ e.stopPropagation();
+ // Otherwise, we open the link twice.
+ e.preventDefault();
+ e.target.click();
+ }
+
+ /** @private */
+ onLearnMoreClick_() {
+ this.pageHandler_.onVoiceSearchAction(
+ newTabPage.mojom.VoiceSearchAction.SUPPORT_LINK_CLICKED);
+ }
+
+ /**
+ * @param {!Event} e
+ * @private
+ */
+ onTryAgainClick_(e) {
+ // Otherwise, we close the overlay.
+ e.stopPropagation();
+ this.start();
+ this.pageHandler_.onVoiceSearchAction(
+ newTabPage.mojom.VoiceSearchAction.TRY_AGAIN_LINK);
}
/**
* @param {!Event} e
* @private
*/
- onRetryClick_(e) {
+ onMicClick_(e) {
if (this.state_ !== State.ERROR_RECEIVED ||
this.error_ !== Error.NO_MATCH) {
return;
}
+ // Otherwise, we close the overlay.
e.stopPropagation();
this.start();
+ this.pageHandler_.onVoiceSearchAction(
+ newTabPage.mojom.VoiceSearchAction.TRY_AGAIN_MIC_BUTTON);
}
/** @private */
@@ -286,8 +333,9 @@ class VoiceSearchOverlayElement extends PolymerElement {
*/
resetErrorTimer_(duration) {
BrowserProxy.getInstance().clearTimeout(this.timerId_);
- this.timerId_ = BrowserProxy.getInstance().setTimeout(
- this.onOverlayClick_.bind(this), duration);
+ this.timerId_ = BrowserProxy.getInstance().setTimeout(() => {
+ this.$.dialog.close();
+ }, duration);
}
/** @private */
@@ -376,6 +424,8 @@ class VoiceSearchOverlayElement extends PolymerElement {
const queryUrl =
new URL('/search', loadTimeData.getString('googleBaseUrl'));
queryUrl.search = searchParams.toString();
+ this.pageHandler_.onVoiceSearchAction(
+ newTabPage.mojom.VoiceSearchAction.QUERY_SUBMITTED);
BrowserProxy.getInstance().navigate(queryUrl.href);
}
@@ -406,6 +456,7 @@ class VoiceSearchOverlayElement extends PolymerElement {
* @private
*/
onError_(error) {
+ this.pageHandler_.onVoiceSearchError(error);
if (error === Error.ABORTED) {
// We are in the process of closing voice search.
return;
@@ -457,12 +508,39 @@ class VoiceSearchOverlayElement extends PolymerElement {
* @return {string}
* @private
*/
+ getErrorText_() {
+ switch (this.error_) {
+ case Error.NO_SPEECH:
+ return 'no-speech';
+ case Error.AUDIO_CAPTURE:
+ return 'audio-capture';
+ case Error.NETWORK:
+ return 'network';
+ case Error.NOT_ALLOWED:
+ case Error.SERVICE_NOT_ALLOWED:
+ return 'not-allowed';
+ case Error.LANGUAGE_NOT_SUPPORTED:
+ return 'language-not-supported';
+ case Error.NO_MATCH:
+ return 'no-match';
+ case Error.ABORTED:
+ case Error.OTHER:
+ default:
+ return 'other';
+ }
+ }
+
+ /**
+ * @return {string}
+ * @private
+ */
getErrorLink_() {
switch (this.error_) {
case Error.NO_SPEECH:
case Error.AUDIO_CAPTURE:
return 'learn-more';
case Error.NOT_ALLOWED:
+ case Error.SERVICE_NOT_ALLOWED:
return 'details';
case Error.NO_MATCH:
return 'try-again';
diff --git a/chromium/chrome/browser/resources/omnibox/resources.grd b/chromium/chrome/browser/resources/omnibox/resources.grd
index 349526f27ab..273065f153d 100644
--- a/chromium/chrome/browser/resources/omnibox/resources.grd
+++ b/chromium/chrome/browser/resources/omnibox/resources.grd
@@ -14,53 +14,41 @@
file="omnibox.html"
flattenhtml="true"
allowexternalscript="true"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OMNIBOX_POPUP_HTML"
file="omnibox_popup.html"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OMNIBOX_CSS"
file="omnibox.css"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OMNIBOX_INPUT_CSS"
file="omnibox_input.css"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OUTPUT_RESULTS_GROUP_CSS"
file="output_results_group.css"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OMNIBOX_OUTPUT_COLUMN_WIDTHS_CSS"
file="omnibox_output_column_widths.css"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OMNIBOX_ELEMENT_JS"
file="omnibox_element.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OMNIBOX_INPUT_JS"
file="omnibox_input.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OMNIBOX_OUTPUT_JS"
file="omnibox_output.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OMNIBOX_POPUP_JS"
- file="omnibox_popup.js"
- type="BINDATA"
- compress="gzip" />
+ file="omnibox_popup.js"
+ type="BINDATA" />
<include name="IDR_OMNIBOX_JS"
file="omnibox.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OMNIBOX_MOJO_JS"
file="${root_gen_dir}\chrome\browser\ui\webui\omnibox\omnibox.mojom-lite.js"
use_base_dir="false"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/optimize_webui.gni b/chromium/chrome/browser/resources/optimize_webui.gni
index bfc1f5a4121..01db4694669 100644
--- a/chromium/chrome/browser/resources/optimize_webui.gni
+++ b/chromium/chrome/browser/resources/optimize_webui.gni
@@ -103,5 +103,16 @@ template("unpak") {
"--pak_file",
rebase_path("$target_gen_dir/${invoker.pak_file}", root_build_dir),
]
+
+ if (defined(invoker.pak_base_dir)) {
+ args += [
+ "--pak_base_dir",
+ rebase_path("$target_gen_dir/${invoker.pak_base_dir}", root_build_dir),
+ ]
+ }
+
+ if (defined(invoker.excludes)) {
+ args += [ "--excludes" ] + invoker.excludes
+ }
}
}
diff --git a/chromium/chrome/browser/resources/optimize_webui.py b/chromium/chrome/browser/resources/optimize_webui.py
index 388cb640460..30ffbf7f343 100755
--- a/chromium/chrome/browser/resources/optimize_webui.py
+++ b/chromium/chrome/browser/resources/optimize_webui.py
@@ -58,25 +58,29 @@ _POLYMER_PATH = os.path.join(
# These files are already combined and minified.
_BASE_EXCLUDES = [
- # Common excludes for both Polymer 2 and 3.
- 'chrome://resources/polymer/v1_0/web-animations-js/' +
- 'web-animations-next-lite.min.js',
- 'chrome://resources/css/roboto.css',
- 'chrome://resources/css/text_defaults.css',
- 'chrome://resources/css/text_defaults_md.css',
- 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.html',
-
# Excludes applying only to Polymer 2.
'chrome://resources/html/polymer.html',
'chrome://resources/polymer/v1_0/polymer/polymer.html',
'chrome://resources/polymer/v1_0/polymer/polymer-micro.html',
'chrome://resources/polymer/v1_0/polymer/polymer-mini.html',
- 'chrome://resources/js/load_time_data.js',
+ 'chrome://resources/js/load_time_data.js'
+]
+for excluded_file in [
+ # Common excludes for both Polymer 2 and 3.
+ 'resources/polymer/v1_0/web-animations-js/web-animations-next-lite.min.js',
+ 'resources/css/roboto.css',
+ 'resources/css/text_defaults.css',
+ 'resources/css/text_defaults_md.css',
+ 'resources/mojo/mojo/public/js/mojo_bindings_lite.html',
# Excludes applying only to Polymer 3.
- 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js',
- 'chrome://resources/js/load_time_data.m.js',
-]
+ 'resources/polymer/v3_0/polymer/polymer_bundled.min.js',
+ 'resources/js/load_time_data.m.js',
+]:
+ # Exclude both the chrome://resources form and the scheme-relative form for
+ # files used in Polymer 3.
+ _BASE_EXCLUDES.append("chrome://" + excluded_file)
+ _BASE_EXCLUDES.append("//" + excluded_file)
_VULCANIZE_BASE_ARGS = [
'--inline-css',
@@ -85,15 +89,19 @@ _VULCANIZE_BASE_ARGS = [
'--strip-comments',
]
-_URL_MAPPINGS = [
- ('chrome://resources/cr_components/', _CR_COMPONENTS_PATH),
- ('chrome://resources/cr_elements/', _CR_ELEMENTS_PATH),
- ('chrome://resources/css/', _CSS_RESOURCES_PATH),
- ('chrome://resources/html/', _HTML_RESOURCES_PATH),
- ('chrome://resources/js/', _JS_RESOURCES_PATH),
- ('chrome://resources/polymer/v1_0/', _POLYMER_PATH),
- ('chrome://resources/images/', _IMAGES_RESOURCES_PATH)
-]
+_URL_MAPPINGS = []
+for (redirect_url, file_path) in [
+ ('resources/cr_components/', _CR_COMPONENTS_PATH),
+ ('resources/cr_elements/', _CR_ELEMENTS_PATH),
+ ('resources/css/', _CSS_RESOURCES_PATH),
+ ('resources/html/', _HTML_RESOURCES_PATH),
+ ('resources/js/', _JS_RESOURCES_PATH),
+ ('resources/polymer/v1_0/', _POLYMER_PATH),
+ ('resources/images/', _IMAGES_RESOURCES_PATH),
+]:
+ # Redirect both the chrome://resources form and the scheme-relative form.
+ _URL_MAPPINGS.append(('chrome://' + redirect_url, file_path))
+ _URL_MAPPINGS.append(('//' + redirect_url, file_path))
_VULCANIZE_REDIRECT_ARGS = list(itertools.chain.from_iterable(map(
@@ -123,7 +131,7 @@ def _update_dep_file(in_folder, args, manifest):
# Add a slash in front of every dependency that is not a chrome:// URL, so
# that we can map it to the correct source file path below.
request_list = map(
- lambda dep: '/' + dep if not dep.startswith('chrome://') else dep,
+ lambda dep: '/' + dep if not (dep.startswith('chrome://') or dep.startswith('//')) else dep,
request_list)
# Undo the URL mappings applied by vulcanize to get file paths relative to
@@ -138,7 +146,7 @@ def _update_dep_file(in_folder, args, manifest):
# If the input was a folder holding an unpacked .pak file, the generated
# depfile should not list files already in the .pak file.
- if args.input.endswith('.unpak'):
+ if args.input.endswith('unpak'):
filter_url = args.input
deps = [d for d in deps if not d.startswith(filter_url)]
@@ -210,9 +218,10 @@ def _bundle_v3(tmp_out_dir, in_path, out_path, manifest_out_path, args,
# arbitrary names?
bundled_paths = []
for index, js_file in enumerate(args.js_module_in_files):
- expected_name = '%s.rollup.js' % js_file[:-len('.js')]
+ base_file_name = os.path.basename(js_file)
+ expected_name = '%s.rollup.js' % base_file_name[:-len('.js')]
assert args.js_out_files[index] == expected_name, \
- 'Output file corresponding to %s should be named %s.rollup.js' % \
+ 'Output file corresponding to %s should be named %s' % \
(js_file, expected_name)
bundled_paths.append(os.path.join(tmp_out_dir, expected_name))
diff --git a/chromium/chrome/browser/resources/pdf/BUILD.gn b/chromium/chrome/browser/resources/pdf/BUILD.gn
index c975fd597e2..02cef40417b 100644
--- a/chromium/chrome/browser/resources/pdf/BUILD.gn
+++ b/chromium/chrome/browser/resources/pdf/BUILD.gn
@@ -3,6 +3,22 @@
# found in the LICENSE file.
import("//third_party/closure_compiler/compile_js.gni")
+import("//tools/polymer/html_to_js.gni")
+
+group("web_components") {
+ public_deps = [
+ ":web_components_local",
+ "elements:web_components",
+ ]
+}
+
+html_to_js("web_components_local") {
+ js_files = [
+ "pdf_viewer.js",
+ "pdf_viewer_pp.js",
+ "pdf_viewer_shared_style.js",
+ ]
+}
group("closure_compile") {
deps = [
@@ -32,10 +48,12 @@ js_library("constants") {
}
js_library("gesture_detector") {
+ deps = [ "//ui/webui/resources/js/cr:event_target.m" ]
}
js_library("open_pdf_params_parser") {
deps = [ ":constants" ]
+ externs_list = [ "$externs_path/pending.js" ]
}
js_library("pdf_scripting_api") {
@@ -83,32 +101,61 @@ js_library("toolbar_manager") {
]
}
-js_library("controller") {
+js_library("ink_controller") {
deps = [
":annotation_tool",
+ ":controller",
+ ":viewport",
+ "//ui/webui/resources/js/cr:event_target.m",
+ ]
+}
+
+js_library("controller") {
+ deps = [
":viewport",
"elements:viewer-pdf-toolbar",
"//ui/webui/resources/js:assert.m",
"//ui/webui/resources/js:load_time_data.m",
"//ui/webui/resources/js:promise_resolver.m",
- "//ui/webui/resources/js:util.m",
"//ui/webui/resources/js/cr:event_target.m",
]
}
+js_library("pdf_viewer_base") {
+ deps = [
+ ":browser_api",
+ ":constants",
+ ":controller",
+ ":metrics",
+ ":pdf_scripting_api",
+ ":pdf_viewer_utils",
+ ":viewport",
+ ":viewport_scroller",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/js:assert.m",
+ "//ui/webui/resources/js:event_tracker.m",
+ "//ui/webui/resources/js:load_time_data.m",
+ "//ui/webui/resources/js:promise_resolver.m",
+ "//ui/webui/resources/js:util.m",
+ ]
+ externs_list = [ "$externs_path/resources_private.js" ]
+}
+
js_library("pdf_viewer") {
deps = [
":bookmark_type",
+ ":browser_api",
":constants",
":controller",
+ ":ink_controller",
":metrics",
":navigator",
":pdf_scripting_api",
+ ":pdf_viewer_base",
+ ":pdf_viewer_utils",
":toolbar_manager",
":viewport",
- ":viewport_scroller",
"elements:viewer-error-screen",
- "elements:viewer-page-indicator",
"elements:viewer-password-screen",
"elements:viewer-pdf-toolbar",
"elements:viewer-zoom-toolbar",
@@ -121,19 +168,39 @@ js_library("pdf_viewer") {
externs_list = [ "$externs_path/resources_private.js" ]
}
-js_library("main_util") {
+js_library("pdf_viewer_utils") {
deps = [
- ":browser_api",
- ":pdf_viewer",
+ ":controller",
+ ":viewport",
]
}
-js_library("main") {
- deps = [ ":main_util" ]
+js_library("pdf_viewer_pp") {
+ deps = [
+ ":constants",
+ ":controller",
+ ":pdf_scripting_api",
+ ":pdf_viewer_base",
+ ":pdf_viewer_utils",
+ ":toolbar_manager",
+ ":viewport",
+ "elements:viewer-error-screen",
+ "elements:viewer-page-indicator",
+ "elements:viewer-zoom-toolbar",
+ "//ui/webui/resources/js:assert.m",
+ "//ui/webui/resources/js:event_tracker.m",
+ "//ui/webui/resources/js:load_time_data.m",
+ "//ui/webui/resources/js:promise_resolver.m",
+ "//ui/webui/resources/js:util.m",
+ ]
+ externs_list = [ "$externs_path/resources_private.js" ]
}
-js_library("main_pp") {
- deps = [ ":main_util" ]
+js_library("main") {
+ deps = [
+ ":browser_api",
+ ":pdf_viewer",
+ ]
}
js_type_check("pdf_resources") {
@@ -144,14 +211,16 @@ js_type_check("pdf_resources") {
":constants",
":controller",
":gesture_detector",
+ ":ink_controller",
":main",
- ":main_pp",
- ":main_util",
":metrics",
":navigator",
":open_pdf_params_parser",
":pdf_scripting_api",
":pdf_viewer",
+ ":pdf_viewer_base",
+ ":pdf_viewer_pp",
+ ":pdf_viewer_utils",
":toolbar_manager",
":viewport",
":viewport_scroller",
diff --git a/chromium/chrome/browser/resources/pdf/annotation_tool.js b/chromium/chrome/browser/resources/pdf/annotation_tool.js
index 5e887b048b7..e8fa6e74d6c 100644
--- a/chromium/chrome/browser/resources/pdf/annotation_tool.js
+++ b/chromium/chrome/browser/resources/pdf/annotation_tool.js
@@ -9,7 +9,7 @@
* @typedef {{
* tool: string,
* size: number,
- * color: (string|null),
+ * color: (string|undefined),
* }}
*/
let AnnotationTool;
diff --git a/chromium/chrome/browser/resources/pdf/browser_api.js b/chromium/chrome/browser/resources/pdf/browser_api.js
index 53ceeef1da9..5e2fb44cdc3 100644
--- a/chromium/chrome/browser/resources/pdf/browser_api.js
+++ b/chromium/chrome/browser/resources/pdf/browser_api.js
@@ -28,7 +28,6 @@ function lookupDefaultZoom(streamInfo) {
* Returns a promise that will resolve to the initial zoom factor
* upon starting the plugin. This may differ from the default zoom
* if, for example, the page is zoomed before the plugin is run.
- *
* @param {!Object} streamInfo The stream object pointing to the data contained
* in the PDF.
* @return {Promise<number>} A promise that will resolve to the initial zoom
@@ -46,9 +45,7 @@ function lookupInitialZoom(streamInfo) {
});
}
-/**
- * A class providing an interface to the browser.
- */
+// A class providing an interface to the browser.
export class BrowserApi {
/**
* @param {!Object} streamInfo The stream object which points to the data
@@ -90,7 +87,6 @@ export class BrowserApi {
/**
* Sets the browser zoom.
- *
* @param {number} zoom The zoom factor to send to the browser.
* @return {Promise} A promise that will be resolved when the browser zoom
* has been updated.
@@ -104,23 +100,17 @@ export class BrowserApi {
});
}
- /**
- * @return {number} The default browser zoom factor.
- */
+ /** @return {number} The default browser zoom factor. */
getDefaultZoom() {
return this.defaultZoom_;
}
- /**
- * @return {number} The initial browser zoom factor.
- */
+ /** @return {number} The initial browser zoom factor. */
getInitialZoom() {
return this.initialZoom_;
}
- /**
- * @return {BrowserApi.ZoomBehavior} How to manage zoom.
- */
+ /** @return {BrowserApi.ZoomBehavior} How to manage zoom. */
getZoomBehavior() {
return this.zoomBehavior_;
}
@@ -160,7 +150,6 @@ BrowserApi.ZoomBehavior = {
/**
* Creates a BrowserApi for an extension running as a mime handler.
- *
* @return {!Promise<!BrowserApi>} A promise to a BrowserApi instance
* constructed using the mimeHandlerPrivate API.
*/
@@ -197,7 +186,6 @@ function createBrowserApiForMimeHandlerView() {
/**
* Creates a BrowserApi instance for an extension not running as a mime handler.
- *
* @return {!Promise<!BrowserApi>} A promise to a BrowserApi instance
* constructed from the URL.
*/
diff --git a/chromium/chrome/browser/resources/pdf/constants.js b/chromium/chrome/browser/resources/pdf/constants.js
index 70da3e827d7..475061b73ae 100644
--- a/chromium/chrome/browser/resources/pdf/constants.js
+++ b/chromium/chrome/browser/resources/pdf/constants.js
@@ -21,3 +21,14 @@ export const TwoUpViewAction = {
TWO_UP_VIEW_ENABLE: 'two-up-view-enable',
TWO_UP_VIEW_DISABLE: 'two-up-view-disable',
};
+
+/**
+ * Enumeration of save message request types. Must Match SaveRequestType in
+ * pdf/out_of_process_instance.h.
+ * @enum {number}
+ */
+export const SaveRequestType = {
+ ANNOTATION: 0,
+ ORIGINAL: 1,
+ EDITED: 2,
+};
diff --git a/chromium/chrome/browser/resources/pdf/controller.js b/chromium/chrome/browser/resources/pdf/controller.js
index 9eccd835645..95c02f1fa0d 100644
--- a/chromium/chrome/browser/resources/pdf/controller.js
+++ b/chromium/chrome/browser/resources/pdf/controller.js
@@ -6,8 +6,8 @@ import {assert} from 'chrome://resources/js/assert.m.js';
import {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_target.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js';
-import {$} from 'chrome://resources/js/util.m.js';
+import {SaveRequestType} from './constants.js';
import {PartialPoint, Point, Viewport} from './viewport.js';
/** @typedef {{ type: string }} */
@@ -45,25 +45,6 @@ let EmailMessageData;
*/
export let PrintPreviewParams;
-// Note: Redefining this type here, to work around the fact that ink externs
-// are only available on Chrome OS, so the targets that contain them cannot be
-// built on other platforms.
-// TODO (rbpotter): Break InkController into its own file that is only included
-// on Chrome OS.
-
-/**
- * @typedef {{
- * setAnnotationTool: function(AnnotationTool):void,
- * viewportChanged: function():void,
- * saveDocument: function():!Promise,
- * undo: function():void,
- * redo: function():void,
- * load: function(string, !ArrayBuffer):!Promise,
- * viewport: !Viewport,
- * }}
- */
-let ViewerInkHostElement;
-
/**
* Creates a cryptographically secure pseudorandom 128-bit token.
* @return {string} The generated token as a hex string.
@@ -105,12 +86,13 @@ export class ContentController {
/**
* Requests that the current document be saved.
- * @param {boolean} requireResult whether a response is required, otherwise
- * the controller may save the document to disk internally.
+ * @param {!SaveRequestType} requestType The type of save request. If
+ * ANNOTATION, a response is required, otherwise the controller may save
+ * the document to disk internally.
* @return {Promise<{fileName: string, dataToSave: ArrayBuffer}>}
* @abstract
*/
- save(requireResult) {}
+ save(requestType) {}
/**
* Loads PDF document from `data` activates UI.
@@ -128,110 +110,9 @@ export class ContentController {
unload() {}
}
-/**
- * Controller for annotation mode, on Chrome OS only. Fires the following events
- * from its event target:
- * has-unsaved-changes: Fired to indicate there are ink annotations that have
- * not been saved.
- * set-annotation-undo-state: Contains information about whether undo or redo
- * options are available.
- */
-export class InkController extends ContentController {
- /** @param {!Viewport} viewport */
- constructor(viewport) {
- super();
-
- /** @private {!Viewport} */
- this.viewport_ = viewport;
-
- /** @private {?ViewerInkHostElement} */
- this.inkHost_ = null;
-
- /** @private {!EventTarget} */
- this.eventTarget_ = new EventTarget();
-
- /** @type {?AnnotationTool} */
- this.tool_ = null;
- }
-
- /** @return {!EventTarget} */
- getEventTarget() {
- return this.eventTarget_;
- }
-
- /** @param {AnnotationTool} tool */
- setAnnotationTool(tool) {
- this.tool_ = tool;
- if (this.inkHost_) {
- this.inkHost_.setAnnotationTool(tool);
- }
- }
-
- /** @override */
- rotateClockwise() {
- // TODO(dstockwell): implement rotation
- }
-
- /** @override */
- rotateCounterclockwise() {
- // TODO(dstockwell): implement rotation
- }
-
- /** @override */
- setTwoUpView(enableTwoUpView) {
- // TODO(dstockwell): Implement two up view.
- }
-
- /** @override */
- viewportChanged() {
- this.inkHost_.viewportChanged();
- }
-
- /** @override */
- save(requireResult) {
- return this.inkHost_.saveDocument();
- }
-
- /** @override */
- undo() {
- this.inkHost_.undo();
- }
-
- /** @override */
- redo() {
- this.inkHost_.redo();
- }
-
- /** @override */
- load(filename, data) {
- if (!this.inkHost_) {
- const inkHost = document.createElement('viewer-ink-host');
- $('content').appendChild(inkHost);
- this.inkHost_ = /** @type {!ViewerInkHostElement} */ (inkHost);
- this.inkHost_.viewport = this.viewport_;
- inkHost.addEventListener('stroke-added', e => {
- this.eventTarget_.dispatchEvent(new CustomEvent('has-unsaved-changes'));
- });
- inkHost.addEventListener('undo-state-changed', e => {
- this.eventTarget_.dispatchEvent(
- new CustomEvent('set-annotation-undo-state', {detail: e.detail}));
- });
- }
- return this.inkHost_.load(filename, data);
- }
-
- /** @override */
- unload() {
- this.inkHost_.remove();
- this.inkHost_ = null;
- }
-}
-
-/**
- * PDF plugin controller, responsible for communicating with the embedded plugin
- * element. Dispatches a 'plugin-message' event containing the message from the
- * plugin, if a message type not handled by this controller is received.
- */
+// PDF plugin controller, responsible for communicating with the embedded plugin
+// element. Dispatches a 'plugin-message' event containing the message from the
+// plugin, if a message type not handled by this controller is received.
export class PluginController extends ContentController {
/**
* @param {!HTMLEmbedElement} plugin
@@ -407,11 +288,15 @@ export class PluginController extends ContentController {
}
/** @override */
- save(requireResult) {
+ save(requestType) {
const resolver = new PromiseResolver();
const newToken = createToken();
this.pendingTokens_.set(newToken, resolver);
- this.postMessage_({type: 'save', token: newToken, force: requireResult});
+ this.postMessage_({
+ type: 'save',
+ token: newToken,
+ saveRequestType: requestType,
+ });
return resolver.promise;
}
@@ -420,6 +305,7 @@ export class PluginController extends ContentController {
const url = URL.createObjectURL(new Blob([data]));
this.plugin_.removeAttribute('headers');
this.plugin_.setAttribute('stream-url', url);
+ this.plugin_.setAttribute('has-edits', '');
this.plugin_.style.display = 'block';
try {
await this.getLoadedCallback_();
@@ -476,7 +362,6 @@ export class PluginController extends ContentController {
/**
* Handles the pdf file buffer received from the plugin.
- *
* @param {!SaveDataMessageData} messageData data of the message event.
* @private
*/
diff --git a/chromium/chrome/browser/resources/pdf/elements/BUILD.gn b/chromium/chrome/browser/resources/pdf/elements/BUILD.gn
index 1980c0a3421..0eaa9db89f2 100644
--- a/chromium/chrome/browser/resources/pdf/elements/BUILD.gn
+++ b/chromium/chrome/browser/resources/pdf/elements/BUILD.gn
@@ -14,6 +14,7 @@ js_type_check("closure_compile") {
":viewer-page-selector",
":viewer-password-screen",
":viewer-pdf-toolbar",
+ ":viewer-pdf-toolbar-new",
":viewer-toolbar-dropdown",
":viewer-zoom-button",
":viewer-zoom-toolbar",
@@ -67,7 +68,10 @@ js_library("viewer-page-selector") {
}
js_library("viewer-password-screen") {
- deps = [ "//ui/webui/resources/cr_elements/cr_input:cr_input.m" ]
+ deps = [
+ "//ui/webui/resources/cr_elements/cr_input:cr_input.m",
+ "//ui/webui/resources/js:load_time_data.m",
+ ]
}
js_library("viewer-pdf-toolbar") {
@@ -76,10 +80,21 @@ js_library("viewer-pdf-toolbar") {
":viewer-page-selector",
":viewer-toolbar-dropdown",
"..:annotation_tool",
+ "..:constants",
+ "//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu.m",
+ "//ui/webui/resources/js:assert.m",
+ "//ui/webui/resources/js:load_time_data.m",
+ "//ui/webui/resources/js:promise_resolver.m",
]
externs_list = [ "$externs_path/pending.js" ]
}
+js_library("viewer-pdf-toolbar-new") {
+ deps = [
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ ]
+}
+
js_library("viewer-pen-options") {
}
@@ -109,6 +124,7 @@ html_to_js("web_components") {
"viewer-page-selector.js",
"viewer-password-screen.js",
"viewer-pdf-toolbar.js",
+ "viewer-pdf-toolbar-new.js",
"viewer-toolbar-dropdown.js",
"viewer-zoom-button.js",
"viewer-zoom-toolbar.js",
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark.html b/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark.html
index ec39a68550e..8cf60ea1aa7 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-bookmark.html
@@ -47,13 +47,13 @@
<paper-ripple></paper-ripple>
<cr-icon-button id="expand" iron-icon="cr:chevron-right"
on-click="toggleChildren_"></cr-icon-button>
- <span id="title" tabindex="0">{{bookmark.title}}</span>
+ <span id="title" tabindex="0">[[bookmark.title]]</span>
</div>
<!-- dom-if will stamp the complex bookmark tree lazily as individual nodes
are opened. -->
<template is="dom-if" if="[[childrenShown_]]">
<template is="dom-repeat" items="[[bookmark.children]]">
- <viewer-bookmark bookmark="{{item}}" depth="[[childDepth_]]">
+ <viewer-bookmark bookmark="[[item]]" depth="[[childDepth_]]">
</viewer-bookmark>
</template>
</template>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen.html b/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen.html
index 03047141d77..e2c210fbd08 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen.html
@@ -1,10 +1,10 @@
<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="title">$i18n{errorDialogTitle}</div>
+ <div slot="body">$i18n{pageLoadFailed}</div>
<div slot="button-container" hidden$="[[!reloadFn]]">
<cr-button class="action-button" on-click="reload">
- [[strings.pageReload]]
+ $i18n{pageReload}
</cr-button>
</div>
</cr-dialog>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen.js b/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen.js
index d3383b06e25..d5702f659d4 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-error-screen.js
@@ -15,8 +15,6 @@ Polymer({
properties: {
reloadFn: Function,
-
- strings: Object,
},
show() {
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning.html b/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning.html
index 1906119a962..61293db59aa 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning.html
@@ -1,13 +1,13 @@
<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="title">$i18n{annotationFormWarningTitle}</div>
+ <div slot="body">$i18n{annotationFormWarningDetail}</div>
<div slot="button-container">
<cr-button class="cancel-button" on-click="onCancel">
- [[strings.annotationFormWarningKeepEditing]]
+ $i18n{annotationFormWarningKeepEditing}
</cr-button>
<cr-button class="action-button" on-click="onAction">
- [[strings.annotationFormWarningDiscard]]
+ $i18n{annotationFormWarningDiscard}
</cr-button>
</div>
</cr-dialog>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning.js b/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning.js
index d0cbd6d1de8..900c8d45b1e 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-form-warning.js
@@ -14,10 +14,6 @@ Polymer({
_template: html`{__html_template__}`,
- properties: {
- strings: Object,
- },
-
/** @private {PromiseResolver} */
resolver_: null,
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-ink-host.js b/chromium/chrome/browser/resources/pdf/elements/viewer-ink-host.js
index fa208811e90..6c8b184407f 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-ink-host.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-ink-host.js
@@ -3,8 +3,9 @@
// found in the LICENSE file.
import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
import {PDFMetrics} from '../metrics.js';
-import {Viewport} from '../viewport.js';
+import {PAGE_SHADOW, Viewport} from '../viewport.js';
/** @enum {string} */
const State = {
@@ -62,7 +63,6 @@ Polymer({
/**
* Whether we should suppress pointer events due to a gesture,
* eg. pinch-zoom.
- *
* @private {boolean}
*/
pointerGesture_: false,
@@ -96,19 +96,10 @@ Polymer({
/**
* Dispatches a pointer event to Ink.
- *
* @param {PointerEvent} e
*/
dispatchPointerEvent_(e) {
- // TODO(dstockwell) come up with a solution to propagate e.timeStamp.
- this.ink_.dispatchPointerEvent(e.type, {
- pointerId: e.pointerId,
- pointerType: e.pointerType,
- clientX: e.clientX,
- clientY: e.clientY,
- pressure: e.pressure,
- buttons: e.buttons,
- });
+ this.ink_.dispatchPointerEvent(e);
},
/** @param {TouchEvent} e */
@@ -135,10 +126,10 @@ Polymer({
// A multi-touch gesture has started with the active pointer. Cancel
// the active pointer and suppress further events until it is released.
this.pointerGesture_ = true;
- this.ink_.dispatchPointerEvent('pointercancel', {
+ this.ink_.dispatchPointerEvent(new PointerEvent('pointercancel', {
pointerId: this.activePointer_.pointerId,
pointerType: this.activePointer_.pointerType,
- });
+ }));
}
return;
}
@@ -241,7 +232,7 @@ Polymer({
// color.
await new Promise(resolve => setTimeout(resolve));
this.ink_.setOutOfBoundsColor(BACKGROUND_COLOR);
- const spacing = Viewport.PAGE_SHADOW.top + Viewport.PAGE_SHADOW.bottom;
+ const spacing = PAGE_SHADOW.top + PAGE_SHADOW.bottom;
this.ink_.setPageSpacing(spacing);
this.style.visibility = 'visible';
},
@@ -256,8 +247,8 @@ Polymer({
const zoom = viewport.getZoom();
const documentWidth = viewport.getDocumentDimensions().width * zoom;
// Adjust for page shadows.
- const y = pos.y - Viewport.PAGE_SHADOW.top * zoom;
- let x = pos.x - Viewport.PAGE_SHADOW.left * zoom;
+ const y = pos.y - PAGE_SHADOW.top * zoom;
+ let x = pos.x - PAGE_SHADOW.left * zoom;
// Center the document if the width is smaller than the viewport.
if (documentWidth < size.width) {
x += (documentWidth - size.width) / 2;
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator.html b/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator.html
index 966a10c3661..5504e761500 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-page-indicator.html
@@ -34,5 +34,5 @@
width: 0;
}
</style>
- <div id="text">{{label}}</div>
+ <div id="text">[[label]]</div>
<div id="triangle-end"></div>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector.html b/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector.html
index 1402b838971..002a23ad3fc 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector.html
@@ -3,6 +3,8 @@
color: #fff;
display: flex;
font-size: 0.81rem;
+
+ --page-selector-spacing: 4px;
}
:host ::selection {
@@ -11,12 +13,10 @@
#pageselector::part(input),
#pagelength {
- box-sizing: content-box;
- padding: 0 3px;
/* --page-length-digits is set through JavaScript. 1px is added because
* the unit 'ch' does not provide exact whole number pixels, and
* therefore seems to have 1px-off bugginess. */
- width: calc(var(--page-length-digits) * 1ch + 1px);
+ width: calc(max(2, var(--page-length-digits)) * 1ch + 1px);
}
#pageselector {
@@ -29,13 +29,18 @@
#pageselector::part(input) {
background: rgba(0, 0, 0, 0.5);
+ box-sizing: content-box;
caret-color: var(--cr-input-color);
- text-align: end;
+ padding: 0 var(--page-selector-spacing);
+ }
+
+ #divider {
+ margin: 0 var(--page-selector-spacing);
}
</style>
<cr-input id="pageselector" value="[[pageNo]]" on-mouseup="select"
on-value-changed="onInputValueChange_" on-change="pageNoCommitted"
- aria-label$="{{strings.labelPageNumber}}">
+ aria-label$="$i18n{labelPageNumber}">
</cr-input>
- /
- <span id="pagelength">{{docLength}}</span>
+ <span id="divider">/</span>
+ <span id="pagelength">[[docLength]]</span>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector.js b/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector.js
index 5eda31ee514..6b8b55ad3dc 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-page-selector.js
@@ -26,8 +26,6 @@ Polymer({
type: Number,
value: 1,
},
-
- strings: Object,
},
/** @return {!CrInputElement} */
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen.html b/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen.html
index 43c0249bffa..b61cdb5434a 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen.html
@@ -4,20 +4,19 @@
}
</style>
<cr-dialog id="dialog" no-cancel>
- <div slot="title">[[strings.passwordDialogTitle]]</div>
+ <div slot="title">$i18n{passwordDialogTitle}</div>
<div slot="body">
- <div id="message">[[strings.passwordPrompt]]</div>
+ <div id="message">$i18n{passwordPrompt}</div>
<cr-input id="password"
type="password"
- error-message="[[getErrorMessage_(strings.passwordInvalid,
- invalid)]]"
+ error-message="[[getErrorMessage_(invalid)]]"
invalid="[[invalid]]"
autofocus>
</cr-input>
</div>
<div slot="button-container">
<cr-button id="submit" class="action-button" on-click="submit">
- [[strings.passwordSubmit]]
+ $i18n{passwordSubmit}
</cr-button>
</div>
</cr-dialog>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen.js b/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen.js
index 79cd849c56b..7bc4507d700 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-password-screen.js
@@ -8,6 +8,7 @@ import 'chrome://resources/cr_elements/cr_input/cr_input.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
+import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
Polymer({
@@ -17,8 +18,6 @@ Polymer({
properties: {
invalid: Boolean,
-
- strings: Object,
},
get active() {
@@ -57,10 +56,9 @@ Polymer({
* Returns |message| if input is invalid, otherwise empty string.
* This avoids setting the error message (which announces to screen readers)
* when there is no error.
- * @param {string} message
* @return {string}
*/
- getErrorMessage_(message) {
- return this.invalid ? message : '';
+ getErrorMessage_() {
+ return this.invalid ? loadTimeData.getString('passwordInvalid') : '';
}
});
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.html b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.html
new file mode 100644
index 00000000000..075635defbb
--- /dev/null
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.html
@@ -0,0 +1,10 @@
+<style>
+ :host {
+ --pdf-toolbar-background-color: rgb(50, 54, 57);
+ background-color: var(--pdf-toolbar-background-color);
+ box-shadow: var(--cr-elevation-2);
+ color: white;
+ height: 48px;
+ }
+</style>
+New PDF Viewer toolbar will appear here.
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.js b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.js
new file mode 100644
index 00000000000..06e1d118df0
--- /dev/null
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar-new.js
@@ -0,0 +1,17 @@
+// Copyright 2020 The Chromium 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 {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+class ViewerPdfToolbarNewElement extends PolymerElement {
+ static get is() {
+ return 'viewer-pdf-toolbar-new';
+ }
+
+ static get template() {
+ return html`{__html_template__}`;
+ }
+}
+customElements.define(
+ ViewerPdfToolbarNewElement.is, ViewerPdfToolbarNewElement);
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar.html b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar.html
index 6a8daca8ea7..51c7bc66cb5 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar.html
@@ -1,4 +1,9 @@
<style include="cr-hidden-style">
+ :host {
+ --pdf-toolbar-background-color: rgb(50, 54, 57);
+ --pdf-toolbar-text-color: rgb(241, 241, 241);
+ }
+
:host ::selection {
background: rgba(255, 255, 255, 0.3);
}
@@ -36,7 +41,7 @@
}
cr-icon-button {
- --cr-icon-button-fill-color: rgb(241, 241, 241);
+ --cr-icon-button-fill-color: var(--pdf-toolbar-text-color);
margin: 6px;
}
@@ -54,8 +59,8 @@
}
#toolbar {
- @apply --shadow-elevation-2dp;
- background-color: rgb(50, 54, 57);
+ background-color: var(--pdf-toolbar-background-color);
+ box-shadow: var(--cr-elevation-2);
position: relative;
}
@@ -67,7 +72,7 @@
#toolbar,
#annotations-bar {
- color: rgb(241, 241, 241);
+ color: var(--pdf-toolbar-text-color);
display: flex;
height: 48px;
padding: 0 16px;
@@ -90,7 +95,7 @@
#pen,
#highlighter {
- --dropdown-open-background: rgb(50, 54, 57);
+ --dropdown-open-background: var(--pdf-viewer-background-color);
}
#eraser {
@@ -138,10 +143,6 @@
#rotate-left {
display: none;
}
-
- #pageselector-container {
- flex: 2;
- }
}
@media(max-width: 450px) {
@@ -156,40 +157,55 @@
display: none;
}
}
+
+ cr-action-menu::part(dialog) {
+ position: fixed;
+ top: 48px;
+ }
</style>
<div id="toolbar">
<div id="aligner">
- <span id="title" title="{{docTitle}}">
- <span>{{docTitle}}</span>
+ <span id="title" title="[[docTitle]]">
+ <span>[[docTitle]]</span>
</span>
<div id="pageselector-container">
<viewer-page-selector id="pageselector" class="invisible"
- doc-length="{{docLength}}" page-no="{{pageNo}}"
- strings="{{strings}}">
+ doc-length="[[docLength]]" page-no="[[pageNo]]">
</viewer-page-selector>
</div>
<div id="buttons" class="invisible">
- <template is="dom-if" if="[[pdfAnnotationsEnabled]]">
+<if expr="chromeos">
+ <template is="dom-if" if="[[pdfAnnotationsEnabled_]]">
<cr-icon-button id="annotate" iron-icon="pdf:create"
disabled="[[!annotationAvailable]]" on-click="toggleAnnotation"
- aria-label$="{{strings.tooltipAnnotate}}"
- title$="{{strings.tooltipAnnotate}}"></cr-icon-button>
+ aria-label$="$i18n{tooltipAnnotate}"
+ title="$i18n{tooltipAnnotate}"></cr-icon-button>
</template>
+</if>
<cr-icon-button id="rotate-right" iron-icon="pdf:rotate-right"
disabled="[[annotationMode]]" on-click="rotateRight"
- aria-label$="{{strings.tooltipRotateCW}}"
- title$="{{strings.tooltipRotateCW}}"></cr-icon-button>
+ aria-label$="$i18n{tooltipRotateCW}"
+ title="$i18n{tooltipRotateCW}"></cr-icon-button>
<cr-icon-button id="download" iron-icon="cr:file-download"
- on-click="download" aria-label$="{{strings.tooltipDownload}}"
- title$="{{strings.tooltipDownload}}"></cr-icon-button>
+ on-click="onDownloadClick_" aria-label$="$i18n{tooltipDownload}"
+ aria-haspopup$="[[downloadHasPopup_]]"
+ title="$i18n{tooltipDownload}"></cr-icon-button>
+ <cr-action-menu id="downloadMenu">
+ <button class="dropdown-item" on-click="onDownloadEditedClick_">
+ $i18n{downloadEdited}
+ </button>
+ <button class="dropdown-item" on-click="onDownloadOriginalClick_">
+ $i18n{downloadOriginal}
+ </button>
+ </cr-action-menu>
<cr-icon-button id="print" iron-icon="cr:print" on-click="print"
- hidden="[[!printingEnabled]]" title$="{{strings.tooltipPrint}}"
- aria-label$="{{strings.tooltipPrint}}"></cr-icon-button>
+ hidden="[[!printingEnabled_]]" title="$i18n{tooltipPrint}"
+ aria-label$="$i18n{tooltipPrint}"></cr-icon-button>
<viewer-toolbar-dropdown id="bookmarks"
selected
@@ -197,7 +213,7 @@
hidden$="[[!bookmarks.length]]"
open-icon="pdf:bookmark"
closed-icon="pdf:bookmark-border"
- header="{{strings.bookmarks}}">
+ header="$i18n{bookmarks}">
<template is="dom-repeat" items="[[bookmarks]]">
<viewer-bookmark bookmark="[[item]]" depth="0"></viewer-bookmark>
</template>
@@ -211,6 +227,7 @@
</div>
</div>
+<if expr="chromeos">
<div id="annotations-bar" hidden>
<viewer-toolbar-dropdown id="pen"
selected$="[[isAnnotationTool_('pen', annotationTool.tool)]]"
@@ -220,7 +237,7 @@
closed-icon="pdf:marker"
dropdown-centered
hide-header
- header$="{{strings.annotationPen}}"
+ header="$i18n{annotationPen}"
style="--pen-tip-fill: #000000">
<viewer-pen-options
selected-color="#000000"
@@ -239,7 +256,7 @@
closed-icon="pdf:highlighter"
dropdown-centered
hide-header
- header$="{{strings.annotationHighlighter}}"
+ header="$i18n{annotationHighlighter}"
style="--pen-tip-fill: #ffbc00">
<viewer-pen-options
selected-color="#ffbc00"
@@ -253,18 +270,19 @@
<cr-icon-button id="eraser"
selected$="[[isAnnotationTool_('eraser', annotationTool.tool)]]"
on-click="annotationToolClicked_" iron-icon="pdf:eraser"
- aria-label$="{{strings.annotationEraser}}"
- title$="{{strings.annotationEraser}}"></cr-icon-button>
+ aria-label$="$i18n{annotationEraser}"
+ title="$i18n{annotationEraser}"></cr-icon-button>
<div id="annotation-separator"></div>
<cr-icon-button id="undo" disabled="[[!canUndoAnnotation]]"
iron-icon="pdf:undo" on-click="undo"
- aria-label$="{{strings.annotationUndo}}"
- title$="{{strings.annotationUndo}}"></cr-icon-button>
+ aria-label$="$i18n{annotationUndo}"
+ title="$i18n{annotationUndo}"></cr-icon-button>
<cr-icon-button id="redo" disabled="[[!canRedoAnnotation]]"
iron-icon="pdf:redo" on-click="redo"
- aria-label$="{{strings.annotationRedo}}"
- title$="{{strings.annotationRedo}}"></cr-icon-button>
+ aria-label$="$i18n{annotationRedo}"
+ title="$i18n{annotationRedo}"></cr-icon-button>
</div>
+</if>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar.js b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar.js
index 9fb821a0ac4..defc20f57bb 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar.js
@@ -10,13 +10,19 @@ import './icons.js';
import './viewer-bookmark.js';
import './viewer-page-selector.js';
import './viewer-toolbar-dropdown.js';
-
// <if expr="chromeos">
import './viewer-pen-options.js';
+
// </if>
+import {AnchorAlignment} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.m.js';
+import {assert} from 'chrome://resources/js/assert.m.js';
+import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
+import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js';
import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
import {Bookmark} from '../bookmark_type.js';
+import {SaveRequestType} from '../constants.js';
Polymer({
is: 'viewer-pdf-toolbar',
@@ -29,10 +35,7 @@ Polymer({
* example the PDF is encrypted or password protected. Note, this is
* true regardless of whether the feature flag is enabled.
*/
- annotationAvailable: {
- type: Boolean,
- value: true,
- },
+ annotationAvailable: Boolean,
/** Whether the viewer is currently in annotation mode. */
annotationMode: {
@@ -45,7 +48,6 @@ Polymer({
/** @type {?AnnotationTool} */
annotationTool: {
type: Object,
- value: null,
notify: true,
},
@@ -74,6 +76,15 @@ Polymer({
/** The title of the PDF document. */
docTitle: String,
+ hasEdits: Boolean,
+
+ hasEnteredAnnotationMode: Boolean,
+
+ isFormFieldFocused: {
+ type: Boolean,
+ observer: 'onFormFieldFocusedChanged_',
+ },
+
/** The current loading progress of the PDF document (0 - 100). */
loadProgress: {
type: Number,
@@ -89,24 +100,52 @@ Polymer({
/** The number of the page being viewed (1-based). */
pageNo: Number,
- /** Whether the PDF Annotations feature is enabled. */
- pdfAnnotationsEnabled: {
+ /**
+ * Whether the PDF Annotations feature is enabled.
+ * @private
+ */
+ pdfAnnotationsEnabled_: {
type: Boolean,
value: false,
},
- /** Whether the Printing feature is enabled. */
- printingEnabled: {
+ /**
+ * Whether the Printing feature is enabled.
+ * @private
+ */
+ printingEnabled_: {
type: Boolean,
value: false,
},
- strings: Object,
+ /** @private */
+ downloadHasPopup_: {
+ type: String,
+ computed: 'computeDownloadHasPopup_(' +
+ 'pdfFormSaveEnabled_, hasEdits, hasEnteredAnnotationMode)',
+ },
+
+ strings: {
+ type: Object,
+ observer: 'onStringsSet_',
+ },
+
+ /**
+ * Whether the PDF Form save feature is enabled.
+ * @private
+ */
+ pdfFormSaveEnabled_: {
+ type: Boolean,
+ value: false,
+ },
},
/** @type {?Object} */
animation_: null,
+ /** @private {?PromiseResolver<boolean>} */
+ waitForFormFocusChange_: null,
+
/**
* @param {number} newProgress
* @param {number} oldProgress
@@ -119,7 +158,9 @@ Polymer({
this.$.pageselector.classList.toggle('invisible', !loaded);
this.$.buttons.classList.toggle('invisible', !loaded);
this.$.progress.style.opacity = loaded ? 0 : 1;
+ // <if expr="chromeos">
this.$['annotations-bar'].hidden = !loaded || !this.annotationMode;
+ // </if>
}
},
@@ -168,7 +209,8 @@ Polymer({
/** @return {boolean} Whether the toolbar should be kept open. */
shouldKeepOpen() {
return this.$.bookmarks.dropdownOpen || this.loadProgress < 100 ||
- this.$.pageselector.isActive() || this.annotationMode;
+ this.$.pageselector.isActive() || this.annotationMode ||
+ this.$.downloadMenu.open;
},
/** @return {boolean} Whether a dropdown was open and was hidden. */
@@ -178,6 +220,7 @@ Polymer({
this.$.bookmarks.toggleDropdown();
result = true;
}
+ // <if expr="chromeos">
if (this.$.pen.dropdownOpen) {
this.$.pen.toggleDropdown();
result = true;
@@ -186,6 +229,7 @@ Polymer({
this.$.highlighter.toggleDropdown();
result = true;
}
+ // </if>
return result;
},
@@ -198,8 +242,67 @@ Polymer({
this.fire('rotate-right');
},
- download() {
- this.fire('save');
+ /** @private */
+ showDownloadMenu_() {
+ this.$.downloadMenu.showAt(this.$.download, {
+ anchorAlignmentX: AnchorAlignment.CENTER,
+ anchorAlignmentY: AnchorAlignment.AFTER_END,
+ noOffset: true,
+ });
+ // For tests
+ this.fire('download-menu-shown-for-testing');
+ },
+
+ /** @private */
+ onDownloadClick_() {
+ this.waitForEdits_().then(hasEdits => {
+ if (hasEdits) {
+ this.showDownloadMenu_();
+ } else {
+ this.fire('save', SaveRequestType.ORIGINAL);
+ }
+ });
+ },
+
+ /**
+ * @return {!Promise<boolean>} Promise that resolves with true if the PDF has
+ * edits and/or annotations, and false otherwise.
+ * @private
+ */
+ waitForEdits_() {
+ if (this.hasEditsToSave_()) {
+ return Promise.resolve(true);
+ }
+ if (!this.isFormFieldFocused || !this.pdfFormSaveEnabled_) {
+ return Promise.resolve(false);
+ }
+ this.waitForFormFocusChange_ = new PromiseResolver();
+ return this.waitForFormFocusChange_.promise;
+ },
+
+ /** @private */
+ onFormFieldFocusedChanged_() {
+ if (!this.waitForFormFocusChange_) {
+ return;
+ }
+
+ this.waitForFormFocusChange_.resolve(this.hasEdits);
+ this.waitForFormFocusChange_ = null;
+ },
+
+ /** @private */
+ onDownloadOriginalClick_() {
+ this.fire('save', SaveRequestType.ORIGINAL);
+ this.$.downloadMenu.close();
+ },
+
+ /** @private */
+ onDownloadEditedClick_() {
+ this.fire(
+ 'save',
+ this.hasEnteredAnnotationMode ? SaveRequestType.ANNOTATION :
+ SaveRequestType.EDITED);
+ this.$.downloadMenu.close();
},
print() {
@@ -255,7 +358,7 @@ Polymer({
const tool = element.id;
const options = element.querySelector('viewer-pen-options') || {
selectedSize: 1,
- selectedColor: null,
+ selectedColor: undefined,
};
const attributeStyleMap = element.attributeStyleMap;
attributeStyleMap.set('--pen-tip-fill', options.selectedColor);
@@ -278,4 +381,32 @@ Polymer({
isAnnotationTool_(toolName) {
return !!this.annotationTool && this.annotationTool.tool === toolName;
},
+
+ /**
+ * @return {boolean}
+ * @private
+ */
+ hasEditsToSave_() {
+ return this.hasEnteredAnnotationMode ||
+ (this.pdfFormSaveEnabled_ && this.hasEdits);
+ },
+
+ /**
+ * @return {string} The value for the aria-haspopup attribute for the download
+ * button.
+ * @private
+ */
+ computeDownloadHasPopup_() {
+ return this.hasEditsToSave_() ? 'menu' : 'false';
+ },
+
+ /** @private */
+ onStringsSet_() {
+ assert(this.strings);
+
+ this.pdfAnnotationsEnabled_ =
+ loadTimeData.getBoolean('pdfAnnotationsEnabled');
+ this.pdfFormSaveEnabled_ = loadTimeData.getBoolean('pdfFormSaveEnabled');
+ this.printingEnabled_ = loadTimeData.getBoolean('printingEnabled');
+ },
});
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-pen-options.html b/chromium/chrome/browser/resources/pdf/elements/viewer-pen-options.html
index b44bf89f9c9..e98c1c20513 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-pen-options.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-pen-options.html
@@ -65,8 +65,8 @@
on-pointerdown="blurOnPointerDown">
</template>
<cr-icon-button id="expand" iron-icon="cr:expand-more" tabindex="3"
- on-click="toggleExpanded_" aria-label$="[[strings.annotationExpand]]"
- title$="[[strings.annotationExpand]]"></cr-icon-button>
+ on-click="toggleExpanded_" aria-label$="$i18n{annotationExpand}"
+ title$="$i18n{annotationExpand}"></cr-icon-button>
</div>
<div id="separator"></div>
<div id="sizes" on-change="sizeChanged_">
@@ -74,7 +74,7 @@
<input type="radio" name="size" value="[[item.size]]"
checked$="[[equal_(selectedSize, item.size)]]"
tabindex="2" style="--item-size: [[item.size]]"
- title$="{{lookup_(strings, item.name)}}"
+ title="[[lookup_(strings, item.name)]]"
aria-label$="[[lookup_(strings, item.name)]]"
on-pointerdown="blurOnPointerDown">
</template>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-pen-options.js b/chromium/chrome/browser/resources/pdf/elements/viewer-pen-options.js
index 0cc12c94384..fd7e6e8661d 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-pen-options.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-pen-options.js
@@ -52,50 +52,62 @@ const sizes = [
{name: 'annotationSize20', size: 1},
];
-/**
- * Displays a set of radio buttons to select from
- * a predefined list of colors and sizes.
- */
+// Displays a set of radio buttons to select from a predefined list of colors
+// and sizes.
Polymer({
is: 'viewer-pen-options',
_template: html`{__html_template__}`,
properties: {
+ /** @private */
expanded_: {
type: Boolean,
value: false,
},
+
selectedSize: {
type: Number,
value: 0.250,
notify: true,
},
+
selectedColor: {
type: String,
value: '#000000',
notify: true,
},
+
+ /** @private */
sizes_: {
type: Array,
value: sizes,
},
+
+ /** @private */
colors_: {
type: Array,
value: colors,
},
+
strings: Object,
},
- /** @type {Array<!Animation>} */
+ /** @private {Array<!Animation>} */
expandAnimations_: null,
- /** @param {Event} e */
+ /**
+ * @param {!Event} e
+ * @private
+ */
sizeChanged_(e) {
this.selectedSize = Number(e.target.value);
},
- /** @param {Event} e */
+ /**
+ * @param {!Event} e
+ * @private
+ */
colorChanged_(e) {
this.selectedColor = e.target.value;
},
@@ -125,6 +137,7 @@ Polymer({
/**
* Updates the state of the UI to reflect the current value of `expanded`.
* Starts or reverses animations and enables/disable controls.
+ * @private
*/
updateExpandedState_() {
const colors = this.$.colors;
@@ -176,19 +189,16 @@ Polymer({
animation.play();
}
for (const input of colors.querySelectorAll('input:nth-child(n+8)')) {
- if (this.expanded_) {
- input.removeAttribute('disabled');
- } else {
- input.setAttribute('disabled', '');
- }
+ input.toggleAttribute('disabled', !this.expanded_);
}
},
/**
* Used to determine equality in computed bindings.
- *
* @param {*} a
* @param {*} b
+ * @return {boolean} Whether a === b
+ * @private
*/
equal_(a, b) {
return a === b;
@@ -196,10 +206,10 @@ Polymer({
/**
* Used to lookup a string in a computed binding.
- *
* @param {Object} strings
* @param {string} name
* @return {string}
+ * @private
*/
lookup_(strings, name) {
return strings ? strings[name] : '';
@@ -209,6 +219,7 @@ Polymer({
* Used to remove focus when clicking or tapping on a styled input
* element. This is a workaround until we can use the :focus-visible
* pseudo selector.
+ * @param {!Event} e
*/
blurOnPointerDown(e) {
const target = e.target;
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown.html b/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown.html
index 8c6e7640bde..ff49695f629 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown.html
@@ -27,23 +27,17 @@
#dropdown {
background-color: var(--cr-menu-background-color);
border-radius: 4px;
+ box-shadow: var(--cr-menu-shadow);
color: var(--cr-primary-text-color);
overflow-y: hidden;
padding-bottom: 2px;
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);
}
}
@@ -89,7 +83,7 @@
<div id="container">
<div id="dropdown" style="display: none">
<template is="dom-if" if="[[!hideHeader]]">
- <h1>{{header}}</h1>
+ <h1>[[header]]</h1>
</template>
<div id="scroll-container">
<slot></slot>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-button.html b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-button.html
index f51075c5cab..ad97fce8a23 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-button.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-button.html
@@ -35,11 +35,10 @@
--cr-icon-button-fill-color: var(--paper-grey-700);
--cr-icon-button-icon-size: 20px;
--cr-icon-button-size: 36px;
- --cr-icon-button-fill-color-focus: rgb(242, 242, 242);
background-color: rgb(242, 242, 242);
border-radius: 50%;
+ box-shadow: var(--cr-elevation-1);
overflow: visible;
- @apply --shadow-elevation-2dp;
}
cr-icon-button([disabled]) {
@@ -48,7 +47,6 @@
:host-context([is-print-preview]) cr-icon-button {
--cr-icon-button-fill-color: white;
- --cr-icon-button-fill-color-focus: var(--google-grey-600);
--cr-icon-button-size: 32px;
background-color: var(--google-grey-600);
}
@@ -62,17 +60,16 @@
@media (prefers-color-scheme: dark) {
:host-context([is-print-preview]) cr-icon-button {
--cr-icon-button-fill-color: var(--google-grey-200);
- --cr-icon-button-fill-color-focus: var(--google-grey-900);
background-color: var(--google-grey-900);
}
}
:host([keyboard-navigation-active]) cr-icon-button:focus {
- @apply --shadow-elevation-6dp;
+ box-shadow: var(--cr-elevation-4);
}
cr-icon-button:active {
- @apply --shadow-elevation-8dp;
+ box-shadow: var(--cr-elevation-5);
}
</style>
<div id="wrapper">
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar.html b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar.html
index ab6a4d461ca..341f6bbf4c7 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar.html
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar.html
@@ -67,7 +67,7 @@
<!-- TODO(crbug.com/51472): Change icons for two-up-view-button -->
<!-- once they are finalized. -->
<viewer-zoom-button id="two-up-view-button" delay="100"
- disabled="[[annotationMode]]" hidden$="[[!twoUpViewEnabled]]"
+ disabled="[[annotationMode]]" hidden$="[[!twoUpViewEnabled_]]"
on-fabclick="twoUpViewToggle_"
keyboard-navigation-active="[[keyboardNavigationActive_]]"
icons="pdf:create pdf:eraser"></viewer-zoom-button>
diff --git a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar.js b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar.js
index d58712f7562..f3bab8c69e1 100644
--- a/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar.js
+++ b/chromium/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar.js
@@ -8,7 +8,9 @@ import './icons.js';
import './viewer-zoom-button.js';
import {assert} from 'chrome://resources/js/assert.m.js';
+import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
import {FittingType, TwoUpViewAction} from '../constants.js';
/**
@@ -32,19 +34,25 @@ Polymer({
properties: {
/** Whether the viewer is currently in annotation mode. */
- annotationMode: {
+ annotationMode: Boolean,
+
+ isPrintPreview: {
type: Boolean,
value: false,
},
- isPrintPreview: Boolean,
+ strings: {
+ type: Object,
+ observer: 'onStringsSet_',
+ },
- twoUpViewEnabled: Boolean,
+ /** @private */
+ twoUpViewEnabled_: Boolean,
/** @private */
fitButtonDelay_: {
type: Number,
- computed: 'computeFitButtonDelay_(twoUpViewEnabled)',
+ computed: 'computeFitButtonDelay_(twoUpViewEnabled_)',
},
/** @private */
@@ -55,12 +63,11 @@ Polymer({
},
/**
- * @param {boolean} twoUpViewEnabled Whether two-up view button is enabled.
- * @return {number} Delay for :qthe fit button.
+ * @return {number} Delay for the fit button.
* @private
*/
- computeFitButtonDelay_(twoUpViewEnabled) {
- return twoUpViewEnabled ? 150 : 100;
+ computeFitButtonDelay_() {
+ return this.twoUpViewEnabled_ ? 150 : 100;
},
listeners: {
@@ -106,20 +113,27 @@ Polymer({
/**
* Change button tooltips to match any changes to localized strings.
- * @param {!{tooltipFitToPage: string,
- * tooltipFitToWidth: string,
- * tooltipTwoUpViewEnable: string,
- * tooltipTwoUpViewDisable: string,
- * tooltipZoomIn: string,
- * tooltipZoomOut: string}} strings
+ * @private
*/
- setStrings(strings) {
+ onStringsSet_() {
+ const strings =
+ /**
+ * @type {{tooltipFitToPage: string,
+ * tooltipFitToWidth: string,
+ * tooltipTwoUpViewEnable: string,
+ * tooltipTwoUpViewDisable: string,
+ * tooltipZoomIn: string,
+ * tooltipZoomOut: string}}
+ */
+ (this.strings);
this.$['fit-button'].tooltips =
[strings.tooltipFitToPage, strings.tooltipFitToWidth];
this.$['two-up-view-button'].tooltips =
[strings.tooltipTwoUpViewEnable, strings.tooltipTwoUpViewDisable];
this.$['zoom-in-button'].tooltips = [strings.tooltipZoomIn];
this.$['zoom-out-button'].tooltips = [strings.tooltipZoomOut];
+ this.twoUpViewEnabled_ =
+ loadTimeData.getBoolean('pdfTwoUpViewEnabled') && !this.isPrintPreview;
},
/** Handle clicks of the fit-button. */
@@ -175,7 +189,7 @@ Polymer({
* @private
*/
twoUpViewToggle_: function() {
- assert(this.twoUpViewEnabled);
+ assert(this.twoUpViewEnabled_);
const twoUpViewAction = this.$['two-up-view-button'].activeIndex ===
TWO_UP_VIEW_DISABLED_STATE ?
TwoUpViewAction.TWO_UP_VIEW_ENABLE :
@@ -184,16 +198,12 @@ Polymer({
this.fire('two-up-view-changed', twoUpViewAction);
},
- /**
- * Handle clicks of the zoom-in-button.
- */
+ /** Handle clicks of the zoom-in-button. */
zoomIn() {
this.fire('zoom-in');
},
- /**
- * Handle clicks of the zoom-out-button.
- */
+ /** Handle clicks of the zoom-out-button. */
zoomOut() {
this.fire('zoom-out');
},
diff --git a/chromium/chrome/browser/resources/pdf/gesture_detector.js b/chromium/chrome/browser/resources/pdf/gesture_detector.js
index e8a0db4e6a3..6755d76b9b0 100644
--- a/chromium/chrome/browser/resources/pdf/gesture_detector.js
+++ b/chromium/chrome/browser/resources/pdf/gesture_detector.js
@@ -2,34 +2,43 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+import {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_target.m.js';
+
/**
- * A class that listens for touch events and produces events when these
- * touches form gestures (e.g. pinching).
+ * @typedef {{
+ * center: !{x: number, y: number},
+ * direction: (string|undefined),
+ * scaleRatio: (?number|undefined),
+ * startScaleRatio: (?number|undefined),
+ * }}
*/
+export let PinchEventDetail;
+
+// A class that listens for touch events and produces events when these
+// touches form gestures (e.g. pinching).
export class GestureDetector {
/**
- * @param {!Element} element The element to monitor for touch gestures.
+ * @param {!EventTarget|!Element} element The element to monitor for touch
+ * gestures.
*/
constructor(element) {
- /** @private {!Element} */
- this.element_ = element;
-
- this.element_.addEventListener(
+ element.addEventListener(
'touchstart',
/** @type {function(!Event)} */ (this.onTouchStart_.bind(this)),
{passive: true});
const boundOnTouch =
/** @type {function(!Event)} */ (this.onTouch_.bind(this));
- this.element_.addEventListener('touchmove', boundOnTouch, {passive: true});
- this.element_.addEventListener('touchend', boundOnTouch, {passive: true});
- this.element_.addEventListener(
- 'touchcancel', boundOnTouch, {passive: true});
+ element.addEventListener('touchmove', boundOnTouch, {passive: true});
+ element.addEventListener('touchend', boundOnTouch, {passive: true});
+ element.addEventListener('touchcancel', boundOnTouch, {passive: true});
- this.element_.addEventListener(
+ element.addEventListener(
'wheel',
/** @type {function(!Event)} */ (this.onWheel_.bind(this)),
{passive: false});
+ document.addEventListener(
+ 'contextmenu', e => this.handleContextMenuEvent_(e));
this.pinchStartEvent_ = null;
this.lastTouchTouchesCount_ = 0;
@@ -52,24 +61,17 @@ export class GestureDetector {
*/
this.wheelEndTimeout_ = null;
- /** @private {!Map<string, !Array<!Function>>} */
- this.listeners_ =
- new Map([['pinchstart', []], ['pinchupdate', []], ['pinchend', []]]);
+ /** @private {!EventTarget} */
+ this.eventTarget_ = new EventTarget();
}
- /**
- * Add a |listener| to be notified of |type| events.
- *
- * @param {string} type The event type to be notified for.
- * @param {!Function} listener The callback.
- */
- addEventListener(type, listener) {
- if (this.listeners_.has(type)) {
- this.listeners_.get(type).push(listener);
- }
+ /** @return {!EventTarget} */
+ getEventTarget() {
+ return this.eventTarget_;
}
/**
+ * Public for tests.
* @return {boolean} True if the last touch start was a two finger touch.
*/
wasTwoFingerTouch() {
@@ -77,22 +79,17 @@ export class GestureDetector {
}
/**
- * Call the relevant listeners with the given |pinchEvent|.
- *
- * @param {!Object} pinchEvent The event to notify the listeners of.
+ * Call the relevant listeners with the given |PinchEventDetail|.
+ * @param {string} type The type of pinch event.
+ * @param {!PinchEventDetail} detail The event to notify the listeners of.
* @private
*/
- notify_(pinchEvent) {
- const listeners = this.listeners_.get(pinchEvent.type);
-
- for (const l of listeners) {
- l(pinchEvent);
- }
+ notify_(type, detail) {
+ this.eventTarget_.dispatchEvent(new CustomEvent(type, {detail}));
}
/**
* The callback for touchstart events on the element.
- *
* @param {!TouchEvent} event Touch event on the element.
* @private
*/
@@ -104,12 +101,11 @@ export class GestureDetector {
this.pinchStartEvent_ = event;
this.lastEvent_ = event;
- this.notify_({type: 'pinchstart', center: GestureDetector.center_(event)});
+ this.notify_('pinchstart', {center: GestureDetector.center_(event)});
}
/**
* The callback for touch move, end, and cancel events on the element.
- *
* @param {!TouchEvent} event Touch event on the element.
* @private
*/
@@ -126,14 +122,12 @@ export class GestureDetector {
const startScaleRatio =
GestureDetector.pinchScaleRatio_(lastEvent, this.pinchStartEvent_);
const center = GestureDetector.center_(lastEvent);
- const endEvent = {
- type: 'pinchend',
- startScaleRatio: startScaleRatio,
- center: center
- };
this.pinchStartEvent_ = null;
this.lastEvent_ = null;
- this.notify_(endEvent);
+ this.notify_('pinchend', {
+ startScaleRatio: startScaleRatio,
+ center: center,
+ });
return;
}
@@ -141,12 +135,11 @@ export class GestureDetector {
const startScaleRatio =
GestureDetector.pinchScaleRatio_(event, this.pinchStartEvent_);
const center = GestureDetector.center_(event);
- this.notify_({
- type: 'pinchupdate',
+ this.notify_('pinchupdate', {
scaleRatio: scaleRatio,
direction: scaleRatio > 1.0 ? 'in' : 'out',
startScaleRatio: startScaleRatio,
- center: center
+ center: center,
});
this.lastEvent_ = event;
@@ -154,7 +147,6 @@ export class GestureDetector {
/**
* The callback for wheel events on the element.
- *
* @param {!WheelEvent} event Wheel event on the element.
* @private
*/
@@ -179,16 +171,15 @@ export class GestureDetector {
if (this.accumulatedWheelScale_ == null) {
this.accumulatedWheelScale_ = 1.0;
- this.notify_({type: 'pinchstart', center: position});
+ this.notify_('pinchstart', {center: position});
}
this.accumulatedWheelScale_ *= scale;
- this.notify_({
- type: 'pinchupdate',
+ this.notify_('pinchupdate', {
scaleRatio: scale,
direction: scale > 1.0 ? 'in' : 'out',
startScaleRatio: this.accumulatedWheelScale_,
- center: position
+ center: position,
});
// We don't get any phase information for the ctrl-wheels, so we don't know
@@ -200,21 +191,35 @@ export class GestureDetector {
}
const gestureEndDelayMs = 100;
const endEvent = {
- type: 'pinchend',
startScaleRatio: this.accumulatedWheelScale_,
- center: position
+ center: position,
};
- this.wheelEndTimeout_ = window.setTimeout(function(endEvent) {
- this.notify_(endEvent);
+ this.wheelEndTimeout_ = window.setTimeout(() => {
+ this.notify_('pinchend', endEvent);
this.wheelEndTimeout_ = null;
this.accumulatedWheelScale_ = null;
- }.bind(this), gestureEndDelayMs, endEvent);
+ }, gestureEndDelayMs);
+ }
+
+ /**
+ * @param {!Event} e The context menu event
+ * @private
+ */
+ handleContextMenuEvent_(e) {
+ // Stop Chrome from popping up the context menu on long press. We need to
+ // make sure the start event did not have 2 touches because we don't want
+ // to block two finger tap opening the context menu. We check for
+ // firesTouchEvents in order to not block the context menu on right click.
+ const capabilities =
+ /** @type {{ sourceCapabilities: Object }} */ (e).sourceCapabilities;
+ if (capabilities.firesTouchEvents && !this.wasTwoFingerTouch()) {
+ e.preventDefault();
+ }
}
/**
* Computes the change in scale between this touch event
* and a previous one.
- *
* @param {!TouchEvent} event Latest touch event on the element.
* @param {!TouchEvent} prevEvent A previous touch event on the element.
* @return {?number} The ratio of the scale of this event and the
@@ -229,7 +234,6 @@ export class GestureDetector {
/**
* Computes the distance between fingers.
- *
* @param {!TouchEvent} event Touch event with at least 2 touch points.
* @return {number} Distance between touch[0] and touch[1].
* @private
@@ -244,9 +248,8 @@ export class GestureDetector {
/**
* Computes the midpoint between fingers.
- *
* @param {!TouchEvent} event Touch event with at least 2 touch points.
- * @return {!Object} Midpoint between touch[0] and touch[1].
+ * @return {!{x: number, y: number}} Midpoint between touch[0] and touch[1].
* @private
*/
static center_(event) {
diff --git a/chromium/chrome/browser/resources/pdf/index.css b/chromium/chrome/browser/resources/pdf/index.css
index 1f6605930ec..20fd3b62cda 100644
--- a/chromium/chrome/browser/resources/pdf/index.css
+++ b/chromium/chrome/browser/resources/pdf/index.css
@@ -13,53 +13,3 @@ body {
line-height: 154%;
margin: 0;
}
-
-viewer-page-indicator {
- opacity: 0;
- visibility: hidden;
- z-index: 2;
-}
-
-viewer-pdf-toolbar {
- position: fixed;
- width: 100%;
- z-index: 4;
-}
-
-#content {
- height: 100%;
- position: fixed;
- width: 100%;
- z-index: 1;
-}
-
-
-viewer-ink-host,
-#plugin {
- height: 100%;
- position: absolute;
- width: 100%;
-}
-
-#sizer {
- position: absolute;
- z-index: 0;
-}
-
-@media(max-height: 250px) {
- viewer-pdf-toolbar {
- display: none;
- }
-}
-
-@media(max-height: 200px) {
- viewer-zoom-toolbar {
- display: none;
- }
-}
-
-@media(max-width: 300px) {
- viewer-zoom-toolbar {
- display: none;
- }
-}
diff --git a/chromium/chrome/browser/resources/pdf/index.html b/chromium/chrome/browser/resources/pdf/index.html
index 6a78136126d..bce88410976 100644
--- a/chromium/chrome/browser/resources/pdf/index.html
+++ b/chromium/chrome/browser/resources/pdf/index.html
@@ -1,5 +1,6 @@
<!doctype html>
-<html $i18n{a11yenhanced}>
+<html dir="$i18n{textdirection}" lang="$i18n{language}"
+ $i18n{pdfViewerUpdateEnabledAttribute}>
<head>
<meta charset="utf-8">
@@ -7,22 +8,8 @@
<link rel="stylesheet" href="index.css">
</head>
<body>
-
-<viewer-pdf-toolbar id="toolbar" hidden></viewer-pdf-toolbar>
-
-<div id="sizer"></div>
-<viewer-password-screen id="password-screen"></viewer-password-screen>
-
-<viewer-zoom-toolbar id="zoom-toolbar" hidden></viewer-zoom-toolbar>
-
-<viewer-error-screen id="error-screen"></viewer-error-screen>
-
-<if expr="chromeos">
-<viewer-form-warning id="form-warning"></viewer-form-warning>
-</if>
-
-<div id="content"></div>
-
+<pdf-viewer id="viewer"></pdf-viewer>
</body>
<script type="module" src="main.js"></script>
+<script type="module" src="pdf_viewer.js"></script>
</html>
diff --git a/chromium/chrome/browser/resources/pdf/index_pp.html b/chromium/chrome/browser/resources/pdf/index_pp.html
index 5c44ada5d73..fd18cd50280 100644
--- a/chromium/chrome/browser/resources/pdf/index_pp.html
+++ b/chromium/chrome/browser/resources/pdf/index_pp.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html $i18n{a11yenhanced}>
+<html is-print-preview dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
<meta charset="utf-8">
@@ -7,16 +7,11 @@
<link rel="stylesheet" href="index.css">
</head>
<body>
-
-<div id="sizer"></div>
-<viewer-zoom-toolbar id="zoom-toolbar" hidden></viewer-zoom-toolbar>
-
-<viewer-page-indicator id="page-indicator"></viewer-page-indicator>
-
-<viewer-error-screen id="error-screen"></viewer-error-screen>
-
-<div id="content"></div>
-
+<pdf-viewer-pp id="viewer"></pdf-viewer-pp>
</body>
-<script type="module" src="main_pp.js"></script>
+<script type="module" src="main.js"></script>
+<!-- The line below refers to pdf_viewer_pp.js, which is served under the path
+ pdf_viewer.js so that the PDF viewer and Print Preview viewer can use the
+ same main.js source. main.js imports pdf_viewer.js. -->
+<script type="module" src="pdf_viewer.js"></script>
</html>
diff --git a/chromium/chrome/browser/resources/pdf/ink/externs.js b/chromium/chrome/browser/resources/pdf/ink/externs.js
deleted file mode 100644
index 8af66dfc91f..00000000000
--- a/chromium/chrome/browser/resources/pdf/ink/externs.js
+++ /dev/null
@@ -1,74 +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 We don't rely on any of these types but they are missing
- * from the Ink extern file currently and need to be defined somewhere.
- * @externs
- */
-
-var ink = {}; // eslint-disable-line no-var
-ink.proto.scene_change = {};
-
-/** @constructor */
-ink.proto.Snapshot = function() {};
-
-/** @constructor */
-ink.proto.Command = function() {};
-
-/** @constructor */
-ink.proto.MutationPacket = function() {};
-
-/** @constructor */
-ink.proto.SetCallbackFlags = function() {};
-
-/** @constructor */
-ink.proto.ToolEvent = function() {};
-
-/** @constructor */
-ink.Box = function() {};
-
-/** @constructor */
-ink.Model = function() {};
-
-/** @constructor */
-ink.ElementListener = function() {};
-
-/** @constructor */
-ink.proto.scene_change.SceneChangeEvent = function() {};
-
-const goog = {};
-goog.events = {};
-goog.disposable = {};
-goog.math = {};
-goog.ui = {};
-goog.html = {};
-goog.proto2 = {};
-
-/** @constructor */
-goog.events.EventTarget = function() {};
-
-/** @interface */
-goog.disposable.IDisposable = function() {};
-
-/** @interface */
-goog.events.Listenable = function() {};
-
-/** @constructor */
-goog.math.Size = function() {};
-
-/** @constructor */
-goog.events.Event = function() {};
-
-/** @constructor */
-goog.proto2.Message = function() {};
-
-/**
- * @extends {goog.events.EventTarget}
- * @constructor
- */
-goog.ui.Component = function() {};
-
-/** @constructor */
-goog.html.SafeUrl = function() {};
diff --git a/chromium/chrome/browser/resources/pdf/ink/index.html b/chromium/chrome/browser/resources/pdf/ink/index.html
index 61d5e7e077b..07f64d813e6 100644
--- a/chromium/chrome/browser/resources/pdf/ink/index.html
+++ b/chromium/chrome/browser/resources/pdf/ink/index.html
@@ -1,5 +1,5 @@
<!DOCTYPE html>
-<script src="glcore_wasm_bootstrap_compiled.js"></script>
+<script src="ink_loader.js"></script>
<script src="ink_lib_binary.js"></script>
<script src="ink_api.js"></script>
<style>
diff --git a/chromium/chrome/browser/resources/pdf/ink/ink_api.js b/chromium/chrome/browser/resources/pdf/ink/ink_api.js
index c394b630077..5d4a4d72a83 100644
--- a/chromium/chrome/browser/resources/pdf/ink/ink_api.js
+++ b/chromium/chrome/browser/resources/pdf/ink/ink_api.js
@@ -3,36 +3,19 @@
// found in the LICENSE file.
/**
- * @typedef {{
- * canUndo: boolean,
- * canRedo: boolean,
- * }}
- */
-let UndoState;
-
-/**
* Wraps the Ink component with an API that can be called
* across an IFrame boundary.
*/
class InkAPI {
- /** @param {!ink.embed.EmbedComponent} embed */
- constructor(embed) {
- this.embed_ = embed;
- this.brush_ = ink.BrushModel.getInstance(embed);
+ /** @param {!drawings.Canvas} canvas */
+ constructor(canvas) {
+ this.canvas_ = canvas;
this.camera_ = null;
}
- /** @param {function(!UndoState)} listener */
+ /** @param {function(!drawings.UndoState)} listener */
addUndoStateListener(listener) {
- /** @param {!ink.UndoStateChangeEvent} e */
- function wrapper(e) {
- listener({
- canUndo: e.getCanUndo(),
- canRedo: e.getCanRedo(),
- });
- }
-
- this.embed_.addEventListener(ink.UndoStateChangeEvent.EVENT_TYPE, wrapper);
+ this.canvas_.addUndoRedoListener(listener);
}
/**
@@ -42,109 +25,70 @@ class InkAPI {
// We change the type from ArrayBuffer to Uint8Array due to the consequences
// of the buffer being passed across the iframe boundary. This realm has a
// different ArrayBuffer constructor than `buffer`.
- // TODO(dstockwell): Update Ink to allow Uint8Array here.
- this.embed_.setPDF(
- /** @type {!ArrayBuffer} */ (
- /** @type {!*} */ (new Uint8Array(buffer))));
+ this.canvas_.setPDF(new Uint8Array(buffer));
}
/**
- * @return {!Promise<Uint8Array>}
+ * @return {!Uint8Array}
*/
getPDF() {
- return this.embed_.getPDF();
+ return this.canvas_.getPDF();
}
/**
* @return {!Uint8Array}
*/
getPDFDestructive() {
- return this.embed_.getPDFDestructive();
+ return this.canvas_.getPDFDestructive();
}
async setCamera(camera) {
this.camera_ = camera;
- this.embed_.setCamera(camera);
+ this.canvas_.setCamera(camera);
// Wait for the next task to avoid a race where Ink drops the camera value
// when the canvas is rotated in low-latency mode.
- setTimeout(() => this.embed_.setCamera(this.camera_), 0);
+ setTimeout(() => this.canvas_.setCamera(this.camera_), 0);
}
/** @param {AnnotationTool} tool */
setAnnotationTool(tool) {
- const shape = {
- eraser: 'MAGIC_ERASE',
- pen: 'INKPEN',
- highlighter: 'SMART_HIGHLIGHTER_TOOL',
- }[tool.tool];
- this.brush_.setShape(shape);
- if (tool.tool !== 'eraser') {
- this.brush_.setColor(/** @type {string} */ (tool.color));
- }
- this.brush_.setStrokeWidth(tool.size);
+ this.canvas_.setTool(tool);
}
flush() {
- return new Promise(resolve => this.embed_.flush(resolve));
+ return this.canvas_.flush();
}
/** @param {string} hexColor */
setOutOfBoundsColor(hexColor) {
- this.embed_.setOutOfBoundsColor(ink.Color.fromString(hexColor));
+ this.canvas_.setOutOfBoundsColor(hexColor);
}
/** @param {string} url */
setBorderImage(url) {
- this.embed_.setBorderImage(url);
+ this.canvas_.setBorderImage(url);
}
/** @param {number} spacing in points */
setPageSpacing(spacing) {
- this.embed_.setVerticalPageLayout(spacing);
+ this.canvas_.setVerticalPageLayout(spacing);
}
- dispatchPointerEvent(type, init) {
- const engine = document.querySelector('#ink-engine');
- const match = engine.style.transform.match(/(\d+)deg/);
- const rotation = match ? Number(match[1]) : 0;
- let offsetX = init.clientX;
- let offsetY = init.clientY;
- // If Ink's canvas has been re-orientated away from 0, we must transform
- // the event's offsetX and offsetY to correspond with the rotation and
- // offset applied.
- if ([90, 180, 270].includes(rotation)) {
- const width = window.innerWidth;
- const height = window.innerHeight;
- const matrix = new DOMMatrix();
- matrix.translateSelf(width / 2, height / 2);
- matrix.rotateSelf(0, 0, -rotation);
- matrix.translateSelf(-width / 2, -height / 2);
- const result = matrix.transformPoint({x: offsetX, y: offsetY});
- offsetX = result.x - engine.offsetLeft;
- offsetY = result.y - engine.offsetTop;
- }
-
- const event = new PointerEvent(type, init);
- // Ink uses offsetX and offsetY, but we can only override them, not pass
- // as part of the init.
- Object.defineProperty(event, 'offsetX', {value: offsetX});
- Object.defineProperty(event, 'offsetY', {value: offsetY});
- engine.dispatchEvent(event);
+ dispatchPointerEvent(evt) {
+ this.canvas_.dispatchInput(evt);
}
undo() {
- this.embed_.undo();
+ this.canvas_.undo();
}
redo() {
- this.embed_.redo();
+ this.canvas_.redo();
}
}
/** @return {Promise<InkAPI>} */
window.initInk = async function() {
- const config = new ink.embed.Config();
- const embed = await ink.embed.EmbedComponent.execute(config);
- embed.assignFlag(ink.proto.Flag.ENABLE_HOST_CAMERA_CONTROL, true);
- return new InkAPI(embed);
+ const canvas = await drawings.Canvas.execute(document.body);
+ return new InkAPI(canvas);
};
diff --git a/chromium/chrome/browser/resources/pdf/ink_controller.js b/chromium/chrome/browser/resources/pdf/ink_controller.js
new file mode 100644
index 00000000000..276b6ab686b
--- /dev/null
+++ b/chromium/chrome/browser/resources/pdf/ink_controller.js
@@ -0,0 +1,128 @@
+// Copyright 2020 The Chromium 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 {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_target.m.js';
+
+import {ContentController} from './controller.js';
+import {Viewport} from './viewport.js';
+
+// Note: Redefining this type here, to work around the fact that ink externs
+// are only available on Chrome OS, so the targets that contain them cannot be
+// built on other platforms.
+
+/**
+ * @typedef {{
+ * setAnnotationTool: function(AnnotationTool):void,
+ * viewportChanged: function():void,
+ * saveDocument: function():!Promise,
+ * undo: function():void,
+ * redo: function():void,
+ * load: function(string, !ArrayBuffer):!Promise,
+ * viewport: !Viewport,
+ * }}
+ */
+let ViewerInkHostElement;
+
+// Controller for annotation mode, on Chrome OS only. Fires the following events
+// from its event target:
+// has-unsaved-changes: Fired to indicate there are ink annotations that have
+// not been saved.
+// set-annotation-undo-state: Contains information about whether undo or redo
+// options are available.
+export class InkController extends ContentController {
+ /**
+ * @param {!Viewport} viewport
+ * @param {!HTMLDivElement} contentElement
+ */
+ constructor(viewport, contentElement) {
+ super();
+
+ /** @private {!Viewport} */
+ this.viewport_ = viewport;
+
+ /** @private {!HTMLDivElement} */
+ this.contentElement_ = contentElement;
+
+ /** @private {?ViewerInkHostElement} */
+ this.inkHost_ = null;
+
+ /** @private {!EventTarget} */
+ this.eventTarget_ = new EventTarget();
+
+ /** @type {?AnnotationTool} */
+ this.tool_ = null;
+ }
+
+ /** @return {!EventTarget} */
+ getEventTarget() {
+ return this.eventTarget_;
+ }
+
+ /** @param {AnnotationTool} tool */
+ setAnnotationTool(tool) {
+ this.tool_ = tool;
+ if (this.inkHost_) {
+ this.inkHost_.setAnnotationTool(tool);
+ }
+ }
+
+ /** @override */
+ rotateClockwise() {
+ // TODO(dstockwell): implement rotation
+ }
+
+ /** @override */
+ rotateCounterclockwise() {
+ // TODO(dstockwell): implement rotation
+ }
+
+ /** @override */
+ setTwoUpView(enableTwoUpView) {
+ // TODO(dstockwell): Implement two up view.
+ }
+
+ /** @override */
+ viewportChanged() {
+ this.inkHost_.viewportChanged();
+ }
+
+ /** @override */
+ save(requestType) {
+ return this.inkHost_.saveDocument();
+ }
+
+ /** @override */
+ undo() {
+ this.inkHost_.undo();
+ }
+
+ /** @override */
+ redo() {
+ this.inkHost_.redo();
+ }
+
+ /** @override */
+ load(filename, data) {
+ if (!this.inkHost_) {
+ const inkHost = document.createElement('viewer-ink-host');
+ this.contentElement_.appendChild(inkHost);
+ this.inkHost_ = /** @type {!ViewerInkHostElement} */ (inkHost);
+ this.inkHost_.viewport = this.viewport_;
+ inkHost.addEventListener('stroke-added', e => {
+ this.eventTarget_.dispatchEvent(new CustomEvent('has-unsaved-changes'));
+ });
+ inkHost.addEventListener('undo-state-changed', e => {
+ this.eventTarget_.dispatchEvent(
+ new CustomEvent('set-annotation-undo-state', {detail: e.detail}));
+ });
+ }
+ return this.inkHost_.load(filename, data);
+ }
+
+ /** @override */
+ unload() {
+ this.inkHost_.remove();
+ this.inkHost_ = null;
+ }
+}
diff --git a/chromium/chrome/browser/resources/pdf/main.js b/chromium/chrome/browser/resources/pdf/main.js
index 28e1726b30b..4b65231c650 100644
--- a/chromium/chrome/browser/resources/pdf/main.js
+++ b/chromium/chrome/browser/resources/pdf/main.js
@@ -2,16 +2,75 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-import './elements/viewer-error-screen.js';
-import './elements/viewer-password-screen.js';
-import './elements/viewer-pdf-toolbar.js';
-import './elements/viewer-zoom-toolbar.js';
-import './elements/shared-vars.js';
-// <if expr="chromeos">
-import './elements/viewer-ink-host.js';
-import './elements/viewer-form-warning.js';
-// </if>
-
-import {main} from './main_util.js';
+import './pdf_viewer.js';
+
+import {BrowserApi, createBrowserApi} from './browser_api.js';
+
+/**
+ * Stores any pending messages received which should be passed to the
+ * PDFViewer when it is created.
+ * @type Array
+ */
+const pendingMessages = [];
+
+/**
+ * Handles events that are received prior to the PDFViewer being created.
+ * @param {Object} message A message event received.
+ */
+function handleScriptingMessage(message) {
+ pendingMessages.push(message);
+}
+
+/**
+ * Initialize the global PDFViewer and pass any outstanding messages to it.
+ * @param {!BrowserApi} browserApi
+ */
+function initViewer(browserApi) {
+ // PDFViewer will handle any messages after it is created.
+ window.removeEventListener('message', handleScriptingMessage, false);
+ const viewer = document.querySelector('#viewer');
+ viewer.init(browserApi);
+ while (pendingMessages.length > 0) {
+ viewer.handleScriptingMessage(pendingMessages.shift());
+ }
+ window.viewer = viewer;
+}
+
+/**
+ * Determine if the content settings allow PDFs to execute javascript.
+ * @param {!BrowserApi} browserApi
+ * @return {!Promise<!BrowserApi>}
+ */
+function configureJavaScriptContentSetting(browserApi) {
+ return new Promise((resolve, reject) => {
+ chrome.contentSettings.javascript.get(
+ {
+ 'primaryUrl': browserApi.getStreamInfo().originalUrl,
+ 'secondaryUrl': window.location.origin
+ },
+ (result) => {
+ browserApi.getStreamInfo().javascript = result.setting;
+ resolve(browserApi);
+ });
+ });
+}
+
+/**
+ * Entrypoint for starting the PDF viewer. This function obtains the browser
+ * API for the PDF and initializes the PDF Viewer.
+ */
+function main() {
+ // Set up an event listener to catch scripting messages which are sent prior
+ // to the PDFViewer being created.
+ window.addEventListener('message', handleScriptingMessage, false);
+ let chain = createBrowserApi();
+
+ // Content settings may not be present in test environments.
+ if (chrome.contentSettings) {
+ chain = chain.then(configureJavaScriptContentSetting);
+ }
+
+ chain.then(initViewer);
+}
main();
diff --git a/chromium/chrome/browser/resources/pdf/main_pp.js b/chromium/chrome/browser/resources/pdf/main_pp.js
deleted file mode 100644
index b21153858b0..00000000000
--- a/chromium/chrome/browser/resources/pdf/main_pp.js
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-import './elements/viewer-error-screen.js';
-import './elements/viewer-page-indicator.js';
-import './elements/viewer-zoom-toolbar.js';
-import './elements/shared-vars.js';
-
-import {main} from './main_util.js';
-
-main();
diff --git a/chromium/chrome/browser/resources/pdf/main_util.js b/chromium/chrome/browser/resources/pdf/main_util.js
deleted file mode 100644
index a0585f05ff4..00000000000
--- a/chromium/chrome/browser/resources/pdf/main_util.js
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-import {BrowserApi, createBrowserApi} from './browser_api.js';
-import {PDFViewer} from './pdf_viewer.js';
-
-
-/**
- * Global PDFViewer object, accessible for testing.
- *
- * @type Object
- */
-window.viewer = null;
-
-
-/**
- * Stores any pending messages received which should be passed to the
- * PDFViewer when it is created.
- *
- * @type Array
- */
-const pendingMessages = [];
-
-/**
- * Handles events that are received prior to the PDFViewer being created.
- *
- * @param {Object} message A message event received.
- */
-function handleScriptingMessage(message) {
- pendingMessages.push(message);
-}
-/**
- * Initialize the global PDFViewer and pass any outstanding messages to it.
- *
- * @param {!BrowserApi} browserApi
- */
-function initViewer(browserApi) {
- // PDFViewer will handle any messages after it is created.
- window.removeEventListener('message', handleScriptingMessage, false);
- window.viewer = new PDFViewer(browserApi);
- while (pendingMessages.length > 0) {
- window.viewer.handleScriptingMessage(pendingMessages.shift());
- }
-}
-
-/**
- * Determine if the content settings allow PDFs to execute javascript.
- *
- * @param {!BrowserApi} browserApi
- * @return {!Promise<!BrowserApi>}
- */
-function configureJavaScriptContentSetting(browserApi) {
- return new Promise((resolve, reject) => {
- chrome.contentSettings.javascript.get(
- {
- 'primaryUrl': browserApi.getStreamInfo().originalUrl,
- 'secondaryUrl': window.location.origin
- },
- (result) => {
- browserApi.getStreamInfo().javascript = result.setting;
- resolve(browserApi);
- });
- });
-}
-
-/**
- * Entrypoint for starting the PDF viewer. This function obtains the browser
- * API for the PDF and constructs a PDFViewer object with it.
- */
-export function main() {
- // Set up an event listener to catch scripting messages which are sent prior
- // to the PDFViewer being created.
- window.addEventListener('message', handleScriptingMessage, false);
- let chain = createBrowserApi();
-
- // Content settings may not be present in test environments.
- if (chrome.contentSettings) {
- chain = chain.then(configureJavaScriptContentSetting);
- }
-
- chain.then(initViewer);
-}
diff --git a/chromium/chrome/browser/resources/pdf/metrics.js b/chromium/chrome/browser/resources/pdf/metrics.js
index d1ca0a8270b..42384c4b0db 100644
--- a/chromium/chrome/browser/resources/pdf/metrics.js
+++ b/chromium/chrome/browser/resources/pdf/metrics.js
@@ -4,13 +4,10 @@
import {FittingType, TwoUpViewAction} from './constants.js';
-/**
- * Handles events specific to the PDF viewer and logs the corresponding metrics.
- */
+// Handles events specific to the PDF viewer and logs the corresponding metrics.
export class PDFMetrics {
/**
* Records when the zoom mode is changed to fit a FittingType.
- *
* @param {FittingType} fittingType the new FittingType.
*/
static recordFitTo(fittingType) {
@@ -25,7 +22,6 @@ export class PDFMetrics {
/**
* Records when the two up view mode is enabled or disabled.
- *
* @param {TwoUpViewAction} twoUpViewAction the new TwoUpViewAction.
*/
static recordTwoUpView(twoUpViewAction) {
@@ -36,8 +32,18 @@ export class PDFMetrics {
}
/**
+ * Records zoom in and zoom out actions.
+ * @param {boolean} isZoomIn True when the action is zooming in, false when
+ * the action is zooming out.
+ */
+ static recordZoomAction(isZoomIn) {
+ PDFMetrics.record(
+ isZoomIn ? PDFMetrics.UserAction.ZOOM_IN :
+ PDFMetrics.UserAction.ZOOM_OUT);
+ }
+
+ /**
* Records the given action to chrome.metricsPrivate.
- *
* @param {PDFMetrics.UserAction} action
*/
static record(action) {
@@ -84,18 +90,15 @@ PDFMetrics.firstActionRecorded_ = new Set();
* The *_FIRST values are recorded automaticlly,
* eg. PDFMetrics.record(...ROTATE) will also record ROTATE_FIRST
* on the first instance.
- *
* @enum {number}
*/
PDFMetrics.UserAction = {
- /**
- * Recorded when the document is first loaded. This event serves as
- * denominator to determine percentages of documents in which an action was
- * taken as well as average number of each action per document.
- */
+ // Recorded when the document is first loaded. This event serves as
+ // denominator to determine percentages of documents in which an action was
+ // taken as well as average number of each action per document.
DOCUMENT_OPENED: 0,
- /** Recorded when the document is rotated clockwise or counter-clockwise. */
+ // Recorded when the document is rotated clockwise or counter-clockwise.
ROTATE_FIRST: 1,
ROTATE: 2,
@@ -105,26 +108,24 @@ PDFMetrics.UserAction = {
FIT_TO_PAGE_FIRST: 5,
FIT_TO_PAGE: 6,
- /** Recorded when the bookmarks panel is opened. */
+ // Recorded when the bookmarks panel is opened.
OPEN_BOOKMARKS_PANEL_FIRST: 7,
OPEN_BOOKMARKS_PANEL: 8,
- /** Recorded when a bookmark is followed. */
+ // Recorded when a bookmark is followed.
FOLLOW_BOOKMARK_FIRST: 9,
FOLLOW_BOOKMARK: 10,
- /** Recorded when the page selection is used to navigate to another page. */
+ // Recorded when the page selection is used to navigate to another page.
PAGE_SELECTOR_NAVIGATE_FIRST: 11,
PAGE_SELECTOR_NAVIGATE: 12,
- /** Recorded when the user triggers a save of the document. */
+ // Recorded when the user triggers a save of the document.
SAVE_FIRST: 13,
SAVE: 14,
- /**
- * Recorded when the user triggers a save of the document and the document
- * has been modified by annotations.
- */
+ // Recorded when the user triggers a save of the document and the document
+ // has been modified by annotations.
SAVE_WITH_ANNOTATION_FIRST: 15,
SAVE_WITH_ANNOTATION: 16,
@@ -137,39 +138,47 @@ PDFMetrics.UserAction = {
EXIT_ANNOTATION_MODE_FIRST: 21,
EXIT_ANNOTATION_MODE: 22,
- /** Recorded when a pen stroke is made. */
+ // Recorded when a pen stroke is made.
ANNOTATE_STROKE_TOOL_PEN_FIRST: 23,
ANNOTATE_STROKE_TOOL_PEN: 24,
- /** Recorded when an eraser stroke is made. */
+ // Recorded when an eraser stroke is made.
ANNOTATE_STROKE_TOOL_ERASER_FIRST: 25,
ANNOTATE_STROKE_TOOL_ERASER: 26,
- /** Recorded when a highlighter stroke is made. */
+ // Recorded when a highlighter stroke is made.
ANNOTATE_STROKE_TOOL_HIGHLIGHTER_FIRST: 27,
ANNOTATE_STROKE_TOOL_HIGHLIGHTER: 28,
- /** Recorded when a stroke is made using touch. */
+ // Recorded when a stroke is made using touch.
ANNOTATE_STROKE_DEVICE_TOUCH_FIRST: 29,
ANNOTATE_STROKE_DEVICE_TOUCH: 30,
- /** Recorded when a stroke is made using mouse. */
+ // Recorded when a stroke is made using mouse.
ANNOTATE_STROKE_DEVICE_MOUSE_FIRST: 31,
ANNOTATE_STROKE_DEVICE_MOUSE: 32,
- /** Recorded when a stroke is made using pen. */
+ // Recorded when a stroke is made using pen.
ANNOTATE_STROKE_DEVICE_PEN_FIRST: 33,
ANNOTATE_STROKE_DEVICE_PEN: 34,
- /** Recorded when two-up view mode is enabled. */
+ // Recorded when two-up view mode is enabled.
TWO_UP_VIEW_ENABLE_FIRST: 35,
TWO_UP_VIEW_ENABLE: 36,
- /** Recorded when two-up view mode is disabled. */
+ // Recorded when two-up view mode is disabled.
TWO_UP_VIEW_DISABLE_FIRST: 37,
TWO_UP_VIEW_DISABLE: 38,
- NUMBER_OF_ACTIONS: 39,
+ // Recorded when zoom in button is clicked.
+ ZOOM_IN_FIRST: 39,
+ ZOOM_IN: 40,
+
+ // Recorded when zoom out button is clicked.
+ ZOOM_OUT_FIRST: 41,
+ ZOOM_OUT: 42,
+
+ NUMBER_OF_ACTIONS: 43,
};
// Map from UserAction to the 'FIRST' action. These metrics are recorded
@@ -252,4 +261,12 @@ PDFMetrics.firstMap_ = new Map([
PDFMetrics.UserAction.TWO_UP_VIEW_DISABLE,
PDFMetrics.UserAction.TWO_UP_VIEW_DISABLE_FIRST,
],
+ [
+ PDFMetrics.UserAction.ZOOM_IN,
+ PDFMetrics.UserAction.ZOOM_IN_FIRST,
+ ],
+ [
+ PDFMetrics.UserAction.ZOOM_OUT,
+ PDFMetrics.UserAction.ZOOM_OUT_FIRST,
+ ],
]);
diff --git a/chromium/chrome/browser/resources/pdf/navigator.js b/chromium/chrome/browser/resources/pdf/navigator.js
index e24d3e8ff02..8aa2c1e3fd6 100644
--- a/chromium/chrome/browser/resources/pdf/navigator.js
+++ b/chromium/chrome/browser/resources/pdf/navigator.js
@@ -5,10 +5,8 @@
import {OpenPdfParamsParser} from './open_pdf_params_parser.js';
import {Viewport} from './viewport.js';
-/**
- * NavigatorDelegate for calling browser-specific functions to do the actual
- * navigating.
- */
+// NavigatorDelegate for calling browser-specific functions to do the actual
+// navigating.
export class NavigatorDelegate {
/**
* @param {number} tabId The tab ID of the PDF viewer or -1 if the viewer is
@@ -63,7 +61,7 @@ export class NavigatorDelegate {
}
}
-/** Navigator for navigating to links inside or outside the PDF. */
+// Navigator for navigating to links inside or outside the PDF.
export class PdfNavigator {
/**
* @param {string} originalUrl The original page URL.
diff --git a/chromium/chrome/browser/resources/pdf/open_pdf_params_parser.js b/chromium/chrome/browser/resources/pdf/open_pdf_params_parser.js
index 08ef73a94db..858a62b47fd 100644
--- a/chromium/chrome/browser/resources/pdf/open_pdf_params_parser.js
+++ b/chromium/chrome/browser/resources/pdf/open_pdf_params_parser.js
@@ -4,10 +4,8 @@
import {FittingType} from './constants.js';
-/**
- * Parses the open pdf parameters passed in the url to set initial viewport
- * settings for opening the pdf.
- */
+// Parses the open pdf parameters passed in the url to set initial viewport
+// settings for opening the pdf.
export class OpenPdfParamsParser {
/**
* @param {function(string):void} getNamedDestinationCallback
@@ -24,7 +22,6 @@ export class OpenPdfParamsParser {
/**
* Parse zoom parameter of open PDF parameters. The PDF should be opened at
* the specified zoom level.
- *
* @param {string} paramValue zoom value.
* @return {Object} Map with zoom parameters (zoom and position).
* @private
@@ -57,7 +54,6 @@ export class OpenPdfParamsParser {
/**
* Parse view parameter of open PDF parameters. The PDF should be opened at
* the specified fitting type mode and position.
- *
* @param {string} paramValue view value.
* @return {Object} Map with view parameters (view and viewPosition).
* @private
@@ -95,57 +91,35 @@ export class OpenPdfParamsParser {
}
/**
- * Parse the parameters encoded in the fragment of a URL into a dictionary.
- *
+ * Parse the parameters encoded in the fragment of a URL.
* @param {string} url to parse
- * @return {Object} Key-value pairs of URL parameters
+ * @return {!URLSearchParams}
* @private
*/
parseUrlParams_(url) {
- const params = {};
-
- const paramIndex = url.search('#');
- if (paramIndex === -1) {
- return params;
- }
-
- const paramTokens = url.substring(paramIndex + 1).split('&');
- if ((paramTokens.length === 1) && (paramTokens[0].search('=') === -1)) {
- // Handle the case of http://foo.com/bar#NAMEDDEST. This is not
- // explicitly mentioned except by example in the Adobe
- // "PDF Open Parameters" document.
- params['nameddest'] = paramTokens[0];
- return params;
- }
-
- for (const paramToken of paramTokens) {
- const keyValueSplit = paramToken.split('=');
- if (keyValueSplit.length !== 2) {
- continue;
+ const hash = new URL(url).hash;
+ const params = new URLSearchParams(hash.substring(1));
+
+ // Handle the case of http://foo.com/bar#NAMEDDEST. This is not
+ // explicitly mentioned except by example in the Adobe
+ // "PDF Open Parameters" document.
+ if (Array.from(params).length === 1) {
+ const key = Array.from(params.keys())[0];
+ if (params.get(key) === '') {
+ params.append('nameddest', key);
+ params.delete(key);
}
- params[keyValueSplit[0]] = keyValueSplit[1];
}
return params;
}
/**
- * Parse PDF url parameters used for controlling the state of UI. These need
- * to be available when the UI is being initialized, rather than when the PDF
- * is finished loading.
- *
* @param {string} url that needs to be parsed.
- * @return {Object} parsed url parameters.
+ * @return {boolean} Whether the toolbar UI element should be shown.
*/
- getUiUrlParams(url) {
- const params = this.parseUrlParams_(url);
- const uiParams = {toolbar: true};
-
- if ('toolbar' in params && params['toolbar'] === '0') {
- uiParams.toolbar = false;
- }
-
- return uiParams;
+ shouldShowToolbar(url) {
+ return this.parseUrlParams_(url).get('toolbar') !== '0';
}
/**
@@ -153,7 +127,6 @@ export class OpenPdfParamsParser {
* and specify actions to be performed when opening pdf files.
* See http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/
* pdfs/pdf_open_parameters.pdf for details.
- *
* @param {string} url that needs to be parsed.
* @param {Function} callback function to be called with viewport info.
*/
@@ -163,25 +136,30 @@ export class OpenPdfParamsParser {
const urlParams = this.parseUrlParams_(url);
- if ('page' in urlParams) {
+ if (urlParams.has('page')) {
// |pageNumber| is 1-based, but goToPage() take a zero-based page number.
- const pageNumber = parseInt(urlParams['page'], 10);
+ const pageNumber = parseInt(urlParams.get('page'), 10);
if (!Number.isNaN(pageNumber) && pageNumber > 0) {
params['page'] = pageNumber - 1;
}
}
- if ('view' in urlParams) {
- Object.assign(params, this.parseViewParam_(urlParams['view']));
+ if (urlParams.has('view')) {
+ Object.assign(
+ params,
+ this.parseViewParam_(/** @type {string} */ (urlParams.get('view'))));
}
- if ('zoom' in urlParams) {
- Object.assign(params, this.parseZoomParam_(urlParams['zoom']));
+ if (urlParams.has('zoom')) {
+ Object.assign(
+ params,
+ this.parseZoomParam_(/** @type {string} */ (urlParams.get('zoom'))));
}
- if (params.page === undefined && 'nameddest' in urlParams) {
+ if (params.page === undefined && urlParams.has('nameddest')) {
this.outstandingRequests_.push({callback: callback, params: params});
- this.getNamedDestinationCallback_(urlParams['nameddest']);
+ this.getNamedDestinationCallback_(
+ /** @type {string} */ (urlParams.get('nameddest')));
} else {
callback(params);
}
@@ -190,7 +168,6 @@ export class OpenPdfParamsParser {
/**
* This is called when a named destination is received and the page number
* corresponding to the request for which a named destination is passed.
- *
* @param {number} pageNumber The page corresponding to the named destination
* requested.
*/
diff --git a/chromium/chrome/browser/resources/pdf/pdf_scripting_api.js b/chromium/chrome/browser/resources/pdf/pdf_scripting_api.js
index 8cae862e05d..6c2cad0de82 100644
--- a/chromium/chrome/browser/resources/pdf/pdf_scripting_api.js
+++ b/chromium/chrome/browser/resources/pdf/pdf_scripting_api.js
@@ -4,26 +4,27 @@
/**
* Turn a dictionary received from postMessage into a key event.
- *
* @param {Object} dict A dictionary representing the key event.
- * @return {!Event} A key event.
+ * @return {!KeyboardEvent} A key event.
*/
export function DeserializeKeyEvent(dict) {
- const e = document.createEvent('Event');
- e.initEvent('keydown', true, true);
- e.keyCode = dict.keyCode;
- e.code = dict.code;
- e.shiftKey = dict.shiftKey;
- e.ctrlKey = dict.ctrlKey;
- e.altKey = dict.altKey;
- e.metaKey = dict.metaKey;
+ const e = new KeyboardEvent('keydown', {
+ bubbles: true,
+ cancelable: true,
+ key: dict.key,
+ code: dict.code,
+ keyCode: dict.keyCode,
+ shiftKey: dict.shiftKey,
+ ctrlKey: dict.ctrlKey,
+ altKey: dict.altKey,
+ metaKey: dict.metaKey,
+ });
e.fromScriptingAPI = true;
return e;
}
/**
* Turn a key event into a dictionary which can be sent over postMessage.
- *
* @param {Event} event A key event.
* @return {Object} A dictionary representing the key event.
*/
@@ -31,6 +32,7 @@ export function SerializeKeyEvent(event) {
return {
keyCode: event.keyCode,
code: event.code,
+ key: event.key,
shiftKey: event.shiftKey,
ctrlKey: event.ctrlKey,
altKey: event.altKey,
@@ -49,11 +51,8 @@ export const LoadState = {
FAILED: 'failed'
};
-/**
- * Create a new PDFScriptingAPI. This provides a scripting interface to
- * the PDF viewer so that it can be customized by things like print preview.
- *
- */
+// Provides a scripting interface to the PDF viewer so that it can be customized
+// by things like print preview.
export class PDFScriptingAPI {
/**
* @param {Window} window the window of the page containing the pdf viewer.
@@ -134,7 +133,6 @@ export class PDFScriptingAPI {
* Send a message to the extension. If messages try to get sent before there
* is a plugin element set, then we queue them up and send them later (this
* can happen in print preview).
- *
* @param {Object} message The message to send.
* @private
*/
@@ -149,7 +147,6 @@ export class PDFScriptingAPI {
/**
* Sets the plugin element containing the PDF viewer. The element will usually
* be passed into the PDFScriptingAPI constructor but may also be set later.
- *
* @param {Object} plugin the plugin element containing the PDF viewer.
*/
setPlugin(plugin) {
@@ -168,7 +165,6 @@ export class PDFScriptingAPI {
/**
* Sets the callback which will be run when the PDF viewport changes.
- *
* @param {Function} callback the callback to be called.
*/
setViewportChangedCallback(callback) {
@@ -198,7 +194,6 @@ export class PDFScriptingAPI {
/**
* Resets the PDF viewer into print preview mode.
- *
* @param {string} url the url of the PDF to load.
* @param {boolean} grayscale whether or not to display the PDF in grayscale.
* @param {Array<number>} pageNumbers an array of the page numbers.
@@ -215,16 +210,13 @@ export class PDFScriptingAPI {
});
}
- /**
- * Hide the toolbars after a delay.
- */
+ /** Hide the toolbars after a delay. */
hideToolbars() {
this.sendMessage_({type: 'hideToolbars'});
}
/**
* Load a page into the document while in print preview mode.
- *
* @param {string} url the url of the pdf page to load.
* @param {number} index the index of the page to load.
*/
@@ -248,7 +240,6 @@ export class PDFScriptingAPI {
/**
* Get the selected text in the document. The callback will be called with the
* text that is selected. May only be called after document load.
- *
* @param {Function} callback a callback to be called with the selected text.
* @return {boolean} true if the function is successful, false if there is an
* outstanding request for selected text that has not been answered.
@@ -262,16 +253,13 @@ export class PDFScriptingAPI {
return true;
}
- /**
- * Print the document. May only be called after document load.
- */
+ /** Print the document. May only be called after document load. */
print() {
this.sendMessage_({type: 'print'});
}
/**
* Send a key event to the extension.
- *
* @param {Event} keyEvent the key event to send to the extension.
*/
sendKeyEvent(keyEvent) {
@@ -293,7 +281,6 @@ export class PDFScriptingAPI {
* iframe which is navigated to the PDF viewer extension and 2) a scripting
* interface which provides access to various features of the viewer for use
* by print preview and accessibility.
- *
* @param {string} src the source URL of the PDF to load initially.
* @param {string} baseUrl the base URL of the PDF viewer
* @return {!HTMLIFrameElement} the iframe element containing the PDF viewer.
diff --git a/chromium/chrome/browser/resources/pdf/pdf_viewer.html b/chromium/chrome/browser/resources/pdf/pdf_viewer.html
new file mode 100644
index 00000000000..a56670db71c
--- /dev/null
+++ b/chromium/chrome/browser/resources/pdf/pdf_viewer.html
@@ -0,0 +1,61 @@
+<style include="pdf-viewer-shared-style">
+ viewer-pdf-toolbar,
+ viewer-pdf-toolbar-new {
+ position: fixed;
+ width: 100%;
+ z-index: 4;
+ }
+
+ viewer-ink-host {
+ height: 100%;
+ position: absolute;
+ width: 100%;
+ }
+
+ @media(max-height: 250px) {
+ viewer-pdf-toolbar {
+ display: none;
+ }
+ }
+</style>
+
+<template is="dom-if" if="[[!pdfViewerUpdateEnabled_]]">
+ <viewer-pdf-toolbar id="toolbar" strings="[[strings]]"
+ annotation-available="[[annotationAvailable_]]"
+ bookmarks="[[bookmarks_]]" doc-title="[[title_]]"
+ has-edits="[[hasEdits_]]"
+ has-entered-annotation-mode="[[hasEnteredAnnotationMode_]]"
+ is-form-field-focused="[[isFormFieldFocused_]]"
+ on-save="onToolbarSave_" on-print="onPrint_"
+ on-annotation-mode-toggled="onAnnotationModeToggled_"
+ on-annotation-tool-changed="onAnnotationToolChanged_"
+ on-rotate-right="rotateClockwise" on-undo="onUndo_" on-redo="onRedo_"
+ hidden>
+ </viewer-pdf-toolbar>
+</template>
+<template is="dom-if" if="[[pdfViewerUpdateEnabled_]]">
+ <viewer-pdf-toolbar-new id="toolbar" hidden>
+ </viewer-pdf-toolbar-new>
+</template>
+
+<div id="sizer"></div>
+<viewer-password-screen id="password-screen"
+ on-password-submitted="onPasswordSubmitted_">
+</viewer-password-screen>
+
+<viewer-zoom-toolbar id="zoom-toolbar" strings="[[strings]]"
+ annotation-mode="[[annotationMode_]]"
+ on-fit-to-changed="onFitToChanged"
+ on-two-up-view-changed="onTwoUpViewChanged_"
+ on-zoom-in="onZoomIn" on-zoom-out="onZoomOut"
+ hidden>
+</viewer-zoom-toolbar>
+
+<viewer-error-screen id="error-screen"></viewer-error-screen>
+
+<if expr="chromeos">
+<viewer-form-warning id="form-warning"></viewer-form-warning>
+</if>
+
+<div id="content"></div>
+
diff --git a/chromium/chrome/browser/resources/pdf/pdf_viewer.js b/chromium/chrome/browser/resources/pdf/pdf_viewer.js
index e6fc90845ab..e23b4b41e48 100644
--- a/chromium/chrome/browser/resources/pdf/pdf_viewer.js
+++ b/chromium/chrome/browser/resources/pdf/pdf_viewer.js
@@ -2,46 +2,38 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+import './elements/viewer-error-screen.js';
+import './elements/viewer-password-screen.js';
+import './elements/viewer-pdf-toolbar.js';
+import './elements/viewer-pdf-toolbar-new.js';
+import './elements/shared-vars.js';
+// <if expr="chromeos">
+import './elements/viewer-ink-host.js';
+import './elements/viewer-form-warning.js';
+// </if>
+import './pdf_viewer_shared_style.js';
+
import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js';
-import {EventTracker} from 'chrome://resources/js/event_tracker.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
-import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js';
-import {$, hasKeyModifiers, isRTL} from 'chrome://resources/js/util.m.js';
+import {hasKeyModifiers, isRTL} from 'chrome://resources/js/util.m.js';
+import {html} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {Bookmark} from './bookmark_type.js';
import {BrowserApi} from './browser_api.js';
-import {FittingType, TwoUpViewAction} from './constants.js';
-import {ContentController, InkController, MessageData, PluginController, PrintPreviewParams} from './controller.js';
-import {FitToChangedEvent} from './elements/viewer-zoom-toolbar.js';
-import {GestureDetector} from './gesture_detector.js';
+import {FittingType, SaveRequestType, TwoUpViewAction} from './constants.js';
import {PDFMetrics} from './metrics.js';
import {NavigatorDelegate, PdfNavigator} from './navigator.js';
import {OpenPdfParamsParser} from './open_pdf_params_parser.js';
import {DeserializeKeyEvent, LoadState, SerializeKeyEvent} from './pdf_scripting_api.js';
+import {PDFViewerBaseElement} from './pdf_viewer_base.js';
+import {DestinationMessageData, DocumentDimensionsMessageData, shouldIgnoreKeyEvents} from './pdf_viewer_utils.js';
import {ToolbarManager} from './toolbar_manager.js';
-import {LayoutOptions, Point, Viewport} from './viewport.js';
-import {ViewportScroller} from './viewport_scroller.js';
-import {ZoomManager} from './zoom_manager.js';
+import {Point} from './viewport.js';
-/**
- * @typedef {{
- * source: Object,
- * origin: string,
- * data: !MessageData,
- * }}
- */
-let MessageObject;
+// <if expr="chromeos">
+import {InkController} from './ink_controller.js';
+// </if>
-/**
- * @typedef {{
- * type: string,
- * height: number,
- * width: number,
- * layoutOptions: (!LayoutOptions|undefined),
- * pageDimensions: Array
- * }}
- */
-let DocumentDimensionsMessageData;
/**
* @typedef {{
@@ -55,17 +47,6 @@ let NavigateMessageData;
/**
* @typedef {{
* type: string,
- * page: number,
- * x: number,
- * y: number,
- * zoom: number
- * }}
- */
-let DestinationMessageData;
-
-/**
- * @typedef {{
- * type: string,
* title: string,
* bookmarks: !Array<!Bookmark>,
* canSerializeDocument: boolean,
@@ -82,22 +63,9 @@ let MetadataMessageData;
*/
let RequiredSaveResult;
-/** @return {number} Width of a scrollbar in pixels */
-function getScrollbarWidth() {
- const div = document.createElement('div');
- div.style.visibility = 'hidden';
- div.style.overflow = 'scroll';
- div.style.width = '50px';
- div.style.height = '50px';
- div.style.position = 'absolute';
- document.body.appendChild(div);
- const result = div.offsetWidth - div.clientWidth;
- div.parentNode.removeChild(div);
- return result;
-}
-
/**
* Return the filename component of a URL, percent decoded if possible.
+ * Exported for tests.
* @param {string} url The URL to get the filename from.
* @return {string} The filename component.
*/
@@ -116,270 +84,187 @@ export function getFilenameFromURL(url) {
}
}
-/**
- * Whether keydown events should currently be ignored. Events are ignored when
- * an editable element has focus, to allow for proper editing controls.
- * @param {Element} activeElement The currently selected DOM node.
- * @return {boolean} True if keydown events should be ignored.
- */
-export function shouldIgnoreKeyEvents(activeElement) {
- while (activeElement.shadowRoot != null &&
- activeElement.shadowRoot.activeElement != null) {
- activeElement = activeElement.shadowRoot.activeElement;
+class PDFViewerElement extends PDFViewerBaseElement {
+ static get is() {
+ return 'pdf-viewer';
}
- return (
- activeElement.isContentEditable ||
- (activeElement.tagName === 'INPUT' && activeElement.type !== 'radio') ||
- activeElement.tagName === 'TEXTAREA');
-}
+ static get template() {
+ return html`{__html_template__}`;
+ }
-/**
- * Creates a new PDFViewer. There should only be one of these objects per
- * document.
- */
-export class PDFViewer {
- /**
- * @param {!BrowserApi} browserApi An object providing an API to the browser.
- */
- constructor(browserApi) {
- /** @private {!BrowserApi} */
- this.browserApi_ = browserApi;
+ static get properties() {
+ return {
+ annotationAvailable_: {
+ type: Boolean,
+ computed: 'computeAnnotationAvailable_(' +
+ 'hadPassword_, rotated_, canSerializeDocument_)',
+ },
- /** @private {string} */
- this.originalUrl_ = this.browserApi_.getStreamInfo().originalUrl;
+ annotationMode_: {
+ type: Boolean,
+ value: false,
+ },
- /** @private {string} */
- this.javascript_ = this.browserApi_.getStreamInfo().javascript || 'block';
+ bookmarks_: Array,
- /** @private {!LoadState} */
- this.loadState_ = LoadState.LOADING;
+ hasEdits_: {
+ type: Boolean,
+ value: false,
+ },
- /** @private {?Object} */
- this.parentWindow_ = null;
+ hasEnteredAnnotationMode_: {
+ type: Boolean,
+ value: false,
+ },
- /** @private {?string} */
- this.parentOrigin_ = null;
+ rotated_: Boolean,
- /** @private {boolean} */
- this.isFormFieldFocused_ = false;
+ hadPassword_: Boolean,
- /** @private {number} */
- this.beepCount_ = 0;
+ canSerializeDocument_: Boolean,
- /** @private {!Array} */
- this.delayedScriptingMessages_ = [];
+ title_: String,
- /** @private {!PromiseResolver} */
- this.loaded_;
+ isFormFieldFocused_: Boolean,
- /** @private {boolean} */
- this.initialLoadComplete_ = false;
+ /** @private */
+ pdfViewerUpdateEnabled_: {
+ type: Boolean,
+ value: function() {
+ return document.documentElement.hasAttribute(
+ 'pdf-viewer-update-enabled');
+ },
+ },
+ };
+ }
+ constructor() {
+ super();
+
+ // Polymer properties
/** @private {boolean} */
- this.isPrintPreview_ = location.origin === 'chrome://print';
- document.documentElement.toggleAttribute(
- 'is-print-preview', this.isPrintPreview_);
+ this.annotationAvailable_;
/** @private {boolean} */
- this.isPrintPreviewLoadingFinished_ = false;
+ this.annotationMode_ = false;
+
+ /** @private {!Array<!Bookmark>} */
+ this.bookmarks_ = [];
/** @private {boolean} */
- this.isUserInitiatedEvent_ = true;
+ this.hasEdits_ = false;
/** @private {boolean} */
this.hasEnteredAnnotationMode_ = false;
/** @private {boolean} */
+ this.rotated_ = false;
+
+ /** @private {boolean} */
this.hadPassword_ = false;
/** @private {boolean} */
this.canSerializeDocument_ = false;
- /** @private {!EventTracker} */
- this.tracker_ = new EventTracker();
-
- PDFMetrics.record(PDFMetrics.UserAction.DOCUMENT_OPENED);
-
- // Parse open pdf parameters.
- /** @private {!OpenPdfParamsParser} */
- this.paramsParser_ = new OpenPdfParamsParser(
- destination => this.pluginController_.getNamedDestination(destination));
- const toolbarEnabled =
- this.paramsParser_.getUiUrlParams(this.originalUrl_).toolbar &&
- !this.isPrintPreview_;
-
- // The sizer element is placed behind the plugin element to cause scrollbars
- // to be displayed in the window. It is sized according to the document size
- // of the pdf and zoom level.
- this.sizer_ = /** @type {!HTMLDivElement} */ ($('sizer'));
-
- /** @private {?ViewerPageIndicatorElement} */
- this.pageIndicator_ = this.isPrintPreview_ ?
- /** @type {!ViewerPageIndicatorElement} */ ($('page-indicator')) :
- null;
-
- /** @private {?ViewerPasswordScreenElement} */
- this.passwordScreen_ =
- /** @type {?ViewerPasswordScreenElement} */ ($('password-screen'));
- if (this.passwordScreen_) {
- this.passwordScreen_.addEventListener('password-submitted', e => {
- this.onPasswordSubmitted_(
- /** @type {!CustomEvent<{password: string}>} */ (e));
- });
- }
+ /** @private {string} */
+ this.title_ = '';
- /** @private {?ViewerErrorScreenElement} */
- this.errorScreen_ =
- /** @type {!ViewerErrorScreenElement} */ ($('error-screen'));
- // Can only reload if we are in a normal tab.
- if (chrome.tabs && this.browserApi_.getStreamInfo().tabId !== -1) {
- this.errorScreen_.reloadFn = () => {
- chrome.tabs.reload(this.browserApi_.getStreamInfo().tabId);
- };
- }
+ /** @private {boolean} */
+ this.isFormFieldFocused_ = false;
- // Create the viewport.
- const shortWindow =
- window.innerHeight < PDFViewer.TOOLBAR_WINDOW_MIN_HEIGHT;
- const topToolbarHeight =
- (toolbarEnabled) ? PDFViewer.MATERIAL_TOOLBAR_HEIGHT : 0;
- const defaultZoom =
- this.browserApi_.getZoomBehavior() === BrowserApi.ZoomBehavior.MANAGE ?
- this.browserApi_.getDefaultZoom() :
- 1.0;
-
- /** @private {!Viewport} */
- this.viewport_ = new Viewport(
- window, this.sizer_, getScrollbarWidth(), defaultZoom,
- topToolbarHeight);
- this.viewport_.setViewportChangedCallback(() => this.viewportChanged_());
- this.viewport_.setBeforeZoomCallback(
- () => this.currentController_.beforeZoom());
- this.viewport_.setAfterZoomCallback(
- () => this.currentController_.afterZoom());
- this.viewport_.setUserInitiatedCallback(
- userInitiated => this.setUserInitiated_(userInitiated));
- window.addEventListener('beforeunload', () => this.resetTrackers_());
-
- // Create the plugin object dynamically so we can set its src. The plugin
- // element is sized to fill the entire window and is set to be fixed
- // positioning, acting as a viewport. The plugin renders into this viewport
- // according to the scroll position of the window.
- /** @private {!HTMLEmbedElement} */
- this.plugin_ =
- /** @type {!HTMLEmbedElement} */ (document.createElement('embed'));
-
- // NOTE: The plugin's 'id' field must be set to 'plugin' since
- // chrome/renderer/printing/print_render_frame_helper.cc actually
- // references it.
- this.plugin_.id = 'plugin';
- this.plugin_.type = 'application/x-google-chrome-pdf';
-
- // Handle scripting messages from outside the extension that wish to
- // interact with it. We also send a message indicating that extension has
- // loaded and is ready to receive messages.
- window.addEventListener('message', message => {
- this.handleScriptingMessage(/** @type {!MessageObject} */ (message));
- }, false);
-
- this.plugin_.setAttribute('src', this.originalUrl_);
- this.plugin_.setAttribute(
- 'stream-url', this.browserApi_.getStreamInfo().streamUrl);
- let headers = '';
- for (const header in this.browserApi_.getStreamInfo().responseHeaders) {
- headers += header + ': ' +
- this.browserApi_.getStreamInfo().responseHeaders[header] + '\n';
- }
- this.plugin_.setAttribute('headers', headers);
+ // Non-Polymer properties
- this.plugin_.setAttribute('background-color', PDFViewer.BACKGROUND_COLOR);
- this.plugin_.setAttribute('top-toolbar-height', topToolbarHeight);
- this.plugin_.setAttribute('javascript', this.javascript_);
+ /** @private {number} */
+ this.beepCount_ = 0;
- if (this.browserApi_.getStreamInfo().embedded) {
- this.plugin_.setAttribute(
- 'top-level-url', this.browserApi_.getStreamInfo().tabUrl);
- } else {
- this.plugin_.setAttribute('full-frame', '');
- }
+ /** @private {boolean} */
+ this.hadPassword_ = false;
+
+ /** @private {boolean} */
+ this.toolbarEnabled_ = false;
+
+ // <if expr="chromeos">
+ /** @private {?InkController} */
+ this.inkController_ = null;
+ // </if>
+
+ /** @private {?ToolbarManager} */
+ this.toolbarManager_ = null;
+
+ /** @private {?PdfNavigator} */
+ this.navigator_ = null;
+
+ /** @private {string} */
+ this.title_ = '';
+
+ /** @private {boolean} */
+ this.pdfViewerUpdateEnabled_;
+ }
- $('content').appendChild(this.plugin_);
+ /** @override */
+ getToolbarHeight() {
+ assert(this.paramsParser);
+ this.toolbarEnabled_ =
+ this.paramsParser.shouldShowToolbar(this.originalUrl);
+ return this.toolbarEnabled_ ? MATERIAL_TOOLBAR_HEIGHT : 0;
+ }
+
+ /** @override */
+ getContent() {
+ return /** @type {!HTMLDivElement} */ (this.$$('#content'));
+ }
- /** @private {!PluginController} */
- this.pluginController_ = new PluginController(
- this.plugin_, this.viewport_, () => this.isUserInitiatedEvent_,
- () => this.loaded);
- this.tracker_.add(
- this.pluginController_.getEventTarget(), 'plugin-message',
- e => this.handlePluginMessage_(e));
+ /** @override */
+ getSizer() {
+ return /** @type {!HTMLDivElement} */ (this.$$('#sizer'));
+ }
+
+ /** @override */
+ getZoomToolbar() {
+ return /** @type {!ViewerZoomToolbarElement} */ (this.$$('#zoom-toolbar'));
+ }
- /** @private {!InkController} */
- this.inkController_ = new InkController(this.viewport_);
- this.tracker_.add(
+ /** @override */
+ getErrorScreen() {
+ return /** @type {!ViewerErrorScreenElement} */ (this.$$('#error-screen'));
+ }
+
+ /**
+ * @return {!ViewerPdfToolbarElement}
+ * @private
+ */
+ getToolbar_() {
+ return /** @type {!ViewerPdfToolbarElement} */ (this.$$('#toolbar'));
+ }
+
+ /** @override */
+ getBackgroundColor() {
+ return BACKGROUND_COLOR;
+ }
+
+ /** @param {!BrowserApi} browserApi */
+ init(browserApi) {
+ super.init(browserApi);
+
+ // <if expr="chromeos">
+ this.inkController_ = new InkController(
+ this.viewport, /** @type {!HTMLDivElement} */ (this.getContent()));
+ this.tracker.add(
this.inkController_.getEventTarget(), 'stroke-added',
() => chrome.mimeHandlerPrivate.setShowBeforeUnloadDialog(true));
- this.tracker_.add(
+ this.tracker.add(
this.inkController_.getEventTarget(), 'set-annotation-undo-state',
e => this.setAnnotationUndoState_(e));
+ // </if>
- /** @private {!ContentController} */
- this.currentController_ = this.pluginController_;
-
- // Setup the button event listeners.
- /** @private {!ViewerZoomToolbarElement} */
- this.zoomToolbar_ =
- /** @type {!ViewerZoomToolbarElement} */ ($('zoom-toolbar'));
- this.zoomToolbar_.isPrintPreview = this.isPrintPreview_;
- this.zoomToolbar_.addEventListener(
- 'fit-to-changed',
- e => this.fitToChanged_(
- /** @type {!CustomEvent<FitToChangedEvent>} */ (e)));
- this.zoomToolbar_.addEventListener(
- 'two-up-view-changed',
- e => this.twoUpViewChanged_(
- /** @type {!CustomEvent<!TwoUpViewAction>} */ (e)));
- this.zoomToolbar_.addEventListener(
- 'zoom-in', () => this.viewport_.zoomIn());
- this.zoomToolbar_.addEventListener(
- 'zoom-out', () => this.viewport_.zoomOut());
-
- /** @private {!GestureDetector} */
- this.gestureDetector_ = new GestureDetector(assert($('content')));
- this.gestureDetector_.addEventListener(
- 'pinchstart', e => this.onPinchStart_(e));
- this.sentPinchEvent_ = false;
- this.gestureDetector_.addEventListener(
- 'pinchupdate', e => this.onPinchUpdate_(e));
- this.gestureDetector_.addEventListener(
- 'pinchend', e => this.onPinchEnd_(e));
-
- /** @private {?ViewerPdfToolbarElement} */
- this.toolbar_ = null;
- if (toolbarEnabled) {
- this.toolbar_ = /** @type {!ViewerPdfToolbarElement} */ ($('toolbar'));
- this.toolbar_.hidden = false;
- this.toolbar_.addEventListener('save', () => this.save_());
- this.toolbar_.addEventListener('print', () => this.print_());
- this.toolbar_.addEventListener(
- 'undo', () => this.currentController_.undo());
- this.toolbar_.addEventListener(
- 'redo', () => this.currentController_.redo());
- this.toolbar_.addEventListener(
- 'rotate-right', () => this.rotateClockwise_());
- this.toolbar_.addEventListener('annotation-mode-toggled', e => {
- this.annotationModeToggled_(
- /** @type {!CustomEvent<{value: boolean}>} */ (e));
- });
- this.toolbar_.addEventListener(
- 'annotation-tool-changed',
- e => this.inkController_.setAnnotationTool(e.detail.value));
-
- this.toolbar_.docTitle = getFilenameFromURL(this.originalUrl_);
+ this.title_ = getFilenameFromURL(this.originalUrl);
+ if (this.toolbarEnabled_) {
+ this.getToolbar_().hidden = false;
}
document.body.addEventListener('change-page', e => {
- this.viewport_.goToPage(e.detail.page);
+ this.viewport.goToPage(e.detail.page);
if (e.detail.origin === 'bookmark') {
PDFMetrics.record(PDFMetrics.UserAction.FOLLOW_BOOKMARK);
} else if (e.detail.origin === 'pageselector') {
@@ -387,12 +272,8 @@ export class PDFViewer {
}
});
- document.body.addEventListener('change-zoom', e => {
- this.viewport_.setZoom(e.detail.zoom);
- });
-
document.body.addEventListener('change-page-and-xy', e => {
- const point = this.viewport_.convertPageToScreen(e.detail.page, e.detail);
+ const point = this.viewport.convertPageToScreen(e.detail.page, e.detail);
this.goToPageAndXY_(e.detail.origin, e.detail.page, point);
});
@@ -409,59 +290,21 @@ export class PDFViewer {
}
});
- /** @private {!ToolbarManager} */
- this.toolbarManager_ =
- new ToolbarManager(window, this.toolbar_, this.zoomToolbar_);
-
- // Set up the ZoomManager.
- /** @private {!ZoomManager} */
- this.zoomManager_ = ZoomManager.create(
- this.browserApi_.getZoomBehavior(), () => this.viewport_.getZoom(),
- zoom => this.browserApi_.setZoom(zoom),
- this.browserApi_.getInitialZoom());
- this.viewport_.setZoomManager(this.zoomManager_);
- this.browserApi_.addZoomEventListener(
- zoom => this.zoomManager_.onBrowserZoomChange(zoom));
+ this.toolbarManager_ = new ToolbarManager(
+ window, this.pdfViewerUpdateEnabled_ ? null : this.getToolbar_(),
+ this.getZoomToolbar());
// Setup the keyboard event listener.
document.addEventListener(
'keydown',
e => this.handleKeyEvent_(/** @type {!KeyboardEvent} */ (e)));
- document.addEventListener('mousemove', e => this.handleMouseEvent_(e));
- document.addEventListener('mouseout', e => this.handleMouseEvent_(e));
- document.addEventListener(
- 'contextmenu', e => this.handleContextMenuEvent_(e));
- const tabId = this.browserApi_.getStreamInfo().tabId;
- /** @private {!PdfNavigator} */
+ const tabId = this.browserApi.getStreamInfo().tabId;
this.navigator_ = new PdfNavigator(
- this.originalUrl_, this.viewport_, this.paramsParser_,
+ this.originalUrl, this.viewport,
+ /** @type {!OpenPdfParamsParser} */ (this.paramsParser),
new NavigatorDelegate(tabId));
- /** @private {!ViewportScroller} */
- this.viewportScroller_ =
- new ViewportScroller(this.viewport_, this.plugin_, window);
-
- /** @private {!Array<!Bookmark>} */
- this.bookmarks_;
-
- /** @private {!Point} */
- this.lastViewportPosition_;
-
- /** @private {boolean} */
- this.inPrintPreviewMode_;
-
- /** @private {boolean} */
- this.dark_;
-
- /** @private {!DocumentDimensionsMessageData} */
- this.documentDimensions_;
-
- // Request translated strings.
- chrome.resourcesPrivate.getStrings(
- chrome.resourcesPrivate.Component.PDF,
- strings => this.handleStrings_(strings));
-
// Listen for save commands from the browser.
if (chrome.mimeHandlerPrivate && chrome.mimeHandlerPrivate.onSave) {
chrome.mimeHandlerPrivate.onSave.addListener(url => this.onSave_(url));
@@ -475,168 +318,57 @@ export class PDFViewer {
* @private
*/
handleKeyEvent_(e) {
- const position = this.viewport_.position;
- // Certain scroll events may be sent from outside of the extension.
- const fromScriptingAPI = e.fromScriptingAPI;
-
if (shouldIgnoreKeyEvents(document.activeElement) || e.defaultPrevented) {
return;
}
this.toolbarManager_.hideToolbarsAfterTimeout();
- const pageUpHandler = () => {
- // Go to the previous page if we are fit-to-page or fit-to-height.
- if (this.viewport_.isPagedMode()) {
- this.viewport_.goToPreviousPage();
- // Since we do the movement of the page.
- e.preventDefault();
- } else if (fromScriptingAPI) {
- position.y -= this.viewport_.size.height;
- this.viewport_.position = position;
- }
- };
- const pageDownHandler = () => {
- // Go to the next page if we are fit-to-page or fit-to-height.
- if (this.viewport_.isPagedMode()) {
- this.viewport_.goToNextPage();
- // Since we do the movement of the page.
- e.preventDefault();
- } else if (fromScriptingAPI) {
- position.y += this.viewport_.size.height;
- this.viewport_.position = position;
- }
- };
+ // Let the viewport handle directional key events.
+ if (this.viewport.handleDirectionalKeyEvent(e, this.isFormFieldFocused_)) {
+ return;
+ }
- switch (e.keyCode) {
- case 9: // Tab key.
+ switch (e.key) {
+ case 'Tab':
this.toolbarManager_.showToolbarsForKeyboardNavigation();
return;
- case 27: // Escape key.
- if (!this.isPrintPreview_) {
- this.toolbarManager_.hideSingleToolbarLayer();
- return;
- }
- break; // Ensure escape falls through to the print-preview handler.
- case 32: // Space key.
- if (e.shiftKey) {
- pageUpHandler();
- } else {
- pageDownHandler();
- }
- return;
- case 33: // Page up key.
- pageUpHandler();
- return;
- case 34: // Page down key.
- pageDownHandler();
- return;
- case 37: // Left arrow key.
- if (!hasKeyModifiers(e)) {
- // Go to the previous page if there are no horizontal scrollbars and
- // no form field is focused.
- if (!(this.viewport_.documentHasScrollbars().horizontal ||
- this.isFormFieldFocused_)) {
- this.viewport_.goToPreviousPage();
- // Since we do the movement of the page.
- e.preventDefault();
- } else if (fromScriptingAPI) {
- position.x -= Viewport.SCROLL_INCREMENT;
- this.viewport_.position = position;
- }
- }
+ case 'Escape':
+ this.toolbarManager_.hideSingleToolbarLayer();
return;
- case 38: // Up arrow key.
- if (fromScriptingAPI) {
- position.y -= Viewport.SCROLL_INCREMENT;
- this.viewport_.position = position;
- }
- return;
- case 39: // Right arrow key.
- if (!hasKeyModifiers(e)) {
- // Go to the next page if there are no horizontal scrollbars and no
- // form field is focused.
- if (!(this.viewport_.documentHasScrollbars().horizontal ||
- this.isFormFieldFocused_)) {
- this.viewport_.goToNextPage();
- // Since we do the movement of the page.
- e.preventDefault();
- } else if (fromScriptingAPI) {
- position.x += Viewport.SCROLL_INCREMENT;
- this.viewport_.position = position;
- }
- }
- return;
- case 40: // Down arrow key.
- if (fromScriptingAPI) {
- position.y += Viewport.SCROLL_INCREMENT;
- this.viewport_.position = position;
- }
- return;
- case 65: // 'a' key.
+ case 'a':
if (e.ctrlKey || e.metaKey) {
- this.pluginController_.selectAll();
+ this.pluginController.selectAll();
// Since we do selection ourselves.
e.preventDefault();
}
return;
- case 71: // 'g' key.
- if (this.toolbar_ && (e.ctrlKey || e.metaKey) && e.altKey) {
+ case 'g':
+ if (this.toolbarEnabled_ && (e.ctrlKey || e.metaKey) && e.altKey) {
this.toolbarManager_.showToolbars();
- this.toolbar_.selectPageNumber();
+ this.getToolbar_().selectPageNumber();
}
return;
- case 219: // Left bracket key.
+ case '[':
if (e.ctrlKey) {
- this.rotateCounterclockwise_();
+ this.rotateCounterclockwise();
}
return;
- case 220: // Backslash key.
+ case '\\':
if (e.ctrlKey) {
- this.zoomToolbar_.fitToggleFromHotKey();
+ this.getZoomToolbar().fitToggleFromHotKey();
}
return;
- case 221: // Right bracket key.
+ case ']':
if (e.ctrlKey) {
- this.rotateClockwise_();
+ this.rotateClockwise();
}
return;
}
- // Give print preview a chance to handle the key event.
- if (!fromScriptingAPI && this.isPrintPreview_) {
- this.sendScriptingMessage_(
- {type: 'sendKeyEvent', keyEvent: SerializeKeyEvent(e)});
- } else {
- // Show toolbars as a fallback.
- if (!(e.shiftKey || e.ctrlKey || e.altKey)) {
- this.toolbarManager_.showToolbars();
- }
- }
- }
-
- handleMouseEvent_(e) {
- if (e.type === 'mousemove') {
- this.toolbarManager_.handleMouseMove(e);
- } else if (e.type === 'mouseout') {
- this.toolbarManager_.hideToolbarsForMouseOut();
- }
- }
-
- /**
- * @param {!Event} e The context menu event
- * @private
- */
- handleContextMenuEvent_(e) {
- // Stop Chrome from popping up the context menu on long press. We need to
- // make sure the start event did not have 2 touches because we don't want
- // to block two finger tap opening the context menu. We check for
- // firesTouchEvents in order to not block the context menu on right click.
- const capabilities =
- /** @type {{ sourceCapabilities: Object }} */ (e).sourceCapabilities;
- if (capabilities.firesTouchEvents &&
- !this.gestureDetector_.wasTwoFingerTouch()) {
- e.preventDefault();
+ // Show toolbars as a fallback.
+ if (!(e.shiftKey || e.ctrlKey || e.altKey)) {
+ this.toolbarManager_.showToolbars();
}
}
@@ -645,59 +377,61 @@ export class PDFViewer {
* @param {!CustomEvent<{value: boolean}>} e
* @private
*/
- async annotationModeToggled_(e) {
+ async onAnnotationModeToggled_(e) {
const annotationMode = e.detail.value;
- this.zoomToolbar_.annotationMode = annotationMode;
+ this.annotationMode_ = annotationMode;
if (annotationMode) {
// Enter annotation mode.
- assert(this.currentController_ === this.pluginController_);
+ assert(this.currentController === this.pluginController);
// TODO(dstockwell): set plugin read-only, begin transition
- this.updateProgress_(0);
+ this.updateProgress(0);
// TODO(dstockwell): handle save failure
- const saveResult = await this.pluginController_.save(true);
- // Data always exists when save is called with requireResult = true.
+ const saveResult =
+ await this.pluginController.save(SaveRequestType.ANNOTATION);
+ // Data always exists when save is called with requestType = ANNOTATION.
const result = /** @type {!RequiredSaveResult} */ (saveResult);
if (result.hasUnsavedChanges) {
assert(!loadTimeData.getBoolean('pdfFormSaveEnabled'));
try {
- await $('form-warning').show();
+ await this.$$('#form-warning').show();
} catch (e) {
// The user aborted entering annotation mode. Revert to the plugin.
- this.toolbar_.annotationMode = false;
- this.zoomToolbar_.annotationMode = false;
- this.updateProgress_(100);
+ this.getToolbar_().annotationMode = false;
+ this.annotationMode_ = false;
+ this.updateProgress(100);
return;
}
}
PDFMetrics.record(PDFMetrics.UserAction.ENTER_ANNOTATION_MODE);
this.hasEnteredAnnotationMode_ = true;
// TODO(dstockwell): feed real progress data from the Ink component
- this.updateProgress_(50);
+ this.updateProgress(50);
await this.inkController_.load(result.fileName, result.dataToSave);
this.inkController_.setAnnotationTool(
- assert(this.toolbar_.annotationTool));
- this.currentController_ = this.inkController_;
- this.pluginController_.unload();
- this.updateProgress_(100);
+ assert(this.getToolbar_().annotationTool));
+ this.currentController = this.inkController_;
+ this.pluginController.unload();
+ this.updateProgress(100);
} else {
// Exit annotation mode.
PDFMetrics.record(PDFMetrics.UserAction.EXIT_ANNOTATION_MODE);
- assert(this.currentController_ === this.inkController_);
+ assert(this.currentController === this.inkController_);
// TODO(dstockwell): set ink read-only, begin transition
- this.updateProgress_(0);
+ this.updateProgress(0);
// This runs separately to allow other consumers of `loaded` to queue
// up after this task.
this.loaded.then(() => {
- this.currentController_ = this.pluginController_;
+ this.currentController = this.pluginController;
this.inkController_.unload();
});
// TODO(dstockwell): handle save failure
- const saveResult = await this.inkController_.save(true);
- // Data always exists when save is called with requireResult = true.
+ const saveResult =
+ await this.inkController_.save(SaveRequestType.ANNOTATION);
+ // Data always exists when save is called with requestType = ANNOTATION.
const result = /** @type {!RequiredSaveResult} */ (saveResult);
- await this.pluginController_.load(result.fileName, result.dataToSave);
+ await this.pluginController.load(result.fileName, result.dataToSave);
// Ensure the plugin gets the initial viewport.
- this.pluginController_.afterZoom();
+ this.pluginController.afterZoom();
}
}
@@ -706,32 +440,21 @@ export class PDFViewer {
* @return {Promise<void>}
*/
async exitAnnotationMode_() {
- if (!this.toolbar_.annotationMode) {
+ if (!this.getToolbar_().annotationMode) {
return;
}
- this.toolbar_.toggleAnnotation();
- this.zoomToolbar_.annotationMode = false;
+ this.getToolbar_().toggleAnnotation();
+ this.annotationMode_ = false;
await this.loaded;
}
- /**
- * Request to change the viewport fitting type.
- * @param {!CustomEvent<FitToChangedEvent>} e
- * @private
- */
- fitToChanged_(e) {
- if (e.detail.fittingType === FittingType.FIT_TO_PAGE) {
- this.viewport_.fitToPage();
- this.toolbarManager_.forceHideTopToolbar();
- } else if (e.detail.fittingType === FittingType.FIT_TO_WIDTH) {
- this.viewport_.fitToWidth();
- } else if (e.detail.fittingType === FittingType.FIT_TO_HEIGHT) {
- this.viewport_.fitToHeight();
- this.toolbarManager_.forceHideTopToolbar();
- }
+ /** @override */
+ onFitToChanged(e) {
+ super.onFitToChanged(e);
- if (e.detail.userInitiated) {
- PDFMetrics.recordFitTo(e.detail.fittingType);
+ if (e.detail.fittingType === FittingType.FIT_TO_PAGE ||
+ e.detail.fittingType === FittingType.FIT_TO_HEIGHT) {
+ this.toolbarManager_.forceHideTopToolbar();
}
}
@@ -741,70 +464,17 @@ export class PDFViewer {
* @param {!CustomEvent<!TwoUpViewAction>} e
* @private
*/
- twoUpViewChanged_(e) {
- this.currentController_.setTwoUpView(
+ onTwoUpViewChanged_(e) {
+ this.currentController.setTwoUpView(
e.detail === TwoUpViewAction.TWO_UP_VIEW_ENABLE);
this.toolbarManager_.forceHideTopToolbar();
- this.toolbar_.annotationAvailable =
+ this.getToolbar_().annotationAvailable =
(e.detail !== TwoUpViewAction.TWO_UP_VIEW_ENABLE);
PDFMetrics.recordTwoUpView(e.detail);
}
/**
- * Sends a 'documentLoaded' message to the PDFScriptingAPI if the document has
- * finished loading.
- * @private
- */
- sendDocumentLoadedMessage_() {
- if (this.loadState_ === LoadState.LOADING) {
- return;
- }
- if (this.isPrintPreview_ && !this.isPrintPreviewLoadingFinished_) {
- return;
- }
- this.sendScriptingMessage_(
- {type: 'documentLoaded', load_state: this.loadState_});
- }
-
- /**
- * Handle open pdf parameters. This function updates the viewport as per
- * the parameters mentioned in the url while opening pdf. The order is
- * important as later actions can override the effects of previous actions.
- * @param {Object} params The open params passed in the URL.
- * @private
- */
- handleURLParams_(params) {
- if (params.zoom) {
- this.viewport_.setZoom(params.zoom);
- }
-
- if (params.position) {
- this.viewport_.goToPageAndXY(
- params.page ? params.page : 0, params.position.x, params.position.y);
- } else if (params.page) {
- this.viewport_.goToPage(params.page);
- }
-
- if (params.view) {
- this.isUserInitiatedEvent_ = false;
- this.zoomToolbar_.forceFit(params.view);
- if (params.viewPosition) {
- const zoomedPositionShift =
- params.viewPosition * this.viewport_.getZoom();
- const currentViewportPosition = this.viewport_.position;
- if (params.view === FittingType.FIT_TO_WIDTH) {
- currentViewportPosition.y += zoomedPositionShift;
- } else if (params.view === FittingType.FIT_TO_HEIGHT) {
- currentViewportPosition.x += zoomedPositionShift;
- }
- this.viewport_.position = currentViewportPosition;
- }
- this.isUserInitiatedEvent_ = true;
- }
- }
-
- /**
* Moves the viewport to a point in a page. Called back after a
* 'transformPagePointReply' is returned from the plugin.
* @param {string} origin Identifier for the caller for logging purposes.
@@ -814,146 +484,38 @@ export class PDFViewer {
* @private
*/
goToPageAndXY_(origin, page, message) {
- this.viewport_.goToPageAndXY(page, message.x, message.y);
+ this.viewport.goToPageAndXY(page, message.x, message.y);
if (origin === 'bookmark') {
PDFMetrics.record(PDFMetrics.UserAction.FOLLOW_BOOKMARK);
}
}
- /**
- * @return {?Promise} Resolved when the load state reaches LOADED,
- * rejects on FAILED. Returns null if no promise has been created, which
- * is the case for initial load of the PDF.
- */
- get loaded() {
- return this.loaded_ ? this.loaded_.promise : null;
- }
-
/** @return {!Viewport} The viewport. Used for testing. */
- get viewport() {
- return this.viewport_;
- }
-
/** @return {!Array<!Bookmark>} The bookmarks. Used for testing. */
get bookmarks() {
return this.bookmarks_;
}
- /**
- * Updates the load state and triggers completion of the `loaded`
- * promise if necessary.
- * @param {!LoadState} loadState
- * @private
- */
- setLoadState_(loadState) {
- if (this.loadState_ === loadState) {
- return;
- }
- assert(
- loadState === LoadState.LOADING ||
- this.loadState_ === LoadState.LOADING);
- this.loadState_ = loadState;
- if (!this.initialLoadComplete_) {
- this.initialLoadComplete_ = true;
- return;
- }
- if (loadState === LoadState.SUCCESS) {
- this.loaded_.resolve();
- } else if (loadState === LoadState.FAILED) {
- this.loaded_.reject();
- } else {
- this.loaded_ = new PromiseResolver();
- }
- }
-
- /**
- * Update the loading progress of the document in response to a progress
- * message being received from the content controller.
- * @param {number} progress the progress as a percentage.
- * @private
- */
- updateProgress_(progress) {
- if (this.toolbar_) {
- this.toolbar_.loadProgress = progress;
- }
-
- if (progress === -1) {
- // Document load failed.
- this.errorScreen_.show();
- this.sizer_.style.display = 'none';
- if (this.passwordScreen_ && this.passwordScreen_.active) {
- this.passwordScreen_.deny();
- this.passwordScreen_.close();
- }
- this.setLoadState_(LoadState.FAILED);
- this.isPrintPreviewLoadingFinished_ = true;
- this.sendDocumentLoadedMessage_();
- } else if (progress === 100) {
- // Document load complete.
- if (this.lastViewportPosition_) {
- this.viewport_.position = this.lastViewportPosition_;
+ /** @override */
+ setLoadState(loadState) {
+ super.setLoadState(loadState);
+ if (loadState === LoadState.FAILED) {
+ const passwordScreen = this.$$('#password-screen');
+ if (passwordScreen && passwordScreen.active) {
+ passwordScreen.deny();
+ passwordScreen.close();
}
- this.paramsParser_.getViewportFromUrlParams(
- this.originalUrl_, params => this.handleURLParams_(params));
- this.setLoadState_(LoadState.SUCCESS);
- this.sendDocumentLoadedMessage_();
- while (this.delayedScriptingMessages_.length > 0) {
- this.handleScriptingMessage(this.delayedScriptingMessages_.shift());
- }
-
- this.toolbarManager_.hideToolbarsAfterTimeout();
- } else {
- this.setLoadState_(LoadState.LOADING);
}
}
- /** @private */
- sendBackgroundColorForPrintPreview_() {
- this.pluginController_.backgroundColorChanged(
- this.dark_ ? PDFViewer.PRINT_PREVIEW_DARK_BACKGROUND_COLOR :
- PDFViewer.PRINT_PREVIEW_BACKGROUND_COLOR);
- }
-
- /**
- * Load a dictionary of translated strings into the UI. Used as a callback for
- * chrome.resourcesPrivate.
- * @param {Object} strings Dictionary of translated strings
- * @private
- */
- handleStrings_(strings) {
- const stringsDictionary =
- /** @type {{ textdirection: string, language: string }} */ (strings);
- document.documentElement.dir = stringsDictionary.textdirection;
- document.documentElement.lang = stringsDictionary.language;
-
- loadTimeData.data = strings;
-
- // Predefined zoom factors to be used when zooming in/out. These are in
- // ascending order.
- const presetZoomFactors = /** @type {!Array<number>} */ (
- JSON.parse(loadTimeData.getString('presetZoomFactors')));
- this.viewport_.setZoomFactorRange(presetZoomFactors);
-
- if (this.isPrintPreview_) {
- this.sendBackgroundColorForPrintPreview_();
- } else {
- $('toolbar').strings = strings;
- $('toolbar').pdfAnnotationsEnabled =
- loadTimeData.getBoolean('pdfAnnotationsEnabled');
- $('toolbar').printingEnabled = loadTimeData.getBoolean('printingEnabled');
- }
- $('zoom-toolbar').setStrings(strings);
- $('zoom-toolbar').twoUpViewEnabled =
- loadTimeData.getBoolean('pdfTwoUpViewEnabled') && !this.isPrintPreview_;
- // Display the zoom toolbar after the UI text direction is set, to ensure it
- // appears on the correct side of the PDF viewer.
- $('zoom-toolbar').hidden = false;
- if (this.passwordScreen_) {
- $('password-screen').strings = strings;
+ /** @override */
+ updateProgress(progress) {
+ if (this.toolbarEnabled_) {
+ this.getToolbar_().loadProgress = progress;
}
- $('error-screen').strings = strings;
- if ($('form-warning')) {
- $('form-warning').strings = strings;
+ super.updateProgress(progress);
+ if (progress === 100) {
+ this.toolbarManager_.hideToolbarsAfterTimeout();
}
}
@@ -964,73 +526,14 @@ export class PDFViewer {
* @private
*/
onPasswordSubmitted_(event) {
- this.pluginController_.getPasswordComplete(event.detail.password);
- }
-
- /**
- * A callback that sets |isUserInitiatedEvent_| to |userInitiated|.
- * @param {boolean} userInitiated The value to set |isUserInitiatedEvent_| to.
- * @private
- */
- setUserInitiated_(userInitiated) {
- assert(this.isUserInitiatedEvent_ !== userInitiated);
- this.isUserInitiatedEvent_ = userInitiated;
- }
-
- /**
- * A callback that's called when an update to a pinch zoom is detected.
- * @param {!Object} e the pinch event.
- * @private
- */
- onPinchUpdate_(e) {
- // Throttle number of pinch events to one per frame.
- if (!this.sentPinchEvent_) {
- this.sentPinchEvent_ = true;
- window.requestAnimationFrame(() => {
- this.sentPinchEvent_ = false;
- this.viewport_.pinchZoom(e);
- });
- }
- }
-
- /**
- * A callback that's called when the end of a pinch zoom is detected.
- * @param {!Object} e the pinch event.
- * @private
- */
- onPinchEnd_(e) {
- // Using rAF for pinch end prevents pinch updates scheduled by rAF getting
- // sent after the pinch end.
- window.requestAnimationFrame(() => {
- this.viewport_.pinchZoomEnd(e);
- });
+ this.pluginController.getPasswordComplete(event.detail.password);
}
- /**
- * A callback that's called when the start of a pinch zoom is detected.
- * @param {!Object} e the pinch event.
- * @private
- */
- onPinchStart_(e) {
- // We also use rAF for pinch start, so that if there is a pinch end event
- // scheduled by rAF, this pinch start will be sent after.
- window.requestAnimationFrame(() => {
- this.viewport_.pinchZoomStart(e);
- });
- }
-
- /**
- * A callback that's called after the viewport changes.
- * @private
- */
- viewportChanged_() {
- if (!this.documentDimensions_) {
- return;
- }
-
+ /** @override */
+ updateUIForViewportChange() {
// Offset the toolbar position so that it doesn't move if scrollbars appear.
- const hasScrollbars = this.viewport_.documentHasScrollbars();
- const scrollbarWidth = this.viewport_.scrollbarWidth;
+ const hasScrollbars = this.viewport.documentHasScrollbars();
+ const scrollbarWidth = this.viewport.scrollbarWidth;
const verticalScrollbarWidth = hasScrollbars.vertical ? scrollbarWidth : 0;
const horizontalScrollbarWidth =
hasScrollbars.horizontal ? scrollbarWidth : 0;
@@ -1039,217 +542,70 @@ export class PDFViewer {
// gives a compromise: if there is no scrollbar visible then the toolbar
// will be half a scrollbar width further left than the spec but if there
// is a scrollbar visible it will be half a scrollbar width further right
- // than the spec. In RTL layout normally, and in LTR layout in Print Preview
- // when the NewPrintPreview flag is enabled, the zoom toolbar is on the left
+ // than the spec. In RTL layout normally, the zoom toolbar is on the left
// left side, but the scrollbar is still on the right, so this is not
// necessary.
- if (isRTL() === this.isPrintPreview_) {
- this.zoomToolbar_.style.right =
+ const zoomToolbar = this.getZoomToolbar();
+ if (!isRTL()) {
+ zoomToolbar.style.right =
-verticalScrollbarWidth + (scrollbarWidth / 2) + 'px';
}
// Having a horizontal scrollbar is much rarer so we don't offset the
// toolbar from the bottom any more than what the spec says. This means
// that when there is a scrollbar visible, it will be a full scrollbar
// width closer to the bottom of the screen than usual, but this is ok.
- this.zoomToolbar_.style.bottom = -horizontalScrollbarWidth + 'px';
+ zoomToolbar.style.bottom = -horizontalScrollbarWidth + 'px';
// Update the page indicator.
- const visiblePage = this.viewport_.getMostVisiblePage();
-
- if (this.toolbar_) {
- this.toolbar_.pageNo = visiblePage + 1;
- }
-
- // TODO(raymes): Give pageIndicator_ the same API as toolbar_.
- if (this.pageIndicator_) {
- const lastIndex = this.pageIndicator_.index;
- this.pageIndicator_.index = visiblePage;
- if (this.documentDimensions_.pageDimensions.length > 1 &&
- hasScrollbars.vertical && lastIndex !== undefined) {
- this.pageIndicator_.style.visibility = 'visible';
- } else {
- this.pageIndicator_.style.visibility = 'hidden';
- }
+ const visiblePage = this.viewport.getMostVisiblePage();
+ if (this.toolbarEnabled_) {
+ this.getToolbar_().pageNo = visiblePage + 1;
}
- this.currentController_.viewportChanged();
-
- const visiblePageDimensions = this.viewport_.getPageScreenRect(visiblePage);
- const size = this.viewport_.size;
- this.sendScriptingMessage_({
- type: 'viewport',
- pageX: visiblePageDimensions.x,
- pageY: visiblePageDimensions.y,
- pageWidth: visiblePageDimensions.width,
- viewportWidth: size.width,
- viewportHeight: size.height
- });
+ this.currentController.viewportChanged();
}
- /**
- * Handle a scripting message from outside the extension (typically sent by
- * PDFScriptingAPI in a page containing the extension) to interact with the
- * plugin.
- * @param {!MessageObject} message The message to handle.
- */
+ /** @override */
handleScriptingMessage(message) {
- if (this.parentWindow_ !== message.source) {
- this.parentWindow_ = message.source;
- this.parentOrigin_ = message.origin;
- // Ensure that we notify the embedder if the document is loaded.
- if (this.loadState_ !== LoadState.LOADING) {
- this.sendDocumentLoadedMessage_();
- }
- }
+ super.handleScriptingMessage(message);
- if (this.handlePrintPreviewScriptingMessage_(message)) {
- return;
- }
-
- // Delay scripting messages from users of the scripting API until the
- // document is loaded. This simplifies use of the APIs.
- if (this.loadState_ !== LoadState.SUCCESS) {
- this.delayedScriptingMessages_.push(message);
+ if (this.delayScriptingMessage(message)) {
return;
}
switch (message.data.type.toString()) {
case 'getSelectedText':
- this.pluginController_.getSelectedText();
+ this.pluginController.getSelectedText();
break;
case 'print':
- this.pluginController_.print();
+ this.pluginController.print();
break;
case 'selectAll':
- this.pluginController_.selectAll();
+ this.pluginController.selectAll();
break;
}
}
- /**
- * Handle scripting messages specific to print preview.
- * @param {!MessageObject} message the message to handle.
- * @return {boolean} true if the message was handled, false otherwise.
- * @private
- */
- handlePrintPreviewScriptingMessage_(message) {
- if (!this.isPrintPreview_) {
- return false;
- }
-
- let messageData = message.data;
- switch (messageData.type.toString()) {
- case 'loadPreviewPage':
- messageData =
- /** @type {{ url: string, index: number }} */ (messageData);
- this.pluginController_.loadPreviewPage(
- messageData.url, messageData.index);
- return true;
- case 'resetPrintPreviewMode':
- messageData = /** @type {!PrintPreviewParams} */ (messageData);
- this.setLoadState_(LoadState.LOADING);
- if (!this.inPrintPreviewMode_) {
- this.inPrintPreviewMode_ = true;
- this.isUserInitiatedEvent_ = false;
- this.zoomToolbar_.forceFit(FittingType.FIT_TO_PAGE);
- this.isUserInitiatedEvent_ = true;
- }
-
- // Stash the scroll location so that it can be restored when the new
- // document is loaded.
- this.lastViewportPosition_ = this.viewport_.position;
-
- // TODO(raymes): Disable these properly in the plugin.
- const printButton = $('print-button');
- if (printButton) {
- printButton.parentNode.removeChild(printButton);
- }
- const saveButton = $('save-button');
- if (saveButton) {
- saveButton.parentNode.removeChild(saveButton);
- }
-
- this.pageIndicator_.pageLabels = messageData.pageNumbers;
-
- this.pluginController_.resetPrintPreviewMode(messageData);
- return true;
- case 'sendKeyEvent':
- this.handleKeyEvent_(/** @type {!KeyboardEvent} */ (DeserializeKeyEvent(
- /** @type {{ keyEvent: Object }} */ (message.data).keyEvent)));
- return true;
- case 'hideToolbars':
- this.toolbarManager_.resetKeyboardNavigationAndHideToolbars();
- return true;
- case 'darkModeChanged':
- this.dark_ = /** @type {{darkMode: boolean}} */ (message.data).darkMode;
- if (this.isPrintPreview_) {
- this.sendBackgroundColorForPrintPreview_();
- }
- return true;
- case 'scrollPosition':
- const position = this.viewport_.position;
- messageData = /** @type {{ x: number, y: number }} */ (message.data);
- position.y += messageData.y;
- position.x += messageData.x;
- this.viewport_.position = position;
- return true;
- }
-
- return false;
- }
-
- /**
- * Send a scripting message outside the extension (typically to
- * PDFScriptingAPI in a page containing the extension).
- * @param {Object} message the message to send.
- * @private
- */
- sendScriptingMessage_(message) {
- if (this.parentWindow_ && this.parentOrigin_) {
- let targetOrigin;
- // Only send data back to the embedder if it is from the same origin,
- // unless we're sending it to ourselves (which could happen in the case
- // of tests). We also allow documentLoaded messages through as this won't
- // leak important information.
- if (this.parentOrigin_ === window.location.origin) {
- targetOrigin = this.parentOrigin_;
- } else if (message.type === 'documentLoaded') {
- targetOrigin = '*';
- } else {
- targetOrigin = this.originalUrl_;
- }
- try {
- this.parentWindow_.postMessage(message, targetOrigin);
- } catch (ok) {
- // TODO(crbug.com/1004425): targetOrigin probably was rejected, such as
- // a "data:" URL. This shouldn't cause this method to throw, though.
- }
- }
- }
-
- /**
- * @param {!CustomEvent<MessageData>} e
- * @private
- */
- handlePluginMessage_(e) {
+ /** @override */
+ handlePluginMessage(e) {
const data = e.detail;
switch (data.type.toString()) {
case 'beep':
this.handleBeep_();
return;
case 'documentDimensions':
- this.setDocumentDimensions_(
+ this.setDocumentDimensions(
/** @type {!DocumentDimensionsMessageData} */ (data));
return;
case 'getPassword':
this.handlePasswordRequest_();
return;
case 'getSelectedTextReply':
- this.handleSelectedTextReply_(
+ this.handleSelectedTextReply(
/** @type {{ selectedText: string }} */ (data).selectedText);
return;
case 'loadProgress':
- this.updateProgress_(
+ this.updateProgress(
/** @type {{ progress: number }} */ (data).progress);
return;
case 'navigate':
@@ -1258,52 +614,56 @@ export class PDFViewer {
return;
case 'navigateToDestination':
const destinationData = /** @type {!DestinationMessageData} */ (data);
- this.handleNavigateToDestination_(
+ this.viewport.handleNavigateToDestination(
destinationData.page, destinationData.x, destinationData.y,
destinationData.zoom);
return;
- case 'printPreviewLoaded':
- this.handlePrintPreviewLoaded_();
- return;
case 'metadata':
const metadata = /** @type {!MetadataMessageData} */ (data);
this.setDocumentMetadata_(
metadata.title, metadata.bookmarks, metadata.canSerializeDocument);
return;
+ case 'setIsEditing':
+ // Editing mode can only be entered once, and cannot be exited.
+ this.hasEdits_ = true;
+ return;
case 'setIsSelecting':
- this.setIsSelecting_(
+ this.viewportScroller.setEnableScrolling(
/** @type {{ isSelecting: boolean }} */ (data).isSelecting);
return;
case 'getNamedDestinationReply':
- this.paramsParser_.onNamedDestinationReceived(
+ this.paramsParser.onNamedDestinationReceived(
/** @type {{ pageNumber: number }} */ (data).pageNumber);
return;
case 'formFocusChange':
this.isFormFieldFocused_ =
/** @type {{ focused: boolean }} */ (data).focused;
return;
+ case 'touchSelectionOccurred':
+ this.sendScriptingMessage({
+ type: 'touchSelectionOccurred',
+ });
+ return;
+ case 'documentFocusChanged':
+ // TODO(crbug.com/1069370): Draw a focus rect around plugin.
+ return;
}
assertNotReached('Unknown message type received: ' + data.type);
}
- /**
- * Sets document dimensions from the current controller.
- * @param {!DocumentDimensionsMessageData} documentDimensions
- * @private
- */
- setDocumentDimensions_(documentDimensions) {
- this.documentDimensions_ = documentDimensions;
- this.isUserInitiatedEvent_ = false;
- this.viewport_.setDocumentDimensions(this.documentDimensions_);
- this.isUserInitiatedEvent_ = true;
+ /** @override */
+ setDocumentDimensions(documentDimensions) {
+ super.setDocumentDimensions(documentDimensions);
// If we received the document dimensions, the password was good so we
// can dismiss the password screen.
- if (this.passwordScreen_ && this.passwordScreen_.active) {
- this.passwordScreen_.close();
+ const passwordScreen = this.$$('#password-screen');
+ if (passwordScreen && passwordScreen.active) {
+ passwordScreen.close();
}
- if (this.toolbar_) {
- this.toolbar_.docLength = this.documentDimensions_.pageDimensions.length;
+ if (this.toolbarEnabled_) {
+ this.getToolbar_().docLength =
+ this.documentDimensions.pageDimensions.length;
}
}
@@ -1323,74 +683,24 @@ export class PDFViewer {
handlePasswordRequest_() {
// If the password screen isn't up, put it up. Otherwise we're
// responding to an incorrect password so deny it.
- assert(!!this.passwordScreen_);
- if (!this.passwordScreen_.active) {
+ const passwordScreen = this.$$('#password-screen');
+ assert(passwordScreen);
+ if (!passwordScreen.active) {
this.hadPassword_ = true;
- this.updateAnnotationAvailable_();
- this.passwordScreen_.show();
+ passwordScreen.show();
} else {
- this.passwordScreen_.deny();
+ passwordScreen.deny();
}
}
/**
- * Handles a selected text reply from the current controller.
- * @param {string} selectedText
- * @private
- */
- handleSelectedTextReply_(selectedText) {
- this.sendScriptingMessage_({
- type: 'getSelectedTextReply',
- selectedText: selectedText,
- });
- }
-
- /**
* Handles a navigation request from the current controller.
* @param {string} url
* @param {!PdfNavigator.WindowOpenDisposition} disposition
* @private
*/
handleNavigate_(url, disposition) {
- // If in print preview, always open a new tab.
- if (this.isPrintPreview_) {
- this.navigator_.navigate(
- url, PdfNavigator.WindowOpenDisposition.NEW_BACKGROUND_TAB);
- } else {
- this.navigator_.navigate(url, disposition);
- }
- }
-
- /**
- * Handles an internal navigation request to a destination from the current
- * controller.
- *
- * @param {number} page
- * @param {number} x
- * @param {number} y
- * @param {number} zoom
- * @private
- */
- handleNavigateToDestination_(page, x, y, zoom) {
- if (zoom) {
- this.viewport_.setZoom(zoom);
- }
-
- if (x || y) {
- this.viewport_.goToPageAndXY(page, x ? x : 0, y ? y : 0);
- } else {
- this.viewport_.goToPage(page);
- }
- }
-
- /**
- * Handles a notification that print preview has loaded from the
- * current controller.
- * @private
- */
- handlePrintPreviewLoaded_() {
- this.isPrintPreviewLoadingFinished_ = true;
- this.sendDocumentLoadedMessage_();
+ this.navigator_.navigate(url, disposition);
}
/**
@@ -1401,27 +711,10 @@ export class PDFViewer {
* @private
*/
setDocumentMetadata_(title, bookmarks, canSerializeDocument) {
- if (title) {
- document.title = title;
- } else {
- document.title = getFilenameFromURL(this.originalUrl_);
- }
+ this.title_ = title ? title : getFilenameFromURL(this.originalUrl);
+ document.title = this.title_;
this.bookmarks_ = bookmarks;
- if (this.toolbar_) {
- this.toolbar_.docTitle = document.title;
- this.toolbar_.bookmarks = this.bookmarks_;
- }
this.canSerializeDocument_ = canSerializeDocument;
- this.updateAnnotationAvailable_();
- }
-
- /**
- * Sets the is selecting flag from the current controller.
- * @param {boolean} isSelecting
- * @private
- */
- setIsSelecting_(isSelecting) {
- this.viewportScroller_.setEnableScrolling(isSelecting);
}
/**
@@ -1431,28 +724,58 @@ export class PDFViewer {
* @private
*/
async onSave_(streamUrl) {
- if (streamUrl !== this.browserApi_.getStreamInfo().streamUrl) {
+ if (streamUrl !== this.browserApi.getStreamInfo().streamUrl) {
return;
}
- this.save_();
+ let saveMode;
+ if (this.hasEnteredAnnotationMode_) {
+ saveMode = SaveRequestType.ANNOTATION;
+ } else if (
+ loadTimeData.getBoolean('pdfFormSaveEnabled') && this.hasEdits_) {
+ saveMode = SaveRequestType.EDITED;
+ } else {
+ saveMode = SaveRequestType.ORIGINAL;
+ }
+
+ this.save_(saveMode);
+ }
+
+ /**
+ * @param {!CustomEvent<!SaveRequestType>} e
+ * @private
+ */
+ onToolbarSave_(e) {
+ this.save_(e.detail);
}
/**
* Saves the current PDF document to disk.
+ * @param {SaveRequestType} requestType The type of save request.
* @private
*/
- async save_() {
+ async save_(requestType) {
PDFMetrics.record(PDFMetrics.UserAction.SAVE);
- if (this.hasEnteredAnnotationMode_) {
+ // If we have entered annotation mode we must require the local
+ // contents to ensure annotations are saved, unless the user specifically
+ // requested the original document. Otherwise we would save the cached
+ // remote copy without annotations.
+ if (requestType === SaveRequestType.ANNOTATION) {
PDFMetrics.record(PDFMetrics.UserAction.SAVE_WITH_ANNOTATION);
}
- // If we have entered annotation mode we must require the local
- // contents to ensure annotations are saved. Otherwise we would
- // save the cached or remote copy without annotatios.
- const requireResult = this.hasEnteredAnnotationMode_;
+ // Always send requests of type ORIGINAL to the plugin controller, not the
+ // ink controller. The ink controller always saves the edited document.
// TODO(dstockwell): Report an error to user if this fails.
- const result = await this.currentController_.save(requireResult);
+ let result;
+ if (requestType !== SaveRequestType.ORIGINAL || !this.annotationMode_) {
+ result = await this.currentController.save(requestType);
+ } else {
+ // Request type original in annotation mode --> need to exit annotation
+ // mode before saving. See https://crbug.com/919364.
+ await this.exitAnnotationMode_();
+ assert(!this.annotationMode_);
+ result = await this.currentController.save(SaveRequestType.ORIGINAL);
+ }
if (result == null) {
// The content controller handled the save internally.
return;
@@ -1465,7 +788,12 @@ export class PDFViewer {
}
chrome.fileSystem.chooseEntry(
- {type: 'saveFile', suggestedName: fileName}, entry => {
+ {
+ type: 'saveFile',
+ accepts: [{description: '*.pdf', extensions: ['pdf']}],
+ suggestedName: fileName
+ },
+ entry => {
if (chrome.runtime.lastError) {
if (chrome.runtime.lastError.message !== 'User cancelled') {
console.log(
@@ -1488,97 +816,83 @@ export class PDFViewer {
}
/** @private */
- async print_() {
+ async onPrint_() {
PDFMetrics.record(PDFMetrics.UserAction.PRINT);
await this.exitAnnotationMode_();
- this.currentController_.print();
+ this.currentController.print();
}
/**
* Updates the toolbar's annotation available flag depending on current
* conditions.
+ * @return {boolean} Whether annotations are available.
* @private
*/
- updateAnnotationAvailable_() {
- if (!this.toolbar_) {
- return;
- }
- let annotationAvailable = true;
- if (this.viewport_.getClockwiseRotations() !== 0) {
- annotationAvailable = false;
- }
- if (this.hadPassword_) {
- annotationAvailable = false;
- }
- if (!this.canSerializeDocument_) {
- annotationAvailable = false;
- }
- this.toolbar_.annotationAvailable = annotationAvailable;
+ computeAnnotationAvailable_() {
+ return this.canSerializeDocument_ && !this.rotated_ && !this.hadPassword_;
}
/** @private */
- rotateClockwise_() {
- PDFMetrics.record(PDFMetrics.UserAction.ROTATE);
- this.viewport_.rotateClockwise();
- this.currentController_.rotateClockwise();
- this.updateAnnotationAvailable_();
+ onUndo_() {
+ this.currentController.undo();
}
/** @private */
- rotateCounterclockwise_() {
- PDFMetrics.record(PDFMetrics.UserAction.ROTATE);
- this.viewport_.rotateCounterclockwise();
- this.currentController_.rotateCounterclockwise();
- this.updateAnnotationAvailable_();
+ onRedo_() {
+ this.currentController.redo();
+ }
+
+ /**
+ * @param {!CustomEvent<{value: AnnotationTool}>} e
+ * @private
+ */
+ onAnnotationToolChanged_(e) {
+ this.inkController_.setAnnotationTool(e.detail.value);
}
+ // <if expr="chromeos">
/**
* @param {!CustomEvent<{canUndo: boolean, canRedo: boolean}>} e
* @private
*/
setAnnotationUndoState_(e) {
- this.toolbar_.canUndoAnnotation = e.detail.canUndo;
- this.toolbar_.canRedoAnnotation = e.detail.canRedo;
+ this.getToolbar_().canUndoAnnotation = e.detail.canUndo;
+ this.getToolbar_().canRedoAnnotation = e.detail.canRedo;
}
+ // </if>
- /** @private */
- resetTrackers_() {
- this.viewport_.resetTracker();
- if (this.tracker_) {
- this.tracker_.removeAll();
- }
+ /** @override */
+ rotateClockwise() {
+ super.rotateClockwise();
+ this.rotated_ = this.viewport.getClockwiseRotations() !== 0;
}
-}
-// Export on |window| such that scripts injected from pdf_extension_test.cc can
-// access it.
-window.PDFViewer = PDFViewer;
+ /** @override */
+ rotateCounterclockwise() {
+ super.rotateCounterclockwise();
+ this.rotated_ = this.viewport.getClockwiseRotations() !== 0;
+ }
+}
/**
* The height of the toolbar along the top of the page. The document will be
* shifted down by this much in the viewport.
+ * @type {number}
*/
-PDFViewer.MATERIAL_TOOLBAR_HEIGHT = 56;
+const MATERIAL_TOOLBAR_HEIGHT = 56;
/**
* Minimum height for the material toolbar to show (px). Should match the media
* query in index-material.css. If the window is smaller than this at load,
* leave no space for the toolbar.
+ * @type {number}
*/
-PDFViewer.TOOLBAR_WINDOW_MIN_HEIGHT = 250;
-
-/**
- * The background color used for print preview (--google-grey-refresh-300).
- */
-PDFViewer.PRINT_PREVIEW_BACKGROUND_COLOR = '0xFFDADCE0';
-
-/**
- * The background color used for print preview when dark mode is enabled
- * (--google-grey-refresh-700).
- */
-PDFViewer.PRINT_PREVIEW_DARK_BACKGROUND_COLOR = '0xFF5F6368';
+const TOOLBAR_WINDOW_MIN_HEIGHT = 250;
/**
* The background color used for the regular viewer.
+ * @type {string}
*/
-PDFViewer.BACKGROUND_COLOR = '0xFF525659';
+const BACKGROUND_COLOR = '0xFF525659';
+
+customElements.define(PDFViewerElement.is, PDFViewerElement);
diff --git a/chromium/chrome/browser/resources/pdf/pdf_viewer_base.js b/chromium/chrome/browser/resources/pdf/pdf_viewer_base.js
new file mode 100644
index 00000000000..bb0c9a91d12
--- /dev/null
+++ b/chromium/chrome/browser/resources/pdf/pdf_viewer_base.js
@@ -0,0 +1,640 @@
+// 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.
+
+import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js';
+import {EventTracker} from 'chrome://resources/js/event_tracker.m.js';
+import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
+import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js';
+import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+import {BrowserApi} from './browser_api.js';
+import {FittingType} from './constants.js';
+import {ContentController, MessageData, PluginController} from './controller.js';
+import {FitToChangedEvent} from './elements/viewer-zoom-toolbar.js';
+import {PDFMetrics} from './metrics.js';
+import {OpenPdfParamsParser} from './open_pdf_params_parser.js';
+import {LoadState} from './pdf_scripting_api.js';
+import {DocumentDimensionsMessageData, MessageObject} from './pdf_viewer_utils.js';
+import {Point, Viewport} from './viewport.js';
+import {ViewportScroller} from './viewport_scroller.js';
+import {ZoomManager} from './zoom_manager.js';
+
+/** @return {number} Width of a scrollbar in pixels */
+function getScrollbarWidth() {
+ const div = document.createElement('div');
+ div.style.visibility = 'hidden';
+ div.style.overflow = 'scroll';
+ div.style.width = '50px';
+ div.style.height = '50px';
+ div.style.position = 'absolute';
+ document.body.appendChild(div);
+ const result = div.offsetWidth - div.clientWidth;
+ div.parentNode.removeChild(div);
+ return result;
+}
+
+export class PDFViewerBaseElement extends PolymerElement {
+ static get is() {
+ return 'pdf-viewer-base';
+ }
+
+ static get template() {
+ return null;
+ }
+
+ static get properties() {
+ return {
+ strings: Object,
+ };
+ }
+
+ constructor() {
+ super();
+
+ /** @protected {Object|undefined} */
+ this.strings = undefined;
+
+ /** @protected {?BrowserApi} */
+ this.browserApi = null;
+
+ /** @protected {?ContentController} */
+ this.currentController = null;
+
+ /** @protected {string} */
+ this.originalUrl = '';
+
+ /** @protected {!EventTracker} */
+ this.tracker = new EventTracker();
+
+ /** @protected {boolean} */
+ this.isUserInitiatedEvent = true;
+
+ /** @protected {?Point} */
+ this.lastViewportPosition = null;
+
+ /** @protected {?OpenPdfParamsParser} */
+ this.paramsParser = null;
+
+ /** @protected {?ViewportScroller} */
+ this.viewportScroller = null;
+
+ /** @protected {?DocumentDimensionsMessageData} */
+ this.documentDimensions = null;
+
+ /** @private {boolean} */
+ this.overrideSendScriptingMessageForTest_ = false;
+
+ /** @private {!LoadState} */
+ this.loadState_ = LoadState.LOADING;
+
+ /** @private {?Object} */
+ this.parentWindow_ = null;
+
+ /** @private {?string} */
+ this.parentOrigin_ = null;
+
+ /** @private {!Array} */
+ this.delayedScriptingMessages_ = [];
+
+ /** @private {?PromiseResolver} */
+ this.loaded_ = null;
+
+ /** @private {boolean} */
+ this.initialLoadComplete_ = false;
+
+ /** @private {?Viewport} */
+ this.viewport_ = null;
+
+ /** @private {?PluginController} */
+ this.pluginController_ = null;
+
+ /** @private {?HTMLEmbedElement} */
+ this.plugin_ = null;
+
+ /** @private {?ZoomManager} */
+ this.zoomManager_ = null;
+ }
+
+ /** @return {number} The height of the top toolbar */
+ getToolbarHeight() {
+ return 0;
+ }
+
+ /**
+ * @return {!HTMLDivElement}
+ * @protected
+ */
+ getContent() {}
+
+ /**
+ * @return {!HTMLDivElement}
+ * @protected
+ */
+ getSizer() {}
+
+ /**
+ * @return {!ViewerZoomToolbarElement}
+ * @protected
+ */
+ getZoomToolbar() {}
+
+ /**
+ * @return {!ViewerErrorScreenElement}
+ * @protected
+ */
+ getErrorScreen() {}
+
+ /**
+ * @param {string} query
+ * @return {?Element}
+ * @protected
+ */
+ $$(query) {
+ return this.shadowRoot.querySelector(query);
+ }
+
+ /** @return {string} */
+ getBackgroundColor() {
+ return '';
+ }
+
+ /**
+ * @return {!HTMLEmbedElement} The plugin
+ * @private
+ */
+ createPlugin_() {
+ // Create the plugin object dynamically so we can set its src. The plugin
+ // element is sized to fill the entire window and is set to be fixed
+ // positioning, acting as a viewport. The plugin renders into this viewport
+ // according to the scroll position of the window.
+ const plugin =
+ /** @type {!HTMLEmbedElement} */ (document.createElement('embed'));
+
+ // NOTE: The plugin's 'id' field must be set to 'plugin' since
+ // ChromePrintRenderFrameHelperDeleage::GetPdfElement() in
+ // chrome/renderer/printing/chrome_print_render_frame_helper_delegate.cc
+ // actually references it.
+ plugin.id = 'plugin';
+ plugin.type = 'application/x-google-chrome-pdf';
+
+ plugin.setAttribute('src', this.originalUrl);
+ plugin.setAttribute(
+ 'stream-url', this.browserApi.getStreamInfo().streamUrl);
+ let headers = '';
+ for (const header in this.browserApi.getStreamInfo().responseHeaders) {
+ headers += header + ': ' +
+ this.browserApi.getStreamInfo().responseHeaders[header] + '\n';
+ }
+ plugin.setAttribute('headers', headers);
+
+ plugin.setAttribute('background-color', this.getBackgroundColor());
+ plugin.setAttribute('top-toolbar-height', this.getToolbarHeight());
+
+ const javascript = this.browserApi.getStreamInfo().javascript || 'block';
+ plugin.setAttribute('javascript', javascript);
+
+ if (this.browserApi.getStreamInfo().embedded) {
+ plugin.setAttribute(
+ 'top-level-url', this.browserApi.getStreamInfo().tabUrl);
+ } else {
+ plugin.toggleAttribute('full-frame', true);
+ }
+
+ return plugin;
+ }
+
+ /** @param {!BrowserApi} browserApi */
+ init(browserApi) {
+ this.browserApi = browserApi;
+ this.originalUrl = this.browserApi.getStreamInfo().originalUrl;
+
+ PDFMetrics.record(PDFMetrics.UserAction.DOCUMENT_OPENED);
+
+ // Parse open pdf parameters.
+ this.paramsParser = new OpenPdfParamsParser(
+ destination => this.pluginController_.getNamedDestination(destination));
+
+ // Can only reload if we are in a normal tab.
+ if (chrome.tabs && this.browserApi.getStreamInfo().tabId !== -1) {
+ this.getErrorScreen().reloadFn = () => {
+ chrome.tabs.reload(this.browserApi.getStreamInfo().tabId);
+ };
+ }
+
+ // Create the viewport.
+ const defaultZoom =
+ this.browserApi.getZoomBehavior() === BrowserApi.ZoomBehavior.MANAGE ?
+ this.browserApi.getDefaultZoom() :
+ 1.0;
+ this.viewport_ = new Viewport(
+ window, this.getSizer(), this.getContent(), getScrollbarWidth(),
+ defaultZoom, this.getToolbarHeight());
+ this.viewport_.setViewportChangedCallback(() => this.viewportChanged_());
+ this.viewport_.setBeforeZoomCallback(
+ () => this.currentController.beforeZoom());
+ this.viewport_.setAfterZoomCallback(
+ () => this.currentController.afterZoom());
+ this.viewport_.setUserInitiatedCallback(
+ userInitiated => this.setUserInitiated_(userInitiated));
+ window.addEventListener('beforeunload', () => this.resetTrackers_());
+
+ // Handle scripting messages from outside the extension that wish to
+ // interact with it. We also send a message indicating that extension has
+ // loaded and is ready to receive messages.
+ window.addEventListener('message', message => {
+ this.handleScriptingMessage(/** @type {!MessageObject} */ (message));
+ }, false);
+
+ // Create the plugin.
+ this.plugin_ = this.createPlugin_();
+ this.getContent().appendChild(this.plugin_);
+ this.pluginController_ = new PluginController(
+ this.plugin_, this.viewport_, () => this.isUserInitiatedEvent,
+ () => this.loaded);
+ this.currentController = this.pluginController_;
+ this.tracker.add(
+ this.pluginController_.getEventTarget(), 'plugin-message',
+ e => this.handlePluginMessage(e));
+
+ document.body.addEventListener('change-page-and-xy', e => {
+ const point = this.viewport_.convertPageToScreen(e.detail.page, e.detail);
+ this.viewport_.goToPageAndXY(e.detail.page, point.x, point.y);
+ });
+
+ // Set up the ZoomManager.
+ this.zoomManager_ = ZoomManager.create(
+ this.browserApi.getZoomBehavior(), () => this.viewport_.getZoom(),
+ zoom => this.browserApi.setZoom(zoom),
+ this.browserApi.getInitialZoom());
+ this.viewport_.setZoomManager(assert(this.zoomManager_));
+ this.browserApi.addZoomEventListener(
+ zoom => this.zoomManager_.onBrowserZoomChange(zoom));
+
+ this.viewportScroller =
+ new ViewportScroller(this.viewport_, this.plugin_, window);
+
+ // Request translated strings.
+ chrome.resourcesPrivate.getStrings(
+ chrome.resourcesPrivate.Component.PDF,
+ strings => this.handleStrings(strings));
+ }
+
+ /**
+ * Update the loading progress of the document in response to a progress
+ * message being received from the content controller.
+ * @param {number} progress the progress as a percentage.
+ */
+ updateProgress(progress) {
+ if (progress === -1) {
+ // Document load failed.
+ this.getErrorScreen().show();
+ this.getSizer().style.display = 'none';
+ this.setLoadState(LoadState.FAILED);
+ this.sendDocumentLoadedMessage();
+ } else if (progress === 100) {
+ // Document load complete.
+ if (this.lastViewportPosition) {
+ this.viewport_.position = this.lastViewportPosition;
+ }
+ this.paramsParser.getViewportFromUrlParams(
+ this.originalUrl, params => this.handleURLParams_(params));
+ this.setLoadState(LoadState.SUCCESS);
+ this.sendDocumentLoadedMessage();
+ while (this.delayedScriptingMessages_.length > 0) {
+ this.handleScriptingMessage(this.delayedScriptingMessages_.shift());
+ }
+ } else {
+ this.setLoadState(LoadState.LOADING);
+ }
+ }
+
+ /** @return {boolean} Whether the documentLoaded message can be sent. */
+ readyToSendLoadMessage() {
+ return true;
+ }
+
+ /**
+ * Sends a 'documentLoaded' message to the PDFScriptingAPI if the document has
+ * finished loading.
+ */
+ sendDocumentLoadedMessage() {
+ if (this.loadState_ === LoadState.LOADING ||
+ !this.readyToSendLoadMessage()) {
+ return;
+ }
+ this.sendScriptingMessage(
+ {type: 'documentLoaded', load_state: this.loadState_});
+ }
+
+ /**
+ * Called to update the UI before sending the viewport scripting message.
+ * Should be overridden by subclasses.
+ * @protected
+ */
+ updateUIForViewportChange() {}
+
+ /**
+ * A callback that's called after the viewport changes.
+ * @private
+ */
+ viewportChanged_() {
+ if (!this.documentDimensions) {
+ return;
+ }
+
+ this.updateUIForViewportChange();
+
+ const visiblePage = this.viewport_.getMostVisiblePage();
+ const visiblePageDimensions = this.viewport_.getPageScreenRect(visiblePage);
+ const size = this.viewport_.size;
+ this.sendScriptingMessage({
+ type: 'viewport',
+ pageX: visiblePageDimensions.x,
+ pageY: visiblePageDimensions.y,
+ pageWidth: visiblePageDimensions.width,
+ viewportWidth: size.width,
+ viewportHeight: size.height
+ });
+ }
+
+ /**
+ * Handle a scripting message from outside the extension (typically sent by
+ * PDFScriptingAPI in a page containing the extension) to interact with the
+ * plugin.
+ * @param {!MessageObject} message The message to handle.
+ */
+ handleScriptingMessage(message) {
+ if (this.parentWindow_ !== message.source) {
+ this.parentWindow_ = message.source;
+ this.parentOrigin_ = message.origin;
+ // Ensure that we notify the embedder if the document is loaded.
+ if (this.loadState_ !== LoadState.LOADING) {
+ this.sendDocumentLoadedMessage();
+ }
+ }
+ }
+
+ /**
+ * @param {!MessageObject} message The message to handle.
+ * @return {boolean} Whether the message was delayed and added to the queue.
+ */
+ delayScriptingMessage(message) {
+ // Delay scripting messages from users of the scripting API until the
+ // document is loaded. This simplifies use of the APIs.
+ if (this.loadState_ !== LoadState.SUCCESS) {
+ this.delayedScriptingMessages_.push(message);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @param {!CustomEvent<MessageData>} e
+ * @protected
+ */
+ handlePluginMessage(e) {}
+
+ /**
+ * Sets document dimensions from the current controller.
+ * @param {!DocumentDimensionsMessageData} documentDimensions
+ * @protected
+ */
+ setDocumentDimensions(documentDimensions) {
+ this.documentDimensions = documentDimensions;
+ this.isUserInitiatedEvent = false;
+ this.viewport_.setDocumentDimensions(this.documentDimensions);
+ this.isUserInitiatedEvent = true;
+ }
+
+ /**
+ * @return {?Promise} Resolved when the load state reaches LOADED,
+ * rejects on FAILED. Returns null if no promise has been created, which
+ * is the case for initial load of the PDF.
+ */
+ get loaded() {
+ return this.loaded_ ? this.loaded_.promise : null;
+ }
+
+ /** @return {!Viewport} */
+ get viewport() {
+ return assert(this.viewport_);
+ }
+
+ /**
+ * @return {!PluginController}
+ * @protected
+ */
+ get pluginController() {
+ return assert(this.pluginController_);
+ }
+
+ /**
+ * Updates the load state and triggers completion of the `loaded`
+ * promise if necessary.
+ * @param {!LoadState} loadState
+ * @protected
+ */
+ setLoadState(loadState) {
+ if (this.loadState_ === loadState) {
+ return;
+ }
+ assert(
+ loadState === LoadState.LOADING ||
+ this.loadState_ === LoadState.LOADING);
+ this.loadState_ = loadState;
+ if (!this.initialLoadComplete_) {
+ this.initialLoadComplete_ = true;
+ return;
+ }
+ if (loadState === LoadState.SUCCESS) {
+ this.loaded_.resolve();
+ } else if (loadState === LoadState.FAILED) {
+ this.loaded_.reject();
+ } else {
+ this.loaded_ = new PromiseResolver();
+ }
+ }
+
+ /**
+ * Load a dictionary of translated strings into the UI. Used as a callback for
+ * chrome.resourcesPrivate.
+ * @param {?Object} strings Dictionary of translated strings
+ * @protected
+ */
+ handleStrings(strings) {
+ if (!strings) {
+ return;
+ }
+ loadTimeData.data = strings;
+
+ // Predefined zoom factors to be used when zooming in/out. These are in
+ // ascending order.
+ const presetZoomFactors = /** @type {!Array<number>} */ (
+ JSON.parse(loadTimeData.getString('presetZoomFactors')));
+ this.viewport_.setZoomFactorRange(presetZoomFactors);
+
+ this.strings = strings;
+
+ // Display the zoom toolbar after the UI text direction is set, to ensure it
+ // appears on the correct side of the PDF viewer.
+ this.getZoomToolbar().hidden = false;
+ }
+
+ /**
+ * Handle open pdf parameters. This function updates the viewport as per
+ * the parameters mentioned in the url while opening pdf. The order is
+ * important as later actions can override the effects of previous actions.
+ * @param {Object} params The open params passed in the URL.
+ * @private
+ */
+ handleURLParams_(params) {
+ if (params.zoom) {
+ this.viewport_.setZoom(params.zoom);
+ }
+
+ if (params.position) {
+ this.viewport_.goToPageAndXY(
+ params.page ? params.page : 0, params.position.x, params.position.y);
+ } else if (params.page) {
+ this.viewport_.goToPage(params.page);
+ }
+
+ if (params.view) {
+ this.isUserInitiatedEvent = false;
+ this.getZoomToolbar().forceFit(params.view);
+ if (params.viewPosition) {
+ const zoomedPositionShift =
+ params.viewPosition * this.viewport_.getZoom();
+ const currentViewportPosition = this.viewport_.position;
+ if (params.view === FittingType.FIT_TO_WIDTH) {
+ currentViewportPosition.y += zoomedPositionShift;
+ } else if (params.view === FittingType.FIT_TO_HEIGHT) {
+ currentViewportPosition.x += zoomedPositionShift;
+ }
+ this.viewport_.position = currentViewportPosition;
+ }
+ this.isUserInitiatedEvent = true;
+ }
+ }
+
+ /**
+ * A callback that sets |isUserInitiatedEvent| to |userInitiated|.
+ * @param {boolean} userInitiated The value to set |isUserInitiatedEvent| to.
+ * @private
+ */
+ setUserInitiated_(userInitiated) {
+ assert(this.isUserInitiatedEvent !== userInitiated);
+ this.isUserInitiatedEvent = userInitiated;
+ }
+
+ overrideSendScriptingMessageForTest() {
+ this.overrideSendScriptingMessageForTest_ = true;
+ }
+
+ /**
+ * Send a scripting message outside the extension (typically to
+ * PDFScriptingAPI in a page containing the extension).
+ * @param {Object} message the message to send.
+ * @protected
+ */
+ sendScriptingMessage(message) {
+ if (this.parentWindow_ && this.parentOrigin_) {
+ let targetOrigin;
+ // Only send data back to the embedder if it is from the same origin,
+ // unless we're sending it to ourselves (which could happen in the case
+ // of tests). We also allow documentLoaded messages through as this won't
+ // leak important information.
+ if (this.parentOrigin_ === window.location.origin) {
+ targetOrigin = this.parentOrigin_;
+ } else if (message.type === 'documentLoaded') {
+ targetOrigin = '*';
+ } else {
+ targetOrigin = this.originalUrl;
+ }
+ try {
+ this.parentWindow_.postMessage(message, targetOrigin);
+ } catch (ok) {
+ // TODO(crbug.com/1004425): targetOrigin probably was rejected, such as
+ // a "data:" URL. This shouldn't cause this method to throw, though.
+ }
+ }
+ }
+
+ /**
+ * Request to change the viewport fitting type.
+ * @param {!CustomEvent<FitToChangedEvent>} e
+ * @protected
+ */
+ onFitToChanged(e) {
+ if (e.detail.fittingType === FittingType.FIT_TO_PAGE) {
+ this.viewport_.fitToPage();
+ } else if (e.detail.fittingType === FittingType.FIT_TO_WIDTH) {
+ this.viewport_.fitToWidth();
+ } else if (e.detail.fittingType === FittingType.FIT_TO_HEIGHT) {
+ this.viewport_.fitToHeight();
+ }
+
+ if (e.detail.userInitiated) {
+ PDFMetrics.recordFitTo(e.detail.fittingType);
+ }
+ }
+
+ /** @protected */
+ onZoomIn() {
+ this.viewport_.zoomIn();
+ PDFMetrics.recordZoomAction(/*isZoomIn=*/ true);
+ }
+
+ /** @protected */
+ onZoomOut() {
+ this.viewport_.zoomOut();
+ PDFMetrics.recordZoomAction(/*isZoomIn=*/ false);
+ }
+
+ /**
+ * Handles a selected text reply from the current controller.
+ * @param {string} selectedText
+ * @protected
+ */
+ handleSelectedTextReply(selectedText) {
+ const message = {
+ type: 'getSelectedTextReply',
+ selectedText: selectedText,
+ };
+ if (this.overrideSendScriptingMessageForTest_) {
+ this.overrideSendScriptingMessageForTest_ = false;
+ try {
+ this.sendScriptingMessage(message);
+ } finally {
+ this.parentWindow_.postMessage('flush', '*');
+ }
+ return;
+ }
+ this.sendScriptingMessage(message);
+ }
+
+ /** @protected */
+ rotateClockwise() {
+ PDFMetrics.record(PDFMetrics.UserAction.ROTATE);
+ this.viewport_.rotateClockwise();
+ this.currentController.rotateClockwise();
+ }
+
+ /** @protected */
+ rotateCounterclockwise() {
+ PDFMetrics.record(PDFMetrics.UserAction.ROTATE);
+ this.viewport_.rotateCounterclockwise();
+ this.currentController.rotateCounterclockwise();
+ }
+
+ /** @private */
+ resetTrackers_() {
+ this.viewport_.resetTracker();
+ if (this.tracker) {
+ this.tracker.removeAll();
+ }
+ }
+}
+
+customElements.define(PDFViewerBaseElement.is, PDFViewerBaseElement);
diff --git a/chromium/chrome/browser/resources/pdf/pdf_viewer_pp.html b/chromium/chrome/browser/resources/pdf/pdf_viewer_pp.html
new file mode 100644
index 00000000000..dac20fda069
--- /dev/null
+++ b/chromium/chrome/browser/resources/pdf/pdf_viewer_pp.html
@@ -0,0 +1,21 @@
+<style include="pdf-viewer-shared-style">
+ viewer-page-indicator {
+ opacity: 0;
+ visibility: hidden;
+ z-index: 2;
+ }
+</style>
+
+<div id="sizer"></div>
+
+<viewer-zoom-toolbar id="zoom-toolbar" strings="[[strings]]"
+ on-fit-to-changed="onFitToChanged" is-print-preview
+ on-zoom-in="onZoomIn" on-zoom-out="onZoomOut"
+ hidden>
+</viewer-zoom-toolbar>
+
+<viewer-error-screen id="error-screen"></viewer-error-screen>
+
+<viewer-page-indicator id="page-indicator"></viewer-page-indicator>
+
+<div id="content"></div>
diff --git a/chromium/chrome/browser/resources/pdf/pdf_viewer_pp.js b/chromium/chrome/browser/resources/pdf/pdf_viewer_pp.js
new file mode 100644
index 00000000000..6fa9a6f3e3c
--- /dev/null
+++ b/chromium/chrome/browser/resources/pdf/pdf_viewer_pp.js
@@ -0,0 +1,379 @@
+// 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.
+
+import './elements/viewer-error-screen.js';
+import './elements/viewer-page-indicator.js';
+import './elements/shared-vars.js';
+import './pdf_viewer_shared_style.js';
+
+import {assertNotReached} from 'chrome://resources/js/assert.m.js';
+import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
+import {isRTL} from 'chrome://resources/js/util.m.js';
+import {html} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+import {BrowserApi} from './browser_api.js';
+import {FittingType} from './constants.js';
+import {MessageData, PrintPreviewParams} from './controller.js';
+import {DeserializeKeyEvent, LoadState, SerializeKeyEvent} from './pdf_scripting_api.js';
+import {PDFViewerBaseElement} from './pdf_viewer_base.js';
+import {DestinationMessageData, DocumentDimensionsMessageData, MessageObject, shouldIgnoreKeyEvents} from './pdf_viewer_utils.js';
+import {ToolbarManager} from './toolbar_manager.js';
+
+class PDFViewerPPElement extends PDFViewerBaseElement {
+ static get is() {
+ return 'pdf-viewer-pp';
+ }
+
+ static get template() {
+ return html`{__html_template__}`;
+ }
+
+ constructor() {
+ super();
+
+ /** @private {boolean} */
+ this.isPrintPreviewLoadingFinished_ = false;
+
+ /** @private {boolean} */
+ this.inPrintPreviewMode_ = false;
+
+ /** @private {boolean} */
+ this.dark_ = false;
+
+ /** @private {?ToolbarManager} */
+ this.toolbarManager_ = null;
+ }
+
+ /** @override */
+ getContent() {
+ return /** @type {!HTMLDivElement} */ (this.$$('#content'));
+ }
+
+ /** @override */
+ getSizer() {
+ return /** @type {!HTMLDivElement} */ (this.$$('#sizer'));
+ }
+
+ /** @override */
+ getZoomToolbar() {
+ return /** @type {!ViewerZoomToolbarElement} */ (this.$$('#zoom-toolbar'));
+ }
+
+ /** @override */
+ getErrorScreen() {
+ return /** @type {!ViewerErrorScreenElement} */ (this.$$('#error-screen'));
+ }
+
+ /** @override */
+ getBackgroundColor() {
+ return PRINT_PREVIEW_BACKGROUND_COLOR;
+ }
+
+ /** @param {!BrowserApi} browserApi */
+ init(browserApi) {
+ super.init(browserApi);
+
+ this.toolbarManager_ =
+ new ToolbarManager(window, null, this.getZoomToolbar());
+
+ // Setup the keyboard event listener.
+ document.addEventListener(
+ 'keydown',
+ e => this.handleKeyEvent_(/** @type {!KeyboardEvent} */ (e)));
+ }
+
+ /**
+ * Handle key events. These may come from the user directly or via the
+ * scripting API.
+ * @param {!KeyboardEvent} e the event to handle.
+ * @private
+ */
+ handleKeyEvent_(e) {
+ if (shouldIgnoreKeyEvents(document.activeElement) || e.defaultPrevented) {
+ return;
+ }
+
+ this.toolbarManager_.hideToolbarsAfterTimeout();
+ // Let the viewport handle directional key events.
+ if (this.viewport.handleDirectionalKeyEvent(e, false)) {
+ return;
+ }
+
+ switch (e.key) {
+ case 'Tab':
+ this.toolbarManager_.showToolbarsForKeyboardNavigation();
+ return;
+ case 'Escape':
+ break; // Ensure escape falls through to the print-preview handler.
+ case 'a':
+ if (e.ctrlKey || e.metaKey) {
+ this.pluginController.selectAll();
+ // Since we do selection ourselves.
+ e.preventDefault();
+ }
+ return;
+ case '[':
+ if (e.ctrlKey) {
+ this.rotateCounterclockwise();
+ }
+ return;
+ case '\\':
+ if (e.ctrlKey) {
+ this.getZoomToolbar().fitToggleFromHotKey();
+ }
+ return;
+ case ']':
+ if (e.ctrlKey) {
+ this.rotateClockwise();
+ }
+ return;
+ }
+
+ // Give print preview a chance to handle the key event.
+ if (!e.fromScriptingAPI) {
+ this.sendScriptingMessage(
+ {type: 'sendKeyEvent', keyEvent: SerializeKeyEvent(e)});
+ } else {
+ // Show toolbars as a fallback.
+ if (!(e.shiftKey || e.ctrlKey || e.altKey)) {
+ this.toolbarManager_.showToolbars();
+ }
+ }
+ }
+
+ /** @private */
+ sendBackgroundColorForPrintPreview_() {
+ this.pluginController.backgroundColorChanged(
+ this.dark_ ? PRINT_PREVIEW_DARK_BACKGROUND_COLOR :
+ PRINT_PREVIEW_BACKGROUND_COLOR);
+ }
+
+ /** @override */
+ updateUIForViewportChange() {
+ // Offset the toolbar position so that it doesn't move if scrollbars appear.
+ const hasScrollbars = this.viewport.documentHasScrollbars();
+ const scrollbarWidth = this.viewport.scrollbarWidth;
+ const verticalScrollbarWidth = hasScrollbars.vertical ? scrollbarWidth : 0;
+ const horizontalScrollbarWidth =
+ hasScrollbars.horizontal ? scrollbarWidth : 0;
+
+ // Shift the zoom toolbar to the left by half a scrollbar width. This
+ // gives a compromise: if there is no scrollbar visible then the toolbar
+ // will be half a scrollbar width further left than the spec but if there
+ // is a scrollbar visible it will be half a scrollbar width further right
+ // than the spec. In LTR layout, the zoom toolbar is on the left
+ // left side, but the scrollbar is still on the right, so this is not
+ // necessary.
+ const zoomToolbar = this.getZoomToolbar();
+ if (isRTL()) {
+ zoomToolbar.style.right =
+ -verticalScrollbarWidth + (scrollbarWidth / 2) + 'px';
+ }
+ // Having a horizontal scrollbar is much rarer so we don't offset the
+ // toolbar from the bottom any more than what the spec says. This means
+ // that when there is a scrollbar visible, it will be a full scrollbar
+ // width closer to the bottom of the screen than usual, but this is ok.
+ zoomToolbar.style.bottom = -horizontalScrollbarWidth + 'px';
+
+ // Update the page indicator.
+ const visiblePage = this.viewport.getMostVisiblePage();
+ const pageIndicator = this.$$('#page-indicator');
+ const lastIndex = pageIndicator.index;
+ pageIndicator.index = visiblePage;
+ if (this.documentDimensions.pageDimensions.length > 1 &&
+ hasScrollbars.vertical && lastIndex !== undefined) {
+ pageIndicator.style.visibility = 'visible';
+ } else {
+ pageIndicator.style.visibility = 'hidden';
+ }
+
+ this.pluginController.viewportChanged();
+ }
+
+ /** @override */
+ handleScriptingMessage(message) {
+ super.handleScriptingMessage(message);
+
+ if (this.handlePrintPreviewScriptingMessage_(message)) {
+ return;
+ }
+
+ if (this.delayScriptingMessage(message)) {
+ return;
+ }
+
+ switch (message.data.type.toString()) {
+ case 'getSelectedText':
+ this.pluginController.getSelectedText();
+ break;
+ case 'selectAll':
+ this.pluginController.selectAll();
+ break;
+ }
+ }
+
+ /**
+ * Handle scripting messages specific to print preview.
+ * @param {!MessageObject} message the message to handle.
+ * @return {boolean} true if the message was handled, false otherwise.
+ * @private
+ */
+ handlePrintPreviewScriptingMessage_(message) {
+ let messageData = message.data;
+ switch (messageData.type.toString()) {
+ case 'loadPreviewPage':
+ messageData =
+ /** @type {{ url: string, index: number }} */ (messageData);
+ this.pluginController.loadPreviewPage(
+ messageData.url, messageData.index);
+ return true;
+ case 'resetPrintPreviewMode':
+ messageData = /** @type {!PrintPreviewParams} */ (messageData);
+ this.setLoadState(LoadState.LOADING);
+ if (!this.inPrintPreviewMode_) {
+ this.inPrintPreviewMode_ = true;
+ this.isUserInitiatedEvent = false;
+ this.getZoomToolbar().forceFit(FittingType.FIT_TO_PAGE);
+ this.isUserInitiatedEvent = true;
+ }
+
+ // Stash the scroll location so that it can be restored when the new
+ // document is loaded.
+ this.lastViewportPosition = this.viewport.position;
+ this.$$('#page-indicator').pageLabels = messageData.pageNumbers;
+
+ this.pluginController.resetPrintPreviewMode(messageData);
+ return true;
+ case 'sendKeyEvent':
+ this.handleKeyEvent_(/** @type {!KeyboardEvent} */ (DeserializeKeyEvent(
+ /** @type {{ keyEvent: Object }} */ (message.data).keyEvent)));
+ return true;
+ case 'hideToolbars':
+ this.toolbarManager_.resetKeyboardNavigationAndHideToolbars();
+ return true;
+ case 'darkModeChanged':
+ this.dark_ = /** @type {{darkMode: boolean}} */ (message.data).darkMode;
+ this.sendBackgroundColorForPrintPreview_();
+ return true;
+ case 'scrollPosition':
+ const position = this.viewport.position;
+ messageData = /** @type {{ x: number, y: number }} */ (message.data);
+ position.y += messageData.y;
+ position.x += messageData.x;
+ this.viewport.position = position;
+ return true;
+ }
+
+ return false;
+ }
+
+ /** @override */
+ setLoadState(loadState) {
+ super.setLoadState(loadState);
+ if (loadState === LoadState.FAILED) {
+ this.isPrintPreviewLoadingFinished_ = true;
+ }
+ }
+
+ /** @override */
+ handlePluginMessage(e) {
+ const data = e.detail;
+ switch (data.type.toString()) {
+ case 'documentDimensions':
+ this.setDocumentDimensions(
+ /** @type {!DocumentDimensionsMessageData} */ (data));
+ return;
+ case 'getSelectedTextReply':
+ this.handleSelectedTextReply(
+ /** @type {{ selectedText: string }} */ (data).selectedText);
+ return;
+ case 'loadProgress':
+ this.updateProgress(
+ /** @type {{ progress: number }} */ (data).progress);
+ return;
+ case 'navigateToDestination':
+ const destinationData = /** @type {!DestinationMessageData} */ (data);
+ this.viewport.handleNavigateToDestination(
+ destinationData.page, destinationData.x, destinationData.y,
+ destinationData.zoom);
+ return;
+ case 'printPreviewLoaded':
+ this.handlePrintPreviewLoaded_();
+ return;
+ case 'setIsSelecting':
+ this.viewportScroller.setEnableScrolling(
+ /** @type {{ isSelecting: boolean }} */ (data).isSelecting);
+ return;
+ case 'getNamedDestinationReply':
+ this.paramsParser.onNamedDestinationReceived(
+ /** @type {{ pageNumber: number }} */ (data).pageNumber);
+ return;
+ case 'touchSelectionOccurred':
+ this.sendScriptingMessage({
+ type: 'touchSelectionOccurred',
+ });
+ return;
+ case 'documentFocusChanged':
+ // TODO(crbug.com/1069370): Draw a focus rect around plugin.
+ return;
+ case 'beep':
+ case 'formFocusChange':
+ case 'getPassword':
+ case 'metadata':
+ case 'navigate':
+ case 'setIsEditing':
+ // These messages are not relevant in Print Preview.
+ return;
+ }
+ assertNotReached('Unknown message type received: ' + data.type);
+ }
+
+ /**
+ * Handles a notification that print preview has loaded from the
+ * current controller.
+ * @private
+ */
+ handlePrintPreviewLoaded_() {
+ this.isPrintPreviewLoadingFinished_ = true;
+ this.sendDocumentLoadedMessage();
+ }
+
+ /** @override */
+ readyToSendLoadMessage() {
+ return this.isPrintPreviewLoadingFinished_;
+ }
+
+ /** @override */
+ handleStrings(strings) {
+ super.handleStrings(strings);
+
+ if (!strings) {
+ return;
+ }
+ this.sendBackgroundColorForPrintPreview_();
+ }
+
+ /** @override */
+ updateProgress(progress) {
+ super.updateProgress(progress);
+ if (progress === 100) {
+ this.toolbarManager_.hideToolbarsAfterTimeout();
+ }
+ }
+}
+
+/**
+ * The background color used for print preview (--google-grey-refresh-300).
+ * @type {string}
+ */
+const PRINT_PREVIEW_BACKGROUND_COLOR = '0xFFDADCE0';
+
+/**
+ * The background color used for print preview when dark mode is enabled
+ * (--google-grey-refresh-700).
+ * @type {string}
+ */
+const PRINT_PREVIEW_DARK_BACKGROUND_COLOR = '0xFF5F6368';
+
+customElements.define(PDFViewerPPElement.is, PDFViewerPPElement);
diff --git a/chromium/chrome/browser/resources/pdf/pdf_viewer_shared_style.html b/chromium/chrome/browser/resources/pdf/pdf_viewer_shared_style.html
new file mode 100644
index 00000000000..ba2a5e4cf9b
--- /dev/null
+++ b/chromium/chrome/browser/resources/pdf/pdf_viewer_shared_style.html
@@ -0,0 +1,33 @@
+<template>
+ <style>
+ #content {
+ height: 100%;
+ position: fixed;
+ width: 100%;
+ z-index: 1;
+ }
+
+ #plugin {
+ height: 100%;
+ position: absolute;
+ width: 100%;
+ }
+
+ #sizer {
+ position: absolute;
+ z-index: 0;
+ }
+
+ @media(max-height: 200px) {
+ viewer-zoom-toolbar {
+ display: none;
+ }
+ }
+
+ @media(max-width: 300px) {
+ viewer-zoom-toolbar {
+ display: none;
+ }
+ }
+ </style>
+</template>
diff --git a/chromium/chrome/browser/resources/pdf/pdf_viewer_shared_style.js b/chromium/chrome/browser/resources/pdf/pdf_viewer_shared_style.js
new file mode 100644
index 00000000000..d7411e11a3a
--- /dev/null
+++ b/chromium/chrome/browser/resources/pdf/pdf_viewer_shared_style.js
@@ -0,0 +1,11 @@
+// Copyright 2020 The Chromium 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 {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+const template = document.createElement('template');
+template.innerHTML = `
+<dom-module id="pdf-viewer-shared-style">{__html_template__}</dom-module>
+`;
+document.body.appendChild(template.content.cloneNode(true));
diff --git a/chromium/chrome/browser/resources/pdf/pdf_viewer_utils.js b/chromium/chrome/browser/resources/pdf/pdf_viewer_utils.js
new file mode 100644
index 00000000000..2250aa80637
--- /dev/null
+++ b/chromium/chrome/browser/resources/pdf/pdf_viewer_utils.js
@@ -0,0 +1,64 @@
+// Copyright 2020 The Chromium 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 {MessageData} from './controller.js';
+import {LayoutOptions} from './viewport.js';
+
+/**
+ * @typedef {{
+ * source: Object,
+ * origin: string,
+ * data: !MessageData,
+ * }}
+ */
+export let MessageObject;
+
+/**
+ * @typedef {{
+ * type: string,
+ * height: number,
+ * width: number,
+ * layoutOptions: (!LayoutOptions|undefined),
+ * pageDimensions: Array
+ * }}
+ */
+export let DocumentDimensionsMessageData;
+
+/**
+ * @typedef {{
+ * type: string,
+ * page: number,
+ * x: number,
+ * y: number,
+ * zoom: number
+ * }}
+ */
+export let DestinationMessageData;
+
+/**
+ * @typedef {{
+ * hasUnsavedChanges: (boolean|undefined),
+ * fileName: string,
+ * dataToSave: !ArrayBuffer
+ * }}
+ */
+export let RequiredSaveResult;
+
+/**
+ * Whether keydown events should currently be ignored. Events are ignored when
+ * an editable element has focus, to allow for proper editing controls.
+ * @param {Element} activeElement The currently selected DOM node.
+ * @return {boolean} True if keydown events should be ignored.
+ */
+export function shouldIgnoreKeyEvents(activeElement) {
+ while (activeElement.shadowRoot != null &&
+ activeElement.shadowRoot.activeElement != null) {
+ activeElement = activeElement.shadowRoot.activeElement;
+ }
+
+ return (
+ activeElement.isContentEditable ||
+ (activeElement.tagName === 'INPUT' && activeElement.type !== 'radio') ||
+ activeElement.tagName === 'TEXTAREA');
+}
diff --git a/chromium/chrome/browser/resources/pdf/toolbar_manager.js b/chromium/chrome/browser/resources/pdf/toolbar_manager.js
index 847b21172fc..f4b7aade0b4 100644
--- a/chromium/chrome/browser/resources/pdf/toolbar_manager.js
+++ b/chromium/chrome/browser/resources/pdf/toolbar_manager.js
@@ -4,20 +4,42 @@
import {isRTL} from 'chrome://resources/js/util.m.js';
-/** Idle time in ms before the UI is hidden. */
+/**
+ * Idle time in ms before the UI is hidden.
+ * @type {number}
+ */
const HIDE_TIMEOUT = 2000;
-/** Time in ms after force hide before toolbar is shown again. */
+
+/**
+ * Time in ms after force hide before toolbar is shown again.
+ * @type {number}
+ */
const FORCE_HIDE_TIMEOUT = 1000;
+
/**
* Velocity required in a mousemove to reveal the UI (pixels/ms). This is
* intended to be high enough that a fast flick of the mouse is required to
* reach it.
+ * @type {number}
*/
const SHOW_VELOCITY = 10;
-/** Distance from the top of the screen required to reveal the toolbars. */
+
+/**
+ * Distance from the top of the screen required to reveal the toolbars.
+ * @type {number}
+ */
const TOP_TOOLBAR_REVEAL_DISTANCE = 100;
-/** Distance from the bottom-right of the screen required to reveal toolbars. */
+
+/**
+ * Distance from right of the screen required to reveal toolbars.
+ * @type {number}
+ */
const SIDE_TOOLBAR_REVEAL_DISTANCE_RIGHT = 150;
+
+/**
+ * Distance from bottom of the screen required to reveal toolbars.
+ * @type {number}
+ */
const SIDE_TOOLBAR_REVEAL_DISTANCE_BOTTOM = 250;
/**
@@ -45,7 +67,7 @@ function isMouseNearSideToolbar(e, window, reverse) {
return atSide && atBottom;
}
-/** Responsible for co-ordinating between multiple toolbar elements. */
+// Responsible for co-ordinating between multiple toolbar elements.
export class ToolbarManager {
/**
* @param {!Window} window The window containing the UI.
@@ -89,6 +111,12 @@ export class ToolbarManager {
this.window_.addEventListener('resize', this.resizeDropdowns_.bind(this));
this.resizeDropdowns_();
+ document.addEventListener(
+ 'mousemove',
+ e => this.handleMouseMove_(/** @type {!MouseEvent} */ (e)));
+ document.addEventListener(
+ 'mouseout', () => this.hideToolbarsForMouseOut_());
+
if (this.isPrintPreview_) {
this.zoomToolbar_.addEventListener('keyboard-navigation-active', e => {
this.keyboardNavigationActive = e.detail;
@@ -96,8 +124,11 @@ export class ToolbarManager {
}
}
- /** @param {!MouseEvent} e */
- handleMouseMove(e) {
+ /**
+ * @param {!MouseEvent} e
+ * @private
+ */
+ handleMouseMove_(e) {
this.isMouseNearTopToolbar_ = !!this.toolbar_ && isMouseNearTopToolbar(e);
this.isMouseNearSideToolbar_ =
isMouseNearSideToolbar(e, this.window_, this.isPrintPreview_);
@@ -192,8 +223,9 @@ export class ToolbarManager {
/**
* Hide toolbars after a delay, regardless of the position of the mouse.
* Intended to be called when the mouse has moved out of the parent window.
+ * @private
*/
- hideToolbarsForMouseOut() {
+ hideToolbarsForMouseOut_() {
this.isMouseNearTopToolbar_ = false;
this.isMouseNearSideToolbar_ = false;
this.hideToolbarsAfterTimeout();
diff --git a/chromium/chrome/browser/resources/pdf/viewport.js b/chromium/chrome/browser/resources/pdf/viewport.js
index 37967176729..3e68d39f673 100644
--- a/chromium/chrome/browser/resources/pdf/viewport.js
+++ b/chromium/chrome/browser/resources/pdf/viewport.js
@@ -4,9 +4,10 @@
import {assert} from 'chrome://resources/js/assert.m.js';
import {EventTracker} from 'chrome://resources/js/event_tracker.m.js';
-import {$} from 'chrome://resources/js/util.m.js';
+import {$, hasKeyModifiers} from 'chrome://resources/js/util.m.js';
import {FittingType} from './constants.js';
+import {GestureDetector, PinchEventDetail} from './gesture_detector.js';
import {InactiveZoomManager, ZoomManager} from './zoom_manager.js';
/**
@@ -66,35 +67,29 @@ function vectorDelta(p1, p2) {
return {x: p2.x - p1.x, y: p2.y - p1.y};
}
-/**
- * @param {!Point} coordinateInFrame
- * @return {!Point} Coordinate converted to plugin coordinates.
- */
-function frameToPluginCoordinate(coordinateInFrame) {
- const container = $('plugin');
- return {
- x: coordinateInFrame.x - container.getBoundingClientRect().left,
- y: coordinateInFrame.y - container.getBoundingClientRect().top
- };
-}
-
export class Viewport {
/**
* @param {!Window} window
* @param {!HTMLDivElement} sizer The element which represents the size of the
* document in the viewport
+ * @param {!HTMLDivElement} content The element which is the parent of the
+ * plugin in the viewer.
* @param {number} scrollbarWidth The width of scrollbars on the page
* @param {number} defaultZoom The default zoom level.
* @param {number} topToolbarHeight The number of pixels that should initially
* be left blank above the document for the toolbar.
*/
- constructor(window, sizer, scrollbarWidth, defaultZoom, topToolbarHeight) {
+ constructor(
+ window, sizer, content, scrollbarWidth, defaultZoom, topToolbarHeight) {
/** @private {!Window} */
this.window_ = window;
/** @private {!HTMLDivElement} */
this.sizer_ = sizer;
+ /** @private {!HTMLDivElement} */
+ this.content_ = content;
+
/** @private {number} */
this.scrollbarWidth_ = scrollbarWidth;
@@ -168,11 +163,33 @@ export class Viewport {
/** @private {!EventTracker} */
this.tracker_ = new EventTracker();
+ /** @private {!GestureDetector} */
+ this.gestureDetector_ = new GestureDetector(this.content_);
+
+ /** @private {boolean} */
+ this.sentPinchEvent_ = false;
+
+ this.gestureDetector_.getEventTarget().addEventListener(
+ 'pinchstart',
+ e => this.onPinchStart_(
+ /** @type {!CustomEvent<!PinchEventDetail>} */ (e)));
+ this.gestureDetector_.getEventTarget().addEventListener(
+ 'pinchupdate',
+ e => this.onPinchUpdate_(
+ /** @type {!CustomEvent<!PinchEventDetail>} */ (e)));
+ this.gestureDetector_.getEventTarget().addEventListener(
+ 'pinchend',
+ e => this.onPinchEnd_(
+ /** @type {!CustomEvent<!PinchEventDetail>} */ (e)));
+
// Set to a default zoom manager - used in tests.
this.setZoomManager(new InactiveZoomManager(this.getZoom.bind(this), 1));
window.addEventListener('scroll', this.updateViewport_.bind(this));
window.addEventListener('resize', this.resizeWrapper_.bind(this));
+
+ document.body.addEventListener(
+ 'change-zoom', e => this.setZoom(e.detail.zoom));
}
/** @param {function():void} viewportChangedCallback */
@@ -288,8 +305,8 @@ export class Viewport {
y: point.y * pointsToPixels,
});
return {
- x: result.x + Viewport.PAGE_SHADOW.left,
- y: result.y + Viewport.PAGE_SHADOW.top,
+ x: result.x + PAGE_SHADOW.left,
+ y: result.y + PAGE_SHADOW.top,
};
}
@@ -348,9 +365,9 @@ export class Viewport {
* @param {number} zoom Zoom to compute scrollbars for
* @return {{horizontal: boolean, vertical: boolean}} Whether horizontal or
* vertical scrollbars are needed.
- * @private
+ * Public so tests can call it directly.
*/
- documentNeedsScrollbars_(zoom) {
+ documentNeedsScrollbars(zoom) {
const zoomedDimensions = this.getZoomedDocumentDimensions_(zoom);
if (!zoomedDimensions) {
return {horizontal: false, vertical: false};
@@ -376,7 +393,7 @@ export class Viewport {
* vertical scrollbars are needed.
*/
documentHasScrollbars() {
- return this.documentNeedsScrollbars_(this.getZoom());
+ return this.documentNeedsScrollbars(this.getZoom());
}
/**
@@ -394,6 +411,19 @@ export class Viewport {
}
/**
+ * @param {!Point} coordinateInFrame
+ * @return {!Point} Coordinate converted to plugin coordinates.
+ * @private
+ */
+ frameToPluginCoordinate_(coordinateInFrame) {
+ const container = this.content_.querySelector('#plugin');
+ return {
+ x: coordinateInFrame.x - container.getBoundingClientRect().left,
+ y: coordinateInFrame.y - container.getBoundingClientRect().top
+ };
+ }
+
+ /**
* Called when the viewport should be updated.
* @private
*/
@@ -447,7 +477,7 @@ export class Viewport {
/** @return {!Size} the size of the viewport excluding scrollbars. */
get size() {
- const needsScrollbars = this.documentNeedsScrollbars_(this.getZoom());
+ const needsScrollbars = this.documentNeedsScrollbars(this.getZoom());
const scrollbarWidth = needsScrollbars.vertical ? this.scrollbarWidth_ : 0;
const scrollbarHeight =
needsScrollbars.horizontal ? this.scrollbarWidth_ : 0;
@@ -589,9 +619,7 @@ export class Viewport {
};
}
- /**
- * @param {number} newZoom The zoom level to zoom to.
- */
+ /** @param {number} newZoom The zoom level to zoom to. */
setZoom(newZoom) {
this.fittingType_ = FittingType.NONE;
this.mightZoom_(() => {
@@ -775,7 +803,7 @@ export class Viewport {
pageDimensions.width, pageDimensions.height);
// Check if there needs to be any scrollbars.
- const needsScrollbars = this.documentNeedsScrollbars_(zoom);
+ const needsScrollbars = this.documentNeedsScrollbars(zoom);
// If the document fits, just return the zoom.
if (!needsScrollbars.horizontal && !needsScrollbars.vertical) {
@@ -992,84 +1020,152 @@ export class Viewport {
}
/**
- * Pinch zoom event handler.
- * @param {!Object} e The pinch event.
+ * @param {!KeyboardEvent} e
+ * @private
*/
- pinchZoom(e) {
- this.mightZoom_(() => {
- this.pinchPhase_ = e.direction === 'out' ?
- Viewport.PinchPhase.PINCH_UPDATE_ZOOM_OUT :
- Viewport.PinchPhase.PINCH_UPDATE_ZOOM_IN;
-
- const scaleDelta = e.startScaleRatio / this.prevScale_;
- if (this.firstPinchCenterInFrame_ != null) {
- this.pinchPanVector_ =
- vectorDelta(e.center, this.firstPinchCenterInFrame_);
- }
+ pageUpHandler_(e) {
+ // Go to the previous page if we are fit-to-page or fit-to-height.
+ if (this.isPagedMode_()) {
+ this.goToPreviousPage();
+ // Since we do the movement of the page.
+ e.preventDefault();
+ } else if (
+ /** @type {!{fromScriptingAPI: (boolean|undefined)}} */ (e)
+ .fromScriptingAPI) {
+ this.position.y -= this.size.height;
+ }
+ }
- const needsScrollbars =
- this.documentNeedsScrollbars_(this.zoomManager_.applyBrowserZoom(
- this.clampZoom_(this.internalZoom_ * scaleDelta)));
-
- this.pinchCenter_ = e.center;
-
- // If there's no horizontal scrolling, keep the content centered so the
- // user can't zoom in on the non-content area.
- // TODO(mcnee) Investigate other ways of scaling when we don't have
- // horizontal scrolling. We want to keep the document centered,
- // but this causes a potentially awkward transition when we start
- // using the gesture center.
- if (!needsScrollbars.horizontal) {
- this.pinchCenter_ = {
- x: this.window_.innerWidth / 2,
- y: this.window_.innerHeight / 2
- };
- } else if (this.keepContentCentered_) {
- this.oldCenterInContent_ =
- this.frameToContent_(frameToPluginCoordinate(e.center));
- this.keepContentCentered_ = false;
- }
+ /**
+ * @param {!KeyboardEvent} e
+ * @private
+ */
+ pageDownHandler_(e) {
+ // Go to the next page if we are fit-to-page or fit-to-height.
+ if (this.isPagedMode_()) {
+ this.goToNextPage();
+ // Since we do the movement of the page.
+ e.preventDefault();
+ } else if (
+ /** @type {!{fromScriptingAPI: (boolean|undefined)}} */ (e)
+ .fromScriptingAPI) {
+ this.position.y += this.size.height;
+ }
+ }
- this.setPinchZoomInternal_(scaleDelta, frameToPluginCoordinate(e.center));
- this.updateViewport_();
- this.prevScale_ = e.startScaleRatio;
- });
+ /**
+ * @param {!KeyboardEvent} e
+ * @param {boolean} formFieldFocused
+ * @private
+ */
+ arrowLeftHandler_(e, formFieldFocused) {
+ if (hasKeyModifiers(e)) {
+ return;
+ }
+
+ // Go to the previous page if there are no horizontal scrollbars and
+ // no form field is focused.
+ if (!(this.documentHasScrollbars().horizontal || formFieldFocused)) {
+ this.goToPreviousPage();
+ // Since we do the movement of the page.
+ e.preventDefault();
+ } else if (
+ /** @type {!{fromScriptingAPI: (boolean|undefined)}} */ (e)
+ .fromScriptingAPI) {
+ this.position.x -= SCROLL_INCREMENT;
+ }
}
- /** @param {!Object} e The pinch event. */
- pinchZoomStart(e) {
- this.pinchPhase_ = Viewport.PinchPhase.PINCH_START;
- this.prevScale_ = 1;
- this.oldCenterInContent_ =
- this.frameToContent_(frameToPluginCoordinate(e.center));
+ /**
+ * @param {!KeyboardEvent} e
+ * @param {boolean} formFieldFocused
+ * @private
+ */
+ arrowRightHandler_(e, formFieldFocused) {
+ if (hasKeyModifiers(e)) {
+ return;
+ }
- const needsScrollbars = this.documentNeedsScrollbars_(this.getZoom());
- this.keepContentCentered_ = !needsScrollbars.horizontal;
- // We keep track of begining of the pinch.
- // By doing so we will be able to compute the pan distance.
- this.firstPinchCenterInFrame_ = e.center;
+ // Go to the next page if there are no horizontal scrollbars and no
+ // form field is focused.
+ if (!(this.documentHasScrollbars().horizontal || formFieldFocused)) {
+ this.goToNextPage();
+ // Since we do the movement of the page.
+ e.preventDefault();
+ } else if (
+ /** @type {!{fromScriptingAPI: (boolean|undefined)}} */ (e)
+ .fromScriptingAPI) {
+ this.position.x += SCROLL_INCREMENT;
+ }
}
- /** @param {!Object} e The pinch event. */
- pinchZoomEnd(e) {
- this.mightZoom_(() => {
- this.pinchPhase_ = Viewport.PinchPhase.PINCH_END;
- const scaleDelta = e.startScaleRatio / this.prevScale_;
- this.pinchCenter_ = /** @type {!Point} */ (e.center);
+ /**
+ * @param {boolean} fromScriptingAPI
+ * @private
+ */
+ arrowDownHandler_(fromScriptingAPI) {
+ if (fromScriptingAPI) {
+ this.position.y += SCROLL_INCREMENT;
+ }
+ }
- this.setPinchZoomInternal_(scaleDelta, frameToPluginCoordinate(e.center));
- this.updateViewport_();
- });
+ /**
+ * @param {boolean} fromScriptingAPI
+ * @private
+ */
+ arrowUpHandler_(fromScriptingAPI) {
+ if (fromScriptingAPI) {
+ this.position.y -= SCROLL_INCREMENT;
+ }
+ }
- this.pinchPhase_ = Viewport.PinchPhase.PINCH_NONE;
- this.pinchPanVector_ = null;
- this.pinchCenter_ = null;
- this.firstPinchCenterInFrame_ = null;
+ /**
+ * Handle certain directional key events.
+ * @param {!KeyboardEvent} e the event to handle.
+ * @param {boolean} formFieldFocused Whether a form field is currently
+ * focused.
+ * @return {boolean} Whether the event was handled.
+ */
+ handleDirectionalKeyEvent(e, formFieldFocused) {
+ // Certain scroll events may be sent from outside of the extension.
+ const fromScriptingAPI =
+ /** @type {!{fromScriptingAPI: (boolean|undefined)}} */ (e)
+ .fromScriptingAPI;
+
+ switch (e.key) {
+ case '':
+ if (e.shiftKey) {
+ this.pageUpHandler_(e);
+ } else {
+ this.pageDownHandler_(e);
+ }
+ return true;
+ case 'PageUp':
+ this.pageUpHandler_(e);
+ return true;
+ case 'PageDown':
+ this.pageDownHandler_(e);
+ return true;
+ case 'ArrowLeft':
+ this.arrowLeftHandler_(e, formFieldFocused);
+ return true;
+ case 'ArrowUp':
+ this.arrowUpHandler_(!!fromScriptingAPI);
+ return true;
+ case 'ArrowRight':
+ this.arrowRightHandler_(e, formFieldFocused);
+ return true;
+ case 'ArrowDown':
+ this.arrowDownHandler_(!!fromScriptingAPI);
+ return true;
+ default:
+ return false;
+ }
}
/**
* Go to the next page. If the document is in two-up view, go to the left page
- * of the next row.
+ * of the next row. Public for tests.
*/
goToNextPage() {
const currentPage = this.getMostVisiblePage();
@@ -1080,7 +1176,7 @@ export class Viewport {
/**
* Go to the previous page. If the document is in two-up view, go to the left
- * page of the previous row.
+ * page of the previous row. Public for tests.
*/
goToPreviousPage() {
const currentPage = this.getMostVisiblePage();
@@ -1123,7 +1219,7 @@ export class Viewport {
// Unless we're in fit to page or fit to height mode, scroll above the
// page by |this.topToolbarHeight_| so that the toolbar isn't covering it
// initially.
- if (!this.isPagedMode()) {
+ if (!this.isPagedMode_()) {
toolbarOffset = this.topToolbarHeight_;
}
this.position = {
@@ -1160,7 +1256,7 @@ export class Viewport {
*/
getPageInsetDimensions(page) {
const pageDimensions = this.pageDimensions_[page];
- const shadow = Viewport.PAGE_SHADOW;
+ const shadow = PAGE_SHADOW;
return {
x: pageDimensions.x + shadow.left,
y: pageDimensions.y + shadow.top,
@@ -1192,7 +1288,7 @@ export class Viewport {
// TODO(raymes): This should really be set when the PDF plugin passes the
// page coordinates, but it isn't yet.
const x = (this.documentDimensions_.width - pageDimensions.width) / 2 +
- Viewport.PAGE_SHADOW.left;
+ PAGE_SHADOW.left;
// Compute the space on the left of the document if the document fits
// completely in the screen.
const zoom = this.getZoom();
@@ -1213,14 +1309,34 @@ export class Viewport {
* In a paged mode, page up and page down scroll to the top of the
* previous/next page and part of the page is under the toolbar.
* @return {boolean} Whether the current fitting type is a paged mode.
+ * @private
*/
- isPagedMode() {
+ isPagedMode_() {
return (
this.fittingType_ === FittingType.FIT_TO_PAGE ||
this.fittingType_ === FittingType.FIT_TO_HEIGHT);
}
/**
+ * Handles a navigation request to a destination from the current controller.
+ * @param {number} page
+ * @param {number} x
+ * @param {number} y
+ * @param {number} zoom
+ */
+ handleNavigateToDestination(page, x, y, zoom) {
+ if (zoom) {
+ this.setZoom(zoom);
+ }
+
+ if (x || y) {
+ this.goToPageAndXY(page, x ? x : 0, y ? y : 0);
+ } else {
+ this.goToPage(page);
+ }
+ }
+
+ /**
* @param {!PartialPoint} point The position to which to scroll the viewport.
*/
scrollTo(point) {
@@ -1254,6 +1370,112 @@ export class Viewport {
this.tracker_.removeAll();
}
}
+
+ /**
+ * A callback that's called when an update to a pinch zoom is detected.
+ * @param {!CustomEvent<!PinchEventDetail>} e the pinch event.
+ * @private
+ */
+ onPinchUpdate_(e) {
+ // Throttle number of pinch events to one per frame.
+ if (this.sentPinchEvent_) {
+ return;
+ }
+
+ this.sentPinchEvent_ = true;
+ this.window_.requestAnimationFrame(() => {
+ this.sentPinchEvent_ = false;
+ this.mightZoom_(() => {
+ const {direction, center, startScaleRatio} = e.detail;
+ this.pinchPhase_ = direction === 'out' ?
+ Viewport.PinchPhase.PINCH_UPDATE_ZOOM_OUT :
+ Viewport.PinchPhase.PINCH_UPDATE_ZOOM_IN;
+
+ const scaleDelta = startScaleRatio / this.prevScale_;
+ if (this.firstPinchCenterInFrame_ != null) {
+ this.pinchPanVector_ =
+ vectorDelta(center, this.firstPinchCenterInFrame_);
+ }
+
+ const needsScrollbars =
+ this.documentNeedsScrollbars(this.zoomManager_.applyBrowserZoom(
+ this.clampZoom_(this.internalZoom_ * scaleDelta)));
+
+ this.pinchCenter_ = center;
+
+ // If there's no horizontal scrolling, keep the content centered so
+ // the user can't zoom in on the non-content area.
+ // TODO(mcnee) Investigate other ways of scaling when we don't have
+ // horizontal scrolling. We want to keep the document centered,
+ // but this causes a potentially awkward transition when we start
+ // using the gesture center.
+ if (!needsScrollbars.horizontal) {
+ this.pinchCenter_ = {
+ x: this.window_.innerWidth / 2,
+ y: this.window_.innerHeight / 2
+ };
+ } else if (this.keepContentCentered_) {
+ this.oldCenterInContent_ =
+ this.frameToContent_(this.frameToPluginCoordinate_(center));
+ this.keepContentCentered_ = false;
+ }
+
+ this.setPinchZoomInternal_(
+ scaleDelta, this.frameToPluginCoordinate_(center));
+ this.updateViewport_();
+ this.prevScale_ = /** @type {number} */ (startScaleRatio);
+ });
+ });
+ }
+
+ /**
+ * A callback that's called when the end of a pinch zoom is detected.
+ * @param {!CustomEvent<!PinchEventDetail>} e the pinch event.
+ * @private
+ */
+ onPinchEnd_(e) {
+ // Using rAF for pinch end prevents pinch updates scheduled by rAF getting
+ // sent after the pinch end.
+ this.window_.requestAnimationFrame(() => {
+ this.mightZoom_(() => {
+ const {center, startScaleRatio} = e.detail;
+ this.pinchPhase_ = Viewport.PinchPhase.PINCH_END;
+ const scaleDelta = startScaleRatio / this.prevScale_;
+ this.pinchCenter_ = /** @type {!Point} */ (center);
+
+ this.setPinchZoomInternal_(
+ scaleDelta, this.frameToPluginCoordinate_(center));
+ this.updateViewport_();
+ });
+
+ this.pinchPhase_ = Viewport.PinchPhase.PINCH_NONE;
+ this.pinchPanVector_ = null;
+ this.pinchCenter_ = null;
+ this.firstPinchCenterInFrame_ = null;
+ });
+ }
+
+ /**
+ * A callback that's called when the start of a pinch zoom is detected.
+ * @param {!CustomEvent<!PinchEventDetail>} e the pinch event.
+ * @private
+ */
+ onPinchStart_(e) {
+ // We also use rAF for pinch start, so that if there is a pinch end event
+ // scheduled by rAF, this pinch start will be sent after.
+ this.window_.requestAnimationFrame(() => {
+ this.pinchPhase_ = Viewport.PinchPhase.PINCH_START;
+ this.prevScale_ = 1;
+ this.oldCenterInContent_ =
+ this.frameToContent_(this.frameToPluginCoordinate_(e.detail.center));
+
+ const needsScrollbars = this.documentNeedsScrollbars(this.getZoom());
+ this.keepContentCentered_ = !needsScrollbars.horizontal;
+ // We keep track of beginning of the pinch.
+ // By doing so we will be able to compute the pan distance.
+ this.firstPinchCenterInFrame_ = e.detail.center;
+ });
+ }
}
/**
@@ -1274,11 +1496,15 @@ Viewport.PinchPhase = {
* keys are pressed. Usually we just let the browser handle scrolling on the
* window when these keys are pressed but in certain cases we need to simulate
* these events.
+ * @type {number}
*/
-Viewport.SCROLL_INCREMENT = 40;
+const SCROLL_INCREMENT = 40;
-/** The width of the page shadow around pages in pixels. */
-Viewport.PAGE_SHADOW = {
+/**
+ * The width of the page shadow around pages in pixels.
+ * @type {!{top: number, bottom: number, left: number, right: number}}
+ */
+export const PAGE_SHADOW = {
top: 3,
bottom: 7,
left: 5,
diff --git a/chromium/chrome/browser/resources/pdf/viewport_scroller.js b/chromium/chrome/browser/resources/pdf/viewport_scroller.js
index c0d8fe4f45f..8d0186ce3d9 100644
--- a/chromium/chrome/browser/resources/pdf/viewport_scroller.js
+++ b/chromium/chrome/browser/resources/pdf/viewport_scroller.js
@@ -2,12 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-/**
- * Creates a new ViewportScroller.
- * A ViewportScroller scrolls the page in response to drag selection with the
- * mouse.
- *
- */
+// Scrolls the page in response to drag selection with the mouse.
export class ViewportScroller {
/**
* @param {Object} viewport The viewport info of the page.
@@ -27,7 +22,6 @@ export class ViewportScroller {
/**
* Start scrolling the page by |scrollVelocity_| every
* |DRAG_TIMER_INTERVAL_MS_|.
- *
* @private
*/
startDragScrollTimer_() {
@@ -41,7 +35,6 @@ export class ViewportScroller {
/**
* Stops the drag scroll timer if it is active.
- *
* @private
*/
stopDragScrollTimer_() {
@@ -54,7 +47,6 @@ export class ViewportScroller {
/**
* Scrolls the viewport by the current scroll velocity.
- *
* @private
*/
dragScrollPage_() {
@@ -71,7 +63,6 @@ export class ViewportScroller {
/**
* Calculate the velocity to scroll while dragging using the distance of the
* cursor outside the viewport.
- *
* @param {Object} event The mousemove event.
* @return {Object} Object with x and y direction scroll velocity.
* @private
@@ -95,7 +86,6 @@ export class ViewportScroller {
/**
* Handles mousemove events. It updates the scroll velocity and starts and
* stops timer based on scroll velocity.
- *
* @param {Object} event The mousemove event.
* @private
*/
@@ -111,7 +101,6 @@ export class ViewportScroller {
/**
* Sets whether to scroll the viewport when the mouse is outside the
* viewport.
- *
* @param {boolean} isSelecting Represents selection status.
*/
setEnableScrolling(isSelecting) {
@@ -134,14 +123,12 @@ export class ViewportScroller {
/**
* The period of time in milliseconds to wait between updating the viewport
* position by the scroll velocity.
- *
* @private
*/
ViewportScroller.DRAG_TIMER_INTERVAL_MS_ = 100;
/**
* The maximum drag scroll distance per DRAG_TIMER_INTERVAL in pixels.
- *
* @private
*/
ViewportScroller.MAX_DRAG_SCROLL_DISTANCE_ = 100;
diff --git a/chromium/chrome/browser/resources/pdf/zoom_manager.js b/chromium/chrome/browser/resources/pdf/zoom_manager.js
index bb4e687e02c..bab9f2ec738 100644
--- a/chromium/chrome/browser/resources/pdf/zoom_manager.js
+++ b/chromium/chrome/browser/resources/pdf/zoom_manager.js
@@ -6,11 +6,8 @@ import {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_t
import {BrowserApi} from './browser_api.js';
-/**
- * Abstract parent of classes that manage updating the browser
- * with zoom changes and/or updating the viewer's zoom when
- * the browser zoom changes.
- */
+// Abstract parent of classes that manage updating the browser with zoom changes
+// and/or updating the viewer's zoom when the browser zoom changes.
export class ZoomManager {
/**
* @param {function():number} getViewportZoom Callback to get the viewport's
@@ -39,7 +36,6 @@ export class ZoomManager {
/**
* Creates the appropriate kind of zoom manager given the zoom behavior.
- *
* @param {BrowserApi.ZoomBehavior} zoomBehavior How to manage zoom.
* @param {function():number} getViewportZoom A function that gets the current
* viewport zoom.
@@ -62,20 +58,16 @@ export class ZoomManager {
/**
* Invoked when a browser-initiated zoom-level change occurs.
- *
* @param {number} newZoom the zoom level to zoom to.
*/
onBrowserZoomChange(newZoom) {}
- /**
- * Invoked when an extension-initiated zoom-level change occurs.
- */
+ /** Invoked when an extension-initiated zoom-level change occurs. */
onPdfZoomChange() {}
/**
* Combines the internal pdf zoom and the browser zoom to
* produce the total zoom level for the viewer.
- *
* @param {number} internalZoom the zoom level internal to the viewer.
* @return {number} the total zoom level.
*/
@@ -86,7 +78,6 @@ export class ZoomManager {
/**
* Given a zoom level, return the internal zoom level needed to
* produce that zoom level.
- *
* @param {number} totalZoom the total zoom level.
* @return {number} the zoom level internal to the viewer.
*/
@@ -96,7 +87,6 @@ export class ZoomManager {
/**
* Returns whether two numbers are approximately equal.
- *
* @param {number} a The first number.
* @param {number} b The second number.
*/
@@ -109,15 +99,11 @@ export class ZoomManager {
}
}
-/**
- * InactiveZoomManager has no control over the browser's zoom
- * and does not respond to browser zoom changes.
- */
+// Has no control over the browser's zoom and does not respond to browser zoom
+// changes.
export class InactiveZoomManager extends ZoomManager {}
-/**
- * ActiveZoomManager controls the browser's zoom.
- */
+// ActiveZoomManager controls the browser's zoom.
class ActiveZoomManager extends ZoomManager {
/**
* Constructs a ActiveZoomManager.
@@ -139,7 +125,6 @@ class ActiveZoomManager extends ZoomManager {
/**
* Invoked when a browser-initiated zoom-level change occurs.
- *
* @param {number} newZoom the zoom level to zoom to.
*/
onBrowserZoomChange(newZoom) {
@@ -193,7 +178,6 @@ class ActiveZoomManager extends ZoomManager {
/**
* Combines the internal pdf zoom and the browser zoom to
* produce the total zoom level for the viewer.
- *
* @param {number} internalZoom the zoom level internal to the viewer.
* @return {number} the total zoom level.
*/
@@ -206,7 +190,6 @@ class ActiveZoomManager extends ZoomManager {
/**
* Given a zoom level, return the internal zoom level needed to
* produce that zoom level.
- *
* @param {number} totalZoom the total zoom level.
* @return {number} the zoom level internal to the viewer.
*/
@@ -217,14 +200,11 @@ class ActiveZoomManager extends ZoomManager {
}
}
-/**
- * This EmbeddedZoomManager responds to changes in the browser zoom,
- * but does not control the browser zoom.
- */
+// Responds to changes in the browser zoom, but does not control the browser
+// zoom.
class EmbeddedZoomManager extends ZoomManager {
/**
* Invoked when a browser-initiated zoom-level change occurs.
- *
* @param {number} newZoom the new browser zoom level.
*/
onBrowserZoomChange(newZoom) {
diff --git a/chromium/chrome/browser/resources/print_preview/BUILD.gn b/chromium/chrome/browser/resources/print_preview/BUILD.gn
index 63df1dd2a18..abe2ff3da74 100644
--- a/chromium/chrome/browser/resources/print_preview/BUILD.gn
+++ b/chromium/chrome/browser/resources/print_preview/BUILD.gn
@@ -44,7 +44,7 @@ if (optimize_webui) {
]
deps = [
- "../pdf/elements:web_components",
+ "../pdf:web_components",
"ui:web_components",
]
defines = chrome_grit_defines
@@ -74,10 +74,23 @@ js_type_check("print_preview_module_resources") {
":dark_mode_behavior",
":metrics",
":native_layer",
+ ":print_preview",
":print_preview_utils",
]
}
+js_library("print_preview") {
+ deps = [
+ ":cloud_print_interface",
+ ":native_layer",
+ "data:destination",
+ "data:destination_store",
+ "data:measurement_system",
+ "ui:app",
+ "ui:settings_select",
+ ]
+}
+
js_library("print_preview_utils") {
deps = [
":dark_mode_behavior",
@@ -118,6 +131,7 @@ js_library("native_layer") {
"data:destination_match",
"data:destination_policies",
"data:measurement_system",
+ "data:printer_status_cros",
"//ui/webui/resources/js:assert.m",
"//ui/webui/resources/js:cr.m",
]
diff --git a/chromium/chrome/browser/resources/print_preview/data/BUILD.gn b/chromium/chrome/browser/resources/print_preview/data/BUILD.gn
index 030f5a2088f..61a94abfa0a 100644
--- a/chromium/chrome/browser/resources/print_preview/data/BUILD.gn
+++ b/chromium/chrome/browser/resources/print_preview/data/BUILD.gn
@@ -22,6 +22,7 @@ js_type_check("closure_compile_module") {
":measurement_system",
":model",
":printable_area",
+ ":printer_status_cros",
":scaling",
":size",
":state",
@@ -165,3 +166,6 @@ js_library("user_manager") {
"//ui/webui/resources/js:web_ui_listener_behavior.m",
]
}
+
+js_library("printer_status_cros") {
+}
diff --git a/chromium/chrome/browser/resources/print_preview/data/destination.js b/chromium/chrome/browser/resources/print_preview/data/destination.js
index 3c6155bd266..a6938175df1 100644
--- a/chromium/chrome/browser/resources/print_preview/data/destination.js
+++ b/chromium/chrome/browser/resources/print_preview/data/destination.js
@@ -10,6 +10,7 @@ import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
// <if expr="chromeos">
import {ColorModeRestriction, DestinationPolicies, DuplexModeRestriction, PinModeRestriction} from './destination_policies.js';
+import {PrinterStatusReason} from '../data/printer_status_cros.js';
// </if>
/**
@@ -139,7 +140,7 @@ export let VendorCapability;
* only on Chrome OS.
*
* @typedef {{
- * vendor_capability: !Array<!VendorCapability>,
+ * vendor_capability: (Array<!VendorCapability>|undefined),
* collate: ({default: (boolean|undefined)}|undefined),
* color: ({
* option: !Array<{
@@ -162,7 +163,8 @@ export let VendorCapability;
* type: (string|undefined),
* vendor_id: (string|undefined),
* custom_display_name: (string|undefined),
- * is_default: (boolean|undefined)
+ * is_default: (boolean|undefined),
+ * name: (string|undefined),
* }>
* }|undefined),
* dpi: ({
@@ -412,6 +414,12 @@ export class Destination {
* @private {string}
*/
this.eulaUrl_ = '';
+
+ /**
+ * Stores the printer status reason for a local Chrome OS printer.
+ * @private {!PrinterStatusReason}
+ */
+ this.printerStatusReason_ = PrinterStatusReason.UNKNOWN_REASON;
// </if>
assert(
@@ -597,6 +605,22 @@ export class Destination {
set eulaUrl(eulaUrl) {
this.eulaUrl_ = eulaUrl;
}
+
+ /**
+ * @return {!PrinterStatusReason} The printer status reason for a local
+ * Chrome OS printer.
+ */
+ get printerStatusReason() {
+ return this.printerStatusReason_;
+ }
+
+ /**
+ * @param {!PrinterStatusReason} printerStatusReason The printer status reason
+ * to be set.
+ */
+ set printerStatusReason(printerStatusReason) {
+ this.printerStatusReason_ = printerStatusReason;
+ }
// </if>
/**
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 f8b40cdd974..2844928fe10 100644
--- a/chromium/chrome/browser/resources/print_preview/data/destination_store.js
+++ b/chromium/chrome/browser/resources/print_preview/data/destination_store.js
@@ -10,7 +10,7 @@ import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {CloudPrintInterface, CloudPrintInterfaceEventType, CloudPrintInterfacePrinterFailedDetail, CloudPrintInterfaceProcessInviteDetail, CloudPrintInterfaceSearchDoneDetail} from '../cloud_print_interface.js';
import {Metrics, MetricsContext} from '../metrics.js';
-import {CapabilitiesResponse, LocalDestinationInfo, NativeLayer, PrinterSetupResponse, PrivetPrinterDescription, ProvisionalDestinationInfo} from '../native_layer.js';
+import {CapabilitiesResponse, LocalDestinationInfo, NativeLayer, NativeLayerImpl, PrinterSetupResponse, PrivetPrinterDescription, ProvisionalDestinationInfo} from '../native_layer.js';
import {Cdd, CloudOrigins, createDestinationKey, createRecentDestinationKey, Destination, DestinationConnectionStatus, DestinationOrigin, DestinationProvisionalType, DestinationType, RecentDestination} from './destination.js';
import {DestinationMatch, originToType, PrinterType} from './destination_match.js';
@@ -229,7 +229,7 @@ export class DestinationStore extends EventTarget {
* Used to fetch local print destinations.
* @private {!NativeLayer}
*/
- this.nativeLayer_ = NativeLayer.getInstance();
+ this.nativeLayer_ = NativeLayerImpl.getInstance();
/**
* Whether PDF printer is enabled. It's disabled, for example, in App
diff --git a/chromium/chrome/browser/resources/print_preview/data/model.js b/chromium/chrome/browser/resources/print_preview/data/model.js
index 8eea52a6e5f..b0a3948e24e 100644
--- a/chromium/chrome/browser/resources/print_preview/data/model.js
+++ b/chromium/chrome/browser/resources/print_preview/data/model.js
@@ -10,7 +10,7 @@ import {Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.m
import {BackgroundGraphicsModeRestriction, Policies} from '../native_layer.js';
-import {Cdd, CddCapabilities, Destination, DestinationOrigin, DestinationType, RecentDestination} from './destination.js';
+import {Cdd, CddCapabilities, Destination, DestinationOrigin, DestinationType, RecentDestination, VendorCapability} from './destination.js';
import {getPrinterTypeForDestination} from './destination_match.js';
// <if expr="chromeos">
import {ColorModeRestriction, DuplexModeRestriction, PinModeRestriction} from './destination_policies.js';
@@ -44,6 +44,7 @@ export let Setting;
* collate: !Setting,
* layout: !Setting,
* color: !Setting,
+ * customMargins: !Setting,
* mediaSize: !Setting,
* margins: !Setting,
* dpi: !Setting,
@@ -950,7 +951,8 @@ Polymer({
if (this.settings.vendorItems.available) {
const vendorSettings = {};
- for (const item of caps.vendor_capability) {
+ for (const item of /** @type {!Array<!VendorCapability>} */ (
+ caps.vendor_capability)) {
let defaultValue = null;
if (item.type === 'SELECT' && item.select_cap &&
item.select_cap.option) {
diff --git a/chromium/chrome/browser/resources/print_preview/data/printer_status_cros.js b/chromium/chrome/browser/resources/print_preview/data/printer_status_cros.js
new file mode 100644
index 00000000000..0cc0c513121
--- /dev/null
+++ b/chromium/chrome/browser/resources/print_preview/data/printer_status_cros.js
@@ -0,0 +1,56 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * These values must be kept in sync with the Reason enum in
+ * /chromeos/printing/cups_printer_status.h
+ * @enum {number}
+ */
+export const PrinterStatusReason = {
+ CONNECTING_TO_DEVICE: 0,
+ DEVICE_ERROR: 1,
+ DOOR_OPEN: 2,
+ LOW_ON_INK: 3,
+ LOW_ON_PAPER: 4,
+ NO_ERROR: 5,
+ OUT_OF_INK: 6,
+ OUT_OF_PAPER: 7,
+ OUTPUT_ALMOST_FULL: 8,
+ OUTPUT_FULL: 9,
+ PAPER_JAM: 10,
+ PAUSED: 11,
+ PRINTER_QUEUE_FULL: 12,
+ PRINTER_UNREACHABLE: 13,
+ STOPPED: 14,
+ TRAY_MISSING: 15,
+ UNKNOWN_REASON: 16,
+};
+
+/**
+ * These values must be kept in sync with the Severity enum in
+ * /chromeos/printing/cups_printer_status.h
+ * @enum {number}
+ */
+export const PrinterStatusSeverity = {
+ UNKOWN_SEVERITY: 0,
+ REPORT: 1,
+ WARNING: 2,
+ ERROR: 3,
+};
+
+/**
+ * A container for the results of a printer status query. A printer status query
+ * can return multiple error reasons. |timestamp| is set at the time of status
+ * creation.
+ *
+ * @typedef {{
+ * printerId: string,
+ * statusReasons: !Array<{
+ * reason: PrinterStatusReason,
+ * severity: PrinterStatusSeverity,
+ * }>,
+ * timestamp: number,
+ * }}
+ */
+export let PrinterStatus;
diff --git a/chromium/chrome/browser/resources/print_preview/metrics.js b/chromium/chrome/browser/resources/print_preview/metrics.js
index 34325bc2883..dc889e6ad99 100644
--- a/chromium/chrome/browser/resources/print_preview/metrics.js
+++ b/chromium/chrome/browser/resources/print_preview/metrics.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.
-import {NativeLayer} from './native_layer.js';
+import {NativeLayer, NativeLayerImpl} from './native_layer.js';
/**
* Object used to measure usage statistics.
@@ -89,7 +89,7 @@ export class MetricsContext {
this.maxBucket_ = maxBucket;
/** @private {!NativeLayer} */
- this.nativeLayer_ = NativeLayer.getInstance();
+ this.nativeLayer_ = NativeLayerImpl.getInstance();
}
/**
diff --git a/chromium/chrome/browser/resources/print_preview/native_layer.js b/chromium/chrome/browser/resources/print_preview/native_layer.js
index ff0c3d18686..a7f13fc56bb 100644
--- a/chromium/chrome/browser/resources/print_preview/native_layer.js
+++ b/chromium/chrome/browser/resources/print_preview/native_layer.js
@@ -3,12 +3,13 @@
// found in the LICENSE file.
import {assert} from 'chrome://resources/js/assert.m.js';
-import {sendWithPromise} from 'chrome://resources/js/cr.m.js';
+import {addSingletonGetter, sendWithPromise} from 'chrome://resources/js/cr.m.js';
import {Cdd, Destination} from './data/destination.js';
import {PrinterType} from './data/destination_match.js';
// <if expr="chromeos">
import {DestinationPolicies} from './data/destination_policies.js';
+import {PrinterStatus} from './data/printer_status_cros.js';
// </if>
import {MeasurementSystemUnitType} from './data/measurement_system.js';
@@ -118,7 +119,7 @@ export let PrivetPrinterDescription;
* printer:(PrivetPrinterDescription |
* LocalDestinationInfo |
* undefined),
- * capabilities: !Cdd,
+ * capabilities: ?Cdd,
* }}
*/
export let CapabilitiesResponse;
@@ -146,44 +147,22 @@ export let ProvisionalDestinationInfo;
/**
* An interface to the native Chromium printing system layer.
+ * @interface
*/
export class NativeLayer {
- /**
- * Creates a new NativeLayer if the current instance is not set.
- * @return {!NativeLayer} The singleton instance.
- */
- static getInstance() {
- if (currentInstance === null) {
- currentInstance = new NativeLayer();
- }
- return assert(currentInstance);
- }
-
- /**
- * @param {!NativeLayer} instance The NativeLayer instance
- * to set for print preview construction.
- */
- static setInstance(instance) {
- currentInstance = instance;
- }
-
// <if expr="chromeos">
/**
* Requests access token for cloud print requests for DEVICE origin.
* @return {!Promise<string>}
*/
- getAccessToken() {
- return sendWithPromise('getAccessToken');
- }
+ getAccessToken() {}
// </if>
/**
* Gets the initial settings to initialize the print preview with.
* @return {!Promise<!NativeInitialSettings>}
*/
- getInitialSettings() {
- return sendWithPromise('getInitialSettings');
- }
+ getInitialSettings() {}
/**
* Requests the system's print destinations. The promise will be resolved
@@ -193,9 +172,7 @@ export class NativeLayer {
* request.
* @return {!Promise}
*/
- getPrinters(type) {
- return sendWithPromise('getPrinters', type);
- }
+ getPrinters(type) {}
/**
* Requests the destination's printing capabilities. Returns a promise that
@@ -204,13 +181,7 @@ export class NativeLayer {
* @param {!PrinterType} type The destination's printer type.
* @return {!Promise<!CapabilitiesResponse>}
*/
- getPrinterCapabilities(destinationId, type) {
- return sendWithPromise(
- 'getPrinterCapabilities', destinationId,
- destinationId === Destination.GooglePromotedId.SAVE_AS_PDF ?
- PrinterType.PDF_PRINTER :
- type);
- }
+ getPrinterCapabilities(destinationId, type) {}
// <if expr="chromeos">
/**
@@ -220,9 +191,7 @@ export class NativeLayer {
* @param {!string} destinationId ID of the destination.
* @return {!Promise<string>}
*/
- getEulaUrl(destinationId) {
- return sendWithPromise('getEulaUrl', destinationId);
- }
+ getEulaUrl(destinationId) {}
/**
* Requests Chrome to resolve provisional extension destination by granting
@@ -230,19 +199,14 @@ export class NativeLayer {
* @param {string} provisionalDestinationId
* @return {!Promise<!ProvisionalDestinationInfo>}
*/
- grantExtensionPrinterAccess(provisionalDestinationId) {
- return sendWithPromise(
- 'grantExtensionPrinterAccess', provisionalDestinationId);
- }
+ grantExtensionPrinterAccess(provisionalDestinationId) {}
/**
* Requests that Chrome perform printer setup for the given printer.
* @param {string} printerId
* @return {!Promise<!PrinterSetupResponse>}
*/
- setupPrinter(printerId) {
- return sendWithPromise('setupPrinter', printerId);
- }
+ setupPrinter(printerId) {}
// </if>
/**
@@ -256,17 +220,13 @@ export class NativeLayer {
* @return {!Promise<number>} Promise that resolves with the unique ID of
* the preview UI when the preview has been generated.
*/
- getPreview(printTicket) {
- return sendWithPromise('getPreview', printTicket);
- }
+ getPreview(printTicket) {}
/**
* Opens the chrome://settings printing page. For Chrome OS, open the
- * printing settings in the Settings App.
+ * printing settings in the Settings App.
*/
- openSettingsPrintPage() {
- chrome.send('openPrinterSettings');
- }
+ openSettingsPrintPage() {}
/**
* Requests that the document be printed.
@@ -275,28 +235,20 @@ export class NativeLayer {
* @return {!Promise} Promise that will resolve when the print request is
* finished or rejected.
*/
- print(printTicket) {
- return sendWithPromise('print', printTicket);
- }
+ print(printTicket) {}
/** Requests that the current pending print request be cancelled. */
- cancelPendingPrintRequest() {
- chrome.send('cancelPendingPrintRequest');
- }
+ cancelPendingPrintRequest() {}
/**
* Sends the app state to be saved in the sticky settings.
* @param {string} appStateStr JSON string of the app state to persist.
*/
- saveAppState(appStateStr) {
- chrome.send('saveAppState', [appStateStr]);
- }
+ saveAppState(appStateStr) {}
// <if expr="not chromeos and not is_win">
/** Shows the system's native printing dialog. */
- showSystemDialog() {
- chrome.send('showSystemDialog');
- }
+ showSystemDialog() {}
// </if>
/**
@@ -306,17 +258,10 @@ export class NativeLayer {
* @param {boolean} isCancel whether this was called due to the user
* closing the dialog without printing.
*/
- dialogClose(isCancel) {
- if (isCancel) {
- chrome.send('closePrintPreviewDialog');
- }
- chrome.send('dialogClose');
- }
+ dialogClose(isCancel) {}
/** Hide the print preview dialog and allow the native layer to close it. */
- hidePreview() {
- chrome.send('hidePreview');
- }
+ hidePreview() {}
/**
* Opens the Google Cloud Print sign-in tab. If the user signs in
@@ -324,26 +269,16 @@ export class NativeLayer {
* @param {boolean} addAccount Whether to open an 'add a new account' or
* default sign in page.
*/
- signIn(addAccount) {
- chrome.send('signIn', [addAccount]);
- }
-
- /**
- * Sends a message to the test, letting it know that an
- * option has been set to a particular value and that the change has
- * finished modifying the preview area.
- */
- uiLoadedForTest() {
- chrome.send('UILoadedForTest');
- }
+ signIn(addAccount) {}
+ // <if expr="chromeos">
/**
- * Notifies the test that the option it tried to change
- * had not been changed successfully.
+ * Sends a request to the printer with id |printerId| for its current status.
+ * @param {string} printerId
+ * @return {!Promise<!PrinterStatus>}
*/
- uiFailedLoadingForTest() {
- chrome.send('UIFailedLoadingForTest');
- }
+ requestPrinterStatusUpdate(printerId) {}
+ // </if>
/**
* Notifies the metrics handler to record a histogram value.
@@ -351,11 +286,117 @@ export class NativeLayer {
* @param {number} bucket The bucket to record
* @param {number} maxBucket The maximum bucket value in the histogram.
*/
+ recordInHistogram(histogram, bucket, maxBucket) {}
+}
+
+/** @implements {NativeLayer} */
+export class NativeLayerImpl {
+ // <if expr="chromeos">
+ /** @override */
+ getAccessToken() {
+ return sendWithPromise('getAccessToken');
+ }
+ // </if>
+
+ /** @override */
+ getInitialSettings() {
+ return sendWithPromise('getInitialSettings');
+ }
+
+ /** @override */
+ getPrinters(type) {
+ return sendWithPromise('getPrinters', type);
+ }
+
+ /** @override */
+ getPrinterCapabilities(destinationId, type) {
+ return sendWithPromise(
+ 'getPrinterCapabilities', destinationId,
+ destinationId === Destination.GooglePromotedId.SAVE_AS_PDF ?
+ PrinterType.PDF_PRINTER :
+ type);
+ }
+
+ // <if expr="chromeos">
+ /** @override */
+ getEulaUrl(destinationId) {
+ return sendWithPromise('getEulaUrl', destinationId);
+ }
+
+ /** @override */
+ grantExtensionPrinterAccess(provisionalDestinationId) {
+ return sendWithPromise(
+ 'grantExtensionPrinterAccess', provisionalDestinationId);
+ }
+
+ /** @override */
+ setupPrinter(printerId) {
+ return sendWithPromise('setupPrinter', printerId);
+ }
+ // </if>
+
+ /** @override */
+ getPreview(printTicket) {
+ return sendWithPromise('getPreview', printTicket);
+ }
+
+ /** @override */
+ openSettingsPrintPage() {
+ chrome.send('openPrinterSettings');
+ }
+
+ /** @override */
+ print(printTicket) {
+ return sendWithPromise('print', printTicket);
+ }
+
+ /** @override */
+ cancelPendingPrintRequest() {
+ chrome.send('cancelPendingPrintRequest');
+ }
+
+ /** @override */
+ saveAppState(appStateStr) {
+ chrome.send('saveAppState', [appStateStr]);
+ }
+
+ // <if expr="not chromeos and not is_win">
+ /** @override */
+ showSystemDialog() {
+ chrome.send('showSystemDialog');
+ }
+ // </if>
+
+ /** @override */
+ dialogClose(isCancel) {
+ if (isCancel) {
+ chrome.send('closePrintPreviewDialog');
+ }
+ chrome.send('dialogClose');
+ }
+
+ /** @override */
+ hidePreview() {
+ chrome.send('hidePreview');
+ }
+
+ /** @override */
+ signIn(addAccount) {
+ chrome.send('signIn', [addAccount]);
+ }
+
+ // <if expr="chromeos">
+ /** @override */
+ requestPrinterStatusUpdate(printerId) {
+ return sendWithPromise('requestPrinterStatus', printerId);
+ }
+ // </if>
+
+ /** @override */
recordInHistogram(histogram, bucket, maxBucket) {
chrome.send(
'metricsHandler:recordInHistogram', [histogram, bucket, maxBucket]);
}
}
-/** @private {?NativeLayer} */
-let currentInstance = null;
+addSingletonGetter(NativeLayerImpl);
diff --git a/chromium/chrome/browser/resources/print_preview/print_preview.html b/chromium/chrome/browser/resources/print_preview/print_preview.html
index 4aa26d79dbd..6a792ccc483 100644
--- a/chromium/chrome/browser/resources/print_preview/print_preview.html
+++ b/chromium/chrome/browser/resources/print_preview/print_preview.html
@@ -1,6 +1,5 @@
<!doctype html>
-<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{a11yenhanced}
- class="loading">
+<html dir="$i18n{textdirection}" lang="$i18n{language}" class="loading">
<head>
<title>$i18n{title}</title>
<meta charset="utf-8">
diff --git a/chromium/chrome/browser/resources/print_preview/print_preview.js b/chromium/chrome/browser/resources/print_preview/print_preview.js
index 21658c88e7f..10d3ac4aae4 100644
--- a/chromium/chrome/browser/resources/print_preview/print_preview.js
+++ b/chromium/chrome/browser/resources/print_preview/print_preview.js
@@ -4,25 +4,30 @@
import './ui/app.js';
+export {PluralStringProxyImpl as PrintPreviewPluralStringProxyImpl} from 'chrome://resources/js/plural_string_proxy.js';
export {CloudPrintInterface, CloudPrintInterfaceEventType} from './cloud_print_interface.js';
export {CloudPrintInterfaceImpl} from './cloud_print_interface_impl.js';
-export {ColorMode, createDestinationKey, Destination, DestinationCertificateStatus, DestinationConnectionStatus, DestinationOrigin, DestinationType, makeRecentDestination} from './data/destination.js';
+export {ColorMode, createDestinationKey, Destination, DestinationCertificateStatus, DestinationConnectionStatus, DestinationOrigin, DestinationType, makeRecentDestination, RecentDestination} from './data/destination.js';
export {PrinterType} from './data/destination_match.js';
// <if expr="chromeos">
export {ColorModeRestriction, DuplexModeRestriction, PinModeRestriction} from './data/destination_policies.js';
+export {PrinterStatus, PrinterStatusReason, PrinterStatusSeverity} from './data/printer_status_cros.js';
+export {PrinterState} from './ui/printer_status_icon_cros.js';
// </if>
export {DestinationErrorType, DestinationStore} from './data/destination_store.js';
+export {PageLayoutInfo} from './data/document_info.js';
export {InvitationStore} from './data/invitation_store.js';
-export {CustomMarginsOrientation, Margins, MarginsType} from './data/margins.js';
+export {CustomMarginsOrientation, Margins, MarginsSetting, MarginsType} from './data/margins.js';
export {MeasurementSystem, MeasurementSystemUnitType} from './data/measurement_system.js';
export {DuplexMode, DuplexType, getInstance, whenReady} from './data/model.js';
export {ScalingType} from './data/scaling.js';
export {Size} from './data/size.js';
export {Error, State} from './data/state.js';
-export {BackgroundGraphicsModeRestriction, NativeLayer} from './native_layer.js';
+export {BackgroundGraphicsModeRestriction, CapabilitiesResponse, LocalDestinationInfo, NativeInitialSettings, NativeLayer, NativeLayerImpl, PrinterSetupResponse, ProvisionalDestinationInfo} from './native_layer.js';
export {getSelectDropdownBackground} from './print_preview_utils.js';
export {DEFAULT_MAX_COPIES} from './ui/copies_settings.js';
export {DestinationState} from './ui/destination_settings.js';
export {PluginProxy} from './ui/plugin_proxy.js';
export {PreviewAreaState} from './ui/preview_area.js';
export {SelectBehavior} from './ui/select_behavior.js';
+export {SelectOption} from './ui/settings_select.js';
diff --git a/chromium/chrome/browser/resources/print_preview/print_preview_pdf_resources.grd b/chromium/chrome/browser/resources/print_preview/print_preview_pdf_resources.grd
new file mode 100644
index 00000000000..d8483272925
--- /dev/null
+++ b/chromium/chrome/browser/resources/print_preview/print_preview_pdf_resources.grd
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<grit latest_public_release="0" current_release="1" output_all_resource_defines="false">
+ <outputs>
+ <output filename="grit/print_preview_pdf_resources.h" type="rc_header">
+ <emit emit_type='prepend'></emit>
+ </output>
+ <output filename="grit/print_preview_pdf_resources_map.cc"
+ type="resource_file_map_source" />
+ <output filename="grit/print_preview_pdf_resources_map.h"
+ type="resource_map_header" />
+ <output filename="print_preview_pdf_resources.pak" type="data_package" />
+ </outputs>
+ <release seq="1">
+ <includes>
+ <include name="IDR_PRINT_PREVIEW_PDF_INDEX_PP_HTML"
+ file="../pdf/index_pp.html"
+ type="BINDATA" />
+ <include name="IDR_PRINT_PREVIEW_PDF_PDF_VIEWER_PP_JS"
+ file="${root_gen_dir}/chrome/browser/resources/pdf/pdf_viewer_pp.js"
+ use_base_dir="false"
+ type="BINDATA" />
+ <include name="IDR_PRINT_PREVIEW_PDF_VIEWER_PAGE_INDICATOR_JS"
+ file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-page-indicator.js"
+ use_base_dir="false"
+ type="BINDATA" />
+ </includes>
+ </release>
+</grit>
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 8f7cd3fe0b5..9bbd50d630f 100644
--- a/chromium/chrome/browser/resources/print_preview/print_preview_resources.grd
+++ b/chromium/chrome/browser/resources/print_preview/print_preview_resources.grd
@@ -49,6 +49,12 @@
<include name="IDR_PRINT_PREVIEW_UI_DESTINATION_SELECT_CROS_JS"
file="${root_gen_dir}/chrome/browser/resources/print_preview/ui/destination_select_cros.js"
use_base_dir="false" compress="false" type="BINDATA"/>
+ <include name="IDR_PRINT_PREVIEW_UI_PRINT_PREVIEW_DESTINATION_DROPDOWN_CROS_JS"
+ file="${root_gen_dir}/chrome/browser/resources/print_preview/ui/destination_dropdown_cros.js"
+ use_base_dir="false" compress="false" type="BINDATA"/>
+ <include name="IDR_PRINT_PREVIEW_UI_PRINT_PREVIEW_PRINTER_STATUS_ICON_CROS_JS"
+ file="${root_gen_dir}/chrome/browser/resources/print_preview/ui/printer_status_icon_cros.js"
+ use_base_dir="false" compress="false" type="BINDATA"/>
</if>
<include name="IDR_PRINT_PREVIEW_UI_DESTINATION_SELECT_CSS_JS"
file="${root_gen_dir}/chrome/browser/resources/print_preview/ui/destination_select_css.js"
@@ -141,16 +147,6 @@
<include name="IDR_PRINT_PREVIEW_UI_ICONS_JS"
file="${root_gen_dir}/chrome/browser/resources/print_preview/ui/icons.js"
use_base_dir="false" compress="false" type="BINDATA"/>
- <include name="IDR_PRINT_PREVIEW_PDF_INDEX_PP_HTML"
- file="../pdf/index_pp.html"
- type="BINDATA" />
- <include name="IDR_PRINT_PREVIEW_PDF_MAIN_PP_JS"
- file="../pdf/main_pp.js"
- type="BINDATA" />
- <include name="IDR_PRINT_PREVIEW_PDF_VIEWER_PAGE_INDICATOR_JS"
- file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-page-indicator.js"
- use_base_dir="false"
- type="BINDATA" />
</includes>
<structures>
<structure name="IDR_PRINT_PREVIEW_PRINT_PREVIEW_HTML"
@@ -196,6 +192,10 @@
file="data/destination_policies.js"
compress="false"
type="chrome_html" />
+ <structure name="IDR_PRINT_PREVIEW_DATA_PRINTER_STATUS_CROS_JS"
+ file="data/printer_status_cros.js"
+ compress="false"
+ type="chrome_html" />
</if>
<structure name="IDR_PRINT_PREVIEW_DATA_DESTINATION_STORE_JS"
file="data/destination_store.js"
diff --git a/chromium/chrome/browser/resources/print_preview/print_preview_resources_vulcanized.grd b/chromium/chrome/browser/resources/print_preview/print_preview_resources_vulcanized.grd
index 0eecabc3c5d..1ac21ce8b10 100644
--- a/chromium/chrome/browser/resources/print_preview/print_preview_resources_vulcanized.grd
+++ b/chromium/chrome/browser/resources/print_preview/print_preview_resources_vulcanized.grd
@@ -15,23 +15,11 @@
<include name="IDR_PRINT_PREVIEW_PRINT_PREVIEW_HTML"
file="print_preview.html"
type="chrome_html"
- preprocess="true"
- compress="gzip" />
+ preprocess="true" />
<include name="IDR_PRINT_PREVIEW_PRINT_PREVIEW_ROLLUP_JS"
file="${root_gen_dir}\chrome\browser\resources\print_preview\print_preview.rollup.js"
use_base_dir="false"
preprocess="true"
- compress="gzip"
- type="BINDATA" />
- <include name="IDR_PRINT_PREVIEW_PDF_INDEX_PP_HTML"
- file="../pdf/index_pp.html"
- type="BINDATA" />
- <include name="IDR_PRINT_PREVIEW_PDF_MAIN_PP_JS"
- file="../pdf/main_pp.js"
- type="BINDATA" />
- <include name="IDR_PRINT_PREVIEW_PDF_VIEWER_PAGE_INDICATOR_JS"
- file="${root_gen_dir}/chrome/browser/resources/pdf/elements/viewer-page-indicator.js"
- use_base_dir="false"
type="BINDATA" />
</includes>
</release>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/BUILD.gn b/chromium/chrome/browser/resources/print_preview/ui/BUILD.gn
index 860caec75e9..d95c0bb6565 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/BUILD.gn
+++ b/chromium/chrome/browser/resources/print_preview/ui/BUILD.gn
@@ -53,8 +53,10 @@ js_type_check("closure_compile_module") {
if (is_chromeos) {
deps += [
+ ":destination_dropdown_cros",
":destination_select_cros",
":pin_settings",
+ ":printer_status_icon_cros",
]
} else {
deps += [ ":destination_select" ]
@@ -117,6 +119,7 @@ js_library("button_strip") {
"../data:destination",
"../data:state",
"//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/js:plural_string_proxy",
]
if (is_chromeos) {
@@ -131,6 +134,7 @@ js_library("header") {
"../data:state",
"//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
"//ui/webui/resources/js:load_time_data.m",
+ "//ui/webui/resources/js:plural_string_proxy",
]
}
@@ -160,9 +164,11 @@ js_library("destination_settings") {
if (is_chromeos) {
js_library("destination_select_cros") {
deps = [
+ ":destination_dropdown_cros",
":select_behavior",
"..:print_preview_utils",
"../data:destination",
+ "../data:printer_status_cros",
"//third_party/polymer/v3_0/components-chromium/iron-iconset-svg:iron-iconset-svg",
"//third_party/polymer/v3_0/components-chromium/iron-meta:iron-meta",
"//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
@@ -178,6 +184,22 @@ if (is_chromeos) {
"//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
]
}
+
+ js_library("destination_dropdown_cros") {
+ deps = [
+ ":printer_status_icon_cros",
+ "..:print_preview_utils",
+ "//third_party/polymer/v3_0/components-chromium/iron-dropdown:iron-dropdown",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/cr_elements/cr_input:cr_input.m",
+ ]
+ }
+
+ js_library("printer_status_icon_cros") {
+ deps = [
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ ]
+ }
} else {
js_library("destination_select") {
deps = [
@@ -544,8 +566,10 @@ html_to_js("web_components") {
]
if (is_chromeos) {
js_files += [
+ "destination_dropdown_cros.js",
"destination_select_cros.js",
"pin_settings.js",
+ "printer_status_icon_cros.js",
]
} else {
js_files += [ "destination_select.js" ]
diff --git a/chromium/chrome/browser/resources/print_preview/ui/app.js b/chromium/chrome/browser/resources/print_preview/ui/app.js
index 575afacd7aa..5c7b6601686 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/app.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/app.js
@@ -26,7 +26,7 @@ import {DuplexMode, whenReady} from '../data/model.js';
import {PrintableArea} from '../data/printable_area.js';
import {Size} from '../data/size.js';
import {Error, State} from '../data/state.js';
-import {NativeInitialSettings, NativeLayer} from '../native_layer.js';
+import {NativeInitialSettings, NativeLayer, NativeLayerImpl} from '../native_layer.js';
import {DestinationState} from './destination_settings.js';
import {PreviewAreaState} from './preview_area.js';
@@ -168,7 +168,7 @@ Polymer({
/** @override */
attached() {
document.documentElement.classList.remove('loading');
- this.nativeLayer_ = NativeLayer.getInstance();
+ this.nativeLayer_ = NativeLayerImpl.getInstance();
this.addWebUIListener('print-failed', this.onPrintFailed_.bind(this));
this.addWebUIListener(
'print-preset-options', this.onPrintPresetOptions_.bind(this));
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 28ea8d6232d..4624470278a 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/button_strip.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/button_strip.js
@@ -8,6 +8,7 @@ import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import '../strings.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
+import {PluralStringProxyImpl} from 'chrome://resources/js/plural_string_proxy.js';
import {IronA11yAnnouncer} from 'chrome://resources/polymer/v3_0/iron-a11y-announcer/iron-a11y-announcer.js';
import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
@@ -50,7 +51,6 @@ Polymer({
/** @private */
errorMessage_: {
type: String,
- computed: 'computeErrorMessage_(destination.id, maxSheets, sheetCount)',
observer: 'errorMessageChanged_',
},
// </if>
@@ -59,6 +59,9 @@ Polymer({
observers: [
'updatePrintButtonLabel_(destination.id)',
'updatePrintButtonEnabled_(state, destination.id, maxSheets, sheetCount)',
+ // <if expr="chromeos">
+ 'updateErrorMessage_(state, destination.id, maxSheets, sheetCount)',
+ // </if>
],
/** @private {!State} */
@@ -140,19 +143,17 @@ Polymer({
return this.sheetCount > 0 && this.printButtonDisabled_();
},
- /**
- * @return {string} Localized message to show as an error.
- * @private
- */
- computeErrorMessage_() {
+ /** @private */
+ updateErrorMessage_() {
if (!this.showSheetsError_()) {
- return '';
+ this.errorMessage_ = '';
+ return;
}
-
- const singularOrPlural = this.maxSheets > 1 ? 'Plural' : 'Singular';
- const label = loadTimeData.getString(`sheetsLimitLabel${singularOrPlural}`);
- return loadTimeData.getStringF(
- 'sheetsLimitErrorMessage', this.maxSheets.toLocaleString(), label);
+ PluralStringProxyImpl.getInstance()
+ .getPluralString('sheetsLimitErrorMessage', this.maxSheets)
+ .then(label => {
+ this.errorMessage_ = label;
+ });
},
/**
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 e0532e60acf..c3b9f5bbd2c 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_dialog.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_dialog.js
@@ -33,7 +33,7 @@ import {DestinationStore} from '../data/destination_store.js';
import {Invitation} from '../data/invitation.js';
import {InvitationStore} from '../data/invitation_store.js';
import {Metrics, MetricsContext} from '../metrics.js';
-import {NativeLayer} from '../native_layer.js';
+import {NativeLayerImpl} from '../native_layer.js';
Polymer({
is: 'print-preview-destination-dialog',
@@ -129,12 +129,7 @@ Polymer({
this.$$('.promo-text').innerHTML =
this.i18nAdvanced('cloudPrintPromotion', {
substitutions: ['<a is="action-link" class="sign-in">', '</a>'],
- attrs: {
- 'is': (node, v) => v === 'action-link',
- 'class': (node, v) => v === 'sign-in',
- 'tabindex': (node, v) => v === '0',
- 'role': (node, v) => v === 'link',
- },
+ attrs: ['is', 'class', 'tabindex', 'role'],
});
},
@@ -340,7 +335,7 @@ Polymer({
/** @private */
onSignInClick_() {
this.metrics_.record(Metrics.DestinationSearchBucket.SIGNIN_TRIGGERED);
- NativeLayer.getInstance().signIn(false);
+ NativeLayerImpl.getInstance().signIn(false);
},
/** @private */
@@ -426,7 +421,7 @@ Polymer({
this.metrics_.record(Metrics.DestinationSearchBucket.ACCOUNT_CHANGED);
} else {
select.value = this.activeUser;
- NativeLayer.getInstance().signIn(true);
+ NativeLayerImpl.getInstance().signIn(true);
this.metrics_.record(
Metrics.DestinationSearchBucket.ADD_ACCOUNT_SELECTED);
}
@@ -463,6 +458,6 @@ Polymer({
/** @private */
onOpenSettingsPrintPage_() {
this.metrics_.record(Metrics.DestinationSearchBucket.MANAGE_BUTTON_CLICKED);
- NativeLayer.getInstance().openSettingsPrintPage();
+ NativeLayerImpl.getInstance().openSettingsPrintPage();
},
});
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_dropdown_cros.html b/chromium/chrome/browser/resources/print_preview/ui/destination_dropdown_cros.html
new file mode 100644
index 00000000000..c20bcbae4a6
--- /dev/null
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_dropdown_cros.html
@@ -0,0 +1,150 @@
+<style include="cr-shared-style cr-hidden-style md-select">
+ :host([opened_]) cr-input {
+ --cr-input-border-radius: 4px 4px 0 0;
+ }
+
+ iron-dropdown,
+ cr-input {
+ width: var(--md-select-width);
+ }
+
+ cr-input::part(input) {
+ opacity: 1;
+ padding-inline-end: 32px;
+ padding-inline-start: 8px;
+ text-overflow: clip;
+ }
+
+ iron-dropdown {
+ border: 0.5px solid rgba(0, 0, 0, 0.5);
+ max-height: 270px;
+ }
+
+ iron-dropdown [slot='dropdown-content'] {
+ background-color: white;
+ box-shadow: 0 2px 6px var(--google-grey-600);
+ min-width: var(--md-select-width);
+ padding: 8px 0;
+ }
+
+ #input-overlay {
+ border-radius: 4px;
+ height: 100%;
+ left: 0;
+ overflow: hidden;
+ pointer-events: none;
+ position: absolute;
+ top: 0;
+ width: 100%;
+ }
+
+ #dropdown-icon {
+ --iron-icon-height: 20px;
+ --iron-icon-width: 20px;
+ margin-top: -10px;
+ padding-inline-end: 6px;
+ position: absolute;
+ right: 0;
+ top: 50%;
+ }
+
+ :host-context([dir='rtl']) #dropdown-icon {
+ left: 0;
+ right: unset;
+ }
+
+ cr-input:focus-within #dropdown-icon {
+ --iron-icon-fill-color: var(--google-blue-600);
+ }
+
+ #input-box {
+ height: 100%;
+ left: 0;
+ pointer-events: none;
+ top: 0;
+ width: 100%;
+ }
+
+ #dropdown-box {
+ pointer-events: initial;
+ width: 100%;
+ }
+
+ .list-item {
+ background: none;
+ border: none;
+ box-sizing: border-box;
+ font: inherit;
+ min-height: 32px;
+ padding: 0 8px;
+ text-align: start;
+ width: 100%;
+ }
+
+ .list-item:focus {
+ outline: none;
+ }
+
+ .list-item[selected_] {
+ background-color: var(--google-blue-refresh-100);
+ }
+
+ .dot {
+ background-color: #bbb;
+ border-radius: 50%;
+ display: inline-block;
+ height: 10px;
+ width: 10px;
+ }
+
+ #pre-input-box,
+ .printer-display-name {
+ padding-inline-start: 8px;
+ }
+</style>
+<cr-input id="dropdownInput" on-keydown="onKeyDown_"
+ value="[[value.displayName]]" disabled="[[disabled]]" readonly>
+ <div id="pre-input-overlay" slot="inline-prefix">
+ <div id="pre-input-box">
+ <iron-icon icon="[[destinationIcon]]"></iron-icon>
+ </div>
+ </div>
+ <div id="input-overlay" slot="suffix">
+ <div id="input-box">
+ <iron-icon id="dropdown-icon" icon="cr:arrow-drop-down"></iron-icon>
+ </div>
+ <div id="dropdown-box">
+ <iron-dropdown horizontal-align="left" vertical-align="top"
+ vertical-offset="0" no-cancel-on-outside-click
+ no-cancel-on-esc-key>
+ <div slot="dropdown-content">
+ <template is="dom-repeat" items="[[itemList]]">
+ <button id="[[item.key]]" class="list-item" on-click="onSelect_"
+ tabindex="-1" value="[[item.key]]">
+ <printer-status-icon-cros background="white"
+ state$="[[computePrinterState_(item.printerStatusReason)]]">
+ </printer-status-icon-cros>
+ <span class="printer-display-name">[[item.displayName]]</span>
+ </button>
+ </template>
+ <button class="list-item" on-click="onSelect_" tabindex="-1"
+ value="[[pdfDestinationKey]]" hidden$="[[pdfPrinterDisabled]]">
+ $i18n{printToPDF}
+ </button>
+ <button class="list-item" on-click="onSelect_" tabindex="-1"
+ value="[[driveDestinationKey]]" hidden$="[[!driveDestinationKey]]">
+ $i18n{printToGoogleDrive}
+ </button>
+ <button class="list-item" on-click="onSelect_" tabindex="-1"
+ value="noDestinations" hidden$="[[!noDestinations]]">
+ $i18n{noDestinationsMessage}
+ </button>
+ <button class="list-item" on-click="onSelect_" tabindex="-1"
+ value="seeMore" aria-label$="[[i18n(seeMoreDestinationsLabel)]]">
+ $i18n{seeMore}
+ </button>
+ </div>
+ </iron-dropdown>
+ </div>
+ </div>
+</cr-input>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_dropdown_cros.js b/chromium/chrome/browser/resources/print_preview/ui/destination_dropdown_cros.js
new file mode 100644
index 00000000000..3d95796c331
--- /dev/null
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_dropdown_cros.js
@@ -0,0 +1,273 @@
+// Copyright 2020 The Chromium 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 'chrome://resources/cr_elements/cr_input/cr_input.m.js';
+import 'chrome://resources/cr_elements/hidden_style_css.m.js';
+import 'chrome://resources/cr_elements/md_select_css.m.js';
+import 'chrome://resources/cr_elements/shared_vars_css.m.js';
+// TODO(gavinwill): Remove iron-dropdown dependency https://crbug.com/1082587.
+import 'chrome://resources/polymer/v3_0/iron-dropdown/iron-dropdown.js';
+import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
+
+import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+import {Destination} from '../data/destination.js';
+import {PrinterStatusReason} from '../data/printer_status_cros.js';
+
+import {PrinterState} from './printer_status_icon_cros.js';
+
+Polymer({
+ is: 'print-preview-destination-dropdown-cros',
+
+ _template: html`{__html_template__}`,
+
+ properties: {
+ /** @type {!Destination} */
+ value: Object,
+
+ /** @type {!Array<!Destination>} */
+ itemList: {
+ type: Array,
+ observer: 'enqueueDropdownRefit_',
+ },
+
+ /** @type {boolean} */
+ disabled: {
+ type: Boolean,
+ value: false,
+ },
+
+ driveDestinationKey: String,
+
+ noDestinations: Boolean,
+
+ pdfPrinterDisabled: Boolean,
+
+ pdfDestinationKey: String,
+
+ destinationIcon: String,
+ },
+
+ listeners: {
+ 'mousemove': 'onMouseMove_',
+ },
+
+ /** @override */
+ attached() {
+ this.pointerDownListener_ = event => this.onPointerDown_(event);
+ document.addEventListener('pointerdown', this.pointerDownListener_);
+ },
+
+ /** @override */
+ detached() {
+ document.removeEventListener('pointerdown', this.pointerDownListener_);
+ },
+
+ /**
+ * Enqueues a task to refit the iron-dropdown if it is open.
+ * @private
+ */
+ enqueueDropdownRefit_() {
+ const dropdown = this.$$('iron-dropdown');
+ if (!this.dropdownRefitPending_ && dropdown.opened) {
+ this.dropdownRefitPending_ = true;
+ setTimeout(() => {
+ dropdown.refit();
+ this.dropdownRefitPending_ = false;
+ }, 0);
+ }
+ },
+
+ /** @private */
+ openDropdown_() {
+ if (this.disabled) {
+ return;
+ }
+
+ this.$$('iron-dropdown').open();
+ this.opened_ = true;
+ },
+
+ /** @private */
+ closeDropdown_() {
+ this.$$('iron-dropdown').close();
+ this.opened_ = false;
+
+ const selectedItem = this.findSelectedItem_();
+ if (selectedItem) {
+ selectedItem.removeAttribute('selected_');
+ }
+ },
+
+ /**
+ * @param {!Event} event
+ * @private
+ */
+ onMouseMove_(event) {
+ const item = event.composedPath().find(
+ elm => elm.classList && elm.classList.contains('list-item'));
+ if (!item) {
+ return;
+ }
+
+ // Select the item the mouse is hovering over. If the user uses the
+ // keyboard, the selection will shift. But once the user moves the mouse,
+ // selection should be updated based on the location of the mouse cursor.
+ const selectedItem = this.findSelectedItem_();
+ if (item === selectedItem) {
+ return;
+ }
+
+ if (selectedItem) {
+ selectedItem.removeAttribute('selected_');
+ }
+ item.setAttribute('selected_', '');
+ },
+
+ /**
+ * @param {!Event} event
+ * @private
+ */
+ onPointerDown_(event) {
+ const paths = event.composedPath();
+ const dropdown =
+ /** @type {!IronDropdownElement} */ (this.$$('iron-dropdown'));
+ const dropdownInput =
+ /** @type {!CrInputElement} */ (this.$$('#dropdownInput'));
+
+ // Exit if path includes |dropdown| because event will be handled by
+ // onSelect_.
+ if (paths.includes(dropdown)) {
+ return;
+ }
+
+ if (!paths.includes(dropdownInput) || dropdown.opened) {
+ this.closeDropdown_();
+ return;
+ }
+
+ this.openDropdown_();
+ },
+
+ /** @private */
+ onSelect_() {
+ const selectedItem = this.findSelectedItem_();
+ this.closeDropdown_();
+ this.fire('dropdown-value-selected', selectedItem);
+ },
+
+ /**
+ * @param {!Event} event
+ * @private
+ */
+ onKeyDown_(event) {
+ event.stopPropagation();
+ const dropdown = this.$$('iron-dropdown');
+ switch (event.code) {
+ case 'Tab':
+ this.closeDropdown_();
+ break;
+ case 'ArrowUp':
+ case 'ArrowDown': {
+ const items = dropdown.getElementsByClassName('list-item');
+ if (items.length === 0) {
+ break;
+ }
+ this.updateSelected_(event.code === 'ArrowDown');
+ break;
+ }
+ case 'Enter': {
+ if (dropdown.opened) {
+ this.onSelect_();
+ break;
+ }
+ this.openDropdown_();
+ break;
+ }
+ case 'Escape': {
+ if (dropdown.opened) {
+ this.closeDropdown_();
+ event.preventDefault();
+ }
+ break;
+ }
+ }
+ },
+
+ /**
+ * Updates the currently selected element based on keyboard up/down movement.
+ * @param {boolean} moveDown
+ * @private
+ */
+ updateSelected_(moveDown) {
+ const items = this.getButtonListFromDropdown_();
+ const numItems = items.length;
+ if (numItems === 0) {
+ return;
+ }
+
+ let nextIndex = 0;
+ const currentIndex = this.findSelectedItemIndex_();
+ if (currentIndex === -1) {
+ nextIndex = moveDown ? 0 : numItems - 1;
+ } else {
+ const delta = moveDown ? 1 : -1;
+ nextIndex = (numItems + currentIndex + delta) % numItems;
+ items[currentIndex].removeAttribute('selected_');
+ }
+ items[nextIndex].setAttribute('selected_', '');
+ // The newly selected item might not be visible because the dropdown needs
+ // to be scrolled. So scroll the dropdown if necessary.
+ items[nextIndex].scrollIntoViewIfNeeded();
+ },
+
+ /**
+ * Finds the currently selected dropdown item.
+ * @return {Element|undefined} Currently selected dropdown item, or undefined
+ * if no item is selected.
+ * @private
+ */
+ findSelectedItem_() {
+ const items = this.getButtonListFromDropdown_();
+ return items.find(item => item.hasAttribute('selected_'));
+ },
+
+ /**
+ * Finds the index of currently selected dropdown item.
+ * @return {number} Index of the currently selected dropdown item, or -1 if
+ * no item is selected.
+ * @private
+ */
+ findSelectedItemIndex_() {
+ const items = this.getButtonListFromDropdown_();
+ return items.findIndex(item => item.hasAttribute('selected_'));
+ },
+
+ /**
+ * Returns list of all the visible items in the dropdown.
+ * @return {!Array<!Element>}
+ * @private
+ */
+ getButtonListFromDropdown_() {
+ const dropdown = this.$$('iron-dropdown');
+ return Array.from(dropdown.getElementsByClassName('list-item'))
+ .filter(item => !item.hidden);
+ },
+
+ /**
+ * @param {?PrinterStatusReason} printerStatusReason
+ * @return {number}
+ * @private
+ */
+ computePrinterState_(printerStatusReason) {
+ if (!printerStatusReason ||
+ printerStatusReason === PrinterStatusReason.UNKNOWN_REASON) {
+ return PrinterState.UNKNOWN;
+ }
+ if (printerStatusReason === PrinterStatusReason.NO_ERROR) {
+ return PrinterState.GOOD;
+ }
+ return PrinterState.ERROR;
+ },
+});
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_select_cros.html b/chromium/chrome/browser/resources/print_preview/ui/destination_select_cros.html
index 2d8d0b8d28f..9ef6b0878c1 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_select_cros.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_select_cros.html
@@ -7,8 +7,8 @@
<div class="throbber"></div>
</div>
<template is="dom-if" if="[[!printerStatusFlagEnabled_]]">
- <select class="md-select" aria-label$="[[i18n(destinationLabel)]]"
- hidden$="[[!loaded]]"
+ <select id="dropdown" class="md-select"
+ aria-label$="[[i18n(destinationLabel)]]" hidden$="[[!loaded]]"
style="background-image:[[backgroundImages_]];"
disabled$="[[disabled]]"
value="{{selectedValue::change}}">
@@ -33,7 +33,16 @@
</select>
</template>
<template is="dom-if" if="[[printerStatusFlagEnabled_]]">
- <div>print-preview-destination-select-cros</div>
+ <print-preview-destination-dropdown-cros id="dropdown"
+ value="[[destination]]" hidden$="[[!loaded]]"
+ item-list="[[recentDestinationList]]"
+ pdf-destination-key="[[pdfDestinationKey_]]"
+ drive-destination-key="[[driveDestinationKey]]"
+ no-destinations="[[noDestinations]]"
+ pdf-printer-disabled="[[pdfPrinterDisabled]]"
+ destination-icon="[[destinationIcon_]]" disabled="[[disabled]]"
+ on-dropdown-value-selected="onDropdownValueSelected_">
+ </print-preview-destination-dropdown-cros>
</template>
</div>
</print-preview-settings-section>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/destination_select_cros.js b/chromium/chrome/browser/resources/print_preview/ui/destination_select_cros.js
index f76ac017631..9eab3a242b4 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_select_cros.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_select_cros.js
@@ -7,22 +7,46 @@ import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/cr_elements/md_select_css.m.js';
import 'chrome://resources/js/util.m.js';
import 'chrome://resources/polymer/v3_0/iron-iconset-svg/iron-iconset-svg.js';
+import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
import 'chrome://resources/polymer/v3_0/iron-meta/iron-meta.js';
+import './destination_dropdown_cros.js';
import './destination_select_css.js';
import './icons.js';
import './print_preview_shared_css.js';
import './throbber_css.js';
import '../strings.m.js';
+import {assert} from 'chrome://resources/js/assert.m.js';
import {I18nBehavior} from 'chrome://resources/js/i18n_behavior.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {Base, html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
-import {Destination, DestinationOrigin, PDF_DESTINATION_KEY, RecentDestination} from '../data/destination.js';
+import {CloudOrigins, Destination, DestinationOrigin, PDF_DESTINATION_KEY, RecentDestination} from '../data/destination.js';
+import {PrinterStatus, PrinterStatusReason, PrinterStatusSeverity} from '../data/printer_status_cros.js';
+import {NativeLayer, NativeLayerImpl} from '../native_layer.js';
import {getSelectDropdownBackground} from '../print_preview_utils.js';
import {SelectBehavior} from './select_behavior.js';
+/** @const {!Map<!PrinterStatusReason, string>} */
+const ERROR_STRING_KEY_MAP = new Map([
+ [PrinterStatusReason.CONNECTING_TO_DEVICE, 'printerStatusConnectingToDevice'],
+ [PrinterStatusReason.DEVICE_ERROR, 'printerStatusDeviceError'],
+ [PrinterStatusReason.DOOR_OPEN, 'printerStatusDoorOpen'],
+ [PrinterStatusReason.LOW_ON_INK, 'printerStatusLowOnInk'],
+ [PrinterStatusReason.LOW_ON_PAPER, 'printerStatusLowOnPaper'],
+ [PrinterStatusReason.OUT_OF_INK, 'printerStatusOutOfInk'],
+ [PrinterStatusReason.OUT_OF_PAPER, 'printerStatusOutOfPaper'],
+ [PrinterStatusReason.OUTPUT_ALMOST_FULL, 'printerStatusOutputAlmostFull'],
+ [PrinterStatusReason.OUTPUT_FULL, 'printerStatusOutputFull'],
+ [PrinterStatusReason.PAPER_JAM, 'printerStatusPaperJam'],
+ [PrinterStatusReason.PAUSED, 'printerStatusPaused'],
+ [PrinterStatusReason.PRINTER_QUEUE_FULL, 'printerStatusPrinterQueueFull'],
+ [PrinterStatusReason.PRINTER_UNREACHABLE, 'printerStatusPrinterUnreachable'],
+ [PrinterStatusReason.STOPPED, 'printerStatusStopped'],
+ [PrinterStatusReason.TRAY_MISSING, 'printerStatusTrayMissing'],
+]);
+
Polymer({
is: 'print-preview-destination-select-cros',
@@ -36,7 +60,11 @@ Polymer({
dark: Boolean,
/** @type {!Destination} */
- destination: Object,
+ destination: {
+ type: Object,
+ observer: 'updateStatusText_',
+ },
+
disabled: Boolean,
@@ -49,7 +77,10 @@ Polymer({
pdfPrinterDisabled: Boolean,
/** @type {!Array<!Destination>} */
- recentDestinationList: Array,
+ recentDestinationList: {
+ type: Array,
+ observer: 'onRecentDestinationListChanged_',
+ },
/** @private {string} */
pdfDestinationKey_: {
@@ -57,17 +88,20 @@ Polymer({
value: PDF_DESTINATION_KEY,
},
+ /** @private */
+ statusText_: String,
+
/** @private {string} */
- statusText_: {
+ backgroundImages_: {
type: String,
- computed: 'computeStatusText_(destination)',
+ computed:
+ 'computeBackgroundImages_(destinationIcon_, dark, noDestinations)',
},
/** @private {string} */
- backgroundImages_: {
+ destinationIcon_: {
type: String,
- computed:
- 'computeBackgroundImages_(selectedValue, destination, noDestinations, dark)',
+ computed: 'computeDestinationIcon_(selectedValue, destination)',
},
/** @private */
@@ -78,14 +112,32 @@ Polymer({
},
readOnly: true,
},
+
+ /**
+ * The key for this map is a destination.id and the value is a
+ * destination.key. This map is needed to track which destinations have had
+ * statuses requested while also giving quick look up of destination id to
+ * the corresponding destination key.
+ * @private {!Map<string, string>}
+ */
+ statusRequestedMap_: Map,
},
/** @private {!IronMetaElement} */
meta_: /** @type {!IronMetaElement} */ (
Base.create('iron-meta', {type: 'iconset'})),
+ /** @override */
+ attached() {
+ if (!this.printerStatusFlagEnabled_) {
+ return;
+ }
+
+ this.statusRequestedMap_ = new Map();
+ },
+
focus() {
- this.$$('.md-select').focus();
+ this.$$('#dropdown').focus();
},
/** Sets the select to the current value of |destination|. */
@@ -100,7 +152,7 @@ Polymer({
* @return {string} The iconset and icon for the current selection.
* @private
*/
- getDestinationIcon_() {
+ computeDestinationIcon_() {
if (!this.selectedValue) {
return '';
}
@@ -140,8 +192,7 @@ Polymer({
* @private
*/
computeBackgroundImages_() {
- const icon = this.getDestinationIcon_();
- if (!icon) {
+ if (!this.destinationIcon_) {
return '';
}
@@ -149,7 +200,7 @@ Polymer({
if (this.noDestinations) {
iconSetAndIcon = ['cr', 'error'];
}
- iconSetAndIcon = iconSetAndIcon || icon.split(':');
+ iconSetAndIcon = iconSetAndIcon || this.destinationIcon_.split(':');
const iconset = /** @type {!IronIconsetSvgElement} */ (
this.meta_.byKey(iconSetAndIcon[0]));
return getSelectDropdownBackground(iconset, iconSetAndIcon[1], this);
@@ -160,17 +211,179 @@ Polymer({
},
/**
- * @return {string} The connection status text to display.
+ * @param {!Event} e
* @private
*/
- computeStatusText_() {
+ onDropdownValueSelected_(e) {
+ assert(this.printerStatusFlagEnabled_);
+
+ const selectedItem = e.detail;
+ if (!selectedItem || selectedItem.value === this.destination.key) {
+ return;
+ }
+
+ this.fire('selected-option-change', selectedItem.value);
+ },
+
+ /**
+ * Send a printer status request for any new destination in the dropdown.
+ * @private
+ */
+ onRecentDestinationListChanged_() {
+ if (!this.printerStatusFlagEnabled_) {
+ return;
+ }
+
+ for (const destination of this.recentDestinationList) {
+ if (destination.origin !== DestinationOrigin.CROS ||
+ this.statusRequestedMap_.has(destination.id)) {
+ continue;
+ }
+
+ NativeLayerImpl.getInstance()
+ .requestPrinterStatusUpdate(destination.id)
+ .then(status => this.onPrinterStatusReceived_(status));
+ this.statusRequestedMap_.set(destination.id, destination.key);
+ }
+ },
+
+ /**
+ * Check if the printer in |printerStatus| is currently in the dropdown.
+ * Update its status icon if it's present.
+ * @param {!PrinterStatus} printerStatus
+ * @private
+ */
+ onPrinterStatusReceived_(printerStatus) {
+ assert(this.printerStatusFlagEnabled_);
+ if (!printerStatus.printerId) {
+ return;
+ }
+
+ const destinationKey =
+ this.statusRequestedMap_.get(printerStatus.printerId);
+ if (!destinationKey) {
+ return;
+ }
+
+ const indexFound = this.recentDestinationList.findIndex(destination => {
+ return destination.id === printerStatus.printerId &&
+ destination.origin === DestinationOrigin.CROS;
+ });
+ if (indexFound === -1) {
+ return;
+ }
+
+ const statusReason = this.getStatusReasonFromPrinterStatus_(printerStatus);
+ if (!statusReason) {
+ return;
+ }
+
+
+ this.recentDestinationList[indexFound].printerStatusReason = statusReason;
+ // Set the new printer status reason then use notifyPath to trigger the
+ // dropdown printer status icons to recalculate their badge color.
+ this.notifyPath(`recentDestinationList.${indexFound}.printerStatusReason`);
+
+ // Update the status text if this printer status is for the
+ // currently selected printer.
+ if (this.destination && this.destination.key === destinationKey) {
+ this.updateStatusText_();
+ }
+ },
+
+ /**
+ * A |printerStatus| can have multiple status reasons so this function's
+ * responsibility is to determine which status reason is most relevant to
+ * surface to the user. Any status reason with a severity of WARNING or ERROR
+ * will get highest precedence since this usually means the printer is in a
+ * bad state. NO_ERROR status reason is the next highest precedence so the
+ * printer can be shown as available whenever possible.
+ * @param {!PrinterStatus} printerStatus
+ * @return {!PrinterStatusReason} Status reason extracted from
+ * |printerStatus|.
+ * @private
+ */
+ getStatusReasonFromPrinterStatus_(printerStatus) {
+ assert(this.printerStatusFlagEnabled_);
+
+ if (!printerStatus.printerId) {
+ return PrinterStatusReason.UNKNOWN_REASON;
+ }
+
+ let seenNoErrorReason = false;
+ for (const statusReason of printerStatus.statusReasons) {
+ const reason = statusReason.reason;
+ const severity = statusReason.severity;
+
+ if (reason !== PrinterStatusReason.UNKNOWN_REASON &&
+ (severity === PrinterStatusSeverity.WARNING ||
+ severity === PrinterStatusSeverity.ERROR)) {
+ return reason;
+ }
+
+ if (reason === PrinterStatusReason.NO_ERROR) {
+ seenNoErrorReason = true;
+ }
+ }
+ return seenNoErrorReason ? PrinterStatusReason.NO_ERROR :
+ PrinterStatusReason.UNKNOWN_REASON;
+ },
+
+ /**
+ * Check the current destination for an error status then set |statusText_|
+ * appropriately. If no error status exists, unset |statusText_|.
+ * @private
+ */
+ updateStatusText_: function() {
// |destination| can be either undefined, or null here.
if (!this.destination) {
- return '';
+ this.statusText_ = '';
+ return;
+ }
+
+ // Cloudprint destinations contain their own status text.
+ if (CloudOrigins.some(origin => origin === this.destination.origin)) {
+ this.statusText_ = this.destination.shouldShowInvalidCertificateError ?
+ this.i18n('noLongerSupportedFragment') :
+ this.destination.connectionStatusText;
+ return;
}
- return this.destination.shouldShowInvalidCertificateError ?
- this.i18n('noLongerSupportedFragment') :
- this.destination.connectionStatusText;
+ // Only when the flag is enabled do we need to fetch a local printer status
+ // error string.
+ if (!this.printerStatusFlagEnabled_) {
+ this.statusText_ = '';
+ return;
+ }
+
+ const printerStatusReason = this.destination.printerStatusReason;
+ if (!printerStatusReason ||
+ printerStatusReason === PrinterStatusReason.NO_ERROR ||
+ printerStatusReason === PrinterStatusReason.UNKNOWN_REASON) {
+ this.statusText_ = '';
+ return;
+ }
+
+ this.statusText_ = this.getErrorString_(printerStatusReason);
+ },
+
+ /**
+ * @param {!PrinterStatusReason} printerStatusReason
+ * @return {!string}
+ * @private
+ */
+ getErrorString_: function(printerStatusReason) {
+ const errorTextKey = ERROR_STRING_KEY_MAP.get(printerStatusReason);
+ return errorTextKey ?
+ this.i18n(errorTextKey, this.destination.displayName) :
+ '';
+ },
+
+ /**
+ * @return {!boolean}
+ * @private
+ */
+ shouldShowStatus_: function() {
+ return !!this.statusText_;
},
});
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 f7259dbcfd0..4dce6653ae7 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/destination_settings.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/destination_settings.js
@@ -66,7 +66,7 @@ Polymer({
value: null,
},
- /** @private {!DestinationState} */
+ /** @type {!DestinationState} */
destinationState: {
type: Number,
notify: true,
@@ -527,6 +527,11 @@ Polymer({
});
},
+ /** @return {!DestinationStore} */
+ getDestinationStoreForTest() {
+ return assert(this.destinationStore_);
+ },
+
// <if expr="chromeos">
/**
* @param {!CustomEvent<string>} e Event containing the current destination's
diff --git a/chromium/chrome/browser/resources/print_preview/ui/header.js b/chromium/chrome/browser/resources/print_preview/ui/header.js
index 3848934ecb3..e441b03788d 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/header.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/header.js
@@ -9,6 +9,7 @@ import './print_preview_vars_css.js';
import '../strings.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
+import {PluralStringProxyImpl} from 'chrome://resources/js/plural_string_proxy.js';
import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {Destination} from '../data/destination.js';
@@ -40,12 +41,13 @@ Polymer({
sheetCount: Number,
/** @private {?string} */
- summary_: {
- type: String,
- computed: 'computeSummary_(sheetCount, state, destination.id)',
- },
+ summary_: String,
},
+ observers: [
+ 'updateSummary_(sheetCount, state, destination.id)',
+ ],
+
/**
* @return {boolean}
* @private
@@ -56,21 +58,22 @@ Polymer({
this.destination.id === Destination.GooglePromotedId.DOCS);
},
- /**
- * @return {?string}
- * @private
- */
- computeSummary_() {
+ /** @private */
+ updateSummary_() {
switch (this.state) {
case (State.PRINTING):
- return loadTimeData.getString(
+ this.summary_ = loadTimeData.getString(
this.isPdfOrDrive_() ? 'saving' : 'printing');
+ break;
case (State.READY):
- return this.getSheetsSummary_();
+ this.updateSheetsSummary_();
+ break;
case (State.FATAL_ERROR):
- return this.getErrorMessage_();
+ this.summary_ = this.getErrorMessage_();
+ break;
default:
- return null;
+ this.summary_ = null;
+ break;
}
},
@@ -89,21 +92,19 @@ Polymer({
}
},
- /**
- * @return {string}
- * @private
- */
- getSheetsSummary_() {
+ /** @private */
+ updateSheetsSummary_() {
if (this.sheetCount === 0) {
- return '';
+ this.summary_ = '';
+ return;
}
- const pageOrSheets = this.isPdfOrDrive_() ? 'Page' : 'Sheets';
- const singularOrPlural = this.sheetCount > 1 ? 'Plural' : 'Singular';
- const label = loadTimeData.getString(
- `printPreview${pageOrSheets}Label${singularOrPlural}`);
- return loadTimeData.getStringF(
- 'printPreviewSummaryFormatShort', this.sheetCount.toLocaleString(),
- label);
+ const pageOrSheet = this.isPdfOrDrive_() ? 'Page' : 'Sheet';
+ PluralStringProxyImpl.getInstance()
+ .getPluralString(
+ `printPreview${pageOrSheet}SummaryLabel`, this.sheetCount)
+ .then(label => {
+ this.summary_ = label;
+ });
},
});
diff --git a/chromium/chrome/browser/resources/print_preview/ui/link_container.html b/chromium/chrome/browser/resources/print_preview/ui/link_container.html
index 6ada90e22fa..9c483864f6c 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/link_container.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/link_container.html
@@ -42,7 +42,7 @@
}
.link:not([actionable]) .label {
- @apply --print-preview-disabled-label;
+ opacity: var(--cr-disabled-opacity);
}
</style>
<div class="link" id="systemDialogLink"
diff --git a/chromium/chrome/browser/resources/print_preview/ui/more_settings.html b/chromium/chrome/browser/resources/print_preview/ui/more_settings.html
index d63ce664e66..13c6d2c7678 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/more_settings.html
+++ b/chromium/chrome/browser/resources/print_preview/ui/more_settings.html
@@ -33,7 +33,7 @@
}
:host([disabled]) #label {
- @apply --print-preview-disabled-label;
+ opacity: var(--cr-disabled-opacity);
}
</style>
<div on-click="toggleExpandButton_" actionable>
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 e75d9bffbf7..feb0ebf3849 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,7 @@ import {PrintableArea} from '../data/printable_area.js';
import {ScalingType} from '../data/scaling.js';
import {Size} from '../data/size.js';
import {Error, State} from '../data/state.js';
-import {NativeLayer} from '../native_layer.js';
+import {NativeLayer, NativeLayerImpl} from '../native_layer.js';
import {areRangesEqual} from '../print_preview_utils.js';
import {MARGIN_KEY_MAP} from './margin_control_container.js';
@@ -140,7 +140,7 @@ Polymer({
/** @override */
attached() {
- this.nativeLayer_ = NativeLayer.getInstance();
+ this.nativeLayer_ = NativeLayerImpl.getInstance();
this.addWebUIListener(
'page-preview-ready', this.onPagePreviewReady_.bind(this));
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 816b95996fe..6ecd94cd733 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
@@ -50,7 +50,7 @@
on-search="onSearchTermSearch" on-input="onSearchTermInput"
aria-label$="[[label]]" placeholder="[[label]]"
autofocus="[[autofocus]]" spellcheck="false">
- <div slot="prefix" id="icon" class="cr-icon icon-search" alt=""></div>
+ <div slot="inline-prefix" id="icon" class="cr-icon icon-search" alt=""></div>
<cr-icon-button id="clearSearch" class="icon-cancel"
hidden$="[[!hasSearchText]]" slot="suffix" on-click="onClearClick_"
title="[[clearLabel]]">
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 d476823e7ec..2208774d52e 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
@@ -8,10 +8,6 @@
--print-preview-settings-border: 1px solid var(--google-grey-200);
--print-preview-dialog-margin: 34px;
- --print-preview-disabled-label: {
- color: var(--paper-grey-600);
- opacity: .65;
- }
--cr-form-field-label-height: initial;
--cr-form-field-label-line-height: .75rem;
--destination-item-height: 32px;
diff --git a/chromium/chrome/browser/resources/print_preview/ui/printer_status_icon_cros.html b/chromium/chrome/browser/resources/print_preview/ui/printer_status_icon_cros.html
new file mode 100644
index 00000000000..450956a6557
--- /dev/null
+++ b/chromium/chrome/browser/resources/print_preview/ui/printer_status_icon_cros.html
@@ -0,0 +1,67 @@
+<style include="cr-shared-style">
+ div {
+ display: inline;
+ position: relative;
+ }
+
+ .badge {
+ border-radius: 50%;
+ display: inline-block;
+ position: absolute;
+ --status-badge-radius: 8px;
+ --background-badge-radius: 12px;
+ --background-badge-left: 12px;
+ --background-badge-top: 6px;
+ }
+
+ :host-context([dir='rtl']) .badge {
+ --background-badge-left: -4px;
+ }
+
+ #status-badge {
+ height: var(--status-badge-radius);
+ left: calc(var(--background-badge-left) + (var(--background-badge-radius) - var(--status-badge-radius))/2);
+ top: calc(var(--background-badge-top) + (var(--background-badge-radius) - var(--status-badge-radius))/2);
+ width: var(--status-badge-radius);
+ }
+
+ :host-context([state='0']) #status-badge {
+ background-color: var(--google-green-700);
+ }
+
+ :host-context([state='1']) #status-badge {
+ background-color: var(--google-red-600);
+ }
+
+ :host-context([state='2']) #status-badge {
+ background-color: var(--google-grey-500);
+ }
+
+ :host-context([dir='rtl']) #status-badge {
+ right: calc(var(--background-badge-left) + (var(--background-badge-radius) - var(--status-badge-radius))/2);
+ }
+
+ #background-badge {
+ height: var(--background-badge-radius);
+ left: var(--background-badge-left);
+ top: var(--background-badge-top);
+ width: var(--background-badge-radius);
+ }
+
+ :host-context([background='grey']) #background-badge {
+ background-color: var(--google-grey-refresh-100);
+ }
+
+ :host-context([background='white']) #background-badge {
+ background-color: white;
+ }
+
+ :host-context([dir='rtl']) #background-badge {
+ right: var(--background-badge-left);
+ }
+</style>
+<div>
+ <iron-icon icon="print-preview:print"></iron-icon>
+ <span id="background-badge" class="badge"></span>
+ <span id="status-badge" class="badge"></span>
+</div>
diff --git a/chromium/chrome/browser/resources/print_preview/ui/printer_status_icon_cros.js b/chromium/chrome/browser/resources/print_preview/ui/printer_status_icon_cros.js
new file mode 100644
index 00000000000..3ae2dc8a7de
--- /dev/null
+++ b/chromium/chrome/browser/resources/print_preview/ui/printer_status_icon_cros.js
@@ -0,0 +1,40 @@
+// Copyright 2020 The Chromium 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 'chrome://resources/cr_elements/shared_vars_css.m.js';
+import './icons.js';
+
+import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+/**
+ * Enumeration giving a local Chrome OS printer 3 different state possibilities
+ * depending on its current status.
+ * @enum {number}
+ */
+export const PrinterState = {
+ GOOD: 0,
+ ERROR: 1,
+ UNKNOWN: 2,
+};
+
+Polymer({
+ is: 'printer-status-icon-cros',
+
+ properties: {
+ /** Determines color of the background badge. */
+ background: String,
+
+ /**
+ * State of the associated printer. Determines color of the status badge.
+ * @type {!PrinterState}
+ */
+ state: {
+ type: Number,
+ reflectToAttribute: true,
+ }
+ },
+
+ _template: html`{__html_template__}`,
+
+});
diff --git a/chromium/chrome/browser/resources/print_preview/ui/select_behavior.js b/chromium/chrome/browser/resources/print_preview/ui/select_behavior.js
index 4e21bb4d903..fbc6df96b58 100644
--- a/chromium/chrome/browser/resources/print_preview/ui/select_behavior.js
+++ b/chromium/chrome/browser/resources/print_preview/ui/select_behavior.js
@@ -31,10 +31,11 @@ export const SelectBehavior = {
}
this.debounce('select-change', () => {
- this.onProcessSelectChange(this.selectedValue);
-
- // For testing only
- this.fire('process-select-change');
+ if (this.isConnected) {
+ this.onProcessSelectChange(this.selectedValue);
+ // For testing only
+ this.fire('process-select-change');
+ }
}, 100);
},
diff --git a/chromium/chrome/browser/resources/quota_internals/event_handler.js b/chromium/chrome/browser/resources/quota_internals/event_handler.js
index 6d0e7ddd9d3..d8c8b787ab3 100644
--- a/chromium/chrome/browser/resources/quota_internals/event_handler.js
+++ b/chromium/chrome/browser/resources/quota_internals/event_handler.js
@@ -391,6 +391,22 @@ function handleStatistics(event) {
}
/**
+ * Event Handler for |cr.quota.onStoragePressureFlagUpdated|.
+ * |event.detail| contains a boolean representing whether or not to show
+ * the storage pressure UI.
+ * @param {!CustomEvent<!Object>} event StoragePressureFlagUpdated event.
+ */
+function handleStoragePressureFlagInfo(event) {
+ const data = event.detail;
+ $('storage-pressure-loading').hidden = true;
+ if (data.isStoragePressureEnabled) {
+ $('storage-pressure-outer').hidden = false;
+ } else {
+ $('storage-pressure-disabled').hidden = false;
+ }
+}
+
+/**
* Update description on 'tree-item-description' field with
* selected item in tree view.
*/
@@ -490,6 +506,8 @@ function onLoad() {
cr.quota.onPerOriginInfoUpdated.addEventListener(
'update', handlePerOriginInfo);
cr.quota.onStatisticsUpdated.addEventListener('update', handleStatistics);
+ cr.quota.onStoragePressureFlagUpdated.addEventListener(
+ 'update', handleStoragePressureFlagInfo);
cr.quota.requestInfo();
$('refresh-button').addEventListener('click', cr.quota.requestInfo, false);
diff --git a/chromium/chrome/browser/resources/quota_internals/main.html b/chromium/chrome/browser/resources/quota_internals/main.html
index 59d0a4bbb2d..c1f7fb6458f 100644
--- a/chromium/chrome/browser/resources/quota_internals/main.html
+++ b/chromium/chrome/browser/resources/quota_internals/main.html
@@ -56,16 +56,26 @@ found in the LICENSE file.
<table>
<tbody id="stat-entries" class="entries"></tbody>
</table>
- <h2>Test Storage Pressure Behavior</h2>
- <div class="pressure">
- Origin to test:
- <input id="storage-pressure-origin"
- value="https://www.example.com">
- </div>
- <div class="pressure">
- <button id="trigger-notification">
- Trigger Storage Pressure Notification
- </button>
+ <div id="storage-pressure-section">
+ <h2>Test Storage Pressure Behavior</h2>
+ <div id="storage-pressure-loading">
+ Loading...
+ </div>
+ <div id="storage-pressure-outer" hidden>
+ <div class="pressure">
+ Origin to test:
+ <input id="storage-pressure-origin"
+ value="https://www.example.com">
+ </div>
+ <div class="pressure">
+ <button id="trigger-notification">
+ Trigger Storage Pressure Notification
+ </button>
+ </div>
+ </div>
+ <div id="storage-pressure-disabled" hidden>
+ Storage Pressure feature disabled.
+ </div>
</div>
</tabpanel>
diff --git a/chromium/chrome/browser/resources/quota_internals/message_dispatcher.js b/chromium/chrome/browser/resources/quota_internals/message_dispatcher.js
index 473ce67bfd7..25fa7ecf1bb 100644
--- a/chromium/chrome/browser/resources/quota_internals/message_dispatcher.js
+++ b/chromium/chrome/browser/resources/quota_internals/message_dispatcher.js
@@ -38,13 +38,15 @@ cr.define('cr.quota', function() {
* * onGlobalInfoUpdated,
* * onPerHostInfoUpdated,
* * onPerOriginInfoUpdated,
- * * onStatisticsUpdated.
+ * * onStatisticsUpdated,
+ * * onStoragePressureFlagUpdated.
* @param {string} message Message label. Possible Values are:
* * 'AvailableSpaceUpdated',
* * 'GlobalInfoUpdated',
* * 'PerHostInfoUpdated',
* * 'PerOriginInfoUpdated',
- * * 'StatisticsUpdated'.
+ * * 'StatisticsUpdated',
+ * * 'StoragePressureFlagUpdated'.
* @param {Object} detail Message specific additional data.
*/
function messageHandler(message, detail) {
@@ -65,6 +67,9 @@ cr.define('cr.quota', function() {
case 'StatisticsUpdated':
target = cr.quota.onStatisticsUpdated;
break;
+ case 'StoragePressureFlagUpdated':
+ target = cr.quota.onStoragePressureFlagUpdated;
+ break;
default:
console.error('Unknown Message');
break;
@@ -82,6 +87,7 @@ cr.define('cr.quota', function() {
onPerHostInfoUpdated: new cr.EventTarget(),
onPerOriginInfoUpdated: new cr.EventTarget(),
onStatisticsUpdated: new cr.EventTarget(),
+ onStoragePressureFlagUpdated: new cr.EventTarget(),
requestInfo: requestInfo,
triggerStoragePressure: triggerStoragePressure,
diff --git a/chromium/chrome/browser/resources/quota_internals/quota_internals_resources.grd b/chromium/chrome/browser/resources/quota_internals/quota_internals_resources.grd
index c5b1cca697e..3694a9782c4 100644
--- a/chromium/chrome/browser/resources/quota_internals/quota_internals_resources.grd
+++ b/chromium/chrome/browser/resources/quota_internals/quota_internals_resources.grd
@@ -8,9 +8,9 @@
</outputs>
<release seq="1">
<includes>
- <include name="IDR_QUOTA_INTERNALS_MAIN_HTML" file="main.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip"/>
- <include name="IDR_QUOTA_INTERNALS_EVENT_HANDLER_JS" file="event_handler.js" type="BINDATA" compress="gzip"/>
- <include name="IDR_QUOTA_INTERNALS_MESSAGE_DISPATCHER_JS" file="message_dispatcher.js" type="BINDATA" compress="gzip"/>
+ <include name="IDR_QUOTA_INTERNALS_MAIN_HTML" file="main.html" flattenhtml="true" allowexternalscript="true" type="BINDATA"/>
+ <include name="IDR_QUOTA_INTERNALS_EVENT_HANDLER_JS" file="event_handler.js" type="BINDATA"/>
+ <include name="IDR_QUOTA_INTERNALS_MESSAGE_DISPATCHER_JS" file="message_dispatcher.js" type="BINDATA"/>
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/settings/BUILD.gn b/chromium/chrome/browser/resources/settings/BUILD.gn
index 4250f4fa750..a0a669d3b12 100644
--- a/chromium/chrome/browser/resources/settings/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/BUILD.gn
@@ -71,6 +71,7 @@ group("closure_compile") {
"appearance_page:closure_compile",
"controls:closure_compile",
"languages_page:closure_compile",
+ "nearby_share_page:closure_compile",
"people_page:closure_compile",
"prefs:closure_compile",
"privacy_page:closure_compile",
@@ -148,6 +149,7 @@ group("closure_compile_module") {
"controls:closure_compile_module",
"downloads_page:closure_compile_module",
"languages_page:closure_compile_module",
+ "nearby_share_page:closure_compile_module",
"on_startup_page:closure_compile_module",
"people_page:closure_compile_module",
"prefs:closure_compile_module",
@@ -196,7 +198,6 @@ js_type_check("closure_compile_local_module") {
":metrics_browser_proxy",
":open_window_proxy",
":page_visibility",
- ":plural_string_proxy",
":route",
":router.m",
":search_settings.m",
@@ -213,6 +214,8 @@ js_library("settings") {
":metrics_browser_proxy",
":open_window_proxy",
"about_page:about_page_browser_proxy.m",
+ "autofill_page:multi_store_exception_entry",
+ "autofill_page:multi_store_password_ui_entry",
"autofill_page:password_manager_proxy",
"people_page:sync_browser_proxy.m",
"privacy_page:privacy_page_browser_proxy.m",
@@ -278,10 +281,6 @@ js_library("page_visibility") {
deps = [ "//ui/webui/resources/js:load_time_data.m" ]
}
-js_library("plural_string_proxy") {
- deps = [ "//ui/webui/resources/js:cr.m" ]
-}
-
js_library("route") {
deps = [
":page_visibility",
diff --git a/chromium/chrome/browser/resources/settings/autofill_page/BUILD.gn b/chromium/chrome/browser/resources/settings/autofill_page/BUILD.gn
index f48d5203d74..f74ab14757f 100644
--- a/chromium/chrome/browser/resources/settings/autofill_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/autofill_page/BUILD.gn
@@ -16,6 +16,11 @@ js_type_check("closure_compile_module") {
":blocking_request_manager",
":credit_card_edit_dialog",
":credit_card_list_entry",
+ ":merge_exceptions_store_copies_behavior",
+ ":merge_passwords_store_copies_behavior",
+ ":multi_store_exception_entry",
+ ":multi_store_id_handler",
+ ":multi_store_password_ui_entry",
":password_check",
":password_check_behavior",
":password_check_edit_dialog",
@@ -24,8 +29,12 @@ js_type_check("closure_compile_module") {
":password_edit_dialog",
":password_list_item",
":password_manager_proxy",
+ ":password_move_to_account_dialog",
":password_remove_confirmation_dialog",
+ ":password_remove_dialog",
+ ":passwords_device_section",
":passwords_export_dialog",
+ ":passwords_list_handler",
":passwords_section",
":payments_list",
":payments_section",
@@ -100,9 +109,8 @@ js_library("password_check") {
":blocking_request_manager",
":password_check_behavior",
":password_manager_proxy",
- "..:plural_string_proxy",
- "../prefs:prefs_behavior.m",
"..:route",
+ "../prefs:prefs_behavior.m",
"//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
"//ui/webui/resources/js:assert.m",
"//ui/webui/resources/js:i18n_behavior.m",
@@ -112,7 +120,7 @@ js_library("password_check") {
js_library("password_check_behavior") {
deps = [
":password_manager_proxy",
- "..:plural_string_proxy",
+ "//ui/webui/resources/js:plural_string_proxy",
]
externs_list = [ "$externs_path/passwords_private.js" ]
}
@@ -152,6 +160,29 @@ js_library("password_edit_dialog") {
]
}
+js_library("multi_store_password_ui_entry") {
+ sources = [ "multi_store_password_ui_entry.js" ]
+ deps = [
+ ":multi_store_id_handler",
+ ":password_manager_proxy",
+ "//ui/webui/resources/js:assert.m",
+ ]
+}
+
+js_library("multi_store_exception_entry") {
+ sources = [ "multi_store_exception_entry.js" ]
+ deps = [
+ ":multi_store_id_handler",
+ ":password_manager_proxy",
+ "//ui/webui/resources/js:assert.m",
+ ]
+}
+
+js_library("multi_store_id_handler") {
+ sources = [ "multi_store_id_handler.js" ]
+ deps = [ "//ui/webui/resources/js:assert.m" ]
+}
+
js_library("password_remove_confirmation_dialog") {
deps = [
":password_manager_proxy",
@@ -171,9 +202,50 @@ js_library("password_list_item") {
]
}
+js_library("passwords_list_handler") {
+ deps = [
+ ":blocking_request_manager",
+ ":password_edit_dialog",
+ ":password_manager_proxy",
+ ":password_move_to_account_dialog",
+ ":password_remove_dialog",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu.m",
+ "//ui/webui/resources/cr_elements/cr_button:cr_button.m",
+ "//ui/webui/resources/cr_elements/cr_toast:cr_toast.m",
+ "//ui/webui/resources/js:assert.m",
+ "//ui/webui/resources/js:i18n_behavior.m",
+ "//ui/webui/resources/js/cr/ui:focus_without_ink.m",
+ ]
+}
+
+js_library("password_move_to_account_dialog") {
+ deps = [
+ ":multi_store_password_ui_entry",
+ ":password_manager_proxy",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/cr_elements/cr_button:cr_button.m",
+ "//ui/webui/resources/cr_elements/cr_dialog:cr_dialog.m",
+ "//ui/webui/resources/js:assert.m",
+ "//ui/webui/resources/js:i18n_behavior.m",
+ ]
+}
+
js_library("password_manager_proxy") {
deps = [ "//ui/webui/resources/js:cr.m" ]
- externs_list = [ "$externs_path/passwords_private.js" ]
+ externs_list =
+ chrome_extension_public_externs + [ "$externs_path/passwords_private.js" ]
+}
+
+js_library("password_remove_dialog") {
+ deps = [
+ ":multi_store_password_ui_entry",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/cr_elements/cr_button:cr_button.m",
+ "//ui/webui/resources/cr_elements/cr_checkbox:cr_checkbox.m",
+ "//ui/webui/resources/cr_elements/cr_dialog:cr_dialog.m",
+ "//ui/webui/resources/js:assert.m",
+ ]
}
js_library("passwords_export_dialog") {
@@ -185,21 +257,23 @@ js_library("passwords_export_dialog") {
js_library("passwords_section") {
deps = [
- ":password_edit_dialog",
+ ":merge_exceptions_store_copies_behavior",
+ ":merge_passwords_store_copies_behavior",
+ ":multi_store_exception_entry",
+ ":multi_store_password_ui_entry",
":password_list_item",
":password_manager_proxy",
+ ":passwords_list_handler",
"..:global_scroll_target_behavior.m",
- "..:plural_string_proxy",
"..:route",
+ "../people_page:profile_info_browser_proxy.m",
"../people_page:sync_browser_proxy.m",
"../prefs:prefs_behavior.m",
"//third_party/polymer/v3_0/components-chromium/iron-a11y-announcer:iron-a11y-announcer",
"//third_party/polymer/v3_0/components-chromium/iron-a11y-keys-behavior:iron-a11y-keys-behavior",
"//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu.m",
- "//ui/webui/resources/cr_elements/cr_toast:cr_toast_manager.m",
"//ui/webui/resources/js:assert.m",
"//ui/webui/resources/js:i18n_behavior.m",
- "//ui/webui/resources/js:list_property_update_behavior.m",
"//ui/webui/resources/js:util.m",
"//ui/webui/resources/js:web_ui_listener_behavior.m",
"//ui/webui/resources/js/cr/ui:focus_without_ink.m",
@@ -210,6 +284,25 @@ js_library("passwords_section") {
]
}
+js_library("passwords_device_section") {
+ deps = [
+ ":merge_passwords_store_copies_behavior",
+ ":multi_store_password_ui_entry",
+ ":password_list_item",
+ ":password_manager_proxy",
+ ":passwords_list_handler",
+ "..:i18n_setup",
+ "..:open_window_proxy",
+ "..:route",
+ "../people_page:profile_info_browser_proxy.m",
+ "//third_party/polymer/v3_0/components-chromium/iron-a11y-keys-behavior:iron-a11y-keys-behavior",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/js:icon.m",
+ "//ui/webui/resources/js:util.m",
+ "//ui/webui/resources/js:web_ui_listener_behavior.m",
+ ]
+}
+
js_library("payments_list") {
deps = [
":credit_card_list_entry",
@@ -240,11 +333,29 @@ js_library("payments_section") {
js_library("show_password_behavior") {
deps = [
":blocking_request_manager",
+ ":multi_store_password_ui_entry",
":password_manager_proxy",
]
externs_list = [ "$externs_path/passwords_private.js" ]
}
+js_library("merge_passwords_store_copies_behavior") {
+ deps = [
+ ":multi_store_password_ui_entry",
+ ":password_manager_proxy",
+ "//ui/webui/resources/js:assert.m",
+ "//ui/webui/resources/js:list_property_update_behavior.m",
+ ]
+}
+
+js_library("merge_exceptions_store_copies_behavior") {
+ deps = [
+ ":multi_store_exception_entry",
+ ":password_manager_proxy",
+ "//ui/webui/resources/js:assert.m",
+ ]
+}
+
js_library("upi_id_list_entry") {
deps = [
"//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
@@ -257,6 +368,7 @@ html_to_js("web_components") {
"address_edit_dialog.js",
"autofill_page.js",
"autofill_section.js",
+ "passwords_list_handler.js",
"credit_card_edit_dialog.js",
"credit_card_list_entry.js",
"password_check_edit_dialog.js",
@@ -264,10 +376,13 @@ html_to_js("web_components") {
"password_check_list_item.js",
"password_check.js",
"password_edit_dialog.js",
+ "password_remove_dialog.js",
"password_list_item.js",
+ "password_move_to_account_dialog.js",
"password_remove_confirmation_dialog.js",
"passwords_export_dialog.js",
"passwords_section.js",
+ "passwords_device_section.js",
"passwords_shared_css.js",
"payments_list.js",
"payments_section.js",
diff --git a/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn
index 2e345985162..9a49bb22976 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/BUILD.gn
@@ -8,11 +8,16 @@ import("//tools/grit/grit_rule.gni")
import("//ui/webui/resources/tools/js_modulizer.gni")
import("//ui/webui/webui_features.gni")
import("../../optimize_webui.gni")
+import("./os_settings.gni")
if (optimize_webui) {
settings_pak_file = "os_settings_resources.pak"
unpak_folder = "os_settings_resources.unpak"
+ # Put v3 unpacked files in a separate folder, to avoid a possible race
+ # between v2 and v3 build targets writing files to the same location.
+ unpak_folder_v3 = "os_settings_resources_v3.unpak"
+
optimize_webui("build") {
host = "os-settings"
html_in_files = [
@@ -34,9 +39,7 @@ if (optimize_webui) {
"chrome://resources/css/cros_colors.generated.css",
"chrome://resources/mojo/chromeos/services/network_config/public/mojom/cros_network_config.mojom.html",
"chrome://os-settings/app-management/app_management.mojom-lite.js",
- "chrome://os-settings/app-management/bitmap.mojom-lite.js",
"chrome://os-settings/app-management/file_path.mojom-lite.js",
- "chrome://os-settings/app-management/image_info.mojom-lite.js",
"chrome://os-settings/app-management/image.mojom-lite.js",
"chrome://os-settings/app-management/types.mojom-lite.js",
"chrome://os-settings/constants/routes.mojom-lite.js",
@@ -47,14 +50,70 @@ if (optimize_webui) {
"chrome://resources/mojo/mojo/public/mojom/base/big_buffer.mojom.html",
"chrome://resources/mojo/mojo/public/mojom/base/string16.mojom.html",
"chrome://resources/mojo/mojo/public/mojom/base/time.mojom.html",
+ "chrome://resources/mojo/skia/public/mojom/bitmap.mojom-lite.js",
+ "chrome://resources/mojo/skia/public/mojom/image_info.mojom-lite.js",
+ "chrome://resources/mojo/url/mojom/url.mojom-lite.js",
]
deps = [ ":unpak" ]
}
+ optimize_webui("build_polymer3") {
+ host = "os-settings"
+ input = rebase_path("$target_gen_dir/$unpak_folder_v3", root_build_dir)
+ js_out_files = [ "os_settings.rollup.js" ]
+ js_module_in_files = [ "chromeos/os_settings.js" ]
+
+ deps = [
+ ":unpak_v3",
+ "../../../../../ui/webui/resources:modulize",
+ ]
+ excludes = [
+ "chrome://resources/js/cr.m.js",
+ "chrome://resources/css/cros_colors.generated.css",
+ "chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js",
+ "chrome://resources/mojo/url/mojom/url.mojom-lite.js",
+ "app-management/app_management.mojom-lite.js",
+ "app-management/bitmap.mojom-lite.js",
+ "app-management/file_path.mojom-lite.js",
+ "app-management/image_info.mojom-lite.js",
+ "app-management/image.mojom-lite.js",
+ "app-management/types.mojom-lite.js",
+ "constants/routes.mojom-lite.js",
+ "constants/setting.mojom-lite.js",
+ "search/search.mojom-lite.js",
+ "search/search_result_icon.mojom-lite.js",
+ "search/user_action_recorder.mojom-lite.js",
+ ]
+ }
+
+ unpak_excludes = [
+ "../../ui/webui/settings/chromeos/constants/routes.mojom-lite.js",
+ "../../ui/webui/settings/chromeos/constants/setting.mojom-lite.js",
+ "../../../../mojo/public/mojom/base/file_path.mojom-lite.js",
+ "../../../../ui/gfx/image/mojom/image.mojom-lite.js",
+ "../../../../url/mojom/url.mojom-lite.js",
+ "../../ui/webui/app_management/app_management.mojom-lite.js",
+ "../../../../components/services/app_service/public/mojom/types.mojom-lite.js",
+ "../../ui/webui/settings/chromeos/search/search.mojom-lite.js",
+ "../../ui/webui/settings/chromeos/search/search_result_icon.mojom-lite.js",
+ "../../ui/webui/settings/chromeos/search/user_action_recorder.mojom-lite.js",
+ ]
+
+ unpak("unpak_v3") {
+ pak_file = settings_pak_file
+ out_folder = unpak_folder_v3
+ pak_base_dir = "../"
+ excludes = unpak_excludes
+
+ deps = [ ":flattened_resources" ]
+ }
+
unpak("unpak") {
pak_file = settings_pak_file
out_folder = unpak_folder
+ pak_base_dir = "../"
+ excludes = unpak_excludes
deps = [ ":flattened_resources" ]
}
@@ -174,13 +233,15 @@ group("closure_compile_module") {
# TODO: Uncomment as the Polymer3 migration makes progress.
#":closure_compile_local_module",
#"ambient_mode_page:closure_compile_module",
- #"bluetooth_page:closure_compile_module",
+ "bluetooth_page:closure_compile_module",
+
#"crostini_page:closure_compile_module",
#"date_time_page:closure_compile_module",
#"device_page:closure_compile_module",
#"google_assistant_page:closure_compile_module",
#"internet_page:closure_compile_module",
- #"localized_link:closure_compile_module",
+ "localized_link:closure_compile_module",
+
#"multidevice_page:closure_compile_module",
#"os_a11y_page:closure_compile_module",
#"os_about_page:closure_compile_module",
@@ -191,7 +252,8 @@ group("closure_compile_module") {
#"os_people_page:closure_compile_module",
#"os_printing_page:closure_compile_module",
#"os_privacy_page:closure_compile_module",
- #"os_reset_page:closure_compile_module",
+ "os_reset_page:closure_compile_module",
+
#"os_search_page:closure_compile_module",
#"os_settings_main:closure_compile_module",
#"os_settings_menu:closure_compile_module",
@@ -204,28 +266,28 @@ group("closure_compile_module") {
]
}
-# TODO: Uncomment as the Polymer3 migration makes progress.
-#js_type_check("closure_compile_local_module") {
-# is_polymer3 = true
-# deps = [
-# ":metrics_recorder.m",
-# ":os_icons.m",
-# ":os_page_visibility.m",
-# ":os_route.m",
-# ":os_settings.m",
-# ":os_settings_icons_css.m",
-# ":os_settings_routes.m",
-# ":route_origin_behavior.m",
-# ":search_handler.m",
-# ]
-#}
+js_type_check("closure_compile_local_module") {
+ is_polymer3 = true
+ deps = [
+ ":metrics_recorder.m",
+
+ # ":os_icons.m",
+ # ":os_page_visibility.m",
+ ":os_route.m",
+
+ # ":os_settings.m",
+ # ":os_settings_icons_css.m",
+ ":os_settings_routes.m",
+
+ # ":route_origin_behavior.m",
+ # ":search_handler.m",
+ ]
+}
js_library("metrics_recorder.m") {
sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/metrics_recorder.m.js" ]
- deps = [
- # TODO: Fill those in.
- ]
- extra_deps = [ ":metrics_recorder_module" ]
+ deps = [ "//chrome/browser/ui/webui/settings/chromeos/search:mojo_bindings_js_library_for_compile" ]
+ extra_deps = [ ":modulize" ]
}
js_library("os_icons.m") {
@@ -251,9 +313,13 @@ js_library("os_route.m") {
"$root_gen_dir/chrome/browser/resources/settings/chromeos/os_route.m.js",
]
deps = [
- # TODO: Fill those in.
+ ":os_settings_routes.m",
+ "..:router.m",
+ "//chrome/browser/ui/webui/settings/chromeos/constants:mojom_js_library_for_compile",
+ "//ui/webui/resources/js:cr.m",
+ "//ui/webui/resources/js:load_time_data.m",
]
- extra_deps = [ ":os_route_module" ]
+ extra_deps = [ ":modulize" ]
}
js_library("os_settings_icons_css.m") {
@@ -266,9 +332,7 @@ js_library("os_settings_icons_css.m") {
js_library("os_settings_routes.m") {
sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/os_settings_routes.m.js" ]
- deps = [
- # TODO: Fill those in.
- ]
+ deps = [ "//ui/webui/resources/js:load_time_data.m" ]
extra_deps = [ ":modulize" ]
}
@@ -323,19 +387,21 @@ group("polymer3_elements") {
"personalization_page:polymer3_elements",
# Local targets
- ":metrics_recorder_module",
":modulize",
":os_icons_module",
":os_page_visibility_module",
- ":os_route_module",
":os_settings_icons_css_module",
- ]
-}
-polymer_modulizer("metrics_recorder") {
- js_file = "metrics_recorder.js"
- html_file = "metrics_recorder.html"
- html_type = "dom-module"
+ # Shared with browser settings
+ "..:modulize",
+ "..:settings_shared_css_module",
+ "..:settings_vars_css_module",
+ "../nearby_share_page:polymer3_elements",
+ "../prefs:modulize",
+ "../prefs:prefs_module",
+ "../settings_page:settings_animated_pages_module",
+ "../settings_page:settings_subpage_module",
+ ]
}
polymer_modulizer("os_icons") {
@@ -350,12 +416,6 @@ polymer_modulizer("os_page_visibility") {
html_type = "dom-module"
}
-polymer_modulizer("os_route") {
- js_file = "os_route.js"
- html_file = "os_route.html"
- html_type = "dom-module"
-}
-
polymer_modulizer("os_settings_icons_css") {
js_file = "os_settings_icons_css.m.js"
html_file = "os_settings_icons_css.html"
@@ -364,8 +424,11 @@ polymer_modulizer("os_settings_icons_css") {
js_modulizer("modulize") {
input_files = [
+ "metrics_recorder.js",
"os_settings_routes.js",
"route_origin_behavior.js",
"search_handler.js",
+ "os_route.js",
]
+ namespace_rewrites = os_settings_namespace_rewrites
}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/ambient_mode_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/ambient_mode_page/BUILD.gn
index 3e19c60857f..71795b20191 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/ambient_mode_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/ambient_mode_page/BUILD.gn
@@ -8,31 +8,54 @@ js_type_check("closure_compile") {
deps = [
":ambient_mode_browser_proxy",
":ambient_mode_page",
+ ":ambient_mode_photos_page",
+ ":constants",
]
}
js_library("ambient_mode_browser_proxy") {
- deps = [ "//ui/webui/resources/js:cr" ]
+ deps = [
+ ":constants",
+ "//ui/webui/resources/js:cr",
+ ]
externs_list = [ "$externs_path/chrome_send.js" ]
}
js_library("ambient_mode_page") {
deps = [
":ambient_mode_browser_proxy",
+ ":constants",
+ "..:os_route",
+ "../..:router",
"../../prefs:prefs_behavior",
"//ui/webui/resources/js:cr",
"//ui/webui/resources/js:i18n_behavior",
- "//ui/webui/resources/js:load_time_data",
"//ui/webui/resources/js:web_ui_listener_behavior",
]
}
+js_library("ambient_mode_photos_page") {
+ deps = [
+ ":ambient_mode_browser_proxy",
+ ":constants",
+ "..:os_route",
+ "../..:router",
+ "//ui/webui/resources/js:cr",
+ "//ui/webui/resources/js:i18n_behavior",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
+ ]
+}
+
+js_library("constants") {
+}
+
# TODO: Uncomment as the Polymer3 migration makes progress.
#js_type_check("closure_compile_module") {
# is_polymer3 = true
# deps = [
# ":ambient_mode_browser_proxy.m",
-# ":ambient_mode_page.m"
+# ":ambient_mode_page.m",
+# ":ambient_mode_photos_page.m",
# ]
#}
@@ -52,11 +75,20 @@ js_library("ambient_mode_page.m") {
extra_deps = [ ":ambient_mode_page_module" ]
}
+js_library("ambient_mode_photos_page.m") {
+ sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/ambient_mode_page/ambient_mode_photos_page.m.js" ]
+ deps = [
+ # TODO: Fill those in.
+ ]
+ extra_deps = [ ":ambient_mode_photos_page_module" ]
+}
+
import("//tools/polymer/polymer.gni")
group("polymer3_elements") {
public_deps = [
":ambient_mode_page_module",
+ ":ambient_mode_photos_page_module",
":modulize",
]
}
@@ -67,8 +99,17 @@ polymer_modulizer("ambient_mode_page") {
html_type = "dom-module"
}
+polymer_modulizer("ambient_mode_photos_page") {
+ js_file = "ambient_mode_photos_page.js"
+ html_file = "ambient_mode_photos_page.html"
+ html_type = "dom-module"
+}
+
import("//ui/webui/resources/tools/js_modulizer.gni")
js_modulizer("modulize") {
- input_files = [ "ambient_mode_browser_proxy.js" ]
+ input_files = [
+ "ambient_mode_browser_proxy.js",
+ "constants.js",
+ ]
}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/bluetooth_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/bluetooth_page/BUILD.gn
index a3432524ed1..9d36108f851 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/bluetooth_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/bluetooth_page/BUILD.gn
@@ -3,6 +3,8 @@
# found in the LICENSE file.
import("//third_party/closure_compiler/compile_js.gni")
+import("//tools/polymer/polymer.gni")
+import("../os_settings.gni")
js_type_check("closure_compile") {
deps = [
@@ -14,11 +16,11 @@ js_type_check("closure_compile") {
js_library("bluetooth_page") {
deps = [
- ":bluetooth_system_on_extensions",
"..:os_route",
"../..:router",
"../../prefs:prefs_behavior",
"../../settings_page:settings_animated_pages",
+ "//services/device/public/mojom:mojom_js_library_for_compile",
"//ui/webui/resources/js:assert",
"//ui/webui/resources/js:i18n_behavior",
]
@@ -34,20 +36,20 @@ js_library("bluetooth_page") {
js_library("bluetooth_subpage") {
deps = [
- ":bluetooth_system_on_extensions",
"..:metrics_recorder",
"..:os_route",
"../..:router",
- "//ui/webui/resources/cr_components/chromeos:bluetooth_dialog",
+ "//services/device/public/mojom:mojom_js_library_for_compile",
+ "//ui/webui/resources/cr_components/chromeos/bluetooth:bluetooth_dialog",
"//ui/webui/resources/cr_elements:cr_scrollable_behavior",
"//ui/webui/resources/js:assert",
"//ui/webui/resources/js:i18n_behavior",
"//ui/webui/resources/js:list_property_update_behavior",
]
- externs_list = [
- "$externs_path/bluetooth.js",
- "$externs_path/bluetooth_private.js",
- ]
+ externs_list = chrome_extension_public_externs + [
+ "$externs_path/bluetooth.js",
+ "$externs_path/bluetooth_private.js",
+ ]
extra_sources = [
"$interfaces_path/bluetooth_interface.js",
"$interfaces_path/bluetooth_private_interface.js",
@@ -56,7 +58,7 @@ js_library("bluetooth_subpage") {
js_library("bluetooth_device_list_item") {
deps = [
- ":bluetooth_system_on_extensions",
+ "//services/device/public/mojom:mojom_js_library_for_compile",
"//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu",
"//ui/webui/resources/js:i18n_behavior",
"//ui/webui/resources/js/cr/ui:focus_row_behavior",
@@ -64,33 +66,42 @@ js_library("bluetooth_device_list_item") {
externs_list = [ "$externs_path/bluetooth.js" ]
}
-js_library("bluetooth_system_on_extensions") {
- sources = []
- deps = [ "//services/device/public/mojom:mojom_js_library_for_compile" ]
+js_type_check("closure_compile_module") {
+ is_polymer3 = true
+ deps = [
+ ":bluetooth_device_list_item.m",
+ ":bluetooth_page.m",
+ ":bluetooth_subpage.m",
+ ]
}
-# TODO: Uncomment as the Polymer3 migration makes progress.
-#js_type_check("closure_compile_module") {
-# is_polymer3 = true
-# deps = [
-# ":bluetooth_device_list_item.m",
-# ":bluetooth_page.m",
-# ":bluetooth_subpage.m"
-# ]
-#}
-
js_library("bluetooth_device_list_item.m") {
sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_device_list_item.m.js" ]
deps = [
- # TODO: Fill those in.
+ "//services/device/public/mojom:mojom_js_library_for_compile",
+ "//ui/webui/resources/cr_elements/cr_action_menu:cr_action_menu.m",
+ "//ui/webui/resources/js:i18n_behavior.m",
+ "//ui/webui/resources/js/cr/ui:focus_row_behavior.m",
]
+ externs_list = [ "$externs_path/bluetooth.js" ]
extra_deps = [ ":bluetooth_device_list_item_module" ]
}
js_library("bluetooth_page.m") {
sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_page.m.js" ]
deps = [
- # TODO: Fill those in.
+ ":bluetooth_subpage.m",
+ "..:os_route.m",
+ "../..:router.m",
+ "../../prefs:prefs_behavior.m",
+ "../../settings_page:settings_animated_pages.m",
+ "//services/device/public/mojom:mojom_js_library_for_compile",
+ "//ui/webui/resources/js:assert.m",
+ "//ui/webui/resources/js:i18n_behavior.m",
+ ]
+ externs_list = [
+ "$externs_path/bluetooth.js",
+ "$externs_path/bluetooth_private.js",
]
extra_deps = [ ":bluetooth_page_module" ]
}
@@ -98,13 +109,24 @@ js_library("bluetooth_page.m") {
js_library("bluetooth_subpage.m") {
sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_subpage.m.js" ]
deps = [
- # TODO: Fill those in.
+ "..:metrics_recorder.m",
+ "..:os_route.m",
+ "../..:router.m",
+ "//services/device/public/mojom:mojom_js_library_for_compile",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/cr_components/chromeos/bluetooth:bluetooth_dialog.m",
+ "//ui/webui/resources/cr_elements:cr_scrollable_behavior.m",
+ "//ui/webui/resources/js:assert.m",
+ "//ui/webui/resources/js:i18n_behavior.m",
+ "//ui/webui/resources/js:list_property_update_behavior.m",
+ ]
+ externs_list = [
+ "$externs_path/bluetooth.js",
+ "$externs_path/bluetooth_private.js",
]
extra_deps = [ ":bluetooth_subpage_module" ]
}
-import("//tools/polymer/polymer.gni")
-
group("polymer3_elements") {
public_deps = [
":bluetooth_device_list_item_module",
@@ -117,16 +139,25 @@ polymer_modulizer("bluetooth_device_list_item") {
js_file = "bluetooth_device_list_item.js"
html_file = "bluetooth_device_list_item.html"
html_type = "dom-module"
+ migrated_imports = os_settings_migrated_imports
+ namespace_rewrites = os_settings_namespace_rewrites
+ auto_imports = os_settings_auto_imports
}
polymer_modulizer("bluetooth_page") {
js_file = "bluetooth_page.js"
html_file = "bluetooth_page.html"
html_type = "dom-module"
+ migrated_imports = os_settings_migrated_imports
+ namespace_rewrites = os_settings_namespace_rewrites
+ auto_imports = os_settings_auto_imports
}
polymer_modulizer("bluetooth_subpage") {
js_file = "bluetooth_subpage.js"
html_file = "bluetooth_subpage.html"
html_type = "dom-module"
+ migrated_imports = os_settings_migrated_imports
+ namespace_rewrites = os_settings_namespace_rewrites
+ auto_imports = os_settings_auto_imports
}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/crostini_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/crostini_page/BUILD.gn
index 8da221484d9..abf46959d3f 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/crostini_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/crostini_page/BUILD.gn
@@ -12,6 +12,7 @@ js_type_check("closure_compile") {
":crostini_export_import",
":crostini_page",
":crostini_port_forwarding",
+ ":crostini_port_forwarding_add_port_dialog",
":crostini_shared_paths",
":crostini_shared_usb_devices",
":crostini_subpage",
@@ -92,6 +93,14 @@ js_library("crostini_port_forwarding") {
]
}
+js_library("crostini_port_forwarding_add_port_dialog") {
+ deps = [
+ ":crostini_browser_proxy",
+ "..:metrics_recorder",
+ "//ui/webui/resources/js:cr",
+ ]
+}
+
js_library("crostini_subpage") {
deps = [
":crostini_browser_proxy",
diff --git a/chromium/chrome/browser/resources/settings/chromeos/date_time_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/date_time_page/BUILD.gn
index 4d73c447751..3bfa5759c96 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/date_time_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/date_time_page/BUILD.gn
@@ -8,6 +8,7 @@ js_type_check("closure_compile") {
deps = [
":date_time_page",
":date_time_types",
+ ":timezone_browser_proxy",
":timezone_selector",
":timezone_subpage",
]
@@ -17,7 +18,6 @@ js_library("date_time_page") {
deps = [
":date_time_types",
":timezone_selector",
- ":timezone_subpage",
"..:os_route",
"../..:router",
"../../prefs:prefs_behavior",
@@ -33,6 +33,10 @@ js_library("date_time_types") {
deps = [ "//ui/webui/resources/js:cr" ]
}
+js_library("timezone_browser_proxy") {
+ deps = [ "//ui/webui/resources/js:cr" ]
+}
+
js_library("timezone_selector") {
deps = [
":date_time_types",
@@ -46,6 +50,7 @@ js_library("timezone_selector") {
js_library("timezone_subpage") {
deps = [
":date_time_types",
+ ":timezone_browser_proxy",
":timezone_selector",
"../../prefs:prefs_behavior",
"//ui/webui/resources/js:cr",
@@ -58,6 +63,7 @@ js_library("timezone_subpage") {
# deps = [
# ":date_time_page.m",
# ":date_time_types.m",
+# ":timezone_browser_proxy.m",
# ":timezone_selector.m",
# ":timezone_subpage.m"
# ]
@@ -79,6 +85,14 @@ js_library("date_time_types.m") {
extra_deps = [ ":date_time_types_module" ]
}
+js_library("timezone_browser_proxy.m") {
+ sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/date_time_page/timezone_browser_proxy.m.js" ]
+ deps = [
+ # TODO: Fill those in.
+ ]
+ extra_deps = [ ":modulize" ]
+}
+
js_library("timezone_selector.m") {
sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/date_time_page/timezone_selector.m.js" ]
deps = [
@@ -101,6 +115,7 @@ group("polymer3_elements") {
public_deps = [
":date_time_page_module",
":date_time_types_module",
+ ":modulize",
":timezone_selector_module",
":timezone_subpage_module",
]
@@ -129,3 +144,9 @@ polymer_modulizer("timezone_subpage") {
html_file = "timezone_subpage.html"
html_type = "dom-module"
}
+
+import("//ui/webui/resources/tools/js_modulizer.gni")
+
+js_modulizer("modulize") {
+ input_files = [ "timezone_browser_proxy.js" ]
+}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/device_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/device_page/BUILD.gn
index a9273bb0410..56c8f9e9eab 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/device_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/device_page/BUILD.gn
@@ -82,10 +82,10 @@ js_library("display") {
"//ui/webui/resources/js:i18n_behavior",
"//ui/webui/resources/js/cr/ui:focus_without_ink",
]
- externs_list = [
- "$externs_path/settings_private.js",
- "$externs_path/system_display.js",
- ]
+ externs_list = chrome_extension_public_externs + [
+ "$externs_path/settings_private.js",
+ "$externs_path/system_display.js",
+ ]
extra_sources = [ "$interfaces_path/system_display_interface.js" ]
}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/localized_link/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/localized_link/BUILD.gn
index 7bd578dc434..2f90cb59d16 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/localized_link/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/localized_link/BUILD.gn
@@ -3,6 +3,9 @@
# found in the LICENSE file.
import("//third_party/closure_compiler/compile_js.gni")
+import("//tools/polymer/polymer.gni")
+import("//ui/webui/resources/tools/js_modulizer.gni")
+import("../os_settings.gni")
js_type_check("closure_compile") {
deps = [ ":localized_link" ]
@@ -12,24 +15,20 @@ js_library("localized_link") {
deps = [ "//ui/webui/resources/js:assert" ]
}
-# TODO: Uncomment as the Polymer3 migration makes progress.
-#js_type_check("closure_compile_module") {
-# is_polymer3 = true
-# deps = [
-# ":localized_link.m"
-# ]
-#}
+js_type_check("closure_compile_module") {
+ is_polymer3 = true
+ deps = [ ":localized_link.m" ]
+}
js_library("localized_link.m") {
sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/localized_link/localized_link.m.js" ]
deps = [
- # TODO: Fill those in.
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/js:assert.m",
]
extra_deps = [ ":localized_link_module" ]
}
-import("//tools/polymer/polymer.gni")
-
group("polymer3_elements") {
public_deps = [ ":localized_link_module" ]
}
@@ -38,4 +37,8 @@ polymer_modulizer("localized_link") {
js_file = "localized_link.js"
html_file = "localized_link.html"
html_type = "dom-module"
+ namespace_rewrites = os_settings_namespace_rewrites
+ auto_imports =
+ os_settings_auto_imports +
+ [ "ui/webui/resources/html/assert.html|assert,assertNotReached" ]
}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/multidevice_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/multidevice_page/BUILD.gn
index 238c338b802..fb41281d966 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/multidevice_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/multidevice_page/BUILD.gn
@@ -63,6 +63,7 @@ js_library("multidevice_page") {
"..:os_route",
"../..:router",
"../../controls:password_prompt_dialog",
+ "../../prefs:prefs_behavior",
"../localized_link:localized_link",
"//ui/webui/resources/js:cr",
"//ui/webui/resources/js:web_ui_listener_behavior",
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/plugin_vm_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/plugin_vm_page/BUILD.gn
index 3c63e8b8004..a3971b9ff9b 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/plugin_vm_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_apps_page/app_management_page/plugin_vm_page/BUILD.gn
@@ -18,9 +18,13 @@ js_library("plugin_vm_browser_proxy") {
js_library("plugin_vm_detail_view") {
deps = [
+ ":plugin_vm_browser_proxy",
+ ":plugin_vm_permission_dialog",
"../:constants",
+ "../:permission_item",
"../:store_client",
"../:util",
+ "//ui/webui/resources/js:web_ui_listener_behavior",
]
}
@@ -31,6 +35,10 @@ js_library("plugin_vm_shared_paths") {
]
}
+js_library("plugin_vm_permission_dialog") {
+ deps = [ ":plugin_vm_browser_proxy" ]
+}
+
# TODO: Uncomment as the Polymer3 migration makes progress.
#js_type_check("closure_compile_module") {
# is_polymer3 = true
@@ -71,6 +79,7 @@ group("polymer3_elements") {
public_deps = [
":modulize",
":plugin_vm_detail_view_module",
+ ":plugin_vm_permission_dialog_module",
":plugin_vm_shared_paths_module",
]
}
@@ -81,6 +90,12 @@ polymer_modulizer("plugin_vm_detail_view") {
html_type = "dom-module"
}
+polymer_modulizer("plugin_vm_permission_dialog") {
+ js_file = "plugin_vm_permission_dialog.js"
+ html_file = "plugin_vm_permission_dialog.html"
+ html_type = "dom-module"
+}
+
polymer_modulizer("plugin_vm_shared_paths") {
js_file = "plugin_vm_shared_paths.js"
html_file = "plugin_vm_shared_paths.html"
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
index 1af53f2340e..6f55d8d266b 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/os_languages_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_languages_page/BUILD.gn
@@ -3,9 +3,13 @@
# found in the LICENSE file.
import("//third_party/closure_compiler/compile_js.gni")
+import("//ui/webui/resources/tools/js_modulizer.gni")
+import("../os_settings.gni")
js_type_check("closure_compile") {
deps = [
+ ":input_method_options_page",
+ ":input_method_util",
":manage_input_methods_page",
":os_add_languages_dialog",
":os_languages_page",
@@ -16,6 +20,20 @@ js_type_check("closure_compile") {
]
}
+js_library("input_method_options_page") {
+ deps = [
+ ":input_method_util",
+ "../..:router",
+ "../../languages_page:languages_types",
+ "../../prefs",
+ "//ui/webui/resources/js:i18n_behavior",
+ ]
+}
+
+js_library("input_method_util") {
+ deps = [ "//ui/webui/resources/js:cr" ]
+}
+
js_library("manage_input_methods_page") {
deps = [
"../../languages_page:languages_types",
@@ -26,6 +44,7 @@ js_library("manage_input_methods_page") {
js_library("os_languages_section") {
deps = [
+ ":input_method_options_page",
":manage_input_methods_page",
":os_languages_page",
"..:os_route",
@@ -43,6 +62,7 @@ js_library("os_languages_section") {
js_library("os_languages_page") {
deps = [
+ ":input_method_util",
"..:metrics_recorder",
"..:os_route",
"../..:lifetime_browser_proxy",
@@ -73,6 +93,8 @@ js_library("os_add_languages_dialog") {
#js_type_check("closure_compile_module") {
# is_polymer3 = true
# deps = [
+# ":input_method_options_page.m",
+# ":input_method_util.m",
# ":manage_input_methods_page.m",
# ":os_add_languages_dialog.m",
# ":os_languages_page.m",
@@ -80,6 +102,22 @@ js_library("os_add_languages_dialog") {
# ]
#}
+js_library("input_method_util.m") {
+ sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/os_languages_page/input_method_util.m.js" ]
+ deps = [
+ # TODO: Fill those in.
+ ]
+ extra_deps = [ ":modulize" ]
+}
+
+js_library("input_method_options_page.m") {
+ sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/os_languages_page/input_method_options_page.m.js" ]
+ deps = [
+ # TODO: Fill those in.
+ ]
+ extra_deps = [ ":input_method_options_page_module" ]
+}
+
js_library("manage_input_methods_page.m") {
sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/os_languages_page/manage_input_methods_page.m.js" ]
deps = [
@@ -116,7 +154,9 @@ import("//tools/polymer/polymer.gni")
group("polymer3_elements") {
public_deps = [
+ ":input_method_options_page_module",
":manage_input_methods_page_module",
+ ":modulize",
":os_add_languages_dialog_module",
":os_languages_page_module",
":os_languages_section_module",
@@ -146,3 +186,14 @@ polymer_modulizer("os_languages_section") {
html_file = "os_languages_section.html"
html_type = "dom-module"
}
+
+polymer_modulizer("input_method_options_page") {
+ js_file = "input_method_options_page.js"
+ html_file = "input_method_options_page.html"
+ html_type = "dom-module"
+}
+
+js_modulizer("modulize") {
+ input_files = [ "input_method_util.js" ]
+ namespace_rewrites = os_settings_namespace_rewrites
+}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_privacy_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_privacy_page/BUILD.gn
index f89ff3750c3..32e7bbe7959 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/os_privacy_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_privacy_page/BUILD.gn
@@ -9,8 +9,10 @@ js_type_check("closure_compile") {
}
js_library("os_privacy_page") {
- deps =
- [ "//chrome/browser/resources/settings/controls:settings_toggle_button" ]
+ deps = [
+ "//chrome/browser/resources/settings/controls:settings_toggle_button",
+ "//ui/webui/resources/js:load_time_data",
+ ]
}
# TODO: Uncomment as the Polymer3 migration makes progress.
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_reset_page/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_reset_page/BUILD.gn
index cf97405216f..e05a9896a07 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/os_reset_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_reset_page/BUILD.gn
@@ -3,6 +3,9 @@
# found in the LICENSE file.
import("//third_party/closure_compiler/compile_js.gni")
+import("//tools/polymer/polymer.gni")
+import("//ui/webui/resources/tools/js_modulizer.gni")
+import("../os_settings.gni")
js_type_check("closure_compile") {
deps = [
@@ -25,6 +28,7 @@ js_library("os_reset_page") {
deps = [
"//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",
]
}
@@ -34,20 +38,23 @@ js_library("os_reset_browser_proxy") {
externs_list = [ "$externs_path/chrome_send.js" ]
}
-# TODO: Uncomment as the Polymer3 migration makes progress.
-#js_type_check("closure_compile_module") {
-# is_polymer3 = true
-# deps = [
-# ":os_powerwash_dialog.m",
-# ":os_reset_browser_proxy.m",
-# ":os_reset_page.m"
-# ]
-#}
+js_type_check("closure_compile_module") {
+ is_polymer3 = true
+ deps = [
+ ":os_powerwash_dialog.m",
+ ":os_reset_browser_proxy.m",
+ ":os_reset_page.m",
+ ]
+}
js_library("os_powerwash_dialog.m") {
sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/os_reset_page/os_powerwash_dialog.m.js" ]
deps = [
- # TODO: Fill those in.
+ ":os_reset_browser_proxy.m",
+ "..:metrics_recorder.m",
+ "../..:lifetime_browser_proxy.m",
+ "../localized_link:localized_link.m",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
]
extra_deps = [ ":os_powerwash_dialog_module" ]
}
@@ -55,7 +62,8 @@ js_library("os_powerwash_dialog.m") {
js_library("os_reset_browser_proxy.m") {
sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/os_reset_page/os_reset_browser_proxy.m.js" ]
deps = [
- # TODO: Fill those in.
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/js:cr.m",
]
extra_deps = [ ":modulize" ]
}
@@ -63,13 +71,14 @@ js_library("os_reset_browser_proxy.m") {
js_library("os_reset_page.m") {
sources = [ "$root_gen_dir/chrome/browser/resources/settings/chromeos/os_reset_page/os_reset_page.m.js" ]
deps = [
- # TODO: Fill those in.
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/js:assert.m",
+ "//ui/webui/resources/js:load_time_data.m",
+ "//ui/webui/resources/js/cr/ui:focus_without_ink.m",
]
extra_deps = [ ":os_reset_page_module" ]
}
-import("//tools/polymer/polymer.gni")
-
group("polymer3_elements") {
public_deps = [
":modulize",
@@ -82,16 +91,21 @@ polymer_modulizer("os_powerwash_dialog") {
js_file = "os_powerwash_dialog.js"
html_file = "os_powerwash_dialog.html"
html_type = "dom-module"
+ namespace_rewrites = os_settings_namespace_rewrites
+ auto_imports = os_settings_auto_imports
}
polymer_modulizer("os_reset_page") {
js_file = "os_reset_page.js"
html_file = "os_reset_page.html"
html_type = "dom-module"
+ migrated_imports = settings_migrated_imports
+ namespace_rewrites = os_settings_namespace_rewrites
+ auto_imports = os_settings_auto_imports +
+ [ "ui/webui/resources/html/assert.html|assert" ]
}
-import("//ui/webui/resources/tools/js_modulizer.gni")
-
js_modulizer("modulize") {
input_files = [ "os_reset_browser_proxy.js" ]
+ namespace_rewrites = os_settings_namespace_rewrites
}
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_settings.gni b/chromium/chrome/browser/resources/settings/chromeos/os_settings.gni
new file mode 100644
index 00000000000..400b8e0059e
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_settings.gni
@@ -0,0 +1,24 @@
+# Copyright 2020 The Chromium 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")
+import("../settings.gni")
+
+os_settings_namespace_rewrites =
+ settings_namespace_rewrites + [
+ "settings.OsResetBrowserProxy|OsResetBrowserProxy",
+ "settings.recordSettingChange|recordSettingChange",
+ ]
+
+os_settings_auto_imports = settings_auto_imports + [
+ "chrome/browser/resources/settings/chromeos/os_reset_page/os_reset_browser_proxy.html|OsResetBrowserProxy,OsResetBrowserProxyImpl",
+ "chrome/browser/resources/settings/chromeos/metrics_recorder.html|recordSettingChange",
+ "chrome/browser/resources/settings/lifetime_browser_proxy.html|LifetimeBrowserProxy,LifetimeBrowserProxyImpl",
+ "chrome/browser/resources/settings/chromeos/os_route.html|routes",
+ "chrome/browser/resources/settings/route.html|routes",
+ "chrome/browser/resources/settings/router.html|Router,Route,RouteObserverBehavior",
+ "ui/webui/resources/html/polymer.html|Polymer,html,flush",
+ ]
+
+os_settings_migrated_imports = settings_migrated_imports
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 f9e55626477..7afa56ffe1d 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
@@ -14,7 +14,6 @@ js_library("os_settings_page") {
"..:os_route",
"../..:router",
"../..:search_settings",
- "../../prefs:prefs_behavior",
"../../settings_page:main_page_behavior",
"../os_apps_page:android_apps_browser_proxy",
"//ui/webui/resources/js:load_time_data",
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_settings_resources_v3.grdp b/chromium/chrome/browser/resources/settings/chromeos/os_settings_resources_v3.grdp
index db555e9d3a1..c764effbb47 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/os_settings_resources_v3.grdp
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_settings_resources_v3.grdp
@@ -1,13 +1,137 @@
<?xml version="1.0" encoding="utf-8"?>
<grit-part>
- <include name="IDR_OS_SETTINGS_SEARCH_HANDLER_M_JS"
- file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/search_handler.m.js"
+ <include name="IDR_OS_SETTINGS_RESET_BROWSER_PROXY_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/os_reset_page/os_reset_browser_proxy.m.js"
use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_RESET_POWERWASH_DIALOG_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/os_reset_page/os_powerwash_dialog.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_RESET_PAGE_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/os_reset_page/os_reset_page.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_BLUETOOTH_PAGE_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_page.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_BLUETOOTH_SUBPAGE_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_subpage.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_BLUETOOTH_DEVICE_LIST_ITEM_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/bluetooth_page/bluetooth_device_list_item.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_LOCALIZED_LINK_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/localized_link/localized_link.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_METRIC_RECORDER_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/metrics_recorder.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_OS_ICONS_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/os_icons.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_SETTINGS_OS_ROUTE_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/os_route.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_SETTINGS_OS_SETTINGS_ROUTE_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/chromeos/os_settings_routes.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_SETTINGS_SUBPAGE_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/settings_page/settings_subpage.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA"/>
+ <include name="IDR_OS_SETTINGS_SETTINGS_ANIMATED_PAGES_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/settings_page/settings_animated_pages.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA"/>
+ <include name="IDR_OS_SETTINGS_SETTINGS_TOGGLE_BUTTON_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/controls/settings_toggle_button.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_SETTINGS_BOOLEAN_CONTROL_BEHAVIOR_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/controls/settings_boolean_control_behavior.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_PREF_CONTROL_BEHAVIOR_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/controls/pref_control_behavior.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_LIFETIME_BROWSER_PROXY_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/lifetime_browser_proxy.m.js"
+ use_base_dir="false"
+ compress="false"
+ preprocess="true"
+ type="BINDATA"/>
+ <include name="IDR_OS_SETTINGS_PREFS_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/prefs/prefs.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA"/>
+ <include name="IDR_OS_SETTINGS_PREFS_BEHAVIOR_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/prefs/prefs_behavior.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA"/>
+ <include name="IDR_OS_SETTINGS_PREFS_TYPES_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/prefs/prefs_types.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA"/>
+ <include name="IDR_OS_SETTINGS_NEARBY_SHARE_SUBPAGE_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/nearby_share_page/nearby_share_subpage.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_ROUTER_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/router.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_SETTINGS_SHARED_CSS_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/settings_shared_css.m.js"
+ use_base_dir="false"
+ preprocess="true"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_SETTINGS_VARS_CSS_M_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/settings_vars_css.m.js"
+ use_base_dir="false"
+ compress="false"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_I18N_SETUP_JS"
+ file="i18n_setup.js"
+ compress="false"
type="BINDATA" />
<include name="IDR_OS_SETTINGS_SETTINGS_V3_HTML"
file="chromeos/os_settings_v3.html"
+ compress="false"
type="BINDATA" />
<include name="IDR_OS_SETTINGS_SETTINGS_V3_JS"
file="chromeos/os_settings.js"
+ compress="false"
type="BINDATA" />
-</grit-part> \ No newline at end of file
+</grit-part>
diff --git a/chromium/chrome/browser/resources/settings/chromeos/os_settings_search_box/BUILD.gn b/chromium/chrome/browser/resources/settings/chromeos/os_settings_search_box/BUILD.gn
index a206a3b623f..71f87b6c7d0 100644
--- a/chromium/chrome/browser/resources/settings/chromeos/os_settings_search_box/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/chromeos/os_settings_search_box/BUILD.gn
@@ -22,6 +22,7 @@ js_library("os_settings_search_box") {
"//ui/webui/resources/cr_elements/cr_toolbar:cr_toolbar_search_field",
"//ui/webui/resources/js:assert",
]
+ externs_list = [ "$externs_path/metrics_private.js" ]
}
js_library("os_search_result_row") {
@@ -34,6 +35,7 @@ js_library("os_search_result_row") {
"//ui/webui/resources/js:i18n_behavior",
"//ui/webui/resources/js/cr/ui:focus_row_behavior",
]
+ externs_list = [ "$externs_path/metrics_private.js" ]
}
# TODO: Uncomment as the Polymer3 migration makes progress.
@@ -51,6 +53,7 @@ js_library("os_search_result_row.m") {
# TODO: Fill those in.
]
extra_deps = [ ":os_search_result_row_module" ]
+ externs_list = [ "$externs_path/metrics_private.js" ]
}
js_library("os_settings_search_box.m") {
@@ -59,6 +62,7 @@ js_library("os_settings_search_box.m") {
# TODO: Fill those in.
]
extra_deps = [ ":os_settings_search_box_module" ]
+ externs_list = [ "$externs_path/metrics_private.js" ]
}
import("//tools/polymer/polymer.gni")
diff --git a/chromium/chrome/browser/resources/settings/controls/BUILD.gn b/chromium/chrome/browser/resources/settings/controls/BUILD.gn
index 69216da31e1..506ca163505 100644
--- a/chromium/chrome/browser/resources/settings/controls/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/controls/BUILD.gn
@@ -57,7 +57,8 @@ js_library("password_prompt_dialog") {
"//ui/webui/resources/cr_elements/cr_dialog:cr_dialog",
"//ui/webui/resources/cr_elements/cr_input:cr_input",
]
- externs_list = [ "$externs_path/quick_unlock_private.js" ]
+ externs_list = chrome_extension_public_externs +
+ [ "$externs_path/quick_unlock_private.js" ]
extra_sources = [ "$interfaces_path/quick_unlock_private_interface.js" ]
}
@@ -183,7 +184,8 @@ js_library("password_prompt_dialog.m") {
"//ui/webui/resources/cr_elements/cr_dialog:cr_dialog.m",
"//ui/webui/resources/cr_elements/cr_input:cr_input.m",
]
- externs_list = [ "$externs_path/quick_unlock_private.js" ]
+ externs_list = chrome_extension_public_externs +
+ [ "$externs_path/quick_unlock_private.js" ]
extra_deps = [ ":password_prompt_dialog_module" ]
}
diff --git a/chromium/chrome/browser/resources/settings/nearby_share_page/BUILD.gn b/chromium/chrome/browser/resources/settings/nearby_share_page/BUILD.gn
new file mode 100644
index 00000000000..81c2a5030f6
--- /dev/null
+++ b/chromium/chrome/browser/resources/settings/nearby_share_page/BUILD.gn
@@ -0,0 +1,54 @@
+# Copyright 2020 The Chromium 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")
+import("//tools/polymer/polymer.gni")
+import("../settings.gni")
+
+js_type_check("closure_compile") {
+ deps = [ ":nearby_share_subpage" ]
+}
+
+js_library("nearby_share_subpage") {
+ deps = [
+ "../prefs",
+ "../prefs:prefs_behavior",
+ "../prefs:prefs_types",
+ "//ui/webui/resources/js:cr",
+ "//ui/webui/resources/js:i18n_behavior",
+ ]
+}
+
+group("polymer3_elements") {
+ public_deps = [
+ "../controls:polymer3_elements",
+ "../prefs:polymer3_elements",
+ ":nearby_share_subpage_module",
+ ]
+}
+
+js_type_check("closure_compile_module") {
+ is_polymer3 = true
+ deps = [ ":nearby_share_subpage.m" ]
+}
+
+js_library("nearby_share_subpage.m") {
+ sources = [ "$root_gen_dir/chrome/browser/resources/settings/nearby_share_page/nearby_share_subpage.m.js" ]
+ deps = [
+ "../prefs:prefs.m",
+ "../prefs:prefs_behavior.m",
+ "../prefs:prefs_types.m",
+ "//ui/webui/resources/js:cr.m",
+ "//ui/webui/resources/js:i18n_behavior.m",
+ ]
+ extra_deps = [ ":nearby_share_subpage_module" ]
+}
+
+polymer_modulizer("nearby_share_subpage") {
+ js_file = "nearby_share_subpage.js"
+ html_file = "nearby_share_subpage.html"
+ html_type = "dom-module"
+ namespace_rewrites = settings_namespace_rewrites
+ auto_imports = settings_auto_imports
+}
diff --git a/chromium/chrome/browser/resources/settings/os_settings_resources.grd b/chromium/chrome/browser/resources/settings/os_settings_resources.grd
index cf80563c962..4e4138f4717 100644
--- a/chromium/chrome/browser/resources/settings/os_settings_resources.grd
+++ b/chromium/chrome/browser/resources/settings/os_settings_resources.grd
@@ -25,18 +25,10 @@
compress="false" type="BINDATA" />
<!-- App Management -->
- <include name="IDR_OS_SETTINGS_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS"
- file="${root_gen_dir}\skia\public\mojom\bitmap.mojom-lite.js"
- use_base_dir="false"
- compress="false" type="BINDATA" />
<include name="IDR_OS_SETTINGS_APP_MANAGEMENT_FILE_PATH_MOJO_LITE_JS"
file="${root_gen_dir}\mojo\public\mojom\base\file_path.mojom-lite.js"
use_base_dir="false"
compress="false" type="BINDATA" />
- <include name="IDR_OS_SETTINGS_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS"
- file="${root_gen_dir}\skia\public\mojom\image_info.mojom-lite.js"
- use_base_dir="false"
- compress="false" type="BINDATA" />
<include name="IDR_OS_SETTINGS_APP_MANAGEMENT_IMAGE_MOJO_LITE_JS"
file="${root_gen_dir}\ui\gfx\image\mojom\image.mojom-lite.js"
use_base_dir="false"
@@ -46,7 +38,7 @@
use_base_dir="false"
compress="false" type="BINDATA" />
<include name="IDR_OS_SETTINGS_APP_MANAGEMENT_TYPES_MOJO_LITE_JS"
- file="${root_gen_dir}\chrome\services\app_service\public\mojom\types.mojom-lite.js"
+ file="${root_gen_dir}\components\services\app_service\public\mojom\types.mojom-lite.js"
use_base_dir="false"
compress="false" type="BINDATA" />
@@ -77,18 +69,30 @@
<structure name="IDR_OS_SETTINGS_A11Y_PAGE_HTML"
file="chromeos/os_a11y_page/os_a11y_page.html"
compress="false" type="chrome_html" />
- <structure name="IDR_OS_SETTINGS_AMBIENT_MODE_PAGE_AMBIENT_MODE_PAGE_JS"
+ <structure name="IDR_OS_SETTINGS_AMBIENT_MODE_PAGE_JS"
file="chromeos/ambient_mode_page/ambient_mode_page.js"
compress="false" type="chrome_html" />
- <structure name="IDR_OS_SETTINGS_AMBIENT_MODE_PAGE_AMBIENT_MODE_PAGE_HTML"
+ <structure name="IDR_OS_SETTINGS_AMBIENT_MODE_PAGE_HTML"
file="chromeos/ambient_mode_page/ambient_mode_page.html"
compress="false" type="chrome_html" />
- <structure name="IDR_OS_SETTINGS_AMBIENT_MODE_PAGE_AMBIENT_MODE_BROWSER_PROXY_JS"
+ <structure name="IDR_OS_SETTINGS_AMBIENT_MODE_PHOTOS_PAGE_JS"
+ file="chromeos/ambient_mode_page/ambient_mode_photos_page.js"
+ compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_AMBIENT_MODE_PHOTOS_PAGE_HTML"
+ file="chromeos/ambient_mode_page/ambient_mode_photos_page.html"
+ compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_AMBIENT_MODE_PAGE_BROWSER_PROXY_JS"
file="chromeos/ambient_mode_page/ambient_mode_browser_proxy.js"
compress="false" type="chrome_html" />
- <structure name="IDR_OS_SETTINGS_AMBIENT_MODE_PAGE_AMBIENT_MODE_BROWSER_PROXY_HTML"
+ <structure name="IDR_OS_SETTINGS_AMBIENT_MODE_PAGE_BROWSER_PROXY_HTML"
file="chromeos/ambient_mode_page/ambient_mode_browser_proxy.html"
compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_AMBIENT_CONSTANTS_JS"
+ file="chromeos/ambient_mode_page/constants.js"
+ compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_AMBIENT_CONSTANTS_HTML"
+ file="chromeos/ambient_mode_page/constants.html"
+ compress="false" type="chrome_html" />
<structure name="IDR_OS_SETTINGS_APPS_PAGE_JS"
file="chromeos/os_apps_page/os_apps_page.js"
compress="false" type="chrome_html" />
@@ -248,6 +252,12 @@
<structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PLUGIN_VM_BROWSER_PROXY_HTML"
file="chromeos/os_apps_page/app_management_page/plugin_vm_page/plugin_vm_browser_proxy.html"
compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PLUGIN_VM_PERMISSION_DIALOG_JS"
+ file="chromeos/os_apps_page/app_management_page/plugin_vm_page/plugin_vm_permission_dialog.js"
+ compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_APP_MANAGEMENT_PLUGIN_VM_PERMISSION_DIALOG_HTML"
+ file="chromeos/os_apps_page/app_management_page/plugin_vm_page/plugin_vm_permission_dialog.html"
+ compress="false" type="chrome_html" />
<structure name="IDR_OS_SETTINGS_CAPTIONS_SUBPAGE_JS"
file="a11y_page/captions_subpage.js"
compress="false" type="chrome_html" />
@@ -349,6 +359,9 @@
file="lifetime_browser_proxy.js"
compress="false" type="chrome_html"
preprocess="true" />
+ <structure name="IDR_OS_SETTINGS_SEARCH_SETTINGS_HTML"
+ file="search_settings.html"
+ compress="false" type="chrome_html" />
<structure name="IDR_OS_SETTINGS_SEARCH_SETTINGS_JS"
file="search_settings.js"
compress="false" type="chrome_html" />
@@ -375,7 +388,8 @@
compress="false" type="chrome_html" />
<structure name="IDR_OS_SETTINGS_CR_SETTINGS_SUBPAGE_JS"
file="settings_page/settings_subpage.js"
- compress="false" type="chrome_html" />
+ compress="false" type="chrome_html"
+ preprocess="true" />
<structure name="IDR_OS_SETTINGS_CR_SETTINGS_PAGE_CSS_HTML"
file="settings_page_css.html"
compress="false" type="chrome_html" />
@@ -657,6 +671,18 @@
<structure name="IDR_OS_SETTINGS_LANGUAGES_MANAGE_INPUT_METHODS_PAGE_JS"
file="chromeos/os_languages_page/manage_input_methods_page.js"
compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_LANGUAGES_INPUT_METHOD_OPTIONS_PAGE_HTML"
+ file="chromeos/os_languages_page/input_method_options_page.html"
+ compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_LANGUAGES_INPUT_METHOD_OPTIONS_PAGE_JS"
+ file="chromeos/os_languages_page/input_method_options_page.js"
+ compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_LANGUAGES_INPUT_METHOD_UTIL_HTML"
+ file="chromeos/os_languages_page/input_method_util.html"
+ compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_LANGUAGES_INPUT_METHOD_UTIL_JS"
+ file="chromeos/os_languages_page/input_method_util.js"
+ compress="false" type="chrome_html" />
<structure name="IDR_OS_SETTINGS_LANGUAGES_SMART_INPUTS_PAGE_HTML"
file="chromeos/os_languages_page/smart_inputs_page.html"
compress="false" type="chrome_html" />
@@ -1095,6 +1121,12 @@
<structure name="IDR_OS_SETTINGS_DATE_TIME_TYPES_JS"
file="chromeos/date_time_page/date_time_types.js"
compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_TIMEZONE_BROWSER_PROXY_JS"
+ file="chromeos/date_time_page/timezone_browser_proxy.js"
+ compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_TIMEZONE_BROWSER_PROXY_HTML"
+ file="chromeos/date_time_page/timezone_browser_proxy.html"
+ compress="false" type="chrome_html" />
<structure name="IDR_OS_SETTINGS_TIMEZONE_SELECTOR_HTML"
file="chromeos/date_time_page/timezone_selector.html"
compress="false" type="chrome_html" />
@@ -1206,6 +1238,12 @@
<structure name="IDR_OS_SETTINGS_MULTIDEVICE_TETHER_ITEM_JS"
file="chromeos/multidevice_page/multidevice_tether_item.js"
compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_NEARBY_SHARE_SUBPAGE_HTML"
+ file="nearby_share_page/nearby_share_subpage.html"
+ compress="false" type="chrome_html" />
+ <structure name="IDR_OS_SETTINGS_NEARBY_SHARE_SUBPAGE_JS"
+ file="nearby_share_page/nearby_share_subpage.js"
+ compress="false" type="chrome_html" />
<structure name="IDR_OS_SETTINGS_NETWORK_PROXY_SECTION_HTML"
file="chromeos/internet_page/network_proxy_section.html"
compress="false" 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 88da13ccd00..a6e99635d9f 100644
--- a/chromium/chrome/browser/resources/settings/os_settings_resources_vulcanized.grd
+++ b/chromium/chrome/browser/resources/settings/os_settings_resources_vulcanized.grd
@@ -17,27 +17,23 @@
use_base_dir="false"
flattenhtml="true"
allowexternalscript="true"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OS_SETTINGS_CRISPER_JS"
file="${root_gen_dir}\chrome\browser\resources\settings\chromeos\crisper.js"
use_base_dir="false"
flattenhtml="true"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OS_SETTINGS_LAZY_LOAD_VULCANIZED_HTML"
file="${root_gen_dir}\chrome\browser\resources\settings\chromeos\lazy_load.vulcanized.html"
use_base_dir="false"
flattenhtml="true"
allowexternalscript="true"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OS_SETTINGS_LAZY_LOAD_CRISPER_JS"
file="${root_gen_dir}\chrome\browser\resources\settings\chromeos\lazy_load.crisper.js"
use_base_dir="false"
flattenhtml="true"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_OS_SETTINGS_MANIFEST"
file="os_settings_manifest.json"
type="BINDATA"
@@ -54,53 +50,46 @@
type="BINDATA" />
<!-- App Management -->
- <include name="IDR_OS_SETTINGS_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS"
- file="${root_gen_dir}\skia\public\mojom\bitmap.mojom-lite.js"
- compress="gzip"
- use_base_dir="false"
- type="BINDATA" />
<include name="IDR_OS_SETTINGS_APP_MANAGEMENT_FILE_PATH_MOJO_LITE_JS"
file="${root_gen_dir}\mojo\public\mojom\base\file_path.mojom-lite.js"
- compress="gzip"
- use_base_dir="false"
- type="BINDATA" />
- <include name="IDR_OS_SETTINGS_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS"
- file="${root_gen_dir}\skia\public\mojom\image_info.mojom-lite.js"
- compress="gzip"
use_base_dir="false"
type="BINDATA" />
<include name="IDR_OS_SETTINGS_APP_MANAGEMENT_IMAGE_MOJO_LITE_JS"
file="${root_gen_dir}\ui\gfx\image\mojom\image.mojom-lite.js"
- compress="gzip"
use_base_dir="false"
type="BINDATA" />
<include name="IDR_OS_SETTINGS_APP_MANAGEMENT_MOJO_LITE_JS"
file="${root_gen_dir}\chrome\browser\ui\webui\app_management\app_management.mojom-lite.js"
- compress="gzip"
use_base_dir="false"
type="BINDATA" />
<include name="IDR_OS_SETTINGS_APP_MANAGEMENT_TYPES_MOJO_LITE_JS"
- file="${root_gen_dir}\chrome\services\app_service\public\mojom\types.mojom-lite.js"
- compress="gzip"
+ file="${root_gen_dir}\components\services\app_service\public\mojom\types.mojom-lite.js"
use_base_dir="false"
type="BINDATA" />
<!-- Search -->
<include name="IDR_OS_SETTINGS_SEARCH_MOJOM_LITE_JS"
file="${root_gen_dir}\chrome\browser\ui\webui\settings\chromeos\search\search.mojom-lite.js"
- compress="gzip"
use_base_dir="false"
type="BINDATA" />
<include name="IDR_OS_SETTINGS_SEARCH_RESULT_ICON_MOJOM_LITE_JS"
file="${root_gen_dir}\chrome\browser\ui\webui\settings\chromeos\search\search_result_icon.mojom-lite.js"
- compress="gzip"
use_base_dir="false"
type="BINDATA" />
<include name="IDR_OS_SETTINGS_USER_ACTION_RECORDER_MOJOM_LITE_JS"
file="${root_gen_dir}\chrome\browser\ui\webui\settings\chromeos\search\user_action_recorder.mojom-lite.js"
- compress="gzip"
use_base_dir="false"
type="BINDATA" />
+
+ <!-- Polymer3 related files-->
+ <include name="IDR_OS_SETTINGS_SETTINGS_ROLLUP_JS"
+ file="${root_gen_dir}\chrome\browser\resources\settings\chromeos\os_settings.rollup.js"
+ use_base_dir="false"
+ preprocess="true"
+ type="BINDATA" />
+ <include name="IDR_OS_SETTINGS_OS_SETTINGS_V3_HTML"
+ file="chromeos/os_settings_v3.html"
+ type="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/settings/safety_check_page/BUILD.gn b/chromium/chrome/browser/resources/settings/safety_check_page/BUILD.gn
index bbe3b9a0e4d..bf337dd7635 100644
--- a/chromium/chrome/browser/resources/settings/safety_check_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/safety_check_page/BUILD.gn
@@ -12,11 +12,12 @@ js_type_check("closure_compile_module") {
deps = [
":safety_check_browser_proxy",
":safety_check_child",
- ":safety_check_extensions_element",
+ ":safety_check_chrome_cleaner_child",
+ ":safety_check_extensions_child",
":safety_check_page",
- ":safety_check_passwords_element",
- ":safety_check_safe_browsing_element",
- ":safety_check_updates_element",
+ ":safety_check_passwords_child",
+ ":safety_check_safe_browsing_child",
+ ":safety_check_updates_child",
]
}
@@ -32,7 +33,19 @@ js_library("safety_check_child") {
]
}
-js_library("safety_check_extensions_element") {
+js_library("safety_check_chrome_cleaner_child") {
+ deps = [
+ ":safety_check_child",
+ "..:metrics_browser_proxy",
+ "..:route",
+ "..:router.m",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/js:assert.m",
+ "//ui/webui/resources/js:web_ui_listener_behavior.m",
+ ]
+}
+
+js_library("safety_check_extensions_child") {
deps = [
":safety_check_child",
"..:metrics_browser_proxy",
@@ -46,10 +59,11 @@ js_library("safety_check_extensions_element") {
js_library("safety_check_page") {
deps = [
":safety_check_browser_proxy",
- ":safety_check_extensions_element",
- ":safety_check_passwords_element",
- ":safety_check_safe_browsing_element",
- ":safety_check_updates_element",
+ ":safety_check_chrome_cleaner_child",
+ ":safety_check_extensions_child",
+ ":safety_check_passwords_child",
+ ":safety_check_safe_browsing_child",
+ ":safety_check_updates_child",
"..:hats_browser_proxy",
"..:metrics_browser_proxy",
"../autofill_page:password_manager_proxy",
@@ -62,7 +76,7 @@ js_library("safety_check_page") {
]
}
-js_library("safety_check_passwords_element") {
+js_library("safety_check_passwords_child") {
deps = [
":safety_check_child",
"..:metrics_browser_proxy",
@@ -75,7 +89,7 @@ js_library("safety_check_passwords_element") {
]
}
-js_library("safety_check_safe_browsing_element") {
+js_library("safety_check_safe_browsing_child") {
deps = [
":safety_check_child",
"..:metrics_browser_proxy",
@@ -88,7 +102,7 @@ js_library("safety_check_safe_browsing_element") {
]
}
-js_library("safety_check_updates_element") {
+js_library("safety_check_updates_child") {
deps = [
":safety_check_child",
"..:lifetime_browser_proxy.m",
@@ -102,10 +116,11 @@ js_library("safety_check_updates_element") {
html_to_js("web_components") {
js_files = [
"safety_check_child.js",
- "safety_check_extensions_element.js",
+ "safety_check_chrome_cleaner_child.js",
+ "safety_check_extensions_child.js",
"safety_check_page.js",
- "safety_check_passwords_element.js",
- "safety_check_safe_browsing_element.js",
- "safety_check_updates_element.js",
+ "safety_check_passwords_child.js",
+ "safety_check_safe_browsing_child.js",
+ "safety_check_updates_child.js",
]
}
diff --git a/chromium/chrome/browser/resources/settings/settings.gni b/chromium/chrome/browser/resources/settings/settings.gni
index 48e79e57b99..0c82dda4fd4 100644
--- a/chromium/chrome/browser/resources/settings/settings.gni
+++ b/chromium/chrome/browser/resources/settings/settings.gni
@@ -14,7 +14,6 @@ settings_namespace_rewrites = [
"settings.AccountManagerBrowserProxy|AccountManagerBrowserProxy",
"settings.Account|Account",
"settings.ALL_SITES_DIALOG|ALL_SITES_DIALOG",
- "settings.AllSitesAction|AllSitesAction",
"settings.AllSitesAction2|AllSitesAction2",
"settings.AndroidInfoBrowserProxy|AndroidInfoBrowserProxy",
"settings.AndroidSmsInfo|AndroidSmsInfo",
@@ -97,6 +96,7 @@ settings_namespace_rewrites = [
"settings.MetricsReporting|MetricsReporting",
"settings.SafetyCheckBrowserProxy|SafetyCheckBrowserProxy",
"settings.SafetyCheckCallbackConstants|SafetyCheckCallbackConstants",
+ "settings.SafetyCheckChromeCleanerStatus|SafetyCheckChromeCleanerStatus",
"settings.SafetyCheckExtensionsStatus|SafetyCheckExtensionsStatus",
"settings.SafetyCheckIconStatus|SafetyCheckIconStatus",
"settings.SafetyCheckParentStatus|SafetyCheckParentStatus",
diff --git a/chromium/chrome/browser/resources/settings/settings_page/BUILD.gn b/chromium/chrome/browser/resources/settings/settings_page/BUILD.gn
index fda50ecb1e5..c7432bfa778 100644
--- a/chromium/chrome/browser/resources/settings/settings_page/BUILD.gn
+++ b/chromium/chrome/browser/resources/settings/settings_page/BUILD.gn
@@ -46,7 +46,9 @@ js_library("settings_subpage") {
"//ui/webui/resources/cr_elements/cr_search_field:cr_search_field",
"//ui/webui/resources/js:assert",
"//ui/webui/resources/js:find_shortcut_behavior",
+ "//ui/webui/resources/js:i18n_behavior",
"//ui/webui/resources/js:load_time_data",
+ "//ui/webui/resources/js:util",
"//ui/webui/resources/js/cr/ui:focus_without_ink",
]
}
@@ -102,7 +104,9 @@ js_library("settings_subpage.m") {
"//ui/webui/resources/cr_elements/cr_search_field:cr_search_field.m",
"//ui/webui/resources/js:assert.m",
"//ui/webui/resources/js:find_shortcut_behavior.m",
+ "//ui/webui/resources/js:i18n_behavior.m",
"//ui/webui/resources/js:load_time_data.m",
+ "//ui/webui/resources/js:util.m",
"//ui/webui/resources/js/cr/ui:focus_without_ink.m",
]
extra_deps = [ ":settings_subpage_module" ]
@@ -150,6 +154,7 @@ polymer_modulizer("settings_subpage") {
"third_party/polymer/v1_0/components-chromium/iron-resizable-behavior/iron-resizable-behavior.html|IronResizableBehavior",
"ui/webui/resources/html/assert.html|assert",
"ui/webui/resources/html/polymer.html|html, Polymer, afterNextRender",
+ "ui/webui/resources/html/util.html|listenOnce",
]
namespace_rewrites = settings_namespace_rewrites +
[ "Polymer.IronResizableBehavior|IronResizableBehavior" ]
diff --git a/chromium/chrome/browser/resources/settings/settings_resources_v3.grdp b/chromium/chrome/browser/resources/settings/settings_resources_v3.grdp
index 4953d88930c..72c22ccadf5 100644
--- a/chromium/chrome/browser/resources/settings/settings_resources_v3.grdp
+++ b/chromium/chrome/browser/resources/settings/settings_resources_v3.grdp
@@ -86,10 +86,23 @@
file="autofill_page/blocking_request_manager.js"
compress="false" type="BINDATA" />
</if>
- <include name="IDR_SETTINGS_AUTOFILL_PAGE_SHOW_PASSWORD_BEHAVIOR_JS"
- file="autofill_page/show_password_behavior.js"
+ <include name="IDR_SETTINGS_AUTOFILL_PAGE_MERGE_EXCEPTIONS_STORE_COPIES_BEHAVIOR_JS"
+ file="autofill_page/merge_exceptions_store_copies_behavior.js"
+ compress="false" type="BINDATA"
+ preprocess="true" />
+ <include name="IDR_SETTINGS_AUTOFILL_PAGE_MERGE_PASSWORDS_STORE_COPIES_BEHAVIOR_JS"
+ file="autofill_page/merge_passwords_store_copies_behavior.js"
compress="false" type="BINDATA"
preprocess="true" />
+ <include name="IDR_SETTINGS_AUTOFILL_PAGE_MULTI_STORE_EXCEPTION_ENTRY_JS"
+ file="autofill_page/multi_store_exception_entry.js"
+ compress="false" type="BINDATA" />
+ <include name="IDR_SETTINGS_AUTOFILL_PAGE_MULTI_STORE_ID_HANDLER_JS"
+ file="autofill_page/multi_store_id_handler.js"
+ compress="false" type="BINDATA" />
+ <include name="IDR_SETTINGS_AUTOFILL_PAGE_MULTI_STORE_PASSWORD_UI_ENTRY_JS"
+ file="autofill_page/multi_store_password_ui_entry.js"
+ compress="false" type="BINDATA" />
<include name="IDR_SETTINGS_AUTOFILL_PAGE_PASSWORD_CHECK_JS"
file="${root_gen_dir}/chrome/browser/resources/settings/autofill_page/password_check.js"
use_base_dir="false"
@@ -115,6 +128,11 @@
file="${root_gen_dir}/chrome/browser/resources/settings/autofill_page/password_list_item.js"
use_base_dir="false"
compress="false" type="BINDATA" />
+ <include name="IDR_SETTINGS_AUTOFILL_PAGE_PASSWORDS_LIST_HANDLER_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/autofill_page/passwords_list_handler.js"
+ use_base_dir="false"
+ compress="false" type="BINDATA"
+ preprocess="true"/>
<include name="IDR_SETTINGS_AUTOFILL_PAGE_PASSWORD_MANAGER_PROXY_JS"
file="autofill_page/password_manager_proxy.js"
compress="false" type="BINDATA" />
@@ -127,11 +145,26 @@
use_base_dir="false"
compress="false" type="BINDATA"
preprocess="true" />
+ <include name="IDR_SETTINGS_AUTOFILL_PAGE_PASSWORDS_DEVICE_SECTION_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/autofill_page/passwords_device_section.js"
+ use_base_dir="false"
+ compress="false" type="BINDATA"
+ preprocess="true" />
<include name="IDR_SETTINGS_AUTOFILL_PAGE_PASSWORD_EDIT_DIALOG_JS"
file="${root_gen_dir}/chrome/browser/resources/settings/autofill_page/password_edit_dialog.js"
use_base_dir="false"
compress="false" type="BINDATA"
preprocess="true" />
+ <include name="IDR_SETTINGS_AUTOFILL_PAGE_PASSWORD_MOVE_TO_ACCOUNT_DIALOG_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/autofill_page/password_move_to_account_dialog.js"
+ use_base_dir="false"
+ compress="false" type="BINDATA"
+ preprocess="true" />
+ <include name="IDR_SETTINGS_AUTOFILL_PAGE_PASSWORD_REMOVE_DIALOG_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/autofill_page/password_remove_dialog.js"
+ use_base_dir="false"
+ compress="false" type="BINDATA"
+ preprocess="true" />
<include name="IDR_SETTINGS_AUTOFILL_PAGE_PASSWORDS_EXPORT_DIALOG_JS"
file="${root_gen_dir}/chrome/browser/resources/settings/autofill_page/passwords_export_dialog.js"
use_base_dir="false"
@@ -141,6 +174,10 @@
file="${root_gen_dir}/chrome/browser/resources/settings/autofill_page/payments_section.js"
use_base_dir="false"
compress="false" type="BINDATA" />
+ <include name="IDR_SETTINGS_AUTOFILL_PAGE_SHOW_PASSWORD_BEHAVIOR_JS"
+ file="autofill_page/show_password_behavior.js"
+ compress="false" type="BINDATA"
+ preprocess="true" />
<include name="IDR_SETTINGS_BASIC_PAGE_BASIC_PAGE_JS"
file="${root_gen_dir}/chrome/browser/resources/settings/basic_page/basic_page.js"
use_base_dir="false"
@@ -412,9 +449,6 @@
use_base_dir="false"
preprocess="true"
compress="false" type="BINDATA" />
- <include name="IDR_SETTINGS_PLURAL_STRING_PROXY_JS"
- file="plural_string_proxy.js"
- compress="false" type="BINDATA" />
<include name="IDR_SETTINGS_PREFS_PREFS_M_JS"
file="${root_gen_dir}/chrome/browser/resources/settings/prefs/prefs.m.js"
use_base_dir="false"
@@ -551,24 +585,28 @@
file="${root_gen_dir}/chrome/browser/resources/settings/safety_check_page/safety_check_child.js"
use_base_dir="false"
compress="false" type="BINDATA" />
- <include name="IDR_SETTINGS_SAFETY_CHECK_PAGE_SAFETY_CHECK_EXTENSIONS_ELEMENT_JS"
- file="${root_gen_dir}/chrome/browser/resources/settings/safety_check_page/safety_check_extensions_element.js"
+ <include name="IDR_SETTINGS_SAFETY_CHECK_PAGE_SAFETY_CHECK_CHROME_CLEANER_CHILD_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/safety_check_page/safety_check_chrome_cleaner_child.js"
+ use_base_dir="false"
+ compress="false" type="BINDATA" />
+ <include name="IDR_SETTINGS_SAFETY_CHECK_PAGE_SAFETY_CHECK_EXTENSIONS_CHILD_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/safety_check_page/safety_check_extensions_child.js"
use_base_dir="false"
compress="false" type="BINDATA" />
<include name="IDR_SETTINGS_SAFETY_CHECK_PAGE_SAFETY_CHECK_PAGE_JS"
file="${root_gen_dir}/chrome/browser/resources/settings/safety_check_page/safety_check_page.js"
use_base_dir="false"
compress="false" type="BINDATA" />
- <include name="IDR_SETTINGS_SAFETY_CHECK_PAGE_SAFETY_CHECK_PASSWORDS_ELEMENT_JS"
- file="${root_gen_dir}/chrome/browser/resources/settings/safety_check_page/safety_check_passwords_element.js"
+ <include name="IDR_SETTINGS_SAFETY_CHECK_PAGE_SAFETY_CHECK_PASSWORDS_CHILD_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/safety_check_page/safety_check_passwords_child.js"
use_base_dir="false"
compress="false" type="BINDATA" />
- <include name="IDR_SETTINGS_SAFETY_CHECK_PAGE_SAFETY_CHECK_SAFE_BROWSING_ELEMENT_JS"
- file="${root_gen_dir}/chrome/browser/resources/settings/safety_check_page/safety_check_safe_browsing_element.js"
+ <include name="IDR_SETTINGS_SAFETY_CHECK_PAGE_SAFETY_CHECK_SAFE_BROWSING_CHILD_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/safety_check_page/safety_check_safe_browsing_child.js"
use_base_dir="false"
compress="false" type="BINDATA" />
- <include name="IDR_SETTINGS_SAFETY_CHECK_PAGE_SAFETY_CHECK_UPDATES_ELEMENT_JS"
- file="${root_gen_dir}/chrome/browser/resources/settings/safety_check_page/safety_check_updates_element.js"
+ <include name="IDR_SETTINGS_SAFETY_CHECK_PAGE_SAFETY_CHECK_UPDATES_CHILD_JS"
+ file="${root_gen_dir}/chrome/browser/resources/settings/safety_check_page/safety_check_updates_child.js"
use_base_dir="false"
compress="false" type="BINDATA" />
<include name="IDR_SETTINGS_SEARCH_ENGINES_BROWSER_PROXY_M_JS"
@@ -627,7 +665,8 @@
<include name="IDR_SETTINGS_SETTINGS_PAGE_SETTINGS_SUBPAGE_M_JS"
file="${root_gen_dir}/chrome/browser/resources/settings/settings_page/settings_subpage.m.js"
use_base_dir="false"
- compress="false" type="BINDATA" />
+ compress="false" type="BINDATA"
+ preprocess="true" />
<include name="IDR_SETTINGS_SETTINGS_UI_SETTINGS_UI_JS"
file="${root_gen_dir}/chrome/browser/resources/settings/settings_ui/settings_ui.js"
use_base_dir="false"
diff --git a/chromium/chrome/browser/resources/settings/settings_resources_vulcanized.grd b/chromium/chrome/browser/resources/settings/settings_resources_vulcanized.grd
index 51e23355bdf..aa1881dbc5d 100644
--- a/chromium/chrome/browser/resources/settings/settings_resources_vulcanized.grd
+++ b/chromium/chrome/browser/resources/settings/settings_resources_vulcanized.grd
@@ -14,74 +14,58 @@
<includes>
<include name="IDR_SETTINGS_IMAGES_COOKIES_BANNER_SVG"
file="images/cookies_banner.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_IMAGES_COOKIES_BANNER_DARK_SVG"
file="images/cookies_banner_dark.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_IMAGES_PERMISSIONS_BANNER_SVG"
file="images/permissions_banner.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_IMAGES_PERMISSIONS_BANNER_DARK_SVG"
file="images/permissions_banner_dark.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_IMAGES_SAFE_BROWSING_BANNER_SVG"
file="images/safe_browsing_banner.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_IMAGES_SAFE_BROWSING_BANNER_DARK_SVG"
file="images/safe_browsing_banner_dark.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_IMAGES_SYNC_BANNER_SVG"
file="images/sync_banner.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_IMAGES_SYNC_BANNER_DARK_SVG"
file="images/sync_banner_dark.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_IMAGES_PASSWORD_CHECK_NEUTRAL_SVG"
file="images/password_check_neutral.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_IMAGES_PASSWORD_CHECK_NEUTRAL_DARK_SVG"
file="images/password_check_neutral_dark.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_IMAGES_PASSWORD_CHECK_POSITIVE_SVG"
file="images/password_check_positive.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_IMAGES_PASSWORD_CHECK_POSITIVE_DARK_SVG"
file="images/password_check_positive_dark.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<!-- Polymer 3 related files -->
<include name="IDR_SETTINGS_SETTINGS_V3_HTML"
file="settings_v3.html"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_SETTINGS_SETTINGS_ROLLUP_JS"
file="${root_gen_dir}\chrome\browser\resources\settings\settings.rollup.js"
use_base_dir="false"
preprocess="true"
- compress="gzip"
type="BINDATA" />
<include name="IDR_SETTINGS_LAZY_LOAD_ROLLUP_JS"
file="${root_gen_dir}\chrome\browser\resources\settings\lazy_load.rollup.js"
preprocess="true"
type="BINDATA"
- compress="gzip"
use_base_dir="false" />
<include name="IDR_SETTINGS_SHARED_ROLLUP_JS"
file="${root_gen_dir}\chrome\browser\resources\settings\shared.rollup.js"
preprocess="true"
type="BINDATA"
- compress="gzip"
use_base_dir="false" />
</includes>
</release>
diff --git a/chromium/chrome/browser/resources/signin/BUILD.gn b/chromium/chrome/browser/resources/signin/BUILD.gn
index 8f8022c8193..f3e1f7e8491 100644
--- a/chromium/chrome/browser/resources/signin/BUILD.gn
+++ b/chromium/chrome/browser/resources/signin/BUILD.gn
@@ -8,8 +8,10 @@ group("closure_compile") {
deps = [ "sync_confirmation:closure_compile" ]
if (!is_chromeos) {
deps += [
+ "profile_picker:closure_compile",
"signin_email_confirmation:closure_compile",
"signin_error:closure_compile",
+ "signin_reauth:closure_compile",
]
}
}
@@ -23,6 +25,7 @@ group("web_components") {
public_deps += [
"signin_email_confirmation:web_components",
"signin_error:web_components",
+ "signin_reauth:web_components",
]
}
}
diff --git a/chromium/chrome/browser/resources/signin/profile_picker/BUILD.gn b/chromium/chrome/browser/resources/signin/profile_picker/BUILD.gn
new file mode 100644
index 00000000000..e27205ad0b0
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/profile_picker/BUILD.gn
@@ -0,0 +1,36 @@
+# Copyright 2020 The Chromium 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")
+import("//tools/polymer/html_to_js.gni")
+
+js_type_check("closure_compile") {
+ is_polymer3 = true
+ deps = [
+ ":profile_picker_app",
+ ":profile_picker_main_view",
+ ]
+}
+
+js_library("profile_picker_main_view") {
+ deps = [
+ "//third_party/polymer/v3_0/components-chromium/iron-icon",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/cr_elements/cr_icon_button:cr_icon_button.m",
+ ]
+}
+
+js_library("profile_picker_app") {
+ deps = [
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/cr_elements/cr_view_manager:cr_view_manager.m",
+ ]
+}
+
+html_to_js("web_components") {
+ js_files = [
+ "profile_picker_app.js",
+ "profile_picker_main_view.js",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/signin/profile_picker/icons.js b/chromium/chrome/browser/resources/signin/profile_picker/icons.js
new file mode 100644
index 00000000000..81d509c0c86
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/profile_picker/icons.js
@@ -0,0 +1,15 @@
+import 'chrome://resources/polymer/v3_0/iron-iconset-svg/iron-iconset-svg.js';
+
+const element = document.createElement('iron-iconset-svg');
+element.name = 'profiles';
+element.size = 74;
+element.innerHTML = `
+<svg>
+ <defs>
+ <g id="add" viewBox="0 0 74 74">
+ <circle cx="37" cy="37" r="37" stroke="none"/>
+ <path d="M36.9999 46.4349C36.1315 46.4349 35.4274 45.7309 35.4274 44.8624V38.5724H29.1374C28.269 38.5724 27.5649 37.8684 27.5649 36.9999C27.5649 36.1315 28.269 35.4274 29.1374 35.4274H35.4274V29.1374C35.4274 28.269 36.1315 27.5649 36.9999 27.5649C37.8684 27.5649 38.5724 28.269 38.5724 29.1374V35.4274H44.8624C45.7309 35.4274 46.4349 36.1315 46.4349 36.9999C46.4349 37.8684 45.7309 38.5724 44.8624 38.5724H38.5724V44.8624C38.5724 45.7309 37.8684 46.4349 36.9999 46.4349Z" fill="var(--iron-icon-stroke-color)"/>
+ </g>
+ </defs>
+</svg>`;
+document.head.appendChild(element);
diff --git a/chromium/chrome/browser/resources/signin/profile_picker/profile_picker.html b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker.html
index 8ddf6a371f0..ce6fe52046e 100644
--- a/chromium/chrome/browser/resources/signin/profile_picker/profile_picker.html
+++ b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker.html
@@ -2,7 +2,18 @@
<html dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
<meta charset="utf-8">
+ <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>
+ <profile-picker-app></profile-picker-app>
+ <script type="module" src="profile_picker_app.js"></script>
</body>
</html>
diff --git a/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_app.html b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_app.html
new file mode 100644
index 00000000000..e227ef80fef
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_app.html
@@ -0,0 +1,12 @@
+<style>
+ cr-view-manager {
+ display: flex;
+ font-size: 100%;
+ margin: 0;
+ min-height: 100vh;
+ }
+</style>
+<cr-view-manager>
+ <profile-picker-main-view slot="view" class="active">
+ </profile-picker-main-view>
+</cr-view-manager>
diff --git a/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_app.js b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_app.js
new file mode 100644
index 00000000000..83e6c76fbd6
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_app.js
@@ -0,0 +1,14 @@
+// Copyright 2020 The Chromium 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 'chrome://resources/cr_elements/cr_view_manager/cr_view_manager.m.js';
+import './profile_picker_main_view.js';
+
+import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+Polymer({
+ is: 'profile-picker-app',
+
+ _template: html`{__html_template__}`,
+});
diff --git a/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.html b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.html
new file mode 100644
index 00000000000..5700543c6d2
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.html
@@ -0,0 +1,54 @@
+<style>
+ .profiles-container {
+ --grid-gutter: 12px;
+ --max-columns: 4;
+ --profile-item-height:178px;
+ --profile-item-width: 162px;
+ align-items: center;
+ display: grid;
+ height: 80%;
+ grid-column-gap: var(--grid-gutter);
+ grid-row-gap: var(--grid-gutter);
+ grid-template-columns: repeat(auto-fit, var(--profile-item-width));
+ justify-content: center;
+ margin: auto;
+ max-width: calc(var(--profile-item-width) * var(--max-columns) +
+ var(--grid-gutter) * var(--max-columns));
+ }
+
+.profile-item {
+ align-items: center;
+ display: flex;
+ flex-direction: column;
+ height: var(--profile-item-height);
+ justify-content: center;
+ width: var(--profile-item-width);
+ }
+
+ #addProfile {
+ border: 1px dashed;
+ border-color: var(--google-grey-400);
+ border-radius: 12px;
+ }
+
+ cr-icon-button[iron-icon='profiles:add'] {
+ --cr-icon-button-icon-size: 74px;
+ --cr-icon-button-size: 84px;
+ --cr-icon-button-fill-color: var(--google-grey-refresh-100);
+ --cr-icon-button-margin-end: 0px;
+ --cr-icon-button-margin-start: 0px;
+ --cr-icon-button-stroke-color: var(--google-grey-refresh-700);
+ }
+
+@media (prefers-color-scheme: dark) {
+ /* TODO(msalama): Dark mode mocks not ready yet.*/
+}
+</style>
+<div class="profiles-container">
+ <div id="addProfile" class="profile-item">
+ <!-- TODO(msalama): Add title, aria-label once strings are ready-->
+ <cr-icon-button iron-icon="profiles:add"
+ on-click="onAddProfileClick_">
+ </cr-icon-button>
+ </div>
+</div>
diff --git a/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.js b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.js
new file mode 100644
index 00000000000..bde47adde55
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.js
@@ -0,0 +1,20 @@
+// Copyright 2020 The Chromium 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 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
+import 'chrome://resources/cr_elements/shared_vars_css.m.js';
+import './icons.js';
+
+import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+Polymer({
+ is: 'profile-picker-main-view',
+
+ _template: html`{__html_template__}`,
+
+ /** @private */
+ onAddProfileClick_() {
+ // TODO(msalama): do something.
+ },
+});
diff --git a/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_resources.grd b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_resources.grd
index d77a8a27541..244cc063482 100644
--- a/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_resources.grd
+++ b/chromium/chrome/browser/resources/signin/profile_picker/profile_picker_resources.grd
@@ -11,12 +11,26 @@
<output filename="profile_picker_resources.pak" type="data_package" />
</outputs>
<release seq="1">
+ <includes>
+ <!-- Generated Polymer 3 elements -->
+ <include name="IDR_PROFILE_PICKER_PROFILE_PICKER_MAIN_VIEW_JS"
+ file="${root_gen_dir}/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.js"
+ use_base_dir="false" type="BINDATA" preprocess="true"/>
+ <include name="IDR_PROFILE_PICKER_PROFILE_PICKER_APP_JS"
+ file="${root_gen_dir}/chrome/browser/resources/signin/profile_picker/profile_picker_app.js"
+ use_base_dir="false" type="BINDATA" preprocess="true"/>
+ </includes>
<structures>
<structure
name="IDR_PROFILE_PICKER_PROFILE_PICKER_HTML"
file="profile_picker.html"
type="chrome_html"
compress="false"/>
+ <structure
+ name="IDR_PROFILE_PICKER_ICONS_JS"
+ file="icons.js"
+ type="chrome_html"
+ compress="false"/>
</structures>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation_app.html b/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation_app.html
index b5d7e465d99..7e5090fa00e 100644
--- a/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation_app.html
+++ b/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation_app.html
@@ -37,17 +37,6 @@
color: var(--cr-primary-text-color);
}
}
-
- #closeButton {
- margin-inline-start: 8px;
- }
-
-<if expr="is_macosx or is_linux">
- #closeButton {
- margin-inline-end: 8px;
- margin-inline-start: 0;
- }
-</if>
</style>
<div class="container">
<div class="top-title-bar" id='dialogTitle'>
@@ -75,7 +64,7 @@
</div>
<div class="action-container">
<cr-button class="action-button" id="confirmButton"
- on-click="onConfirm_">
+ on-click="onConfirm_" autofocus>
$i18n{signinEmailConfirmationConfirmLabel}
</cr-button>
<cr-button id="closeButton" on-click="onCancel_">
diff --git a/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation_app.js b/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation_app.js
index f9756526a7f..5e3408f9426 100644
--- a/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation_app.js
+++ b/chromium/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation_app.js
@@ -10,7 +10,6 @@ import './signin_shared_css.js';
import './strings.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
-import {getDeepActiveElement} from 'chrome://resources/js/util.m.js';
import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
Polymer({
@@ -30,19 +29,6 @@ Polymer({
'signinEmailConfirmationCreateProfileButtonSubtitle', newEmail);
this.$.startSyncRadioButtonSubtitle.textContent = loadTimeData.getStringF(
'signinEmailConfirmationStartSyncButtonSubtitle', newEmail);
-
- document.addEventListener('keydown', this.onKeyDown_.bind(this));
- },
-
- 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".
- if (e.key == 'Enter' &&
- !/^(A|CR-BUTTON)$/.test(getDeepActiveElement().tagName)) {
- this.$.confirmButton.click();
- e.preventDefault();
- }
},
/** @private */
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 fd8fd98f9e4..779b871ae88 100644
--- a/chromium/chrome/browser/resources/signin/signin_error/signin_error.js
+++ b/chromium/chrome/browser/resources/signin/signin_error/signin_error.js
@@ -2,19 +2,11 @@
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
-import {addWebUIListener} from 'chrome://resources/js/cr.m.js';
-
function initialize() {
- addWebUIListener('clear-focus', clearFocus);
-
// 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();
-}
-
document.addEventListener('DOMContentLoaded', initialize);
diff --git a/chromium/chrome/browser/resources/signin/signin_error/signin_error_app.html b/chromium/chrome/browser/resources/signin/signin_error/signin_error_app.html
index 8e5db6f273d..9b32f228187 100644
--- a/chromium/chrome/browser/resources/signin/signin_error/signin_error_app.html
+++ b/chromium/chrome/browser/resources/signin/signin_error/signin_error_app.html
@@ -10,10 +10,6 @@
margin-bottom: 0;
}
- #closeButton {
- margin-inline-start: 8px;
- }
-
#profile-blocking-error-message {
margin-top: 30px;
}
@@ -31,13 +27,6 @@
margin-inline-end: 16px;
width: var(--cr-icon-size);
}
-
-<if expr="is_macosx or is_linux">
- #closeButton {
- margin-inline-end: 8px;
- margin-inline-start: 0;
- }
-</if>
</style>
<div class="container">
<div class="top-title-bar">$i18n{signinErrorTitle}</div>
@@ -70,9 +59,8 @@
on-click="onSwitchToExistingProfile_">
$i18n{signinErrorSwitchLabel}
</cr-button>
- <cr-button id="closeButton"
- hidden="[[switchButtonUnavailable_]]"
- on-click="onConfirm_">
+ <cr-button id="closeButton" hidden="[[switchButtonUnavailable_]]"
+ on-click="onConfirm_" autofocus>
$i18n{signinErrorCloseLabel}
</cr-button>
<cr-button id="confirmButton" hidden="[[!switchButtonUnavailable_]]"
diff --git a/chromium/chrome/browser/resources/signin/signin_error/signin_error_app.js b/chromium/chrome/browser/resources/signin/signin_error/signin_error_app.js
index 5ed8b298b33..592338a6c56 100644
--- a/chromium/chrome/browser/resources/signin/signin_error/signin_error_app.js
+++ b/chromium/chrome/browser/resources/signin/signin_error/signin_error_app.js
@@ -65,25 +65,15 @@ Polymer({
},
},
- /** @private {?function(!Event)} */
- boundKeyDownHandler_: null,
-
/** @override */
attached() {
- this.boundKeyDownHandler_ = this.onKeyDown_.bind(this);
- document.addEventListener('keydown', this.boundKeyDownHandler_);
-
this.addWebUIListener('switch-button-unavailable', () => {
this.switchButtonUnavailable_ = true;
+ // Move focus to the only displayed button in this case.
+ this.$$('#confirmButton').focus();
});
},
- /** @override */
- detached() {
- document.removeEventListener('keydown', this.boundKeyDownHandler_);
- this.boundKeyDownHandler_ = null;
- },
-
/** @private */
onConfirm_() {
chrome.send('confirm');
@@ -98,16 +88,4 @@ Polymer({
onLearnMore_() {
chrome.send('learnMore');
},
-
- /**
- * @param {!Event} e
- * @private
- */
- onKeyDown_(e) {
- if (e.key == 'Enter' &&
- !/^(A|CR-BUTTON)$/.test(e.composedPath()[0].tagName)) {
- this.onConfirm_();
- e.preventDefault();
- }
- },
});
diff --git a/chromium/chrome/browser/resources/signin/signin_reauth/BUILD.gn b/chromium/chrome/browser/resources/signin/signin_reauth/BUILD.gn
new file mode 100644
index 00000000000..5b8112b7bec
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/signin_reauth/BUILD.gn
@@ -0,0 +1,33 @@
+# Copyright 2020 The Chromium 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")
+import("//tools/polymer/html_to_js.gni")
+
+js_type_check("closure_compile") {
+ is_polymer3 = true
+ deps = [
+ ":signin_reauth_app",
+ ":signin_reauth_browser_proxy",
+ ]
+}
+
+js_library("signin_reauth_app") {
+ deps = [
+ ":signin_reauth_browser_proxy",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ "//ui/webui/resources/js:i18n_behavior.m",
+ "//ui/webui/resources/js:load_time_data.m",
+ "//ui/webui/resources/js:web_ui_listener_behavior.m",
+ ]
+}
+
+js_library("signin_reauth_browser_proxy") {
+ deps = [ "//ui/webui/resources/js:cr.m" ]
+ externs_list = [ "$externs_path/chrome_send.js" ]
+}
+
+html_to_js("web_components") {
+ js_files = [ "signin_reauth_app.js" ]
+}
diff --git a/chromium/chrome/browser/resources/signin/signin_reauth/images/account_passwords_reauth_illustration.svg b/chromium/chrome/browser/resources/signin/signin_reauth/images/account_passwords_reauth_illustration.svg
new file mode 100644
index 00000000000..ec0caee138d
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/signin_reauth/images/account_passwords_reauth_illustration.svg
@@ -0,0 +1 @@
+<svg width="540" height="170" viewBox="0 0 540 170" fill="none" xmlns="http://www.w3.org/2000/svg"><path opacity=".04" d="M281.956 123.563c14.58 0 26.399-.944 26.399-2.108 0-1.164-11.819-2.108-26.399-2.108s-26.399.944-26.399 2.108c0 1.164 11.819 2.108 26.399 2.108zm-136.22 4.217c14.58 0 26.399-.944 26.399-2.109 0-1.164-11.819-2.108-26.399-2.108s-26.399.944-26.399 2.108c0 1.165 11.819 2.109 26.399 2.109zm144.668 13.171v4.749h45.406v-9.487l-45.406 4.738z" fill="#202124"/><path d="M278.788 116.184V54.572c0-2.65 2.123-4.797 4.741-4.797h6.875v66.409h-11.616z" fill="#F8F9FA"/><path fill-rule="evenodd" clip-rule="evenodd" d="M283.512 48.721h7.948v68.518h-13.728V54.493a5.776 5.776 0 0 1 5.78-5.772zm6.021 66.594v-64.67h-6.021a3.85 3.85 0 0 0-3.853 3.848v60.822h9.874z" fill="#E8EAED"/><path d="M284.068 116.184V54.572a4.792 4.792 0 0 1 4.788-4.797h74.901a4.792 4.792 0 0 1 4.788 4.797v61.612h-84.477z" fill="#fff"/><path fill-rule="evenodd" clip-rule="evenodd" d="M288.771 48.721h75.072c3.18 0 5.758 2.584 5.758 5.772v62.746h-86.589V54.493c0-3.188 2.578-5.772 5.759-5.772zm78.911 5.772a3.843 3.843 0 0 0-3.839-3.848H288.77a3.843 3.843 0 0 0-3.839 3.848v60.822h82.751V54.493z" fill="#E8EAED"/><path d="M283.549 123.563c-2.63 0-4.761-2.205-4.761-4.926v-2.453h59.134v7.379h-54.373z" fill="#F8F9FA"/><path fill-rule="evenodd" clip-rule="evenodd" d="M277.732 115.13h61.246v9.487h-55.514c-3.166 0-5.732-2.685-5.732-5.998v-3.489zm59.336 7.488v-5.488h-57.425v1.489c0 2.209 1.711 3.999 3.821 3.999h53.604z" fill="#E8EAED"/><path d="M336.363 123.563c-2.638 0-4.777-2.205-4.777-4.926v-2.453h86.59v2.453c0 2.721-2.139 4.926-4.777 4.926h-77.036z" fill="#fff"/><path fill-rule="evenodd" clip-rule="evenodd" d="M330.53 115.13h88.702v3.489c0 3.313-2.574 5.998-5.748 5.998h-77.206c-3.174 0-5.748-2.685-5.748-5.998v-3.489zm86.786 3.489v-1.489h-84.87v1.489c0 2.209 1.716 3.999 3.832 3.999h77.206c2.116 0 3.832-1.79 3.832-3.999z" fill="#E8EAED"/><path d="M382.925 119.347h-16.088c-.949 0-1.859-.343-2.529-.952-.67-.61-1.045-1.436-1.043-2.297v-.968h23.232v.95c.007.864-.366 1.695-1.036 2.308-.671.614-1.584.959-2.536.959z" fill="#E8EAED"/><path fill="#F8F9FA" d="M290.404 57.154h70.75v52.706h-70.75z"/><path fill-rule="evenodd" clip-rule="evenodd" d="M289.348 56.1h72.861v54.814h-72.861V56.1zm70.944 52.89V58.023h-69.027v50.967h69.027z" fill="#E8EAED"/><rect x="326.307" y="81.399" width="17.951" height="1.054" rx=".527" fill="#DADCE0"/><rect x="326.307" y="83.507" width="14.784" height="1.054" rx=".527" fill="#DADCE0"/><rect x="160.52" y="48.721" width="55.966" height="78.004" rx="5" fill="#fff"/><path fill-rule="evenodd" clip-rule="evenodd" d="M165.166 47.667h45.618c3.149 0 5.702 2.562 5.702 5.723v68.667c0 3.161-2.553 5.723-5.702 5.723h-45.618c-3.149 0-5.702-2.562-5.702-5.723V53.39c0-3.16 2.553-5.723 5.702-5.723zm49.419 5.722a3.808 3.808 0 0 0-3.801-3.815h-45.618a3.808 3.808 0 0 0-3.802 3.815v68.668a3.808 3.808 0 0 0 3.802 3.815h45.618a3.808 3.808 0 0 0 3.801-3.815V53.389z" fill="#E8EAED"/><path fill="#F8F9FA" d="M165.8 53.992h44.351v67.463H165.8z"/><path fill-rule="evenodd" clip-rule="evenodd" d="M164.744 53.992h46.462v68.517h-46.462V53.992zm44.526 66.614V55.895h-42.59v64.711h42.59z" fill="#E8EAED"/><rect x="137.289" y="67.695" width="32.735" height="59.03" rx="5" fill="#fff"/><path fill-rule="evenodd" clip-rule="evenodd" d="M142.04 66.641h23.231c3.208 0 5.808 2.566 5.808 5.732v49.675c0 3.165-2.6 5.732-5.808 5.732H142.04c-3.207 0-5.808-2.567-5.808-5.732V72.373c0-3.166 2.601-5.732 5.808-5.732zm27.103 5.732c0-2.11-1.733-3.821-3.871-3.821H142.04c-2.138 0-3.872 1.71-3.872 3.821v49.675c0 2.11 1.734 3.821 3.872 3.821h23.232c2.138 0 3.871-1.711 3.871-3.821V72.373z" fill="#E8EAED"/><path fill="#E8EAED" d="M136.232 76.128h34.847v2.108h-34.847zm0 42.165h34.847v2.108h-34.847z"/><path fill="#F8F9FA" d="M138.344 78.237h30.623v40.056h-30.623z"/><rect x="145.736" y="71.912" width="15.839" height="2.108" rx="1" fill="#E8EAED"/><rect x="147.848" y="100.373" width="12.672" height="1.054" rx=".527" fill="#DADCE0"/><rect x="148.904" y="103.535" width="10.56" height="1.054" rx=".527" fill="#DADCE0"/><rect x="181.639" y="83.507" width="12.672" height="1.054" rx=".527" fill="#DADCE0"/><rect x="182.695" y="86.669" width="10.56" height="1.054" rx=".527" fill="#DADCE0"/><path fill-rule="evenodd" clip-rule="evenodd" d="M148.292 88.135a5.809 5.809 0 0 1 5.374-3.574 5.793 5.793 0 0 1 5.798 5.787 5.798 5.798 0 0 1-3.581 5.365 5.816 5.816 0 0 1-6.334-1.255 5.791 5.791 0 0 1-1.257-6.323zm5.374-1.838a1.735 1.735 0 1 1 1.23 2.964 1.743 1.743 0 0 1-1.896.377 1.736 1.736 0 0 1 .666-3.34zm0 8.222c-1.4.001-2.707-.7-3.479-1.866 0-1.147 2.319-1.776 3.479-1.776 1.16 0 3.469.629 3.479 1.776a4.17 4.17 0 0 1-3.479 1.866zm29.483-26.434a5.807 5.807 0 0 1 5.393-3.552 5.803 5.803 0 0 1 5.769 5.798 5.798 5.798 0 0 1-3.595 5.36 5.815 5.815 0 0 1-6.334-1.275 5.788 5.788 0 0 1-1.233-6.331zm5.393-1.81a1.741 1.741 0 1 1 1.231 2.978 1.747 1.747 0 0 1-2.976-1.245 1.734 1.734 0 0 1 1.745-1.732zm0 8.229a4.162 4.162 0 0 1-3.48-1.87c0-1.152 2.317-1.782 3.48-1.782 1.164 0 3.471.63 3.481 1.782a4.153 4.153 0 0 1-3.481 1.87z" fill="#DADCE0"/><path d="M129.626 40.703c-4.229 1.222-7.12 4.922-7.121 9.115 0 .559.477 1.011 1.065 1.011.589 0 1.066-.452 1.066-1.01.001-3.304 2.278-6.22 5.611-7.182 3.333-.963 6.938.252 8.881 2.994l.441.622.755-.22a4.453 4.453 0 0 1 1.222-.175 4.29 4.29 0 0 1 2.948 1.16 3.86 3.86 0 0 1 1.223 2.8c0 .559.477 1.011 1.066 1.011.588 0 1.065-.452 1.065-1.01 0-1.587-.665-3.109-1.847-4.23-1.183-1.123-2.788-1.753-4.46-1.753a6.74 6.74 0 0 0-1.085.093c-2.545-3.072-6.841-4.379-10.83-3.226z" fill="#E8EAED"/><path d="M141.604 43.45a5.845 5.845 0 0 0-4.034 1.596.888.888 0 0 0 .002 1.299.998.998 0 0 0 1.363-.002 3.868 3.868 0 0 1 2.669-1.055c.533 0 .964-.412.964-.919 0-.507-.431-.919-.964-.918zm44.229-17.528c-1.67-.002-3.277.627-4.461 1.748-1.184 1.122-1.848 2.645-1.845 4.231.001.558.479 1.01 1.068 1.009.588-.002 1.064-.454 1.063-1.012a3.843 3.843 0 0 1 1.221-2.8 4.286 4.286 0 0 1 2.954-1.156 4.5 4.5 0 0 1 1.225.169l.751.213.438-.617c1.945-2.741 5.552-3.955 8.885-2.99 3.334.963 5.61 3.88 5.607 7.182 0 .558.477 1.01 1.065 1.01.589.001 1.066-.45 1.066-1.009.004-4.191-2.885-7.892-7.116-9.116-3.991-1.154-8.292.152-10.837 3.225a6.727 6.727 0 0 0-1.084-.087z" fill="#E8EAED"/><path d="M185.774 28.422a3.816 3.816 0 0 1 2.67 1.053.991.991 0 0 0 1.358.006.89.89 0 0 0 .006-1.299 5.78 5.78 0 0 0-4.046-1.597c-.531.003-.958.417-.955.924.004.508.437.916.967.913zm210.924 30.427c-3.482 0-6.306 2.676-6.306 5.977 0 .558.477 1.01 1.066 1.01.588 0 1.065-.452 1.065-1.01 0-2.185 1.87-3.957 4.177-3.957a4.5 4.5 0 0 1 1.223.168l.751.213.438-.617c1.944-2.74 5.552-3.955 8.885-2.99 3.334.964 5.61 3.88 5.607 7.182 0 .558.477 1.01 1.065 1.011.588 0 1.066-.451 1.066-1.01.004-4.19-2.885-7.891-7.116-9.115-3.991-1.155-8.292.151-10.837 3.224a6.727 6.727 0 0 0-1.084-.086z" fill="#E8EAED"/><path d="M396.639 60.294a3.854 3.854 0 0 1 2.652 1.053c.377.36.991.364 1.372.007a.883.883 0 0 0 .008-1.299c-1.063-1.018-2.512-1.593-4.026-1.598-.536-.001-.972.409-.973.916-.002.507.431.92.967.921z" fill="#E8EAED"/><rect x="317.178" y="74.461" width="103.485" height="30.569" rx="5.37" fill="#1A73E8"/><rect x="403.768" y="79.731" width="2.112" height="18.974" rx="1" fill="#EA4335"/><path fill="#fff" d="M328.794 88.164h15.839v2.108h-15.839z"/><path d="M333.784 82.454l7.668 13.254-2.075 1.195-7.668-13.253 2.075-1.196z" fill="#fff"/><path d="M341.452 83.65l-7.668 13.253-2.076-1.195 7.669-13.254 2.075 1.195zm11.629 4.514h15.839v2.108h-15.839z" fill="#fff"/><path d="M358.706 82.45l7.668 13.254-2.075 1.196-7.668-13.254 2.075-1.195z" fill="#fff"/><path d="M366.374 83.646L358.706 96.9l-2.075-1.196 7.668-13.253 2.075 1.195zm12.05 4.518h15.839v2.108h-15.839z" fill="#fff"/><path d="M383.628 82.457l7.668 13.254-2.075 1.195-7.668-13.253 2.075-1.196z" fill="#fff"/><path d="M391.296 83.653l-7.668 13.253-2.075-1.195 7.668-13.254 2.075 1.196z" fill="#fff"/><path d="M311.883 128.724c-2.144.314-4.773 3.411-7.199 6.603-2.164 2.851-4.289 5.701-3.881 7.943.824 4.817 9.256 2.214 11.498 1.777l24.354-4.675v-14.546s-5.298-1.729-8.141 0c-2.843 1.73-3.881 6.243-6.481 6.575-2.601.333-6.113-4.256-10.15-3.677z" fill="#F6A81B"/><path opacity=".1" d="M300.83 144.032l35.825-6.281v-4.26l-34.72 6.664s-1.541 2.703-1.105 3.877z" fill="#231F20"/><path fill-rule="evenodd" clip-rule="evenodd" d="M331.375 130.329c0-8.733 7.092-15.812 15.84-15.812 8.748 0 15.839 7.079 15.839 15.812 0 8.732-7.091 15.811-15.839 15.811-8.748 0-15.84-7.079-15.84-15.811zm17.503.154a3.618 3.618 0 0 0 3.343 2.231 3.613 3.613 0 0 0 2.557-1.052 3.612 3.612 0 0 0-1.166-5.893 3.623 3.623 0 0 0-3.946.777 3.607 3.607 0 0 0-.788 3.937z" fill="#FAB505"/><path opacity=".2" fill-rule="evenodd" clip-rule="evenodd" d="M363.054 130.329c0 8.732-7.091 15.811-15.839 15.811v-31.623c8.748 0 15.839 7.079 15.839 15.812zm-14.176.154a3.618 3.618 0 0 0 3.343 2.231 3.613 3.613 0 0 0 2.557-1.052 3.612 3.612 0 0 0-1.166-5.893 3.623 3.623 0 0 0-3.946.777 3.605 3.605 0 0 0-.788 3.937z" fill="#fff"/><path d="M303.809 120.637c0 18.666-15.136 33.798-33.809 33.798s-33.809-15.132-33.809-33.798c0-18.666 15.136-33.799 33.809-33.799s33.809 15.133 33.809 33.799z" fill="#fff" stroke="#F1F3F4"/></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/signin/signin_reauth/images/account_passwords_reauth_illustration_dark.svg b/chromium/chrome/browser/resources/signin/signin_reauth/images/account_passwords_reauth_illustration_dark.svg
new file mode 100644
index 00000000000..051afdde074
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/signin_reauth/images/account_passwords_reauth_illustration_dark.svg
@@ -0,0 +1 @@
+<svg width="540" height="170" viewBox="0 0 540 170" fill="none" xmlns="http://www.w3.org/2000/svg"><path opacity=".04" d="M281.956 123.563c14.58 0 26.399-.944 26.399-2.108 0-1.164-11.819-2.108-26.399-2.108s-26.399.944-26.399 2.108c0 1.164 11.819 2.108 26.399 2.108z" fill="#202124"/><path opacity=".18" d="M145.736 127.78c14.58 0 26.399-.944 26.399-2.109 0-1.164-11.819-2.108-26.399-2.108s-26.399.944-26.399 2.108c0 1.165 11.819 2.109 26.399 2.109zm156.601 13.171v4.749h45.407v-9.487l-45.407 4.738z" fill="#fff"/><path d="M278.788 116.184V54.572c0-2.65 2.123-4.797 4.741-4.797h6.875v66.409h-11.616z" fill="#303030"/><path fill-rule="evenodd" clip-rule="evenodd" d="M283.512 48.721h7.948v68.518h-13.728V54.493a5.776 5.776 0 0 1 5.78-5.772zm6.021 66.594v-64.67h-6.021a3.85 3.85 0 0 0-3.853 3.848v60.822h9.874z" fill="#5F6368"/><path d="M284.068 116.184V54.572a4.792 4.792 0 0 1 4.788-4.797h74.901a4.792 4.792 0 0 1 4.788 4.797v61.612h-84.477z" fill="#414447"/><path fill-rule="evenodd" clip-rule="evenodd" d="M288.771 48.721h75.072c3.18 0 5.758 2.584 5.758 5.772v62.746h-86.589V54.493c0-3.188 2.578-5.772 5.759-5.772zm78.911 5.772a3.843 3.843 0 0 0-3.839-3.848H288.77a3.843 3.843 0 0 0-3.839 3.848v60.822h82.751V54.493z" fill="#5F6368"/><path d="M283.549 123.563c-2.63 0-4.761-2.205-4.761-4.926v-2.453h59.134v7.379h-54.373z" fill="#303030"/><path fill-rule="evenodd" clip-rule="evenodd" d="M277.732 115.13h61.246v9.487h-55.514c-3.166 0-5.732-2.685-5.732-5.998v-3.489zm59.336 7.488v-5.488h-57.425v1.489c0 2.209 1.711 3.999 3.821 3.999h53.604z" fill="#5F6368"/><path d="M336.363 123.563c-2.638 0-4.777-2.205-4.777-4.926v-2.453h86.59v2.453c0 2.721-2.139 4.926-4.777 4.926h-77.036z" fill="#414447"/><path fill-rule="evenodd" clip-rule="evenodd" d="M330.53 115.13h88.702v3.489c0 3.313-2.574 5.998-5.748 5.998h-77.206c-3.174 0-5.748-2.685-5.748-5.998v-3.489zm86.786 3.489v-1.489h-84.87v1.489c0 2.209 1.716 3.999 3.832 3.999h77.206c2.116 0 3.832-1.79 3.832-3.999z" fill="#5F6368"/><path d="M382.925 119.347h-16.088c-.949 0-1.859-.343-2.529-.952-.67-.61-1.045-1.436-1.043-2.297v-.968h23.232v.95c.007.864-.366 1.695-1.036 2.308-.671.614-1.584.959-2.536.959z" fill="#5F6368"/><path fill="#303030" d="M290.404 57.154h70.75v52.706h-70.75z"/><path fill-rule="evenodd" clip-rule="evenodd" d="M289.348 56.1h72.861v54.814h-72.861V56.1zm70.944 52.89V58.023h-69.027v50.967h69.027z" fill="#5F6368"/><rect x="326.307" y="81.399" width="17.951" height="1.054" rx=".527" fill="#5F6368"/><rect x="326.307" y="83.507" width="14.784" height="1.054" rx=".527" fill="#5F6368"/><rect x="160.52" y="48.721" width="55.966" height="78.004" rx="4" fill="#414447"/><path fill-rule="evenodd" clip-rule="evenodd" d="M165.166 47.667h45.618c3.149 0 5.702 2.562 5.702 5.723v68.667c0 3.161-2.553 5.723-5.702 5.723h-45.618c-3.149 0-5.702-2.562-5.702-5.723V53.39c0-3.16 2.553-5.723 5.702-5.723zm49.419 5.722a3.808 3.808 0 0 0-3.801-3.815h-45.618a3.808 3.808 0 0 0-3.802 3.815v68.668a3.808 3.808 0 0 0 3.802 3.815h45.618a3.808 3.808 0 0 0 3.801-3.815V53.389z" fill="#5F6368"/><path fill="#303030" d="M165.8 53.992h44.351v67.463H165.8z"/><path fill-rule="evenodd" clip-rule="evenodd" d="M164.744 53.992h46.462v68.517h-46.462V53.992zm44.526 66.614V55.895h-42.59v64.711h42.59z" fill="#5F6368"/><rect x="137.289" y="67.695" width="32.735" height="59.03" rx="4" fill="#414447"/><path fill-rule="evenodd" clip-rule="evenodd" d="M142.04 66.641h23.231c3.208 0 5.808 2.566 5.808 5.732v49.675c0 3.165-2.6 5.732-5.808 5.732H142.04c-3.207 0-5.808-2.567-5.808-5.732V72.373c0-3.166 2.601-5.732 5.808-5.732zm27.103 5.732c0-2.11-1.733-3.821-3.871-3.821H142.04c-2.138 0-3.872 1.71-3.872 3.821v49.675c0 2.11 1.734 3.821 3.872 3.821h23.232c2.138 0 3.871-1.711 3.871-3.821V72.373z" fill="#5F6368"/><path fill="#5F6368" d="M136.232 76.128h34.847v2.108h-34.847zm0 42.165h34.847v2.108h-34.847z"/><path fill="#303030" d="M138.344 78.237h30.623v40.056h-30.623z"/><rect x="145.736" y="71.912" width="15.839" height="2.108" rx="1" fill="#5F6368"/><rect x="147.848" y="100.373" width="12.672" height="1.054" rx=".527" fill="#5F6368"/><rect x="148.904" y="103.535" width="10.56" height="1.054" rx=".527" fill="#5F6368"/><rect x="181.639" y="83.507" width="12.672" height="1.054" rx=".527" fill="#5F6368"/><rect x="182.695" y="86.669" width="10.56" height="1.054" rx=".527" fill="#5F6368"/><path fill-rule="evenodd" clip-rule="evenodd" d="M148.292 88.135a5.809 5.809 0 0 1 5.374-3.574 5.793 5.793 0 0 1 5.798 5.787 5.798 5.798 0 0 1-3.581 5.365 5.816 5.816 0 0 1-6.334-1.255 5.791 5.791 0 0 1-1.257-6.323zm5.374-1.838a1.735 1.735 0 1 1 1.23 2.964 1.743 1.743 0 0 1-1.896.377 1.736 1.736 0 0 1 .666-3.34zm0 8.222c-1.4.001-2.707-.7-3.479-1.866 0-1.147 2.319-1.776 3.479-1.776 1.16 0 3.469.629 3.479 1.776a4.17 4.17 0 0 1-3.479 1.866zm29.483-26.434a5.807 5.807 0 0 1 5.393-3.552 5.803 5.803 0 0 1 5.769 5.798 5.798 5.798 0 0 1-3.595 5.36 5.815 5.815 0 0 1-6.334-1.275 5.788 5.788 0 0 1-1.233-6.331zm5.393-1.81a1.741 1.741 0 1 1 1.231 2.978 1.747 1.747 0 0 1-2.976-1.245 1.734 1.734 0 0 1 1.745-1.732zm0 8.229a4.162 4.162 0 0 1-3.48-1.87c0-1.152 2.317-1.782 3.48-1.782 1.164 0 3.471.63 3.481 1.782a4.153 4.153 0 0 1-3.481 1.87z" fill="#5F6368"/><path d="M129.626 40.703c-4.229 1.222-7.12 4.922-7.121 9.115 0 .559.477 1.011 1.065 1.011.589 0 1.066-.452 1.066-1.01.001-3.304 2.278-6.22 5.611-7.182 3.333-.963 6.938.252 8.881 2.994l.441.622.755-.22a4.453 4.453 0 0 1 1.222-.175 4.29 4.29 0 0 1 2.948 1.16 3.86 3.86 0 0 1 1.223 2.8c0 .559.477 1.011 1.066 1.011.588 0 1.065-.452 1.065-1.01 0-1.587-.665-3.109-1.847-4.23-1.183-1.123-2.788-1.753-4.46-1.753a6.74 6.74 0 0 0-1.085.093c-2.545-3.072-6.841-4.379-10.83-3.226z" fill="#5F6368"/><path d="M141.604 43.45a5.845 5.845 0 0 0-4.034 1.596.888.888 0 0 0 .002 1.299.998.998 0 0 0 1.363-.002 3.868 3.868 0 0 1 2.669-1.055c.533 0 .964-.412.964-.919 0-.507-.431-.919-.964-.918zm44.229-17.528c-1.67-.002-3.277.627-4.461 1.748-1.184 1.122-1.848 2.645-1.845 4.231.001.558.479 1.01 1.068 1.009.588-.002 1.064-.454 1.063-1.012a3.843 3.843 0 0 1 1.221-2.8 4.286 4.286 0 0 1 2.954-1.156 4.5 4.5 0 0 1 1.225.169l.751.213.438-.617c1.945-2.741 5.552-3.955 8.885-2.99 3.334.963 5.61 3.88 5.607 7.182 0 .558.477 1.01 1.065 1.01.589.001 1.066-.45 1.066-1.009.004-4.191-2.885-7.892-7.116-9.116-3.991-1.154-8.292.152-10.837 3.225a6.727 6.727 0 0 0-1.084-.087z" fill="#5F6368"/><path d="M185.774 28.422a3.816 3.816 0 0 1 2.67 1.053.991.991 0 0 0 1.358.006.89.89 0 0 0 .006-1.299 5.78 5.78 0 0 0-4.046-1.597c-.531.003-.958.417-.955.924.004.508.437.916.967.913zm210.924 30.427c-3.482 0-6.306 2.676-6.306 5.977 0 .558.477 1.01 1.066 1.01.588 0 1.065-.452 1.065-1.01 0-2.185 1.87-3.957 4.177-3.957a4.5 4.5 0 0 1 1.223.168l.751.213.438-.617c1.944-2.74 5.552-3.955 8.885-2.99 3.334.964 5.61 3.88 5.607 7.182 0 .558.477 1.01 1.065 1.011.588 0 1.066-.451 1.066-1.01.004-4.19-2.885-7.891-7.116-9.115-3.991-1.155-8.292.151-10.837 3.224a6.727 6.727 0 0 0-1.084-.086z" fill="#5F6368"/><path d="M396.639 60.294a3.854 3.854 0 0 1 2.652 1.053c.377.36.991.364 1.372.007a.883.883 0 0 0 .008-1.299c-1.063-1.018-2.512-1.593-4.026-1.598-.536-.001-.972.409-.973.916-.002.507.431.92.967.921z" fill="#5F6368"/><rect x="317.178" y="74.461" width="103.485" height="30.569" rx="5.37" fill="#8AB4F8"/><rect x="403.768" y="79.731" width="2.112" height="18.974" rx="1" fill="#F28B82"/><path fill="#5F6368" d="M328.794 88.164h15.839v2.108h-15.839z"/><path d="M333.784 82.454l7.668 13.254-2.075 1.195-7.668-13.253 2.075-1.196z" fill="#5F6368"/><path d="M341.452 83.65l-7.668 13.253-2.076-1.195 7.669-13.254 2.075 1.195zm11.629 4.514h15.839v2.108h-15.839z" fill="#5F6368"/><path d="M358.706 82.45l7.668 13.254-2.075 1.196-7.668-13.254 2.075-1.195z" fill="#5F6368"/><path d="M366.374 83.646L358.706 96.9l-2.075-1.196 7.668-13.253 2.075 1.195zm12.05 4.518h15.839v2.108h-15.839z" fill="#5F6368"/><path d="M383.628 82.457l7.668 13.254-2.075 1.195-7.668-13.253 2.075-1.196z" fill="#5F6368"/><path d="M391.296 83.653l-7.668 13.253-2.075-1.195 7.668-13.254 2.075 1.196z" fill="#5F6368"/><path d="M311.883 128.724c-2.144.314-4.773 3.411-7.199 6.603-2.164 2.851-4.289 5.701-3.881 7.943.824 4.817 9.256 2.214 11.498 1.777l24.354-4.675v-14.546s-5.298-1.729-8.141 0c-2.843 1.73-3.881 6.243-6.481 6.575-2.601.333-6.113-4.256-10.15-3.677z" fill="#FED563"/><path opacity=".1" d="M300.83 144.032l35.825-6.281v-4.26l-34.72 6.664s-1.541 2.703-1.105 3.877z" fill="#231F20"/><path fill-rule="evenodd" clip-rule="evenodd" d="M331.375 130.329c0-8.733 7.092-15.812 15.84-15.812 8.748 0 15.839 7.079 15.839 15.812 0 8.732-7.091 15.811-15.839 15.811-8.748 0-15.84-7.079-15.84-15.811zm17.503.154a3.618 3.618 0 0 0 3.343 2.231 3.613 3.613 0 0 0 2.557-1.052 3.612 3.612 0 0 0-1.166-5.893 3.623 3.623 0 0 0-3.946.777 3.607 3.607 0 0 0-.788 3.937z" fill="#FED563"/><path opacity=".24" fill-rule="evenodd" clip-rule="evenodd" d="M363.054 130.329c0 8.732-7.091 15.811-15.839 15.811v-31.623c8.748 0 15.839 7.079 15.839 15.812zm-14.176.154a3.618 3.618 0 0 0 3.343 2.231 3.613 3.613 0 0 0 2.557-1.052 3.612 3.612 0 0 0-1.166-5.893 3.623 3.623 0 0 0-3.946.777 3.605 3.605 0 0 0-.788 3.937z" fill="#fff"/><path d="M303.809 120.637c0 18.666-15.136 33.798-33.809 33.798s-33.809-15.132-33.809-33.798c0-18.666 15.136-33.799 33.809-33.799s33.809 15.133 33.809 33.799z" fill="#414447" stroke="#5F6368"/></svg> \ No newline at end of file
diff --git a/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth.html b/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth.html
new file mode 100644
index 00000000000..0cdd9b27b8f
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth.html
@@ -0,0 +1,24 @@
+<!doctype html>
+<html dir="$i18n{textdirection}" lang="$i18n{language}">
+ <head>
+ <meta charset="utf-8">
+ <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
+ <style>
+ body {
+ height: 100vh;
+ margin: 0;
+ width: 100vw;
+ }
+
+ @media (prefers-color-scheme: dark) {
+ body {
+ background-color: var(--google-grey-900);
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <signin-reauth-app></signin-reauth-app>
+ <script type="module" src="signin_reauth_app.js"></script>
+ </body>
+</html>
diff --git a/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_app.html b/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_app.html
new file mode 100644
index 00000000000..f6257f63261
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_app.html
@@ -0,0 +1,87 @@
+<style include="signin-dialog-shared cr-hidden-style">
+ :host {
+ color: var(--cr-primary-text-color);
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ }
+
+ #illustrationContainer {
+ height: 170px;
+ position: relative;
+ width: 100%;
+ }
+
+ #illustration {
+ background: url(./images/signin_reauth_illustration.svg);
+ background-size: 100% 100%;
+ height: 100%;
+ position: absolute;
+ top: 0;
+ width: 100%;
+ }
+
+ @media (prefers-color-scheme: dark) {
+ #illustration {
+ background: url(./images/signin_reauth_illustration_dark.svg);
+ }
+ }
+
+ #illustrationContainer > img {
+ border-radius: 50%;
+ height: 58px;
+ left: 0;
+ margin: auto;
+ position: absolute;
+ right: 0;
+ top: 92px;
+ width: 58px;
+ }
+
+ #contentContainer {
+ flex-grow: 1;
+ width: 100%;
+ }
+
+ h1 {
+ font-weight: normal;
+ margin-bottom: 8px;
+ padding: 0 40px;
+ }
+
+ .message-container {
+ color: var(--cr-secondary-text-color);
+ line-height: 20px;
+ margin-bottom: 16px;
+ padding: 0 40px;
+ }
+
+ cr-button {
+ padding-inline-end: 16px;
+ padding-inline-start: 16px;
+ }
+</style>
+<div id="illustrationContainer">
+ <div id="illustration"></div>
+ <img src="[[accountImageSrc_]]">
+</div>
+<div id="contentContainer">
+ <h1 id="signinReauthTitle">
+ $i18n{signinReauthTitle}
+ </h1>
+ <div class="message-container">
+ <div>$i18n{signinReauthDesc}</div>
+ </div>
+</div>
+<div class="action-container">
+ <paper-spinner-lite active hidden$="[[!confirmButtonHidden_]]">
+ </paper-spinner-lite>
+ <cr-button id="confirmButton" class="action-button" on-click="onConfirm_"
+ hidden="[[confirmButtonHidden_]]">
+ [[confirmButtonLabel_]]
+ </cr-button>
+ <cr-button id="cancelButton" on-click="onCancel_"
+ hidden="[[cancelButtonHidden_]]">
+ $i18n{signinReauthCloseLabel}
+ </cr-button>
+</div>
diff --git a/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_app.js b/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_app.js
new file mode 100644
index 00000000000..e2c6b4ec6d9
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_app.js
@@ -0,0 +1,78 @@
+// Copyright 2020 The Chromium 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 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
+import 'chrome://resources/cr_elements/hidden_style_css.m.js';
+import 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js';
+import './strings.m.js';
+import './signin_shared_css.js';
+
+import {I18nBehavior} from 'chrome://resources/js/i18n_behavior.m.js';
+import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
+import {WebUIListenerBehavior} from 'chrome://resources/js/web_ui_listener_behavior.m.js';
+import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+import {SigninReauthBrowserProxy, SigninReauthBrowserProxyImpl} from './signin_reauth_browser_proxy.js';
+
+Polymer({
+ is: 'signin-reauth-app',
+
+ _template: html`{__html_template__}`,
+
+ behaviors: [I18nBehavior, WebUIListenerBehavior],
+
+ properties: {
+ /** @private */
+ accountImageSrc_: {
+ type: String,
+ value() {
+ return loadTimeData.getString('accountImageUrl');
+ },
+ },
+
+ /** @private */
+ confirmButtonLabel_: String,
+
+ /** @private */
+ confirmButtonHidden_: {type: Boolean, value: true},
+
+ /** @private */
+ cancelButtonHidden_: {type: Boolean, value: true}
+ },
+
+ /** @private {SigninReauthBrowserProxy} */
+ signinReauthBrowserProxy_: null,
+
+ /** @override */
+ attached() {
+ this.signinReauthBrowserProxy_ = SigninReauthBrowserProxyImpl.getInstance();
+ this.addWebUIListener(
+ 'reauth-type-received', this.onReauthTypeReceived_.bind(this));
+ this.signinReauthBrowserProxy_.initialize();
+ },
+
+ /** @private */
+ onConfirm_() {
+ this.signinReauthBrowserProxy_.confirm();
+ },
+
+ /** @private */
+ onCancel_() {
+ this.signinReauthBrowserProxy_.cancel();
+ },
+
+ /**
+ * @param {boolean} requiresReauth Whether the user will be asked to
+ * reauthenticate after clicking on the confirm button.
+ * @private
+ */
+ onReauthTypeReceived_(requiresReauth) {
+ this.confirmButtonHidden_ = false;
+ this.$.confirmButton.focus();
+ this.cancelButtonHidden_ = requiresReauth;
+ this.confirmButtonLabel_ = requiresReauth ?
+ this.i18n('signinReauthNextLabel') :
+ this.i18n('signinReauthConfirmLabel');
+ },
+});
diff --git a/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_browser_proxy.js b/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_browser_proxy.js
new file mode 100644
index 00000000000..d4a040455aa
--- /dev/null
+++ b/chromium/chrome/browser/resources/signin/signin_reauth/signin_reauth_browser_proxy.js
@@ -0,0 +1,47 @@
+// Copyright 2020 The Chromium 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 signin reauth dialog to
+ * interact with the browser.
+ */
+import {addSingletonGetter} from 'chrome://resources/js/cr.m.js';
+
+/** @interface */
+export class SigninReauthBrowserProxy {
+ /**
+ * Called when the app has been initialized.
+ */
+ initialize() {}
+
+ /**
+ * Called when the user confirms the signin reauth dialog.
+ */
+ confirm() {}
+
+ /**
+ * Called when the user cancels the signin reauth.
+ */
+ cancel() {}
+}
+
+/** @implements {SigninReauthBrowserProxy} */
+export class SigninReauthBrowserProxyImpl {
+ /** @override */
+ initialize() {
+ chrome.send('initialize');
+ }
+
+ /** @override */
+ confirm() {
+ chrome.send('confirm');
+ }
+
+ /** @override */
+ cancel() {
+ chrome.send('cancel');
+ }
+}
+
+addSingletonGetter(SigninReauthBrowserProxyImpl);
diff --git a/chromium/chrome/browser/resources/signin/signin_shared_css.html b/chromium/chrome/browser/resources/signin/signin_shared_css.html
index c7de5b75449..3b31a483eb2 100644
--- a/chromium/chrome/browser/resources/signin/signin_shared_css.html
+++ b/chromium/chrome/browser/resources/signin/signin_shared_css.html
@@ -26,11 +26,20 @@
padding: 16px;
}
+ cr-button + cr-button {
+ margin-inline-start: 8px;
+ }
+
<if expr="is_macosx or is_linux">
.action-container {
flex-flow: row-reverse;
justify-content: flex-start;
}
+
+ cr-button + cr-button {
+ margin-inline-end: 8px;
+ margin-inline-start: 0;
+ }
</if>
</style>
</template>
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 04c560fac17..9fb93b71e60 100644
--- a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation.js
@@ -7,7 +7,6 @@ import {addWebUIListener} from 'chrome://resources/js/cr.m.js';
import {SyncConfirmationBrowserProxyImpl} from './sync_confirmation_browser_proxy.js';
function initialize() {
- addWebUIListener('clear-focus', clearFocus);
const syncConfirmationBrowserProxy =
SyncConfirmationBrowserProxyImpl.getInstance();
// Prefer using |document.body.offsetHeight| instead of
@@ -21,8 +20,4 @@ function initialize() {
document.body.style.width = 'auto';
}
-function clearFocus() {
- document.activeElement.blur();
-}
-
document.addEventListener('DOMContentLoaded', initialize);
diff --git a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.html b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.html
index d8a68eb5b90..3cc7d3045b8 100644
--- a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.html
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.html
@@ -16,18 +16,6 @@
width: 100%;
}
- 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. */
- cr-button:not(.action-button) {
- margin-inline-end: 8px;
- margin-inline-start: 0;
- }
-</if>
-
#illustration-container {
height: 168px;
margin-bottom: 32px;
@@ -138,7 +126,7 @@
</div>
<div class="action-container">
<cr-button class="action-button" id="confirmButton"
- on-click="onConfirm_" consent-confirmation>
+ on-click="onConfirm_" consent-confirmation autofocus>
$i18n{syncConfirmationConfirmLabel}
</cr-button>
<cr-button id="cancelButton" on-click="onUndo_">
diff --git a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.js b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.js
index 1557d13bc78..83d2cccafb7 100644
--- a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.js
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_confirmation_app.js
@@ -36,28 +36,15 @@ Polymer({
/** @private {?SyncConfirmationBrowserProxy} */
syncConfirmationBrowserProxy_: null,
- /** @private {?function(Event)} */
- boundKeyDownHandler_: null,
-
/** @override */
attached() {
this.syncConfirmationBrowserProxy_ =
SyncConfirmationBrowserProxyImpl.getInstance();
- this.boundKeyDownHandler_ = this.onKeyDown_.bind(this);
- // This needs to be bound to document instead of "this" because the dialog
- // window opens initially, the focus level is only on document, so the key
- // event is not captured by "this".
- document.addEventListener('keydown', this.boundKeyDownHandler_);
this.addWebUIListener(
'account-image-changed', this.handleAccountImageChanged_.bind(this));
this.syncConfirmationBrowserProxy_.requestAccountImage();
},
- /** @override */
- detached() {
- document.removeEventListener('keydown', this.boundKeyDownHandler_);
- },
-
/** @private */
onConfirm_(e) {
this.syncConfirmationBrowserProxy_.confirm(
@@ -75,14 +62,6 @@ Polymer({
this.getConsentDescription_(), this.getConsentConfirmation_(e.path));
},
- /** @private */
- onKeyDown_(e) {
- if (e.key == 'Enter' && !/^(A|CR-BUTTON)$/.test(e.path[0].tagName)) {
- this.onConfirm_(e);
- e.preventDefault();
- }
- },
-
/**
* @param {!Array<!HTMLElement>} path Path of the click event. Must contain
* a consent confirmation element.
diff --git a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation_app.html b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation_app.html
index 4ec21e8f6d3..c0b206c5bff 100644
--- a/chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation_app.html
+++ b/chromium/chrome/browser/resources/signin/sync_confirmation/sync_disabled_confirmation_app.html
@@ -2,14 +2,6 @@
.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;
diff --git a/chromium/chrome/browser/resources/tab_strip/drag_manager.js b/chromium/chrome/browser/resources/tab_strip/drag_manager.js
index 69b836bf742..b50733200f8 100644
--- a/chromium/chrome/browser/resources/tab_strip/drag_manager.js
+++ b/chromium/chrome/browser/resources/tab_strip/drag_manager.js
@@ -9,7 +9,7 @@ import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {isTabElement, TabElement} from './tab.js';
import {isTabGroupElement, TabGroupElement} from './tab_group.js';
-import {TabData, TabNetworkState, TabsApiProxy} from './tabs_api_proxy.js';
+import {TabData, TabNetworkState, TabsApiProxy, TabsApiProxyImpl} from './tabs_api_proxy.js';
/** @const {number} */
export const PLACEHOLDER_TAB_ID = -1;
@@ -107,7 +107,7 @@ class DragSession {
this.srcGroup = srcGroup;
/** @private @const {!TabsApiProxy} */
- this.tabsProxy_ = TabsApiProxy.getInstance();
+ this.tabsProxy_ = TabsApiProxyImpl.getInstance();
}
/**
@@ -359,7 +359,8 @@ class DragSession {
const dragOverTabElement =
/** @type {!TabElement|undefined} */ (composedPath.find(isTabElement));
- if (dragOverTabElement && !dragOverTabElement.tab.pinned) {
+ if (dragOverTabElement && !dragOverTabElement.tab.pinned &&
+ dragOverTabElement.isValidDragOverTarget) {
let dragOverIndex = this.delegate_.getIndexOfTab(dragOverTabElement);
dragOverIndex +=
this.shouldOffsetIndexForGroup_(dragOverTabElement) ? 1 : 0;
@@ -369,7 +370,7 @@ class DragSession {
const dragOverGroupElement = /** @type {!TabGroupElement|undefined} */ (
composedPath.find(isTabGroupElement));
- if (dragOverGroupElement) {
+ if (dragOverGroupElement && dragOverGroupElement.isValidDragOverTarget) {
let dragOverIndex = this.delegate_.getIndexOfTab(
/** @type {!TabElement} */ (dragOverGroupElement.firstElementChild));
dragOverIndex +=
@@ -388,8 +389,9 @@ class DragSession {
const dragOverTabElement =
/** @type {?TabElement} */ (composedPath.find(isTabElement));
if (dragOverTabElement &&
- dragOverTabElement.tab.pinned !== tabElement.tab.pinned) {
- // Can only drag between the same pinned states.
+ (dragOverTabElement.tab.pinned !== tabElement.tab.pinned ||
+ !dragOverTabElement.isValidDragOverTarget)) {
+ // Can only drag between the same pinned states and valid TabElements.
return;
}
@@ -401,7 +403,8 @@ class DragSession {
const dragOverTabGroup =
/** @type {?TabGroupElement} */ (composedPath.find(isTabGroupElement));
if (dragOverTabGroup &&
- dragOverTabGroup.dataset.groupId !== previousGroupId) {
+ dragOverTabGroup.dataset.groupId !== previousGroupId &&
+ dragOverTabGroup.isValidDragOverTarget) {
this.delegate_.placeTabElement(
tabElement, this.dstIndex, false, dragOverTabGroup.dataset.groupId);
return;
@@ -433,7 +436,7 @@ export class DragManager {
this.dragSession_ = null;
/** @private {!TabsApiProxy} */
- this.tabsProxy_ = TabsApiProxy.getInstance();
+ this.tabsProxy_ = TabsApiProxyImpl.getInstance();
}
/** @private */
diff --git a/chromium/chrome/browser/resources/tab_strip/tab.js b/chromium/chrome/browser/resources/tab_strip/tab.js
index 4c6fbb904e1..61da08df076 100644
--- a/chromium/chrome/browser/resources/tab_strip/tab.js
+++ b/chromium/chrome/browser/resources/tab_strip/tab.js
@@ -11,10 +11,10 @@ import {isRTL} from 'chrome://resources/js/util.m.js';
import {AlertIndicatorsElement} from './alert_indicators.js';
import {CustomElement} from './custom_element.js';
-import {TabStripEmbedderProxy} from './tab_strip_embedder_proxy.js';
+import {TabStripEmbedderProxy, TabStripEmbedderProxyImpl} from './tab_strip_embedder_proxy.js';
import {tabStripOptions} from './tab_strip_options.js';
import {TabSwiper} from './tab_swiper.js';
-import {CloseTabAction, TabData, TabNetworkState, TabsApiProxy} from './tabs_api_proxy.js';
+import {CloseTabAction, TabData, TabNetworkState, TabsApiProxy, TabsApiProxyImpl} from './tabs_api_proxy.js';
const DEFAULT_ANIMATION_DURATION = 125;
@@ -84,14 +84,22 @@ export class TabElement extends CustomElement {
this.tab_;
/** @private {!TabsApiProxy} */
- this.tabsApi_ = TabsApiProxy.getInstance();
+ this.tabsApi_ = TabsApiProxyImpl.getInstance();
/** @private {!TabStripEmbedderProxy} */
- this.embedderApi_ = TabStripEmbedderProxy.getInstance();
+ this.embedderApi_ = TabStripEmbedderProxyImpl.getInstance();
/** @private {!HTMLElement} */
this.titleTextEl_ = /** @type {!HTMLElement} */ (this.$('#titleText'));
+ /**
+ * Flag indicating if this TabElement can accept dragover events. This
+ * is used to pause dragover events while animating as animating causes
+ * the elements below the pointer to shift.
+ * @private {boolean}
+ */
+ this.isValidDragOverTarget_ = true;
+
this.tabEl_.addEventListener('click', () => this.onClick_());
this.tabEl_.addEventListener('contextmenu', e => this.onContextMenu_(e));
this.tabEl_.addEventListener(
@@ -169,6 +177,16 @@ export class TabElement extends CustomElement {
this.tab_ = Object.freeze(tab);
}
+ /** @return {boolean} */
+ get isValidDragOverTarget() {
+ return !this.hasAttribute('dragging_') && this.isValidDragOverTarget_;
+ }
+
+ /** @param {boolean} isValid */
+ set isValidDragOverTarget(isValid) {
+ this.isValidDragOverTarget_ = isValid;
+ }
+
/** @param {!Function} callback */
set onTabActivating(callback) {
this.onTabActivating_ = callback;
diff --git a/chromium/chrome/browser/resources/tab_strip/tab_group.js b/chromium/chrome/browser/resources/tab_strip/tab_group.js
index e50abdbf55a..cfd47a53868 100644
--- a/chromium/chrome/browser/resources/tab_strip/tab_group.js
+++ b/chromium/chrome/browser/resources/tab_strip/tab_group.js
@@ -5,7 +5,7 @@
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {CustomElement} from './custom_element.js';
-import {TabStripEmbedderProxy} from './tab_strip_embedder_proxy.js';
+import {TabStripEmbedderProxy, TabStripEmbedderProxyImpl} from './tab_strip_embedder_proxy.js';
import {TabGroupVisualData} from './tabs_api_proxy.js';
export class TabGroupElement extends CustomElement {
@@ -17,13 +17,30 @@ export class TabGroupElement extends CustomElement {
super();
/** @private @const {!TabStripEmbedderProxy} */
- this.embedderApi_ = TabStripEmbedderProxy.getInstance();
+ this.embedderApi_ = TabStripEmbedderProxyImpl.getInstance();
/** @private @const {!HTMLElement} */
this.chip_ = /** @type {!HTMLElement} */ (this.$('#chip'));
this.chip_.addEventListener('click', () => this.onClickChip_());
this.chip_.addEventListener(
'keydown', e => this.onKeydownChip_(/** @type {!KeyboardEvent} */ (e)));
+
+ /**
+ * Flag indicating if this element can accept dragover events. This flag
+ * is updated by TabListElement while animating.
+ * @private {boolean}
+ */
+ this.isValidDragOverTarget_ = true;
+ }
+
+ /** @return {boolean} */
+ get isValidDragOverTarget() {
+ return !this.hasAttribute('dragging_') && this.isValidDragOverTarget_;
+ }
+
+ /** @param {boolean} isValid */
+ set isValidDragOverTarget(isValid) {
+ this.isValidDragOverTarget_ = isValid;
}
/** @return {!HTMLElement} */
diff --git a/chromium/chrome/browser/resources/tab_strip/tab_list.html b/chromium/chrome/browser/resources/tab_strip/tab_list.html
index 12be60a5f39..f6cb511ab76 100644
--- a/chromium/chrome/browser/resources/tab_strip/tab_list.html
+++ b/chromium/chrome/browser/resources/tab_strip/tab_list.html
@@ -41,11 +41,12 @@
* tab. 20px is subtracted from the height of an unpinned tab as there
* are two 10px gaps to separate each of the 3 pinned tabs. */
--tabstrip-pinned-tab-size: calc((var(--tabstrip-tab-height) - 20px) / 3);
+ --tabstrip-tab-spacing: 10px;
display: grid;
grid-auto-columns: var(--tabstrip-pinned-tab-size);
grid-auto-flow: column;
- grid-gap: 10px;
+ grid-gap: var(--tabstrip-tab-spacing);
grid-template-rows: repeat(3, var(--tabstrip-pinned-tab-size));
padding-block-end: var(--tabstrip-tab-list-vertical-padding);
padding-block-start: var(--tabstrip-tab-list-vertical-padding);
diff --git a/chromium/chrome/browser/resources/tab_strip/tab_list.js b/chromium/chrome/browser/resources/tab_strip/tab_list.js
index 08ac72db837..5ab5de62076 100644
--- a/chromium/chrome/browser/resources/tab_strip/tab_list.js
+++ b/chromium/chrome/browser/resources/tab_strip/tab_list.js
@@ -15,11 +15,11 @@ import {isRTL} from 'chrome://resources/js/util.m.js';
import {CustomElement} from './custom_element.js';
import {DragManager, DragManagerDelegate} from './drag_manager.js';
-import {TabElement} from './tab.js';
+import {isTabElement, TabElement} from './tab.js';
import {isTabGroupElement, TabGroupElement} from './tab_group.js';
-import {TabStripEmbedderProxy} from './tab_strip_embedder_proxy.js';
+import {TabStripEmbedderProxy, TabStripEmbedderProxyImpl} from './tab_strip_embedder_proxy.js';
import {tabStripOptions} from './tab_strip_options.js';
-import {TabData, TabGroupVisualData, TabsApiProxy} from './tabs_api_proxy.js';
+import {TabData, TabGroupVisualData, TabsApiProxy, TabsApiProxyImpl} from './tabs_api_proxy.js';
/**
* The amount of padding to leave between the edge of the screen and the active
@@ -47,8 +47,88 @@ const LayoutVariable = {
TAB_WIDTH: '--tabstrip-tab-thumbnail-width',
};
+/**
+ * Animates a series of elements to indicate that tabs have moved position.
+ * @param {!Element} movedElement
+ * @param {number} prevIndex
+ * @param {number} newIndex
+ */
+function animateElementMoved(movedElement, prevIndex, newIndex) {
+ // Direction is -1 for moving towards a lower index, +1 for moving
+ // towards a higher index. If moving towards a lower index, the TabList needs
+ // to animate everything from the movedElement's current index to its prev
+ // index by traversing the nextElementSibling of each element because the
+ // movedElement is now at a preceding position from all the elements it has
+ // slid across. If moving towards a higher index, the TabList needs to
+ // traverse the previousElementSiblings.
+ const direction = Math.sign(newIndex - prevIndex);
+
+ /**
+ * @param {!Element} element
+ * @return {?Element}
+ */
+ function getSiblingToAnimate(element) {
+ return direction === -1 ? element.nextElementSibling :
+ element.previousElementSibling;
+ }
+ let elementToAnimate = getSiblingToAnimate(movedElement);
+ for (let i = newIndex; i !== prevIndex && elementToAnimate; i -= direction) {
+ const elementToAnimatePrevIndex = i;
+ const elementToAnimateNewIndex = i - direction;
+ slideElement(
+ elementToAnimate, elementToAnimatePrevIndex, elementToAnimateNewIndex);
+ elementToAnimate = getSiblingToAnimate(elementToAnimate);
+ }
+
+ slideElement(movedElement, prevIndex, newIndex);
+}
+
+/**
+ * Animates the slide of an element across the tab strip (both vertically and
+ * horizontally for pinned tabs, and horizontally for other tabs and groups).
+ * @param {!Element} element
+ * @param {number} prevIndex
+ * @param {number} newIndex
+ */
+function slideElement(element, prevIndex, newIndex) {
+ let horizontalMovement = newIndex - prevIndex;
+ let verticalMovement = 0;
+
+ if (isTabElement(element) && element.tab.pinned) {
+ const pinnedTabsPerColumn = 3;
+ const columnChange = Math.floor(newIndex / pinnedTabsPerColumn) -
+ Math.floor(prevIndex / pinnedTabsPerColumn);
+ horizontalMovement = columnChange;
+ verticalMovement =
+ (newIndex - prevIndex) - (columnChange * pinnedTabsPerColumn);
+ }
+
+ horizontalMovement *= isRTL() ? -1 : 1;
+
+ const translateX = `calc(${horizontalMovement * -1} * ` +
+ '(var(--tabstrip-tab-width) + var(--tabstrip-tab-spacing)))';
+ const translateY = `calc(${verticalMovement * -1} * ` +
+ '(var(--tabstrip-tab-height) + var(--tabstrip-tab-spacing)))';
+
+ element.isValidDragOverTarget = false;
+ const animation = element.animate(
+ [
+ {transform: `translate(${translateX}, ${translateY})`},
+ {transform: 'translate(0, 0)'},
+ ],
+ {
+ duration: 120,
+ easing: 'ease-out',
+ });
+ function onComplete() {
+ element.isValidDragOverTarget = true;
+ }
+ animation.oncancel = onComplete;
+ animation.onfinish = onComplete;
+}
+
/** @implements {DragManagerDelegate} */
-class TabListElement extends CustomElement {
+export class TabListElement extends CustomElement {
static get template() {
return `{__html_template__}`;
}
@@ -122,10 +202,10 @@ class TabListElement extends CustomElement {
this.pinnedTabsElement_ = /** @type {!Element} */ (this.$('#pinnedTabs'));
/** @private {!TabStripEmbedderProxy} */
- this.tabStripEmbedderProxy_ = TabStripEmbedderProxy.getInstance();
+ this.tabStripEmbedderProxy_ = TabStripEmbedderProxyImpl.getInstance();
/** @private {!TabsApiProxy} */
- this.tabsApi_ = TabsApiProxy.getInstance();
+ this.tabsApi_ = TabsApiProxyImpl.getInstance();
/** @private {!Element} */
this.unpinnedTabsElement_ =
@@ -265,7 +345,9 @@ class TabListElement extends CustomElement {
this.addWebUIListener_('tab-created', tab => this.onTabCreated_(tab));
this.addWebUIListener_(
- 'tab-moved', (tabId, newIndex) => this.onTabMoved_(tabId, newIndex));
+ 'tab-moved',
+ (tabId, newIndex, pinned) =>
+ this.onTabMoved_(tabId, newIndex, pinned));
this.addWebUIListener_('tab-removed', tabId => this.onTabRemoved_(tabId));
this.addWebUIListener_(
'tab-replaced', (oldId, newId) => this.onTabReplaced_(oldId, newId));
@@ -556,13 +638,13 @@ class TabListElement extends CustomElement {
/**
* @param {number} tabId
* @param {number} newIndex
+ * @param {boolean} pinned
* @private
*/
- onTabMoved_(tabId, newIndex) {
+ onTabMoved_(tabId, newIndex, pinned) {
const movedTab = this.findTabElement_(tabId);
if (movedTab) {
- this.placeTabElement(
- movedTab, newIndex, movedTab.tab.pinned, movedTab.tab.groupId);
+ this.placeTabElement(movedTab, newIndex, pinned, movedTab.tab.groupId);
if (movedTab.tab.active) {
this.scrollToTab_(movedTab);
}
@@ -638,50 +720,14 @@ class TabListElement extends CustomElement {
placeTabElement(element, index, pinned, groupId) {
const isInserting = !element.isConnected;
- // Remove the element if it already exists in the DOM.
- element.remove();
-
- if (pinned) {
- this.pinnedTabsElement_.insertBefore(
- element, this.pinnedTabsElement_.childNodes[index]);
- } else {
- let elementToInsert = element;
- let elementAtIndex = this.$all('tabstrip-tab').item(index);
- let parentElement = this.unpinnedTabsElement_;
-
- if (groupId) {
- let tabGroupElement = this.findTabGroupElement_(groupId);
- if (tabGroupElement) {
- // If a TabGroupElement already exists, add the TabElement to it.
- parentElement = tabGroupElement;
- } else {
- // If a TabGroupElement does not exist, create one and add the
- // TabGroupElement into the DOM.
- tabGroupElement = document.createElement('tabstrip-tab-group');
- tabGroupElement.setAttribute('data-group-id', groupId);
- tabGroupElement.appendChild(element);
- elementToInsert = tabGroupElement;
- }
- }
-
- if (elementAtIndex && elementAtIndex.parentElement &&
- isTabGroupElement(elementAtIndex.parentElement) &&
- (elementAtIndex.previousElementSibling === null &&
- elementAtIndex.tab.groupId !== groupId)) {
- // If the element at the model index is in a group, and the group is
- // different from the new tab's group, and is the first element in its
- // group, insert the new element before its TabGroupElement. If a
- // TabElement is being sandwiched between two TabElements in a group, it
- // can be assumed that the tab will eventually be inserted into the
- // group as well.
- elementAtIndex = elementAtIndex.parentElement;
- }
+ const previousIndex = isInserting ? -1 : this.getIndexOfTab(element);
+ const previousParent = element.parentElement;
+ this.updateTabElementDomPosition_(element, index, pinned, groupId);
- if (elementAtIndex && elementAtIndex.parentElement === parentElement) {
- parentElement.insertBefore(elementToInsert, elementAtIndex);
- } else {
- parentElement.appendChild(elementToInsert);
- }
+ if (!isInserting && previousParent === element.parentElement) {
+ // Only animate if the tab is being moved within the same parent. Tab
+ // moves that change pinned state or grouped states do not animate.
+ animateElementMoved(element, previousIndex, index);
}
if (isInserting) {
@@ -694,7 +740,15 @@ class TabListElement extends CustomElement {
* @param {number} index
*/
placeTabGroupElement(element, index) {
- element.remove();
+ const previousDomIndex =
+ Array.from(this.unpinnedTabsElement_.children).indexOf(element);
+ if (element.isConnected && element.childElementCount &&
+ this.getIndexOfTab(
+ /** @type {!TabElement} */ (element.firstElementChild)) < index) {
+ // If moving after its original position, the index value needs to be
+ // offset by 1 to consider itself already attached to the DOM.
+ index++;
+ }
let elementAtIndex = this.$all('tabstrip-tab')[index];
if (elementAtIndex && elementAtIndex.parentElement &&
@@ -703,6 +757,14 @@ class TabListElement extends CustomElement {
}
this.unpinnedTabsElement_.insertBefore(element, elementAtIndex);
+
+ // Animating the TabGroupElement move should be treated the same as
+ // animating a TabElement. Therefore, treat indices as if they were mere
+ // tabs and do not use the group's model index as they are not as accurate
+ // in representing DOM movements.
+ animateElementMoved(
+ element, previousDomIndex,
+ Array.from(this.unpinnedTabsElement_.children).indexOf(element));
}
/** @private */
@@ -775,6 +837,63 @@ class TabListElement extends CustomElement {
}
/**
+ * @param {!TabElement} element
+ * @param {number} index
+ * @param {boolean} pinned
+ * @param {string=} groupId
+ * @private
+ */
+ updateTabElementDomPosition_(element, index, pinned, groupId) {
+ // Remove the element if it already exists in the DOM. This simplifies
+ // the way indices work as it does not have to count its old index in
+ // the initial layout of the DOM.
+ element.remove();
+
+ if (pinned) {
+ this.pinnedTabsElement_.insertBefore(
+ element, this.pinnedTabsElement_.childNodes[index]);
+ } else {
+ let elementToInsert = element;
+ let elementAtIndex = this.$all('tabstrip-tab').item(index);
+ let parentElement = this.unpinnedTabsElement_;
+
+ if (groupId) {
+ let tabGroupElement = this.findTabGroupElement_(groupId);
+ if (tabGroupElement) {
+ // If a TabGroupElement already exists, add the TabElement to it.
+ parentElement = tabGroupElement;
+ } else {
+ // If a TabGroupElement does not exist, create one and add the
+ // TabGroupElement into the DOM.
+ tabGroupElement = document.createElement('tabstrip-tab-group');
+ tabGroupElement.setAttribute('data-group-id', groupId);
+ tabGroupElement.appendChild(element);
+ elementToInsert = tabGroupElement;
+ }
+ }
+
+ if (elementAtIndex && elementAtIndex.parentElement &&
+ isTabGroupElement(elementAtIndex.parentElement) &&
+ (elementAtIndex.previousElementSibling === null &&
+ elementAtIndex.tab.groupId !== groupId)) {
+ // If the element at the model index is in a group, and the group is
+ // different from the new tab's group, and is the first element in its
+ // group, insert the new element before its TabGroupElement. If a
+ // TabElement is being sandwiched between two TabElements in a group, it
+ // can be assumed that the tab will eventually be inserted into the
+ // group as well.
+ elementAtIndex = elementAtIndex.parentElement;
+ }
+
+ if (elementAtIndex && elementAtIndex.parentElement === parentElement) {
+ parentElement.insertBefore(elementToInsert, elementAtIndex);
+ } else {
+ parentElement.appendChild(elementToInsert);
+ }
+ }
+ }
+
+ /**
* @param {!TabElement} tabElement
* @private
*/
diff --git a/chromium/chrome/browser/resources/tab_strip/tab_strip_embedder_proxy.js b/chromium/chrome/browser/resources/tab_strip/tab_strip_embedder_proxy.js
index 898858e782c..3bfcc59f238 100644
--- a/chromium/chrome/browser/resources/tab_strip/tab_strip_embedder_proxy.js
+++ b/chromium/chrome/browser/resources/tab_strip/tab_strip_embedder_proxy.js
@@ -4,31 +4,24 @@
import {addSingletonGetter, addWebUIListener, sendWithPromise} from 'chrome://resources/js/cr.m.js';
+/** @interface */
export class TabStripEmbedderProxy {
/** @return {boolean} */
- isVisible() {
- return document.visibilityState === 'visible';
- }
+ isVisible() {}
/**
* @return {!Promise<!Object<string, string>>} Object with CSS variables
* as keys and rgba strings as values
*/
- getColors() {
- return sendWithPromise('getThemeColors');
- }
+ getColors() {}
/**
* @return {!Promise<!Object<string, string>>} Object with CSS variables
* as keys and pixel lengths as values
*/
- getLayout() {
- return sendWithPromise('getLayout');
- }
+ getLayout() {}
- observeThemeChanges() {
- chrome.send('observeThemeChanges');
- }
+ observeThemeChanges() {}
/**
* @param {string} groupId
@@ -37,53 +30,97 @@ export class TabStripEmbedderProxy {
* @param {number} width
* @param {number} height
*/
- showEditDialogForGroup(groupId, locationX, locationY, width, height) {
- chrome.send(
- 'showEditDialogForGroup',
- [groupId, locationX, locationY, width, height]);
- }
+ showEditDialogForGroup(groupId, locationX, locationY, width, height) {}
/**
* @param {number} tabId
* @param {number} locationX
* @param {number} locationY
*/
- showTabContextMenu(tabId, locationX, locationY) {
- chrome.send('showTabContextMenu', [tabId, locationX, locationY]);
- }
+ showTabContextMenu(tabId, locationX, locationY) {}
/**
* @param {number} locationX
* @param {number} locationY
*/
+ showBackgroundContextMenu(locationX, locationY) {}
+
+ closeContainer() {}
+
+ /** @param {number} durationMs Activation duration time in ms. */
+ reportTabActivationDuration(durationMs) {}
+
+ /**
+ * @param {number} tabCount Number of tabs.
+ * @param {number} durationMs Activation duration time in ms.
+ */
+ reportTabDataReceivedDuration(tabCount, durationMs) {}
+
+ /**
+ * @param {number} tabCount Number of tabs.
+ * @param {number} durationMs Creation duration time in ms.
+ */
+ reportTabCreationDuration(tabCount, durationMs) {}
+}
+
+/** @implements {TabStripEmbedderProxy} */
+export class TabStripEmbedderProxyImpl {
+ /** @override */
+ isVisible() {
+ return document.visibilityState === 'visible';
+ }
+
+ /** @override */
+ getColors() {
+ return sendWithPromise('getThemeColors');
+ }
+
+ /** @override */
+ getLayout() {
+ return sendWithPromise('getLayout');
+ }
+
+ /** @override */
+ observeThemeChanges() {
+ chrome.send('observeThemeChanges');
+ }
+
+ /** @override */
+ showEditDialogForGroup(groupId, locationX, locationY, width, height) {
+ chrome.send(
+ 'showEditDialogForGroup',
+ [groupId, locationX, locationY, width, height]);
+ }
+
+ /** @override */
+ showTabContextMenu(tabId, locationX, locationY) {
+ chrome.send('showTabContextMenu', [tabId, locationX, locationY]);
+ }
+
+ /** @override */
showBackgroundContextMenu(locationX, locationY) {
chrome.send('showBackgroundContextMenu', [locationX, locationY]);
}
+ /** @override */
closeContainer() {
chrome.send('closeContainer');
}
- /** @param {number} durationMs Activation duration time in ms. */
+ /** @override */
reportTabActivationDuration(durationMs) {
chrome.send('reportTabActivationDuration', [durationMs]);
}
- /**
- * @param {number} tabCount Number of tabs.
- * @param {number} durationMs Activation duration time in ms.
- */
+ /** @override */
reportTabDataReceivedDuration(tabCount, durationMs) {
chrome.send('reportTabDataReceivedDuration', [tabCount, durationMs]);
}
- /**
- * @param {number} tabCount Number of tabs.
- * @param {number} durationMs Creation duration time in ms.
- */
+ /** @override */
reportTabCreationDuration(tabCount, durationMs) {
chrome.send('reportTabCreationDuration', [tabCount, durationMs]);
}
}
-addSingletonGetter(TabStripEmbedderProxy);
+addSingletonGetter(TabStripEmbedderProxyImpl);
diff --git a/chromium/chrome/browser/resources/tab_strip/tab_strip_resources.grd b/chromium/chrome/browser/resources/tab_strip/tab_strip_resources.grd
index fe3ddc57f85..64fb60b1810 100644
--- a/chromium/chrome/browser/resources/tab_strip/tab_strip_resources.grd
+++ b/chromium/chrome/browser/resources/tab_strip/tab_strip_resources.grd
@@ -16,69 +16,57 @@
name="IDR_TAB_STRIP_HTML"
file="tab_strip.html"
type="chrome_html"
- compress="gzip"
preprocess="true"/>
<structure
name="IDR_TAB_STRIP_TABS_API_PROXY_JS"
file="tabs_api_proxy.js"
- type="chrome_html"
- compress="gzip"/>
+ type="chrome_html"/>
<structure
name="IDR_TAB_STRIP_CUSTOM_ELEMENT_JS"
file="custom_element.js"
- type="chrome_html"
- compress="gzip"/>
+ type="chrome_html"/>
<structure
name="IDR_TAB_STRIP_TAB_GROUP_JS"
file="${root_gen_dir}/chrome/browser/resources/tab_strip/tab_group.js"
use_base_dir="false"
- type="chrome_html"
- compress="gzip"/>
+ type="chrome_html"/>
<structure
name="IDR_TAB_STRIP_TAB_LIST_JS"
file="${root_gen_dir}/chrome/browser/resources/tab_strip/tab_list.js"
use_base_dir="false"
type="chrome_html"
- compress="gzip"
preprocess="true"/>
<structure
name="IDR_TAB_STRIP_TAB_JS"
file="${root_gen_dir}/chrome/browser/resources/tab_strip/tab.js"
use_base_dir="false"
- type="chrome_html"
- compress="gzip"/>
+ type="chrome_html"/>
<structure
name="IDR_TAB_STRIP_ALERT_INDICATOR_JS"
file="${root_gen_dir}/chrome/browser/resources/tab_strip/alert_indicator.js"
use_base_dir="false"
- type="chrome_html"
- compress="gzip"/>
+ type="chrome_html"/>
<structure
name="IDR_TAB_STRIP_ALERT_INDICATORS_JS"
file="${root_gen_dir}/chrome/browser/resources/tab_strip/alert_indicators.js"
use_base_dir="false"
- type="chrome_html"
- compress="gzip"/>
+ type="chrome_html"/>
<structure
name="IDR_TAB_STRIP_EMBEDDER_PROXY_JS"
file="tab_strip_embedder_proxy.js"
- type="chrome_html"
- compress="gzip"/>
+ type="chrome_html"/>
<structure
name="IDR_TAB_STRIP_OPTIONS_JS"
file="tab_strip_options.js"
- type="chrome_html"
- compress="gzip"/>
+ type="chrome_html"/>
<structure
name="IDR_TAB_STRIP_TAB_SWIPER_JS"
file="tab_swiper.js"
- type="chrome_html"
- compress="gzip"/>
+ type="chrome_html"/>
<structure
name="IDR_TAB_STRIP_DRAG_MANAGER_JS"
file="drag_manager.js"
type="chrome_html"
- compress="gzip"
preprocess="true"/>
</structures>
@@ -87,53 +75,43 @@
<include
name="IDR_TAB_STRIP_PICTURE_IN_PICTURE_ALT_SVG"
file="alert_indicators/picture_in_picture_alt.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include
name="IDR_TAB_STRIP_SERIAL_PORT_SVG"
file="alert_indicators/serial_port.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include
name="IDR_TAB_STRIP_TAB_AUDIO_MUTING_ROUNDED_SVG"
file="alert_indicators/tab_audio_muting_rounded.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include
name="IDR_TAB_STRIP_TAB_AUDIO_ROUNDED_SVG"
file="alert_indicators/tab_audio_rounded.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include
name="IDR_TAB_STRIP_TAB_BLUETOOTH_CONNECTED_SVG"
file="alert_indicators/tab_bluetooth_connected.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include
name="IDR_TAB_STRIP_TAB_HID_CONNECTED_SVG"
file="alert_indicators/tab_hid_connected.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include
name="IDR_TAB_STRIP_TAB_MEDIA_CAPTURING_WITH_ARROW_SVG"
file="alert_indicators/tab_media_capturing_with_arrow.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include
name="IDR_TAB_STRIP_TAB_MEDIA_RECORING_SVG"
file="alert_indicators/tab_media_recording.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include
name="IDR_TAB_STRIP_TAB_USB_CONNECTED_SVG"
file="alert_indicators/tab_usb_connected.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include
name="IDR_TAB_STRIP_VR_HEADSET_SVG"
file="alert_indicators/vr_headset.svg"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/tab_strip/tabs_api_proxy.js b/chromium/chrome/browser/resources/tab_strip/tabs_api_proxy.js
index a2faa8074d7..b691666cc5a 100644
--- a/chromium/chrome/browser/resources/tab_strip/tabs_api_proxy.js
+++ b/chromium/chrome/browser/resources/tab_strip/tabs_api_proxy.js
@@ -67,7 +67,7 @@ export const TabAlertState = {
export let TabData;
/** @typedef {!Tab} */
-let ExtensionsApiTab;
+export let ExtensionsApiTab;
/**
* @typedef {{
@@ -78,40 +78,86 @@ let ExtensionsApiTab;
*/
export let TabGroupVisualData;
+/** @interface */
export class TabsApiProxy {
/**
* @param {number} tabId
* @return {!Promise<!ExtensionsApiTab>}
*/
+ activateTab(tabId) {}
+
+ createNewTab() {}
+
+ /**
+ * @return {!Promise<!Object<!TabGroupVisualData>>} Object of group IDs as
+ * strings mapped to their visual data.
+ */
+ getGroupVisualData() {}
+
+ /**
+ * @return {!Promise<!Array<!TabData>>}
+ */
+ getTabs() {}
+
+ /**
+ * @param {number} tabId
+ * @param {!CloseTabAction} closeTabAction
+ */
+ closeTab(tabId, closeTabAction) {}
+
+ /**
+ * @param {number} tabId
+ * @param {string} groupId
+ */
+ groupTab(tabId, groupId) {}
+
+ /**
+ * @param {string} groupId
+ * @param {number} newIndex
+ */
+ moveGroup(groupId, newIndex) {}
+
+ /**
+ * @param {number} tabId
+ * @param {number} newIndex
+ */
+ moveTab(tabId, newIndex) {}
+
+ /**
+ * @param {number} tabId
+ * @param {boolean} thumbnailTracked
+ */
+ setThumbnailTracked(tabId, thumbnailTracked) {}
+
+ /** @param {number} tabId */
+ ungroupTab(tabId) {}
+}
+
+/** @implements {TabsApiProxy} */
+export class TabsApiProxyImpl {
+ /** @override */
activateTab(tabId) {
return new Promise(resolve => {
chrome.tabs.update(tabId, {active: true}, resolve);
});
}
+ /** @override */
createNewTab() {
chrome.send('createNewTab');
}
- /**
- * @return {!Promise<!Object<!TabGroupVisualData>>} Object of group IDs as
- * strings mapped to their visual data.
- */
+ /** @override */
getGroupVisualData() {
return sendWithPromise('getGroupVisualData');
}
- /**
- * @return {!Promise<!Array<!TabData>>}
- */
+ /** @override */
getTabs() {
return sendWithPromise('getTabs');
}
- /**
- * @param {number} tabId
- * @param {!CloseTabAction} closeTabAction
- */
+ /** @override */
closeTab(tabId, closeTabAction) {
chrome.send(
'closeTab', [tabId, closeTabAction === CloseTabAction.SWIPED_TO_CLOSE]);
@@ -120,42 +166,30 @@ export class TabsApiProxy {
Object.keys(CloseTabAction).length);
}
- /**
- * @param {number} tabId
- * @param {string} groupId
- */
+ /** @override */
groupTab(tabId, groupId) {
chrome.send('groupTab', [tabId, groupId]);
}
- /**
- * @param {string} groupId
- * @param {number} newIndex
- */
+ /** @override */
moveGroup(groupId, newIndex) {
chrome.send('moveGroup', [groupId, newIndex]);
}
- /**
- * @param {number} tabId
- * @param {number} newIndex
- */
+ /** @override */
moveTab(tabId, newIndex) {
chrome.send('moveTab', [tabId, newIndex]);
}
- /**
- * @param {number} tabId
- * @param {boolean} thumbnailTracked
- */
+ /** @override */
setThumbnailTracked(tabId, thumbnailTracked) {
chrome.send('setThumbnailTracked', [tabId, thumbnailTracked]);
}
- /** @param {number} tabId */
+ /** @override */
ungroupTab(tabId) {
chrome.send('ungroupTab', [tabId]);
}
}
-addSingletonGetter(TabsApiProxy);
+addSingletonGetter(TabsApiProxyImpl);
diff --git a/chromium/chrome/browser/resources/tools/rollup_plugin.js b/chromium/chrome/browser/resources/tools/rollup_plugin.js
index d6c49bf8164..c70fe31f001 100644
--- a/chromium/chrome/browser/resources/tools/rollup_plugin.js
+++ b/chromium/chrome/browser/resources/tools/rollup_plugin.js
@@ -9,6 +9,8 @@ const path = require('path');
const chromeResourcesUrl = 'chrome://resources/';
const polymerUrl = 'chrome://resources/polymer/v3_0/';
+const schemeRelativeResourcesUrl = '//resources/';
+const schemeRelativePolymerUrl = '//resources/polymer/v3_0/';
// TODO: Determine whether it is worth maintaining this list vs always checking
// both directories for the existence of a file.
@@ -19,6 +21,7 @@ const nonGeneratedFiles = [
'certificates_browser_proxy.js',
'cr.m.js',
'cr_splitter.js',
+ 'plural_string_proxy.js',
];
function normalizeSlashes(filepath) {
@@ -66,6 +69,8 @@ export default function plugin(srcPath, genPath, rootPath, host, excludes) {
let pathFromPolymer = '';
if (source.startsWith(polymerUrl)) {
pathFromPolymer = source.slice(polymerUrl.length);
+ } else if (source.startsWith(schemeRelativePolymerUrl)) {
+ pathFromPolymer = source.slice(schemeRelativePolymerUrl.length);
} else if (!!origin && origin.startsWith(polymerSrcPath)) {
pathFromPolymer =
combinePaths(relativePath(polymerSrcPath, origin), source);
@@ -82,6 +87,8 @@ export default function plugin(srcPath, genPath, rootPath, host, excludes) {
let pathFromResources = '';
if (source.startsWith(chromeResourcesUrl)) {
pathFromResources = source.slice(chromeResourcesUrl.length);
+ } else if (source.startsWith(schemeRelativeResourcesUrl)) {
+ pathFromResources = source.slice(schemeRelativeResourcesUrl.length);
} else if (!!origin && origin.startsWith(resourcesSrcPath)) {
pathFromResources =
combinePaths(relativePath(resourcesSrcPath, origin), source);
diff --git a/chromium/chrome/browser/resources/unpack_pak.py b/chromium/chrome/browser/resources/unpack_pak.py
index d0c6ef69332..24b1d5f29d6 100755
--- a/chromium/chrome/browser/resources/unpack_pak.py
+++ b/chromium/chrome/browser/resources/unpack_pak.py
@@ -24,18 +24,31 @@ from grit.format import data_pack
def ParseLine(line):
return re.match(' {"([^"]+)", ([^},]+)', line)
-def GetFileAndDirName(out_path, pak_dir, resource_path):
- dirname = os.path.dirname(resource_path)
- # When files are generated, |dirname| becomes
- # @out_folder@/<gen_path>/path_to_resource. To make the structure look as if
- # this file was not generated, remove @out_folder@ and <gen_path>.
- if ('@out_folder@' in dirname):
- dirname = os.path.relpath(dirname, os.path.join('@out_folder@', pak_dir))
- filename = os.path.basename(resource_path)
- dirname = os.path.join(out_path, dirname)
- return (filename, dirname)
-
-def Unpack(pak_path, out_path):
+def UnpackResource(root_dir, out_path, excludes, resource_path, resource_text):
+ dirname = os.path.dirname(resource_path)
+ # When files are generated, |dirname| becomes
+ # @out_folder@/<gen_path>/path_to_resource. To make the structure look as if
+ # this file was not generated, remove @out_folder@ and <gen_path>.
+ if ('@out_folder@' in dirname):
+ dirname = os.path.relpath(dirname, os.path.join('@out_folder@', root_dir))
+ filename = os.path.basename(resource_path)
+ resource_path = os.path.join(dirname, filename).replace('\\', '/')
+ if (resource_path in excludes):
+ return
+
+ out_dir = os.path.normpath(
+ os.path.join(out_path, dirname)).replace('\\', '/')
+ assert out_dir.startswith(out_path), \
+ 'Cannot unpack files to locations not in %s. %s should be removed ' \
+ 'from the pak file or excluded from unpack.' \
+ % (out_path, resource_path)
+
+ if not os.path.exists(out_dir):
+ os.makedirs(out_dir)
+ with open(os.path.join(out_dir, filename), 'w') as file:
+ file.write(resource_text)
+
+def Unpack(pak_path, out_path, pak_base_dir, excludes):
pak_dir = os.path.dirname(pak_path)
pak_id = os.path.splitext(os.path.basename(pak_path))[0]
@@ -62,23 +75,25 @@ def Unpack(pak_path, out_path):
resource_filenames[res.group(2)] = res.group(1)
assert resource_filenames
+ root_dir = pak_base_dir if pak_base_dir else pak_dir
# Extract packed files, while preserving directory structure.
for (resource_id, text) in data.resources.iteritems():
- (filename, dirname) = GetFileAndDirName(
- out_path, pak_dir, resource_filenames[resource_ids[resource_id]])
- if not os.path.exists(dirname):
- os.makedirs(dirname)
- with open(os.path.join(dirname, filename), 'w') as file:
- file.write(text)
-
+ UnpackResource(root_dir, out_path, excludes or [],
+ resource_filenames[resource_ids[resource_id]], text)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--pak_file')
parser.add_argument('--out_folder')
+ # The expected reference point/root path for files appearing in the pak file.
+ # If this argument is not provided, the location of the pak file will be used
+ # by default.
+ parser.add_argument('--pak_base_dir')
+ # Resources in the pak file which should not be unpacked.
+ parser.add_argument('--excludes', nargs='*')
args = parser.parse_args()
- Unpack(args.pak_file, args.out_folder)
+ Unpack(args.pak_file, args.out_folder, args.pak_base_dir, args.excludes)
timestamp_file_path = os.path.join(args.out_folder, _TIMESTAMP_FILENAME)
with open(timestamp_file_path, 'a'):
diff --git a/chromium/chrome/browser/resources/unpack_pak_test.py b/chromium/chrome/browser/resources/unpack_pak_test.py
index 6572d9bc0d0..dd0ccb1dda5 100755
--- a/chromium/chrome/browser/resources/unpack_pak_test.py
+++ b/chromium/chrome/browser/resources/unpack_pak_test.py
@@ -4,10 +4,34 @@
# found in the LICENSE file.
import unpack_pak
+import tempfile
+import os
+import shutil
import unittest
+_HERE_DIR = os.path.dirname(__file__)
class UnpackPakTest(unittest.TestCase):
+ def setUp(self):
+ self._out_folder = None
+ self._tmp_dirs = []
+
+ def tearDown(self):
+ for tmp_dir in self._tmp_dirs:
+ shutil.rmtree(tmp_dir)
+
+ def _setup_output_dirs(self):
+ tmp_dir = tempfile.mkdtemp(dir=_HERE_DIR)
+ self._tmp_dirs.append(tmp_dir)
+ self._root_output_dir = os.path.join(tmp_dir, 'gen', 'mywebui')
+ os.makedirs(self._root_output_dir)
+ self._unpak_dir = os.path.normpath(
+ os.path.join(self._root_output_dir, 'unpak')).replace('\\', '/')
+
+ def _read_unpacked_file(self, file_name):
+ assert self._unpak_dir
+ return open(os.path.join(self._unpak_dir, file_name), 'r').read()
+
def testMapFileLine(self):
self.assertTrue(unpack_pak.ParseLine(' {"path.js", IDR_PATH}'))
@@ -15,18 +39,35 @@ class UnpackPakTest(unittest.TestCase):
self.assertTrue(unpack_pak.ParseLine(' {"path.js", IDR_PATH, false}'))
self.assertTrue(unpack_pak.ParseLine(' {"path.js", IDR_PATH, true}'))
- def testGetFileAndDirName(self):
- (f, d) = unpack_pak.GetFileAndDirName(
- 'out/build/gen/foo/foo.unpak', 'out/build/gen/foo', 'a/b.js')
- self.assertEquals('b.js', f)
- self.assertEquals('out/build/gen/foo/foo.unpak/a', d)
-
- def testGetFileAndDirNameForGeneratedResource(self):
- (f, d) = unpack_pak.GetFileAndDirName(
- 'out/build/gen/foo/foo.unpak', 'out/build/gen/foo',
- '@out_folder@/out/build/gen/foo/a/b.js')
- self.assertEquals('b.js', f)
- self.assertEquals('out/build/gen/foo/foo.unpak/a', d)
+ def testUnpackResource(self):
+ self._setup_output_dirs()
+ unpack_pak.UnpackResource(
+ os.path.join('gen', 'mywebui'), self._unpak_dir, [],
+ 'sub_dir/some_element.js', 'alert(\'hello from element in sub_dir\');')
+ unpacked_contents = self._read_unpacked_file('sub_dir/some_element.js')
+ self.assertIn('hello from element in sub_dir', unpacked_contents)
+
+ def testUnpackGeneratedResource(self):
+ self._setup_output_dirs()
+ generated_resource_path = os.path.join(
+ '@out_folder@', 'gen', 'mywebui', 'sub_dir', 'some_element.js')
+ unpack_pak.UnpackResource(
+ os.path.join('gen', 'mywebui'), self._unpak_dir,
+ [], generated_resource_path,
+ 'alert(\'hello from element in sub_dir\');')
+ unpacked_contents = self._read_unpacked_file('sub_dir/some_element.js')
+ self.assertIn('hello from element in sub_dir', unpacked_contents)
+
+ def testUnpackExcludedResource(self):
+ self._setup_output_dirs()
+ generated_shared_resource_path = os.path.join(
+ '@out_folder@', 'gen', 'shared', 'shared_element.js')
+ self.assertEqual(0, len(os.listdir(self._root_output_dir)))
+ unpack_pak.UnpackResource(
+ os.path.join('gen', 'mywebui'), self._unpak_dir,
+ ['../shared/shared_element.js'], generated_shared_resource_path,
+ 'alert(\'hello from shared element\');')
+ self.assertEqual(0, len(os.listdir(self._root_output_dir)))
if __name__ == '__main__':
unittest.main()
diff --git a/chromium/chrome/browser/resources/usb_internals/resources.grd b/chromium/chrome/browser/resources/usb_internals/resources.grd
index 48bc89841bd..68f7a927a57 100644
--- a/chromium/chrome/browser/resources/usb_internals/resources.grd
+++ b/chromium/chrome/browser/resources/usb_internals/resources.grd
@@ -12,31 +12,25 @@
<includes>
<include name="IDR_USB_INTERNALS_CSS"
file="usb_internals.css"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_USB_INTERNALS_DESCRIPTOR_PANEL_JS"
file="descriptor_panel.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_USB_INTERNALS_DEVICES_PAGE_JS"
file="devices_page.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_USB_INTERNALS_HTML"
file="usb_internals.html"
flattenhtml="true"
allowexternalscript="true"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_USB_INTERNALS_JS"
file="usb_internals.js"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
<include name="IDR_USB_INTERNALS_MOJOM_LITE_JS"
file="${root_gen_dir}\chrome\browser\ui\webui\usb_internals\usb_internals.mojom-lite.js"
use_base_dir="false"
- type="BINDATA"
- compress="gzip" />
+ type="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/user_manager/create_profile.js b/chromium/chrome/browser/resources/user_manager/create_profile.js
index ca0c2d6858b..da2cff63f83 100644
--- a/chromium/chrome/browser/resources/user_manager/create_profile.js
+++ b/chromium/chrome/browser/resources/user_manager/create_profile.js
@@ -202,15 +202,7 @@ Polymer({
* @private
*/
i18nAllowIDAttr_(id) {
- const opts = {
- 'attrs': {
- 'id'(node, value) {
- return node.tagName == 'A';
- }
- }
- };
-
- return this.i18nAdvanced(id, opts);
+ return this.i18nAdvanced(id, {attrs: ['id']});
},
/**
diff --git a/chromium/chrome/browser/resources/web_app_internals/BUILD.gn b/chromium/chrome/browser/resources/web_app_internals/BUILD.gn
new file mode 100644
index 00000000000..a02c5b41cf8
--- /dev/null
+++ b/chromium/chrome/browser/resources/web_app_internals/BUILD.gn
@@ -0,0 +1,22 @@
+# Copyright 2020 The Chromium 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")
+import("//tools/polymer/html_to_js.gni")
+
+html_to_js("components") {
+ js_files = [ "web_app_internals.js" ]
+}
+
+js_type_check("closure_compile") {
+ is_polymer3 = true
+ deps = [ ":web_app_internals" ]
+}
+
+js_library("web_app_internals") {
+ deps = [
+ "//chrome/browser/ui/webui/internals/web_app:mojo_bindings_js_library_for_compile",
+ "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled",
+ ]
+}
diff --git a/chromium/chrome/browser/resources/web_app_internals/OWNERS b/chromium/chrome/browser/resources/web_app_internals/OWNERS
new file mode 100644
index 00000000000..1255a2cc323
--- /dev/null
+++ b/chromium/chrome/browser/resources/web_app_internals/OWNERS
@@ -0,0 +1 @@
+file://chrome/browser/web_applications/OWNERS
diff --git a/chromium/chrome/browser/resources/web_app_internals/index.html b/chromium/chrome/browser/resources/web_app_internals/index.html
new file mode 100644
index 00000000000..9cbae310a6f
--- /dev/null
+++ b/chromium/chrome/browser/resources/web_app_internals/index.html
@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
+ <title>Web App Internals</title>
+ </head>
+ <body>
+ <web-app-internals></web-app-internals>
+ <script type="module" src="web_app_internals.js"></script>
+ </body>
+</html>
diff --git a/chromium/chrome/browser/resources/web_app_internals/web_app_internals.html b/chromium/chrome/browser/resources/web_app_internals/web_app_internals.html
new file mode 100644
index 00000000000..2982293b591
--- /dev/null
+++ b/chromium/chrome/browser/resources/web_app_internals/web_app_internals.html
@@ -0,0 +1,76 @@
+<style>
+ h2 {
+ margin-bottom: 10px;
+ margin-top: 0;
+ }
+
+ .section {
+ margin: 10px;
+ margin-bottom: 20px;
+ padding: 5px;
+ }
+
+ .web-app {
+ background-color: var(--highlight, #00000007);
+ border-inline-start-color: rgb(0, 50, 220);
+ border-inline-start-style: solid;
+ }
+
+ .highlight {
+ --highlight: #eff;
+ }
+
+ .web-app-name {
+ font-weight: bold;
+ }
+</style>
+
+<h1>Web App Internals</h1>
+
+<div class="section">
+ BMO enabled: <b>[[isBmoEnabled_]]</b>
+ <template is="dom-if" if="[[!isBmoEnabled_]]">
+ <p>
+ Web apps are using the extension system via bookmark apps, see
+ <a href="chrome://extensions-internals">
+ chrome://extensions-internals
+ </a>
+ for bookmark app details.
+ </p>
+ <p>
+ Enable BMO via
+ <a href="chrome://flags/#enable-desktop-pwas-without-extensions">
+ chrome://flags/#enable-desktop-pwas-without-extensions.
+ </a>
+ </p>
+ </template>
+</div>
+
+<div class="section">
+ <h2>Page index:</h2>
+ <template is="dom-repeat" items="[[webAppList_]]">
+ <div>
+ <a href="#[[item.id]]">
+ <img src="chrome://app-icon/[[item.id]]/32">
+ [[item.name]]
+ </a>
+ </div>
+ </template>
+ <a href="#external">Externally installed web app prefs</a>
+</div>
+
+<div class="section">
+ <h2 id="details">Web apps details:</h2>
+ <template is="dom-repeat" items="[[webAppList_]]">
+ <div class="section web-app" id="[[item.id]]">
+ <h2>[[item.name]]</h2>
+ <img src="chrome://app-icon/[[item.id]]/128">
+ <pre>[[item.debugInfo]]</pre>
+ </div>
+ </template>
+</div>
+
+<div class="section" id="external">
+ <h2>Externally installed web app prefs:</h2>
+ <pre>[[externallyInstalledWebAppPrefs_]]</pre>
+</div>
diff --git a/chromium/chrome/browser/resources/web_app_internals/web_app_internals.js b/chromium/chrome/browser/resources/web_app_internals/web_app_internals.js
new file mode 100644
index 00000000000..dfc512aa1b6
--- /dev/null
+++ b/chromium/chrome/browser/resources/web_app_internals/web_app_internals.js
@@ -0,0 +1,88 @@
+// Copyright 2020 The Chromium 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 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js';
+import './web_app_internals.mojom-lite.js';
+import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
+
+Polymer({
+ is: 'web-app-internals',
+
+ _template: html`{__html_template__}`,
+
+ properties: {
+ /**
+ * Whether Bookmark apps off Extensions is enabled.
+ * @private {!boolean}
+ */
+ isBmoEnabled_: Boolean,
+
+ /**
+ * List of internal details about installed web apps.
+ * @private {!Array<!mojom.webAppInternals.WebApp>}
+ */
+ webAppList_: Array,
+
+ /**
+ * Prefs associated with non-user installed web apps.
+ * @private {!string}
+ */
+ externallyInstalledWebAppPrefs_: String,
+ },
+
+ /**
+ * @override
+ * Fetches internal data about installed web apps from the browser.
+ */
+ ready() {
+ (async () => {
+ const remote =
+ mojom.webAppInternals.WebAppInternalsPageHandler.getRemote();
+
+ this.isBmoEnabled_ = (await remote.isBmoEnabled()).isBmoEnabled;
+
+ this.webAppList_ = (await remote.getWebApps()).webAppList;
+ this.webAppList_.sort((a, b) => a.name.localeCompare(b.name));
+
+ this.externallyInstalledWebAppPrefs_ =
+ (await remote.getExternallyInstalledWebAppPrefs())
+ .externallyInstalledWebAppPrefs;
+
+ this.highlightHashedId_();
+ this.hashChangeListener_ = () => this.highlightHashedId_();
+ window.addEventListener('hashchange', this.hashChangeListener_);
+ })();
+ },
+
+ /**
+ * @override
+ * Cleans up global event listeners.
+ */
+ detached() {
+ window.removeEventListener('hashchange', this.hashChangeListener_);
+ },
+
+ /**
+ * Reads the current URL hash, scrolls the targeted element into view and
+ * highlights it.
+ * @private
+ */
+ highlightHashedId_() {
+ for (const element of this.shadowRoot.querySelectorAll('.highlight')) {
+ element.classList.remove('highlight');
+ }
+
+ if (!location.hash) {
+ return;
+ }
+
+ const highlighted = this.shadowRoot.querySelector(location.hash);
+ if (!highlighted) {
+ return;
+ }
+
+ highlighted.scrollIntoView();
+ highlighted.classList.add('highlight');
+ },
+});
diff --git a/chromium/chrome/browser/resources/webapks/webapks_ui_resources.grd b/chromium/chrome/browser/resources/webapks/webapks_ui_resources.grd
index a744953fce7..e1bae8d7ae2 100644
--- a/chromium/chrome/browser/resources/webapks/webapks_ui_resources.grd
+++ b/chromium/chrome/browser/resources/webapks/webapks_ui_resources.grd
@@ -8,9 +8,9 @@
</outputs>
<release seq="1">
<includes>
- <include name="IDR_WEBAPKS_UI_CSS" file="about_webapks.css" type="BINDATA" compress="gzip" />
- <include name="IDR_WEBAPKS_UI_HTML" file="about_webapks.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" compress="gzip" />
- <include name="IDR_WEBAPKS_UI_JS" file="about_webapks.js" type="BINDATA" compress="gzip" />
+ <include name="IDR_WEBAPKS_UI_CSS" file="about_webapks.css" type="BINDATA" />
+ <include name="IDR_WEBAPKS_UI_HTML" file="about_webapks.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
+ <include name="IDR_WEBAPKS_UI_JS" file="about_webapks.js" type="BINDATA" />
</includes>
</release>
</grit>
diff --git a/chromium/chrome/browser/resources/welcome/welcome_resources.grd b/chromium/chrome/browser/resources/welcome/welcome_resources.grd
index 5a9e022c50c..64ba34f9eef 100644
--- a/chromium/chrome/browser/resources/welcome/welcome_resources.grd
+++ b/chromium/chrome/browser/resources/welcome/welcome_resources.grd
@@ -16,149 +16,127 @@
<includes>
<include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_BLUE_CIRCLE_SVG"
file="images/background_svgs/blue_circle.svg"
- compress="gzip"
type="BINDATA" />
<include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_GREEN_RECTANGLE_SVG"
file="images/background_svgs/green_rectangle.svg"
- compress="gzip"
type="BINDATA" />
<include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_GREY_OVAL_SVG"
file="images/background_svgs/grey_oval.svg"
- compress="gzip"
type="BINDATA" />
<include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_GREY_ROUNDED_RECTANGLE_SVG"
file="images/background_svgs/grey_rounded_rectangle.svg"
- compress="gzip"
type="BINDATA" />
<include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_RED_TRIANGLE_SVG"
file="images/background_svgs/red_triangle.svg"
- compress="gzip"
type="BINDATA" />
<include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_YELLOW_DOTS_SVG"
file="images/background_svgs/yellow_dots.svg"
- compress="gzip"
type="BINDATA" />
<include name="IDR_WELCOME_IMAGES_BACKGROUND_SVGS_YELLOW_SEMICIRCLE_SVG"
file="images/background_svgs/yellow_semicircle.svg"
- compress="gzip"
type="BINDATA" />
<!-- Generated Polymer 3 elements -->
<include name="IDR_WELCOME_APP_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/welcome_app.js"
- use_base_dir="false" type="BINDATA" compress="gzip" preprocess="true"/>
+ use_base_dir="false" type="BINDATA" preprocess="true"/>
<include name="IDR_GOOGLE_APPS_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/google_apps/nux_google_apps.js"
- use_base_dir="false" type="BINDATA" compress="gzip" preprocess="true"/>
+ use_base_dir="false" type="BINDATA" preprocess="true"/>
<include name="IDR_SET_AS_DEFAULT_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/set_as_default/nux_set_as_default.js"
- use_base_dir="false" type="BINDATA" compress="gzip" preprocess="true"/>
+ use_base_dir="false" type="BINDATA" preprocess="true"/>
<include name="IDR_WELCOME_LANDING_VIEW_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/landing_view.js"
- use_base_dir="false" type="BINDATA" compress="gzip"/>
+ use_base_dir="false" type="BINDATA"/>
<include name="IDR_WELCOME_SIGNIN_VIEW_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/signin_view.js"
- use_base_dir="false" type="BINDATA" compress="gzip"/>
+ use_base_dir="false" type="BINDATA"/>
<include name="IDR_NTP_BACKGROUND_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/ntp_background/nux_ntp_background.js"
- use_base_dir="false" type="BINDATA" compress="gzip"/>
+ use_base_dir="false" type="BINDATA"/>
<include name="IDR_WELCOME_SHARED_STEP_INDICATOR_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/shared/step_indicator.js"
- use_base_dir="false" type="BINDATA" compress="gzip"/>
+ use_base_dir="false" type="BINDATA"/>
<include name="IDR_WELCOME_SHARED_ONBOARDING_BACKGROUND_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/shared/onboarding_background.js"
- use_base_dir="false" type="BINDATA" compress="gzip"/>
+ use_base_dir="false" type="BINDATA"/>
<!-- Generated style files -->
<include name="IDR_WELCOME_SHARED_ANIMATIONS_CSS_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/shared/animations_css.js"
- use_base_dir="false" type="BINDATA" compress="gzip"/>
+ use_base_dir="false" type="BINDATA"/>
<include name="IDR_WELCOME_SHARED_CHOOSER_SHARED_CSS_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/shared/chooser_shared_css.js"
- use_base_dir="false" type="BINDATA" compress="gzip"/>
+ use_base_dir="false" type="BINDATA"/>
<include name="IDR_WELCOME_SHARED_NAVI_COLORS_CSS_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/shared/navi_colors_css.js"
- use_base_dir="false" type="BINDATA" compress="gzip"/>
+ use_base_dir="false" type="BINDATA"/>
<include name="IDR_WELCOME_SHARED_ACTION_LINK_STYLE_CSS_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/shared/action_link_style_css.js"
- use_base_dir="false" type="BINDATA" compress="gzip"/>
+ use_base_dir="false" type="BINDATA"/>
<include name="IDR_WELCOME_SHARED_SPLASH_PAGES_SHARED_CSS_JS"
file="${root_gen_dir}/chrome/browser/resources/welcome/shared/splash_pages_shared_css.js"
- use_base_dir="false" type="BINDATA" compress="gzip"/>
+ use_base_dir="false" type="BINDATA"/>
</includes>
<structures>
<structure name="IDR_WELCOME_LANDING_VIEW_PROXY_JS"
file="landing_view_proxy.js"
type="chrome_html"
- compress="gzip"
preprocess="true"/>
<structure name="IDR_WELCOME_NAVIGATION_BEHAVIOR_JS"
file="navigation_behavior.js"
type="chrome_html"
- compress="gzip"
preprocess="true"/>
<structure name="IDR_WELCOME_SHARED_BOOKMARK_PROXY_JS"
file="shared/bookmark_proxy.js"
- compress="gzip"
type="chrome_html" />
<structure name="IDR_WELCOME_SHARED_MODULE_METRICS_PROXY_JS"
file="shared/module_metrics_proxy.js"
- compress="gzip"
type="chrome_html" />
<structure name="IDR_WELCOME_SHARED_NUX_TYPES_JS"
file="shared/nux_types.js"
- compress="gzip"
type="chrome_html" />
<structure name="IDR_WELCOME_SIGNIN_VIEW_PROXY_JS"
file="signin_view_proxy.js"
type="chrome_html"
- compress="gzip"
preprocess="true"/>
<structure name="IDR_WELCOME_BROWSER_PROXY_JS"
file="welcome_browser_proxy.js"
- compress="gzip"
type="chrome_html"/>
<structure name="IDR_WELCOME_CSS"
file="welcome.css"
type="chrome_html"
- compress="gzip"
preprocess="true"/>
<structure name="IDR_WELCOME_HTML"
file="welcome.html"
type="chrome_html"
- compress="gzip"
preprocess="true"/>
<structure name="IDR_WELCOME_JS"
file="welcome.js"
type="chrome_html"
- compress="gzip"
preprocess="true"/>
<!-- Google apps-->
<structure name="IDR_GOOGLE_APP_PROXY_JS"
file="google_apps/google_app_proxy.js"
- 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" />
<!-- Set as default-->
<structure name="IDR_SET_AS_DEFAULT_PROXY_JS"
file="set_as_default/nux_set_as_default_proxy.js"
- compress="gzip"
type="chrome_html" />
<!-- NTP background-->
<structure name="IDR_NTP_BACKGROUND_PROXY_JS"
file="ntp_background/ntp_background_proxy.js"
- compress="gzip"
type="chrome_html" />
<structure name="IDR_NTP_BACKGROUND_METRICS_PROXY_JS"
file="ntp_background/ntp_background_metrics_proxy.js"
- compress="gzip"
type="chrome_html" />
</structures>
</release>
diff --git a/chromium/chrome/browser/safe_browsing/BUILD.gn b/chromium/chrome/browser/safe_browsing/BUILD.gn
index d041bd3f61a..82edacf2604 100644
--- a/chromium/chrome/browser/safe_browsing/BUILD.gn
+++ b/chromium/chrome/browser/safe_browsing/BUILD.gn
@@ -20,6 +20,7 @@ static_library("safe_browsing") {
"//chrome/common",
"//chrome/common:constants",
"//components/browser_sync",
+ "//components/enterprise/common:strings",
"//components/keyed_service/content",
"//components/language/core/browser",
"//components/page_info",
@@ -242,6 +243,8 @@ static_library("safe_browsing") {
]
deps += [
":advanced_protection",
+ ":chrome_enterprise_url_lookup_service",
+ ":chrome_enterprise_url_lookup_service_factory",
"//chrome/common/safe_browsing:archive_analyzer_results",
"//chrome/common/safe_browsing:binary_feature_extractor",
"//chrome/common/safe_browsing:disk_image_type_sniffer_mac",
@@ -263,14 +266,13 @@ static_library("safe_browsing") {
}
} else if (safe_browsing_mode == 2) {
sources += [
- "android/safe_browsing_bridge.cc",
"android/services_delegate_android.cc",
"android/services_delegate_android.h",
"telemetry/android/android_telemetry_service.cc",
"telemetry/android/android_telemetry_service.h",
]
deps += [
- "//chrome/android:jni_headers",
+ "//chrome/browser/safe_browsing/android",
"//components/safe_browsing:buildflags",
"//components/safe_browsing/android:safe_browsing_mobile",
]
@@ -278,6 +280,36 @@ static_library("safe_browsing") {
}
}
+source_set("chrome_enterprise_url_lookup_service_factory") {
+ sources = [
+ "chrome_enterprise_url_lookup_service_factory.cc",
+ "chrome_enterprise_url_lookup_service_factory.h",
+ ]
+
+ deps = [
+ ":chrome_enterprise_url_lookup_service",
+ ":verdict_cache_manager_factory",
+ "//chrome/common",
+ "//components/keyed_service/content",
+ "//content/public/browser",
+ ]
+}
+
+source_set("chrome_enterprise_url_lookup_service") {
+ sources = [
+ "chrome_enterprise_url_lookup_service.cc",
+ "chrome_enterprise_url_lookup_service.h",
+ ]
+
+ deps = [
+ "//components/safe_browsing/core:realtimeapi_proto",
+ "//components/safe_browsing/core:verdict_cache_manager",
+ "//components/safe_browsing/core/realtime:policy_engine",
+ "//components/safe_browsing/core/realtime:url_lookup_service_base",
+ "//services/network/public/cpp:cpp",
+ ]
+}
+
source_set("url_lookup_service_factory") {
sources = [
"url_lookup_service_factory.cc",
diff --git a/chromium/chrome/browser/safe_browsing/android/BUILD.gn b/chromium/chrome/browser/safe_browsing/android/BUILD.gn
new file mode 100644
index 00000000000..e6473eafd3b
--- /dev/null
+++ b/chromium/chrome/browser/safe_browsing/android/BUILD.gn
@@ -0,0 +1,28 @@
+# Copyright 2020 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//build/config/android/rules.gni")
+
+generate_jni("jni_headers") {
+ sources = [ "java/src/org/chromium/chrome/browser/safe_browsing/SafeBrowsingBridge.java" ]
+}
+
+source_set("android") {
+ sources = [ "safe_browsing_bridge.cc" ]
+ deps = [
+ ":jni_headers",
+ "//components/prefs",
+ "//components/safe_browsing/core:file_type_policies",
+ "//components/safe_browsing/core/common:safe_browsing_prefs",
+ ]
+}
+
+android_library("java") {
+ sources = [ "java/src/org/chromium/chrome/browser/safe_browsing/SafeBrowsingBridge.java" ]
+ deps = [
+ "//base:base_java",
+ "//base:jni_java",
+ ]
+ annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ]
+}
diff --git a/chromium/chrome/browser/safety_check/android/BUILD.gn b/chromium/chrome/browser/safety_check/android/BUILD.gn
new file mode 100644
index 00000000000..e4cb0fe7af3
--- /dev/null
+++ b/chromium/chrome/browser/safety_check/android/BUILD.gn
@@ -0,0 +1,90 @@
+# Copyright 2020 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//build/config/android/rules.gni")
+
+generate_jni("jni_headers") {
+ sources = [
+ "java/src/org/chromium/chrome/browser/safety_check/SafetyCheckBridge.java",
+ ]
+}
+
+source_set("android") {
+ sources = [
+ "safety_check_bridge.cc",
+ "safety_check_bridge.h",
+ ]
+ deps = [
+ ":jni_headers",
+ "//components/prefs",
+ "//components/safety_check",
+ ]
+}
+
+android_library("java") {
+ sources = [
+ "java/src/org/chromium/chrome/browser/safety_check/SafetyCheckBridge.java",
+ "java/src/org/chromium/chrome/browser/safety_check/SafetyCheckController.java",
+ "java/src/org/chromium/chrome/browser/safety_check/SafetyCheckElement.java",
+ "java/src/org/chromium/chrome/browser/safety_check/SafetyCheckModel.java",
+ "java/src/org/chromium/chrome/browser/safety_check/SafetyCheckSettingsFragment.java",
+ ]
+ deps = [
+ ":java_resources",
+ "//base:base_java",
+ "//base:jni_java",
+ "//components/browser_ui/settings/android:java",
+ "//third_party/android_deps:android_support_v7_appcompat_java",
+ "//third_party/android_deps:androidx_fragment_fragment_java",
+ "//third_party/android_deps:androidx_preference_preference_java",
+ "//ui/android:ui_full_java",
+ ]
+ annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ]
+ srcjar_deps = [
+ ":bulk_leak_check_service_enums",
+ ":safety_check_enums",
+ ]
+}
+
+android_library("junit") {
+ # Skip platform checks since Robolectric depends on requires_android targets.
+ bypass_platform_checks = true
+ testonly = true
+ sources = [
+ "javatests/src/org/chromium/chrome/browser/safety_check/SafetyCheckBridgeTest.java",
+ "javatests/src/org/chromium/chrome/browser/safety_check/SafetyCheckModelTest.java",
+ ]
+ deps = [
+ ":java",
+ "//base:base_java",
+ "//base:base_java_test_support",
+ "//base:base_junit_test_support",
+ "//base/test:test_support_java",
+ "//chrome/browser/preferences:java",
+ "//third_party/junit:junit",
+ "//third_party/mockito:mockito_java",
+ ]
+}
+
+android_resources("java_resources") {
+ sources = [
+ "java/res/layout/safety_check_button.xml",
+ "java/res/values/dimens.xml",
+ "java/res/xml/safety_check_preferences.xml",
+ ]
+ deps = [
+ "//chrome/browser/ui/android/strings:ui_strings_grd",
+ "//components/browser_ui/settings/android:java_resources",
+ "//components/browser_ui/styles/android:java_resources",
+ ]
+ custom_package = "org.chromium.chrome.browser.safety_check"
+}
+
+java_cpp_enum("safety_check_enums") {
+ sources = [ "//components/safety_check/safety_check.h" ]
+}
+
+java_cpp_enum("bulk_leak_check_service_enums") {
+ sources = [ "//components/password_manager/core/browser/bulk_leak_check_service_interface.h" ]
+}
diff --git a/chromium/chrome/browser/settings/BUILD.gn b/chromium/chrome/browser/settings/BUILD.gn
index 3de774ae89e..255e091fbe1 100644
--- a/chromium/chrome/browser/settings/BUILD.gn
+++ b/chromium/chrome/browser/settings/BUILD.gn
@@ -30,12 +30,14 @@ android_library("javatests") {
":test_support_java",
"//chrome/android:chrome_java",
"//chrome/test/android:chrome_java_test_support",
+ "//components/browser_ui/settings/android:java",
"//content/public/test/android:content_java_test_support",
"//third_party/android_deps:android_support_v7_appcompat_java",
"//third_party/android_deps:androidx_preference_preference_java",
+ "//third_party/android_deps:espresso_java",
"//third_party/android_support_test_runner:rules_java",
"//third_party/android_support_test_runner:runner_java",
- "//third_party/espresso:espresso_all_java",
+ "//third_party/guava:guava_android_java",
"//third_party/hamcrest:hamcrest_java",
"//third_party/junit",
]
@@ -47,9 +49,13 @@ android_library("test_support_java") {
sources = [ "android/java/src/org/chromium/chrome/browser/settings/SettingsActivityTestRule.java" ]
deps = [
+ "//base:base_java",
"//chrome/android:chrome_java",
+ "//chrome/browser/settings:java",
"//content/public/test/android:content_java_test_support",
"//third_party/android_deps:androidx_preference_preference_java",
"//third_party/android_support_test_runner:rules_java",
+ "//third_party/android_support_test_runner:runner_java",
+ "//third_party/junit",
]
}
diff --git a/chromium/chrome/browser/share/BUILD.gn b/chromium/chrome/browser/share/BUILD.gn
index f985017e519..6045a6af331 100644
--- a/chromium/chrome/browser/share/BUILD.gn
+++ b/chromium/chrome/browser/share/BUILD.gn
@@ -4,6 +4,8 @@
source_set("share") {
sources = [
+ "bitmap_download_request.cc",
+ "bitmap_uri_request.cc",
"features.cc",
"features.h",
"qr_code_generation_request.cc",
diff --git a/chromium/chrome/browser/share/android/BUILD.gn b/chromium/chrome/browser/share/android/BUILD.gn
index a2f5d566a68..31e1051eb6e 100644
--- a/chromium/chrome/browser/share/android/BUILD.gn
+++ b/chromium/chrome/browser/share/android/BUILD.gn
@@ -7,12 +7,17 @@ import("//build/config/android/rules.gni")
android_resources("java_resources") {
sources = [
"java/res/drawable/camera_img.xml",
+ "java/res/drawable/delete.xml",
+ "java/res/drawable/edit.xml",
"java/res/drawable/qrcode_background.xml",
+ "java/res/drawable/save.xml",
+ "java/res/drawable/share.xml",
"java/res/layout/qrcode_camera_error_layout.xml",
"java/res/layout/qrcode_dialog.xml",
"java/res/layout/qrcode_open_settings_layout.xml",
"java/res/layout/qrcode_permission_layout.xml",
"java/res/layout/qrcode_share_layout.xml",
+ "java/res/layout/screenshot_share_sheet.xml",
"java/res/values-night/colors.xml",
"java/res/values-sw600dp/dimens.xml",
"java/res/values/colors.xml",
@@ -22,5 +27,9 @@ android_resources("java_resources") {
}
generate_jni("jni_headers") {
- sources = [ "java/src/org/chromium/chrome/browser/share/qrcode/QRCodeGenerationRequest.java" ]
+ sources = [
+ "java/src/org/chromium/chrome/browser/share/BitmapDownloadRequest.java",
+ "java/src/org/chromium/chrome/browser/share/BitmapUriRequest.java",
+ "java/src/org/chromium/chrome/browser/share/qrcode/QRCodeGenerationRequest.java",
+ ]
}
diff --git a/chromium/chrome/browser/share/android/java_sources.gni b/chromium/chrome/browser/share/android/java_sources.gni
index 83b88104972..0efd97e290e 100644
--- a/chromium/chrome/browser/share/android/java_sources.gni
+++ b/chromium/chrome/browser/share/android/java_sources.gni
@@ -5,15 +5,14 @@
# TODO(crbug/1022172): This should be a separate build target when circular
# dependencies are removed.
share_java_sources = [
- "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/SaveImageNotificationManager.java",
- "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/ShareImageFileUtils.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/BitmapDownloadRequest.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/BitmapUriRequest.java",
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/clipboard/ClipboardImageFileProvider.java",
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/qrcode/QRCodeGenerationRequest.java",
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/qrcode/QrCodeCoordinator.java",
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/qrcode/QrCodeDialog.java",
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/qrcode/QrCodeDialogTab.java",
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/qrcode/QrCodePageAdapter.java",
- "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/qrcode/QrCodeShareActivity.java",
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/qrcode/TabLayoutPageListener.java",
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/qrcode/scan_tab/CameraPreview.java",
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/qrcode/scan_tab/CameraPreviewOverlay.java",
@@ -28,4 +27,18 @@ share_java_sources = [
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/qrcode/share_tab/QrCodeShareViewBinder.java",
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/qrcode/share_tab/QrCodeShareViewProperties.java",
"//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotCoordinator.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotShareSheetCoordinator.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotShareSheetDialog.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotShareSheetDialogCoordinator.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotShareSheetMediator.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotShareSheetSaveDelegate.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotShareSheetView.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotShareSheetViewBinder.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotShareSheetViewProperties.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/share_sheet/ChromeOptionShareCallback.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/share_sheet/ChromeProvidedSharingOptionsProvider.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/share_sheet/ShareSheetBottomSheetContent.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/share_sheet/ShareSheetCoordinator.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/share_sheet/ShareSheetItemViewProperties.java",
+ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/share_sheet/ShareSheetPropertyModelBuilder.java",
]
diff --git a/chromium/chrome/browser/share/android/test_java_sources.gni b/chromium/chrome/browser/share/android/test_java_sources.gni
index 9b4b3a09254..b7e09b1aa25 100644
--- a/chromium/chrome/browser/share/android/test_java_sources.gni
+++ b/chromium/chrome/browser/share/android/test_java_sources.gni
@@ -4,6 +4,11 @@
# TODO(crbug.com/1022172): This should be a separate build target when circular dependencies are removed.
share_test_java_sources = [
- "//chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/ShareImageFileUtilsTest.java",
"//chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/clipboard/ClipboardImageFileProviderTest.java",
+ "//chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/screenshot/ScreenshotShareSheetViewTest.java",
+ "//chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/share_sheet/ChromeProvidedSharingOptionsProviderTest.java",
+ "//chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/share_sheet/ShareSheetCoordinatorTest.java",
+ "//chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/share_sheet/ShareSheetPropertyModelBuilderTest.java",
]
+
+share_junit_test_java_sources = [ "//chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/screenshot/ScreenshotShareSheetMediatorUnitTest.java" ]
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 bce592b0662..aa5b7ab1095 100644
--- a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc
+++ b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.cc
@@ -194,7 +194,7 @@ void SpellCheckHostChromeImpl::RequestTextCheck(
base::Unretained(this))));
}
-#if BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#if defined(OS_WIN)
void SpellCheckHostChromeImpl::GetPerLanguageSuggestions(
const base::string16& word,
GetPerLanguageSuggestionsCallback callback) {
@@ -208,7 +208,7 @@ void SpellCheckHostChromeImpl::GetPerLanguageSuggestions(
spellcheck_platform::GetPerLanguageSuggestions(
spellcheck->platform_spell_checker(), word, std::move(callback));
}
-#endif // BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#endif // defined(OS_WIN)
void SpellCheckHostChromeImpl::OnRequestFinished(SpellingRequest* request) {
auto iterator = requests_.find(request);
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 984b852311b..17bb3d80a82 100644
--- a/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h
+++ b/chromium/chrome/browser/spellchecker/spell_check_host_chrome_impl.h
@@ -79,11 +79,11 @@ class SpellCheckHostChromeImpl : public SpellCheckHostImpl {
int route_id,
RequestTextCheckCallback callback) override;
-#if BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#if defined(OS_WIN)
void GetPerLanguageSuggestions(
const base::string16& word,
GetPerLanguageSuggestionsCallback callback) override;
-#endif // BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#endif // defined(OS_WIN)
// Clears a finished request from |requests_|. Exposed to SpellingRequest.
void OnRequestFinished(SpellingRequest* request);
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
index d838e7028bc..6c8810f7135 100644
--- 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
@@ -28,14 +28,7 @@ class PlatformSpellChecker;
class SpellCheckHostChromeImplWinBrowserTest : public InProcessBrowserTest {
public:
SpellCheckHostChromeImplWinBrowserTest() {
-#if BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
- feature_list_.InitWithFeatures(
- /*enabled_features=*/{spellcheck::kWinUseBrowserSpellChecker,
- spellcheck::kWinUseHybridSpellChecker},
- /*disabled_features=*/{});
-#else
feature_list_.InitAndEnableFeature(spellcheck::kWinUseBrowserSpellChecker);
-#endif // BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
}
void SetUpOnMainThread() override {
@@ -123,7 +116,6 @@ IN_PROC_BROWSER_TEST_F(SpellCheckHostChromeImplWinBrowserTest,
EXPECT_EQ(result_[0].decoration, SpellCheckResult::SPELLING);
}
-#if BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
IN_PROC_BROWSER_TEST_F(SpellCheckHostChromeImplWinBrowserTest,
GetPerLanguageSuggestions) {
if (!spellcheck::WindowsVersionSupportsSpellchecker()) {
@@ -148,4 +140,3 @@ IN_PROC_BROWSER_TEST_F(SpellCheckHostChromeImplWinBrowserTest,
ASSERT_EQ(1U, suggestion_result_.size());
EXPECT_GT(suggestion_result_[0].size(), 0U);
}
-#endif // BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc b/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc
index cdda080ce7f..582654c85e6 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_custom_dictionary.cc
@@ -453,10 +453,8 @@ void SpellcheckCustomDictionary::OnLoaded(
fix_invalid_file_.Reset(
base::BindOnce(&SpellcheckCustomDictionary::FixInvalidFile,
weak_ptr_factory_.GetWeakPtr(), std::move(result)));
- base::PostTask(
- FROM_HERE,
- {content::BrowserThread::UI, base::TaskPriority::BEST_EFFORT},
- fix_invalid_file_.callback());
+ content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
+ ->PostTask(FROM_HERE, fix_invalid_file_.callback());
}
}
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_factory.cc b/chromium/chrome/browser/spellchecker/spellcheck_factory.cc
index 5253d1f48e1..229f29e47b3 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_factory.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_factory.cc
@@ -43,13 +43,6 @@ KeyedService* SpellcheckServiceFactory::BuildServiceInstanceFor(
// Many variables are initialized from the |context| in the SpellcheckService.
SpellcheckService* spellcheck = new SpellcheckService(context);
- PrefService* prefs = user_prefs::UserPrefs::Get(context);
- DCHECK(prefs);
-
- // Instantiates Metrics object for spellchecking for use.
- spellcheck->StartRecordingMetrics(
- prefs->GetBoolean(spellcheck::prefs::kSpellCheckEnable));
-
return spellcheck;
}
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_factory.h b/chromium/chrome/browser/spellchecker/spellcheck_factory.h
index 7adf9db4f84..66e05d429d7 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_factory.h
+++ b/chromium/chrome/browser/spellchecker/spellcheck_factory.h
@@ -8,6 +8,7 @@
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/memory/singleton.h"
+#include "build/build_config.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
class SpellcheckService;
@@ -39,6 +40,12 @@ class SpellcheckServiceFactory : public BrowserContextKeyedServiceFactory {
bool ServiceIsNULLWhileTesting() const override;
FRIEND_TEST_ALL_PREFIXES(SpellcheckServiceBrowserTest, DeleteCorruptedBDICT);
+#if defined(OS_WIN)
+ FRIEND_TEST_ALL_PREFIXES(SpellcheckServiceWindowsHybridBrowserTest,
+ WindowsHybridSpellcheck);
+ FRIEND_TEST_ALL_PREFIXES(SpellcheckServiceWindowsHybridBrowserTestDelayInit,
+ WindowsHybridSpellcheckDelayInit);
+#endif // defined(OS_WIN)
DISALLOW_COPY_AND_ASSIGN(SpellcheckServiceFactory);
};
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
index 25feeebf536..5272b99db1d 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc
@@ -90,48 +90,54 @@ bool SaveDictionaryData(std::unique_ptr<std::string> data,
} // namespace
-SpellcheckHunspellDictionary::DictionaryFile::DictionaryFile() {
-}
+SpellcheckHunspellDictionary::DictionaryFile::DictionaryFile(
+ base::TaskRunner* task_runner) : task_runner_(task_runner) {}
SpellcheckHunspellDictionary::DictionaryFile::~DictionaryFile() {
+ if (file.IsValid()) {
+ task_runner_->PostTask(FROM_HERE,
+ base::BindOnce(&CloseDictionary, std::move(file)));
+ }
}
SpellcheckHunspellDictionary::DictionaryFile::DictionaryFile(
DictionaryFile&& other)
- : path(other.path), file(std::move(other.file)) {}
+ : path(other.path),
+ file(std::move(other.file)),
+ task_runner_(std::move(other.task_runner_)) {}
SpellcheckHunspellDictionary::DictionaryFile&
SpellcheckHunspellDictionary::DictionaryFile::operator=(
DictionaryFile&& other) {
path = other.path;
file = std::move(other.file);
+ task_runner_ = std::move(other.task_runner_);
return *this;
}
SpellcheckHunspellDictionary::SpellcheckHunspellDictionary(
const std::string& language,
+ const std::string& platform_spellcheck_language,
content::BrowserContext* browser_context,
SpellcheckService* spellcheck_service)
: task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})),
language_(language),
+ platform_spellcheck_language_(platform_spellcheck_language),
use_browser_spellchecker_(false),
browser_context_(browser_context),
spellcheck_service_(spellcheck_service),
- download_status_(DOWNLOAD_NONE) {}
+ download_status_(DOWNLOAD_NONE),
+ dictionary_file_(task_runner_.get()) {}
SpellcheckHunspellDictionary::~SpellcheckHunspellDictionary() {
- if (dictionary_file_.file.IsValid()) {
- task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&CloseDictionary, std::move(dictionary_file_.file)));
- }
-
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
// Disable the language from platform spellchecker.
- if (spellcheck::UseBrowserSpellChecker())
+ if (spellcheck::UseBrowserSpellChecker() && HasPlatformSupport()) {
spellcheck_platform::DisableLanguage(
- spellcheck_service_->platform_spell_checker(), language_);
+ spellcheck_service_->platform_spell_checker(),
+ GetPlatformSpellcheckLanguage());
+ }
#endif // BUILDFLAG(USE_BROWSER_SPELLCHECKER)
}
@@ -140,9 +146,10 @@ void SpellcheckHunspellDictionary::Load() {
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
if (spellcheck::UseBrowserSpellChecker() &&
- spellcheck_platform::SpellCheckerAvailable()) {
+ spellcheck_platform::SpellCheckerAvailable() && HasPlatformSupport()) {
spellcheck_platform::PlatformSupportsLanguage(
- spellcheck_service_->platform_spell_checker(), language_,
+ spellcheck_service_->platform_spell_checker(),
+ GetPlatformSpellcheckLanguage(),
base::BindOnce(
&SpellcheckHunspellDictionary::PlatformSupportsLanguageComplete,
weak_ptr_factory_.GetWeakPtr()));
@@ -177,6 +184,21 @@ const std::string& SpellcheckHunspellDictionary::GetLanguage() const {
return language_;
}
+const std::string& SpellcheckHunspellDictionary::GetPlatformSpellcheckLanguage()
+ const {
+#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+ // Currently the platform spellcheck language is only distinguished for
+ // Windows.
+ return platform_spellcheck_language_;
+#else
+ return language_;
+#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+}
+
+bool SpellcheckHunspellDictionary::HasPlatformSupport() const {
+ return !GetPlatformSpellcheckLanguage().empty();
+}
+
bool SpellcheckHunspellDictionary::IsUsingPlatformChecker() const {
return use_browser_spellchecker_;
}
@@ -308,13 +330,14 @@ void SpellcheckHunspellDictionary::DownloadDictionary(GURL url) {
base::Unretained(this)));
// Attempt downloading the dictionary only once.
- browser_context_ = NULL;
+ browser_context_ = nullptr;
}
#if !defined(OS_ANDROID)
// static
SpellcheckHunspellDictionary::DictionaryFile
-SpellcheckHunspellDictionary::OpenDictionaryFile(const base::FilePath& path) {
+SpellcheckHunspellDictionary::OpenDictionaryFile(base::TaskRunner* task_runner,
+ const base::FilePath& path) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
@@ -325,7 +348,7 @@ SpellcheckHunspellDictionary::OpenDictionaryFile(const base::FilePath& path) {
// For systemwide installations on Windows, the default directory may not
// have permissions for download. In that case, the alternate directory for
// download is chrome::DIR_USER_DATA.
- DictionaryFile dictionary;
+ DictionaryFile dictionary(task_runner);
#if defined(OS_WIN)
// Check if the dictionary exists in the fallback location. If so, use it
@@ -367,7 +390,7 @@ SpellcheckHunspellDictionary::OpenDictionaryFile(const base::FilePath& path) {
// static
SpellcheckHunspellDictionary::DictionaryFile
SpellcheckHunspellDictionary::InitializeDictionaryLocation(
- const std::string& language) {
+ base::TaskRunner* task_runner, const std::string& language) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
@@ -382,7 +405,7 @@ SpellcheckHunspellDictionary::InitializeDictionaryLocation(
base::FilePath dict_path =
spellcheck::GetVersionedFileName(language, dict_dir);
- return OpenDictionaryFile(dict_path);
+ return OpenDictionaryFile(task_runner, dict_path);
}
void SpellcheckHunspellDictionary::InitializeDictionaryLocationComplete(
@@ -396,7 +419,7 @@ void SpellcheckHunspellDictionary::InitializeDictionaryLocationComplete(
// TODO(rouslan): Remove this test-only case.
if (spellcheck_service_->SignalStatusEvent(
SpellcheckService::BDICT_CORRUPTED)) {
- browser_context_ = NULL;
+ browser_context_ = nullptr;
}
if (browser_context_) {
@@ -443,9 +466,10 @@ void SpellcheckHunspellDictionary::PlatformSupportsLanguageComplete(
if (platform_supports_language) {
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
- if (spellcheck::UseBrowserSpellChecker()) {
+ if (spellcheck::UseBrowserSpellChecker() && HasPlatformSupport()) {
spellcheck_platform::SetLanguage(
- spellcheck_service_->platform_spell_checker(), language_,
+ spellcheck_service_->platform_spell_checker(),
+ GetPlatformSpellcheckLanguage(),
base::BindOnce(&SpellcheckHunspellDictionary::
SpellCheckPlatformSetLanguageComplete,
weak_ptr_factory_.GetWeakPtr()));
@@ -454,24 +478,14 @@ void SpellcheckHunspellDictionary::PlatformSupportsLanguageComplete(
#endif // BUILDFLAG(USE_BROWSER_SPELLCHECKER)
NOTREACHED();
} else {
-#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
- // The platform spellchecker doesn't support this language. Fall back to
- // Hunspell, unless the hybrid spellchecker is disabled.
- if (spellcheck::UseBrowserSpellChecker() &&
- !spellcheck::UseWinHybridSpellChecker()) {
- // Can't fall back to Hunspell, because the hybrid spellchecker is not
- // enabled. We can't spellcheck this language, so there's no further
- // processing to do.
- return;
- }
-#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
// Either the platform spellchecker is unavailable / disabled, or it doesn't
// support this language. In either case, we must use Hunspell for this
// language, unless we are on Android, which doesn't support Hunspell.
#if !defined(OS_ANDROID) && BUILDFLAG(USE_RENDERER_SPELLCHECKER)
base::PostTaskAndReplyWithResult(
task_runner_.get(), FROM_HERE,
- base::BindOnce(&InitializeDictionaryLocation, language_),
+ base::BindOnce(&InitializeDictionaryLocation,
+ base::RetainedRef(task_runner_.get()), language_),
base::BindOnce(
&SpellcheckHunspellDictionary::InitializeDictionaryLocationComplete,
weak_ptr_factory_.GetWeakPtr()));
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h
index 4af3201238d..a8acd00dc44 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h
+++ b/chromium/chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h
@@ -53,6 +53,7 @@ class SpellcheckHunspellDictionary
};
SpellcheckHunspellDictionary(const std::string& language,
+ const std::string& platform_spellcheck_language,
content::BrowserContext* browser_context,
SpellcheckService* spellcheck_service);
~SpellcheckHunspellDictionary() override;
@@ -68,6 +69,8 @@ class SpellcheckHunspellDictionary
const base::File& GetDictionaryFile() const;
const std::string& GetLanguage() const;
+ const std::string& GetPlatformSpellcheckLanguage() const;
+ bool HasPlatformSupport() const;
bool IsUsingPlatformChecker() const;
// Add an observer for Hunspell dictionary events.
@@ -97,7 +100,7 @@ class SpellcheckHunspellDictionary
// blocking sequence.
struct DictionaryFile {
public:
- DictionaryFile();
+ explicit DictionaryFile(base::TaskRunner* task_runner);
~DictionaryFile();
DictionaryFile(DictionaryFile&& other);
@@ -110,6 +113,9 @@ class SpellcheckHunspellDictionary
base::File file;
private:
+ // Task runner where the file is created.
+ scoped_refptr<base::TaskRunner> task_runner_;
+
DISALLOW_COPY_AND_ASSIGN(DictionaryFile);
};
@@ -124,11 +130,12 @@ class SpellcheckHunspellDictionary
#if !defined(OS_ANDROID)
// Figures out the location for the dictionary, verifies its contents, and
// opens it.
- static DictionaryFile OpenDictionaryFile(const base::FilePath& path);
+ static DictionaryFile OpenDictionaryFile(base::TaskRunner* task_runner,
+ const base::FilePath& path);
// Gets the default location for the dictionary file.
static DictionaryFile InitializeDictionaryLocation(
- const std::string& language);
+ base::TaskRunner* task_runner, const std::string& language);
// The reply point for PostTaskAndReplyWithResult, called after the dictionary
// file has been initialized.
@@ -156,9 +163,14 @@ class SpellcheckHunspellDictionary
// Task runner where the file operations takes place.
scoped_refptr<base::SequencedTaskRunner> const task_runner_;
- // The language of the dictionary file.
+ // The language of the dictionary file (passed when loading Hunspell
+ // dictionaries).
const std::string language_;
+ // The spellcheck language passed to platform APIs may differ from the accept
+ // language (can be empty, indicating to use accept language and Hunspell).
+ const std::string platform_spellcheck_language_;
+
// Whether to use the platform spellchecker instead of Hunspell.
bool use_browser_spellchecker_;
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_language_policy_handlers_unittest.cc b/chromium/chrome/browser/spellchecker/spellcheck_language_policy_handlers_unittest.cc
index fd5ff6c2907..4dcf37eeeca 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_language_policy_handlers_unittest.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_language_policy_handlers_unittest.cc
@@ -17,6 +17,7 @@
#include "base/strings/string_util.h"
#include "base/test/scoped_feature_list.h"
#include "base/values.h"
+#include "build/build_config.h"
#include "chrome/common/pref_names.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/policy_constants.h"
@@ -102,22 +103,19 @@ class SpellcheckLanguagePolicyHandlersTest
};
TEST_P(SpellcheckLanguagePolicyHandlersTest, ApplyPolicySettings) {
-#if BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
base::test::ScopedFeatureList feature_list;
if (GetParam().windows_spellchecker_enabled) {
if (!spellcheck::WindowsVersionSupportsSpellchecker())
return;
- // Force hybrid spellchecking to be enabled.
- feature_list.InitWithFeatures(
- /*enabled_features=*/{spellcheck::kWinUseBrowserSpellChecker,
- spellcheck::kWinUseHybridSpellChecker},
- /*disabled_features=*/{});
+ // Force Windows native spellchecking to be enabled.
+ feature_list.InitAndEnableFeature(spellcheck::kWinUseBrowserSpellChecker);
} else {
// Hunspell-only spellcheck languages will be used.
feature_list.InitAndDisableFeature(spellcheck::kWinUseBrowserSpellChecker);
}
-#endif // BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
PrefValueMap prefs;
policy::PolicyMap policy;
@@ -169,7 +167,7 @@ INSTANTIATE_TEST_SUITE_P(
TestCases,
SpellcheckLanguagePolicyHandlersTest,
testing::Values(
-#if BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
// Test cases for Windows spellchecker (policy languages not restricted
// to Hunspell).
TestCase({"ar-SA", "es-MX", "fi", "fr",
@@ -185,7 +183,7 @@ INSTANTIATE_TEST_SUITE_P(
{""} /* expected forced languages */,
false /* spellcheck enabled */,
true /* windows spellchecker enabled */),
-#endif // BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
// Test cases for Hunspell only spellchecker. ar-SA and fi are
// non-Hunspell languages so are ignored for policy enforcement. If they
// ever obtain Hunspell support, the first test case below will fail.
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_service.cc b/chromium/chrome/browser/spellchecker/spellcheck_service.cc
index af11ea50738..69a1dd21df9 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_service.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_service.cc
@@ -18,11 +18,13 @@
#include "base/synchronization/waitable_event.h"
#include "base/values.h"
#include "build/build_config.h"
+#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/spellchecker/spellcheck_factory.h"
#include "chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h"
#include "components/language/core/browser/pref_names.h"
#include "components/prefs/pref_member.h"
#include "components/prefs/pref_service.h"
+#include "components/prefs/scoped_user_pref_update.h"
#include "components/spellcheck/browser/pref_names.h"
#include "components/spellcheck/browser/spellcheck_host_metrics.h"
#include "components/spellcheck/browser/spellcheck_platform.h"
@@ -71,15 +73,6 @@ SpellcheckService::SpellcheckService(content::BrowserContext* context)
: context_(context) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
-#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
- // The Windows spell checker must be created before the dictionaries are
- // initialized.
- if (spellcheck::WindowsVersionSupportsSpellchecker()) {
- platform_spell_checker_ = std::make_unique<WindowsSpellChecker>(
- base::ThreadPool::CreateCOMSTATaskRunner({base::MayBlock()}));
- }
-#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
-
PrefService* prefs = user_prefs::UserPrefs::Get(context);
pref_change_registrar_.Init(prefs);
StringListPrefMember dictionaries_pref;
@@ -114,6 +107,21 @@ SpellcheckService::SpellcheckService(content::BrowserContext* context)
single_dictionary_pref.SetValue("");
#endif // defined(OS_MACOSX) || defined(OS_ANDROID)
+#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+ if (!spellcheck::UseBrowserSpellChecker()) {
+ // A user may have disabled the Windows spellcheck feature after adding
+ // non-Hunspell supported languages on the language settings page. Remove
+ // preferences for non-Hunspell languages so that there is no attempt to
+ // load a non-existent Hunspell dictionary, and so that Hunspell
+ // spellchecking isn't broken because of the failed load.
+ ListPrefUpdate update(prefs, spellcheck::prefs::kSpellCheckDictionaries);
+ update->EraseListValueIf([](const base::Value& entry) {
+ return spellcheck::GetCorrespondingSpellCheckLanguage(entry.GetString())
+ .empty();
+ });
+ }
+#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+
pref_change_registrar_.Add(
spellcheck::prefs::kSpellCheckDictionaries,
base::BindRepeating(&SpellcheckService::OnSpellCheckDictionariesChanged,
@@ -143,11 +151,21 @@ SpellcheckService::SpellcheckService(content::BrowserContext* context)
custom_dictionary_->AddObserver(this);
custom_dictionary_->Load();
- registrar_.Add(this,
- content::NOTIFICATION_RENDERER_PROCESS_CREATED,
+ registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED,
content::NotificationService::AllSources());
- LoadHunspellDictionaries();
+#if defined(OS_WIN)
+ if (spellcheck::UseBrowserSpellChecker() &&
+ base::FeatureList::IsEnabled(
+ spellcheck::kWinDelaySpellcheckServiceInit)) {
+ // If initialization of the spellcheck service is on-demand, it is up to the
+ // instantiator of the spellcheck service to call InitializeDictionaries
+ // with a callback.
+ return;
+ }
+#endif // defined(OS_WIN)
+
+ InitializeDictionaries(base::DoNothing());
}
SpellcheckService::~SpellcheckService() {
@@ -161,8 +179,9 @@ base::WeakPtr<SpellcheckService> SpellcheckService::GetWeakPtr() {
#if !defined(OS_MACOSX)
// static
-void SpellcheckService::GetDictionaries(base::SupportsUserData* browser_context,
- std::vector<Dictionary>* dictionaries) {
+void SpellcheckService::GetDictionaries(
+ content::BrowserContext* browser_context,
+ std::vector<Dictionary>* dictionaries) {
PrefService* prefs = user_prefs::UserPrefs::Get(browser_context);
std::set<std::string> spellcheck_dictionaries;
for (const auto& value :
@@ -178,8 +197,23 @@ void SpellcheckService::GetDictionaries(base::SupportsUserData* browser_context,
",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
for (const auto& accept_language : accept_languages) {
Dictionary dictionary;
+#if defined(OS_WIN)
+ if (spellcheck::UseBrowserSpellChecker()) {
+ SpellcheckService* spellcheck =
+ SpellcheckServiceFactory::GetForContext(browser_context);
+ if (spellcheck && spellcheck->UsesWindowsDictionary(accept_language))
+ dictionary.language = accept_language;
+ }
+
+ if (dictionary.language.empty()) {
+ dictionary.language =
+ spellcheck::GetCorrespondingSpellCheckLanguage(accept_language);
+ }
+#else
dictionary.language =
spellcheck::GetCorrespondingSpellCheckLanguage(accept_language);
+#endif // defined(OS_WIN)
+
if (dictionary.language.empty())
continue;
@@ -212,9 +246,13 @@ std::string SpellcheckService::GetSupportedAcceptLanguageCode(
supported_language_full_tag);
#if defined(OS_WIN)
- if (!spellcheck::UseWinHybridSpellChecker())
+ if (!spellcheck::UseBrowserSpellChecker())
return supported_accept_language;
+ // Exclude dictionaries that are for private use, such as "ja-Latn-JP-x-ext".
+ if (SpellcheckService::HasPrivateUseSubTag(supported_language_full_tag))
+ return "";
+
// Collect the hardcoded list of accept-languages supported by the browser,
// that is, languages that can be added as preferred languages in the
// languages settings page.
@@ -272,8 +310,18 @@ std::string SpellcheckService::GetSupportedAcceptLanguageCode(
/* include_script_tag */ false));
});
- if (iter != accept_languages.end())
+ if (iter != accept_languages.end()) {
+ // Special case for Serbian--"sr" implies Cyrillic script. Don't mark it as
+ // supported for sr-Latn*.
+ if (base::EqualsCaseInsensitiveASCII(
+ SpellcheckService::GetLanguageAndScriptTag(
+ supported_language_full_tag,
+ /* include_script_tag */ true),
+ "sr-Latn")) {
+ return "";
+ }
return *iter;
+ }
#endif // defined(OS_WIN)
@@ -328,7 +376,7 @@ SpellcheckCustomDictionary* SpellcheckService::GetCustomDictionary() {
return custom_dictionary_.get();
}
-void SpellcheckService::LoadHunspellDictionaries() {
+void SpellcheckService::LoadDictionaries() {
hunspell_dictionaries_.clear();
PrefService* prefs = user_prefs::UserPrefs::Get(context_);
@@ -359,16 +407,50 @@ void SpellcheckService::LoadHunspellDictionaries() {
}
for (const auto& dictionary : dictionaries) {
+ // The spellcheck language passed to platform APIs may differ from the
+ // accept language.
+ std::string platform_spellcheck_language;
+#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+ if (spellcheck::UseBrowserSpellChecker()) {
+ std::string windows_dictionary_name =
+ GetSupportedWindowsDictionaryLanguage(dictionary);
+ if (!windows_dictionary_name.empty()) {
+ platform_spellcheck_language =
+ SpellcheckService::GetTagToPassToWindowsSpellchecker(
+ dictionary, windows_dictionary_name);
+ }
+ }
+#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+
hunspell_dictionaries_.push_back(
- std::make_unique<SpellcheckHunspellDictionary>(dictionary, context_,
- this));
+ std::make_unique<SpellcheckHunspellDictionary>(
+ dictionary, platform_spellcheck_language, context_, this));
hunspell_dictionaries_.back()->AddObserver(this);
hunspell_dictionaries_.back()->Load();
}
#if defined(OS_WIN)
RecordSpellcheckLocalesStats();
+
+#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+ if (base::FeatureList::IsEnabled(
+ spellcheck::kWinDelaySpellcheckServiceInit) &&
+ spellcheck::UseBrowserSpellChecker()) {
+ // Only want to fire the callback on first call to LoadDictionaries
+ // originating from InitializeDictionaries, since supported platform
+ // dictionaries are cached throughout the browser session and not
+ // dynamically updated. LoadDictionaries can be called multiple times in a
+ // browser session, even before InitializeDictionaries is called, e.g. when
+ // language settings are changed.
+ if (!dictionaries_loaded() && dictionaries_loaded_callback_) {
+ dictionaries_loaded_ = true;
+ std::move(dictionaries_loaded_callback_).Run();
+ }
+ return;
+ }
+#endif // BUILDFLAG(USE_BROWSER_SPELLCHECKER)
#endif // defined(OS_WIN)
+ dictionaries_loaded_ = true;
}
const std::vector<std::unique_ptr<SpellcheckHunspellDictionary>>&
@@ -435,6 +517,134 @@ void SpellcheckService::OnHunspellDictionaryDownloadFailure(
const std::string& language) {
}
+void SpellcheckService::InitializeDictionaries(base::OnceClosure done) {
+ // The dictionaries only need to be initialized once.
+ if (dictionaries_loaded()) {
+ std::move(done).Run();
+ return;
+ }
+
+#if defined(OS_WIN)
+ dictionaries_loaded_callback_ = std::move(done);
+ // Need to initialize the platform spellchecker in order to record platform
+ // locale stats even if the platform spellcheck feature is disabled.
+ InitializePlatformSpellchecker();
+#endif // defined(OS_WIN)
+
+ PrefService* prefs = user_prefs::UserPrefs::Get(context_);
+ DCHECK(prefs);
+
+ // Instantiates Metrics object for spellchecking to use.
+ StartRecordingMetrics(
+ prefs->GetBoolean(spellcheck::prefs::kSpellCheckEnable));
+
+#if defined(OS_WIN)
+ if (spellcheck::UseBrowserSpellChecker() && platform_spell_checker()) {
+ spellcheck_platform::RetrieveSpellcheckLanguages(
+ platform_spell_checker(),
+ base::BindOnce(&SpellcheckService::InitWindowsDictionaryLanguages,
+ GetWeakPtr()));
+ return;
+ }
+#endif // defined(OS_WIN)
+
+ // Using Hunspell.
+ LoadDictionaries();
+}
+
+#if defined(OS_WIN)
+void SpellcheckService::InitWindowsDictionaryLanguages(
+ const std::vector<std::string>& windows_spellcheck_languages) {
+ windows_spellcheck_dictionary_map_.clear();
+ for (const auto& windows_spellcheck_language : windows_spellcheck_languages) {
+ std::string accept_language =
+ SpellcheckService::GetSupportedAcceptLanguageCode(
+ windows_spellcheck_language);
+ AddWindowsSpellcheckDictionary(accept_language,
+ windows_spellcheck_language);
+
+ // There is one unfortunate special case (so far the only one known). The
+ // accept language "sr" is supported, and if you use it as a display
+ // language you see Cyrillic script. If a Windows language pack is
+ // installed that supports "sr-Cyrl-*", mark the "sr" accept language
+ // as having Windows spellcheck support instead of using Hunspell.
+ if (base::EqualsCaseInsensitiveASCII(
+ "sr-Cyrl", SpellcheckService::GetLanguageAndScriptTag(
+ windows_spellcheck_language,
+ /* include_script_tag */ true))) {
+ AddWindowsSpellcheckDictionary("sr", windows_spellcheck_language);
+ }
+ }
+
+ // A user may have removed a language pack for a non-Hunspell language after
+ // enabling it for spellcheck on the language settings page. Remove
+ // preferences for this language so that there is no attempt to load a
+ // non-existent Hunspell dictionary, and so that Hunspell spellchecking isn't
+ // broken because of the failed load.
+ PrefService* prefs = user_prefs::UserPrefs::Get(context_);
+ DCHECK(prefs);
+ // When following object goes out of scope, preference change observers will
+ // be notified (even if there is no preference change).
+ ListPrefUpdate update(prefs, spellcheck::prefs::kSpellCheckDictionaries);
+ update->EraseListValueIf([this](const base::Value& entry) {
+ const std::string dictionary_name = entry.GetString();
+ return (!UsesWindowsDictionary(dictionary_name) &&
+ spellcheck::GetCorrespondingSpellCheckLanguage(dictionary_name)
+ .empty());
+ });
+
+ if (first_run::IsChromeFirstRun()) {
+ // Ensure that spellcheck is enabled for the first dialect of the
+ // accepted languages if there is a Windows dictionary installed for
+ // that dialect.
+ base::Value user_dictionaries =
+ prefs->GetList(spellcheck::prefs::kSpellCheckDictionaries)->Clone();
+ std::vector<std::string> user_languages =
+ base::SplitString(prefs->GetString(language::prefs::kAcceptLanguages),
+ ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
+
+ // Some first run scenarios will add an accept language to preferences that
+ // is not found in the hard-coded list in kAcceptLanguageList. Only
+ // languages in kAcceptLanguageList can be spellchecked. An example is an
+ // installation on a device where Finnnish is the Windows display
+ // language--the initial accept language preferences are observed to be
+ // "fi-FI,fi,en-US,en". Only "fi" is contained in kAcceptLanguageList.
+ std::string first_user_language;
+ std::vector<std::string> accept_languages;
+ l10n_util::GetAcceptLanguages(&accept_languages);
+ for (const auto& user_language : user_languages) {
+ if (base::Contains(accept_languages, user_language)) {
+ first_user_language = user_language;
+ break;
+ }
+ }
+
+ bool first_user_language_spellchecked = false;
+ for (const auto& dictionary_value : user_dictionaries.GetList()) {
+ first_user_language_spellchecked =
+ base::Contains(dictionary_value.GetString(), first_user_language);
+ if (first_user_language_spellchecked)
+ break;
+ }
+
+ if (!first_user_language_spellchecked &&
+ UsesWindowsDictionary(first_user_language)) {
+ user_dictionaries.Insert(user_dictionaries.GetList().begin(),
+ base::Value(first_user_language));
+ prefs->Set(spellcheck::prefs::kSpellCheckDictionaries, user_dictionaries);
+ }
+ }
+
+ // No need to call LoadDictionaries() as when the ListPrefUpdate
+ // object goes out of scope, the preference change handler will do this.
+}
+
+bool SpellcheckService::UsesWindowsDictionary(
+ std::string accept_language) const {
+ return !GetSupportedWindowsDictionaryLanguage(accept_language).empty();
+}
+#endif // defined(OS_WIN)
+
// static
void SpellcheckService::OverrideBinderForTesting(SpellCheckerBinder binder) {
GetSpellCheckerBinderOverride() = std::move(binder);
@@ -468,6 +678,50 @@ std::string SpellcheckService::GetLanguageAndScriptTag(
}
// static
+bool SpellcheckService::HasPrivateUseSubTag(const std::string& full_tag) {
+ std::vector<std::string> subtags = base::SplitString(
+ full_tag, "-", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
+
+ // Private use subtags are separated from the other subtags by the reserved
+ // single-character subtag 'x'.
+ return base::Contains(subtags, "x");
+}
+
+#if defined(OS_WIN)
+// static
+std::string SpellcheckService::GetTagToPassToWindowsSpellchecker(
+ const std::string& accept_language,
+ const std::string& supported_language_full_tag) {
+ // First try exact match. Per BCP47, tags are in ASCII and should be treated
+ // as case-insensitive (although there are conventions for the capitalization
+ // of subtags, they are sometimes broken).
+ if (base::EqualsCaseInsensitiveASCII(supported_language_full_tag,
+ accept_language)) {
+ // Unambiguous spellcheck dictionary to be used.
+ return supported_language_full_tag;
+ }
+
+ // Accept language does not match script or region subtags.
+ // If there is a script subtag, include it, to avoid for example passing
+ // "sr" which is ambiguous as Serbian can use Cyrillic or Latin script.
+ // There is one unfortunate special case (so far the only one known). The
+ // accept language "sr" is supported, and if you use it as a display
+ // language you see Cyrillic script. However, the Windows spellcheck API
+ // returns "sr-Latn-*" dictionaries if the unqualified language tag is
+ // passed. The following forces Windows spellchecking to use Cyrillic script
+ // in this case, and if the language pack is not installed there will be a
+ // fallback to Hunspell support when spellchecking is performed.
+ if (base::EqualsCaseInsensitiveASCII("sr", accept_language))
+ return "sr-Cyrl";
+
+ return SpellcheckService::GetLanguageAndScriptTag(
+ supported_language_full_tag,
+ /* include_script_tag */ true);
+}
+
+#endif // defined(OS_WIN)
+
+// static
void SpellcheckService::AttachStatusEvent(base::WaitableEvent* status_event) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -495,7 +749,7 @@ SpellcheckService::GetSpellCheckerForProcess(content::RenderProcessHost* host) {
void SpellcheckService::InitForAllRenderers() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (content::RenderProcessHost::iterator i(
- content::RenderProcessHost::AllHostsIterator());
+ content::RenderProcessHost::AllHostsIterator());
!i.IsAtEnd(); i.Advance()) {
content::RenderProcessHost* process = i.GetCurrentValue();
if (process && process->GetProcess().Handle())
@@ -506,7 +760,7 @@ void SpellcheckService::InitForAllRenderers() {
void SpellcheckService::OnSpellCheckDictionariesChanged() {
// If there are hunspell dictionaries, then fire off notifications to the
// renderers after the dictionaries are finished loading.
- LoadHunspellDictionaries();
+ LoadDictionaries();
// If there are no hunspell dictionaries to load, then immediately let the
// renderers know the new state.
@@ -551,15 +805,35 @@ std::vector<std::string> SpellcheckService::GetNormalizedAcceptLanguages(
",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (normalize_for_spellcheck) {
- std::transform(accept_languages.begin(), accept_languages.end(),
- accept_languages.begin(),
- &spellcheck::GetCorrespondingSpellCheckLanguage);
+ std::transform(
+ accept_languages.begin(), accept_languages.end(),
+ accept_languages.begin(), [&](const std::string& language) {
+#if defined(OS_WIN)
+ if (spellcheck::UseBrowserSpellChecker() &&
+ UsesWindowsDictionary(language))
+ return language;
+#endif // defined(OS_WIN)
+ return spellcheck::GetCorrespondingSpellCheckLanguage(language);
+ });
}
return accept_languages;
}
#if defined(OS_WIN)
+void SpellcheckService::InitializePlatformSpellchecker() {
+ // The Windows spell checker must be created before the dictionaries are
+ // initialized. Note it is instantiated even if only Hunspell is being used
+ // since metrics on the availability of Windows platform language packs are
+ // being recorded. Thus method should only be called once, except in test
+ // code.
+ if (!platform_spell_checker() &&
+ spellcheck::WindowsVersionSupportsSpellchecker()) {
+ platform_spell_checker_ = std::make_unique<WindowsSpellChecker>(
+ base::ThreadPool::CreateCOMSTATaskRunner({base::MayBlock()}));
+ }
+}
+
void SpellcheckService::RecordSpellcheckLocalesStats() {
if (spellcheck::WindowsVersionSupportsSpellchecker() && metrics_ &&
platform_spell_checker() && !hunspell_dictionaries_.empty()) {
@@ -581,4 +855,34 @@ void SpellcheckService::RecordChromeLocalesStats() {
platform_spell_checker(), std::move(accept_languages), metrics_.get());
}
}
+
+void SpellcheckService::AddWindowsSpellcheckDictionary(
+ const std::string& accept_language,
+ const std::string& supported_language_full_tag) {
+ if (!accept_language.empty()) {
+ windows_spellcheck_dictionary_map_.insert(
+ {accept_language, supported_language_full_tag});
+ }
+}
+
+std::string SpellcheckService::GetSupportedWindowsDictionaryLanguage(
+ const std::string& accept_language) const {
+ // BCP47 language tag used by the Windows spellchecker API.
+ std::string spellcheck_language;
+
+ auto it = windows_spellcheck_dictionary_map_.find(accept_language);
+ if (it != windows_spellcheck_dictionary_map_.end())
+ spellcheck_language = it->second;
+
+ return spellcheck_language;
+}
+
+void SpellcheckService::AddSpellcheckLanguagesForTesting(
+ const std::vector<std::string>& languages) {
+ InitializePlatformSpellchecker();
+ if (platform_spell_checker()) {
+ spellcheck_platform::AddSpellcheckLanguagesForTesting(
+ platform_spell_checker(), languages);
+ }
+}
#endif // defined(OS_WIN)
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_service.h b/chromium/chrome/browser/spellchecker/spellcheck_service.h
index 97df131375c..4c3d45d9ce6 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_service.h
+++ b/chromium/chrome/browser/spellchecker/spellcheck_service.h
@@ -7,6 +7,7 @@
#include <stddef.h>
+#include <map>
#include <memory>
#include <string>
#include <vector>
@@ -31,7 +32,6 @@ class SpellCheckHostMetrics;
namespace base {
class WaitableEvent;
-class SupportsUserData;
}
namespace content {
@@ -41,6 +41,12 @@ class NotificationSource;
class RenderProcessHost;
}
+#if defined(OS_WIN)
+namespace extensions {
+class LanguageSettingsPrivateApiTestDelayInit;
+}
+#endif // defined(OS_WIN)
+
// Encapsulates the browser side spellcheck service. There is one of these per
// profile and each is created by the SpellCheckServiceFactory. The
// SpellcheckService maintains any per-profile information about spellcheck.
@@ -84,7 +90,7 @@ class SpellcheckService : public KeyedService,
// Returns all currently configured |dictionaries| to display in the context
// menu over a text area. The context menu is used for selecting the
// dictionaries used for spellcheck.
- static void GetDictionaries(base::SupportsUserData* browser_context,
+ static void GetDictionaries(content::BrowserContext* browser_context,
std::vector<Dictionary>* dictionaries);
#endif // !OS_MACOSX
@@ -116,9 +122,6 @@ class SpellcheckService : public KeyedService,
// Returns the instance of the custom dictionary.
SpellcheckCustomDictionary* GetCustomDictionary();
- // Starts the process of loading the Hunspell dictionaries.
- void LoadHunspellDictionaries();
-
// Returns the instance of the vector of Hunspell dictionaries.
const std::vector<std::unique_ptr<SpellcheckHunspellDictionary>>&
GetHunspellDictionaries();
@@ -152,6 +155,21 @@ class SpellcheckService : public KeyedService,
void OnHunspellDictionaryDownloadFailure(
const std::string& language) override;
+ // One-time initialization of dictionaries if needed.
+ void InitializeDictionaries(base::OnceClosure done);
+
+#if defined(OS_WIN)
+ // Callback for spellcheck_platform::RetrieveSpellcheckLanguages. Populates
+ // map of preferred languages to available platform dictionaries then
+ // loads the dictionaries.
+ void InitWindowsDictionaryLanguages(
+ const std::vector<std::string>& windows_spellcheck_languages);
+
+ // Indicates whether given accept language has Windows spellcheck platform
+ // support.
+ bool UsesWindowsDictionary(std::string accept_language) const;
+#endif // defined(OS_WIN)
+
// The returned pointer can be null if the current platform doesn't need a
// per-profile, platform-specific spell check object. Currently, only Windows
// requires one, and only on certain versions.
@@ -159,6 +177,9 @@ class SpellcheckService : public KeyedService,
return platform_spell_checker_.get();
}
+ // Indicates whether dictionaries have been loaded initially.
+ bool dictionaries_loaded() const { return dictionaries_loaded_; }
+
// Allows tests to override how SpellcheckService binds its interface
// receiver, instead of going through a RenderProcessHost by default.
using SpellCheckerBinder = base::RepeatingCallback<void(
@@ -167,12 +188,40 @@ class SpellcheckService : public KeyedService,
private:
FRIEND_TEST_ALL_PREFIXES(SpellcheckServiceBrowserTest, DeleteCorruptedBDICT);
+#if defined(OS_WIN)
+ FRIEND_TEST_ALL_PREFIXES(SpellcheckServiceWindowsHybridBrowserTest,
+ WindowsHybridSpellcheck);
+ FRIEND_TEST_ALL_PREFIXES(SpellcheckServiceWindowsHybridBrowserTestDelayInit,
+ WindowsHybridSpellcheckDelayInit);
+ friend class SpellcheckServiceHybridUnitTestBase;
+ friend class SpellcheckServiceHybridUnitTestDelayInitBase;
+ friend class extensions::LanguageSettingsPrivateApiTestDelayInit;
+#endif // defined(OS_WIN)
+
+ // Starts the process of loading the dictionaries (Hunspell and platform). Can
+ // be called multiple times in a browser session if spellcheck settings
+ // change.
+ void LoadDictionaries();
// Parses a full BCP47 language tag to return just the language subtag,
// optionally with a hyphen and script subtag appended.
static std::string GetLanguageAndScriptTag(const std::string& full_tag,
bool include_script_tag);
+ // Returns true if full BCP47 language tag contains private use subtag (e.g in
+ // the tag "ja-Latn-JP-x-ext"), indicating the tag is only for use by private
+ // agreement.
+ static bool HasPrivateUseSubTag(const std::string& full_tag);
+
+#if defined(OS_WIN)
+ // Returns the BCP47 language tag to pass to the Windows spellcheck API, based
+ // on the accept language and full tag, with special logic for languages that
+ // can be written in different scripts.
+ static std::string GetTagToPassToWindowsSpellchecker(
+ const std::string& accept_language,
+ const std::string& supported_language_full_tag);
+#endif // defined(OS_WIN)
+
// Attaches an event so browser tests can listen the status events.
static void AttachStatusEvent(base::WaitableEvent* status_event);
@@ -207,12 +256,36 @@ class SpellcheckService : public KeyedService,
bool normalize_for_spellcheck = true) const;
#if defined(OS_WIN)
+ // Initializes the platform spell checker.
+ void InitializePlatformSpellchecker();
+
// Records statistics about spell check support for the user's Chrome locales.
void RecordChromeLocalesStats();
// Records statistics about which spell checker supports which of the user's
// enabled spell check locales.
void RecordSpellcheckLocalesStats();
+
+ // Adds an item to the cached collection mapping an accept language from
+ // language settings to a BCP47 language tag to be passed to the Windows
+ // spellchecker API, guarding against duplicate entries for the same accept
+ // language.
+ void AddWindowsSpellcheckDictionary(
+ const std::string& accept_language,
+ const std::string& supported_language_full_tag);
+
+ // Gets the BCP47 language tag to pass to Windows spellcheck API, by
+ // searching through the collection of languages already known to have
+ // Windows spellchecker support on the system. Can return an empty string
+ // if there is no Windows spellchecker support for this language on the
+ // system.
+ std::string GetSupportedWindowsDictionaryLanguage(
+ const std::string& accept_language) const;
+
+ // Test-only method for adding fake list of platform spellcheck languages
+ // before calling InitializeDictionaries().
+ void AddSpellcheckLanguagesForTesting(
+ const std::vector<std::string>& languages);
#endif // defined(OS_WIN)
// WindowsSpellChecker must be created before the dictionary instantiation and
@@ -232,6 +305,21 @@ class SpellcheckService : public KeyedService,
std::vector<std::unique_ptr<SpellcheckHunspellDictionary>>
hunspell_dictionaries_;
+#if defined(OS_WIN)
+ // Maps accept language tags to Windows spellcheck BCP47 tags, an analog
+ // of the hardcoded kSupportedSpellCheckerLanguages used for Hunspell,
+ // with the difference that only language packs installed on the system
+ // with spellchecker support are included.
+ std::map<std::string, std::string> windows_spellcheck_dictionary_map_;
+
+ // Callback passed as argument to InitializeDictionaries, and invoked when
+ // the dictionaries are loaded for the first time.
+ base::OnceClosure dictionaries_loaded_callback_;
+#endif // defined(OS_WIN)
+
+ // Flag indicating dictionaries have been loaded initially.
+ bool dictionaries_loaded_ = false;
+
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 ef602ba4d53..bf59a235f1b 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_service_browsertest.cc
@@ -4,6 +4,7 @@
#include "chrome/browser/spellchecker/spellcheck_service.h"
+#include <map>
#include <string>
#include <vector>
@@ -18,6 +19,7 @@
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/metrics/histogram_tester.h"
+#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "build/build_config.h"
@@ -33,6 +35,7 @@
#include "components/spellcheck/browser/pref_names.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/common/spellcheck_result.h"
#include "components/spellcheck/spellcheck_buildflags.h"
#include "components/user_prefs/user_prefs.h"
@@ -44,9 +47,9 @@
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
-#if BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
#include "components/spellcheck/common/spellcheck_features.h"
-#endif // BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
using content::BrowserContext;
using content::RenderProcessHost;
@@ -56,6 +59,19 @@ class SpellcheckServiceBrowserTest : public InProcessBrowserTest,
public:
SpellcheckServiceBrowserTest() = default;
+#if defined(OS_WIN)
+ void SetUp() override {
+ // Tests were designed assuming Hunspell dictionary used and many fail when
+ // Windows spellcheck is enabled by default. The feature flag needs to be
+ // disabled in SetUp() instead of the constructor because the derived class
+ // SpellcheckServiceWindowsHybridBrowserTest overrides the base class
+ // behavior and sets the spellcheck::kWinUseBrowserSpellChecker feature
+ // flag. You can't use ScopedFeatureList to initialize a feature flag twice.
+ feature_list_.InitAndDisableFeature(spellcheck::kWinUseBrowserSpellChecker);
+ InProcessBrowserTest::SetUp();
+ }
+#endif // defined(OS_WIN)
+
void SetUpOnMainThread() override {
renderer_.reset(new content::MockRenderProcessHost(GetContext()));
renderer_->Init();
@@ -104,12 +120,12 @@ class SpellcheckServiceBrowserTest : public InProcessBrowserTest,
SpellcheckService* spellcheck =
SpellcheckServiceFactory::GetForContext(renderer_->GetBrowserContext());
-#if BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
- if (spellcheck::UseWinHybridSpellChecker()) {
- // If the Windows hybrid spell checker is in use, initialization is async.
+#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+ if (spellcheck::UseBrowserSpellChecker()) {
+ // If the Windows native spell checker is in use, initialization is async.
RunTestRunLoop();
}
-#endif // BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
ASSERT_NE(nullptr, spellcheck);
}
@@ -224,6 +240,10 @@ class SpellcheckServiceBrowserTest : public InProcessBrowserTest,
// Quits the RunLoop on Mojo request flow completion.
base::OnceClosure quit_;
+#if defined(OS_WIN)
+ base::test::ScopedFeatureList feature_list_;
+#endif // defined(OS_WIN)
+
private:
// Mocked RenderProcessHost.
std::unique_ptr<content::MockRenderProcessHost> renderer_;
@@ -461,14 +481,14 @@ IN_PROC_BROWSER_TEST_F(SpellcheckServiceHostBrowserTest, CallSpellingService) {
// 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.
IN_PROC_BROWSER_TEST_F(SpellcheckServiceBrowserTest, DeleteCorruptedBDICT) {
-#if BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
- if (spellcheck::UseWinHybridSpellChecker()) {
- // If doing hybrid spell checking on Windows, Hunspell dictionaries are not
+#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+ if (spellcheck::UseBrowserSpellChecker()) {
+ // If doing native spell checking on Windows, Hunspell dictionaries are not
// used for en-US, so the corrupt dictionary event will never be raised.
// Skip this test.
return;
}
-#endif // BUILDFLAG(USE_WIN_HYBRID_SPELLCHECKER)
+#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
// Corrupted BDICT data: please do not use this BDICT data for other tests.
const uint8_t kCorruptedBDICT[] = {
@@ -509,13 +529,15 @@ IN_PROC_BROWSER_TEST_F(SpellcheckServiceBrowserTest, DeleteCorruptedBDICT) {
SpellcheckServiceFactory::GetInstance()->GetServiceForBrowserContext(
context,
false));
- ASSERT_EQ(NULL, service);
+ ASSERT_EQ(nullptr, service);
// Getting the spellcheck_service will initialize the SpellcheckService
// object with the corrupted BDICT file created above since the hunspell
// dictionary is loaded in the SpellcheckService constructor right now.
// The SpellCheckHost object will send a BDICT_CORRUPTED event.
- SpellcheckServiceFactory::GetForContext(context);
+ service = SpellcheckServiceFactory::GetForContext(context);
+ ASSERT_NE(nullptr, service);
+ ASSERT_TRUE(service->dictionaries_loaded());
// Check the received event. Also we check if Chrome has successfully deleted
// the corrupted dictionary. We delete the corrupted dictionary to avoid
@@ -613,3 +635,132 @@ IN_PROC_BROWSER_TEST_F(SpellcheckServiceBrowserTest,
->GetString(1, &pref));
EXPECT_EQ("fr", pref);
}
+
+#if defined(OS_WIN)
+class SpellcheckServiceWindowsHybridBrowserTest
+ : public SpellcheckServiceBrowserTest {
+ public:
+ SpellcheckServiceWindowsHybridBrowserTest() = default;
+
+ void SetUp() override {
+ feature_list_.InitAndEnableFeature(spellcheck::kWinUseBrowserSpellChecker);
+ InProcessBrowserTest::SetUp();
+ }
+};
+
+IN_PROC_BROWSER_TEST_F(SpellcheckServiceWindowsHybridBrowserTest,
+ WindowsHybridSpellcheck) {
+ if (!spellcheck::WindowsVersionSupportsSpellchecker())
+ return;
+
+ ASSERT_TRUE(spellcheck::UseBrowserSpellChecker());
+
+ // Note that the base class forces dictionary sync to not be performed, which
+ // on its own would have created a SpellcheckService object. So testing here
+ // that we are still instantiating the SpellcheckService as a browser startup
+ // task to support hybrid spellchecking.
+ SpellcheckService* service = static_cast<SpellcheckService*>(
+ SpellcheckServiceFactory::GetInstance()->GetServiceForBrowserContext(
+ GetContext(), /* create */ false));
+ ASSERT_NE(nullptr, service);
+
+ // The list of Windows spellcheck languages should have been populated by at
+ // least one language. This assures that the spellcheck context menu will
+ // include Windows spellcheck languages that lack Hunspell support.
+ ASSERT_TRUE(service->dictionaries_loaded());
+ ASSERT_FALSE(service->windows_spellcheck_dictionary_map_.empty());
+}
+
+class SpellcheckServiceWindowsHybridBrowserTestDelayInit
+ : public SpellcheckServiceBrowserTest {
+ public:
+ SpellcheckServiceWindowsHybridBrowserTestDelayInit() = default;
+
+ void SetUp() override {
+ // Don't initialize the SpellcheckService on browser launch.
+ feature_list_.InitWithFeatures(
+ /*enabled_features=*/{spellcheck::kWinUseBrowserSpellChecker,
+ spellcheck::kWinDelaySpellcheckServiceInit},
+ /*disabled_features=*/{});
+ InProcessBrowserTest::SetUp();
+ }
+
+ void OnDictionariesInitialized() {
+ dictionaries_initialized_received_ = true;
+ if (quit_on_callback_)
+ std::move(quit_on_callback_).Run();
+ }
+
+ protected:
+ void RunUntilCallbackReceived() {
+ if (dictionaries_initialized_received_)
+ return;
+ base::RunLoop run_loop;
+ quit_on_callback_ = run_loop.QuitClosure();
+ run_loop.Run();
+
+ // reset status.
+ dictionaries_initialized_received_ = false;
+ }
+
+ private:
+ bool dictionaries_initialized_received_ = false;
+
+ // Quits the RunLoop on receiving the callback from InitializeDictionaries.
+ base::OnceClosure quit_on_callback_;
+};
+
+IN_PROC_BROWSER_TEST_F(SpellcheckServiceWindowsHybridBrowserTestDelayInit,
+ WindowsHybridSpellcheckDelayInit) {
+ if (!spellcheck::WindowsVersionSupportsSpellchecker())
+ return;
+
+ ASSERT_TRUE(spellcheck::UseBrowserSpellChecker());
+
+ // Note that the base class forces dictionary sync to not be performed, and
+ // the kWinDelaySpellcheckServiceInit flag is set, which together should
+ // prevent creation of a SpellcheckService object on browser startup. So
+ // testing here that this is indeed the case.
+ SpellcheckService* service = static_cast<SpellcheckService*>(
+ SpellcheckServiceFactory::GetInstance()->GetServiceForBrowserContext(
+ GetContext(), /* create */ false));
+ ASSERT_EQ(nullptr, service);
+
+ // Now create the SpellcheckService but don't call InitializeDictionaries().
+ service = static_cast<SpellcheckService*>(
+ SpellcheckServiceFactory::GetInstance()->GetServiceForBrowserContext(
+ GetContext(), /* create */ true));
+
+ ASSERT_NE(nullptr, service);
+
+ // The list of Windows spellcheck languages should not have been populated
+ // yet since InitializeDictionaries() has not been called.
+ ASSERT_FALSE(service->dictionaries_loaded());
+ ASSERT_TRUE(service->windows_spellcheck_dictionary_map_.empty());
+
+ service->InitializeDictionaries(
+ base::BindOnce(&SpellcheckServiceWindowsHybridBrowserTestDelayInit::
+ OnDictionariesInitialized,
+ base::Unretained(this)));
+
+ RunUntilCallbackReceived();
+ ASSERT_TRUE(service->dictionaries_loaded());
+ // The list of Windows spellcheck languages should now have been populated.
+ std::map<std::string, std::string>
+ windows_spellcheck_dictionary_map_first_call =
+ service->windows_spellcheck_dictionary_map_;
+ ASSERT_FALSE(windows_spellcheck_dictionary_map_first_call.empty());
+
+ // It should be safe to call InitializeDictionaries again (it should
+ // immediately run the callback).
+ service->InitializeDictionaries(
+ base::BindOnce(&SpellcheckServiceWindowsHybridBrowserTestDelayInit::
+ OnDictionariesInitialized,
+ base::Unretained(this)));
+
+ RunUntilCallbackReceived();
+ ASSERT_TRUE(service->dictionaries_loaded());
+ ASSERT_EQ(windows_spellcheck_dictionary_map_first_call,
+ service->windows_spellcheck_dictionary_map_);
+}
+#endif // defined(OS_WIN)
diff --git a/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc b/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc
index 3a4fa901884..c4ecd5f7f14 100644
--- a/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc
+++ b/chromium/chrome/browser/spellchecker/spellcheck_service_unittest.cc
@@ -12,41 +12,38 @@
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/supports_user_data.h"
+#include "base/test/scoped_feature_list.h"
+#include "build/build_config.h"
+#include "chrome/browser/first_run/first_run.h"
+#include "chrome/browser/spellchecker/spellcheck_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
+#include "chrome/test/base/testing_profile.h"
#include "components/language/core/browser/pref_names.h"
-#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
#include "components/spellcheck/browser/pref_names.h"
+#include "components/spellcheck/browser/spellcheck_platform.h"
+#include "components/spellcheck/common/spellcheck_features.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
struct TestCase {
- TestCase(const std::string& accept_languages,
- const std::string& unsplit_spellcheck_dictionaries,
- const std::string& unsplit_expected_languages,
- const std::string& unsplit_expected_languages_used_for_spellcheck)
+ TestCase(
+ const std::string& accept_languages,
+ const std::vector<std::string>& spellcheck_dictionaries,
+ const std::vector<std::string>& expected_languages,
+ const std::vector<std::string>& expected_languages_used_for_spellcheck)
: accept_languages(accept_languages),
- spellcheck_dictionaries(
- base::SplitString(unsplit_spellcheck_dictionaries,
- ",",
- base::TRIM_WHITESPACE,
- base::SPLIT_WANT_ALL)) {
- std::vector<std::string> languages =
- base::SplitString(unsplit_expected_languages, ",",
- base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
-
- std::vector<std::string> used_for_spellcheck =
- base::SplitString(unsplit_expected_languages_used_for_spellcheck, ",",
- base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
-
+ spellcheck_dictionaries(spellcheck_dictionaries) {
SpellcheckService::Dictionary dictionary;
- for (const auto& language : languages) {
- dictionary.language = language;
- dictionary.used_for_spellcheck =
- base::Contains(used_for_spellcheck, language);
- expected_dictionaries.push_back(dictionary);
+ for (const auto& language : expected_languages) {
+ if (!language.empty()) {
+ dictionary.language = language;
+ dictionary.used_for_spellcheck =
+ base::Contains(expected_languages_used_for_spellcheck, language);
+ expected_dictionaries.push_back(dictionary);
+ }
}
}
@@ -82,47 +79,74 @@ std::ostream& operator<<(std::ostream& out, const TestCase& test_case) {
return out;
}
-class SpellcheckServiceUnitTest : public testing::TestWithParam<TestCase> {
+static std::unique_ptr<KeyedService> BuildSpellcheckService(
+ content::BrowserContext* profile) {
+ return std::make_unique<SpellcheckService>(static_cast<Profile*>(profile));
+}
+
+class SpellcheckServiceUnitTestBase : public testing::Test {
public:
- SpellcheckServiceUnitTest() {
- user_prefs::UserPrefs::Set(&context_, &prefs_);
- }
- ~SpellcheckServiceUnitTest() override {}
+ SpellcheckServiceUnitTestBase() = default;
+ ~SpellcheckServiceUnitTestBase() override = default;
+
+ content::BrowserContext* browser_context() { return &profile_; }
+ PrefService* prefs() { return profile_.GetPrefs(); }
+ protected:
void SetUp() override {
- prefs()->registry()->RegisterListPref(
- spellcheck::prefs::kSpellCheckDictionaries);
- prefs()->registry()->RegisterStringPref(language::prefs::kAcceptLanguages,
- std::string());
+#if defined(OS_WIN)
+ // Tests were designed assuming Hunspell dictionary used and may fail when
+ // Windows spellcheck is enabled by default.
+ feature_list_.InitAndDisableFeature(spellcheck::kWinUseBrowserSpellChecker);
+#endif // defined(OS_WIN)
+
+ // Use SetTestingFactoryAndUse to force creation and initialization.
+ SpellcheckServiceFactory::GetInstance()->SetTestingFactoryAndUse(
+ &profile_, base::BindRepeating(&BuildSpellcheckService));
}
- base::SupportsUserData* context() { return &context_; }
- TestingPrefServiceSimple* prefs() { return &prefs_; }
+ content::BrowserTaskEnvironment task_environment_;
+
+#if defined(OS_WIN)
+ // feature_list_ needs to be destroyed after profile_.
+ base::test::ScopedFeatureList feature_list_;
+#endif // defined(OS_WIN)
+ TestingProfile profile_;
private:
- struct : public base::SupportsUserData {
- } context_;
- TestingPrefServiceSimple prefs_;
- content::BrowserTaskEnvironment task_environment_;
+ DISALLOW_COPY_AND_ASSIGN(SpellcheckServiceUnitTestBase);
+};
- DISALLOW_COPY_AND_ASSIGN(SpellcheckServiceUnitTest);
+class SpellcheckServiceUnitTest : public SpellcheckServiceUnitTestBase,
+ public testing::WithParamInterface<TestCase> {
};
INSTANTIATE_TEST_SUITE_P(
TestCases,
SpellcheckServiceUnitTest,
testing::Values(
- TestCase("en,aa", "aa", "", ""),
- TestCase("en,en-JP,fr,aa", "fr", "fr", "fr"),
- TestCase("en,en-JP,fr,zz,en-US", "fr", "fr,en-US", "fr"),
- TestCase("en,en-US,en-GB", "en-GB", "en-US,en-GB", "en-GB"),
- TestCase("en,en-US,en-AU", "en-AU", "en-US,en-AU", "en-AU"),
- TestCase("en,en-US,en-AU", "en-US", "en-US,en-AU", "en-US"),
- TestCase("en,en-US", "en-US", "en-US", "en-US"),
- TestCase("en,en-US,fr", "en-US", "en-US,fr", "en-US"),
- TestCase("en,fr,en-US,en-AU", "en-US,fr", "fr,en-US,en-AU", "fr,en-US"),
- TestCase("en-US,en", "en-US", "en-US", "en-US"),
- TestCase("hu-HU,hr-HR", "hr", "hu,hr", "hr")));
+ TestCase("en,aa", {"aa"}, {""}, {""}),
+ TestCase("en,en-JP,fr,aa", {"fr"}, {"fr"}, {"fr"}),
+ TestCase("en,en-JP,fr,zz,en-US", {"fr"}, {"fr", "en-US"}, {"fr"}),
+ TestCase("en,en-US,en-GB", {"en-GB"}, {"en-US", "en-GB"}, {"en-GB"}),
+ TestCase("en,en-US,en-AU", {"en-AU"}, {"en-US", "en-AU"}, {"en-AU"}),
+ TestCase("en,en-US,en-AU", {"en-US"}, {"en-US", "en-AU"}, {"en-US"}),
+ TestCase("en,en-US", {"en-US"}, {"en-US"}, {"en-US"}),
+ TestCase("en,en-US,fr", {"en-US"}, {"en-US", "fr"}, {"en-US"}),
+ TestCase("en,fr,en-US,en-AU",
+ {"en-US", "fr"},
+ {"fr", "en-US", "en-AU"},
+ {"fr", "en-US"}),
+ TestCase("en-US,en", {"en-US"}, {"en-US"}, {"en-US"}),
+#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+ // Scenario where user disabled the Windows spellcheck feature with some
+ // non-Hunspell languages set in preferences.
+ TestCase("fr,eu,en-US,ar",
+ {"fr", "eu", "en-US", "ar"},
+ {"fr", "en-US"},
+ {"fr", "en-US"}),
+#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+ TestCase("hu-HU,hr-HR", {"hr"}, {"hu", "hr"}, {"hr"})));
TEST_P(SpellcheckServiceUnitTest, GetDictionaries) {
prefs()->SetString(language::prefs::kAcceptLanguages,
@@ -133,7 +157,340 @@ TEST_P(SpellcheckServiceUnitTest, GetDictionaries) {
spellcheck_dictionaries);
std::vector<SpellcheckService::Dictionary> dictionaries;
- SpellcheckService::GetDictionaries(context(), &dictionaries);
+ SpellcheckService::GetDictionaries(browser_context(), &dictionaries);
EXPECT_EQ(GetParam().expected_dictionaries, dictionaries);
}
+
+#if defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
+class SpellcheckServiceHybridUnitTestBase
+ : public SpellcheckServiceUnitTestBase {
+ public:
+ SpellcheckServiceHybridUnitTestBase() = default;
+
+ protected:
+ void SetUp() override {
+ InitFeatures();
+
+ // Add command line switch that forces first run state, since code path
+ // through SpellcheckService::InitWindowsDictionaryLanguages depends on
+ // whether this is first run.
+ first_run::ResetCachedSentinelDataForTesting();
+ base::CommandLine::ForCurrentProcess()->AppendSwitch(
+ switches::kForceFirstRun);
+
+ // Use SetTestingFactoryAndUse to force creation and initialization.
+ SpellcheckServiceFactory::GetInstance()->SetTestingFactoryAndUse(
+ &profile_, base::BindRepeating(&BuildSpellcheckService));
+ }
+
+ virtual void InitFeatures() {
+ feature_list_.InitAndEnableFeature(spellcheck::kWinUseBrowserSpellChecker);
+ }
+
+ virtual void InitializeSpellcheckService(
+ const std::vector<std::string>& spellcheck_languages_for_testing) {
+ // Fake the presence of Windows spellcheck dictionaries.
+ spellcheck_service_ =
+ SpellcheckServiceFactory::GetInstance()->GetForContext(
+ browser_context());
+
+ spellcheck_service_->InitWindowsDictionaryLanguages(
+ spellcheck_languages_for_testing);
+
+ ASSERT_TRUE(spellcheck_service_->dictionaries_loaded());
+ }
+
+ void RunGetDictionariesTest(
+ const std::string accept_languages,
+ const std::vector<std::string> spellcheck_dictionaries,
+ const std::vector<SpellcheckService::Dictionary> expected_dictionaries);
+
+ void RunDictionaryMappingTest(
+ const std::string full_tag,
+ const std::string expected_accept_language,
+ const std::string expected_tag_passed_to_spellcheck);
+
+ // Used for faking the presence of Windows spellcheck dictionaries.
+ static const std::vector<std::string>
+ windows_spellcheck_languages_for_testing_;
+
+ SpellcheckService* spellcheck_service_;
+};
+
+void SpellcheckServiceHybridUnitTestBase::RunGetDictionariesTest(
+ const std::string accept_languages,
+ const std::vector<std::string> spellcheck_dictionaries,
+ const std::vector<SpellcheckService::Dictionary> expected_dictionaries) {
+ if (!spellcheck::WindowsVersionSupportsSpellchecker())
+ return;
+
+ prefs()->SetString(language::prefs::kAcceptLanguages, accept_languages);
+ base::ListValue spellcheck_dictionaries_list;
+ spellcheck_dictionaries_list.AppendStrings(spellcheck_dictionaries);
+ prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries,
+ spellcheck_dictionaries_list);
+
+ InitializeSpellcheckService(windows_spellcheck_languages_for_testing_);
+
+ std::vector<SpellcheckService::Dictionary> dictionaries;
+ SpellcheckService::GetDictionaries(browser_context(), &dictionaries);
+
+ EXPECT_EQ(expected_dictionaries, dictionaries);
+}
+
+void SpellcheckServiceHybridUnitTestBase::RunDictionaryMappingTest(
+ const std::string full_tag,
+ const std::string expected_accept_language,
+ const std::string expected_tag_passed_to_spellcheck) {
+ if (!spellcheck::WindowsVersionSupportsSpellchecker())
+ return;
+
+ InitializeSpellcheckService({full_tag});
+
+ std::string supported_accept_language =
+ SpellcheckService::GetSupportedAcceptLanguageCode(full_tag);
+
+ EXPECT_EQ(expected_accept_language, supported_accept_language);
+
+ if (!supported_accept_language.empty()) {
+ EXPECT_EQ(full_tag,
+ spellcheck_service_->GetSupportedWindowsDictionaryLanguage(
+ expected_accept_language));
+ } else {
+ // Unsupported language--should not be in map.
+ ASSERT_TRUE(
+ spellcheck_service_->windows_spellcheck_dictionary_map_.empty());
+ }
+
+ EXPECT_EQ(expected_tag_passed_to_spellcheck,
+ SpellcheckService::GetTagToPassToWindowsSpellchecker(
+ expected_accept_language, full_tag));
+
+ // Special case for Serbian. The "sr" accept language is interpreted as using
+ // Cyrillic script. There should be an extra entry in the windows dictionary
+ // map if Cyrillic windows dictionary is installed.
+ if (base::EqualsCaseInsensitiveASCII(
+ "sr-Cyrl", SpellcheckService::GetLanguageAndScriptTag(
+ full_tag,
+ /* include_script_tag */ true))) {
+ EXPECT_EQ(full_tag,
+ spellcheck_service_->GetSupportedWindowsDictionaryLanguage("sr"));
+ } else {
+ EXPECT_TRUE(spellcheck_service_->GetSupportedWindowsDictionaryLanguage("sr")
+ .empty());
+ }
+}
+
+// static
+const std::vector<std::string> SpellcheckServiceHybridUnitTestBase::
+ windows_spellcheck_languages_for_testing_ = {
+ "fr-FR", // Has both Windows and Hunspell support.
+ "es-MX", // Has both Windows and Hunspell support, but for Hunspell
+ // maps to es-ES.
+ "gl-ES", // (Galician) Has only Windows support, no Hunspell
+ // dictionary.
+ "fi-FI", // (Finnish) Has only Windows support, no Hunspell
+ // dictionary.
+ "haw-US", // (Hawaiian) No Hunspell dictionary. Note that first two
+ // letters of language code are "ha," the same as Hausa.
+ "ast", // (Asturian) Has only Windows support, no Hunspell
+ // dictionary. Note that last two letters of language
+ // code are "st," the same as Sesotho.
+ "kok-Deva-IN", // Konkani (Devanagari, India)--note presence of
+ // script subtag.
+ "sr-Cyrl-ME", // Serbian (Cyrillic, Montenegro)--note presence of
+ // script subtag.
+ "sr-Latn-ME", // Serbian (Latin, Montenegro)--note presence of
+ // script subtag.
+ "ja-Latn-JP-x-ext", // Japanese with Latin script--note presence of
+ // private use subtag. Ignore private use
+ // dictionaries.
+};
+
+class SpellcheckServiceHybridUnitTest
+ : public SpellcheckServiceHybridUnitTestBase,
+ public testing::WithParamInterface<TestCase> {};
+
+static const TestCase kHybridGetDictionariesParams[] = {
+ // Galician (gl) has only Windows support, no Hunspell dictionary. Croatian
+ // (hr) has only Hunspell support, no local Windows dictionary. First
+ // language is supported by windows and should be spellchecked
+ TestCase("gl", {""}, {"gl"}, {"gl"}),
+ TestCase("gl", {"gl"}, {"gl"}, {"gl"}),
+ TestCase("gl,hr", {""}, {"gl", "hr"}, {"gl"}),
+ TestCase("gl,hr", {"gl"}, {"gl", "hr"}, {"gl"}),
+ TestCase("gl,hr", {"hr"}, {"gl", "hr"}, {"gl", "hr"}),
+ TestCase("gl,hr", {"gl", "hr"}, {"gl", "hr"}, {"gl", "hr"}),
+ // First language is not supported by windows so nothing is changed
+ TestCase("hr", {""}, {"hr"}, {""}), TestCase("hr", {"hr"}, {"hr"}, {"hr"}),
+ TestCase("hr,gl", {"hr"}, {"hr", "gl"}, {"hr"}),
+ // Finnish has only "fi" in hard-coded list of accept languages.
+ TestCase("fi-FI,fi,en-US,en", {"en-US"}, {"fi", "en-US"}, {"fi", "en-US"}),
+ // First language is supported by Windows but private use dictionaries
+ // are ignored.
+ TestCase("ja,gl", {"gl"}, {"gl"}, {"gl"}),
+ // (Basque) No Hunspell support, has Windows support but
+ // language pack not present.
+ TestCase("eu", {"eu"}, {""}, {""}),
+ TestCase("es-419,es-MX",
+ {"es-419", "es-MX"},
+ {"es-419", "es-MX"},
+ {"es-419", "es-MX"}),
+ TestCase("fr-FR,es-MX,gl,pt-BR,hr,it",
+ {"fr-FR", "gl", "pt-BR", "it"},
+ {"fr-FR", "es-MX", "gl", "pt-BR", "hr", "it"},
+ {"fr-FR", "gl", "pt-BR", "it"}),
+ // Hausa with Hawaiian language pack (ha/haw string in string).
+ TestCase("ha", {"ha"}, {""}, {""}),
+ // Sesotho with Asturian language pack (st/ast string in string).
+ TestCase("st", {"st"}, {""}, {""}),
+ // User chose generic Serbian in languages preferences (which uses
+ // Cyrillic script).
+ TestCase("sr,sr-Latn-RS", {"sr", "sr-Latn-RS"}, {"sr"}, {"sr"})};
+
+INSTANTIATE_TEST_SUITE_P(TestCases,
+ SpellcheckServiceHybridUnitTest,
+ testing::ValuesIn(kHybridGetDictionariesParams));
+
+TEST_P(SpellcheckServiceHybridUnitTest, GetDictionaries) {
+ RunGetDictionariesTest(GetParam().accept_languages,
+ GetParam().spellcheck_dictionaries,
+ GetParam().expected_dictionaries);
+}
+
+struct DictionaryMappingTestCase {
+ std::string full_tag;
+ std::string expected_accept_language;
+ std::string expected_tag_passed_to_spellcheck;
+};
+
+std::ostream& operator<<(std::ostream& out,
+ const DictionaryMappingTestCase& test_case) {
+ out << "full_tag=" << test_case.full_tag
+ << ", expected_accept_language=" << test_case.expected_accept_language
+ << ", expected_tag_passed_to_spellcheck="
+ << test_case.expected_tag_passed_to_spellcheck;
+
+ return out;
+}
+
+class SpellcheckServiceWindowsDictionaryMappingUnitTest
+ : public SpellcheckServiceHybridUnitTestBase,
+ public testing::WithParamInterface<DictionaryMappingTestCase> {};
+
+static const DictionaryMappingTestCase kHybridDictionaryMappingsParams[] = {
+ DictionaryMappingTestCase({"en-CA", "en-CA", "en-CA"}),
+ DictionaryMappingTestCase({"en-PH", "en", "en"}),
+ DictionaryMappingTestCase({"es-MX", "es-MX", "es-MX"}),
+ DictionaryMappingTestCase({"ar-SA", "ar", "ar"}),
+ // Konkani not supported in Chromium.
+ DictionaryMappingTestCase({"kok-Deva-IN", "", "kok-Deva"}),
+ DictionaryMappingTestCase({"sr-Cyrl-RS", "sr", "sr-Cyrl"}),
+ DictionaryMappingTestCase({"sr-Cyrl-ME", "sr", "sr-Cyrl"}),
+ // Only sr with Cyrillic implied supported in Chromium.
+ DictionaryMappingTestCase({"sr-Latn-RS", "", "sr-Latn"}),
+ DictionaryMappingTestCase({"sr-Latn-ME", "", "sr-Latn"}),
+ DictionaryMappingTestCase({"ca-ES", "ca", "ca"}),
+ DictionaryMappingTestCase({"ca-ES-valencia", "ca", "ca"})};
+
+INSTANTIATE_TEST_SUITE_P(TestCases,
+ SpellcheckServiceWindowsDictionaryMappingUnitTest,
+ testing::ValuesIn(kHybridDictionaryMappingsParams));
+
+TEST_P(SpellcheckServiceWindowsDictionaryMappingUnitTest, CheckMappings) {
+ RunDictionaryMappingTest(GetParam().full_tag,
+ GetParam().expected_accept_language,
+ GetParam().expected_tag_passed_to_spellcheck);
+}
+
+class SpellcheckServiceHybridUnitTestDelayInitBase
+ : public SpellcheckServiceHybridUnitTestBase {
+ public:
+ SpellcheckServiceHybridUnitTestDelayInitBase() = default;
+
+ void OnDictionariesInitialized() {
+ dictionaries_initialized_received_ = true;
+ if (quit_)
+ std::move(quit_).Run();
+ }
+
+ protected:
+ void InitFeatures() override {
+ // Don't initialize the SpellcheckService on browser launch.
+ feature_list_.InitWithFeatures(
+ /*enabled_features=*/{spellcheck::kWinUseBrowserSpellChecker,
+ spellcheck::kWinDelaySpellcheckServiceInit},
+ /*disabled_features=*/{});
+ }
+
+ void InitializeSpellcheckService(
+ const std::vector<std::string>& spellcheck_languages_for_testing)
+ override {
+ // Fake the presence of Windows spellcheck dictionaries.
+ spellcheck_service_ =
+ SpellcheckServiceFactory::GetInstance()->GetForContext(
+ browser_context());
+
+ spellcheck_service_->AddSpellcheckLanguagesForTesting(
+ spellcheck_languages_for_testing);
+
+ // Asynchronously load the dictionaries.
+ ASSERT_FALSE(spellcheck_service_->dictionaries_loaded());
+ spellcheck_service_->InitializeDictionaries(
+ base::BindOnce(&SpellcheckServiceHybridUnitTestDelayInitBase::
+ OnDictionariesInitialized,
+ base::Unretained(this)));
+
+ RunUntilCallbackReceived();
+ ASSERT_TRUE(spellcheck_service_->dictionaries_loaded());
+ }
+
+ void RunUntilCallbackReceived() {
+ if (dictionaries_initialized_received_)
+ return;
+ base::RunLoop run_loop;
+ quit_ = run_loop.QuitClosure();
+ run_loop.Run();
+
+ // reset status.
+ dictionaries_initialized_received_ = false;
+ }
+
+ private:
+ bool dictionaries_initialized_received_ = false;
+
+ // Quits the RunLoop on receiving the callback from InitializeDictionaries.
+ base::OnceClosure quit_;
+};
+
+class SpellcheckServiceHybridUnitTestDelayInit
+ : public SpellcheckServiceHybridUnitTestDelayInitBase,
+ public testing::WithParamInterface<TestCase> {};
+
+INSTANTIATE_TEST_SUITE_P(TestCases,
+ SpellcheckServiceHybridUnitTestDelayInit,
+ testing::ValuesIn(kHybridGetDictionariesParams));
+
+TEST_P(SpellcheckServiceHybridUnitTestDelayInit, GetDictionaries) {
+ RunGetDictionariesTest(GetParam().accept_languages,
+ GetParam().spellcheck_dictionaries,
+ GetParam().expected_dictionaries);
+}
+
+class SpellcheckServiceWindowsDictionaryMappingUnitTestDelayInit
+ : public SpellcheckServiceHybridUnitTestDelayInitBase,
+ public testing::WithParamInterface<DictionaryMappingTestCase> {};
+
+INSTANTIATE_TEST_SUITE_P(
+ TestCases,
+ SpellcheckServiceWindowsDictionaryMappingUnitTestDelayInit,
+ testing::ValuesIn(kHybridDictionaryMappingsParams));
+
+TEST_P(SpellcheckServiceWindowsDictionaryMappingUnitTestDelayInit,
+ CheckMappings) {
+ RunDictionaryMappingTest(GetParam().full_tag,
+ GetParam().expected_accept_language,
+ GetParam().expected_tag_passed_to_spellcheck);
+}
+#endif // defined(OS_WIN) && BUILDFLAG(USE_BROWSER_SPELLCHECKER)
diff --git a/chromium/chrome/browser/spellchecker/spelling_request.cc b/chromium/chrome/browser/spellchecker/spelling_request.cc
index 37e993acff9..d3029666f29 100644
--- a/chromium/chrome/browser/spellchecker/spelling_request.cc
+++ b/chromium/chrome/browser/spellchecker/spelling_request.cc
@@ -7,7 +7,6 @@
#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"
@@ -133,8 +132,8 @@ void SpellingRequest::OnLocalCheckCompletedOnAnyThread(
base::WeakPtr<SpellingRequest> request,
const std::vector<SpellCheckResult>& results) {
// Local checking can happen on any thread - don't DCHECK thread.
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&SpellingRequest::OnLocalCheckCompleted,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&SpellingRequest::OnLocalCheckCompleted,
request, results));
}
diff --git a/chromium/chrome/browser/subresource_filter/BUILD.gn b/chromium/chrome/browser/subresource_filter/BUILD.gn
index 86151132998..89289d9aed1 100644
--- a/chromium/chrome/browser/subresource_filter/BUILD.gn
+++ b/chromium/chrome/browser/subresource_filter/BUILD.gn
@@ -26,6 +26,7 @@ if (is_android) {
"//chrome/android:chrome_java",
"//chrome/android:chrome_test_java",
"//chrome/browser/tab:java",
+ "//chrome/browser/tabmodel:java",
"//chrome/browser/ui/messages/android:java",
"//chrome/test/android:chrome_java_test_support",
"//components/safe_browsing/android:safe_browsing_java",
diff --git a/chromium/chrome/browser/tab/BUILD.gn b/chromium/chrome/browser/tab/BUILD.gn
index cef802edf3a..f8606d00a4c 100644
--- a/chromium/chrome/browser/tab/BUILD.gn
+++ b/chromium/chrome/browser/tab/BUILD.gn
@@ -4,7 +4,6 @@
import("//build/config/android/config.gni")
import("//build/config/android/rules.gni")
-import("//chrome/android/features/android_library_factory_tmpl.gni")
import("//chrome/browser/buildflags.gni")
android_library("java") {
@@ -14,9 +13,13 @@ android_library("java") {
"java/src/org/chromium/chrome/browser/tab/TabAttributeKeys.java",
"java/src/org/chromium/chrome/browser/tab/TabAttributes.java",
"java/src/org/chromium/chrome/browser/tab/TabCreationState.java",
+ "java/src/org/chromium/chrome/browser/tab/TabDelegateFactory.java",
"java/src/org/chromium/chrome/browser/tab/TabHidingType.java",
"java/src/org/chromium/chrome/browser/tab/TabLifecycle.java",
"java/src/org/chromium/chrome/browser/tab/TabObserver.java",
+ "java/src/org/chromium/chrome/browser/tab/TabViewManager.java",
+ "java/src/org/chromium/chrome/browser/tab/TabViewProvider.java",
+ "java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroid.java",
]
# TabSelectionType, TabLaunchType
@@ -24,9 +27,14 @@ android_library("java") {
deps = [
"//base:base_java",
+ "//chrome/browser/contextmenu:java",
"//chrome/browser/ui/android/native_page:java",
+ "//components/browser_ui/util/android:java",
"//components/embedder_support/android:content_view_java",
+ "//components/embedder_support/android:web_contents_delegate_java",
+ "//components/external_intents/android:java",
"//components/find_in_page/android:java",
+ "//components/navigation_interception/android:navigation_interception_java",
"//content/public/android:content_java",
"//ui/android:ui_full_java",
]
diff --git a/chromium/chrome/browser/tab_contents/form_interaction_tab_helper.cc b/chromium/chrome/browser/tab_contents/form_interaction_tab_helper.cc
index a051fd57620..9161993328e 100644
--- a/chromium/chrome/browser/tab_contents/form_interaction_tab_helper.cc
+++ b/chromium/chrome/browser/tab_contents/form_interaction_tab_helper.cc
@@ -5,7 +5,6 @@
#include "chrome/browser/tab_contents/form_interaction_tab_helper.h"
#include "base/bind.h"
-#include "base/task/post_task.h"
#include "components/performance_manager/public/graph/graph.h"
#include "components/performance_manager/public/graph/page_node.h"
#include "components/performance_manager/public/performance_manager.h"
@@ -68,8 +67,8 @@ void FormInteractionTabHelper::GraphObserver::DispatchOnHadFormInteraction(
void FormInteractionTabHelper::GraphObserver::OnHadFormInteractionChanged(
const performance_manager::PageNode* page_node) {
// Forward the notification over to the UI thread.
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&GraphObserver::DispatchOnHadFormInteraction,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&GraphObserver::DispatchOnHadFormInteraction,
page_node->GetContentsProxy(),
page_node->HadFormInteraction()));
}
diff --git a/chromium/chrome/browser/tab_contents/form_interaction_tab_helper_unittest.cc b/chromium/chrome/browser/tab_contents/form_interaction_tab_helper_unittest.cc
index 88bc9fe0d5a..38c7993d8a3 100644
--- a/chromium/chrome/browser/tab_contents/form_interaction_tab_helper_unittest.cc
+++ b/chromium/chrome/browser/tab_contents/form_interaction_tab_helper_unittest.cc
@@ -19,6 +19,7 @@
#include "components/performance_manager/public/performance_manager.h"
#include "components/performance_manager/test_support/graph_impl.h"
#include "components/performance_manager/test_support/mock_graphs.h"
+#include "components/performance_manager/test_support/test_harness_helper.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/navigation_simulator.h"
@@ -36,9 +37,7 @@ class FormInteractionTabHelperTest : public ChromeRenderViewHostTestHarness {
void SetUp() override {
ChromeRenderViewHostTestHarness::SetUp();
- perf_man_ =
- performance_manager::PerformanceManagerImpl::Create(base::DoNothing());
- registry_ = performance_manager::PerformanceManagerRegistry::Create();
+ pm_harness_.SetUp();
performance_manager::testing::CreatePageAggregatorAndPassItToGraph();
performance_manager::PerformanceManagerImpl::CallOnGraph(
FROM_HERE, base::BindOnce([](performance_manager::Graph* graph) {
@@ -49,7 +48,6 @@ class FormInteractionTabHelperTest : public ChromeRenderViewHostTestHarness {
std::unique_ptr<content::WebContents> CreateTestWebContents() {
std::unique_ptr<content::WebContents> contents =
ChromeRenderViewHostTestHarness::CreateTestWebContents();
- registry_->CreatePageNodeForWebContents(contents.get());
FormInteractionTabHelper::CreateForWebContents(contents.get());
// Simulate a navigation event to force the initialization of the main
// frame.
@@ -60,16 +58,12 @@ class FormInteractionTabHelperTest : public ChromeRenderViewHostTestHarness {
}
void TearDown() override {
- registry_->TearDown();
- registry_.reset();
- performance_manager::PerformanceManagerImpl::Destroy(std::move(perf_man_));
- task_environment()->RunUntilIdle();
+ pm_harness_.TearDown();
ChromeRenderViewHostTestHarness::TearDown();
}
private:
- std::unique_ptr<performance_manager::PerformanceManagerImpl> perf_man_;
- std::unique_ptr<performance_manager::PerformanceManagerRegistry> registry_;
+ performance_manager::PerformanceManagerTestHarnessHelper pm_harness_;
};
TEST_F(FormInteractionTabHelperTest, HadFormInteractionSingleFrame) {
diff --git a/chromium/chrome/browser/tab_contents/navigation_metrics_recorder_browsertest.cc b/chromium/chrome/browser/tab_contents/navigation_metrics_recorder_browsertest.cc
index c3e8989646e..4d693b58603 100644
--- a/chromium/chrome/browser/tab_contents/navigation_metrics_recorder_browsertest.cc
+++ b/chromium/chrome/browser/tab_contents/navigation_metrics_recorder_browsertest.cc
@@ -11,6 +11,7 @@
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/ui_test_utils.h"
+#include "components/navigation_metrics/navigation_metrics.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/web_contents.h"
@@ -53,11 +54,13 @@ IN_PROC_BROWSER_TEST_F(NavigationMetricsRecorderBrowserTest, TestMetrics) {
base::HistogramTester histograms;
ui_test_utils::NavigateToURL(browser(),
GURL("data:text/html, <html></html>"));
- histograms.ExpectTotalCount("Navigation.MainFrameScheme", 1);
- histograms.ExpectBucketCount("Navigation.MainFrameScheme", 5 /* data: */, 1);
- histograms.ExpectTotalCount("Navigation.MainFrameSchemeDifferentPage", 1);
- histograms.ExpectBucketCount("Navigation.MainFrameSchemeDifferentPage",
+ histograms.ExpectTotalCount(navigation_metrics::kMainFrameScheme, 1);
+ histograms.ExpectBucketCount(navigation_metrics::kMainFrameScheme,
5 /* data: */, 1);
+ histograms.ExpectTotalCount(navigation_metrics::kMainFrameSchemeDifferentPage,
+ 1);
+ histograms.ExpectBucketCount(
+ navigation_metrics::kMainFrameSchemeDifferentPage, 5 /* data: */, 1);
}
IN_PROC_BROWSER_TEST_F(NavigationMetricsRecorderBrowserTest,
diff --git a/chromium/chrome/browser/tab_contents/view_source_browsertest.cc b/chromium/chrome/browser/tab_contents/view_source_browsertest.cc
index bd11caab8dd..dc01e1f9b4f 100644
--- a/chromium/chrome/browser/tab_contents/view_source_browsertest.cc
+++ b/chromium/chrome/browser/tab_contents/view_source_browsertest.cc
@@ -339,7 +339,18 @@ IN_PROC_BROWSER_TEST_F(ViewSourceTest, HttpPostInMainframe) {
"document.getElementById('form').submit();"));
form_post_observer.Wait();
GURL target_url(embedded_test_server()->GetURL("a.com", "/echoall"));
- EXPECT_EQ(target_url, original_main_frame->GetLastCommittedURL());
+
+ content::RenderFrameHost* current_main_frame =
+ original_contents->GetMainFrame();
+ if (content::CanSameSiteMainFrameNavigationsChangeRenderFrameHosts()) {
+ // When ProactivelySwapBrowsingInstance or RenderDocument is enabled on
+ // same-site main frame navigations, the form submission above will result
+ // in a change of RFH.
+ EXPECT_NE(current_main_frame, original_main_frame);
+ } else {
+ EXPECT_EQ(current_main_frame, original_main_frame);
+ }
+ EXPECT_EQ(target_url, current_main_frame->GetLastCommittedURL());
// Extract the response nonce.
std::string response_nonce;
@@ -347,13 +358,13 @@ IN_PROC_BROWSER_TEST_F(ViewSourceTest, HttpPostInMainframe) {
domAutomationController.send(
document.getElementById('response-nonce').innerText); )";
EXPECT_TRUE(ExecuteScriptAndExtractString(
- original_main_frame, response_nonce_extraction_script, &response_nonce));
+ current_main_frame, response_nonce_extraction_script, &response_nonce));
// Open view-source mode tab for the main frame. This tries to mimic the
// behavior of RenderViewContextMenu::ExecuteCommand when it handles
// IDC_CONTENT_CONTEXT_VIEWFRAMESOURCE.
content::WebContentsAddedObserver view_source_contents_observer;
- original_main_frame->ViewSource();
+ current_main_frame->ViewSource();
content::WebContents* view_source_contents =
view_source_contents_observer.GetWebContents();
EXPECT_TRUE(WaitForLoadStop(view_source_contents));
@@ -390,7 +401,7 @@ IN_PROC_BROWSER_TEST_F(ViewSourceTest, HttpPostInMainframe) {
// Verify that the original contents and the view-source contents are in a
// different process - see https://crbug.com/699493.
- EXPECT_NE(original_main_frame->GetSiteInstance(),
+ EXPECT_NE(current_main_frame->GetSiteInstance(),
view_source_contents->GetMainFrame()->GetSiteInstance());
// Verify the title of view-source is derived from the URL (not from the title
@@ -399,7 +410,7 @@ IN_PROC_BROWSER_TEST_F(ViewSourceTest, HttpPostInMainframe) {
EXPECT_EQ("EmbeddedTestServer - EchoAll",
base::UTF16ToUTF8(original_contents->GetTitle()));
EXPECT_THAT(title, Not(HasSubstr("EmbeddedTestServer - EchoAll")));
- GURL original_url = original_main_frame->GetLastCommittedURL();
+ GURL original_url = current_main_frame->GetLastCommittedURL();
EXPECT_THAT(title, HasSubstr(content::kViewSourceScheme));
EXPECT_THAT(title, HasSubstr(original_url.host()));
EXPECT_THAT(title, HasSubstr(original_url.port()));
diff --git a/chromium/chrome/browser/tabmodel/BUILD.gn b/chromium/chrome/browser/tabmodel/BUILD.gn
new file mode 100644
index 00000000000..21fb576b444
--- /dev/null
+++ b/chromium/chrome/browser/tabmodel/BUILD.gn
@@ -0,0 +1,31 @@
+# Copyright 2020 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//build/config/android/rules.gni")
+
+android_library("java") {
+ sources = [
+ "android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModel.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModelFilter.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModelSelectorObserver.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/NextTabPolicy.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/TabList.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/TabModel.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/TabModelFilter.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/TabModelFilterFactory.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/TabModelFilterProvider.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/TabModelObserver.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/TabModelSelector.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/TabModelSelectorObserver.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/TabModelSelectorTabModelObserver.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/TabModelSelectorTabObserver.java",
+ "android/java/src/org/chromium/chrome/browser/tabmodel/TabModelUtils.java",
+ ]
+ deps = [
+ "//base:base_java",
+ "//chrome/browser/profiles/android:java",
+ "//chrome/browser/tab:java",
+ "//content/public/android:content_java",
+ ]
+}
diff --git a/chromium/chrome/browser/thumbnail/generator/BUILD.gn b/chromium/chrome/browser/thumbnail/generator/BUILD.gn
index a4dd63a43df..361335f2028 100644
--- a/chromium/chrome/browser/thumbnail/generator/BUILD.gn
+++ b/chromium/chrome/browser/thumbnail/generator/BUILD.gn
@@ -114,6 +114,7 @@ if (is_android) {
"//chrome/browser/flags:java",
"//chrome/browser/util:java",
"//chrome/test/android:chrome_java_test_support",
+ "//components/browser_ui/util/android:java",
"//content/public/android:content_java",
"//content/public/test/android:content_java_test_support",
"//third_party/android_deps:android_support_v4_java",
diff --git a/chromium/chrome/browser/touch_to_fill/android/BUILD.gn b/chromium/chrome/browser/touch_to_fill/android/BUILD.gn
index de15117cc14..9231bf842ab 100644
--- a/chromium/chrome/browser/touch_to_fill/android/BUILD.gn
+++ b/chromium/chrome/browser/touch_to_fill/android/BUILD.gn
@@ -3,7 +3,6 @@
# found in the LICENSE file.
import("//build/config/android/rules.gni")
-import("//chrome/android/features/android_library_factory_tmpl.gni")
source_set("android") {
visibility = [ "//chrome/browser/touch_to_fill:factory" ]
@@ -28,9 +27,6 @@ generate_jni("jni_headers") {
android_library("public_java") {
deps = [
- # TODO(crbug.com/1004415): Remove dependency on chrome_java and depend on
- # bottomsheet directly. Add public_java to chrome_java target instead.
- "//chrome/android:chrome_java",
"//components/browser_ui/android/bottomsheet:java",
"//ui/android:ui_java",
]
@@ -47,13 +43,22 @@ junit_binary("touch_to_fill_junit_tests") {
sources = [ "junit/src/org/chromium/chrome/browser/touch_to_fill/TouchToFillControllerTest.java" ]
deps = [
+ "//base:base_java",
"//base:base_java_test_support",
"//base:base_junit_test_support",
+ "//chrome/android:chrome_java",
"//chrome/android:chrome_test_util_java",
+ "//chrome/browser/touch_to_fill/android:public_java",
"//chrome/browser/touch_to_fill/android/internal:java",
+ "//chrome/browser/ui/android/favicon:java",
+ "//chrome/test/android:chrome_java_test_support",
+ "//components/browser_ui/android/bottomsheet:java",
"//components/module_installer/android:module_installer_java",
+ "//components/url_formatter/android:url_formatter_java",
+ "//third_party/hamcrest:hamcrest_java",
"//third_party/junit",
"//third_party/mockito:mockito_java",
+ "//ui/android:ui_full_java",
]
}
@@ -75,9 +80,10 @@ android_library("test_java") {
"//chrome/browser/touch_to_fill/android/internal:java",
"//chrome/test/android:chrome_java_test_support",
"//components/browser_ui/android/bottomsheet:java",
+ "//components/browser_ui/android/bottomsheet/test:java",
"//content/public/test/android:content_java_test_support",
"//third_party/android_deps:androidx_recyclerview_recyclerview_java",
- "//third_party/espresso:espresso_all_java",
+ "//third_party/android_deps:espresso_java",
"//third_party/hamcrest:hamcrest_java",
"//third_party/junit",
"//third_party/mockito:mockito_java",
diff --git a/chromium/chrome/browser/touch_to_fill/android/internal/BUILD.gn b/chromium/chrome/browser/touch_to_fill/android/internal/BUILD.gn
index 28683e96f91..66dfa82cb62 100644
--- a/chromium/chrome/browser/touch_to_fill/android/internal/BUILD.gn
+++ b/chromium/chrome/browser/touch_to_fill/android/internal/BUILD.gn
@@ -17,6 +17,7 @@ android_library("java") {
"//chrome/browser/touch_to_fill/android:public_java",
"//chrome/browser/ui/android/favicon:java",
"//chrome/browser/util:java",
+ "//components/browser_ui/android/bottomsheet:java",
"//components/embedder_support/android:util_java",
"//components/url_formatter/android:url_formatter_java",
"//third_party/android_deps:androidx_recyclerview_recyclerview_java",
diff --git a/chromium/chrome/browser/ui/BUILD.gn b/chromium/chrome/browser/ui/BUILD.gn
index 4a31f9315ce..a429fd97511 100644
--- a/chromium/chrome/browser/ui/BUILD.gn
+++ b/chromium/chrome/browser/ui/BUILD.gn
@@ -26,6 +26,12 @@ import("//third_party/protobuf/proto_library.gni")
import("//ui/base/ui_features.gni")
import("//ui/views/features.gni")
+# Reset sources_assignment_filter for the BUILD.gn file to prevent
+# regression during the migration of Chromium away from the feature.
+# See docs/no_sources_assignment_filter.md for more information.
+# TODO(crbug.com/1018739): remove this when migration is done.
+set_sources_assignment_filter([])
+
# Use a static library here because many test binaries depend on this but don't
# require many files from it. This makes linking more efficient.
static_library("ui") {
@@ -39,8 +45,6 @@ static_library("ui") {
"autofill/autofill_popup_controller.h",
"autofill/autofill_popup_controller_impl.cc",
"autofill/autofill_popup_controller_impl.h",
- "autofill/autofill_popup_controller_impl_mac.h",
- "autofill/autofill_popup_controller_impl_mac.mm",
"autofill/autofill_popup_controller_utils.cc",
"autofill/autofill_popup_controller_utils.h",
"autofill/autofill_popup_view.h",
@@ -63,22 +67,10 @@ static_library("ui") {
"autofill/test/test_autofill_bubble_handler.h",
"blocked_content/blocked_window_params.cc",
"blocked_content/blocked_window_params.h",
- "blocked_content/list_item_position.cc",
- "blocked_content/list_item_position.h",
- "blocked_content/popup_blocker.cc",
- "blocked_content/popup_blocker.h",
- "blocked_content/popup_blocker_tab_helper.cc",
- "blocked_content/popup_blocker_tab_helper.h",
- "blocked_content/popup_opener_tab_helper.cc",
- "blocked_content/popup_opener_tab_helper.h",
- "blocked_content/popup_tracker.cc",
- "blocked_content/popup_tracker.h",
- "blocked_content/safe_browsing_triggered_popup_blocker.cc",
- "blocked_content/safe_browsing_triggered_popup_blocker.h",
+ "blocked_content/chrome_popup_navigation_delegate.cc",
+ "blocked_content/chrome_popup_navigation_delegate.h",
"blocked_content/tab_under_navigation_throttle.cc",
"blocked_content/tab_under_navigation_throttle.h",
- "blocked_content/url_list_manager.cc",
- "blocked_content/url_list_manager.h",
"browser_dialogs.cc",
"browser_dialogs.h",
"browser_navigator_params.cc",
@@ -89,8 +81,6 @@ static_library("ui") {
"chrome_select_file_policy.h",
"color_chooser.h",
"confirm_bubble.h",
- "cookie_controls/cookie_controls_controller.cc",
- "cookie_controls/cookie_controls_controller.h",
"cookie_controls/cookie_controls_service.cc",
"cookie_controls/cookie_controls_service.h",
"cookie_controls/cookie_controls_service_factory.cc",
@@ -109,8 +99,6 @@ static_library("ui") {
"interventions/intervention_infobar_delegate.cc",
"interventions/intervention_infobar_delegate.h",
"javascript_dialogs/chrome_javascript_app_modal_dialog_view_factory.h",
- "javascript_dialogs/javascript_tab_modal_dialog_manager_delegate_android.cc",
- "javascript_dialogs/javascript_tab_modal_dialog_manager_delegate_android.h",
"login/login_handler.cc",
"login/login_handler.h",
"login/login_navigation_throttle.cc",
@@ -237,6 +225,8 @@ static_library("ui") {
"webui/flags_ui_handler.h",
"webui/gcm_internals_ui.cc",
"webui/gcm_internals_ui.h",
+ "webui/internals/internals_ui.cc",
+ "webui/internals/internals_ui.h",
"webui/interstitials/interstitial_ui.cc",
"webui/interstitials/interstitial_ui.h",
"webui/interventions_internals/interventions_internals_page_handler.cc",
@@ -305,8 +295,6 @@ static_library("ui") {
"webui/translate_internals/chrome_translate_internals_handler.h",
"webui/translate_internals/translate_internals_ui.cc",
"webui/translate_internals/translate_internals_ui.h",
- "webui/ukm/ukm_internals_ui.cc",
- "webui/ukm/ukm_internals_ui.h",
"webui/usb_internals/usb_internals_page_handler.cc",
"webui/usb_internals/usb_internals_page_handler.h",
"webui/usb_internals/usb_internals_ui.cc",
@@ -332,15 +320,6 @@ static_library("ui") {
]
}
- if (enable_vr) {
- if (is_win) {
- sources += [
- "xr/xr_session_request_consent_dialog_delegate.cc",
- "xr/xr_session_request_consent_dialog_delegate.h",
- ]
- }
- }
-
if (safe_browsing_mode == 1) {
sources += [
"webui/reset_password/reset_password_ui.cc",
@@ -364,7 +343,6 @@ static_library("ui") {
# have the same dependencies. Once browser_ui is untangled from
# browser, then we can clean up these dependencies.
public_deps = [
- "//chrome/common/string_matching",
"//components/dom_distiller/core",
"//components/safe_browsing:buildflags",
"//components/sync",
@@ -410,6 +388,7 @@ static_library("ui") {
"//chrome/browser/ui/webui/interventions_internals:mojo_bindings",
"//chrome/browser/ui/webui/new_tab_page:mojo_bindings",
"//chrome/browser/ui/webui/omnibox:mojo_bindings",
+ "//chrome/browser/ui/webui/tab_search:mojo_bindings",
"//chrome/browser/ui/webui/usb_internals:mojo_bindings",
"//chrome/common",
"//chrome/common/net",
@@ -421,6 +400,7 @@ static_library("ui") {
"//components/account_id",
"//components/autofill/content/browser:risk_proto",
"//components/autofill/core/browser",
+ "//components/blocked_content",
"//components/bookmarks/browser",
"//components/bookmarks/managed",
"//components/browser_sync",
@@ -538,7 +518,6 @@ static_library("ui") {
"//components/ui_devtools",
"//components/ukm",
"//components/ukm/content",
- "//components/ukm/debug:util",
"//components/undo",
"//components/unified_consent",
"//components/update_client",
@@ -625,6 +604,7 @@ static_library("ui") {
"//chrome/browser/ui/webui/explore_sites_internals:mojo_bindings",
"//chrome/browser/ui/webui/snippets_internals:mojo_bindings",
"//components/browser_ui/util/android",
+ "//components/query_tiles",
"//components/security_state/content/android",
]
if (enable_feed_in_chrome) {
@@ -687,8 +667,6 @@ static_library("ui") {
"android/color_chooser_dialog_android.cc",
"android/content_settings/ads_blocked_infobar_delegate.cc",
"android/content_settings/ads_blocked_infobar_delegate.h",
- "android/content_settings/popup_blocked_infobar_delegate.cc",
- "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",
@@ -769,7 +747,7 @@ static_library("ui") {
"android/sms/sms_infobar.h",
"android/sms/sms_infobar_delegate.cc",
"android/sms/sms_infobar_delegate.h",
- "android/ssl_client_certificate_request.cc",
+ "android/ssl_client_certificate_selector.cc",
"android/status_tray_android.cc",
"android/tab_contents/chrome_web_contents_view_delegate_android.cc",
"android/tab_contents/chrome_web_contents_view_delegate_android.h",
@@ -788,14 +766,16 @@ 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/view_android_helper.cc",
- "android/view_android_helper.h",
"browser_otr_state_android.cc",
+ "javascript_dialogs/javascript_tab_modal_dialog_manager_delegate_android.cc",
+ "javascript_dialogs/javascript_tab_modal_dialog_manager_delegate_android.h",
"screen_capture_notification_ui_stub.cc",
"webui/explore_sites_internals/explore_sites_internals_page_handler.cc",
"webui/explore_sites_internals/explore_sites_internals_page_handler.h",
"webui/explore_sites_internals/explore_sites_internals_ui.cc",
"webui/explore_sites_internals/explore_sites_internals_ui.h",
+ "webui/internals/query_tiles/query_tiles_internals_ui_message_handler.cc",
+ "webui/internals/query_tiles/query_tiles_internals_ui_message_handler.h",
"webui/offline/offline_internals_ui.cc",
"webui/offline/offline_internals_ui.h",
"webui/offline/offline_internals_ui_message_handler.cc",
@@ -824,18 +804,13 @@ static_library("ui") {
]
}
- if (enable_password_change_in_leaked_dialog) {
- sources += [
- "android/passwords/credential_leak_dialog_password_change_view_android.cc",
- "android/passwords/credential_leak_dialog_password_change_view_android.h",
- ]
- }
deps += [
"//chrome/android:jni_headers",
"//chrome/android/features/dev_ui:buildflags",
"//chrome/browser/android/thin_webview:thin_webview",
"//chrome/browser/image_decoder",
"//chrome/browser/resources/webapks:webapks_ui_resources",
+ "//components/browser_ui/client_certificate/android",
"//components/embedder_support/android:context_menu",
"//components/embedder_support/android:web_contents_delegate",
"//components/javascript_dialogs/android:jni_headers",
@@ -970,7 +945,6 @@ static_library("ui") {
"find_bar/find_bar_controller.h",
"find_bar/find_bar_platform_helper.cc",
"find_bar/find_bar_platform_helper.h",
- "find_bar/find_bar_platform_helper_mac.mm",
"focus_tab_after_navigation_helper.cc",
"focus_tab_after_navigation_helper.h",
"global_error/global_error.cc",
@@ -1002,8 +976,9 @@ static_library("ui") {
"global_media_controls/media_toolbar_button_controller_delegate.h",
"global_media_controls/media_toolbar_button_observer.h",
"global_media_controls/overlay_media_notification.h",
- "global_media_controls/overlay_media_notifications_manager.cc",
"global_media_controls/overlay_media_notifications_manager.h",
+ "global_media_controls/overlay_media_notifications_manager_impl.cc",
+ "global_media_controls/overlay_media_notifications_manager_impl.h",
"hats/hats_helper.cc",
"hats/hats_helper.h",
"hats/hats_service.cc",
@@ -1126,8 +1101,8 @@ static_library("ui") {
"passwords/passwords_leak_dialog_delegate.h",
"passwords/passwords_model_delegate.cc",
"passwords/passwords_model_delegate.h",
- "pdf/adobe_reader_info_win.cc",
- "pdf/adobe_reader_info_win.h",
+ "passwords/well_known_change_password_navigation_throttle.cc",
+ "passwords/well_known_change_password_navigation_throttle.h",
"pdf/chrome_pdf_web_contents_helper_client.cc",
"pdf/chrome_pdf_web_contents_helper_client.h",
"permission_bubble/permission_prompt.h",
@@ -1245,6 +1220,8 @@ static_library("ui") {
"task_manager/task_manager_columns.h",
"task_manager/task_manager_table_model.cc",
"task_manager/task_manager_table_model.h",
+ "thumbnails/thumbnail_capture_driver.cc",
+ "thumbnails/thumbnail_capture_driver.h",
"thumbnails/thumbnail_image.cc",
"thumbnails/thumbnail_image.h",
"thumbnails/thumbnail_readiness_tracker.cc",
@@ -1285,8 +1262,6 @@ static_library("ui") {
"webui/app_launcher_login_handler.h",
"webui/app_management/app_management_page_handler.cc",
"webui/app_management/app_management_page_handler.h",
- "webui/app_management/app_management_shelf_delegate_chromeos.cc",
- "webui/app_management/app_management_shelf_delegate_chromeos.h",
"webui/bookmarks/bookmarks_message_handler.cc",
"webui/bookmarks/bookmarks_message_handler.h",
"webui/bookmarks/bookmarks_ui.cc",
@@ -1324,19 +1299,23 @@ static_library("ui") {
"webui/identity_internals_ui.h",
"webui/inspect_ui.cc",
"webui/inspect_ui.h",
+ "webui/internals/web_app/web_app_internals_page_handler_impl.cc",
+ "webui/internals/web_app/web_app_internals_page_handler_impl.h",
"webui/managed_ui_handler.cc",
"webui/managed_ui_handler.h",
"webui/management_ui.cc",
"webui/management_ui.h",
"webui/management_ui_handler.cc",
"webui/management_ui_handler.h",
- "webui/management_ui_handler_chromeos.cc",
- "webui/management_ui_handler_chromeos.h",
"webui/media_router/media_router_internals_ui.cc",
"webui/media_router/media_router_internals_ui.h",
"webui/media_router/media_router_internals_webui_message_handler.cc",
"webui/media_router/media_router_internals_webui_message_handler.h",
"webui/media_router/web_contents_display_observer.h",
+ "webui/nearby_internals/nearby_internals_ui.cc",
+ "webui/nearby_internals/nearby_internals_ui.h",
+ "webui/nearby_share/nearby_share_dialog_ui.cc",
+ "webui/nearby_share/nearby_share_dialog_ui.h",
"webui/new_tab_page/new_tab_page_handler.cc",
"webui/new_tab_page/new_tab_page_handler.h",
"webui/new_tab_page/new_tab_page_ui.cc",
@@ -1455,10 +1434,16 @@ static_library("ui") {
"webui/sync_file_system_internals/sync_file_system_internals_ui.h",
"webui/system_info_ui.cc",
"webui/system_info_ui.h",
+ "webui/tab_search/tab_search_page_handler.cc",
+ "webui/tab_search/tab_search_page_handler.h",
+ "webui/tab_search/tab_search_ui.cc",
+ "webui/tab_search/tab_search_ui.h",
"webui/theme_handler.cc",
"webui/theme_handler.h",
"webui/theme_source.cc",
"webui/theme_source.h",
+ "webui/util/image_util.cc",
+ "webui/util/image_util.h",
"webui/web_footer_experiment_ui.cc",
"webui/web_footer_experiment_ui.h",
"window_sizer/window_sizer.cc",
@@ -1480,13 +1465,12 @@ static_library("ui") {
"//chrome/browser/ui/color:color_headers",
"//chrome/browser/ui/color:mixers",
"//chrome/browser/ui/webui/app_management:mojo_bindings",
+ "//chrome/browser/ui/webui/internals/web_app:mojo_bindings",
"//chrome/common:buildflags",
"//chrome/common/media_router/mojom:media_router",
"//chrome/common/search:generate_chrome_colors_info",
"//chrome/common/search:mojo_bindings",
"//chrome/common/themes:autogenerated_theme_util",
- "//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",
@@ -1494,6 +1478,8 @@ static_library("ui") {
"//components/profile_metrics",
"//components/safety_check",
"//components/search_provider_logos",
+ "//components/services/app_service/public/cpp:app_update",
+ "//components/services/app_service/public/mojom",
"//components/ui_metrics",
"//components/url_formatter",
"//components/vector_icons",
@@ -1512,7 +1498,10 @@ static_library("ui") {
]
if (use_ozone && !is_chromeos) {
- deps += [ "//ui/ozone" ]
+ deps += [
+ "//ui/base:features",
+ "//ui/ozone",
+ ]
}
if (is_linux && !is_chromeos) {
@@ -1537,10 +1526,6 @@ static_library("ui") {
}
}
- if (enable_kaleidoscope) {
- deps += [ "//chrome/browser/media/kaleidoscope/internal" ]
- }
-
if (enable_paint_preview) {
deps += [ "//components/paint_preview/browser" ]
}
@@ -1557,8 +1542,36 @@ static_library("ui") {
if (is_chromeos) {
assert(enable_extensions)
+ assert(enable_supervised_users)
assert(toolkit_views)
sources += [
+ "app_icon_loader_delegate.h",
+ "app_list/app_context_menu.cc",
+ "app_list/app_context_menu.h",
+ "app_list/app_context_menu_delegate.h",
+ "app_list/app_list_client_impl.cc",
+ "app_list/app_list_client_impl.h",
+ "app_list/app_list_controller_delegate.cc",
+ "app_list/app_list_controller_delegate.h",
+ "app_list/app_list_model_builder.cc",
+ "app_list/app_list_model_builder.h",
+ "app_list/app_list_model_updater.cc",
+ "app_list/app_list_model_updater.h",
+ "app_list/app_list_model_updater_observer.h",
+ "app_list/app_list_notifier_impl.cc",
+ "app_list/app_list_notifier_impl.h",
+ "app_list/app_list_syncable_service.cc",
+ "app_list/app_list_syncable_service.h",
+ "app_list/app_list_syncable_service_factory.cc",
+ "app_list/app_list_syncable_service_factory.h",
+ "app_list/app_service/app_service_app_icon_loader.cc",
+ "app_list/app_service/app_service_app_icon_loader.h",
+ "app_list/app_service/app_service_app_item.cc",
+ "app_list/app_service/app_service_app_item.h",
+ "app_list/app_service/app_service_app_model_builder.cc",
+ "app_list/app_service/app_service_app_model_builder.h",
+ "app_list/app_service/app_service_context_menu.cc",
+ "app_list/app_service/app_service_context_menu.h",
"app_list/app_sync_ui_state.cc",
"app_list/app_sync_ui_state.h",
"app_list/app_sync_ui_state_factory.cc",
@@ -1566,6 +1579,110 @@ static_library("ui") {
"app_list/app_sync_ui_state_observer.h",
"app_list/app_sync_ui_state_watcher.cc",
"app_list/app_sync_ui_state_watcher.h",
+ "app_list/arc/arc_app_context_menu.cc",
+ "app_list/arc/arc_app_context_menu.h",
+ "app_list/arc/arc_app_dialog.h",
+ "app_list/arc/arc_app_icon.cc",
+ "app_list/arc/arc_app_icon.h",
+ "app_list/arc/arc_app_icon_descriptor.cc",
+ "app_list/arc/arc_app_icon_descriptor.h",
+ "app_list/arc/arc_app_launcher.cc",
+ "app_list/arc/arc_app_launcher.h",
+ "app_list/arc/arc_app_list_prefs.cc",
+ "app_list/arc/arc_app_list_prefs.h",
+ "app_list/arc/arc_app_list_prefs_factory.cc",
+ "app_list/arc/arc_app_list_prefs_factory.h",
+ "app_list/arc/arc_app_scoped_pref_update.cc",
+ "app_list/arc/arc_app_scoped_pref_update.h",
+ "app_list/arc/arc_app_utils.cc",
+ "app_list/arc/arc_app_utils.h",
+ "app_list/arc/arc_data_removal_dialog.h",
+ "app_list/arc/arc_default_app_list.cc",
+ "app_list/arc/arc_default_app_list.h",
+ "app_list/arc/arc_fast_app_reinstall_starter.cc",
+ "app_list/arc/arc_fast_app_reinstall_starter.h",
+ "app_list/arc/arc_package_sync_model_type_controller.cc",
+ "app_list/arc/arc_package_sync_model_type_controller.h",
+ "app_list/arc/arc_package_syncable_service.cc",
+ "app_list/arc/arc_package_syncable_service.h",
+ "app_list/arc/arc_package_syncable_service_factory.cc",
+ "app_list/arc/arc_package_syncable_service_factory.h",
+ "app_list/arc/arc_pai_starter.cc",
+ "app_list/arc/arc_pai_starter.h",
+ "app_list/arc/arc_playstore_app_context_menu.cc",
+ "app_list/arc/arc_playstore_app_context_menu.h",
+ "app_list/arc/arc_usb_host_permission_manager.cc",
+ "app_list/arc/arc_usb_host_permission_manager.h",
+ "app_list/arc/arc_usb_host_permission_manager_factory.cc",
+ "app_list/arc/arc_usb_host_permission_manager_factory.h",
+ "app_list/arc/arc_vpn_provider_manager.cc",
+ "app_list/arc/arc_vpn_provider_manager.h",
+ "app_list/arc/arc_vpn_provider_manager_factory.cc",
+ "app_list/arc/arc_vpn_provider_manager_factory.h",
+ "app_list/chrome_app_list_item.cc",
+ "app_list/chrome_app_list_item.h",
+ "app_list/chrome_app_list_model_updater.cc",
+ "app_list/chrome_app_list_model_updater.h",
+ "app_list/crostini/crostini_app_context_menu.cc",
+ "app_list/crostini/crostini_app_context_menu.h",
+ "app_list/extension_app_context_menu.cc",
+ "app_list/extension_app_context_menu.h",
+ "app_list/extension_app_utils.cc",
+ "app_list/extension_app_utils.h",
+ "app_list/internal_app/internal_app_metadata.cc",
+ "app_list/internal_app/internal_app_metadata.h",
+ "app_list/md_icon_normalizer.cc",
+ "app_list/md_icon_normalizer.h",
+ "app_list/page_break_app_item.cc",
+ "app_list/page_break_app_item.h",
+ "app_list/page_break_constants.cc",
+ "app_list/page_break_constants.h",
+ "app_list/search/answer_card/answer_card_result.cc",
+ "app_list/search/answer_card/answer_card_result.h",
+ "app_list/search/answer_card/answer_card_search_provider.cc",
+ "app_list/search/answer_card/answer_card_search_provider.h",
+ "app_list/search/app_result.cc",
+ "app_list/search/app_result.h",
+ "app_list/search/app_search_provider.cc",
+ "app_list/search/app_search_provider.h",
+ "app_list/search/app_service_app_result.cc",
+ "app_list/search/app_service_app_result.h",
+ "app_list/search/arc/arc_app_data_search_provider.cc",
+ "app_list/search/arc/arc_app_data_search_provider.h",
+ "app_list/search/arc/arc_app_data_search_result.cc",
+ "app_list/search/arc/arc_app_data_search_result.h",
+ "app_list/search/arc/arc_app_reinstall_app_result.cc",
+ "app_list/search/arc/arc_app_reinstall_app_result.h",
+ "app_list/search/arc/arc_app_reinstall_search_provider.cc",
+ "app_list/search/arc/arc_app_reinstall_search_provider.h",
+ "app_list/search/arc/arc_app_shortcut_search_result.cc",
+ "app_list/search/arc/arc_app_shortcut_search_result.h",
+ "app_list/search/arc/arc_app_shortcuts_search_provider.cc",
+ "app_list/search/arc/arc_app_shortcuts_search_provider.h",
+ "app_list/search/arc/arc_playstore_search_provider.cc",
+ "app_list/search/arc/arc_playstore_search_provider.h",
+ "app_list/search/arc/arc_playstore_search_result.cc",
+ "app_list/search/arc/arc_playstore_search_result.h",
+ "app_list/search/assistant_search_provider.cc",
+ "app_list/search/assistant_search_provider.h",
+ "app_list/search/chrome_search_result.cc",
+ "app_list/search/chrome_search_result.h",
+ "app_list/search/common/file_icon_util.cc",
+ "app_list/search/common/file_icon_util.h",
+ "app_list/search/common/url_icon_source.cc",
+ "app_list/search/common/url_icon_source.h",
+ "app_list/search/cros_action_history/cros_action_recorder.cc",
+ "app_list/search/cros_action_history/cros_action_recorder.h",
+ "app_list/search/cros_action_history/cros_action_recorder_tab_tracker.cc",
+ "app_list/search/cros_action_history/cros_action_recorder_tab_tracker.h",
+ "app_list/search/drive_quick_access_chip_result.cc",
+ "app_list/search/drive_quick_access_chip_result.h",
+ "app_list/search/drive_quick_access_provider.cc",
+ "app_list/search/drive_quick_access_provider.h",
+ "app_list/search/drive_quick_access_result.cc",
+ "app_list/search/drive_quick_access_result.h",
+ "app_list/search/file_chip_result.cc",
+ "app_list/search/file_chip_result.h",
"app_list/search/launcher_search/launcher_search_icon_image_loader.cc",
"app_list/search/launcher_search/launcher_search_icon_image_loader.h",
"app_list/search/launcher_search/launcher_search_icon_image_loader_impl.cc",
@@ -1574,6 +1691,70 @@ static_library("ui") {
"app_list/search/launcher_search/launcher_search_provider.h",
"app_list/search/launcher_search/launcher_search_result.cc",
"app_list/search/launcher_search/launcher_search_result.h",
+ "app_list/search/mixer.cc",
+ "app_list/search/mixer.h",
+ "app_list/search/omnibox_provider.cc",
+ "app_list/search/omnibox_provider.h",
+ "app_list/search/omnibox_result.cc",
+ "app_list/search/omnibox_result.h",
+ "app_list/search/os_settings_provider.cc",
+ "app_list/search/os_settings_provider.h",
+ "app_list/search/search_controller.cc",
+ "app_list/search/search_controller.h",
+ "app_list/search/search_controller_factory.cc",
+ "app_list/search/search_controller_factory.h",
+ "app_list/search/search_metrics_observer.cc",
+ "app_list/search/search_metrics_observer.h",
+ "app_list/search/search_provider.cc",
+ "app_list/search/search_provider.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_event_logger_helper.cc",
+ "app_list/search/search_result_ranker/app_launch_event_logger_helper.h",
+ "app_list/search/search_result_ranker/app_launch_predictor.cc",
+ "app_list/search/search_result_ranker/app_launch_predictor.h",
+ "app_list/search/search_result_ranker/app_list_launch_metrics_provider.cc",
+ "app_list/search/search_result_ranker/app_list_launch_metrics_provider.h",
+ "app_list/search/search_result_ranker/app_list_launch_recorder.cc",
+ "app_list/search/search_result_ranker/app_list_launch_recorder.h",
+ "app_list/search/search_result_ranker/app_list_launch_recorder_util.cc",
+ "app_list/search/search_result_ranker/app_list_launch_recorder_util.h",
+ "app_list/search/search_result_ranker/app_search_result_ranker.cc",
+ "app_list/search/search_result_ranker/app_search_result_ranker.h",
+ "app_list/search/search_result_ranker/chip_ranker.cc",
+ "app_list/search/search_result_ranker/chip_ranker.h",
+ "app_list/search/search_result_ranker/frecency_store.cc",
+ "app_list/search/search_result_ranker/frecency_store.h",
+ "app_list/search/search_result_ranker/histogram_util.cc",
+ "app_list/search/search_result_ranker/histogram_util.h",
+ "app_list/search/search_result_ranker/ml_app_rank_provider.cc",
+ "app_list/search/search_result_ranker/ml_app_rank_provider.h",
+ "app_list/search/search_result_ranker/ranking_item_util.cc",
+ "app_list/search/search_result_ranker/ranking_item_util.h",
+ "app_list/search/search_result_ranker/recurrence_predictor.cc",
+ "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_ranking_event_logger.cc",
+ "app_list/search/search_result_ranker/search_ranking_event_logger.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",
+ "app_list/search/settings_shortcut/settings_shortcut_metadata.h",
+ "app_list/search/settings_shortcut/settings_shortcut_provider.cc",
+ "app_list/search/settings_shortcut/settings_shortcut_provider.h",
+ "app_list/search/settings_shortcut/settings_shortcut_result.cc",
+ "app_list/search/settings_shortcut/settings_shortcut_result.h",
+ "app_list/search/zero_state_file_provider.cc",
+ "app_list/search/zero_state_file_provider.h",
+ "app_list/search/zero_state_file_result.cc",
+ "app_list/search/zero_state_file_result.h",
+ "app_list/web_app_context_menu.cc",
+ "app_list/web_app_context_menu.h",
"ash/accessibility/accessibility_controller_client.cc",
"ash/accessibility/accessibility_controller_client.h",
"ash/ambient/ambient_client_impl.cc",
@@ -1586,6 +1767,29 @@ static_library("ui") {
"ash/ash_shell_init.h",
"ash/ash_util.cc",
"ash/ash_util.h",
+ "ash/assistant/assistant_client_impl.cc",
+ "ash/assistant/assistant_client_impl.h",
+ "ash/assistant/assistant_context_util.cc",
+ "ash/assistant/assistant_context_util.h",
+ "ash/assistant/assistant_setup.cc",
+ "ash/assistant/assistant_setup.h",
+ "ash/assistant/assistant_state_client.cc",
+ "ash/assistant/assistant_state_client.h",
+ "ash/assistant/assistant_web_view_factory_impl.cc",
+ "ash/assistant/assistant_web_view_factory_impl.h",
+ "ash/assistant/assistant_web_view_impl.cc",
+ "ash/assistant/assistant_web_view_impl.h",
+ "ash/assistant/conversation_starters_client_impl.cc",
+ "ash/assistant/conversation_starters_client_impl.h",
+ "ash/assistant/conversation_starters_parser.cc",
+ "ash/assistant/conversation_starters_parser.h",
+ "ash/assistant/device_actions.cc",
+ "ash/assistant/device_actions.h",
+ "ash/assistant/device_actions_delegate.h",
+ "ash/assistant/device_actions_delegate_impl.cc",
+ "ash/assistant/device_actions_delegate_impl.h",
+ "ash/assistant/search_and_assistant_enabled_checker.cc",
+ "ash/assistant/search_and_assistant_enabled_checker.h",
"ash/back_gesture_contextual_nudge_delegate.cc",
"ash/back_gesture_contextual_nudge_delegate.h",
"ash/cast_config_controller_media_router.cc",
@@ -1603,6 +1807,8 @@ static_library("ui") {
"ash/chrome_screenshot_grabber_test_observer.h",
"ash/chrome_shell_delegate.cc",
"ash/chrome_shell_delegate.h",
+ "ash/image_downloader_impl.cc",
+ "ash/image_downloader_impl.h",
"ash/ime_controller_client.cc",
"ash/ime_controller_client.h",
"ash/keyboard/chrome_keyboard_bounds_observer.cc",
@@ -1615,14 +1821,45 @@ 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/launcher/app_service/app_service_app_window_arc_tracker.cc",
+ "ash/launcher/app_service/app_service_app_window_arc_tracker.h",
+ "ash/launcher/app_service/app_service_app_window_crostini_tracker.cc",
+ "ash/launcher/app_service/app_service_app_window_crostini_tracker.h",
+ "ash/launcher/app_service/app_service_app_window_launcher_controller.cc",
+ "ash/launcher/app_service/app_service_app_window_launcher_controller.h",
+ "ash/launcher/app_service/app_service_app_window_launcher_item_controller.cc",
+ "ash/launcher/app_service/app_service_app_window_launcher_item_controller.h",
+ "ash/launcher/app_service/app_service_instance_registry_helper.cc",
+ "ash/launcher/app_service/app_service_instance_registry_helper.h",
+ "ash/launcher/app_service/app_service_shelf_context_menu.cc",
+ "ash/launcher/app_service/app_service_shelf_context_menu.h",
+ "ash/launcher/app_service/launcher_app_service_app_updater.cc",
+ "ash/launcher/app_service/launcher_app_service_app_updater.h",
"ash/launcher/app_shortcut_launcher_item_controller.cc",
"ash/launcher/app_shortcut_launcher_item_controller.h",
+ "ash/launcher/app_window_base.cc",
+ "ash/launcher/app_window_base.h",
"ash/launcher/app_window_launcher_controller.cc",
"ash/launcher/app_window_launcher_controller.h",
"ash/launcher/app_window_launcher_item_controller.cc",
"ash/launcher/app_window_launcher_item_controller.h",
+ "ash/launcher/arc_app_shelf_id.cc",
+ "ash/launcher/arc_app_shelf_id.h",
+ "ash/launcher/arc_app_window.cc",
+ "ash/launcher/arc_app_window.h",
+ "ash/launcher/arc_app_window_delegate.h",
+ "ash/launcher/arc_app_window_info.cc",
+ "ash/launcher/arc_app_window_info.h",
+ "ash/launcher/arc_app_window_launcher_controller.cc",
+ "ash/launcher/arc_app_window_launcher_controller.h",
+ "ash/launcher/arc_app_window_launcher_item_controller.cc",
+ "ash/launcher/arc_app_window_launcher_item_controller.h",
"ash/launcher/arc_playstore_shortcut_launcher_item_controller.cc",
"ash/launcher/arc_playstore_shortcut_launcher_item_controller.h",
+ "ash/launcher/arc_shelf_context_menu.cc",
+ "ash/launcher/arc_shelf_context_menu.h",
+ "ash/launcher/arc_shelf_spinner_item_controller.cc",
+ "ash/launcher/arc_shelf_spinner_item_controller.h",
"ash/launcher/browser_shortcut_launcher_item_controller.cc",
"ash/launcher/browser_shortcut_launcher_item_controller.h",
"ash/launcher/browser_status_monitor.cc",
@@ -1631,6 +1868,12 @@ static_library("ui") {
"ash/launcher/chrome_launcher_controller.h",
"ash/launcher/chrome_launcher_controller_util.cc",
"ash/launcher/chrome_launcher_controller_util.h",
+ "ash/launcher/crostini_app_display.cc",
+ "ash/launcher/crostini_app_display.h",
+ "ash/launcher/crostini_app_window_shelf_controller.cc",
+ "ash/launcher/crostini_app_window_shelf_controller.h",
+ "ash/launcher/crostini_shelf_context_menu.cc",
+ "ash/launcher/crostini_shelf_context_menu.h",
"ash/launcher/discover_window_observer.cc",
"ash/launcher/discover_window_observer.h",
"ash/launcher/extension_app_window_launcher_controller.cc",
@@ -1641,6 +1884,10 @@ static_library("ui") {
"ash/launcher/extension_shelf_context_menu.h",
"ash/launcher/extension_uninstaller.cc",
"ash/launcher/extension_uninstaller.h",
+ "ash/launcher/internal_app_shelf_context_menu.cc",
+ "ash/launcher/internal_app_shelf_context_menu.h",
+ "ash/launcher/internal_app_window_shelf_controller.cc",
+ "ash/launcher/internal_app_window_shelf_controller.h",
"ash/launcher/launcher_app_updater.cc",
"ash/launcher/launcher_app_updater.h",
"ash/launcher/launcher_controller_helper.cc",
@@ -1655,6 +1902,10 @@ static_library("ui") {
"ash/launcher/settings_window_observer.h",
"ash/launcher/shelf_context_menu.cc",
"ash/launcher/shelf_context_menu.h",
+ "ash/launcher/shelf_spinner_controller.cc",
+ "ash/launcher/shelf_spinner_controller.h",
+ "ash/launcher/shelf_spinner_item_controller.cc",
+ "ash/launcher/shelf_spinner_item_controller.h",
"ash/login_screen_client.cc",
"ash/login_screen_client.h",
"ash/media_client_impl.cc",
@@ -1709,11 +1960,35 @@ static_library("ui") {
"settings_window_manager_chromeos.cc",
"settings_window_manager_chromeos.h",
"settings_window_manager_observer_chromeos.h",
+ "supervised_user/parent_permission_dialog.h",
+ "views/apps/app_dialog/app_block_dialog_view.cc",
+ "views/apps/app_dialog/app_block_dialog_view.h",
+ "views/apps/app_dialog/app_pause_dialog_view.cc",
+ "views/apps/app_dialog/app_pause_dialog_view.h",
"views/apps/app_info_dialog/arc_app_info_links_panel.cc",
"views/apps/app_info_dialog/arc_app_info_links_panel.h",
+ "views/apps/chrome_app_window_client_views_chromeos.cc",
"views/apps/chrome_native_app_window_views_aura_ash.cc",
"views/apps/chrome_native_app_window_views_aura_ash.h",
+ "views/arc_app_dialog_view.cc",
+ "views/arc_data_removal_dialog_view.cc",
"views/chrome_views_delegate_chromeos.cc",
+ "views/crostini/crostini_ansible_software_config_view.cc",
+ "views/crostini/crostini_ansible_software_config_view.h",
+ "views/crostini/crostini_app_restart_view.cc",
+ "views/crostini/crostini_app_restart_view.h",
+ "views/crostini/crostini_force_close_view.cc",
+ "views/crostini/crostini_force_close_view.h",
+ "views/crostini/crostini_package_install_failure_view.cc",
+ "views/crostini/crostini_package_install_failure_view.h",
+ "views/crostini/crostini_recovery_view.cc",
+ "views/crostini/crostini_recovery_view.h",
+ "views/crostini/crostini_uninstaller_view.cc",
+ "views/crostini/crostini_uninstaller_view.h",
+ "views/crostini/crostini_update_component_view.cc",
+ "views/crostini/crostini_update_component_view.h",
+ "views/crostini/crostini_update_filesystem_view.cc",
+ "views/crostini/crostini_update_filesystem_view.h",
"views/extensions/print_job_confirmation_dialog_view.cc",
"views/extensions/print_job_confirmation_dialog_view.h",
"views/extensions/request_file_system_dialog_view.cc",
@@ -1724,6 +1999,9 @@ static_library("ui") {
"views/frame/browser_frame_header_ash.h",
"views/frame/browser_non_client_frame_view_ash.cc",
"views/frame/browser_non_client_frame_view_ash.h",
+ "views/frame/browser_non_client_frame_view_factory_chromeos.cc",
+ "views/frame/custom_tab_browser_frame.cc",
+ "views/frame/custom_tab_browser_frame.h",
"views/frame/immersive_mode_controller_ash.cc",
"views/frame/immersive_mode_controller_ash.h",
"views/frame/native_browser_frame_factory_chromeos.cc",
@@ -1731,32 +2009,42 @@ static_library("ui") {
"views/frame/top_controls_slide_controller_chromeos.h",
"views/platform_keys_certificate_selector_chromeos.cc",
"views/platform_keys_certificate_selector_chromeos.h",
+ "views/plugin_vm/plugin_vm_installer_view.cc",
+ "views/plugin_vm/plugin_vm_installer_view.h",
"views/profiles/profile_indicator_icon.cc",
"views/profiles/profile_indicator_icon.h",
- "webui/chrome_url_disabled_ui.cc",
- "webui/chrome_url_disabled_ui.h",
+ "views/relaunch_notification/relaunch_notification_controller_platform_impl_chromeos.cc",
+ "views/relaunch_notification/relaunch_notification_controller_platform_impl_chromeos.h",
# On chromeos, file manager extension handles the file open/save dialog.
"views/select_file_dialog_extension.cc",
"views/select_file_dialog_extension.h",
"views/select_file_dialog_extension_factory.cc",
"views/select_file_dialog_extension_factory.h",
+ "views/supervised_user/extension_install_blocked_by_parent_dialog_view.cc",
+ "views/supervised_user/extension_install_blocked_by_parent_dialog_view.h",
+ "views/supervised_user/parent_permission_dialog_view.cc",
+ "views/supervised_user/parent_permission_dialog_view.h",
"views/touch_selection_menu_chromeos.cc",
"views/touch_selection_menu_chromeos.h",
"views/touch_selection_menu_runner_chromeos.cc",
"views/touch_selection_menu_runner_chromeos.h",
+ "webui/app_management/app_management_shelf_delegate_chromeos.cc",
+ "webui/app_management/app_management_shelf_delegate_chromeos.h",
"webui/certificate_provisioning_ui_handler.cc",
"webui/certificate_provisioning_ui_handler.h",
- "webui/chromeos/account_manager_error_ui.cc",
- "webui/chromeos/account_manager_error_ui.h",
- "webui/chromeos/account_manager_welcome_dialog.cc",
- "webui/chromeos/account_manager_welcome_dialog.h",
- "webui/chromeos/account_manager_welcome_ui.cc",
- "webui/chromeos/account_manager_welcome_ui.h",
- "webui/chromeos/account_migration_welcome_dialog.cc",
- "webui/chromeos/account_migration_welcome_dialog.h",
- "webui/chromeos/account_migration_welcome_ui.cc",
- "webui/chromeos/account_migration_welcome_ui.h",
+ "webui/chrome_url_disabled_ui.cc",
+ "webui/chrome_url_disabled_ui.h",
+ "webui/chromeos/account_manager/account_manager_error_ui.cc",
+ "webui/chromeos/account_manager/account_manager_error_ui.h",
+ "webui/chromeos/account_manager/account_manager_welcome_dialog.cc",
+ "webui/chromeos/account_manager/account_manager_welcome_dialog.h",
+ "webui/chromeos/account_manager/account_manager_welcome_ui.cc",
+ "webui/chromeos/account_manager/account_manager_welcome_ui.h",
+ "webui/chromeos/account_manager/account_migration_welcome_dialog.cc",
+ "webui/chromeos/account_manager/account_migration_welcome_dialog.h",
+ "webui/chromeos/account_manager/account_migration_welcome_ui.cc",
+ "webui/chromeos/account_manager/account_migration_welcome_ui.h",
"webui/chromeos/add_supervision/add_supervision_handler.cc",
"webui/chromeos/add_supervision/add_supervision_handler.h",
"webui/chromeos/add_supervision/add_supervision_handler_utils.cc",
@@ -1780,8 +2068,6 @@ 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",
@@ -1899,6 +2185,8 @@ static_library("ui") {
"webui/chromeos/login/eula_screen_handler.h",
"webui/chromeos/login/fingerprint_setup_screen_handler.cc",
"webui/chromeos/login/fingerprint_setup_screen_handler.h",
+ "webui/chromeos/login/gaia_password_changed_screen_handler.cc",
+ "webui/chromeos/login/gaia_password_changed_screen_handler.h",
"webui/chromeos/login/gaia_screen_handler.cc",
"webui/chromeos/login/gaia_screen_handler.h",
"webui/chromeos/login/gesture_navigation_screen_handler.cc",
@@ -1917,7 +2205,6 @@ static_library("ui") {
"webui/chromeos/login/marketing_opt_in_screen_handler.h",
"webui/chromeos/login/multidevice_setup_screen_handler.cc",
"webui/chromeos/login/multidevice_setup_screen_handler.h",
- "webui/chromeos/login/native_window_delegate.h",
"webui/chromeos/login/network_dropdown_handler.cc",
"webui/chromeos/login/network_dropdown_handler.h",
"webui/chromeos/login/network_screen_handler.cc",
@@ -1944,6 +2231,8 @@ static_library("ui") {
"webui/chromeos/login/sync_consent_screen_handler.h",
"webui/chromeos/login/terms_of_service_screen_handler.cc",
"webui/chromeos/login/terms_of_service_screen_handler.h",
+ "webui/chromeos/login/tpm_error_screen_handler.cc",
+ "webui/chromeos/login/tpm_error_screen_handler.h",
"webui/chromeos/login/update_required_screen_handler.cc",
"webui/chromeos/login/update_required_screen_handler.h",
"webui/chromeos/login/update_screen_handler.cc",
@@ -1966,8 +2255,12 @@ static_library("ui") {
"webui/chromeos/multidevice_setup/multidevice_setup_localized_strings_provider.h",
"webui/chromeos/network_element_localized_strings_provider.cc",
"webui/chromeos/network_element_localized_strings_provider.h",
+ "webui/chromeos/network_logs_message_handler.cc",
+ "webui/chromeos/network_logs_message_handler.h",
"webui/chromeos/network_ui.cc",
"webui/chromeos/network_ui.h",
+ "webui/chromeos/onc_import_message_handler.cc",
+ "webui/chromeos/onc_import_message_handler.h",
"webui/chromeos/power_ui.cc",
"webui/chromeos/power_ui.h",
"webui/chromeos/set_time_ui.cc",
@@ -2002,6 +2295,8 @@ static_library("ui") {
"webui/help/help_utils_chromeos.h",
"webui/help/version_updater_chromeos.cc",
"webui/help/version_updater_chromeos.h",
+ "webui/management_ui_handler_chromeos.cc",
+ "webui/management_ui_handler_chromeos.h",
"webui/settings/chromeos/about_section.cc",
"webui/settings/chromeos/about_section.h",
"webui/settings/chromeos/accessibility_handler.cc",
@@ -2060,6 +2355,8 @@ static_library("ui") {
"webui/settings/chromeos/fingerprint_handler.h",
"webui/settings/chromeos/google_assistant_handler.cc",
"webui/settings/chromeos/google_assistant_handler.h",
+ "webui/settings/chromeos/hierarchy.cc",
+ "webui/settings/chromeos/hierarchy.h",
"webui/settings/chromeos/internet_handler.cc",
"webui/settings/chromeos/internet_handler.h",
"webui/settings/chromeos/internet_section.cc",
@@ -2076,6 +2373,7 @@ static_library("ui") {
"webui/settings/chromeos/multidevice_section.h",
"webui/settings/chromeos/os_settings_features_util.cc",
"webui/settings/chromeos/os_settings_features_util.h",
+ "webui/settings/chromeos/os_settings_identifier.h",
"webui/settings/chromeos/os_settings_manager.cc",
"webui/settings/chromeos/os_settings_manager.h",
"webui/settings/chromeos/os_settings_manager_factory.cc",
@@ -2119,10 +2417,10 @@ static_library("ui") {
"webui/settings/chromeos/wallpaper_handler.h",
"webui/settings/tts_handler.cc",
"webui/settings/tts_handler.h",
+ "webui/signin/inline_login_dialog_chromeos.cc",
+ "webui/signin/inline_login_dialog_chromeos.h",
"webui/signin/inline_login_handler_chromeos.cc",
"webui/signin/inline_login_handler_chromeos.h",
- "webui/signin/inline_login_handler_dialog_chromeos.cc",
- "webui/signin/inline_login_handler_dialog_chromeos.h",
"webui/signin/inline_login_handler_modal_delegate.cc",
"webui/signin/inline_login_handler_modal_delegate.h",
"webui/version_handler_chromeos.cc",
@@ -2132,14 +2430,26 @@ static_library("ui") {
deps += [
"//ash",
+ "//ash/app_list",
+ "//ash/assistant/model",
+ "//ash/assistant/util",
"//ash/keyboard/ui",
"//ash/public/cpp",
+ "//ash/public/cpp/app_list/vector_icons",
"//ash/public/cpp/resources:ash_public_unscaled_resources",
"//ash/public/cpp/vector_icons",
"//ash/shortcut_viewer",
+ "//chrome/app:generated_resources",
"//chrome/browser/chromeos",
"//chrome/browser/chromeos:backdrop_wallpaper_proto",
- "//chrome/browser/resources/chromeos:camera_resources",
+ "//chrome/browser/chromeos/crostini:crostini_installer_types_mojom",
+ "//chrome/browser/resources:bluetooth_pairing_dialog_resources",
+ "//chrome/browser/ui/app_list/search/cros_action_history:cros_action_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",
+ "//chrome/browser/ui/app_list/search/search_result_ranker:search_ranking_event_proto",
"//chrome/browser/ui/webui/app_management:mojo_bindings",
"//chrome/browser/ui/webui/chromeos/add_supervision:mojo_bindings",
"//chrome/browser/ui/webui/chromeos/crostini_installer:mojo_bindings",
@@ -2152,6 +2462,7 @@ static_library("ui") {
"//chromeos/assistant:buildflags",
"//chromeos/audio",
"//chromeos/components/account_manager",
+ "//chromeos/components/camera_app_ui",
"//chromeos/components/help_app_ui",
"//chromeos/components/media_app_ui",
"//chromeos/components/multidevice",
@@ -2159,6 +2470,8 @@ static_library("ui") {
"//chromeos/components/multidevice/logging",
"//chromeos/components/print_management",
"//chromeos/components/proximity_auth",
+ "//chromeos/components/quick_answers",
+ "//chromeos/components/string_matching",
"//chromeos/components/tether",
"//chromeos/components/web_applications",
"//chromeos/constants",
@@ -2179,6 +2492,7 @@ static_library("ui") {
"//chromeos/login/session",
"//chromeos/network",
"//chromeos/resources:resources_grit",
+ "//chromeos/services/assistant:lib",
"//chromeos/services/assistant/public/cpp",
"//chromeos/services/assistant/public/mojom",
"//chromeos/services/assistant/public/proto",
@@ -2192,25 +2506,38 @@ static_library("ui") {
"//chromeos/services/multidevice_setup/public/cpp:prefs",
"//chromeos/services/multidevice_setup/public/cpp:url_provider",
"//chromeos/services/network_config/public/mojom",
+ "//chromeos/services/network_health/public/mojom",
"//chromeos/settings",
"//chromeos/strings",
"//chromeos/system",
"//components/arc",
+ "//components/assist_ranker",
+ "//components/assist_ranker/proto",
"//components/captive_portal/core",
"//components/consent_auditor:consent_auditor",
"//components/exo",
"//components/login",
+ "//components/metrics/structured:structured_events",
+ "//components/services/app_service/public/cpp:app_file_handling",
+ "//components/services/app_service/public/cpp:app_update",
+ "//components/services/app_service/public/cpp:icon_loader",
+ "//components/services/app_service/public/cpp:instance_update",
"//components/session_manager/core",
"//components/user_manager",
"//google_apis/drive",
"//mojo/public/js:resources_grit",
+ "//services/audio/public/mojom",
"//services/data_decoder/public/cpp",
"//services/device/public/cpp:device_features",
"//services/device/public/mojom",
+ "//services/media_session/public/mojom",
+ "//services/preferences/public/mojom",
"//ui/base/ime/chromeos",
"//ui/chromeos",
"//ui/chromeos/events",
"//ui/compositor_extra",
+ "//ui/file_manager:file_manager",
+ "//ui/ozone",
]
public_deps += [ "//chromeos/services/multidevice_setup/public/mojom" ]
allow_circular_includes_from += [ "//chrome/browser/chromeos" ]
@@ -2222,7 +2549,10 @@ static_library("ui") {
"webui/chromeos/emulator/device_emulator_ui.cc",
"webui/chromeos/emulator/device_emulator_ui.h",
]
- deps += [ "//chromeos/components/sample_system_web_app_ui" ]
+ deps += [
+ "//chromeos/components/sample_system_web_app_ui",
+ "//chromeos/components/telemetry_extension_ui",
+ ]
}
if (use_cras) {
@@ -2251,12 +2581,12 @@ static_library("ui") {
"frame/window_frame_util.h",
"passwords/account_storage_auth_helper.cc",
"passwords/account_storage_auth_helper.h",
- "signin_reauth_popup_delegate.cc",
- "signin_reauth_popup_delegate.h",
"signin_view_controller.cc",
"signin_view_controller.h",
"signin_view_controller_delegate.cc",
"signin_view_controller_delegate.h",
+ "tab_contents/chrome_web_contents_menu_helper.cc",
+ "tab_contents/chrome_web_contents_menu_helper.h",
"tab_contents/chrome_web_contents_view_handle_drop.cc",
"tab_contents/chrome_web_contents_view_handle_drop.h",
"views/autofill/payments/virtual_card_selection_dialog_view_impl.cc",
@@ -2302,6 +2632,8 @@ static_library("ui") {
"bookmarks/bookmark_bubble_sign_in_delegate.cc",
"bookmarks/bookmark_bubble_sign_in_delegate.h",
"profile_picker.h",
+ "signin_reauth_view_controller.cc",
+ "signin_reauth_view_controller.h",
"startup/default_browser_infobar_delegate.cc",
"startup/default_browser_infobar_delegate.h",
"startup/default_browser_prompt.cc",
@@ -2345,6 +2677,10 @@ static_library("ui") {
"webui/signin/signin_error_handler.h",
"webui/signin/signin_error_ui.cc",
"webui/signin/signin_error_ui.h",
+ "webui/signin/signin_reauth_handler.cc",
+ "webui/signin/signin_reauth_handler.h",
+ "webui/signin/signin_reauth_ui.cc",
+ "webui/signin/signin_reauth_ui.h",
"webui/signin/signin_utils_desktop.cc",
"webui/signin/signin_utils_desktop.h",
"webui/signin/user_manager_screen_handler.cc",
@@ -2390,22 +2726,10 @@ static_library("ui") {
]
}
- if (is_win || is_linux) {
- sources += [
- "input_method/input_method_engine_base.cc",
- "input_method/input_method_engine_base.h",
- ]
-
- if (!is_chromeos) {
- sources += [
- "input_method/input_method_engine.cc",
- "input_method/input_method_engine.h",
- ]
- }
- }
-
if (is_mac) {
sources += [
+ "autofill/autofill_popup_controller_impl_mac.h",
+ "autofill/autofill_popup_controller_impl_mac.mm",
"browser_commands_mac.h",
"browser_commands_mac.mm",
"browser_mac.cc",
@@ -2533,6 +2857,7 @@ static_library("ui") {
"cocoa/window_size_autosaver.mm",
"content_settings/media_authorization_wrapper_test.h",
"content_settings/media_authorization_wrapper_test.mm",
+ "find_bar/find_bar_platform_helper_mac.mm",
"views/apps/chrome_app_window_client_views_mac.mm",
"views/certificate_viewer_mac_views.mm",
"views/dropdown_bar_host_mac.mm",
@@ -2575,13 +2900,25 @@ static_library("ui") {
if (is_win) {
assert(toolkit_views)
+ assert(use_aura)
sources += [
"network_profile_bubble.cc",
"network_profile_bubble.h",
+ "pdf/adobe_reader_info_win.cc",
+ "pdf/adobe_reader_info_win.h",
"startup/credential_provider_signin_dialog_win.cc",
"startup/credential_provider_signin_dialog_win.h",
"startup/credential_provider_signin_info_fetcher_win.cc",
"startup/credential_provider_signin_info_fetcher_win.h",
+ "views/apps/app_window_desktop_native_widget_aura_win.cc",
+ "views/apps/app_window_desktop_native_widget_aura_win.h",
+ "views/apps/app_window_desktop_window_tree_host_win.cc",
+ "views/apps/app_window_desktop_window_tree_host_win.h",
+ "views/apps/chrome_app_window_client_views_win.cc",
+ "views/apps/chrome_native_app_window_views_win.cc",
+ "views/apps/chrome_native_app_window_views_win.h",
+ "views/apps/glass_app_window_frame_view_win.cc",
+ "views/apps/glass_app_window_frame_view_win.h",
"views/certificate_viewer_win.cc",
"views/chrome_cleaner_dialog_win.cc",
"views/chrome_cleaner_dialog_win.h",
@@ -2599,6 +2936,8 @@ static_library("ui") {
"views/frame/browser_desktop_window_tree_host_win.h",
"views/frame/browser_window_property_manager_win.cc",
"views/frame/browser_window_property_manager_win.h",
+ "views/frame/glass_browser_caption_button_container.cc",
+ "views/frame/glass_browser_caption_button_container.h",
"views/frame/glass_browser_frame_view.cc",
"views/frame/glass_browser_frame_view.h",
"views/frame/minimize_button_metrics_win.cc",
@@ -2654,6 +2993,7 @@ static_library("ui") {
"//third_party/isimpledom",
"//third_party/libphonenumber",
"//third_party/wtl",
+ "//ui/aura",
"//ui/base/ime",
"//ui/events:dom_keycode_converter",
]
@@ -2780,15 +3120,6 @@ static_library("ui") {
}
}
- if (is_chromeos) {
- sources += [
- "views/parent_permission_dialog_view.cc",
- "views/parent_permission_dialog_view.h",
- "views/supervised_user/extension_install_blocked_by_parent_dialog_view.cc",
- "views/supervised_user/extension_install_blocked_by_parent_dialog_view.h",
- ]
- }
-
if (toolkit_views) {
sources += [
"autofill/payments/local_card_migration_bubble.h",
@@ -2814,7 +3145,6 @@ static_library("ui") {
"autofill/payments/save_upi_bubble_controller_impl.cc",
"autofill/payments/save_upi_bubble_controller_impl.h",
"bubble_anchor_util.h",
- "cookie_controls/cookie_controls_view.h",
"manifest_web_app_browser_controller.cc",
"manifest_web_app_browser_controller.h",
"qrcode_generator/qrcode_generator_bubble_controller.cc",
@@ -2831,6 +3161,8 @@ static_library("ui") {
"views/accessibility/caption_bubble.h",
"views/accessibility/caption_bubble_controller_views.cc",
"views/accessibility/caption_bubble_controller_views.h",
+ "views/accessibility/caption_bubble_model.cc",
+ "views/accessibility/caption_bubble_model.h",
"views/accessibility/invert_bubble_view.cc",
"views/accessibility/invert_bubble_view.h",
"views/accessibility/non_accessible_image_view.cc",
@@ -3031,12 +3363,12 @@ static_library("ui") {
"views/frame/browser_root_view.h",
"views/frame/browser_view.cc",
"views/frame/browser_view.h",
- "views/frame/browser_view_commands_mac.h",
- "views/frame/browser_view_commands_mac.mm",
"views/frame/browser_view_layout.cc",
"views/frame/browser_view_layout.h",
"views/frame/browser_view_layout_delegate.h",
"views/frame/browser_window_factory.cc",
+ "views/frame/caption_button_container.cc",
+ "views/frame/caption_button_container.h",
"views/frame/contents_layout_manager.cc",
"views/frame/contents_layout_manager.h",
"views/frame/contents_web_view.cc",
@@ -3093,8 +3425,6 @@ static_library("ui") {
"views/hover_button_controller.h",
"views/hung_renderer_view.cc",
"views/hung_renderer_view.h",
- "views/ime/ime_warning_bubble_view.cc",
- "views/ime/ime_warning_bubble_view.h",
"views/importer/import_lock_dialog_view.cc",
"views/importer/import_lock_dialog_view.h",
"views/infobars/alternate_nav_infobar_view.cc",
@@ -3137,6 +3467,8 @@ static_library("ui") {
"views/location_bar/location_bar_view.h",
"views/location_bar/location_icon_view.cc",
"views/location_bar/location_icon_view.h",
+ "views/location_bar/permission_chip.cc",
+ "views/location_bar/permission_chip.h",
"views/location_bar/selected_keyword_view.cc",
"views/location_bar/selected_keyword_view.h",
"views/location_bar/star_view.cc",
@@ -3179,8 +3511,6 @@ static_library("ui") {
"views/message_box_dialog.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",
@@ -3248,6 +3578,8 @@ static_library("ui") {
"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_icon.cc",
+ "views/page_info/permission_icon.h",
"views/page_info/permission_selector_row.cc",
"views/page_info/permission_selector_row.h",
"views/page_info/permission_selector_row_observer.h",
@@ -3389,6 +3721,8 @@ static_library("ui") {
"views/tab_icon_view.h",
"views/tab_modal_confirm_dialog_views.cc",
"views/tab_modal_confirm_dialog_views.h",
+ "views/tab_search/tab_search_bubble_view.cc",
+ "views/tab_search/tab_search_bubble_view.h",
"views/tab_sharing/tab_sharing_ui_views.cc",
"views/tab_sharing/tab_sharing_ui_views.h",
"views/tabs/alert_indicator.cc",
@@ -3425,6 +3759,8 @@ static_library("ui") {
"views/tabs/tab_group_underline.h",
"views/tabs/tab_group_views.cc",
"views/tabs/tab_group_views.h",
+ "views/tabs/tab_groups_iph_controller.cc",
+ "views/tabs/tab_groups_iph_controller.h",
"views/tabs/tab_hover_card_bubble_view.cc",
"views/tabs/tab_hover_card_bubble_view.h",
"views/tabs/tab_icon.cc",
@@ -3544,10 +3880,12 @@ static_library("ui") {
]
deps += [
+ "//base/util/ranges",
"//base/util/timer",
"//chrome/browser/ui/views",
"//chrome/common/qr_code_generator",
"//components/constrained_window",
+ "//components/content_settings/browser/ui",
"//components/media_message_center",
"//components/page_info",
"//components/payments/content",
@@ -3563,17 +3901,16 @@ static_library("ui") {
if (is_desktop_linux) {
sources += [
+ "views/chrome_views_delegate_linux.cc",
"views/frame/desktop_linux_browser_frame_view.cc",
"views/frame/desktop_linux_browser_frame_view.h",
"views/frame/desktop_linux_browser_frame_view_layout.cc",
"views/frame/desktop_linux_browser_frame_view_layout.h",
+ "views/frame/opaque_browser_frame_view_linux.cc",
+ "views/frame/opaque_browser_frame_view_linux.h",
]
}
- if (is_desktop_linux) {
- sources += [ "views/chrome_views_delegate_linux.cc" ]
- }
-
if (is_linux) {
sources += [
"views/process_singleton_dialog_linux.cc",
@@ -3591,6 +3928,8 @@ static_library("ui") {
"views/apps/native_app_window_frame_view_mac.h",
"views/apps/native_app_window_frame_view_mac.mm",
"views/chrome_views_delegate_mac.cc",
+ "views/frame/browser_view_commands_mac.h",
+ "views/frame/browser_view_commands_mac.mm",
"views/policy/enterprise_startup_dialog_mac_util.h",
"views/policy/enterprise_startup_dialog_mac_util.mm",
"views/ssl_client_certificate_selector_mac.h",
@@ -3642,25 +3981,22 @@ static_library("ui") {
deps += [ "//ui/ozone" ]
}
}
+ if (use_ozone) {
+ deps += [ "//ui/base/cursor:cursor_base" ]
+ }
}
}
- if (is_chromeos) {
- sources += [
- "views/relaunch_notification/relaunch_notification_controller_platform_impl_chromeos.cc",
- "views/relaunch_notification/relaunch_notification_controller_platform_impl_chromeos.h",
- ]
- deps += [ "//ui/ozone" ]
- } else {
+ if (!is_chromeos) {
sources += [
+ "views/accessibility/accessibility_focus_highlight.cc",
+ "views/accessibility/accessibility_focus_highlight.h",
"views/frame/opaque_browser_frame_view.cc",
"views/frame/opaque_browser_frame_view.h",
"views/frame/opaque_browser_frame_view_layout.cc",
"views/frame/opaque_browser_frame_view_layout.h",
"views/frame/opaque_browser_frame_view_layout_delegate.cc",
"views/frame/opaque_browser_frame_view_layout_delegate.h",
- "views/frame/opaque_browser_frame_view_linux.cc",
- "views/frame/opaque_browser_frame_view_linux.h",
"views/frame/opaque_browser_frame_view_platform_specific.cc",
"views/frame/opaque_browser_frame_view_platform_specific.h",
"views/outdated_upgrade_bubble_view.cc",
@@ -3701,33 +4037,14 @@ 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",
- "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",
- "views/apps/app_window_desktop_window_tree_host_win.cc",
- "views/apps/app_window_desktop_window_tree_host_win.h",
"views/apps/app_window_easy_resize_window_targeter.cc",
"views/apps/app_window_easy_resize_window_targeter.h",
- "views/apps/chrome_app_window_client_views_chromeos.cc",
- "views/apps/chrome_app_window_client_views_win.cc",
"views/apps/chrome_native_app_window_views_aura.cc",
"views/apps/chrome_native_app_window_views_aura.h",
- "views/apps/chrome_native_app_window_views_win.cc",
- "views/apps/chrome_native_app_window_views_win.h",
- "views/apps/glass_app_window_frame_view_win.cc",
- "views/apps/glass_app_window_frame_view_win.h",
"views/apps/shaped_app_window_targeter.cc",
"views/apps/shaped_app_window_targeter.h",
"views/dropdown_bar_host_aura.cc",
- "views/frame/browser_non_client_frame_view_factory_chromeos.cc",
- "views/ime/ime_window_frame_view.cc",
- "views/ime/ime_window_frame_view.h",
- "views/ime/ime_window_view.cc",
- "views/ime/ime_window_view.h",
"views/renderer_context_menu/render_view_context_menu_views.cc",
"views/renderer_context_menu/render_view_context_menu_views.h",
"views/tab_contents/chrome_web_contents_view_delegate_views.cc",
@@ -3757,341 +4074,6 @@ static_library("ui") {
}
}
- if (is_chromeos) {
- sources += [
- "app_icon_loader_delegate.h",
- "app_list/app_context_menu.cc",
- "app_list/app_context_menu.h",
- "app_list/app_context_menu_delegate.h",
- "app_list/app_list_client_impl.cc",
- "app_list/app_list_client_impl.h",
- "app_list/app_list_controller_delegate.cc",
- "app_list/app_list_controller_delegate.h",
- "app_list/app_list_model_builder.cc",
- "app_list/app_list_model_builder.h",
- "app_list/app_list_model_updater.cc",
- "app_list/app_list_model_updater.h",
- "app_list/app_list_model_updater_observer.h",
- "app_list/app_list_notifier_impl.cc",
- "app_list/app_list_notifier_impl.h",
- "app_list/app_list_syncable_service.cc",
- "app_list/app_list_syncable_service.h",
- "app_list/app_list_syncable_service_factory.cc",
- "app_list/app_list_syncable_service_factory.h",
- "app_list/app_service/app_service_app_icon_loader.cc",
- "app_list/app_service/app_service_app_icon_loader.h",
- "app_list/app_service/app_service_app_item.cc",
- "app_list/app_service/app_service_app_item.h",
- "app_list/app_service/app_service_app_model_builder.cc",
- "app_list/app_service/app_service_app_model_builder.h",
- "app_list/app_service/app_service_context_menu.cc",
- "app_list/app_service/app_service_context_menu.h",
- "app_list/arc/arc_app_context_menu.cc",
- "app_list/arc/arc_app_context_menu.h",
- "app_list/arc/arc_app_dialog.h",
- "app_list/arc/arc_app_icon.cc",
- "app_list/arc/arc_app_icon.h",
- "app_list/arc/arc_app_icon_descriptor.cc",
- "app_list/arc/arc_app_icon_descriptor.h",
- "app_list/arc/arc_app_launcher.cc",
- "app_list/arc/arc_app_launcher.h",
- "app_list/arc/arc_app_list_prefs.cc",
- "app_list/arc/arc_app_list_prefs.h",
- "app_list/arc/arc_app_list_prefs_factory.cc",
- "app_list/arc/arc_app_list_prefs_factory.h",
- "app_list/arc/arc_app_scoped_pref_update.cc",
- "app_list/arc/arc_app_scoped_pref_update.h",
- "app_list/arc/arc_app_utils.cc",
- "app_list/arc/arc_app_utils.h",
- "app_list/arc/arc_data_removal_dialog.h",
- "app_list/arc/arc_default_app_list.cc",
- "app_list/arc/arc_default_app_list.h",
- "app_list/arc/arc_fast_app_reinstall_starter.cc",
- "app_list/arc/arc_fast_app_reinstall_starter.h",
- "app_list/arc/arc_package_sync_model_type_controller.cc",
- "app_list/arc/arc_package_sync_model_type_controller.h",
- "app_list/arc/arc_package_syncable_service.cc",
- "app_list/arc/arc_package_syncable_service.h",
- "app_list/arc/arc_package_syncable_service_factory.cc",
- "app_list/arc/arc_package_syncable_service_factory.h",
- "app_list/arc/arc_pai_starter.cc",
- "app_list/arc/arc_pai_starter.h",
- "app_list/arc/arc_playstore_app_context_menu.cc",
- "app_list/arc/arc_playstore_app_context_menu.h",
- "app_list/arc/arc_usb_host_permission_manager.cc",
- "app_list/arc/arc_usb_host_permission_manager.h",
- "app_list/arc/arc_usb_host_permission_manager_factory.cc",
- "app_list/arc/arc_usb_host_permission_manager_factory.h",
- "app_list/arc/arc_vpn_provider_manager.cc",
- "app_list/arc/arc_vpn_provider_manager.h",
- "app_list/arc/arc_vpn_provider_manager_factory.cc",
- "app_list/arc/arc_vpn_provider_manager_factory.h",
- "app_list/chrome_app_list_item.cc",
- "app_list/chrome_app_list_item.h",
- "app_list/chrome_app_list_model_updater.cc",
- "app_list/chrome_app_list_model_updater.h",
- "app_list/crostini/crostini_app_context_menu.cc",
- "app_list/crostini/crostini_app_context_menu.h",
- "app_list/crostini/crostini_app_icon.cc",
- "app_list/crostini/crostini_app_icon.h",
- "app_list/extension_app_context_menu.cc",
- "app_list/extension_app_context_menu.h",
- "app_list/extension_app_utils.cc",
- "app_list/extension_app_utils.h",
- "app_list/internal_app/internal_app_metadata.cc",
- "app_list/internal_app/internal_app_metadata.h",
- "app_list/md_icon_normalizer.cc",
- "app_list/md_icon_normalizer.h",
- "app_list/page_break_app_item.cc",
- "app_list/page_break_app_item.h",
- "app_list/page_break_constants.cc",
- "app_list/page_break_constants.h",
- "app_list/search/answer_card/answer_card_result.cc",
- "app_list/search/answer_card/answer_card_result.h",
- "app_list/search/answer_card/answer_card_search_provider.cc",
- "app_list/search/answer_card/answer_card_search_provider.h",
- "app_list/search/app_result.cc",
- "app_list/search/app_result.h",
- "app_list/search/app_search_provider.cc",
- "app_list/search/app_search_provider.h",
- "app_list/search/app_service_app_result.cc",
- "app_list/search/app_service_app_result.h",
- "app_list/search/arc/arc_app_data_search_provider.cc",
- "app_list/search/arc/arc_app_data_search_provider.h",
- "app_list/search/arc/arc_app_data_search_result.cc",
- "app_list/search/arc/arc_app_data_search_result.h",
- "app_list/search/arc/arc_app_reinstall_app_result.cc",
- "app_list/search/arc/arc_app_reinstall_app_result.h",
- "app_list/search/arc/arc_app_reinstall_search_provider.cc",
- "app_list/search/arc/arc_app_reinstall_search_provider.h",
- "app_list/search/arc/arc_app_shortcut_search_result.cc",
- "app_list/search/arc/arc_app_shortcut_search_result.h",
- "app_list/search/arc/arc_app_shortcuts_search_provider.cc",
- "app_list/search/arc/arc_app_shortcuts_search_provider.h",
- "app_list/search/arc/arc_playstore_search_provider.cc",
- "app_list/search/arc/arc_playstore_search_provider.h",
- "app_list/search/arc/arc_playstore_search_result.cc",
- "app_list/search/arc/arc_playstore_search_result.h",
- "app_list/search/assistant_search_provider.cc",
- "app_list/search/assistant_search_provider.h",
- "app_list/search/chrome_search_result.cc",
- "app_list/search/chrome_search_result.h",
- "app_list/search/common/file_icon_util.cc",
- "app_list/search/common/file_icon_util.h",
- "app_list/search/common/url_icon_source.cc",
- "app_list/search/common/url_icon_source.h",
- "app_list/search/cros_action_history/cros_action_recorder.cc",
- "app_list/search/cros_action_history/cros_action_recorder.h",
- "app_list/search/cros_action_history/cros_action_recorder_tab_tracker.cc",
- "app_list/search/cros_action_history/cros_action_recorder_tab_tracker.h",
- "app_list/search/drive_quick_access_chip_result.cc",
- "app_list/search/drive_quick_access_chip_result.h",
- "app_list/search/drive_quick_access_provider.cc",
- "app_list/search/drive_quick_access_provider.h",
- "app_list/search/drive_quick_access_result.cc",
- "app_list/search/drive_quick_access_result.h",
- "app_list/search/file_chip_result.cc",
- "app_list/search/file_chip_result.h",
- "app_list/search/mixer.cc",
- "app_list/search/mixer.h",
- "app_list/search/omnibox_provider.cc",
- "app_list/search/omnibox_provider.h",
- "app_list/search/omnibox_result.cc",
- "app_list/search/omnibox_result.h",
- "app_list/search/os_settings_provider.cc",
- "app_list/search/os_settings_provider.h",
- "app_list/search/search_controller.cc",
- "app_list/search/search_controller.h",
- "app_list/search/search_controller_factory.cc",
- "app_list/search/search_controller_factory.h",
- "app_list/search/search_metrics_observer.cc",
- "app_list/search/search_metrics_observer.h",
- "app_list/search/search_provider.cc",
- "app_list/search/search_provider.h",
- "app_list/search/search_resource_manager.cc",
- "app_list/search/search_resource_manager.h",
- "app_list/search/search_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_event_logger_helper.cc",
- "app_list/search/search_result_ranker/app_launch_event_logger_helper.h",
- "app_list/search/search_result_ranker/app_launch_predictor.cc",
- "app_list/search/search_result_ranker/app_launch_predictor.h",
- "app_list/search/search_result_ranker/app_list_launch_metrics_provider.cc",
- "app_list/search/search_result_ranker/app_list_launch_metrics_provider.h",
- "app_list/search/search_result_ranker/app_list_launch_recorder.cc",
- "app_list/search/search_result_ranker/app_list_launch_recorder.h",
- "app_list/search/search_result_ranker/app_list_launch_recorder_util.cc",
- "app_list/search/search_result_ranker/app_list_launch_recorder_util.h",
- "app_list/search/search_result_ranker/app_search_result_ranker.cc",
- "app_list/search/search_result_ranker/app_search_result_ranker.h",
- "app_list/search/search_result_ranker/chip_ranker.cc",
- "app_list/search/search_result_ranker/chip_ranker.h",
- "app_list/search/search_result_ranker/frecency_store.cc",
- "app_list/search/search_result_ranker/frecency_store.h",
- "app_list/search/search_result_ranker/histogram_util.cc",
- "app_list/search/search_result_ranker/histogram_util.h",
- "app_list/search/search_result_ranker/ml_app_rank_provider.cc",
- "app_list/search/search_result_ranker/ml_app_rank_provider.h",
- "app_list/search/search_result_ranker/ranking_item_util.cc",
- "app_list/search/search_result_ranker/ranking_item_util.h",
- "app_list/search/search_result_ranker/recurrence_predictor.cc",
- "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_ranking_event_logger.cc",
- "app_list/search/search_result_ranker/search_ranking_event_logger.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",
- "app_list/search/settings_shortcut/settings_shortcut_metadata.h",
- "app_list/search/settings_shortcut/settings_shortcut_provider.cc",
- "app_list/search/settings_shortcut/settings_shortcut_provider.h",
- "app_list/search/settings_shortcut/settings_shortcut_result.cc",
- "app_list/search/settings_shortcut/settings_shortcut_result.h",
- "app_list/search/zero_state_file_provider.cc",
- "app_list/search/zero_state_file_provider.h",
- "app_list/search/zero_state_file_result.cc",
- "app_list/search/zero_state_file_result.h",
- "app_list/web_app_context_menu.cc",
- "app_list/web_app_context_menu.h",
- "ash/assistant/assistant_client_impl.cc",
- "ash/assistant/assistant_client_impl.h",
- "ash/assistant/assistant_context_util.cc",
- "ash/assistant/assistant_context_util.h",
- "ash/assistant/assistant_setup.cc",
- "ash/assistant/assistant_setup.h",
- "ash/assistant/assistant_state_client.cc",
- "ash/assistant/assistant_state_client.h",
- "ash/assistant/assistant_web_view_factory_impl.cc",
- "ash/assistant/assistant_web_view_factory_impl.h",
- "ash/assistant/assistant_web_view_impl.cc",
- "ash/assistant/assistant_web_view_impl.h",
- "ash/assistant/conversation_starters_client_impl.cc",
- "ash/assistant/conversation_starters_client_impl.h",
- "ash/assistant/conversation_starters_parser.cc",
- "ash/assistant/conversation_starters_parser.h",
- "ash/assistant/device_actions.cc",
- "ash/assistant/device_actions.h",
- "ash/assistant/device_actions_delegate.h",
- "ash/assistant/device_actions_delegate_impl.cc",
- "ash/assistant/device_actions_delegate_impl.h",
- "ash/assistant/proactive_suggestions_client_impl.cc",
- "ash/assistant/proactive_suggestions_client_impl.h",
- "ash/assistant/proactive_suggestions_loader.cc",
- "ash/assistant/proactive_suggestions_loader.h",
- "ash/assistant/search_and_assistant_enabled_checker.cc",
- "ash/assistant/search_and_assistant_enabled_checker.h",
- "ash/image_downloader_impl.cc",
- "ash/image_downloader_impl.h",
- "ash/launcher/app_service/app_service_app_window_arc_tracker.cc",
- "ash/launcher/app_service/app_service_app_window_arc_tracker.h",
- "ash/launcher/app_service/app_service_app_window_crostini_tracker.cc",
- "ash/launcher/app_service/app_service_app_window_crostini_tracker.h",
- "ash/launcher/app_service/app_service_app_window_launcher_controller.cc",
- "ash/launcher/app_service/app_service_app_window_launcher_controller.h",
- "ash/launcher/app_service/app_service_app_window_launcher_item_controller.cc",
- "ash/launcher/app_service/app_service_app_window_launcher_item_controller.h",
- "ash/launcher/app_service/app_service_instance_registry_helper.cc",
- "ash/launcher/app_service/app_service_instance_registry_helper.h",
- "ash/launcher/app_service/app_service_shelf_context_menu.cc",
- "ash/launcher/app_service/app_service_shelf_context_menu.h",
- "ash/launcher/app_service/launcher_app_service_app_updater.cc",
- "ash/launcher/app_service/launcher_app_service_app_updater.h",
- "ash/launcher/app_window_base.cc",
- "ash/launcher/app_window_base.h",
- "ash/launcher/arc_app_shelf_id.cc",
- "ash/launcher/arc_app_shelf_id.h",
- "ash/launcher/arc_app_window.cc",
- "ash/launcher/arc_app_window.h",
- "ash/launcher/arc_app_window_delegate.h",
- "ash/launcher/arc_app_window_info.cc",
- "ash/launcher/arc_app_window_info.h",
- "ash/launcher/arc_app_window_launcher_controller.cc",
- "ash/launcher/arc_app_window_launcher_controller.h",
- "ash/launcher/arc_app_window_launcher_item_controller.cc",
- "ash/launcher/arc_app_window_launcher_item_controller.h",
- "ash/launcher/arc_shelf_context_menu.cc",
- "ash/launcher/arc_shelf_context_menu.h",
- "ash/launcher/arc_shelf_spinner_item_controller.cc",
- "ash/launcher/arc_shelf_spinner_item_controller.h",
- "ash/launcher/crostini_app_display.cc",
- "ash/launcher/crostini_app_display.h",
- "ash/launcher/crostini_app_window_shelf_controller.cc",
- "ash/launcher/crostini_app_window_shelf_controller.h",
- "ash/launcher/crostini_shelf_context_menu.cc",
- "ash/launcher/crostini_shelf_context_menu.h",
- "ash/launcher/internal_app_shelf_context_menu.cc",
- "ash/launcher/internal_app_shelf_context_menu.h",
- "ash/launcher/internal_app_window_shelf_controller.cc",
- "ash/launcher/internal_app_window_shelf_controller.h",
- "ash/launcher/shelf_spinner_controller.cc",
- "ash/launcher/shelf_spinner_controller.h",
- "ash/launcher/shelf_spinner_item_controller.cc",
- "ash/launcher/shelf_spinner_item_controller.h",
- "supervised_user/parent_permission_dialog.h",
- "views/apps/app_dialog/app_block_dialog_view.cc",
- "views/apps/app_dialog/app_block_dialog_view.h",
- "views/apps/app_dialog/app_pause_dialog_view.cc",
- "views/apps/app_dialog/app_pause_dialog_view.h",
- "views/arc_app_dialog_view.cc",
- "views/arc_data_removal_dialog_view.cc",
- "views/crostini/crostini_ansible_software_config_view.cc",
- "views/crostini/crostini_ansible_software_config_view.h",
- "views/crostini/crostini_app_restart_view.cc",
- "views/crostini/crostini_app_restart_view.h",
- "views/crostini/crostini_force_close_view.cc",
- "views/crostini/crostini_force_close_view.h",
- "views/crostini/crostini_package_install_failure_view.cc",
- "views/crostini/crostini_package_install_failure_view.h",
- "views/crostini/crostini_recovery_view.cc",
- "views/crostini/crostini_recovery_view.h",
- "views/crostini/crostini_uninstaller_view.cc",
- "views/crostini/crostini_uninstaller_view.h",
- "views/crostini/crostini_update_component_view.cc",
- "views/crostini/crostini_update_component_view.h",
- "views/crostini/crostini_update_filesystem_view.cc",
- "views/crostini/crostini_update_filesystem_view.h",
- "views/frame/custom_tab_browser_frame.cc",
- "views/frame/custom_tab_browser_frame.h",
- "views/plugin_vm/plugin_vm_installer_view.cc",
- "views/plugin_vm/plugin_vm_installer_view.h",
- ]
- deps += [
- "//ash/app_list",
- "//ash/assistant/model",
- "//ash/assistant/util",
- "//ash/public/cpp",
- "//ash/public/cpp/app_list/vector_icons",
- "//ash/public/cpp/vector_icons",
- "//chrome/browser/chromeos/crostini:crostini_installer_types_mojom",
- "//chrome/browser/ui/app_list/search/cros_action_history:cros_action_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",
- "//chrome/browser/ui/app_list/search/search_result_ranker:search_ranking_event_proto",
- "//chrome/services/app_service/public/cpp:app_update",
- "//chrome/services/app_service/public/cpp:icon_loader",
- "//chrome/services/app_service/public/cpp:instance_update",
- "//chromeos/services/assistant:lib",
- "//chromeos/services/assistant/public/mojom",
- "//chromeos/services/network_config/public/mojom",
- "//components/assist_ranker",
- "//components/assist_ranker/proto",
- "//components/metrics/structured:structured_events",
- "//components/services/app_service/public/cpp:app_file_handling",
- "//services/audio/public/mojom",
- "//services/device/public/mojom",
- "//services/media_session/public/mojom",
- "//services/preferences/public/mojom",
- "//ui/file_manager:file_manager",
- ]
- }
-
if (enable_extensions) {
deps += [
"//apps",
@@ -4379,10 +4361,6 @@ static_library("test_support") {
testonly = true
sources = [
- "cocoa/test/cocoa_test_helper.h",
- "cocoa/test/cocoa_test_helper.mm",
- "cocoa/test/run_loop_testing.h",
- "cocoa/test/run_loop_testing.mm",
"content_settings/fake_owner.cc",
"content_settings/fake_owner.h",
"find_bar/find_bar_host_unittest_util.h",
@@ -4415,6 +4393,17 @@ static_library("test_support") {
"//ui/shell_dialogs",
]
+ if (is_mac) {
+ assert(toolkit_views)
+ sources += [
+ "cocoa/test/cocoa_test_helper.h",
+ "cocoa/test/cocoa_test_helper.mm",
+ "cocoa/test/run_loop_testing.h",
+ "cocoa/test/run_loop_testing.mm",
+ "views/extensions/extension_action_test_helper_mac.mm",
+ ]
+ }
+
if (toolkit_views) {
deps += [
"//components/constrained_window:constrained_window",
@@ -4422,7 +4411,6 @@ static_library("test_support") {
]
sources += [
"extensions/extension_action_test_helper.h",
- "views/extensions/extension_action_test_helper_mac.mm",
"views/extensions/extension_action_test_helper_views.cc",
"views/extensions/extension_action_test_helper_views.h",
"views/extensions/extensions_menu_test_util.cc",
@@ -4444,11 +4432,11 @@ static_library("test_support") {
if (!is_android) {
sources += [
+ "exclusive_access/exclusive_access_test.cc",
+ "exclusive_access/exclusive_access_test.h",
"exclusive_access/fullscreen_controller_state_test.cc",
"exclusive_access/fullscreen_controller_state_test.h",
"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",
"hats/mock_hats_service.cc",
@@ -4490,6 +4478,12 @@ static_library("test_support") {
"ash/test_session_controller.h",
"ash/test_wallpaper_controller.cc",
"ash/test_wallpaper_controller.h",
+ "webui/settings/chromeos/fake_hierarchy.cc",
+ "webui/settings/chromeos/fake_hierarchy.h",
+ "webui/settings/chromeos/fake_os_settings_section.cc",
+ "webui/settings/chromeos/fake_os_settings_section.h",
+ "webui/settings/chromeos/fake_os_settings_sections.cc",
+ "webui/settings/chromeos/fake_os_settings_sections.h",
]
deps += [
"//ash/public/cpp",
diff --git a/chromium/chrome/browser/ui/android/appmenu/BUILD.gn b/chromium/chrome/browser/ui/android/appmenu/BUILD.gn
index 26b23eec23f..6b117b5cf25 100644
--- a/chromium/chrome/browser/ui/android/appmenu/BUILD.gn
+++ b/chromium/chrome/browser/ui/android/appmenu/BUILD.gn
@@ -21,8 +21,12 @@ android_library("java") {
}
android_library_factory("factory_java") {
+ # These deps will be inherited by the resulting android_library target.
deps = [ ":java" ]
- sources = [ "java/src/org/chromium/chrome/browser/ui/appmenu/AppMenuCoordinatorFactory.java" ]
+
+ # This internal file will be replaced by a generated file so the resulting
+ # android_library target does not actually depend on this internal file.
+ sources = [ "//chrome/browser/ui/android/appmenu/internal/java/src/org/chromium/chrome/browser/ui/appmenu/AppMenuCoordinatorFactory.java" ]
}
android_resources("java_resources") {
diff --git a/chromium/chrome/browser/ui/android/appmenu/internal/BUILD.gn b/chromium/chrome/browser/ui/android/appmenu/internal/BUILD.gn
index 81e5cda8251..91cf3e0a673 100644
--- a/chromium/chrome/browser/ui/android/appmenu/internal/BUILD.gn
+++ b/chromium/chrome/browser/ui/android/appmenu/internal/BUILD.gn
@@ -30,6 +30,7 @@ android_library("java") {
"//components/browser_ui/widget/android:java",
"//third_party/android_deps:android_support_v7_appcompat_java",
"//third_party/android_deps:androidx_annotation_annotation_java",
+ "//third_party/android_deps:androidx_appcompat_appcompat_resources_java",
"//ui/android:ui_java",
]
}
@@ -74,6 +75,7 @@ android_library("javatests") {
"//components/browser_ui/widget/android:test_support_java",
"//content/public/test/android:content_java_test_support",
"//third_party/android_deps:android_support_v7_appcompat_java",
+ "//third_party/android_deps:androidx_appcompat_appcompat_resources_java",
"//third_party/android_support_test_runner:rules_java",
"//third_party/android_support_test_runner:runner_java",
"//third_party/junit",
@@ -110,5 +112,8 @@ java_library("junit") {
deps = [
":java",
"//base:base_junit_test_support",
+ "//third_party/android_deps:robolectric_all_java",
+ "//third_party/junit",
+ "//third_party/mockito:mockito_java",
]
}
diff --git a/chromium/chrome/browser/ui/android/default_browser_promo/BUILD.gn b/chromium/chrome/browser/ui/android/default_browser_promo/BUILD.gn
new file mode 100644
index 00000000000..6ebd8d0b94c
--- /dev/null
+++ b/chromium/chrome/browser/ui/android/default_browser_promo/BUILD.gn
@@ -0,0 +1,78 @@
+# Copyright 2020 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//build/config/android/rules.gni")
+
+android_library("java") {
+ sources = [
+ "java/src/org/chromium/chrome/browser/ui/default_browser_promo/DefaultBrowserPromoDialog.java",
+ "java/src/org/chromium/chrome/browser/ui/default_browser_promo/DefaultBrowserPromoManager.java",
+ "java/src/org/chromium/chrome/browser/ui/default_browser_promo/DefaultBrowserPromoMetrics.java",
+ "java/src/org/chromium/chrome/browser/ui/default_browser_promo/DefaultBrowserPromoUtils.java",
+ ]
+ deps = [
+ ":java_resources",
+ "//base:base_java",
+ "//chrome/browser/android/lifecycle:java",
+ "//chrome/browser/flags:java",
+ "//chrome/browser/preferences:java",
+ "//chrome/browser/profiles/android:java",
+ "//components/browser_ui/widget/android:java",
+ "//ui/android:ui_full_java",
+ ]
+}
+
+android_resources("java_resources") {
+ custom_package = "org.chromium.chrome.browser.ui.default_browser_promo"
+ sources = [
+ "java/res/drawable/default_browser_promo_illustration.xml",
+ "java/res/drawable/ic_illustration_aroundlogo.xml",
+ ]
+ deps = [
+ "//chrome/browser/ui/android/strings:ui_strings_grd",
+ "//components/browser_ui/widget/android:java_resources",
+ "//ui/android:ui_java_resources",
+ ]
+}
+
+java_library("junit") {
+ # Skip platform checks since Robolectric depends on requires_android targets.
+ bypass_platform_checks = true
+ testonly = true
+ sources = [ "java/src/org/chromium/chrome/browser/ui/default_browser_promo/DefaultBrowserPromoUtilsTest.java" ]
+ deps = [
+ ":java",
+ "//base:base_java",
+ "//base:base_junit_test_support",
+ "//third_party/android_deps:robolectric_all_java",
+ "//third_party/junit",
+ "//third_party/mockito:mockito_java",
+ ]
+}
+
+android_library("javatests") {
+ testonly = true
+
+ sources = [ "java/src/org/chromium/chrome/browser/ui/default_browser_promo/DefaultBrowserPromoManagerTest.java" ]
+
+ deps = [
+ ":java",
+ "//base:base_java",
+ "//base:base_java_test_support",
+ "//chrome/android:chrome_java",
+ "//chrome/browser/android/lifecycle:java",
+ "//chrome/test/android:chrome_java_test_support",
+ "//components/browser_ui/widget/android:java",
+ "//content/public/test/android:content_java_test_support",
+ "//third_party/android_deps:android_support_v7_appcompat_java",
+ "//third_party/android_deps:androidx_preference_preference_java",
+ "//third_party/android_deps:espresso_java",
+ "//third_party/android_support_test_runner:rules_java",
+ "//third_party/android_support_test_runner:runner_java",
+ "//third_party/hamcrest:hamcrest_java",
+ "//third_party/junit:junit",
+ "//ui/android:ui_full_java",
+ "//ui/android:ui_java_test_support",
+ ]
+}
diff --git a/chromium/chrome/browser/ui/android/native_page/BUILD.gn b/chromium/chrome/browser/ui/android/native_page/BUILD.gn
index 8157eb75511..01c80a961da 100644
--- a/chromium/chrome/browser/ui/android/native_page/BUILD.gn
+++ b/chromium/chrome/browser/ui/android/native_page/BUILD.gn
@@ -2,7 +2,6 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//build/config/android/rules.gni")
-import("//chrome/android/features/android_library_factory_tmpl.gni")
android_library("java") {
sources = [
diff --git a/chromium/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chromium/chrome/browser/ui/android/strings/android_chrome_strings.grd
index 5958622986a..8400b41389c 100644
--- a/chromium/chrome/browser/ui/android/strings/android_chrome_strings.grd
+++ b/chromium/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -251,9 +251,7 @@ CHAR-LIMIT guidelines:
<message name="IDS_NOTIFICATION_CATEGORY_ANNOUNCEMENT" desc="Label for announcements notifications, within a list of notification categories. [CHAR-LIMIT=32]">
Announcements
</message>
- <message name="IDS_NOTIFICATION_CATEGORY_MEDIA_PLAYBACK" desc="Label for media playback notifications, within a list of notification categories. [CHAR-LIMIT=32]">
- Playing media
- </message>
+
<message name="IDS_NOTIFICATION_CATEGORY_PERMISSION_REQUESTS" desc="Label for permission requests, within a list of notification categories. [CHAR-LIMIT=32]">
Permission requests
</message>
@@ -426,6 +424,12 @@ CHAR-LIMIT guidelines:
<message name="IDS_AUTOFILL_CREDIT_CARD_EDITOR_NAME" desc="Label for text input field containing the name on a credit card. [CHAR-LIMIT=32]">
Name on card
</message>
+ <message name="IDS_AUTOFILL_CREDIT_CARD_EDITOR_NICKNAME" desc="Label for text input field containing the nickname on a credit card. [CHAR-LIMIT=25]">
+ Card nickname
+ </message>
+ <message name="IDS_AUTOFILL_CREDIT_CARD_EDITOR_INVALID_NICKNAME" desc="Label for text input field containing the nickname on a credit card. [CHAR-LIMIT=25]">
+ Nickname can’t include numbers
+ </message>
<message name="IDS_AUTOFILL_CARD_HOLDER_NAME" desc="Label for text input field containing the name on a credit card. [CHAR-LIMIT=32]">
Cardholder name
</message>
@@ -484,6 +488,12 @@ CHAR-LIMIT guidelines:
<message name="IDS_PASSWORDS_LEAK_DETECTION_SWITCH_SIGNED_OUT_ENABLE_DESCRIPTION" desc="Description for the switch toggling whether Chrome should check that entered credentials have been part of a leak. Displayed for users who are not signed in and syncing.">
When you sign in to your Google Account, this feature is turned on
</message>
+ <message name="IDS_PASSWORDS_CHECK_TITLE" desc="Title for the check passwords button which allows to check whether the user's passwords have been compromised.">
+ Check passwords
+ </message>
+ <message name="IDS_PASSWORDS_CHECK_DESCRIPTION" desc="Text explaining the benefits of checking the passwords, to be displayed under the Check Passwords button title.">
+ Keep your passwords safe from data breaches and other security issues
+ </message>
<message name="IDS_SECTION_SAVED_PASSWORDS_EXCEPTIONS" desc="Header for the list of websites for which user selected to never save passwords. [CHAR-LIMIT=32]">
Never saved
</message>
@@ -716,6 +726,45 @@ For example, some websites may respond to this request by showing you ads that a
<message name="IDS_CAN_MAKE_PAYMENT_TITLE" desc="Title for preference to allow websites to know whether you have payment methods available through PaymentRequest.CanMakePayment interface">
Access payment methods
</message>
+ <message name="IDS_SETTINGS_CUSTOM" desc="Label for a custom option in a dropdown menu.">
+ Custom
+ </message>
+ <message name="IDS_SETTINGS_SECURE_DNS_TITLE" desc="Title of the Secure DNS settings option">
+ Use secure DNS
+ </message>
+ <message name="IDS_SETTINGS_SECURE_DNS_DESCRIPTION" desc="Secondary, continued explanation of secure DNS in Privacy options">
+ Determines how to connect to websites over a secure connection
+ </message>
+ <message name="IDS_SETTINGS_AUTOMATIC_MODE_LABEL" desc="Text of the radio button that puts secure DNS in auto-upgrade mode">
+ Use your current service provider
+ </message>
+ <message name="IDS_SETTINGS_AUTOMATIC_MODE_DESCRIPTION" desc="Descriptive text that appears below IDS_SETTINGS_AUTOMATIC_MODE_LABEL.">
+ Secure DNS may not be available all the time
+ </message>
+ <message name="IDS_SETTINGS_AUTOMATIC_MODE_SUMMARY" desc="Short description of automatic mode">
+ Automatic
+ </message>
+ <message name="IDS_SETTINGS_SECURE_DROPDOWN_MODE_DESCRIPTION" desc="Text of the radio button that allows a secure resolver to be selected from a dropdown menu">
+ Choose another provider:
+ </message>
+ <message name="IDS_SETTINGS_SECURE_DROPDOWN_MODE_PRIVACY_POLICY" desc="Text that displays a link to the privacy policy of the resolver selected from a dropdown menu">
+ See this provider's <ph name="BEGIN_LINK">&lt;a target="_blank" href="$1<ex>https://google.com/</ex>"&gt;</ph>privacy policy<ph name="END_LINK">&lt;/a&gt;</ph>
+ </message>
+ <message name="IDS_SETTINGS_SECURE_DNS_DISABLED_FOR_MANAGED_ENVIRONMENT" desc="Substring of the secure DNS setting when secure DNS is disabled due to detection of a managed environment">
+ This setting is disabled on managed browsers
+ </message>
+ <message name="IDS_SETTINGS_SECURE_DNS_DISABLED_FOR_PARENTAL_CONTROL" desc="Substring of the secure DNS setting when secure DNS is disabled due to detection of OS-level parental controls">
+ This setting is disabled because parental controls are on
+ </message>
+ <message name="IDS_SETTINGS_SECURE_DNS_CUSTOM_PLACEHOLDER" desc="Placeholder text for a textbox where users can enter a custom secure DNS provider">
+ Provider URL
+ </message>
+ <message name="IDS_SETTINGS_SECURE_DNS_CUSTOM_FORMAT_ERROR" desc="Error text for an incorrectly formatted entry for the custom secure DNS provider">
+ Enter a correctly formatted URL
+ </message>
+ <message name="IDS_SETTINGS_SECURE_DNS_CUSTOM_CONNECTION_ERROR" desc="Error text for a custom secure DNS provider entry to which a probe connection fails">
+ Please verify that this is a valid provider or try again later
+ </message>
<message name="IDS_CLEAR_BROWSING_DATA_TITLE" desc="Title of the Clear Browsing Data screen. [CHAR-LIMIT=32]">
Clear browsing data
</message>
@@ -821,6 +870,50 @@ Your Google account may have other forms of browsing history like searches and a
<ph name="NUMBER_OF_ITEMS">%1$s<ex>3</ex></ph> items deleted
</message>
+ <!-- Safety check -->
+ <message name="IDS_PREFS_SAFETY_CHECK" desc="Title of the Safety check element in settings, allowing the user to check multiple areas of browser safety. [CHAR-LIMIT=32]">
+ Safety check
+ </message>
+ <message name="IDS_SAFETY_CHECK_DESCRIPTION" desc="Introduces the safety check categories to the user. Followed by several items, such as 'Safe Browsing', 'Updates', 'Passwords'.">
+ Chrome can check if your settings are protecting you from:
+ </message>
+ <message name="IDS_SAFETY_CHECK_SAFE_BROWSING_TITLE" desc="Title for the Safe Browsing section.">
+ Safe Browsing
+ </message>
+ <message name="IDS_SAFETY_CHECK_UPDATES_TITLE" desc="Title for the updates section.">
+ Updates
+ </message>
+ <message name="IDS_SAFETY_CHECK_PASSWORDS_TITLE" desc="Title for the passwords section.">
+ Passwords
+ </message>
+ <message name="IDS_SAFETY_CHECK_BUTTON" desc="Text for the button to start Safety check.">
+ Check now
+ </message>
+ <message name="IDS_SAFETY_CHECK_UNCHECKED" desc="A given element has not been checked.">
+ Unchecked
+ </message>
+ <message name="IDS_SAFETY_CHECK_CHECKING" desc="A given element is being checked.">
+ Checking
+ </message>
+ <message name="IDS_SAFETY_CHECK_ERROR" desc="A generic error state.">
+ An error occurred.
+ </message>
+ <message name="IDS_SAFETY_CHECK_SAFE_BROWSING_DISABLED" desc="Text to display when Safe Browsing is disabled.">
+ Safe Browsing is off. Chrome recommends turning it on.
+ </message>
+ <message name="IDS_SAFETY_CHECK_SAFE_BROWSING_ENABLED_STANDARD" desc="Text to display when Safe Browsing is set to standard protection.">
+ Standard Protection is on
+ </message>
+ <message name="IDS_SAFETY_CHECK_SAFE_BROWSING_ENABLED_ENHANCED" desc="Text to display when Safe Browsing is set to enhanced protection.">
+ Enhanced Protection is on
+ </message>
+ <message name="IDS_SAFETY_CHECK_SAFE_BROWSING_DISABLED_BY_ADMIN" desc="Text to display when Safe Browsing is disabled by admin.">
+ <ph name="BEGIN_LINK">&lt;a target="_blank" href="$1"&gt;</ph>Your administrator<ph name="END_LINK">&lt;/a&gt;</ph> has turned off Safe Browsing
+ </message>
+ <message name="IDS_SAFETY_CHECK_PASSWORDS_NO_PASSWORDS" desc="Text to display when no passwords are saved.">
+ No saved passwords. Chrome can check your passwords when you save them.
+ </message>
+
<!-- Accessibility preferences -->
<message name="IDS_PREFS_ACCESSIBILITY" desc="Title of Accessibility settings, which allows the user to change webpage font sizes. [CHAR-LIMIT=32]">
Accessibility
@@ -994,6 +1087,32 @@ Your Google account may have other forms of browsing history like searches and a
Chrome has saved you <ph name="gigabytes">%1$d<ex>10</ex></ph> GB
</message>
+ <!-- Download later -->
+ <message name="IDS_DOWNLOAD_LATER_DIALOG_TITLE" desc="Title of the download later dialog that let the user to choose the time to download.">
+ Choose when to download
+ </message>
+ <message name="IDS_DOWNLOAD_LATER_DIALOG_SUBTITLE" desc="Subtitle of the download later dialog that let the user to choose the time to download.">
+ You'll see a notification when this file is ready
+ </message>
+ <message name="IDS_DOWNLOAD_LATER_DOWNLOAD_NOW_TEXT" desc="The text for the radio button to trigger the download now in download later dialog.">
+ Now
+ </message>
+ <message name="IDS_DOWNLOAD_LATER_EDIT_LOCATION" desc="The text in the download later dialog that can be clicked to edit download location.">
+ Your file will be saved to <ph name="BEGIN_BOLD">&lt;b&gt;</ph><ph name="DIRECTORY">%1$s<ex>Downloads</ex></ph><ph name="END_BOLD">&lt;/b&gt;</ph>. <ph name="BEGIN_LINK2">&lt;LINK2&gt;</ph>Edit<ph name="END_LINK2">&lt;/LINK2&gt;</ph>.
+ </message>
+ <message name="IDS_DOWNLOAD_DATE_TIME_PICKER_NEXT_TEXT" desc="The text for the positive button of the download date time picker dialog.">
+ Next
+ </message>
+ <message name="IDS_DOWNLOAD_LATER_ON_WIFI_TEXT" desc="The text for the radio button to trigger the download on WIFI in download later dialog.">
+ On Wi-Fi
+ </message>
+ <message name="IDS_DOWNLOAD_LATER_PICK_TIME_TEXT" desc="The text for the radio button to select the download time in download later dialog.">
+ Pick date &amp; time
+ </message>
+ <message name="IDS_DOWNLOAD_LATER_PROMPT_ENABLED_TITLE" desc="A setting text to ask whether to show a dialog about when to download.">
+ Ask when to save files
+ </message>
+
<!-- Downloads location -->
<message name="IDS_DOWNLOADS_LOCATION_SELECTOR_TITLE" desc="Title of the preference that allows the user to select which of the folders they would like to make the default location to save their downloads.">
Download location
@@ -1008,7 +1127,7 @@ Your Google account may have other forms of browsing history like searches and a
Ask where to save files
</message>
<message name="IDS_DOWNLOAD_LOCATION_DIALOG_TITLE" desc="Title for the dialog that asks where the user wants to save the download file before the download begins.">
- Download file
+ Choose where to download
</message>
<message name="IDS_DOWNLOAD_LOCATION_DIALOG_CHECKBOX" desc="Label for the checkbox that allows the user to indicate if they do not want the download location selection dialog to appear every time they initiate a download.">
Don‘t show again
@@ -1487,9 +1606,6 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
</message>
<!-- InfoBar -->
- <message name="IDS_INFOBAR_CLOSE" desc="Accessibility label for the dismiss infobar Button">
- Close
- </message>
<message name="IDS_BOTTOM_BAR_SCREEN_POSITION" desc="Accessibility label to inform users about the InfoBar location">
Options available near bottom of the screen
</message>
@@ -1541,12 +1657,23 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
=1 {1 download pending.}
other {# downloads pending.}}
</message>
+ <message name="IDS_MULTIPLE_DOWNLOAD_SCHEDULED" desc="Label describing that one or more downloads are scheduled">
+ {FILE_COUNT, plural,
+ =1 {1 download scheduled.}
+ other {# downloads scheduled.}}
+ </message>
<message name="IDS_DOWNLOAD_INFOBAR_FILENAME" desc="Label showing the file name that just finished downloading">
<ph name="FILE_NAME">%1$s<ex>abc.png</ex></ph>.
</message>
<message name="IDS_DOWNLOAD_INFOBAR_ACCESSIBILITY_MESSAGE_WITH_LINK" desc="InfoBar accessibility text describing the link on the download progress infobar">
<ph name="MESSAGE">%1$s<ex>Downloading file (200 MB)</ex></ph> <ph name="LINK_NAME">%2$s<ex>Details</ex></ph> button
</message>
+ <message name="IDS_DOWNLOAD_SCHEDULED_ON_WIFI" desc="Label describing that the download was scheduled to start on Wi-Fi.">
+ Download will start on Wi-Fi.
+ </message>
+ <message name="IDS_DOWNLOAD_SCHEDULED_ON_DATE" desc="Label describing that the download was scheduled to start at a later date or time.">
+ Download will start on <ph name="date">%1$s<ex>Feb 28</ex></ph>.
+ </message>
<!-- Inline Update Infobar -->
<message name="IDS_INLINE_UPDATE_INFOBAR_READY_MESSAGE" desc="Text showing that the update process is almost ready.">
@@ -1629,9 +1756,6 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
<message name="IDS_MENU_SHARE_PAGE" desc="Menu item for sharing the current page. [CHAR-LIMIT=27]">
Share…
</message>
- <message name="IDS_SHARE_LINK_CHOOSER_TITLE" desc="title for the share dialog when sharing the current address [CHAR-LIMIT=27]">
- Share via
- </message>
<message name="IDS_ACCESSIBILITY_MENU_SHARE_VIA" desc="Content description share current page via the most recently used application menu item">
Share via <ph name="APPLICATION">%s<ex>Gmail</ex></ph>
</message>
@@ -1722,6 +1846,15 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
<message name="IDS_CONTEXTMENU_SEARCH_WITH_GOOGLE_LENS" desc="Context sensitive menu item for deep linking into google lens. [CHAR-LIMIT=30]">
Search with Google Lens <ph name="BEGIN_NEW">&lt;new&gt;</ph>New<ph name="END_NEW">&lt;/new&gt;</ph>
</message>
+ <message name="IDS_CONTEXTMENU_SHOP_SIMILAR_PRODUCTS" desc="Context sensitive menu item for deep linking into google lens for shopping results. [CHAR-LIMIT=30]">
+ Shop similar products <ph name="BEGIN_NEW">&lt;new&gt;</ph>New<ph name="END_NEW">&lt;/new&gt;</ph>
+ </message>
+ <message name="IDS_CONTEXTMENU_SHOP_IMAGE_WITH_GOOGLE_LENS" desc="Context sensitive menu item for deep linking into google lens for shopping results. [CHAR-LIMIT=30]">
+ Shop image with Google Lens <ph name="BEGIN_NEW">&lt;new&gt;</ph>New<ph name="END_NEW">&lt;/new&gt;</ph>
+ </message>
+ <message name="IDS_CONTEXTMENU_SEARCH_SIMILAR_PRODUCTS" desc="Context sensitive menu item for deep linking into google lens for shopping results. [CHAR-LIMIT=30]">
+ Search similar products <ph name="BEGIN_NEW">&lt;new&gt;</ph>New<ph name="END_NEW">&lt;/new&gt;</ph>
+ </message>
<message name="IDS_CONTEXTMENU_SEARCH_WEB_FOR_IMAGE" desc="Context sensitive menu item for search-for-Image command in a new tab. [CHAR-LIMIT=30]">
Search <ph name="SEARCH_ENGINE">%1$s<ex>Google</ex></ph> for this image
</message>
@@ -1743,8 +1876,8 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
<message name="IDS_CONTEXTMENU_OPEN_IN_EPHEMERAL_TAB" desc="Context-sensitive menu item to open a quick preview of the selected linked page. Note that 'preview' is a verb, not a noun. We're also labeling it *New* to draw attention to it when first released. The selected link will open in an overlay panel on top of the current tab which will go away easily too. [CHAR-LIMIT=30]">
Preview page <ph name="BEGIN_NEW">&lt;new&gt;</ph>New<ph name="END_NEW">&lt;/new&gt;</ph>
</message>
- <message name="IDS_CONTEXTMENU_PERFORMANCE_INFO_FAST" desc="This string is shown in the context sensitive menu for links and is shown underneath the link URL. It indicates to the user that the link's target website should load quickly. [CHAR-LIMIT=30]">
- Fast site
+ <message name="IDS_CONTEXTMENU_PERFORMANCE_INFO_FAST" desc="This string is shown in the context sensitive menu for links and is shown underneath the link URL. It indicates to the user that the link's target page is fast-loading and responsive. [CHAR-LIMIT=30]">
+ Fast page
</message>
<!-- Swipe refresh -->
@@ -2058,7 +2191,10 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
<ph name="FILE_SIZE_OF_TOTAL">%1$s<ex>1.56 MB / 10MB</ex></ph> <ph name="SEPARATOR">•</ph> <ph name="DESCRIPTION">%2$s<ex>failed</ex></ph>
</message>
<message name="IDS_DOWNLOAD_MANAGER_JUST_NOW" desc="Text on a label describing that the associated download event happened just now.">
- Just Now
+ Just now
+ </message>
+ <message name="IDS_DOWNLOAD_MANAGER_SCHEDULED_LATER" desc="Text on a label describing that the associated download is scheduled to start later.">
+ Scheduled for later
</message>
<message name="IDS_DOWNLOAD_MANAGER_OFFLINE_HOME" desc="The title text on download home indicating that we are in offline mode.">
Offline Home
@@ -2189,25 +2325,27 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
<message name="IDS_SIGNIN_PROMO_CHOOSE_ANOTHER_ACCOUNT" desc="Button that the user can press if they want to select a different account before signing in. This button is shown below 'Continue as Joe Doe' button that signs user in with default account.">
Choose another account
</message>
-
- <!-- Messages for remote media playback (casting) -->
- <message name="IDS_ACCESSIBILITY_PLAY" desc="The play button that starts playing the media.">
- Play
+ <message name="IDS_SIGNIN_PROMO_STATUS_MESSAGE" desc="Title string for 'Turn on sync' sync promos.">
+ Sync is off
</message>
- <message name="IDS_ACCESSIBILITY_PAUSE" desc="The pause button that pauses playing the media.">
- Pause
+ <message name="IDS_SYNC_PROMO_TURN_ON_SYNC" desc="Button that the user can press if they want to turn on sync with this account.">
+ Turn on sync
</message>
- <message name="IDS_ACCESSIBILITY_PREVIOUS_TRACK" desc="The previous track button that switches media to the previous track.">
- Previous track
+
+ <message name="IDS_EXTERNAL_APP_LEAVE_INCOGNITO_WARNING" desc="Alert dialog text warning the user (who is currently in incognito mode) that the site they are currently using is going to share data with an external application." formatter_data="android_java">
+ This site is about to share information with an app outside of incognito mode.
</message>
- <message name="IDS_ACCESSIBILITY_NEXT_TRACK" desc="The next track button that switches media to the next track.">
- Next track
+ <message name="IDS_EXTERNAL_APP_LEAVE_INCOGNITO_WARNING_TITLE" desc="Title for dialog asking if the user wants to leave incognito mode. [CHAR-LIMIT=32]" formatter_data="android_java">
+ Leave incognito mode?
</message>
- <message name="IDS_ACCESSIBILITY_SEEK_FORWARD" desc="The seek forward button that seeks media to a later position.">
- Seek forward
+ <message name="IDS_EXTERNAL_APP_LEAVE_INCOGNITO_STAY" desc="Label for the dialog button to stay in incognito mode. [CHAR-LIMIT=20]" formatter_data="android_java">
+ Stay
</message>
- <message name="IDS_ACCESSIBILITY_SEEK_BACKWARD" desc="The seek backward button that seeks media to an earlier position.">
- Seek backward
+ <message name="IDS_EXTERNAL_APP_LEAVE_INCOGNITO_LEAVE" desc="Label for the dialog button to leave incognito mode. [CHAR-LIMIT=20]" formatter_data="android_java">
+ Leave
+ </message>
+ <message name="IDS_EXTERNAL_APP_RESTRICTED_ACCESS_ERROR" desc="A message shown to the user if Chrome receives a file view request to something Chrome does not have access to view." formatter_data="android_java">
+ Chrome does not have access to the requested resource.
</message>
<!-- New Tab Page strings -->
@@ -2731,6 +2869,9 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
<message name="IDS_ACCESSIBILITY_OMNIBOX_BTN_REFINE" desc="Content description for the omnibox refine button.">
Refine
</message>
+ <message name="IDS_ACCESSIBILITY_OMNIBOX_SWITCH_TO_TAB" desc="Content description for the omnibox switch to tab button.">
+ Switch To Tab
+ </message>
<message name="IDS_ACCESSIBILITY_SHARE_SELECTED_ITEMS" desc="Content description for the button to share selected items. [ICU Syntax]">
@@ -2754,10 +2895,6 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
Tabs
</message>
- <message name="IDS_MEDIA_NOTIFICATION_INCOGNITO" desc="Text used as a placeholder for a media notification about playing media, when notification is shown from incognito tab.">
- A site is playing media
- </message>
-
<!-- Contextual Search -->
<message name="IDS_CONTEXTUAL_SEARCH_NETWORK_UNAVAILABLE" desc="Tells the user the network is not accessible.">
Unable to access the network
@@ -2798,6 +2935,12 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
<message name="IDS_CONTEXTUAL_SEARCH_IPH_TAP" desc="An in-product-help message for encouraging users to tap instead of long pressing to trigger the Tap to Search feature.">
You can also search with a quick tap on a word
</message>
+ <message name="IDS_CONTEXTUAL_SEARCH_IPH_TOUCH_AND_HOLD" desc="An in-product-help message for encouraging users to use a touch and hold gesture to trigger the Touch to Search feature.">
+ To search, touch &amp; hold a word
+ </message>
+ <message name="IDS_CONTEXTUAL_SEARCH_IPH_TOUCH_AND_HOLD_ENGAGED" desc="An in-product-help message for encouraging engaged users to use a touch and hold gesture to trigger the Touch to Search feature.">
+ To search, touch &amp; hold a word instead of tapping it
+ </message>
<!-- Web apps -->
<message name="IDS_WEBAPP_ACTIVITY_TITLE" desc="Title in recent tasks list for web apps, i.e. web pages that are shown in a separate window">
@@ -2877,6 +3020,20 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
Preview tab is closed
</message>
+ <!-- Feed Card Menu -->
+ <message name="IDS_FEED_CARD_MENU_DESCRIPTION" desc="The content description of the feed card menu bottom sheet.">
+ Feed card menu
+ </message>
+ <message name="IDS_FEED_CARD_MENU_OPENED_HALF" desc="Accessibility string read when the feed card menu bottom sheet is opened at half height. This should never happen, no need to translate.">
+ Feed card menu half height
+ </message>
+ <message name="IDS_FEED_CARD_MENU_OPENED_FULL" desc="Accessibility string read when the feed card menu bottom sheet is opened at full height. The sheet will occupy up to the full screen.">
+ Feed card menu is opened
+ </message>
+ <message name="IDS_FEED_CARD_MENU_CLOSED" desc="Accessibility string read when the feed card menu bottom sheet is closed.">
+ Feed card menu is closed
+ </message>
+
<!-- Storage Preference UI strings for clearing storage. -->
<message name="IDS_STORAGE_MANAGEMENT_ACTIVITY_LABEL" desc="Title for Chrome's Manage Space Activity.">
Google <ph name="APP_NAME">%1$s<ex>Chrome</ex></ph> storage
@@ -2921,14 +3078,6 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
All Chrome’s app data will be deleted permanently. This includes all files, settings, accounts, databases, etc.
</message>
- <!-- Client certificate selection failure strings. -->
- <message name="IDS_CLIENT_CERT_UNSUPPORTED_TITLE" desc="Title of a dialog box for when the operating system does not support client SSL certificate selection">
- Unable to select certificate.
- </message>
- <message name="IDS_CLIENT_CERT_UNSUPPORTED_MESSAGE" desc="The message in a dialog box for when the operating system does not support client SSL certificate selection">
- Client side certificate selection is not supported by the operating system.
- </message>
-
<!-- WebUsb Picker UI strings -->
<message name="IDS_USB_CHOOSER_DIALOG_PROMPT" desc="The text that is used to introduce the USB chooser dialog to the user.">
<ph name="SITE">%1$s<ex>https://www.google.com</ex></ph> wants to connect
@@ -3002,6 +3151,12 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
<message name="IDS_ACCESSIBILITY_UNMUTE_VIDEO" desc="The accessibility string for the unmute video button.">
Unmute video
</message>
+ <message name="IDS_ACCESSIBILITY_FULL_SCREEN" desc="The accessibility string for the full screen video button.">
+ Full screen
+ </message>
+ <message name="IDS_ACCESSIBILITY_EXIT_FULL_SCREEN" desc="The accessibility string for the exiting of full screen video button.">
+ Exit full screen
+ </message>
<message name="IDS_ACCESSIBILITY_VIDEO_PLAYER" desc="The accessibility string for the video player.">
Video player
</message>
@@ -3161,10 +3316,6 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
Reopen Chrome.
</message>
- <if expr="enable_vr">
- <part file="xr_consent_ui_strings_java.grdp" />
- </if>
-
<if expr="enable_arcore">
<!-- ARCore check infobar -->
<message name="IDS_AR_CORE_CHECK_INFOBAR_INSTALL_TEXT" desc="Text to be displayed in the ARCore check infobar. When a WebXR page is loaded, if ARCore is needed to display AR content and it is not installed, an infobar will be shown to the user prompting them to install ARCore.">
@@ -3178,19 +3329,6 @@ To change this setting, <ph name="BEGIN_LINK">&lt;resetlink&gt;</ph>reset sync<p
<message name="IDS_AR_MODULE_TITLE" desc="Text shown when the AR module is referenced in install start, success, failure UI (e.g. in IDS_MODULE_INSTALL_START_TEXT, which will expand to 'Installing Augmented Reality for Chrome…').">
Augmented Reality
</message>
- <message name="IDS_AR_IMMERSIVE_MODE_CONSENT_TITLE" desc="Title for dialog shown when a site requests consent for starting an augmented reality session.">
- Enter AR from <ph name="DOMAIN">%s<ex>example.com</ex></ph>?
- </message>
- <message name="IDS_AR_IMMERSIVE_MODE_CONSENT_MESSAGE" desc="Message for dialog shown when a site requests consent for starting an augmented reality session.">
- While you're in AR, this site may be able to:
-• create a 3D map of your environment
-• track camera motion
-
-Only you can see what your camera is looking at. The site can't see your camera's images.
- </message>
- <message name="IDS_AR_IMMERSIVE_MODE_CONSENT_BUTTON" desc="Confirm button for dialog shown when a site requests consent for starting an augmented reality session.">
- Enter AR
- </message>
<!-- App upgrade from Play Store -->
<message name="IDS_UPDATE_FROM_MARKET" desc="Title of button that will direct the user to update an app from the market (Play Store)">
@@ -3233,6 +3371,9 @@ Only you can see what your camera is looking at. The site can't see your camera'
<message name="IDS_IPH_DOWNLOAD_HOME_ACCESSIBILITY_TEXT" desc="The in-product-help accessibility text to open download home after a restart.">
Find your files and pages in Downloads from the More Options button
</message>
+ <message name="IDS_IPH_DOWNLOAD_INDICATOR_TEXT" desc="The in-product-help message to open download home, which is shown alongside the offline indicator when the device goes offline.">
+ See your offline files
+ </message>
<message name="IDS_IPH_DATA_SAVER_DETAIL_TEXT" desc="The in-product-help message to open lite mode.">
See how much data you've saved
</message>
@@ -3283,11 +3424,6 @@ Only you can see what your camera is looking at. The site can't see your camera'
Remove and recreate this shortcut
</message>
- <!-- BottomSheet -->
- <message name="IDS_BOTTOM_SHEET_ACCESSIBILITY_DESCRIPTION" desc="Accessibility string read when the bottom sheet is focused informing the user that the sheet can be closed by swiping down.">
- Swipe down to close.
- </message>
-
<!-- SendTabToSelf -->
<message name="IDS_SEND_TAB_TO_SELF_TOAST" desc="Text for a toast indicating that the tab is being shared on the user's other synced devices.">
Sending to <ph name="device_name">%1$s<ex>Tanya's Pixel 2</ex></ph>...
@@ -3570,6 +3706,16 @@ Only you can see what your camera is looking at. The site can't see your camera'
Download
</message>
+ <message name="IDS_QR_CODE_ERROR_TOO_LONG"
+ desc="Error message displayed when a URL exceeds the limit for which we can generate a QR code.">
+ Can't create QR code. URL is more than <ph name="CHARACTER_LIMIT">%1$d<ex>300</ex></ph> characters.
+ </message>
+
+ <message name="IDS_QR_CODE_ERROR_UNKNOWN"
+ desc="Error message displayed when an unknown error occurs.">
+ Can't create QR code
+ </message>
+
<!-- Sharing Hub -->
<message name="IDS_SHARING_MORE_ICON_LABEL" desc="Icon label for the More button in the sharing hub.">
More
@@ -3579,6 +3725,10 @@ Only you can see what your camera is looking at. The site can't see your camera'
Copy link
</message>
+ <message name="IDS_SHARING_COPY_TEXT" desc="Label for the Copy Text button in the sharing hub.">
+ Copy text
+ </message>
+
<message name="IDS_SHARING_SCREENSHOT" desc="Label for Screenshot button in the sharing hub.">
Screenshot
</message>
@@ -3587,6 +3737,10 @@ Only you can see what your camera is looking at. The site can't see your camera'
Link Copied
</message>
+ <message name="IDS_TEXT_COPIED" desc="Text shown in the toast notification when Copy Text is selected in the sharing hub.">
+ Text Copied
+ </message>
+
<message name="IDS_QR_CODE_CAMERA_FRAMING_RECT_DESCRIPTION" desc="Text under the framing rectangle in QR code camera preview.">
Position QR/barcode in this frame.
</message>
@@ -3631,21 +3785,27 @@ Only you can see what your camera is looking at. The site can't see your camera'
chrome_qrcode_<ph name="CURRENT_TIMESTAMP_MS">%1$s<ex>1582667748515</ex></ph>
</message>
- <message name="IDS_QR_CODE_SUCCESSFUL_DOWNLOAD_TITLE" desc="Notification title for successful QR code download.">
- QR code downloaded
+ <!-- Share Screenshot strings -->
+ <message name="IDS_SCREENSHOT_EDIT_TITLE" desc="The text shown on the share option for screenshots.">
+ Edit
</message>
- <message name="IDS_QR_CODE_SUCCESSFUL_DOWNLOAD_TEXT" desc="Notification text for successful QR code download.">
- Tap to open QR code
+ <message name="IDS_SCREENSHOT_DELETE_TITLE" desc="The text shown on the delete option for screenshots.">
+ Delete
</message>
- <message name="IDS_QR_CODE_FAILED_DOWNLOAD_TITLE" desc="Notification title for failed QR code download.">
- Can't download QR code
+ <message name="IDS_SCREENSHOT_SAVE_TITLE" desc="The text shown on the save option for screenshots.">
+ Save
+ </message>
+
+ <message name="IDS_SCREENSHOT_SHARE_TITLE" desc="The text shown on the share option for screenshots.">
+ Share
</message>
- <message name="IDS_QR_CODE_FAILED_DOWNLOAD_TEXT" desc="Notification text for failed QR code download.">
- Something went wrong
+ <message name="IDS_SCREENSHOT_FILENAME_PREFIX" desc="File name prefix for downloaded screenshot that is followed by timestamp.">
+ chrome_screenshot_<ph name="CURRENT_TIMESTAMP_MS">%1$s<ex>1582667748515</ex></ph>
</message>
+
<!-- Chime DFM module strings -->
<message name="IDS_CHIME_MODULE_TITLE" desc="Text shown when the chime module is referenced in install start, success, failure UI (e.g. in IDS_MODULE_INSTALL_START_TEXT, which will expand to 'Installing Google Notifications Platform for Chrome…').">
Google Notifications Platform
@@ -3673,6 +3833,39 @@ Only you can see what your camera is looking at. The site can't see your camera'
Paint Preview playback failed.
</message>
+ <!-- Default Browser Promo Strings-->
+ <message name="IDS_DEFAULT_BROWSER_PROMO_DIALOG_TITLE" desc="Title of the default browser promo dialog">
+ Set <ph name="APP_NAME">%1$s<ex>Chrome</ex></ph> as your default?
+ </message>
+ <message name="IDS_DEFAULT_BROWSER_PROMO_DIALOG_DESC" desc="Description in the default browser promo dialog, which is concatenated with one of the following steps strings">
+ <ph name="APP_NAME">%1$s<ex>Chrome</ex></ph> has the smarts and speed you need to safely do, create, and explore online
+ </message>
+ <message name="IDS_DEFAULT_BROWSER_PROMO_DIALOG_DISAMBIGUATION_SHEET_STEPS" desc="Description of the steps to set the default browser throught disambiguation sheet. 'Always' should match TC ID 5575222334666843269.">
+ 1. Choose <ph name="APP_NAME">%1$s<ex>Chrome</ex></ph>\n2. Tap “Always”
+ </message>
+ <message name="IDS_DEFAULT_BROWSER_PROMO_DIALOG_SYSTEM_SETTINGS_STEPS"
+ desc="Description of the steps to set the default browser throught system settings.
+ 'Go to Settings' should match TC ID 4431460803004659888. 'Browser App' should match TC ID 6222206565850006894.">
+ 1. Go to Settings\n2. Tap “Browser App”\n3. Choose <ph name="APP_NAME">%1$s<ex>Chrome</ex></ph>
+ </message>
+ <message name="IDS_DEFAULT_BROWSER_PROMO_DIALOG_ROLE_MANAGER_STEPS" desc="Description of the steps to set the default browser throught role manager. 'Set as default' should match TC ID 5706081295230541240.">
+ 1. Choose <ph name="APP_NAME">%1$s<ex>Chrome</ex></ph>\n2. Tap “Set as default”
+ </message>
+ <message name="IDS_DEFAULT_BROWSER_PROMO_DIALOG_CHOOSE_CHROME_BUTTON" desc="A button in the default browser promo dialog to choose chrome as default">
+ Choose <ph name="APP_NAME">%1$s<ex>Chrome</ex></ph>
+ </message>
+ <message name="IDS_DEFAULT_BROWSER_PROMO_DIALOG_GO_TO_SETTINGS_BUTTON" desc="A button in the default browser promo to navigate users to systen settings. 'Go to Settings' should match TC ID 4431460803004659888.">
+ Go to Settings
+ </message>
+
+ <!-- HTTPS image compression InfoBar -->
+ <message name="IDS_LITE_MODE_HTTPS_IMAGE_COMPRESSION_MESSAGE" desc="The text of the infobar notifying the user that Chrome's Lite mode will now also compresses HTTPS images.">
+ Lite mode now saves you more data by optimizing images on HTTPS pages.
+ </message>
+ <message name="IDS_LITE_MODE_HTTPS_IMAGE_COMPRESSION_SETTINGS_LINK" desc="This link opens the Lite Mode settings page to explain the feature and configure the settings.">
+ Manage
+ </message>
+
<!-- Browser Promo Notification Strings -->
<message name="IDS_CHROME_REENGAGEMENT_NOTIFICATION_1_TITLE" desc="The title of a notification shown to suggest that users use Chrome. Users probably have not opened Chrome in a while. Promotes relevant articles Chrome has.">
Read today's news <ph name="NEWS_ICON">📰</ph>
diff --git a/chromium/chrome/browser/ui/android/strings/xr_consent_ui_strings_java.grdp b/chromium/chrome/browser/ui/android/strings/xr_consent_ui_strings_java.grdp
deleted file mode 100644
index 5ff87217358..00000000000
--- a/chromium/chrome/browser/ui/android/strings/xr_consent_ui_strings_java.grdp
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-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.
--->
-<!-- XR specific strings (included from generated_resources.grd and android_chrome_strings.grd). -->
-<!-- These strings are used in the consent flow dialog. -->
-<grit-part>
- <!-- XR consent dialog. -->
- <message name="IDS_XR_CONSENT_DIALOG_TITLE" desc="Title of the user consent dialog displayed before allowing a website to start a VR presentation">
- Enter VR from <ph name="DOMAIN">%s<ex>example.com</ex></ph>?
- </message>
- <message name="IDS_XR_CONSENT_DIALOG_DESCRIPTION_DEFAULT" desc="This is the header for a bulleted list of potential concerns that we want to ensure the user is aware of before entering VR. This header and the appended items of the bulleted list make up the body of the user consent dialog displayed before a website may start a VR presentation.">
- While you're in VR, this site may be able to learn about:
- </message>
- <message name="IDS_XR_CONSENT_BULLET" desc="Unicode bullet for list items. Similar to IDS_LIST_BULLET from desktop generated_resources">
- • <ph name="LIST_ITEM_TEXT">%s<ex>the layout of your room</ex></ph>
- </message>
- <message name="IDS_XR_CONSENT_DIALOG_DESCRIPTION_PHYSICAL_FEATURES" desc="Item for the bulleted list of potential concerns in the consent dialog indicating that physical features may be exposed.">
- your physical features, such as height
- </message>
- <message name="IDS_XR_CONSENT_DIALOG_DESCRIPTION_FLOOR_PLAN" desc="Item for the bulleted list of potential concerns in the consent dialog indicating that phyiscal features may be exposed.">
- the layout of your room
- </message>
- <message name="IDS_XR_CONSENT_DIALOG_BUTTON_ALLOW_AND_ENTER_VR" desc="Text on the button of a user consent dialog which allows a website to start a VR presentation">
- Enter VR
- </message>
-</grit-part>
diff --git a/chromium/chrome/browser/ui/ash/assistant/test_support/BUILD.gn b/chromium/chrome/browser/ui/ash/assistant/test_support/BUILD.gn
new file mode 100644
index 00000000000..db1dc372fbe
--- /dev/null
+++ b/chromium/chrome/browser/ui/ash/assistant/test_support/BUILD.gn
@@ -0,0 +1,17 @@
+static_library("test_support") {
+ testonly = true
+
+ sources = [
+ "fake_s3_server.cc",
+ "fake_s3_server.h",
+ "test_util.h",
+ ]
+
+ deps = [
+ "//chromeos/assistant/internal:internal",
+ "//chromeos/services/assistant:lib",
+ "//testing/gmock",
+ "//testing/gtest",
+ "//ui/views:views",
+ ]
+}
diff --git a/chromium/chrome/browser/ui/messages/android/BUILD.gn b/chromium/chrome/browser/ui/messages/android/BUILD.gn
index 44070c13f12..b33d32b618c 100644
--- a/chromium/chrome/browser/ui/messages/android/BUILD.gn
+++ b/chromium/chrome/browser/ui/messages/android/BUILD.gn
@@ -7,32 +7,16 @@ android_resources("java_resources") {
custom_package = "org.chromium.chrome.ui.messages"
sources = [
- "java/res/drawable-hdpi/infobar_shadow_left.9.png",
- "java/res/drawable-hdpi/infobar_shadow_top.png",
- "java/res/drawable-mdpi/infobar_shadow_left.9.png",
- "java/res/drawable-mdpi/infobar_shadow_top.png",
- "java/res/drawable-xhdpi/infobar_shadow_left.9.png",
- "java/res/drawable-xhdpi/infobar_shadow_top.png",
- "java/res/drawable-xxhdpi/infobar_shadow_left.9.png",
- "java/res/drawable-xxhdpi/infobar_shadow_top.png",
- "java/res/drawable-xxxhdpi/infobar_shadow_left.9.png",
- "java/res/drawable-xxxhdpi/infobar_shadow_top.png",
"java/res/drawable/snackbar_background_tablet.xml",
- "java/res/layout/infobar_control_icon_with_description.xml",
- "java/res/layout/infobar_control_message.xml",
- "java/res/layout/infobar_control_spinner.xml",
- "java/res/layout/infobar_control_spinner_drop_down.xml",
- "java/res/layout/infobar_control_spinner_view.xml",
- "java/res/layout/infobar_control_toggle.xml",
"java/res/layout/snackbar.xml",
"java/res/values/dimens.xml",
- "java/res/values/ids.xml",
]
deps = [
"//chrome/browser/ui/android/strings:ui_strings_grd",
"//components/browser_ui/strings/android:browser_ui_strings_grd",
"//components/browser_ui/widget/android:java_resources",
+ "//components/infobars/android:java_resources",
"//ui/android:ui_java_resources",
]
}
@@ -42,10 +26,6 @@ android_library("java") {
"java/src/org/chromium/chrome/browser/ui/messages/infobar/ConfirmInfoBar.java",
"java/src/org/chromium/chrome/browser/ui/messages/infobar/InfoBar.java",
"java/src/org/chromium/chrome/browser/ui/messages/infobar/InfoBarCompactLayout.java",
- "java/src/org/chromium/chrome/browser/ui/messages/infobar/InfoBarControlLayout.java",
- "java/src/org/chromium/chrome/browser/ui/messages/infobar/InfoBarInteractionHandler.java",
- "java/src/org/chromium/chrome/browser/ui/messages/infobar/InfoBarLayout.java",
- "java/src/org/chromium/chrome/browser/ui/messages/infobar/InfoBarMessageView.java",
"java/src/org/chromium/chrome/browser/ui/messages/infobar/InfoBarUiItem.java",
"java/src/org/chromium/chrome/browser/ui/messages/infobar/SimpleConfirmInfoBarBuilder.java",
"java/src/org/chromium/chrome/browser/ui/messages/snackbar/Snackbar.java",
@@ -62,9 +42,11 @@ android_library("java") {
"//chrome/browser/util:java",
"//components/browser_ui/styles/android:java_resources",
"//components/browser_ui/widget/android:java",
+ "//components/infobars/android:java",
"//components/infobars/core:infobar_enums_java",
"//third_party/android_deps:androidx_annotation_annotation_java",
"//third_party/android_deps:androidx_appcompat_appcompat_java",
+ "//third_party/android_deps:androidx_appcompat_appcompat_resources_java",
"//ui/android:ui_full_java",
"//ui/android:ui_utils_java",
]
@@ -99,10 +81,7 @@ java_library("junit") {
android_library("javatests") {
testonly = true
- sources = [
- "java/src/org/chromium/chrome/browser/ui/messages/infobar/InfoBarControlLayoutTest.java",
- "java/src/org/chromium/chrome/browser/ui/messages/snackbar/SnackbarTest.java",
- ]
+ sources = [ "java/src/org/chromium/chrome/browser/ui/messages/snackbar/SnackbarTest.java" ]
deps = [
":java",
diff --git a/chromium/chrome/browser/ui/webui/DEPS b/chromium/chrome/browser/ui/webui/DEPS
index fcf6dcdf5a4..6a321049a58 100644
--- a/chromium/chrome/browser/ui/webui/DEPS
+++ b/chromium/chrome/browser/ui/webui/DEPS
@@ -1,5 +1,5 @@
include_rules = [
- "+chrome/services/app_service/public",
+ "+components/services/app_service/public",
"+device/bluetooth",
"+extensions/strings/grit/extensions_strings.h",
@@ -11,3 +11,10 @@ include_rules = [
"+third_party/brotli", # For compressed resources.
"+third_party/zlib/zlib.h", # For compression level constants.
]
+
+specific_include_rules = {
+ "chrome_webui_navigation_browsertest.cc": [
+ "+content/browser/frame_host/render_frame_host_impl.h",
+ "+content/common/frame.mojom.h",
+ ],
+} \ No newline at end of file
diff --git a/chromium/chrome/browser/ui/webui/about_ui.cc b/chromium/chrome/browser/ui/webui/about_ui.cc
index 2bda9c07e29..a4fe8c0e5aa 100644
--- a/chromium/chrome/browser/ui/webui/about_ui.cc
+++ b/chromium/chrome/browser/ui/webui/about_ui.cc
@@ -440,7 +440,7 @@ class CrostiniCreditsHandler
auto component_manager =
g_browser_process->platform_part()->cros_component_manager();
if (!component_manager) {
- LoadCredits(base::FilePath(chrome::kLinuxCreditsPath));
+ RespondWithPlaceholder();
return;
}
component_manager->Load(
@@ -461,8 +461,8 @@ class CrostiniCreditsHandler
void LoadCrostiniCreditsFileAsync(base::FilePath credits_file_path) {
if (!base::ReadFileToString(credits_file_path, &contents_)) {
- // File with credits not found, ResponseOnUIThread will load credits
- // from resources if contents_ is empty.
+ // File with credits not found, ResponseOnUIThread will load a placeholder
+ // if contents_ is empty.
contents_.clear();
}
}
@@ -473,18 +473,19 @@ class CrostiniCreditsHandler
LoadCredits(path.Append(kTerminaCreditsPath));
return;
}
- LoadCredits(base::FilePath(chrome::kLinuxCreditsPath));
+ RespondWithPlaceholder();
+ }
+
+ void RespondWithPlaceholder() {
+ contents_.clear();
+ ResponseOnUIThread();
}
void ResponseOnUIThread() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
- // If we fail to load Linux credits from disk, load the placeholder from
- // resources.
- // TODO(rjwright): Add a linux-specific placeholder in resources.
+ // If we fail to load Linux credits from disk, use the placeholder.
if (contents_.empty() && path_ != kKeyboardUtilsPath) {
- contents_ =
- ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
- IDR_OS_CREDITS_HTML);
+ contents_ = l10n_util::GetStringUTF8(IDS_CROSTINI_CREDITS_PLACEHOLDER);
}
std::move(callback_).Run(base::RefCountedString::TakeString(&contents_));
}
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 a6b2b88ee09..1fcf042bf88 100644
--- a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc
+++ b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.cc
@@ -28,6 +28,7 @@
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "extensions/browser/extension_system.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
@@ -137,18 +138,21 @@ bool AppLauncherPageUI::HTMLSource::AllowCaching() {
return false;
}
-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() {
- return "style-src 'self' chrome://resources chrome://theme 'unsafe-inline';";
-}
+std::string AppLauncherPageUI::HTMLSource::GetContentSecurityPolicy(
+ network::mojom::CSPDirectiveName directive) {
+ if (directive == network::mojom::CSPDirectiveName::ScriptSrc) {
+ // 'unsafe-inline' is added to script-src.
+ return "script-src chrome://resources 'self' 'unsafe-eval' "
+ "'unsafe-inline';";
+ } else if (directive == network::mojom::CSPDirectiveName::StyleSrc) {
+ return "style-src 'self' chrome://resources chrome://theme "
+ "'unsafe-inline';";
+ } else if (directive == network::mojom::CSPDirectiveName::ImgSrc) {
+ return "img-src chrome://extension-icon chrome://app-icon chrome://theme "
+ "chrome://resources data:;";
+ }
-std::string AppLauncherPageUI::HTMLSource::GetContentSecurityPolicyImgSrc() {
- return "img-src chrome://extension-icon chrome://app-icon chrome://theme "
- "chrome://resources data:;";
+ return content::URLDataSource::GetContentSecurityPolicy(directive);
}
AppLauncherPageUI::HTMLSource::~HTMLSource() = default;
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 280e6003845..070ba242b3c 100644
--- a/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h
+++ b/chromium/chrome/browser/ui/webui/app_launcher_page_ui.h
@@ -45,9 +45,8 @@ class AppLauncherPageUI : public content::WebUIController {
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;
+ std::string GetContentSecurityPolicy(
+ network::mojom::CSPDirectiveName directive) override;
private:
diff --git a/chromium/chrome/browser/ui/webui/app_management/BUILD.gn b/chromium/chrome/browser/ui/webui/app_management/BUILD.gn
index 6db2265d29e..d96d406038e 100644
--- a/chromium/chrome/browser/ui/webui/app_management/BUILD.gn
+++ b/chromium/chrome/browser/ui/webui/app_management/BUILD.gn
@@ -7,5 +7,5 @@ import("//mojo/public/tools/bindings/mojom.gni")
mojom("mojo_bindings") {
sources = [ "app_management.mojom" ]
- public_deps = [ "//chrome/services/app_service/public/mojom" ]
+ public_deps = [ "//components/services/app_service/public/mojom" ]
}
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 dce93502f75..c8b279f43f6 100644
--- a/chromium/chrome/browser/ui/webui/app_management/app_management.mojom
+++ b/chromium/chrome/browser/ui/webui/app_management/app_management.mojom
@@ -4,7 +4,7 @@
module app_management.mojom;
-import "chrome/services/app_service/public/mojom/types.mojom";
+import "components/services/app_service/public/mojom/types.mojom";
struct App {
string id;
@@ -87,4 +87,6 @@ enum PwaPermissionType {
// The Plugin VM app publisher uses this enum directly.
enum PluginVmPermissionType {
PRINTING = 0,
+ CAMERA = 1,
+ MICROPHONE = 2,
};
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 5c0641f3604..70124e8868f 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
@@ -15,8 +15,8 @@
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/app_management/app_management.mojom.h"
-#include "chrome/services/app_service/public/cpp/app_registry_cache.h"
-#include "chrome/services/app_service/public/mojom/types.mojom.h"
+#include "components/services/app_service/public/cpp/app_registry_cache.h"
+#include "components/services/app_service/public/mojom/types.mojom.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
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 039c18af90e..cd94f678a88 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
@@ -9,7 +9,7 @@
#include "base/scoped_observer.h"
#include "chrome/browser/ui/webui/app_management/app_management.mojom-forward.h"
#include "chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.h"
-#include "chrome/services/app_service/public/cpp/app_registry_cache.h"
+#include "components/services/app_service/public/cpp/app_registry_cache.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
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 5ea8f88ffef..7df9ca2b444 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
@@ -10,7 +10,7 @@
#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"
+#include "components/services/app_service/public/mojom/types.mojom.h"
using apps::mojom::OptionalBool;
diff --git a/chromium/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc b/chromium/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc
index 99a612517da..e570ba4c5ed 100644
--- a/chromium/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc
@@ -140,7 +140,8 @@ IN_PROC_BROWSER_TEST_F(ChromeURLDataManagerTest, LargeResourceScale) {
}
class ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled
- : public InProcessBrowserTest {
+ : public InProcessBrowserTest,
+ public testing::WithParamInterface<const char*> {
public:
ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled() {
feature_list_.InitAndEnableFeature(features::kWebUIReportOnlyTrustedTypes);
@@ -166,229 +167,77 @@ class ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled
};
// Verify that there's no Trusted Types violation in chrome://chrome-urls
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInChromeUrls) {
- CheckTrustedTypesViolation("chrome://chrome-urls");
-}
-
-// Verify that there's no Trusted Types violation in chrome://blob-internals
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInBlobInternals) {
- CheckTrustedTypesViolation("chrome://blob-internals");
-}
-
-// Verify that there's no Trusted Types violation in chrome://device-log
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInDeviceLog) {
- CheckTrustedTypesViolation("chrome://device-log");
-}
-
-// Verify that there's no Trusted Types violation in chrome://devices
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInDevices) {
- CheckTrustedTypesViolation("chrome://devices");
-}
-
-// Verify that there's no Trusted Types violation in chrome://gcm-internals
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInGCMInternals) {
- CheckTrustedTypesViolation("chrome://gcm-internals");
-}
-
-// Verify that there's no Trusted Types violation in chrome://inspect
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInInspect) {
- CheckTrustedTypesViolation("chrome://inspect");
-}
-
-// Verify that there's no Trusted Types violation in chrome://local-state
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInLocalState) {
- CheckTrustedTypesViolation("chrome://local-state");
-}
-
-// Verify that there's no Trusted Types violation in chrome://net-export
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInNetExport) {
- CheckTrustedTypesViolation("chrome://net-export");
-}
-
-// Verify that there's no Trusted Types violation in chrome://policy
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInPolicy) {
- CheckTrustedTypesViolation("chrome://policy");
-}
-
-// Verify that there's no Trusted Types violation in chrome://predictors
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInPredictors) {
- CheckTrustedTypesViolation("chrome://predictors");
-}
-
-// Verify that there's no Trusted Types violation in chrome://prefs-internals
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInPrefsInternals) {
- CheckTrustedTypesViolation("chrome://prefs-internals");
-}
-
-// Verify that there's no Trusted Types violation in chrome://sandbox
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInSandbox) {
- CheckTrustedTypesViolation("chrome://sandbox");
-}
-
-// Verify that there's no Trusted Types violation in chrome://suggestions
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInSuggestions) {
- CheckTrustedTypesViolation("chrome://suggestions");
-}
-
-// Verify that there's no Trusted Types violation in chrome://terms
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInTerms) {
- CheckTrustedTypesViolation("chrome://terms");
-}
-
-// Verify that there's no Trusted Types violation in chrome://user-actions
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInUserActions) {
- CheckTrustedTypesViolation("chrome://user-actions");
-}
-
-// Verify that there's no Trusted Types violation in chrome://webrtc-logs
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInWebrtcLogs) {
- CheckTrustedTypesViolation("chrome://webrtc-logs");
-}
-
-// Verify that there's no Trusted Types violation in chrome://autofill-internals
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInAutofillInternals) {
- CheckTrustedTypesViolation("chrome://autofill-internals");
-}
-
-// Verify that there's no Trusted Types violation in
-// chrome://password-manager-internals
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInPasswordManagerInternals) {
- CheckTrustedTypesViolation("chrome://password-manager-internals");
-}
-
-// Verify that there's no Trusted Types violation in chrome://media-internals
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInMediaInternals) {
- CheckTrustedTypesViolation("chrome://media-internals");
-}
-
-// Verify that there's no Trusted Types violation in chrome://histograms
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInHistograms) {
- CheckTrustedTypesViolation("chrome://histograms");
-}
-
-// Verify that there's no Trusted Types violation in chrome://accessibility
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInAccessibility) {
- CheckTrustedTypesViolation("chrome://accessibility");
-}
-
-// Verify that there's no Trusted Types violation in chrome://process-internals
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInProcessInternals) {
- CheckTrustedTypesViolation("chrome://process-internals");
-}
-
-// Verify that there's no Trusted Types violation in chrome://credits
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInCredits) {
- CheckTrustedTypesViolation("chrome://credits");
-}
-
-// Verify that there's no Trusted Types violation in
-// chrome://bluetooth-internals
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInBluetoothInternals) {
- CheckTrustedTypesViolation("chrome://bluetooth-internals");
-}
-
-// Verify that there's no Trusted Types violation in chrome://media-engagement
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInMediaEngagement) {
- CheckTrustedTypesViolation("chrome://media-engagement");
-}
-
-// Verify that there's no Trusted Types violation in chrome://site-engagement
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInSiteEngagement) {
- CheckTrustedTypesViolation("chrome://site-engagement");
-}
-
-// Verify that there's no Trusted Types violation in
-// chrome://translate-internals
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInTranslateInternals) {
- CheckTrustedTypesViolation("chrome://translate-internals");
-}
-
-// Verify that there's no Trusted Types violation in chrome://system
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInSystem) {
- CheckTrustedTypesViolation("chrome://system");
-}
-
-// Verify that there's no Trusted Types violation in chrome://usb-internals
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInUSBInternals) {
- CheckTrustedTypesViolation("chrome://usb-internals");
-}
-
-// Verify that there's no Trusted Types violation in
-// chrome://interventions-internals
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInInterventionsInternals) {
- CheckTrustedTypesViolation("chrome://interventions-internals");
-}
-
-// Verify that there's no Trusted Types violation in chrome://version
-IN_PROC_BROWSER_TEST_F(
- ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInVersion) {
- CheckTrustedTypesViolation("chrome://version");
-}
+IN_PROC_BROWSER_TEST_P(
+ ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
+ NoTrustedTypesViolation) {
+ CheckTrustedTypesViolation(GetParam());
+}
+
+// Non-exhaustive list of chrome:// URLs to test for trusted types violations.
+// This list was derived from chrome://about. :)
+static constexpr const char* const kChromeUrls[] = {
+ "chrome://accessibility",
+ "chrome://autofill-internals",
+ "chrome://blob-internals",
+ "chrome://bluetooth-internals",
+ "chrome://chrome-urls",
+ "chrome://components",
+ "chrome://conflicts",
+ "chrome://crashes",
+ "chrome://credits",
+ "chrome://cryptohome",
+ "chrome://device-log",
+ "chrome://devices",
+ "chrome://download-internals",
+ "chrome://drive-internals",
+ "chrome://explore-sites-internals",
+ "chrome://first-run",
+ "chrome://flags",
+ "chrome://gcm-internals",
+ "chrome://gpu",
+ "chrome://histograms",
+ "chrome://indexeddb-internals",
+ "chrome://inspect",
+ "chrome://interventions-internals",
+ "chrome://invalidations",
+ "chrome://linux-proxy-config",
+ "chrome://local-state",
+ "chrome://machine-learning-internals",
+ "chrome://media-engagement",
+ "chrome://media-internals",
+ "chrome://nacl",
+ "chrome://net-export",
+ "chrome://network-errors",
+ "chrome://ntp-tiles-internals",
+ "chrome://omnibox",
+ "chrome://password-manager-internals",
+ "chrome://policy",
+ "chrome://power",
+ "chrome://predictors",
+ "chrome://prefs-internals",
+ "chrome://process-internals",
+ "chrome://quota-internals",
+ "chrome://safe-browsing",
+ "chrome://sandbox",
+ "chrome://serviceworker-internals",
+ "chrome://signin-internals",
+ "chrome://site-engagement",
+ "chrome://snippets-internals",
+ "chrome://suggestions",
+ "chrome://supervised-user-internals",
+ "chrome://sync-internals",
+ "chrome://system",
+ "chrome://terms",
+ "chrome://translate-internals",
+ "chrome://usb-internals",
+ "chrome://user-actions",
+ "chrome://version",
+ "chrome://webapks",
+ "chrome://webrtc-internals",
+ "chrome://webrtc-logs",
+};
-// Verify that there's no Trusted Types violation in chrome://quota-internals
-IN_PROC_BROWSER_TEST_F(
+INSTANTIATE_TEST_SUITE_P(
+ ,
ChromeURLDataManagerTestWithWebUIReportOnlyTrustedTypesEnabled,
- NoTrustedTypesViolationInQuotaInternals) {
- CheckTrustedTypesViolation("chrome://quota-internals");
-}
+ ::testing::ValuesIn(kChromeUrls));
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 525c874c05e..60709ee12ab 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
@@ -15,6 +15,7 @@
#include "build/build_config.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/accessibility/accessibility_ui.h"
+#include "chrome/browser/browser_features.h"
#include "chrome/browser/buildflags.h"
#include "chrome/browser/devtools/devtools_ui_bindings.h"
#include "chrome/browser/engagement/site_engagement_service.h"
@@ -28,10 +29,9 @@
#include "chrome/browser/ui/webui/autofill_and_password_manager_internals/password_manager_internals_ui.h"
#include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h"
#include "chrome/browser/ui/webui/chrome_url_disabled_ui.h"
-#include "chrome/browser/ui/webui/chromeos/account_manager_error_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/camera/camera_ui.h"
+#include "chrome/browser/ui/webui/chromeos/account_manager/account_manager_error_ui.h"
+#include "chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_ui.h"
+#include "chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_ui.h"
#include "chrome/browser/ui/webui/chromeos/in_session_password_change/password_change_ui.h"
#include "chrome/browser/ui/webui/components/components_ui.h"
#include "chrome/browser/ui/webui/constrained_web_dialog_ui.h"
@@ -43,6 +43,7 @@
#include "chrome/browser/ui/webui/flags_ui.h"
#include "chrome/browser/ui/webui/gcm_internals_ui.h"
#include "chrome/browser/ui/webui/identity_internals_ui.h"
+#include "chrome/browser/ui/webui/internals/internals_ui.h"
#include "chrome/browser/ui/webui/interstitials/interstitial_ui.h"
#include "chrome/browser/ui/webui/interventions_internals/interventions_internals_ui.h"
#include "chrome/browser/ui/webui/invalidations_ui.h"
@@ -53,6 +54,7 @@
#include "chrome/browser/ui/webui/media/media_history_ui.h"
#include "chrome/browser/ui/webui/media/webrtc_logs_ui.h"
#include "chrome/browser/ui/webui/memory_internals_ui.h"
+#include "chrome/browser/ui/webui/nearby_internals/nearby_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"
@@ -66,15 +68,17 @@
#include "chrome/browser/ui/webui/signin_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"
#include "chrome/browser/ui/webui/usb_internals/usb_internals_ui.h"
#include "chrome/browser/ui/webui/user_actions/user_actions_ui.h"
#include "chrome/browser/ui/webui/version_ui.h"
+#include "chrome/browser/web_applications/system_web_app_manager.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/common/webui_url_constants.h"
+#include "chromeos/components/camera_app_ui/camera_app_ui.h"
+#include "chromeos/components/camera_app_ui/url_constants.h"
#include "components/favicon/core/favicon_service.h"
#include "components/favicon_base/favicon_util.h"
#include "components/favicon_base/select_favicon_frames.h"
@@ -101,12 +105,6 @@
#include "ui/web_dialogs/web_dialog_ui.h"
#include "url/gurl.h"
-#if BUILDFLAG(ENABLE_KALEIDOSCOPE)
-#include "chrome/browser/media/kaleidoscope/internal/kaleidoscope_content_ui.h"
-#include "chrome/browser/media/kaleidoscope/internal/kaleidoscope_ui.h"
-#include "media/base/media_switches.h"
-#endif // BUILDFLAG(ENABLE_KALEIDOSCOPE)
-
#if BUILDFLAG(ENABLE_NACL)
#include "chrome/browser/ui/webui/nacl_ui.h"
#endif
@@ -131,7 +129,10 @@
#endif // BUILDFLAG(ENABLE_FEED_IN_CHROME)
#else // defined(OS_ANDROID)
#include "chrome/browser/media/feeds/media_feeds_service.h"
+#include "chrome/browser/media/kaleidoscope/constants.h"
+#include "chrome/browser/media/kaleidoscope/kaleidoscope_ui.h"
#include "chrome/browser/media/router/media_router_feature.h"
+#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/webui/bookmarks/bookmarks_ui.h"
#include "chrome/browser/ui/webui/devtools_ui.h"
#include "chrome/browser/ui/webui/downloads/downloads_ui.h"
@@ -139,6 +140,7 @@
#include "chrome/browser/ui/webui/inspect_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/nearby_share/nearby_share_dialog_ui.h"
#include "chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.h"
#include "chrome/browser/ui/webui/ntp/new_tab_ui.h"
#include "chrome/browser/ui/webui/page_not_available_for_guest/page_not_available_for_guest_ui.h"
@@ -146,7 +148,9 @@
#include "chrome/browser/ui/webui/signin/sync_confirmation_ui.h"
#include "chrome/browser/ui/webui/sync_file_system_internals/sync_file_system_internals_ui.h"
#include "chrome/browser/ui/webui/system_info_ui.h"
+#include "chrome/browser/ui/webui/tab_search/tab_search_ui.h"
#include "chrome/browser/ui/webui/web_footer_experiment_ui.h"
+#include "media/base/media_switches.h"
#endif // defined(OS_ANDROID)
#if defined(OS_CHROMEOS)
@@ -206,6 +210,8 @@
#include "chrome/browser/ui/webui/chromeos/emulator/device_emulator_ui.h"
#include "chromeos/components/sample_system_web_app_ui/sample_system_web_app_ui.h"
#include "chromeos/components/sample_system_web_app_ui/url_constants.h"
+#include "chromeos/components/telemetry_extension_ui/telemetry_extension_ui.h"
+#include "chromeos/components/telemetry_extension_ui/url_constants.h"
#endif
#if !defined(OS_CHROMEOS)
@@ -214,11 +220,11 @@
#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
#include "chrome/browser/ui/sync/sync_promo_ui.h"
-#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/webui/browser_switch/browser_switch_ui.h"
#include "chrome/browser/ui/webui/signin/profile_picker_ui.h"
#include "chrome/browser/ui/webui/signin/signin_email_confirmation_ui.h"
#include "chrome/browser/ui/webui/signin/signin_error_ui.h"
+#include "chrome/browser/ui/webui/signin/signin_reauth_ui.h"
#include "chrome/browser/ui/webui/signin/user_manager_ui.h"
#include "chrome/browser/ui/webui/welcome/helpers.h"
#include "chrome/browser/ui/webui/welcome/welcome_ui.h"
@@ -397,6 +403,10 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
if (!content::HasWebUIScheme(url))
return nullptr;
+ // This factory doesn't support chrome-untrusted:// WebUIs.
+ if (url.SchemeIs(content::kChromeUIUntrustedScheme))
+ return nullptr;
+
// Please keep this in alphabetical order. If #ifs or special logics are
// required, add it below in the appropriate section.
//
@@ -436,6 +446,8 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
return &NewWebUI<FlagsUI>;
if (url.host_piece() == chrome::kChromeUIGCMInternalsHost)
return &NewWebUI<GCMInternalsUI>;
+ if (url.host_piece() == chrome::kChromeUIInternalsHost)
+ return &NewWebUI<InternalsUI>;
if (url.host_piece() == chrome::kChromeUIInterstitialHost)
return &NewWebUI<InterstitialUI>;
if (url.host_piece() == chrome::kChromeUIInterventionsInternalsHost)
@@ -478,8 +490,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
return &NewWebUI<SyncInternalsUI>;
if (url.host_piece() == chrome::kChromeUITranslateInternalsHost)
return &NewWebUI<TranslateInternalsUI>;
- if (url.host_piece() == chrome::kChromeUIUkmHost)
- return &NewWebUI<UkmInternalsUI>;
if (url.host_piece() == chrome::kChromeUIUsbInternalsHost)
return &NewWebUI<UsbInternalsUI>;
if (url.host_piece() == chrome::kChromeUIUserActionsHost)
@@ -513,6 +523,14 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
// Identity API is not available on Android.
if (url.host_piece() == chrome::kChromeUIIdentityInternalsHost)
return &NewWebUI<IdentityInternalsUI>;
+ if (base::FeatureList::IsEnabled(features::kNearbySharing)) {
+ if (url.host_piece() == chrome::kChromeUINearbyInternalsHost)
+ return &NewWebUI<NearbyInternalsUI>;
+ if (url.host_piece() == chrome::kChromeUINearbyShareHost &&
+ profile->IsRegularProfile()) {
+ return &NewWebUI<nearby_share::NearbyShareDialogUI>;
+ }
+ }
if (url.host_piece() == chrome::kChromeUINewTabHost)
return &NewWebUI<NewTabUI>;
if (url.host_piece() == chrome::kChromeUINewTabPageHost)
@@ -520,6 +538,10 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
// Settings are implemented with native UI elements on Android.
if (url.host_piece() == chrome::kChromeUISettingsHost)
return &NewWebUI<settings::SettingsUI>;
+ if (url.host_piece() == chrome::kChromeUITabSearchHost &&
+ base::FeatureList::IsEnabled(features::kTabSearch)) {
+ return &NewWebUI<TabSearchUI>;
+ }
if (url.host_piece() == chrome::kChromeUIExtensionsHost)
return &NewWebUI<extensions::ExtensionsUI>;
if (url.host_piece() == chrome::kChromeUIHistoryHost)
@@ -636,9 +658,10 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
return &NewWebUI<SysInternalsUI>;
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() == chromeos::kChromeUICameraAppHost &&
+ web_app::SystemWebAppManager::IsAppEnabled(
+ web_app::SystemAppType::CAMERA)) {
+ return &NewWebUI<chromeos::CameraAppUI>;
}
if (url.host_piece() == chrome::kChromeUIArcGraphicsTracingHost)
@@ -655,6 +678,11 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
}
if (url.host_piece() == chromeos::kChromeUISampleSystemWebAppHost)
return &NewWebUI<chromeos::SampleSystemWebAppUI>;
+ if (url.host_piece() == chromeos::kChromeUITelemetryExtensionHost) {
+ if (base::FeatureList::IsEnabled(chromeos::features::kTelemetryExtension)) {
+ return &NewWebUI<chromeos::TelemetryExtensionUI>;
+ }
+ }
#endif // !defined(OFFICIAL_BUILD)
#endif // defined(OS_CHROMEOS)
#if defined(OS_ANDROID)
@@ -708,19 +736,21 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui,
if (url.host_piece() == chrome::kChromeUISigninEmailConfirmationHost &&
!profile->IsOffTheRecord())
return &NewWebUI<SigninEmailConfirmationUI>;
+ if (url.host_piece() == chrome::kChromeUISigninReauthHost &&
+ !profile->IsOffTheRecord()) {
+ return &NewWebUI<SigninReauthUI>;
+ }
if (url.host_piece() == chrome::kChromeUIWelcomeHost &&
welcome::IsEnabled(profile))
return &NewWebUI<WelcomeUI>;
#endif
-#if BUILDFLAG(ENABLE_KALEIDOSCOPE)
+#if !defined(OS_ANDROID)
if (base::FeatureList::IsEnabled(media::kKaleidoscope)) {
- if (url.host_piece() == chrome::kChromeUIKaleidoscopeHost)
+ if (url.host_piece() == kKaleidoscopeUIHost)
return &NewWebUI<KaleidoscopeUI>;
- if (url.host_piece() == chrome::kChromeUIKaleidoscopeContentHost)
- return &NewWebUI<KaleidoscopeContentUI>;
}
-#endif // BUILDFLAG(ENABLE_KALEIDOSCOPE)
+#endif // !defined(OS_ANDROID)
#if BUILDFLAG(ENABLE_NACL)
if (url.host_piece() == chrome::kChromeUINaClHost)
return &NewWebUI<NaClUI>;
@@ -945,11 +975,6 @@ bool ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests(
// https://crbug.com/829414
origin.host() == chrome::kChromeUIPrintHost ||
#endif
-#if BUILDFLAG(ENABLE_KALEIDOSCOPE)
- // TODO(https://crbug.com/1039904): This is only for prototyping purposes.
- // Must be removed before launch.
- origin.host() == chrome::kChromeUIKaleidoscopeContentHost ||
-#endif
// https://crbug.com/831812
origin.host() == chrome::kChromeUISyncConfirmationHost ||
// https://crbug.com/831813
diff --git a/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory_browsertest.cc b/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory_browsertest.cc
new file mode 100644
index 00000000000..90231185b83
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chrome_web_ui_controller_factory_browsertest.cc
@@ -0,0 +1,42 @@
+// Copyright 2020 The Chromium 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/chrome_web_ui_controller_factory.h"
+
+#include "base/strings/strcat.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/tabs/tab_strip_model.h"
+#include "chrome/common/webui_url_constants.h"
+#include "chrome/test/base/in_process_browser_test.h"
+#include "chrome/test/base/ui_test_utils.h"
+#include "content/public/test/browser_test.h"
+#include "content/public/test/web_ui_browsertest_util.h"
+
+using ChromeWebUIControllerFactoryBrowserTest = InProcessBrowserTest;
+
+// Verify that if there is a chrome-untrusted:// URLDataSource with the same
+// host as a chrome:// WebUI, we serve the right resources and we don't use the
+// wrong WebUI object.
+IN_PROC_BROWSER_TEST_F(ChromeWebUIControllerFactoryBrowserTest,
+ ChromeUntrustedSameHost) {
+ content::AddUntrustedDataSource(browser()->profile(),
+ chrome::kChromeUIVersionHost);
+ EXPECT_TRUE(ui_test_utils::NavigateToURL(
+ browser(),
+ GURL(base::StrCat({"chrome-untrusted://", chrome::kChromeUIVersionHost,
+ "/title2.html"}))));
+ auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents();
+ EXPECT_EQ(base::ASCIIToUTF16("Title Of Awesomeness"),
+ web_contents->GetTitle());
+ EXPECT_FALSE(web_contents->GetWebUI());
+
+ // Check that we can navigate to chrome://version and that it serves the right
+ // resources and has a WebUI.
+ EXPECT_TRUE(ui_test_utils::NavigateToURL(
+ browser(), GURL(base::StrCat({"chrome://", chrome::kChromeUIVersionHost,
+ "/title2.html"}))));
+ EXPECT_EQ(base::ASCIIToUTF16("About Version"), web_contents->GetTitle());
+ EXPECT_TRUE(web_contents->GetWebUI());
+}
diff --git a/chromium/chrome/browser/ui/webui/chrome_webui_navigation_browsertest.cc b/chromium/chrome/browser/ui/webui/chrome_webui_navigation_browsertest.cc
index 52c3b47241d..1023da7f2bd 100644
--- a/chromium/chrome/browser/ui/webui/chrome_webui_navigation_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/chrome_webui_navigation_browsertest.cc
@@ -8,6 +8,8 @@
#include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
+#include "content/browser/frame_host/render_frame_host_impl.h"
+#include "content/common/frame.mojom.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
@@ -18,6 +20,19 @@
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "url/url_constants.h"
+namespace {
+
+content::mojom::OpenURLParamsPtr CreateOpenURLParams(const GURL& url) {
+ auto params = content::mojom::OpenURLParams::New();
+ params->url = url;
+ params->disposition = WindowOpenDisposition::CURRENT_TAB;
+ params->should_replace_current_entry = false;
+ params->user_gesture = true;
+ return params;
+}
+
+} // namespace
+
// Tests embedder specific behavior of WebUIs.
class ChromeWebUINavigationBrowserTest : public InProcessBrowserTest {
public:
@@ -61,9 +76,9 @@ IN_PROC_BROWSER_TEST_F(ChromeWebUINavigationBrowserTest,
EXPECT_EQ("about:blank", child->GetLastCommittedURL());
content::TestNavigationObserver observer(web_contents);
- GURL webui_url(content::GetWebUIURL("web-ui/title1.html?noxfo=true"));
- content::PwnMessageHelper::OpenURL(child->GetProcess(), child->GetRoutingID(),
- webui_url);
+ static_cast<content::RenderFrameHostImpl*>(child)->OpenURL(
+ CreateOpenURLParams(
+ content::GetWebUIURL("web-ui/title1.html?noxfo=true")));
observer.Wait();
// Retrieve the RenderFrameHost again since it might have been swapped.
@@ -100,10 +115,9 @@ IN_PROC_BROWSER_TEST_F(
content::AddUntrustedDataSource(browser()->profile(), "test-iframe-host",
csp);
- GURL untrusted_url(
- content::GetChromeUntrustedUIURL("test-iframe-host/title1.html"));
- content::PwnMessageHelper::OpenURL(child->GetProcess(), child->GetRoutingID(),
- untrusted_url);
+ static_cast<content::RenderFrameHostImpl*>(child)->OpenURL(
+ CreateOpenURLParams(
+ content::GetChromeUntrustedUIURL("test-iframe-host/title1.html")));
observer.Wait();
// Retrieve the RenderFrameHost again since it might have been swapped.
diff --git a/chromium/chrome/browser/ui/webui/chromeos/DEPS b/chromium/chrome/browser/ui/webui/chromeos/DEPS
index c80e0efe1d0..a0bba8a28e5 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/DEPS
+++ b/chromium/chrome/browser/ui/webui/chromeos/DEPS
@@ -7,10 +7,3 @@ include_rules = [
"+services/device/public/mojom",
"+services/network",
]
-
-specific_include_rules = {
- "keyboard_overlay_ui\.cc": [
- # TODO(mash): Remove. http://crbug.com/770866
- "+ash/shell.h",
- ],
-}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager/OWNERS b/chromium/chrome/browser/ui/webui/chromeos/account_manager/OWNERS
new file mode 100644
index 00000000000..4df9ab85cdc
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager/OWNERS
@@ -0,0 +1,2 @@
+anastasiian@chromium.org
+sinhak@chromium.org
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_error_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_error_ui.cc
index 83c0f366342..b329c687a33 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_error_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_error_ui.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "chrome/browser/ui/webui/chromeos/account_manager_error_ui.h"
+#include "chrome/browser/ui/webui/chromeos/account_manager/account_manager_error_ui.h"
#include "base/bind.h"
#include "build/branding_buildflags.h"
@@ -53,6 +53,10 @@ AccountManagerErrorUI::AccountManagerErrorUI(content::WebUI* web_ui)
// Add required resources.
html_source->AddResourcePath("account_manager_shared.css",
IDR_ACCOUNT_MANAGER_SHARED_CSS);
+ html_source->AddResourcePath("account_manager_browser_proxy.html",
+ IDR_ACCOUNT_MANAGER_BROWSER_PROXY_HTML);
+ html_source->AddResourcePath("account_manager_browser_proxy.js",
+ IDR_ACCOUNT_MANAGER_BROWSER_PROXY_JS);
html_source->AddResourcePath("account_manager_error.js",
IDR_ACCOUNT_MANAGER_ERROR_JS);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_error_ui.h b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_error_ui.h
index 95e8a498e36..f740e1bf35f 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_error_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_error_ui.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ERROR_UI_H_
-#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ERROR_UI_H_
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MANAGER_ERROR_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MANAGER_ERROR_UI_H_
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
@@ -25,4 +25,4 @@ class AccountManagerErrorUI : public ui::WebDialogUI {
} // namespace chromeos
-#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ERROR_UI_H_
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MANAGER_ERROR_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_dialog.cc
index b17dd07fe5f..0765cfa96f0 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_dialog.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h"
+#include "chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_dialog.h"
#include <string>
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_dialog.h
index 67fea954e98..e92b754253c 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_dialog.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_WELCOME_DIALOG_H_
-#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_WELCOME_DIALOG_H_
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MANAGER_WELCOME_DIALOG_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MANAGER_WELCOME_DIALOG_H_
#include <string>
@@ -37,4 +37,4 @@ class AccountManagerWelcomeDialog : public SystemWebDialogDelegate {
} // namespace chromeos
-#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_WELCOME_DIALOG_H_
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MANAGER_WELCOME_DIALOG_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_ui.cc
index 16a69c1d232..8248231f214 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_ui.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h"
+#include "chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_ui.h"
#include "base/bind.h"
#include "base/strings/utf_string_conversions.h"
@@ -45,6 +45,10 @@ AccountManagerWelcomeUI::AccountManagerWelcomeUI(content::WebUI* web_ui)
IDR_ACCOUNT_MANAGER_SHARED_CSS);
html_source->AddResourcePath("account_manager_welcome.js",
IDR_ACCOUNT_MANAGER_WELCOME_JS);
+ html_source->AddResourcePath("account_manager_browser_proxy.html",
+ IDR_ACCOUNT_MANAGER_BROWSER_PROXY_HTML);
+ html_source->AddResourcePath("account_manager_browser_proxy.js",
+ IDR_ACCOUNT_MANAGER_BROWSER_PROXY_JS);
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
html_source->AddResourcePath("account_manager_welcome_1x.png",
IDR_ACCOUNT_MANAGER_WELCOME_1X_PNG);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_ui.h
index ded176fe6df..9a68ddc6579 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_manager_welcome_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_ui.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_WELCOME_UI_H_
-#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_WELCOME_UI_H_
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MANAGER_WELCOME_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MANAGER_WELCOME_UI_H_
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
@@ -24,4 +24,4 @@ class AccountManagerWelcomeUI : public ui::WebDialogUI {
} // namespace chromeos
-#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_WELCOME_UI_H_
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MANAGER_WELCOME_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_dialog.cc
index aeb9b5bfaa6..31504a89ca1 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_dialog.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h"
+#include "chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_dialog.h"
#include <string>
@@ -10,7 +10,7 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/settings_window_manager_chromeos.h"
-#include "chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h"
+#include "chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_ui.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/webui_url_constants.h"
#include "components/prefs/pref_service.h"
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_dialog.h
index 96670974836..6622d961508 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_dialog.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MIGRATION_WELCOME_DIALOG_H_
-#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MIGRATION_WELCOME_DIALOG_H_
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MIGRATION_WELCOME_DIALOG_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MIGRATION_WELCOME_DIALOG_H_
#include <string>
@@ -42,4 +42,4 @@ class AccountMigrationWelcomeDialog : public SystemWebDialogDelegate {
} // namespace chromeos
-#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MIGRATION_WELCOME_DIALOG_H_
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MIGRATION_WELCOME_DIALOG_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_ui.cc
index 12b79aaed4a..2d6596522c5 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_ui.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h"
+#include "chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_ui.h"
#include <memory>
#include <string>
@@ -12,7 +12,7 @@
#include "base/strings/utf_string_conversions.h"
#include "build/branding_buildflags.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h"
+#include "chrome/browser/ui/webui/signin/inline_login_dialog_chromeos.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/browser_resources.h"
@@ -54,9 +54,9 @@ class MigrationMessageHandler : public content::WebUIMessageHandler {
CHECK(!args->GetList().empty());
const std::string& account_email = args->GetList()[0].GetString();
- InlineLoginHandlerDialogChromeOS::Show(
- account_email, InlineLoginHandlerDialogChromeOS::Source::
- kAccountManagerMigrationWelcomeScreen);
+ InlineLoginDialogChromeOS::Show(account_email,
+ InlineLoginDialogChromeOS::Source::
+ kAccountManagerMigrationWelcomeScreen);
HandleCloseDialog(args);
}
@@ -98,10 +98,10 @@ AccountMigrationWelcomeUI::AccountMigrationWelcomeUI(content::WebUI* web_ui)
IDR_ACCOUNT_MANAGER_SHARED_CSS);
html_source->AddResourcePath("account_migration_welcome.js",
IDR_ACCOUNT_MIGRATION_WELCOME_JS);
- html_source->AddResourcePath("account_migration_browser_proxy.html",
- IDR_ACCOUNT_MIGRATION_BROWSER_PROXY_HTML);
- html_source->AddResourcePath("account_migration_browser_proxy.js",
- IDR_ACCOUNT_MIGRATION_BROWSER_PROXY_JS);
+ html_source->AddResourcePath("account_manager_browser_proxy.html",
+ IDR_ACCOUNT_MANAGER_BROWSER_PROXY_HTML);
+ html_source->AddResourcePath("account_manager_browser_proxy.js",
+ IDR_ACCOUNT_MANAGER_BROWSER_PROXY_JS);
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
html_source->AddResourcePath("account_manager_welcome_1x.png",
IDR_ACCOUNT_MANAGER_WELCOME_1X_PNG);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_ui.h
index 24a0c7dd8be..3c7ec92e12d 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/account_manager/account_migration_welcome_ui.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MIGRATION_WELCOME_UI_H_
-#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MIGRATION_WELCOME_UI_H_
+#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MIGRATION_WELCOME_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MIGRATION_WELCOME_UI_H_
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
@@ -26,4 +26,4 @@ class AccountMigrationWelcomeUI : public ui::WebDialogUI {
} // namespace chromeos
-#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MIGRATION_WELCOME_UI_H_
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MANAGER_ACCOUNT_MIGRATION_WELCOME_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_proxy_test.js b/chromium/chrome/browser/ui/webui/chromeos/account_migration_proxy_test.js
deleted file mode 100644
index a81f50bc8c0..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_proxy_test.js
+++ /dev/null
@@ -1,23 +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.
-
-/** @implements {account_migration.AccountMigrationBrowserProxy} */
-class TestAccountMigrationBrowserProxy extends TestBrowserProxy {
- constructor() {
- super([
- 'closeDialog',
- 'reauthenticateAccount',
- ]);
- }
-
- /** @override */
- closeDialog() {
- this.methodCalled('closeDialog');
- }
-
- /** @override */
- reauthenticateAccount(account_email) {
- this.methodCalled('reauthenticateAccount', account_email);
- }
-}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_test.js b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_test.js
deleted file mode 100644
index 7c8a1f74674..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_test.js
+++ /dev/null
@@ -1,89 +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.
-
-GEN('#include "content/public/test/browser_test.h"');
-
-/**
- * Test fixture for generated tests.
- * @extends {testing.Test}
- */
-function AccountMigrationWelcomeUITest() {}
-let testBrowserProxy = null;
-
-AccountMigrationWelcomeUITest.prototype = {
- __proto__: testing.Test.prototype,
-
- /**
- * Define the C++ fixture class and include it.
- * @type {?string}
- * @override
- */
- typedefCppFixture: 'AccountMigrationWelcomeUITest',
-
- /** @override */
- extraLibraries: [
- '//chrome/test/data/webui/test_browser_proxy.js',
- 'account_migration_proxy_test.js',
- ],
-
- /** @override */
- setUp: function() {
- testBrowserProxy = new TestAccountMigrationBrowserProxy();
- account_migration.AccountMigrationBrowserProxyImpl.instance_ =
- testBrowserProxy;
- testing.Test.prototype.setUp.call(this);
- },
-
- /** @override */
- testGenPreamble: function() {
- GEN('ShowDialog();');
- },
-
- /**
- * Tests that the dialog opened to the correct URL.
- */
- testDialogUrl: function() {
- // Remove slash at the end of URL if present.
- const url = window.location.href.replace(/\/$/, '');
- assertEquals(chrome.getVariableValue('expectedUrl'), url);
- },
-
- /**
- * Tests that |closeDialog| function get called after clicking
- * the cancel button
- */
- testCloseDialog: function() {
- $('cancel-button').click();
- assertEquals(1, testBrowserProxy.getCallCount('closeDialog'));
- },
-
- /**
- * Tests that |reauthenticateAccount| function get called with expected email
- * after clicking the migrate button.
- */
- testReauthenticateAccount: function() {
- $('migrate-button').click();
- assertEquals(1, testBrowserProxy.getCallCount('reauthenticateAccount'));
- testBrowserProxy.whenCalled('reauthenticateAccount').then(email => {
- assertEquals(chrome.getVariableValue('expectedEmail'), email);
- });
- },
-};
-
-GEN('#include "chrome/browser/ui/webui/chromeos/account_migration_welcome_ui_test.h"');
-GEN('');
-
-
-TEST_F('AccountMigrationWelcomeUITest', 'testDialogURL', function() {
- this.testDialogUrl();
-});
-
-TEST_F('AccountMigrationWelcomeUITest', 'testCloseDialog', function() {
- this.testCloseDialog();
-});
-
-TEST_F(
- 'AccountMigrationWelcomeUITest', 'testReauthenticateAccount', function() {
- this.testReauthenticateAccount();
- });
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui_test.cc b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui_test.cc
deleted file mode 100644
index a9b5b792260..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui_test.cc
+++ /dev/null
@@ -1,31 +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/account_migration_welcome_ui_test.h"
-
-#include "base/macros.h"
-#include "chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h"
-#include "chrome/common/url_constants.h"
-#include "content/public/browser/render_view_host.h"
-#include "content/public/browser/web_contents.h"
-#include "content/public/browser/web_ui.h"
-#include "content/public/browser/web_ui_message_handler.h"
-#include "content/public/test/browser_test_utils.h"
-#include "ui/web_dialogs/web_dialog_ui.h"
-
-AccountMigrationWelcomeUITest::AccountMigrationWelcomeUITest() = default;
-AccountMigrationWelcomeUITest::~AccountMigrationWelcomeUITest() = default;
-
-void AccountMigrationWelcomeUITest::ShowDialog() {
- auto* account_email = "test@example.com";
- auto* dialog = chromeos::AccountMigrationWelcomeDialog::Show(account_email);
- auto* webui = dialog->GetWebUIForTest();
- auto* web_contents = webui->GetWebContents();
- content::WaitForLoadStop(web_contents);
- web_contents->GetMainFrame()->SetWebUIProperty(
- "expectedUrl", chrome::kChromeUIAccountMigrationWelcomeURL);
- web_contents->GetMainFrame()->SetWebUIProperty("expectedEmail",
- account_email);
- SetWebUIInstance(webui);
-}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui_test.h b/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui_test.h
deleted file mode 100644
index 29ef97bf54a..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/account_migration_welcome_ui_test.h
+++ /dev/null
@@ -1,21 +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_ACCOUNT_MIGRATION_WELCOME_UI_TEST_H_
-#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MIGRATION_WELCOME_UI_TEST_H_
-
-#include "chrome/test/base/ui_test_utils.h"
-#include "chrome/test/base/web_ui_browser_test.h"
-// Test framework for
-// chrome/browser/ui/webui/chromeos/account_migration_welcome_test.js
-class AccountMigrationWelcomeUITest : public WebUIBrowserTest {
- public:
- AccountMigrationWelcomeUITest();
- ~AccountMigrationWelcomeUITest() override;
-
- protected:
- void ShowDialog();
-};
-
-#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ACCOUNT_MIGRATION_WELCOME_UI_TEST_H_
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 cc951296439..021040da4f5 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
@@ -20,7 +20,7 @@
#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision.mojom.h"
#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h"
#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h"
-#include "chrome/services/app_service/public/cpp/app_registry_cache.h"
+#include "components/services/app_service/public/cpp/app_registry_cache.h"
#include "components/signin/public/identity_manager/access_token_fetcher.h"
#include "components/signin/public/identity_manager/access_token_info.h"
#include "components/signin/public/identity_manager/consent_level.h"
@@ -55,10 +55,16 @@ void AddSupervisionHandler::RequestClose(RequestCloseCallback callback) {
void AddSupervisionHandler::GetInstalledArcApps(
GetInstalledArcAppsCallback callback) {
Profile* profile = Profile::FromWebUI(web_ui_);
+ if (!profile) {
+ DLOG(WARNING) << "Profile not found in WebUI";
+ std::move(callback).Run({});
+ return;
+ }
+
apps::AppServiceProxy* proxy =
apps::AppServiceProxyFactory::GetForProfile(profile);
- if (arc::ArcSessionManager::Get() == nullptr) {
+ if (!arc::ArcSessionManager::Get()) {
DLOG(WARNING) << "No ArcSessionManager available";
std::move(callback).Run({});
return;
@@ -71,15 +77,9 @@ void AddSupervisionHandler::GetInstalledArcApps(
}
std::vector<std::string> installed_arc_apps;
-
proxy->AppRegistryCache().ForEachApp(
[&installed_arc_apps, profile](const apps::AppUpdate& update) {
- // We don't include "sticky" ARC apps because they are system-required
- // apps that should not be offered for uninstallation. TODO(danan):
- // check for stickyness via the App Service instead when that is
- // available. (https://crbug.com/948408).
- if (ShouldIncludeAppUpdate(update) &&
- !arc::IsArcAppSticky(update.AppId(), profile)) {
+ if (ShouldIncludeAppUpdate(update)) {
std::string package_name =
arc::AppIdToArcPackageName(update.AppId(), profile);
if (!package_name.empty())
diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc
index 0c7a610df3e..8bc9b023bb2 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.cc
@@ -9,14 +9,12 @@
#include "chrome/browser/supervised_user/supervised_user_service.h"
#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_metrics_recorder.h"
-#include "chrome/services/app_service/public/cpp/app_update.h"
-#include "chrome/services/app_service/public/mojom/types.mojom.h"
+#include "components/services/app_service/public/cpp/app_update.h"
+#include "components/services/app_service/public/mojom/types.mojom.h"
bool ShouldIncludeAppUpdate(const apps::AppUpdate& app_update) {
- // TODO(danan): update this to only return sticky = true arc apps when that
- // attribute is available via the App Service (https://crbug.com/948408).
-
- return app_update.AppType() == apps::mojom::AppType::kArc;
+ return app_update.AppType() == apps::mojom::AppType::kArc &&
+ app_update.InstallSource() != apps::mojom::InstallSource::kSystem;
}
void LogOutHelper() {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils_unittest.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils_unittest.cc
index 6236a41ff69..2640236a92b 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils_unittest.cc
@@ -3,7 +3,7 @@
// found in the LICENSE file.
#include "chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_handler_utils.h"
-#include "chrome/services/app_service/public/cpp/app_update.h"
+#include "components/services/app_service/public/cpp/app_update.h"
#include "testing/gtest/include/gtest/gtest.h"
using AddSupervisionHandlerUtilsTest = testing::Test;
@@ -13,12 +13,13 @@ TEST_F(AddSupervisionHandlerUtilsTest, TestShouldIncludeAppUpdate) {
// Return ARC apps.
apps::mojom::App arc_state;
arc_state.app_type = apps::mojom::AppType::kArc;
- apps::AppUpdate arc_update(&arc_state, nullptr /* delta */);
+ apps::AppUpdate arc_update(&arc_state, nullptr /* delta */, EmptyAccountId());
EXPECT_TRUE(ShouldIncludeAppUpdate(arc_update));
// Don't return non-ARC apps.
apps::mojom::App non_arc_state;
non_arc_state.app_type = apps::mojom::AppType::kBuiltIn;
- apps::AppUpdate non_arc_update(&non_arc_state, nullptr /* delta */);
+ apps::AppUpdate non_arc_update(&non_arc_state, nullptr /* delta */,
+ EmptyAccountId());
EXPECT_FALSE(ShouldIncludeAppUpdate(non_arc_update));
}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui_browsertest.cc
index 7e7fde7f98c..fa0110c7cf3 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/add_supervision/add_supervision_ui_browsertest.cc
@@ -25,10 +25,6 @@
namespace chromeos {
-// NOTE: This test is flaky and therefore disabled under MSAN:
-// https://crbug.com/1002560
-#if !defined(MEMORY_SANITIZER)
-
namespace {
const char kGetAddSupervisionUIElementJS[] =
@@ -94,14 +90,7 @@ class AddSupervisionBrowserTest : public InProcessBrowserTest {
DISALLOW_COPY_AND_ASSIGN(AddSupervisionBrowserTest);
};
-// Disabled on ASan and LSAn builds, because it's very flaky. See
-// crbug.com/1004237
-#if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER)
-#define MAYBE_URLParameters DISABLED_URLParameters
-#else
-#define MAYBE_URLParameters URLParameters
-#endif
-IN_PROC_BROWSER_TEST_F(AddSupervisionBrowserTest, MAYBE_URLParameters) {
+IN_PROC_BROWSER_TEST_F(AddSupervisionBrowserTest, URLParameters) {
// Open the Add Supervision URL.
ui_test_utils::NavigateToURL(browser(), add_supervision_webui_url());
content::WaitForLoadStop(contents());
@@ -172,15 +161,7 @@ IN_PROC_BROWSER_TEST_F(AddSupervisionBrowserTest, ShowOfflineScreen) {
std::string(".webviewDiv")));
}
-// Disabled on ASan and LSAn builds, because it's very flaky. See
-// crbug.com/1004237
-#if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER)
-#define MAYBE_ShowConfirmSignoutDialog DISABLED_ShowConfirmSignoutDialog
-#else
-#define MAYBE_ShowConfirmSignoutDialog ShowConfirmSignoutDialog
-#endif
-IN_PROC_BROWSER_TEST_F(AddSupervisionBrowserTest,
- MAYBE_ShowConfirmSignoutDialog) {
+IN_PROC_BROWSER_TEST_F(AddSupervisionBrowserTest, ShowConfirmSignoutDialog) {
// Open the Add Supervision URL.
ui_test_utils::NavigateToURL(browser(), add_supervision_webui_url());
content::WaitForLoadStop(contents());
@@ -206,14 +187,7 @@ IN_PROC_BROWSER_TEST_F(AddSupervisionBrowserTest,
ASSERT_TRUE(ConfirmSignoutDialog::IsShowing());
}
-// Disabled on ASan and LSAn builds, because it's very flaky. See
-// crbug.com/1004237
-#if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER)
-#define MAYBE_UMATest DISABLED_UMATest
-#else
-#define MAYBE_UMATest UMATest
-#endif
-IN_PROC_BROWSER_TEST_F(AddSupervisionBrowserTest, MAYBE_UMATest) {
+IN_PROC_BROWSER_TEST_F(AddSupervisionBrowserTest, UMATest) {
base::HistogramTester histogram_tester;
base::UserActionTester user_action_tester;
@@ -246,6 +220,4 @@ IN_PROC_BROWSER_TEST_F(AddSupervisionBrowserTest, MAYBE_UMATest) {
1);
}
-#endif // !defined(MEMORY_SANITIZER)
-
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc
index d0a7fc4bb75..8beb112fa72 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.cc
@@ -14,6 +14,7 @@
#include "chrome/grit/browser_resources.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/webui/web_ui_util.h"
namespace {
@@ -36,7 +37,8 @@ content::WebUIDataSource* CreateGraphicsDataSource() {
IDR_ARC_GRAPHICS_TRACING_UI_JS);
source->AddResourcePath(kArcTracingCssPath, IDR_ARC_TRACING_CSS);
source->AddResourcePath(kArcTracingUiJsPath, IDR_ARC_TRACING_UI_JS);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self';");
base::DictionaryValue localized_strings;
@@ -58,7 +60,8 @@ content::WebUIDataSource* CreateOverviewDataSource() {
IDR_ARC_OVERVIEW_TRACING_UI_JS);
source->AddResourcePath(kArcTracingCssPath, IDR_ARC_TRACING_CSS);
source->AddResourcePath(kArcTracingUiJsPath, IDR_ARC_TRACING_UI_JS);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self';");
base::DictionaryValue localized_strings;
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 d74e24d8ba0..8a66b8f69fe 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
@@ -31,6 +31,7 @@
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/common/content_features.h"
#include "net/base/url_util.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/chromeos/resources/grit/ui_chromeos_resources.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
@@ -93,7 +94,8 @@ AssistantOptInUI::AssistantOptInUI(content::WebUI* web_ui)
IDR_ASSISTANT_VOICE_MATCH_ANIMATION);
source->AddResourcePath("voice_match_already_setup_animation.json",
IDR_ASSISTANT_VOICE_MATCH_ALREADY_SETUP_ANIMATION);
- source->OverrideContentSecurityPolicyWorkerSrc("worker-src blob: 'self';");
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::WorkerSrc, "worker-src blob: 'self';");
content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source);
// Do not zoom for Assistant opt-in web contents.
diff --git a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc
index b65490702e4..4ff6decf773 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/bluetooth_pairing_dialog.cc
@@ -7,8 +7,10 @@
#include "base/json/json_writer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h"
+#include "chrome/browser/ui/webui/webui_util.h"
#include "chrome/common/url_constants.h"
-#include "chrome/grit/browser_resources.h"
+#include "chrome/grit/bluetooth_pairing_dialog_resources.h"
+#include "chrome/grit/bluetooth_pairing_dialog_resources_map.h"
#include "chrome/grit/generated_resources.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_ui.h"
@@ -20,6 +22,14 @@ namespace chromeos {
namespace {
+#if !BUILDFLAG(OPTIMIZE_WEBUI)
+namespace {
+const char kGeneratedPath[] =
+ "@out_folder@/gen/chrome/browser/resources/chromeos/"
+ "bluetooth_pairing_dialog/";
+}
+#endif
+
constexpr int kBluetoothPairingDialogHeight = 375;
void AddBluetoothStrings(content::WebUIDataSource* html_source) {
@@ -103,15 +113,17 @@ BluetoothPairingDialogUI::BluetoothPairingDialogUI(content::WebUI* web_ui)
AddBluetoothStrings(source);
source->AddLocalizedString("title", IDS_SETTINGS_BLUETOOTH_PAIR_DEVICE_TITLE);
- source->UseStringsJs();
#if BUILDFLAG(OPTIMIZE_WEBUI)
- source->SetDefaultResource(IDR_BLUETOOTH_PAIRING_DIALOG_VULCANIZED_HTML);
- source->AddResourcePath("crisper.js",
- IDR_BLUETOOTH_PAIRING_DIALOG_CRISPER_JS);
+ webui::SetupBundledWebUIDataSource(
+ source, "bluetooth_pairing_dialog.js",
+ IDR_BLUETOOTH_PAIRING_DIALOG_ROLLUP_JS,
+ IDR_BLUETOOTH_PAIRING_DIALOG_CONTAINER_HTML);
#else
- source->SetDefaultResource(IDR_BLUETOOTH_PAIRING_DIALOG_HTML);
- source->AddResourcePath("bluetooth_pairing_dialog.js",
- IDR_BLUETOOTH_PAIRING_DIALOG_JS);
+ webui::SetupWebUIDataSource(
+ source,
+ base::make_span(kBluetoothPairingDialogResources,
+ kBluetoothPairingDialogResourcesSize),
+ kGeneratedPath, IDR_BLUETOOTH_PAIRING_DIALOG_CONTAINER_HTML);
#endif
content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source);
}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc
deleted file mode 100644
index 9906f67c75e..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.cc
+++ /dev/null
@@ -1,86 +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/camera/camera_ui.h"
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/feature_list.h"
-#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/webui_util.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.
- webui::AddResourcePathsBulk(
- source, base::make_span(kCameraResources, kCameraResourcesSize));
-
- static constexpr webui::ResourcePath kAdditionalResources[] = {
- // Add WebUI version of the CCA browser proxy.
- {"src/js/browser_proxy/browser_proxy.js", IDR_CAMERA_WEBUI_BROWSER_PROXY},
-
- // Add mojom-lite files under expected paths.
- {"src/js/mojo/camera_intent.mojom-lite.js",
- IDR_CAMERA_CAMERA_INTENT_MOJOM_LITE_JS},
- {"src/js/mojo/image_capture.mojom-lite.js",
- IDR_CAMERA_IMAGE_CAPTURE_MOJOM_LITE_JS},
- {"src/js/mojo/camera_common.mojom-lite.js",
- IDR_CAMERA_CAMERA_COMMON_MOJOM_LITE_JS},
- {"src/js/mojo/camera_metadata.mojom-lite.js",
- IDR_CAMERA_CAMERA_METADATA_MOJOM_LITE_JS},
- {"src/js/mojo/camera_metadata_tags.mojom-lite.js",
- IDR_CAMERA_CAMERA_METADATA_TAGS_MOJOM_LITE_JS},
- {"src/js/mojo/camera_app.mojom-lite.js", IDR_CAMERA_APP_MOJOM_LITE_JS},
- {"src/js/mojo/mojo_bindings_lite.js", IDR_MOJO_MOJO_BINDINGS_LITE_JS},
-
- // Add System Web App resources.
- {"pwa.html", IDR_PWA_HTML},
- };
- webui::AddResourcePathsBulk(source, kAdditionalResources);
-
- source->UseStringsJs();
-
- 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
deleted file mode 100644
index 31dabca4e5e..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/camera/camera_ui.h
+++ /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.
-
-#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/crostini_installer/crostini_installer.mojom b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer.mojom
index e679865fb55..72e63a90a51 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer.mojom
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer.mojom
@@ -25,10 +25,15 @@ interface PageHandler {
// If a user cancels the installation without starting it at all, this should
// be called so that metrics can be recorded.
CancelBeforeStart();
- // The page normally is displayed in a dialog. Call this to close the dialog.
- // chrome.send('dialogClose') should not be used, which could kill the page
- // handler before previous mojom calls have been run.
- Close();
+ // This is called when the web page is "closed", and the dialog (or whatever)
+ // hosting it should also be closed. This can happen as a result of
+ // Page::RequestClose() being called, or it can happen spontaneously (e.g.
+ // user clicking cancel on the page or installation finished).
+ //
+ // Note that the web page should not use something like
+ // chrome.send('dialogClose'), which could kill the page handler before
+ // previous mojom calls have been run.
+ OnPageClosed();
// Fetches the amount of free disk space, the result is sent via
// OnAmountOfFreeDiskSpace.
RequestAmountOfFreeDiskSpace();
@@ -54,4 +59,7 @@ interface Page {
OnAmountOfFreeDiskSpace(array<crostini.mojom.DiskSliderTick> ticks,
int8 default_index,
bool is_low_space_available);
+ // Informs the page that it should be closed. The page should respond with
+ // PageHandler::OnPageClosed() to indicate it is ready to be closed.
+ RequestClose();
};
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_dialog.cc
index b3f75d222e5..28c41a9a9af 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_dialog.cc
@@ -4,10 +4,13 @@
#include "chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_dialog.h"
+#include "ash/public/cpp/shelf_types.h"
+#include "ash/public/cpp/window_properties.h"
#include "base/bind_helpers.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/chromeos/crostini/crostini_features.h"
#include "chrome/browser/chromeos/crostini/crostini_manager.h"
+#include "chrome/browser/chromeos/crostini/crostini_shelf_utils.h"
#include "chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_ui.h"
#include "chrome/common/webui_url_constants.h"
#include "ui/base/ui_base_types.h"
@@ -75,6 +78,10 @@ bool CrostiniInstallerDialog::ShouldCloseDialogOnEscape() const {
void CrostiniInstallerDialog::AdjustWidgetInitParams(
views::Widget::InitParams* params) {
params->z_order = ui::ZOrderLevel::kNormal;
+
+ const ash::ShelfID shelf_id(crostini::kCrostiniInstallerShelfId);
+ params->init_properties_container.SetProperty(ash::kShelfIDKey,
+ shelf_id.Serialize());
}
bool CrostiniInstallerDialog::CanCloseDialog() const {
@@ -82,7 +89,14 @@ bool CrostiniInstallerDialog::CanCloseDialog() const {
// closing logic, we should find a more general solution.
// Disallow closing without WebUI consent.
- return installer_ui_ == nullptr || installer_ui_->can_close();
+ //
+ // Note that while the function name |CanCloseDialog| does not indicate the
+ // intend to close the dialog, but it is indeed only called when we are
+ // closing it, so requesting closing the page here is appropriate. One might
+ // think we should actually do all of this in |OnDialogCloseRequested|
+ // instead, but unfortunately that function is called after the web content is
+ // closed.
+ return installer_ui_ == nullptr || installer_ui_->RequestClosePage();
}
void CrostiniInstallerDialog::OnDialogShown(content::WebUI* webui) {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_page_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_page_handler.cc
index 0bd746d7079..306b66c00bd 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_page_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_page_handler.cc
@@ -29,11 +29,11 @@ CrostiniInstallerPageHandler::CrostiniInstallerPageHandler(
mojo::PendingReceiver<chromeos::crostini_installer::mojom::PageHandler>
pending_page_handler,
mojo::PendingRemote<chromeos::crostini_installer::mojom::Page> pending_page,
- base::OnceClosure close_dialog_callback)
+ base::OnceClosure on_page_closed)
: installer_ui_delegate_{installer_ui_delegate},
receiver_{this, std::move(pending_page_handler)},
page_{std::move(pending_page)},
- close_dialog_callback_{std::move(close_dialog_callback)} {}
+ on_page_closed_{std::move(on_page_closed)} {}
CrostiniInstallerPageHandler::~CrostiniInstallerPageHandler() = default;
@@ -43,9 +43,7 @@ void CrostiniInstallerPageHandler::Install(int64_t disk_size_bytes,
if (base::FeatureList::IsEnabled(chromeos::features::kCrostiniDiskResizing)) {
options.disk_size_bytes = disk_size_bytes;
}
- if (base::FeatureList::IsEnabled(chromeos::features::kCrostiniUsername)) {
- options.container_username = username;
- }
+ options.container_username = username;
installer_ui_delegate_->Install(
std::move(options),
base::BindRepeating(&CrostiniInstallerPageHandler::OnProgressUpdate,
@@ -64,9 +62,9 @@ void CrostiniInstallerPageHandler::CancelBeforeStart() {
installer_ui_delegate_->CancelBeforeStart();
}
-void CrostiniInstallerPageHandler::Close() {
- if (close_dialog_callback_) {
- std::move(close_dialog_callback_).Run();
+void CrostiniInstallerPageHandler::OnPageClosed() {
+ if (on_page_closed_) {
+ std::move(on_page_closed_).Run();
}
}
@@ -94,6 +92,10 @@ void CrostiniInstallerPageHandler::RequestAmountOfFreeDiskSpace() {
weak_ptr_factory_.GetWeakPtr()));
}
+void CrostiniInstallerPageHandler::RequestClosePage() {
+ page_->RequestClose();
+}
+
void CrostiniInstallerPageHandler::OnAmountOfFreeDiskSpace(int64_t free_bytes) {
int64_t max_bytes = free_bytes - crostini::disk::kDiskHeadroomBytes;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_page_handler.h b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_page_handler.h
index 94128cd43f6..8794f3de1ba 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_page_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_page_handler.h
@@ -30,16 +30,19 @@ class CrostiniInstallerPageHandler
pending_page_handler,
mojo::PendingRemote<chromeos::crostini_installer::mojom::Page>
pending_page,
- base::OnceClosure close_dialog_callback);
+ base::OnceClosure on_page_closed);
~CrostiniInstallerPageHandler() override;
// chromeos::crostini_installer::mojom::PageHandler:
void Install(int64_t disk_size_bytes, const std::string& username) override;
void Cancel() override;
void CancelBeforeStart() override;
- void Close() override;
+ void OnPageClosed() override;
void RequestAmountOfFreeDiskSpace() override;
+ // Send a close request to the web page.
+ void RequestClosePage();
+
private:
void OnProgressUpdate(crostini::mojom::InstallerState installer_state,
double progress_fraction);
@@ -50,7 +53,7 @@ class CrostiniInstallerPageHandler
crostini::CrostiniInstallerUIDelegate* installer_ui_delegate_;
mojo::Receiver<chromeos::crostini_installer::mojom::PageHandler> receiver_;
mojo::Remote<chromeos::crostini_installer::mojom::Page> page_;
- base::OnceClosure close_dialog_callback_;
+ base::OnceClosure on_page_closed_;
base::WeakPtrFactory<CrostiniInstallerPageHandler> weak_ptr_factory_{this};
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_ui.cc
index 47cab7a6f56..0e249a5e3cb 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_ui.cc
@@ -23,6 +23,7 @@
#include "chromeos/constants/chromeos_features.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/text/bytes_formatting.h"
#include "ui/base/webui/web_ui_util.h"
@@ -84,6 +85,7 @@ void AddStringResources(content::WebUIDataSource* source) {
IDS_CROSTINI_INSTALLER_USERNAME_INVALID_CHARACTERS_ERROR},
{"usernameNotAvailableError",
IDS_CROSTINI_INSTALLER_USERNAME_NOT_AVAILABLE_ERROR},
+ {"customDiskSizeLabel", IDS_CROSTINI_INSTALLER_CUSTOM_DISK_SIZE_LABEL},
};
AddLocalizedStringsBulk(source, kStrings);
@@ -117,6 +119,13 @@ void AddStringResources(content::WebUIDataSource* source) {
ui::FormatBytesWithUnits(crostini::disk::kRecommendedDiskSizeBytes,
ui::DATA_UNITS_GIBIBYTE,
/*show_units=*/true)));
+ source->AddString(
+ "recommendedDiskSizeLabel",
+ l10n_util::GetStringFUTF8(
+ IDS_CROSTINI_INSTALLER_RECOMMENDED_DISK_SIZE_LABEL,
+ ui::FormatBytesWithUnits(crostini::disk::kRecommendedDiskSizeBytes,
+ ui::DATA_UNITS_GIBIBYTE,
+ /*show_units=*/true)));
source->AddString("offlineError",
l10n_util::GetStringFUTF8(
IDS_CROSTINI_INSTALLER_OFFLINE_ERROR, device_name));
@@ -130,15 +139,13 @@ CrostiniInstallerUI::CrostiniInstallerUI(content::WebUI* web_ui)
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUICrostiniInstallerHost);
auto* profile = Profile::FromWebUI(web_ui);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources chrome://test 'self';");
AddStringResources(source);
source->AddBoolean(
"diskResizingEnabled",
base::FeatureList::IsEnabled(chromeos::features::kCrostiniDiskResizing));
- source->AddBoolean(
- "crostiniCustomUsername",
- base::FeatureList::IsEnabled(chromeos::features::kCrostiniUsername));
source->AddString("defaultContainerUsername",
crostini::DefaultContainerUserNameForProfile(profile));
@@ -162,8 +169,13 @@ CrostiniInstallerUI::CrostiniInstallerUI(content::WebUI* web_ui)
CrostiniInstallerUI::~CrostiniInstallerUI() = default;
-bool CrostiniInstallerUI::can_close() {
- return can_close_;
+bool CrostiniInstallerUI::RequestClosePage() {
+ if (page_closed_ || !page_handler_) {
+ return true;
+ }
+
+ page_handler_->RequestClosePage();
+ return false;
}
void CrostiniInstallerUI::ClickInstallForTesting() {
@@ -200,12 +212,12 @@ void CrostiniInstallerUI::CreatePageHandler(
std::move(pending_page_handler), std::move(pending_page),
// Using Unretained(this) because |page_handler_| will not out-live
// |this|.
- base::BindOnce(&CrostiniInstallerUI::OnWebUICloseDialog,
+ base::BindOnce(&CrostiniInstallerUI::OnPageClosed,
base::Unretained(this)));
}
-void CrostiniInstallerUI::OnWebUICloseDialog() {
- can_close_ = true;
+void CrostiniInstallerUI::OnPageClosed() {
+ page_closed_ = true;
// CloseDialog() is a no-op if we are not in a dialog (e.g. user
// access the page using the URL directly, which is not supported).
ui::MojoWebDialogUI::CloseDialog(nullptr);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_ui.h b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_ui.h
index 8f4fee5f139..de78f42ac95 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_installer/crostini_installer_ui.h
@@ -24,7 +24,10 @@ class CrostiniInstallerUI
explicit CrostiniInstallerUI(content::WebUI* web_ui);
~CrostiniInstallerUI() override;
- bool can_close();
+ // Send a close request to the web page. Return true if the page is already
+ // closed.
+ bool RequestClosePage();
+
void ClickInstallForTesting();
// Instantiates implementor of the mojom::PageHandlerFactory
@@ -41,12 +44,12 @@ class CrostiniInstallerUI
mojo::PendingReceiver<chromeos::crostini_installer::mojom::PageHandler>
pending_page_handler) override;
- void OnWebUICloseDialog();
+ void OnPageClosed();
std::unique_ptr<CrostiniInstallerPageHandler> page_handler_;
mojo::Receiver<chromeos::crostini_installer::mojom::PageHandlerFactory>
page_factory_receiver_{this};
- bool can_close_ = false;
+ bool page_closed_ = false;
WEB_UI_CONTROLLER_TYPE_DECL();
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader.mojom b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader.mojom
index 7f01682dc54..94cf4daa863 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader.mojom
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader.mojom
@@ -42,10 +42,15 @@ interface PageHandler {
CancelBeforeStart();
// If an upgrade fails, the user may choose to restore a container backup.
Restore();
- // The page normally is displayed in a dialog. Call this to close the dialog.
- // chrome.send('dialogClose') should not be used, which could kill the page
- // handler before previous mojom calls have been run.
- Close();
+ // This is called when the web page is "closed", and the dialog (or whatever)
+ // hosting it should also be closed. This can happen as a result of
+ // Page::RequestClose() being called, or it can happen spontaneously (e.g.
+ // user clicking cancel on the page or installation finished).
+ //
+ // Note that the web page should not use something like
+ // chrome.send('dialogClose'), which could kill the page handler before
+ // previous mojom calls have been run.
+ OnPageClosed();
// Close the dialog and launch the Terminal or other app after a successful
// upgrade.
Launch();
@@ -81,4 +86,7 @@ interface Page {
// After user cancels the upgrade, this is called when the cancellation
// finishes.
OnCanceled();
+ // Informs the page that it should be closed. The page should respond with
+ // PageHandler::OnPageClosed() to indicate it is ready to be closed.
+ RequestClose();
};
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.cc
index 11110bd02dc..9860f0058e0 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.cc
@@ -4,8 +4,11 @@
#include "chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.h"
+#include "ash/public/cpp/shelf_types.h"
+#include "ash/public/cpp/window_properties.h"
#include "base/metrics/histogram_functions.h"
#include "chrome/browser/chromeos/crostini/crostini_manager.h"
+#include "chrome/browser/chromeos/crostini/crostini_shelf_utils.h"
#include "chrome/browser/chromeos/crostini/crostini_simple_types.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_ui.h"
@@ -35,8 +38,7 @@ void CrostiniUpgraderDialog::Show(base::OnceClosure launch_closure,
instance = new CrostiniUpgraderDialog(std::move(launch_closure),
only_run_launch_closure_on_restart);
instance->ShowSystemDialog();
- base::UmaHistogramEnumeration(crostini::kUpgradeDialogEventHistogram,
- crostini::UpgradeDialogEvent::kDialogShown);
+ EmitUpgradeDialogEventHistogram(crostini::UpgradeDialogEvent::kDialogShown);
}
CrostiniUpgraderDialog::CrostiniUpgraderDialog(
@@ -67,6 +69,10 @@ bool CrostiniUpgraderDialog::ShouldCloseDialogOnEscape() const {
void CrostiniUpgraderDialog::AdjustWidgetInitParams(
views::Widget::InitParams* params) {
params->z_order = ui::ZOrderLevel::kNormal;
+
+ const ash::ShelfID shelf_id(crostini::kCrostiniUpgraderShelfId);
+ params->init_properties_container.SetProperty(ash::kShelfIDKey,
+ shelf_id.Serialize());
}
void CrostiniUpgraderDialog::SetDeletionClosureForTesting(
@@ -83,7 +89,14 @@ bool CrostiniUpgraderDialog::CanCloseDialog() const {
return true;
}
// Disallow closing without WebUI consent.
- return upgrader_ui_ == nullptr || upgrader_ui_->can_close();
+ //
+ // Note that while the function name |CanCloseDialog| does not indicate the
+ // intend to close the dialog, but it is indeed only called when we are
+ // closing it, so requesting closing the page here is appropriate. One might
+ // think we should actually do all of this in |OnDialogCloseRequested|
+ // instead, but unfortunately that function is called after the web content is
+ // closed.
+ return upgrader_ui_ == nullptr || upgrader_ui_->RequestClosePage();
}
namespace {
@@ -101,7 +114,7 @@ void RunLaunchClosure(base::WeakPtr<crostini::CrostiniManager> crostini_manager,
return;
}
crostini_manager->RestartCrostini(
- crostini::kCrostiniDefaultVmName, crostini::kCrostiniDefaultContainerName,
+ crostini::ContainerId::GetDefault(),
base::BindOnce(
[](base::OnceClosure launch_closure,
crostini::CrostiniResult result) {
@@ -122,9 +135,7 @@ void CrostiniUpgraderDialog::OnDialogShown(content::WebUI* webui) {
crostini::CrostiniManager::GetForProfile(Profile::FromWebUI(webui));
crostini_manager->SetCrostiniDialogStatus(crostini::DialogType::UPGRADER,
true);
- crostini_manager->UpgradePromptShown(
- crostini::ContainerId(crostini::kCrostiniDefaultVmName,
- crostini::kCrostiniDefaultContainerName));
+ crostini_manager->UpgradePromptShown(crostini::ContainerId::GetDefault());
upgrader_ui_ = static_cast<CrostiniUpgraderUI*>(webui->GetController());
upgrader_ui_->set_launch_callback(base::BindOnce(
@@ -143,4 +154,9 @@ void CrostiniUpgraderDialog::OnCloseContents(content::WebContents* source,
return SystemWebDialogDelegate::OnCloseContents(source, out_close_dialog);
}
+void CrostiniUpgraderDialog::EmitUpgradeDialogEventHistogram(
+ crostini::UpgradeDialogEvent event) {
+ base::UmaHistogramEnumeration("Crostini.UpgradeDialogEvent", event);
+}
+
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.h
index 7f1a2195063..356b0403b47 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.h
@@ -5,6 +5,7 @@
#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_CROSTINI_UPGRADER_CROSTINI_UPGRADER_DIALOG_H_
#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_CROSTINI_UPGRADER_CROSTINI_UPGRADER_DIALOG_H_
+#include "chrome/browser/chromeos/crostini/crostini_simple_types.h"
#include "chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.h"
namespace chromeos {
@@ -25,6 +26,9 @@ class CrostiniUpgraderDialog : public SystemWebDialogDelegate {
void SetDeletionClosureForTesting(
base::OnceClosure deletion_closure_for_testing);
+ static void EmitUpgradeDialogEventHistogram(
+ crostini::UpgradeDialogEvent event);
+
private:
explicit CrostiniUpgraderDialog(base::OnceClosure launch_closure,
bool only_run_launch_closure_on_restart);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog_browsertest.cc b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog_browsertest.cc
index 48239a18d87..d1c08e6622b 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog_browsertest.cc
@@ -90,8 +90,7 @@ class CrostiniUpgraderDialogBrowserTest : public CrostiniDialogBrowserTest {
os_release.set_id("debian");
os_release.set_version_id("9");
auto container_id = crostini::DefaultContainerId();
- crostini_manager()->SetContainerOsRelease(
- container_id.vm_name, container_id.container_name, os_release);
+ crostini_manager()->SetContainerOsRelease(container_id, os_release);
}
const std::string& app_id() const { return app_id_; }
@@ -132,7 +131,7 @@ IN_PROC_BROWSER_TEST_F(CrostiniUpgraderDialogBrowserTest, ShowsOnAppLaunch) {
ExpectNoDialog();
histogram_tester.ExpectUniqueSample(
- crostini::kUpgradeDialogEventHistogram,
+ "Crostini.UpgradeDialogEvent",
static_cast<base::HistogramBase::Sample>(
crostini::UpgradeDialogEvent::kDialogShown),
1);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_page_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_page_handler.cc
index fd13e73652c..b16643e8411 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_page_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_page_handler.cc
@@ -22,13 +22,13 @@ CrostiniUpgraderPageHandler::CrostiniUpgraderPageHandler(
mojo::PendingReceiver<chromeos::crostini_upgrader::mojom::PageHandler>
pending_page_handler,
mojo::PendingRemote<chromeos::crostini_upgrader::mojom::Page> pending_page,
- base::OnceClosure close_dialog_callback,
+ base::OnceClosure on_page_closed,
base::OnceCallback<void(bool)> launch_callback)
: web_contents_{web_contents},
upgrader_ui_delegate_{upgrader_ui_delegate},
receiver_{this, std::move(pending_page_handler)},
page_{std::move(pending_page)},
- close_dialog_callback_{std::move(close_dialog_callback)},
+ on_page_closed_{std::move(on_page_closed)},
launch_callback_{std::move(launch_callback)} {
upgrader_ui_delegate_->AddObserver(this);
}
@@ -49,14 +49,17 @@ void CrostiniUpgraderPageHandler::OnBackupMaybeStarted(bool did_start) {
Redisplay();
}
+// Send a close request to the web page.
+void CrostiniUpgraderPageHandler::RequestClosePage() {
+ page_->RequestClose();
+}
+
void CrostiniUpgraderPageHandler::Backup(bool show_file_chooser) {
Redisplay();
- base::UmaHistogramEnumeration(crostini::kUpgradeDialogEventHistogram,
- crostini::UpgradeDialogEvent::kDidBackup);
- upgrader_ui_delegate_->Backup(
- crostini::ContainerId(crostini::kCrostiniDefaultVmName,
- crostini::kCrostiniDefaultContainerName),
- show_file_chooser, web_contents_);
+ CrostiniUpgraderDialog::EmitUpgradeDialogEventHistogram(
+ crostini::UpgradeDialogEvent::kDidBackup);
+ upgrader_ui_delegate_->Backup(crostini::ContainerId::GetDefault(),
+ show_file_chooser, web_contents_);
}
void CrostiniUpgraderPageHandler::StartPrechecks() {
@@ -65,24 +68,20 @@ void CrostiniUpgraderPageHandler::StartPrechecks() {
void CrostiniUpgraderPageHandler::Upgrade() {
Redisplay();
- upgrader_ui_delegate_->Upgrade(
- crostini::ContainerId(crostini::kCrostiniDefaultVmName,
- crostini::kCrostiniDefaultContainerName));
+ upgrader_ui_delegate_->Upgrade(crostini::ContainerId::GetDefault());
}
void CrostiniUpgraderPageHandler::Restore() {
Redisplay();
- base::UmaHistogramEnumeration(crostini::kUpgradeDialogEventHistogram,
- crostini::UpgradeDialogEvent::kDidRestore);
- upgrader_ui_delegate_->Restore(
- crostini::ContainerId(crostini::kCrostiniDefaultVmName,
- crostini::kCrostiniDefaultContainerName),
- web_contents_);
+ CrostiniUpgraderDialog::EmitUpgradeDialogEventHistogram(
+ crostini::UpgradeDialogEvent::kDidRestore);
+ upgrader_ui_delegate_->Restore(crostini::ContainerId::GetDefault(),
+ web_contents_);
}
void CrostiniUpgraderPageHandler::Cancel() {
- base::UmaHistogramEnumeration(crostini::kUpgradeDialogEventHistogram,
- crostini::UpgradeDialogEvent::kUpgradeCanceled);
+ CrostiniUpgraderDialog::EmitUpgradeDialogEventHistogram(
+ crostini::UpgradeDialogEvent::kUpgradeCanceled);
upgrader_ui_delegate_->Cancel();
}
@@ -91,8 +90,8 @@ void CrostiniUpgraderPageHandler::Launch() {
}
void CrostiniUpgraderPageHandler::CancelBeforeStart() {
- base::UmaHistogramEnumeration(crostini::kUpgradeDialogEventHistogram,
- crostini::UpgradeDialogEvent::kNotStarted);
+ CrostiniUpgraderDialog::EmitUpgradeDialogEventHistogram(
+ crostini::UpgradeDialogEvent::kNotStarted);
restart_required_ = false;
upgrader_ui_delegate_->CancelBeforeStart();
if (launch_callback_) {
@@ -101,12 +100,12 @@ void CrostiniUpgraderPageHandler::CancelBeforeStart() {
}
}
-void CrostiniUpgraderPageHandler::Close() {
+void CrostiniUpgraderPageHandler::OnPageClosed() {
if (launch_callback_) {
Launch();
}
- if (close_dialog_callback_) {
- std::move(close_dialog_callback_).Run();
+ if (on_page_closed_) {
+ std::move(on_page_closed_).Run();
}
}
@@ -117,15 +116,15 @@ void CrostiniUpgraderPageHandler::OnUpgradeProgress(
void CrostiniUpgraderPageHandler::OnUpgradeSucceeded() {
Redisplay();
- base::UmaHistogramEnumeration(crostini::kUpgradeDialogEventHistogram,
- crostini::UpgradeDialogEvent::kUpgradeSuccess);
+ CrostiniUpgraderDialog::EmitUpgradeDialogEventHistogram(
+ crostini::UpgradeDialogEvent::kUpgradeSuccess);
page_->OnUpgradeSucceeded();
}
void CrostiniUpgraderPageHandler::OnUpgradeFailed() {
Redisplay();
- base::UmaHistogramEnumeration(crostini::kUpgradeDialogEventHistogram,
- crostini::UpgradeDialogEvent::kUpgradeFailed);
+ CrostiniUpgraderDialog::EmitUpgradeDialogEventHistogram(
+ crostini::UpgradeDialogEvent::kUpgradeFailed);
page_->OnUpgradeFailed();
}
@@ -135,15 +134,15 @@ void CrostiniUpgraderPageHandler::OnBackupProgress(int percent) {
void CrostiniUpgraderPageHandler::OnBackupSucceeded(bool was_cancelled) {
Redisplay();
- base::UmaHistogramEnumeration(crostini::kUpgradeDialogEventHistogram,
- crostini::UpgradeDialogEvent::kBackupSucceeded);
+ CrostiniUpgraderDialog::EmitUpgradeDialogEventHistogram(
+ crostini::UpgradeDialogEvent::kBackupSucceeded);
page_->OnBackupSucceeded(was_cancelled);
}
void CrostiniUpgraderPageHandler::OnBackupFailed() {
Redisplay();
- base::UmaHistogramEnumeration(crostini::kUpgradeDialogEventHistogram,
- crostini::UpgradeDialogEvent::kBackupFailed);
+ CrostiniUpgraderDialog::EmitUpgradeDialogEventHistogram(
+ crostini::UpgradeDialogEvent::kBackupFailed);
page_->OnBackupFailed();
}
@@ -158,16 +157,15 @@ void CrostiniUpgraderPageHandler::OnRestoreProgress(int percent) {
void CrostiniUpgraderPageHandler::OnRestoreSucceeded() {
Redisplay();
- base::UmaHistogramEnumeration(
- crostini::kUpgradeDialogEventHistogram,
+ CrostiniUpgraderDialog::EmitUpgradeDialogEventHistogram(
crostini::UpgradeDialogEvent::kRestoreSucceeded);
page_->OnRestoreSucceeded();
}
void CrostiniUpgraderPageHandler::OnRestoreFailed() {
Redisplay();
- base::UmaHistogramEnumeration(crostini::kUpgradeDialogEventHistogram,
- crostini::UpgradeDialogEvent::kRestoreFailed);
+ CrostiniUpgraderDialog::EmitUpgradeDialogEventHistogram(
+ crostini::UpgradeDialogEvent::kRestoreFailed);
page_->OnRestoreFailed();
}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_page_handler.h b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_page_handler.h
index edf98821f6e..01c0ac74c9c 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_page_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_page_handler.h
@@ -32,10 +32,13 @@ class CrostiniUpgraderPageHandler
pending_page_handler,
mojo::PendingRemote<chromeos::crostini_upgrader::mojom::Page>
pending_page,
- base::OnceClosure close_dialog_callback,
+ base::OnceClosure on_page_closed,
base::OnceCallback<void(bool)> launch_callback);
~CrostiniUpgraderPageHandler() override;
+ // Send a close request to the web page.
+ void RequestClosePage();
+
// chromeos::crostini_upgrader::mojom::PageHandler:
void Backup(bool show_file_chooser) override;
void StartPrechecks() override;
@@ -43,7 +46,7 @@ class CrostiniUpgraderPageHandler
void Restore() override;
void Cancel() override;
void CancelBeforeStart() override;
- void Close() override;
+ void OnPageClosed() override;
void Launch() override;
// CrostiniUpgraderUIObserver
@@ -68,7 +71,7 @@ class CrostiniUpgraderPageHandler
crostini::CrostiniUpgraderUIDelegate* upgrader_ui_delegate_; // Not owned.
mojo::Receiver<chromeos::crostini_upgrader::mojom::PageHandler> receiver_;
mojo::Remote<chromeos::crostini_upgrader::mojom::Page> page_;
- base::OnceClosure close_dialog_callback_;
+ base::OnceClosure on_page_closed_;
base::OnceCallback<void(bool)> launch_callback_;
// Will we need to restart the container as part of launch_callback?
// |restart_required_| is true unless the user cancels before starting the
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_ui.cc
index 8d195a25f0e..a9dbb7b64c1 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_ui.cc
@@ -21,6 +21,7 @@
#include "chromeos/constants/chromeos_features.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/text/bytes_formatting.h"
#include "ui/base/webui/web_ui_util.h"
@@ -97,7 +98,8 @@ CrostiniUpgraderUI::CrostiniUpgraderUI(content::WebUI* web_ui)
: ui::MojoWebDialogUI{web_ui} {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUICrostiniUpgraderHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources chrome://test 'self';");
AddStringResources(source);
@@ -122,6 +124,15 @@ CrostiniUpgraderUI::CrostiniUpgraderUI(content::WebUI* web_ui)
CrostiniUpgraderUI::~CrostiniUpgraderUI() = default;
+bool CrostiniUpgraderUI::RequestClosePage() {
+ if (page_closed_ || !page_handler_) {
+ return true;
+ }
+
+ page_handler_->RequestClosePage();
+ return false;
+}
+
void CrostiniUpgraderUI::BindInterface(
mojo::PendingReceiver<
chromeos::crostini_upgrader::mojom::PageHandlerFactory>
@@ -145,13 +156,12 @@ void CrostiniUpgraderUI::CreatePageHandler(
std::move(pending_page_handler), std::move(pending_page),
// Using Unretained(this) because |page_handler_| will not out-live
// |this|.
- base::BindOnce(&CrostiniUpgraderUI::OnWebUICloseDialog,
- base::Unretained(this)),
+ base::BindOnce(&CrostiniUpgraderUI::OnPageClosed, base::Unretained(this)),
std::move(launch_callback_));
}
-void CrostiniUpgraderUI::OnWebUICloseDialog() {
- can_close_ = true;
+void CrostiniUpgraderUI::OnPageClosed() {
+ page_closed_ = true;
// CloseDialog() is a no-op if we are not in a dialog (e.g. user
// access the page using the URL directly, which is not supported).
ui::MojoWebDialogUI::CloseDialog(nullptr);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_ui.h b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_ui.h
index 6126283abd6..13c5605c215 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_ui.h
@@ -27,7 +27,10 @@ class CrostiniUpgraderUI
explicit CrostiniUpgraderUI(content::WebUI* web_ui);
~CrostiniUpgraderUI() override;
- bool can_close() { return can_close_; }
+ // Send a close request to the web page. Return true if the page is already
+ // closed.
+ bool RequestClosePage();
+
void set_launch_callback(base::OnceCallback<void(bool)>(launch_callback)) {
launch_callback_ = std::move(launch_callback);
}
@@ -47,7 +50,7 @@ class CrostiniUpgraderUI
mojo::PendingReceiver<chromeos::crostini_upgrader::mojom::PageHandler>
pending_page_handler) override;
- void OnWebUICloseDialog();
+ void OnPageClosed();
std::unique_ptr<CrostiniUpgraderPageHandler> page_handler_;
mojo::Receiver<chromeos::crostini_upgrader::mojom::PageHandlerFactory>
@@ -56,7 +59,7 @@ class CrostiniUpgraderUI
// Not owned. Passed to |page_handler_|
base::OnceCallback<void(bool)> launch_callback_;
- bool can_close_ = false;
+ bool page_closed_ = false;
WEB_UI_CONTROLLER_TYPE_DECL();
diff --git a/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc
index 0611cef1174..6a9d0c38941 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc
@@ -5,7 +5,6 @@
#include "chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.h"
#include "base/bind.h"
-#include "base/task/post_task.h"
#include "base/values.h"
#include "chromeos/dbus/cryptohome/cryptohome_client.h"
#include "chromeos/dbus/dbus_thread_manager.h"
@@ -40,9 +39,8 @@ void CryptohomeWebUIHandler::OnPageLoaded(const base::ListValue* args) {
cryptohome_client->Pkcs11IsTpmTokenReady(
GetCryptohomeBoolCallback("pkcs11-is-tpm-token-ready"));
- base::PostTaskAndReplyWithResult(
- FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&crypto::IsTPMTokenReady, base::Closure()),
+ content::GetIOThreadTaskRunner({})->PostTaskAndReplyWithResult(
+ FROM_HERE, base::BindOnce(&crypto::IsTPMTokenReady, base::Closure()),
base::BindOnce(&CryptohomeWebUIHandler::DidGetNSSUtilInfoOnUIThread,
weak_ptr_factory_.GetWeakPtr()));
}
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 4333fb4d05c..3345379fa27 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/drive_internals_ui.cc
@@ -22,6 +22,7 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
+#include "base/process/launch.h"
#include "base/strings/pattern.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
@@ -217,6 +218,14 @@ std::pair<ino_t, base::ListValue> GetServiceLogContents(
return {inode, std::move(result)};
}
+bool GetDeveloperMode() {
+ std::string output;
+ if (!base::GetAppOutput({"/usr/bin/crossystem", "cros_debug"}, &output)) {
+ return false;
+ }
+ return output == "1";
+}
+
class DriveInternalsWebUIHandler;
void ZipLogs(Profile* profile,
@@ -263,6 +272,19 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
base::BindRepeating(&DriveInternalsWebUIHandler::OnPeriodicUpdate,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback(
+ "setVerboseLoggingEnabled",
+ base::BindRepeating(
+ &DriveInternalsWebUIHandler::SetVerboseLoggingEnabled,
+ weak_ptr_factory_.GetWeakPtr()));
+ web_ui()->RegisterMessageCallback(
+ "enableTracing",
+ base::BindRepeating(&DriveInternalsWebUIHandler::SetTracingEnabled,
+ weak_ptr_factory_.GetWeakPtr(), true));
+ web_ui()->RegisterMessageCallback(
+ "disableTracing",
+ base::BindRepeating(&DriveInternalsWebUIHandler::SetTracingEnabled,
+ weak_ptr_factory_.GetWeakPtr(), false));
+ web_ui()->RegisterMessageCallback(
"restartDrive",
base::BindRepeating(&DriveInternalsWebUIHandler::RestartDrive,
weak_ptr_factory_.GetWeakPtr()));
@@ -276,6 +298,38 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
weak_ptr_factory_.GetWeakPtr()));
}
+ void RegisterDeveloperMessages() {
+ CHECK(developer_mode_);
+ web_ui()->RegisterMessageCallback(
+ "setStartupArguments",
+ base::BindRepeating(&DriveInternalsWebUIHandler::SetStartupArguments,
+ weak_ptr_factory_.GetWeakPtr()));
+ web_ui()->RegisterMessageCallback(
+ "enableNetworking",
+ base::BindRepeating(&DriveInternalsWebUIHandler::SetNetworkingEnabled,
+ weak_ptr_factory_.GetWeakPtr(), true));
+ web_ui()->RegisterMessageCallback(
+ "disableNetworking",
+ base::BindRepeating(&DriveInternalsWebUIHandler::SetNetworkingEnabled,
+ weak_ptr_factory_.GetWeakPtr(), false));
+ web_ui()->RegisterMessageCallback(
+ "enableForcePauseSyncing",
+ base::BindRepeating(&DriveInternalsWebUIHandler::ForcePauseSyncing,
+ weak_ptr_factory_.GetWeakPtr(), true));
+ web_ui()->RegisterMessageCallback(
+ "disableForcePauseSyncing",
+ base::BindRepeating(&DriveInternalsWebUIHandler::ForcePauseSyncing,
+ weak_ptr_factory_.GetWeakPtr(), false));
+ web_ui()->RegisterMessageCallback(
+ "dumpAccountSettings",
+ base::BindRepeating(&DriveInternalsWebUIHandler::DumpAccountSettings,
+ weak_ptr_factory_.GetWeakPtr()));
+ web_ui()->RegisterMessageCallback(
+ "loadAccountSettings",
+ base::BindRepeating(&DriveInternalsWebUIHandler::LoadAccountSettings,
+ weak_ptr_factory_.GetWeakPtr()));
+ }
+
// Called when the page is first loaded.
void OnPageLoaded(const base::ListValue* args) {
AllowJavascript();
@@ -410,6 +464,17 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
void UpdateDriveDebugSection() {
SetSectionEnabled("drive-debug", true);
+ bool verbose_logging_enabled = profile()->GetPrefs()->GetBoolean(
+ drive::prefs::kDriveFsEnableVerboseLogging);
+ MaybeCallJavascript("updateVerboseLogging",
+ base::Value(verbose_logging_enabled));
+
+ base::ThreadPool::PostTaskAndReplyWithResult(
+ FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
+ base::BindOnce(GetDeveloperMode),
+ base::BindOnce(&DriveInternalsWebUIHandler::OnGetDeveloperMode,
+ weak_ptr_factory_.GetWeakPtr()));
+
// Propagate the amount of local free space in bytes.
base::FilePath home_path;
if (base::PathService::Get(base::DIR_HOME, &home_path)) {
@@ -423,6 +488,33 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
}
}
+ // Called when GetDeveloperMode() is complete.
+ void OnGetDeveloperMode(bool enabled) {
+ developer_mode_ = enabled;
+ if (!enabled) {
+ return;
+ }
+
+ RegisterDeveloperMessages();
+
+ // Get the startup arguments.
+ drive::DriveIntegrationService* integration_service =
+ GetIntegrationService();
+ if (integration_service) {
+ integration_service->GetStartupArguments(
+ base::BindOnce(&DriveInternalsWebUIHandler::OnGetStartupArguments,
+ weak_ptr_factory_.GetWeakPtr()));
+ }
+ }
+
+ // Called when GetStartupArguments() is complete.
+ void OnGetStartupArguments(const std::string& arguments) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK(developer_mode_);
+ MaybeCallJavascript("updateStartupArguments", base::Value(arguments));
+ SetSectionEnabled("developer-mode-controls", true);
+ }
+
// Called when AmountOfFreeDiskSpace() is complete.
void OnGetFreeDiskSpace(int64_t free_space) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -440,6 +532,7 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
drive::prefs::kDisableDriveOverCellular,
drive::prefs::kDriveFsWasLaunchedAtLeastOnce,
drive::prefs::kDriveFsPinnedMigrated,
+ drive::prefs::kDriveFsEnableVerboseLogging,
};
PrefService* pref_service = profile()->GetPrefs();
@@ -552,6 +645,105 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
std::move(response.second));
}
+ // Called when the "Verbose Logging" checkbox on the page is changed.
+ void SetVerboseLoggingEnabled(const base::ListValue* args) {
+ AllowJavascript();
+ drive::DriveIntegrationService* integration_service =
+ GetIntegrationService();
+ if (!integration_service) {
+ return;
+ }
+
+ if (args->GetList().size() == 1 && args->GetList()[0].is_bool()) {
+ bool enabled = args->GetList()[0].GetBool();
+ profile()->GetPrefs()->SetBoolean(
+ drive::prefs::kDriveFsEnableVerboseLogging, enabled);
+ RestartDrive(nullptr);
+ }
+ }
+
+ // Called when the "Startup Arguments" field on the page is submitted.
+ void SetStartupArguments(const base::ListValue* args) {
+ AllowJavascript();
+
+ CHECK(developer_mode_);
+
+ if (args->GetList().size() < 1 || !args->GetList()[0].is_string()) {
+ OnSetStartupArguments(false);
+ return;
+ }
+
+ drive::DriveIntegrationService* integration_service =
+ GetIntegrationService();
+ if (!integration_service) {
+ OnSetStartupArguments(false);
+ return;
+ }
+
+ integration_service->SetStartupArguments(
+ args->GetList()[0].GetString(),
+ base::BindOnce(&DriveInternalsWebUIHandler::OnSetStartupArguments,
+ weak_ptr_factory_.GetWeakPtr()));
+ }
+
+ void OnSetStartupArguments(bool success) {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK(developer_mode_);
+ if (success) {
+ RestartDrive(nullptr);
+ }
+ MaybeCallJavascript("updateStartupArgumentsStatus", base::Value(success));
+ }
+
+ void SetTracingEnabled(bool enabled, const base::ListValue* args) {
+ AllowJavascript();
+ drive::DriveIntegrationService* integration_service =
+ GetIntegrationService();
+ if (integration_service) {
+ integration_service->SetTracingEnabled(enabled);
+ }
+ }
+
+ void SetNetworkingEnabled(bool enabled, const base::ListValue* args) {
+ AllowJavascript();
+ CHECK(developer_mode_);
+ drive::DriveIntegrationService* integration_service =
+ GetIntegrationService();
+ if (integration_service) {
+ integration_service->SetNetworkingEnabled(enabled);
+ }
+ }
+
+ void ForcePauseSyncing(bool enabled, const base::ListValue* args) {
+ AllowJavascript();
+ CHECK(developer_mode_);
+ drive::DriveIntegrationService* integration_service =
+ GetIntegrationService();
+ if (integration_service) {
+ integration_service->ForcePauseSyncing(enabled);
+ }
+ }
+
+ void DumpAccountSettings(const base::ListValue* args) {
+ AllowJavascript();
+ CHECK(developer_mode_);
+ drive::DriveIntegrationService* integration_service =
+ GetIntegrationService();
+ if (integration_service) {
+ integration_service->DumpAccountSettings();
+ }
+ }
+
+ void LoadAccountSettings(const base::ListValue* args) {
+ AllowJavascript();
+ CHECK(developer_mode_);
+ drive::DriveIntegrationService* integration_service =
+ GetIntegrationService();
+ if (integration_service) {
+ integration_service->LoadAccountSettings();
+ }
+ }
+
// Called when the "Restart Drive" button on the page is pressed.
void RestartDrive(const base::ListValue* args) {
AllowJavascript();
@@ -619,6 +811,9 @@ class DriveInternalsWebUIHandler : public content::WebUIMessageHandler {
// Service log file is being parsed.
bool service_log_file_is_processing_ = false;
+ // Whether developer mode is enabled for debug commands.
+ bool developer_mode_ = false;
+
base::WeakPtrFactory<DriveInternalsWebUIHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DriveInternalsWebUIHandler);
};
@@ -695,8 +890,7 @@ class LogsZipper : public download::AllDownloadItemNotifier::Observer {
void CleanUp() {
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
- base::BindOnce(base::IgnoreResult(&base::DeleteFile), zip_path_,
- false));
+ base::BindOnce(base::GetDeleteFileCallback(), zip_path_));
download_notifier_.reset();
if (drive_internals_) {
drive_internals_->OnZipDone();
diff --git a/chromium/chrome/browser/ui/webui/chromeos/edu_account_login_handler_chromeos.cc b/chromium/chrome/browser/ui/webui/chromeos/edu_account_login_handler_chromeos.cc
index 99f1d0742c2..a0611a51052 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/edu_account_login_handler_chromeos.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/edu_account_login_handler_chromeos.cc
@@ -18,7 +18,7 @@
#include "chrome/browser/profiles/profile_key.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/identity_manager_factory.h"
-#include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h"
+#include "chrome/browser/ui/webui/signin/inline_login_dialog_chromeos.h"
#include "chromeos/components/account_manager/account_manager.h"
#include "chromeos/components/account_manager/account_manager_factory.h"
#include "components/image_fetcher/core/image_fetcher_service.h"
@@ -193,11 +193,11 @@ void EduAccountLoginHandler::HandleUpdateEduCoexistenceFlowResult(
const base::Value::ConstListView& args_list = args->GetList();
CHECK_EQ(args_list.size(), 1u);
int result = args_list[0].GetInt();
- DCHECK(result <= static_cast<int>(InlineLoginHandlerDialogChromeOS::
- EduCoexistenceFlowResult::kMaxValue));
- InlineLoginHandlerDialogChromeOS::UpdateEduCoexistenceFlowResult(
- static_cast<InlineLoginHandlerDialogChromeOS::EduCoexistenceFlowResult>(
- result));
+ DCHECK(result <=
+ static_cast<int>(
+ InlineLoginDialogChromeOS::EduCoexistenceFlowResult::kMaxValue));
+ InlineLoginDialogChromeOS::UpdateEduCoexistenceFlowResult(
+ static_cast<InlineLoginDialogChromeOS::EduCoexistenceFlowResult>(result));
}
void EduAccountLoginHandler::FetchFamilyMembers() {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc
index 93318f93336..40bff048c98 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.cc
@@ -91,11 +91,10 @@ class DeviceEmulatorMessageHandler::BluetoothObserver
void DeviceEmulatorMessageHandler::BluetoothObserver::DeviceAdded(
const dbus::ObjectPath& object_path) {
- std::unique_ptr<base::DictionaryValue> device =
- owner_->GetDeviceInfo(object_path);
+ base::Value device = owner_->GetDeviceInfo(object_path);
// Request to add the device to the view's list of devices.
- owner_->FireWebUIListener("bluetooth-device-added", *device);
+ owner_->FireWebUIListener("bluetooth-device-added", device);
}
void DeviceEmulatorMessageHandler::BluetoothObserver::DevicePropertyChanged(
@@ -223,42 +222,40 @@ void DeviceEmulatorMessageHandler::HandleRequestBluetoothInfo(
fake_bluetooth_device_client_->GetDevicesForAdapter(
dbus::ObjectPath(bluez::FakeBluetoothAdapterClient::kAdapterPath));
- auto devices = std::make_unique<base::ListValue>();
// Get each device's properties.
- for (const dbus::ObjectPath& path : paths) {
- std::unique_ptr<base::DictionaryValue> device = GetDeviceInfo(path);
- devices->Append(std::move(device));
- }
+ base::Value devices(base::Value::Type::LIST);
+ for (const dbus::ObjectPath& path : paths)
+ devices.Append(GetDeviceInfo(path));
- std::unique_ptr<base::ListValue> predefined_devices =
+ base::Value predefined_devices =
fake_bluetooth_device_client_->GetBluetoothDevicesAsDictionaries();
- auto pairing_method_options = std::make_unique<base::ListValue>();
- pairing_method_options->AppendString(
+ base::Value pairing_method_options(base::Value::Type::LIST);
+ pairing_method_options.Append(
bluez::FakeBluetoothDeviceClient::kPairingMethodNone);
- pairing_method_options->AppendString(
+ pairing_method_options.Append(
bluez::FakeBluetoothDeviceClient::kPairingMethodPinCode);
- pairing_method_options->AppendString(
+ pairing_method_options.Append(
bluez::FakeBluetoothDeviceClient::kPairingMethodPassKey);
- auto pairing_action_options = std::make_unique<base::ListValue>();
- pairing_action_options->AppendString(
+ base::Value pairing_action_options(base::Value::Type::LIST);
+ pairing_action_options.Append(
bluez::FakeBluetoothDeviceClient::kPairingActionDisplay);
- pairing_action_options->AppendString(
+ pairing_action_options.Append(
bluez::FakeBluetoothDeviceClient::kPairingActionRequest);
- pairing_action_options->AppendString(
+ pairing_action_options.Append(
bluez::FakeBluetoothDeviceClient::kPairingActionConfirmation);
- pairing_action_options->AppendString(
+ pairing_action_options.Append(
bluez::FakeBluetoothDeviceClient::kPairingActionFail);
- auto info = std::make_unique<base::DictionaryValue>();
- info->Set("predefined_devices", std::move(predefined_devices));
- info->Set("devices", std::move(devices));
- info->Set("pairing_method_options", std::move(pairing_method_options));
- info->Set("pairing_action_options", std::move(pairing_action_options));
+ base::Value info(base::Value::Type::DICTIONARY);
+ info.SetKey("predefined_devices", std::move(predefined_devices));
+ info.SetKey("devices", std::move(devices));
+ info.SetKey("pairing_method_options", std::move(pairing_method_options));
+ info.SetKey("pairing_action_options", std::move(pairing_action_options));
// Send the list of devices to the view.
- FireWebUIListener("bluetooth-info-updated", *info);
+ FireWebUIListener("bluetooth-info-updated", info);
}
void DeviceEmulatorMessageHandler::HandleRequestBluetoothPair(
@@ -579,39 +576,36 @@ std::string DeviceEmulatorMessageHandler::CreateBluetoothDeviceFromListValue(
return props.device_path;
}
-std::unique_ptr<base::DictionaryValue>
-DeviceEmulatorMessageHandler::GetDeviceInfo(
+base::Value DeviceEmulatorMessageHandler::GetDeviceInfo(
const dbus::ObjectPath& object_path) {
// Get the device's properties.
bluez::FakeBluetoothDeviceClient::Properties* props =
fake_bluetooth_device_client_->GetProperties(object_path);
- std::unique_ptr<base::DictionaryValue> device(new base::DictionaryValue());
- std::unique_ptr<base::ListValue> uuids(new base::ListValue);
bluez::FakeBluetoothDeviceClient::SimulatedPairingOptions* options =
fake_bluetooth_device_client_->GetPairingOptions(object_path);
- device->SetString("path", object_path.value());
- device->SetString("name", props->name.value());
- device->SetString("alias", props->alias.value());
- device->SetString("address", props->address.value());
+ base::Value device(base::Value::Type::DICTIONARY);
+ device.SetStringKey("path", object_path.value());
+ device.SetStringKey("name", props->name.value());
+ device.SetStringKey("alias", props->alias.value());
+ device.SetStringKey("address", props->address.value());
if (options) {
- device->SetString("pairingMethod", options->pairing_method);
- device->SetString("pairingAuthToken", options->pairing_auth_token);
- device->SetString("pairingAction", options->pairing_action);
+ device.SetStringKey("pairingMethod", options->pairing_method);
+ device.SetStringKey("pairingAuthToken", options->pairing_auth_token);
+ device.SetStringKey("pairingAction", options->pairing_action);
} else {
- device->SetString("pairingMethod", "");
- device->SetString("pairingAuthToken", "");
- device->SetString("pairingAction", "");
- }
- device->SetInteger("classValue", props->bluetooth_class.value());
- device->SetBoolean("isTrusted", props->trusted.value());
- device->SetBoolean("incoming", false);
-
- for (const std::string& uuid : props->uuids.value()) {
- uuids->AppendString(uuid);
+ device.SetStringKey("pairingMethod", "");
+ device.SetStringKey("pairingAuthToken", "");
+ device.SetStringKey("pairingAction", "");
}
-
- device->Set("uuids", std::move(uuids));
+ device.SetIntKey("classValue", props->bluetooth_class.value());
+ device.SetBoolKey("isTrusted", props->trusted.value());
+ device.SetBoolKey("incoming", false);
+
+ base::Value uuids(base::Value::Type::LIST);
+ for (const std::string& uuid : props->uuids.value())
+ uuids.Append(uuid);
+ device.SetKey("uuids", std::move(uuids));
return device;
}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h
index 3afd435d960..9a59d740741 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/emulator/device_emulator_message_handler.h
@@ -16,7 +16,6 @@
#include "device/bluetooth/bluetooth_adapter.h"
namespace base {
-class DictionaryValue;
class ListValue;
} // namespace base
@@ -118,8 +117,7 @@ class DeviceEmulatorMessageHandler :
// Builds a dictionary with each key representing a property of the device
// with path |object_path|.
- std::unique_ptr<base::DictionaryValue> GetDeviceInfo(
- const dbus::ObjectPath& object_path);
+ base::Value GetDeviceInfo(const dbus::ObjectPath& object_path);
void ConnectToBluetoothDevice(const std::string& address);
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
index e7edf2e630f..a8183f48709 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/OWNERS
+++ b/chromium/chrome/browser/ui/webui/chromeos/in_session_password_change/OWNERS
@@ -1,2 +1 @@
-olsen@chromium.org
rsorokin@chromium.org
diff --git a/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc
index 43f44e8bbe9..af861bf1ef7 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.cc
@@ -19,6 +19,7 @@
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "ui/wm/core/shadow_types.h"
namespace chromeos {
@@ -114,6 +115,13 @@ const std::string& InternetConfigDialog::Id() {
return dialog_id_;
}
+void InternetConfigDialog::AdjustWidgetInitParams(
+ views::Widget::InitParams* params) {
+ params->type = views::Widget::InitParams::Type::TYPE_WINDOW_FRAMELESS;
+ params->shadow_type = views::Widget::InitParams::ShadowType::kDrop;
+ params->shadow_elevation = wm::kShadowElevationActiveWindow;
+}
+
void InternetConfigDialog::GetDialogSize(gfx::Size* size) const {
const NetworkState* network =
network_id_.empty() ? nullptr
diff --git a/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.h
index f3d3dfcaf9f..4888ee69139 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/internet_config_dialog.h
@@ -25,6 +25,9 @@ class InternetConfigDialog : public SystemWebDialogDelegate {
// Shows a network configuration dialog for a new network of |network_type|.
static void ShowDialogForNetworkType(const std::string& network_type);
+ // SystemWebDialogDelegate
+ void AdjustWidgetInitParams(views::Widget::InitParams* params) override;
+
protected:
// |dialog_id| provides a pre-calculated identifier for the dialog based on
// the network type and the network id.
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/DEPS b/chromium/chrome/browser/ui/webui/chromeos/login/DEPS
index 4994ed97905..6e2f237df12 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/DEPS
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/DEPS
@@ -1,5 +1,4 @@
specific_include_rules = {
- # TODO(mash): Fix. https://crbug.com/856375.
"core_oobe_handler\.cc": [
"+ash/shell.h",
],
@@ -8,8 +7,6 @@ specific_include_rules = {
"+ash/shell.h",
],
"oobe_display_chooser_unittest.cc": [
- # TODO(mash) Use a non-ash test ui::InputDeviceEventObserver
- # environment for testing this.
"+ash/display/display_configuration_controller.h",
"+ash/shell.h",
"+ash/test/ash_test_base.h",
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc
index f2882ee9ec6..1b1f25b9582 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.cc
@@ -4,19 +4,9 @@
#include "chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h"
-#include <memory>
-
-#include "base/bind.h"
-#include "chrome/browser/chromeos/authpolicy/authpolicy_helper.h"
-#include "chrome/browser/chromeos/login/oobe_screen.h"
-#include "chrome/browser/chromeos/login/ui/login_display_host.h"
#include "chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h"
-#include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h"
#include "chrome/grit/generated_resources.h"
-#include "chromeos/login/auth/key.h"
#include "components/login/localized_values_builder.h"
-#include "components/user_manager/known_user.h"
-#include "ui/base/l10n/l10n_util.h"
namespace chromeos {
@@ -25,24 +15,19 @@ namespace {
constexpr char kUsernameKey[] = "username";
constexpr char kErrorKey[] = "error";
-// Possible error states of the Active Directory password change screen. Must be
-// in the same order as ACTIVE_DIRECTORY_PASSWORD_CHANGE_ERROR_STATE enum
-// values.
-enum class ActiveDirectoryPasswordChangeErrorState {
- WRONG_OLD_PASSWORD = 0,
- NEW_PASSWORD_REJECTED = 1,
-};
-
} // namespace
+constexpr StaticOobeScreenId ActiveDirectoryPasswordChangeView::kScreenId;
+
ActiveDirectoryPasswordChangeScreenHandler::
ActiveDirectoryPasswordChangeScreenHandler(
JSCallsContainer* js_calls_container,
CoreOobeView* core_oobe_view)
- : BaseScreenHandler(OobeScreen::SCREEN_ACTIVE_DIRECTORY_PASSWORD_CHANGE,
- js_calls_container),
- authpolicy_login_helper_(std::make_unique<AuthPolicyHelper>()),
- core_oobe_view_(core_oobe_view) {}
+ : BaseScreenHandler(kScreenId, js_calls_container),
+ core_oobe_view_(core_oobe_view) {
+ set_user_acted_method_path(
+ "login.ActiveDirectoryPasswordChangeScreen.userActed");
+}
ActiveDirectoryPasswordChangeScreenHandler::
~ActiveDirectoryPasswordChangeScreenHandler() {}
@@ -55,86 +40,41 @@ void ActiveDirectoryPasswordChangeScreenHandler::DeclareLocalizedValues(
void ActiveDirectoryPasswordChangeScreenHandler::Initialize() {}
void ActiveDirectoryPasswordChangeScreenHandler::RegisterMessages() {
- AddCallback("completeActiveDirectoryPasswordChange",
+ BaseScreenHandler::RegisterMessages();
+ AddCallback("login.ActiveDirectoryPasswordChangeScreen.changePassword",
&ActiveDirectoryPasswordChangeScreenHandler::HandleComplete);
- AddCallback("cancelActiveDirectoryPasswordChange",
- &ActiveDirectoryPasswordChangeScreenHandler::HandleCancel);
}
-void ActiveDirectoryPasswordChangeScreenHandler::HandleComplete(
+void ActiveDirectoryPasswordChangeScreenHandler::Show(
const std::string& username,
- const std::string& old_password,
- const std::string& new_password) {
- authpolicy_login_helper_->AuthenticateUser(
- username, std::string() /* object_guid */,
- old_password + "\n" + new_password + "\n" + new_password,
- base::BindOnce(
- &ActiveDirectoryPasswordChangeScreenHandler::OnAuthFinished,
- weak_factory_.GetWeakPtr(), username, Key(new_password)));
+ int error) {
+ base::DictionaryValue data;
+ data.SetString(kUsernameKey, username);
+ data.SetInteger(kErrorKey, error);
+ ShowScreenWithData(kScreenId, &data);
}
-void ActiveDirectoryPasswordChangeScreenHandler::HandleCancel() {
- authpolicy_login_helper_->CancelRequestsAndRestart();
+void ActiveDirectoryPasswordChangeScreenHandler::Bind(
+ ActiveDirectoryPasswordChangeScreen* screen) {
+ screen_ = screen;
+ BaseScreenHandler::SetBaseScreen(screen_);
}
-void ActiveDirectoryPasswordChangeScreenHandler::ShowScreen(
- const std::string& username) {
- base::DictionaryValue data;
- data.SetString(kUsernameKey, username);
- ShowScreenWithData(OobeScreen::SCREEN_ACTIVE_DIRECTORY_PASSWORD_CHANGE,
- &data);
+void ActiveDirectoryPasswordChangeScreenHandler::Unbind() {
+ screen_ = nullptr;
+ BaseScreenHandler::SetBaseScreen(nullptr);
}
-void ActiveDirectoryPasswordChangeScreenHandler::ShowScreenWithError(
- int error) {
- base::DictionaryValue data;
- data.SetInteger(kErrorKey, error);
- ShowScreenWithData(OobeScreen::SCREEN_ACTIVE_DIRECTORY_PASSWORD_CHANGE,
- &data);
+void ActiveDirectoryPasswordChangeScreenHandler::ShowSignInError(
+ const std::string& error_text) {
+ core_oobe_view_->ShowSignInError(0, error_text, std::string(),
+ HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
}
-void ActiveDirectoryPasswordChangeScreenHandler::OnAuthFinished(
- const std::string& username,
- const Key& key,
- authpolicy::ErrorType error,
- const authpolicy::ActiveDirectoryAccountInfo& account_info) {
- switch (error) {
- case authpolicy::ERROR_NONE: {
- DCHECK(account_info.has_account_id() &&
- !account_info.account_id().empty());
- const AccountId account_id = user_manager::known_user::GetAccountId(
- username, account_info.account_id(), AccountType::ACTIVE_DIRECTORY);
- DCHECK(LoginDisplayHost::default_host());
- LoginDisplayHost::default_host()->SetDisplayAndGivenName(
- account_info.display_name(), account_info.given_name());
- UserContext user_context(
- user_manager::UserType::USER_TYPE_ACTIVE_DIRECTORY, account_id);
- user_context.SetKey(key);
- user_context.SetAuthFlow(UserContext::AUTH_FLOW_ACTIVE_DIRECTORY);
- user_context.SetIsUsingOAuth(false);
- LoginDisplayHost::default_host()->CompleteLogin(user_context);
- break;
- }
- case authpolicy::ERROR_BAD_PASSWORD:
- ShowScreenWithError(static_cast<int>(
- ActiveDirectoryPasswordChangeErrorState::WRONG_OLD_PASSWORD));
- break;
- case authpolicy::ERROR_PASSWORD_REJECTED:
- ShowScreenWithError(static_cast<int>(
- ActiveDirectoryPasswordChangeErrorState::NEW_PASSWORD_REJECTED));
- core_oobe_view_->ShowSignInError(
- 0,
- l10n_util::GetStringUTF8(
- IDS_AD_PASSWORD_CHANGE_NEW_PASSWORD_REJECTED_LONG_ERROR),
- std::string(), HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
- break;
- default:
- NOTREACHED() << "Unhandled error: " << error;
- ShowScreen(username);
- core_oobe_view_->ShowSignInError(
- 0, l10n_util::GetStringUTF8(IDS_AD_AUTH_UNKNOWN_ERROR), std::string(),
- HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
- }
+void ActiveDirectoryPasswordChangeScreenHandler::HandleComplete(
+ const std::string& old_password,
+ const std::string& new_password) {
+ screen_->ChangePassword(old_password, new_password);
}
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h
index 8768175e503..33e5eb4d230 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h
@@ -8,21 +8,42 @@
#include <string>
#include "base/macros.h"
-#include "chrome/browser/chromeos/authpolicy/authpolicy_helper.h"
+#include "chrome/browser/chromeos/login/screens/active_directory_password_change_screen.h"
#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
-namespace authpolicy {
-class ActiveDirectoryAccountInfo;
-}
-
namespace chromeos {
+class ActiveDirectoryPasswordChangeScreen;
class CoreOobeView;
-class Key;
-// A class that handles WebUI hooks in Active Directory password change screen.
-class ActiveDirectoryPasswordChangeScreenHandler : public BaseScreenHandler {
+// Interface for dependency injection between
+// ActiveDirectoryPasswordChangeScreen and its WebUI representation.
+class ActiveDirectoryPasswordChangeView {
+ public:
+ constexpr static StaticOobeScreenId kScreenId{"ad-password-change"};
+
+ virtual ~ActiveDirectoryPasswordChangeView() {}
+
+ // Shows the contents of the screen.
+ virtual void Show(const std::string& username, int error) = 0;
+
+ // Binds |screen| to the view.
+ virtual void Bind(ActiveDirectoryPasswordChangeScreen* screen) = 0;
+
+ // Unbinds the screen from the view.
+ virtual void Unbind() = 0;
+
+ // Shows sign-in error bubble.
+ virtual void ShowSignInError(const std::string& error_text) = 0;
+};
+
+// A class that handles WebUI hooks in Active Directory password change screen.
+class ActiveDirectoryPasswordChangeScreenHandler
+ : public ActiveDirectoryPasswordChangeView,
+ public BaseScreenHandler {
public:
+ using TView = ActiveDirectoryPasswordChangeView;
+
ActiveDirectoryPasswordChangeScreenHandler(
JSCallsContainer* js_calls_container,
CoreOobeView* core_oobe_view);
@@ -36,37 +57,22 @@ class ActiveDirectoryPasswordChangeScreenHandler : public BaseScreenHandler {
// WebUIMessageHandler implementation:
void RegisterMessages() override;
- // WebUI message handlers.
- void HandleComplete(const std::string& username,
- const std::string& old_password,
- const std::string& new_password);
- void HandleCancel();
-
- // Shows the password change screen for |username|.
- void ShowScreen(const std::string& username);
+ // ActiveDirectoryPasswordChangeView:
+ void Show(const std::string& username, int error) override;
+ void Bind(ActiveDirectoryPasswordChangeScreen* screen) override;
+ void Unbind() override;
+ void ShowSignInError(const std::string& error_text) override;
private:
- // Shows the screen with the error message corresponding to |error|.
- void ShowScreenWithError(int error);
-
- // Callback called by AuthPolicyHelper::AuthenticateUser with results and
- // error code. (see AuthPolicyHelper::AuthenticateUser)
- void OnAuthFinished(
- const std::string& username,
- const Key& key,
- authpolicy::ErrorType error,
- const authpolicy::ActiveDirectoryAccountInfo& account_info);
+ // WebUI message handlers.
+ void HandleComplete(const std::string& old_password,
+ const std::string& new_password);
- // Helper to call AuthPolicyClient and cancel calls if needed. Used to change
- // password on the Active Directory server.
- std::unique_ptr<AuthPolicyHelper> authpolicy_login_helper_;
+ ActiveDirectoryPasswordChangeScreen* screen_ = nullptr;
// Non-owned. Used to display signin error.
CoreOobeView* core_oobe_view_ = nullptr;
- base::WeakPtrFactory<ActiveDirectoryPasswordChangeScreenHandler>
- weak_factory_{this};
-
DISALLOW_COPY_AND_ASSIGN(ActiveDirectoryPasswordChangeScreenHandler);
};
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 30bfa1f347e..fd90616362b 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
@@ -136,7 +136,7 @@ void AssistantOptInFlowScreenHandler::RegisterMessages() {
&AssistantOptInFlowScreenHandler::HandleVoiceMatchScreenShown);
AddCallback("login.AssistantOptInFlowScreen.GetMoreScreen.screenShown",
&AssistantOptInFlowScreenHandler::HandleGetMoreScreenShown);
- AddCallback("login.AssistantOptInFlowScreen.LoadingScreen.timeout",
+ AddCallback("login.AssistantOptInFlowScreen.timeout",
&AssistantOptInFlowScreenHandler::HandleLoadingTimeout);
AddCallback("login.AssistantOptInFlowScreen.flowFinished",
&AssistantOptInFlowScreenHandler::HandleFlowFinished);
@@ -519,7 +519,8 @@ void AssistantOptInFlowScreenHandler::HandleVoiceMatchScreenUserAction(
// No need to disable hotword for retrain flow since user has a model.
prefs->SetBoolean(assistant::prefs::kAssistantHotwordEnabled, false);
}
- StopSpeakerIdEnrollment();
+ if (voice_match_enrollment_started_)
+ StopSpeakerIdEnrollment();
ShowNextScreen();
} else if (action == kRecordPressed) {
if (!prefs->GetBoolean(assistant::prefs::kAssistantHotwordEnabled)) {
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 2839eb2f64b..cff23bb6dcd 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
@@ -9,7 +9,6 @@
#include <string>
#include <utility>
-#include "ash/public/cpp/assistant/assistant_settings.h"
#include "ash/public/cpp/assistant/assistant_setup.h"
#include "ash/public/cpp/assistant/assistant_state.h"
#include "base/macros.h"
@@ -42,7 +41,6 @@ class AssistantOptInFlowScreenView {
DISALLOW_COPY_AND_ASSIGN(AssistantOptInFlowScreenView);
};
-// TODO(updowndota): Refactor to reuse AssistantOptInHandler methods.
class AssistantOptInFlowScreenHandler
: public BaseScreenHandler,
public AssistantOptInFlowScreenView,
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.cc
index cff1e165eaa..7d650badd2d 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/base_webui_handler.cc
@@ -41,8 +41,6 @@ void BaseWebUIHandler::ShowScreen(OobeScreenId screen) {
void BaseWebUIHandler::ShowScreenWithData(OobeScreenId screen,
const base::DictionaryValue* data) {
- if (!web_ui())
- return;
base::DictionaryValue screen_params;
screen_params.SetString("id", screen.name);
if (data) {
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 b4a51961a0f..7071f8ae0f9 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
@@ -19,8 +19,6 @@
#include "build/branding_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
-#include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
-#include "chrome/browser/chromeos/accessibility/magnification_manager.h"
#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"
@@ -29,8 +27,7 @@
#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/policy/enrollment_requisition_manager.h"
#include "chrome/browser/chromeos/system/input_device_settings.h"
#include "chrome/browser/chromeos/system/timezone_resolver_manager.h"
#include "chrome/browser/lifetime/application_lifetime.h"
@@ -64,24 +61,9 @@ namespace chromeos {
namespace {
-bool IsRemoraRequisition() {
- policy::DeviceCloudPolicyManagerChromeOS* policy_manager =
- g_browser_process->platform_part()
- ->browser_policy_connector_chromeos()
- ->GetDeviceCloudPolicyManager();
- return policy_manager && policy_manager->IsRemoraRequisition();
-}
-
void LaunchResetScreen() {
- // Don't recreate WizardController if it already exists.
- WizardController* const wizard_controller =
- WizardController::default_controller();
- if (wizard_controller && !wizard_controller->login_screen_started()) {
- wizard_controller->AdvanceToScreen(ResetView::kScreenId);
- } else {
- DCHECK(LoginDisplayHost::default_host());
- LoginDisplayHost::default_host()->StartWizard(ResetView::kScreenId);
- }
+ DCHECK(LoginDisplayHost::default_host());
+ LoginDisplayHost::default_host()->StartWizard(ResetView::kScreenId);
}
} // namespace
@@ -91,11 +73,6 @@ void LaunchResetScreen() {
CoreOobeHandler::CoreOobeHandler(JSCallsContainer* js_calls_container)
: BaseWebUIHandler(js_calls_container), version_info_updater_(this) {
DCHECK(js_calls_container);
- AccessibilityManager* accessibility_manager = AccessibilityManager::Get();
- CHECK(accessibility_manager);
- accessibility_subscription_ = accessibility_manager->RegisterCallback(
- base::Bind(&CoreOobeHandler::OnAccessibilityStatusChanged,
- base::Unretained(this)));
ash::TabletMode::Get()->AddObserver(this);
@@ -118,17 +95,6 @@ void CoreOobeHandler::DeclareLocalizedValues(
builder->Add("productName", IDS_SHORT_PRODUCT_NAME);
builder->Add("learnMore", IDS_LEARN_MORE);
- // OOBE accessibility options menu strings shown on each screen.
- builder->Add("accessibilityLink", IDS_OOBE_ACCESSIBILITY_LINK);
- builder->Add("spokenFeedbackOption", IDS_OOBE_SPOKEN_FEEDBACK_OPTION);
- builder->Add("selectToSpeakOption", IDS_OOBE_SELECT_TO_SPEAK_OPTION);
- builder->Add("largeCursorOption", IDS_OOBE_LARGE_CURSOR_OPTION);
- builder->Add("highContrastOption", IDS_OOBE_HIGH_CONTRAST_MODE_OPTION);
- builder->Add("screenMagnifierOption", IDS_OOBE_SCREEN_MAGNIFIER_OPTION);
- builder->Add("dockedMagnifierOption", IDS_OOBE_DOCKED_MAGNIFIER_OPTION);
- builder->Add("virtualKeyboardOption", IDS_OOBE_VIRTUAL_KEYBOARD_OPTION);
- builder->Add("closeAccessibilityMenu", IDS_OOBE_CLOSE_ACCESSIBILITY_MENU);
-
// Strings for the device requisition prompt.
builder->Add("deviceRequisitionPromptCancel",
IDS_ENTERPRISE_DEVICE_REQUISITION_PROMPT_CANCEL);
@@ -161,7 +127,6 @@ void CoreOobeHandler::DeclareLocalizedValues(
}
void CoreOobeHandler::Initialize() {
- UpdateA11yState();
UpdateOobeUIVisibility();
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
version_info_updater_.StartUpdate(true);
@@ -188,18 +153,6 @@ void CoreOobeHandler::RegisterMessages() {
&CoreOobeHandler::HandleSkipUpdateEnrollAfterEula);
AddCallback("updateCurrentScreen",
&CoreOobeHandler::HandleUpdateCurrentScreen);
- AddCallback("enableHighContrast", &CoreOobeHandler::HandleEnableHighContrast);
- AddCallback("enableLargeCursor", &CoreOobeHandler::HandleEnableLargeCursor);
- AddCallback("enableVirtualKeyboard",
- &CoreOobeHandler::HandleEnableVirtualKeyboard);
- AddCallback("enableScreenMagnifier",
- &CoreOobeHandler::HandleEnableScreenMagnifier);
- AddCallback("enableSpokenFeedback",
- &CoreOobeHandler::HandleEnableSpokenFeedback);
- AddCallback("enableSelectToSpeak",
- &CoreOobeHandler::HandleEnableSelectToSpeak);
- AddCallback("enableDockedMagnifier",
- &CoreOobeHandler::HandleEnableDockedMagnifier);
AddCallback("setDeviceRequisition",
&CoreOobeHandler::HandleSetDeviceRequisition);
AddCallback("skipToLoginForTesting",
@@ -234,38 +187,20 @@ void CoreOobeHandler::ShowSignInError(
help_link_text, static_cast<int>(help_topic_id));
}
-void CoreOobeHandler::ShowTpmError() {
- CallJS("cr.ui.Oobe.showTpmError");
-}
-
void CoreOobeHandler::ShowDeviceResetScreen() {
LaunchResetScreen();
}
void CoreOobeHandler::ShowEnableDebuggingScreen() {
- // Don't recreate WizardController if it already exists.
- WizardController* wizard_controller = WizardController::default_controller();
- if (wizard_controller && !wizard_controller->login_screen_started()) {
- wizard_controller->AdvanceToScreen(EnableDebuggingScreenView::kScreenId);
- }
+ DCHECK(LoginDisplayHost::default_host());
+ LoginDisplayHost::default_host()->StartWizard(
+ EnableDebuggingScreenView::kScreenId);
}
void CoreOobeHandler::ShowEnableAdbSideloadingScreen() {
- // Don't recreate WizardController if it already exists.
- WizardController* wizard_controller = WizardController::default_controller();
- if (wizard_controller && !wizard_controller->login_screen_started()) {
- wizard_controller->AdvanceToScreen(
- EnableAdbSideloadingScreenView::kScreenId);
- } else {
- DCHECK(LoginDisplayHost::default_host());
- LoginDisplayHost::default_host()->StartWizard(
- EnableAdbSideloadingScreenView::kScreenId);
- }
-}
-
-void CoreOobeHandler::ShowActiveDirectoryPasswordChangeScreen(
- const std::string& username) {
- CallJS("cr.ui.Oobe.showActiveDirectoryPasswordChangeScreen", username);
+ DCHECK(LoginDisplayHost::default_host());
+ LoginDisplayHost::default_host()->StartWizard(
+ EnableAdbSideloadingScreenView::kScreenId);
}
void CoreOobeHandler::ShowSignInUI(const std::string& email) {
@@ -284,19 +219,6 @@ void CoreOobeHandler::RefocusCurrentPod() {
CallJS("cr.ui.Oobe.refocusCurrentPod");
}
-void CoreOobeHandler::ShowPasswordChangedScreen(bool show_password_error,
- const std::string& email) {
- CallJS("cr.ui.Oobe.showPasswordChangedScreen", show_password_error, email);
-}
-
-void CoreOobeHandler::SetUsageStats(bool checked) {
- CallJS("cr.ui.Oobe.setUsageStats", checked);
-}
-
-void CoreOobeHandler::SetTpmPassword(const std::string& tpm_password) {
- CallJS("cr.ui.Oobe.setTpmPassword", tpm_password);
-}
-
void CoreOobeHandler::ClearErrors() {
CallJS("cr.ui.Oobe.clearErrors");
}
@@ -324,7 +246,8 @@ void CoreOobeHandler::SetShelfHeight(int height) {
void CoreOobeHandler::HandleInitialized() {
// TODO(crbug.com/1082670): Remove excessive logging after investigation.
- LOG(ERROR) << "CoreOobeHandler::HandleInitialized";
+ LOG(ERROR) << "1082670 : CoreOobeHandler::HandleInitialized";
+
GetOobeUI()->InitializeHandlers();
AllowJavascript();
}
@@ -344,44 +267,6 @@ void CoreOobeHandler::HandleUpdateCurrentScreen(
screen == EulaView::kScreenId);
}
-void CoreOobeHandler::HandleEnableHighContrast(bool enabled) {
- AccessibilityManager::Get()->EnableHighContrast(enabled);
-}
-
-void CoreOobeHandler::HandleEnableLargeCursor(bool enabled) {
- AccessibilityManager::Get()->EnableLargeCursor(enabled);
-}
-
-void CoreOobeHandler::HandleEnableVirtualKeyboard(bool enabled) {
- AccessibilityManager::Get()->EnableVirtualKeyboard(enabled);
-}
-
-void CoreOobeHandler::HandleEnableScreenMagnifier(bool enabled) {
- DCHECK(MagnificationManager::Get());
- MagnificationManager::Get()->SetMagnifierEnabled(enabled);
-}
-
-void CoreOobeHandler::HandleEnableSpokenFeedback(bool /* enabled */) {
- // Checkbox is initialized on page init and updates when spoken feedback
- // setting is changed so just toggle spoken feedback here.
- AccessibilityManager::Get()->EnableSpokenFeedback(
- !AccessibilityManager::Get()->IsSpokenFeedbackEnabled());
-}
-
-void CoreOobeHandler::HandleEnableSelectToSpeak(bool /* enabled */) {
- // Checkbox is initialized on page init and updates when Select to Speak
- // setting is changed so just toggle Select to Speak here.
- AccessibilityManager::Get()->SetSelectToSpeakEnabled(
- !AccessibilityManager::Get()->IsSelectToSpeakEnabled());
-}
-
-void CoreOobeHandler::HandleEnableDockedMagnifier(bool enabled) {
- // Checkbox is initialized on page init and updates when the docked magnifier
- // setting is changed so just toggle Select to Speak here.
- DCHECK(MagnificationManager::Get());
- MagnificationManager::Get()->SetDockedMagnifierEnabled(enabled);
-}
-
void CoreOobeHandler::HandleHideOobeDialog() {
if (LoginDisplayHost::default_host())
LoginDisplayHost::default_host()->HideOobeDialog();
@@ -389,13 +274,11 @@ void CoreOobeHandler::HandleHideOobeDialog() {
void CoreOobeHandler::HandleSetDeviceRequisition(
const std::string& requisition) {
- policy::BrowserPolicyConnectorChromeOS* connector =
- g_browser_process->platform_part()->browser_policy_connector_chromeos();
std::string initial_requisition =
- connector->GetDeviceCloudPolicyManager()->GetDeviceRequisition();
- connector->GetDeviceCloudPolicyManager()->SetDeviceRequisition(requisition);
+ policy::EnrollmentRequisitionManager::GetDeviceRequisition();
+ policy::EnrollmentRequisitionManager::SetDeviceRequisition(requisition);
- if (IsRemoraRequisition()) {
+ if (policy::EnrollmentRequisitionManager::IsRemoraRequisition()) {
// CfM devices default to static timezone.
g_browser_process->local_state()->SetInteger(
prefs::kResolveDeviceTimezoneByGeolocationMethod,
@@ -405,19 +288,21 @@ void CoreOobeHandler::HandleSetDeviceRequisition(
// Exit Chrome to force the restart as soon as a new requisition is set.
if (initial_requisition !=
- connector->GetDeviceCloudPolicyManager()->GetDeviceRequisition()) {
+ policy::EnrollmentRequisitionManager::GetDeviceRequisition()) {
chrome::AttemptRestart();
}
}
void CoreOobeHandler::HandleSkipToLoginForTesting() {
- if (WizardController::default_controller())
+ WizardController* controller = WizardController::default_controller();
+ if (controller && controller->is_initialized())
WizardController::default_controller()->SkipToLoginForTesting();
}
void CoreOobeHandler::HandleSkipToUpdateForTesting() {
- if (WizardController::default_controller())
- WizardController::default_controller()->SkipToUpdateForTesting();
+ WizardController* controller = WizardController::default_controller();
+ if (controller && controller->is_initialized())
+ controller->SkipToUpdateForTesting();
}
void CoreOobeHandler::HandleToggleResetScreen() {
@@ -464,26 +349,6 @@ void CoreOobeHandler::ForwardAccelerator(std::string accelerator_name) {
CallJS("cr.ui.Oobe.handleAccelerator", accelerator_name);
}
-void CoreOobeHandler::UpdateA11yState() {
- base::DictionaryValue a11y_info;
- a11y_info.SetBoolean("highContrastEnabled",
- AccessibilityManager::Get()->IsHighContrastEnabled());
- a11y_info.SetBoolean("largeCursorEnabled",
- AccessibilityManager::Get()->IsLargeCursorEnabled());
- a11y_info.SetBoolean("spokenFeedbackEnabled",
- AccessibilityManager::Get()->IsSpokenFeedbackEnabled());
- a11y_info.SetBoolean("selectToSpeakEnabled",
- AccessibilityManager::Get()->IsSelectToSpeakEnabled());
- 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);
-}
-
void CoreOobeHandler::UpdateOobeUIVisibility() {
const std::string& display = GetOobeUI()->display_type();
bool has_api_keys_configured = google_apis::HasAPIKeyConfigured() &&
@@ -529,14 +394,8 @@ void CoreOobeHandler::UpdateLabel(const std::string& id,
}
void CoreOobeHandler::UpdateDeviceRequisition() {
- policy::DeviceCloudPolicyManagerChromeOS* policy_manager =
- g_browser_process->platform_part()
- ->browser_policy_connector_chromeos()
- ->GetDeviceCloudPolicyManager();
- if (policy_manager) {
- CallJS("cr.ui.Oobe.updateDeviceRequisition",
- policy_manager->GetDeviceRequisition());
- }
+ CallJS("cr.ui.Oobe.updateDeviceRequisition",
+ policy::EnrollmentRequisitionManager::GetDeviceRequisition());
}
void CoreOobeHandler::UpdateKeyboardState() {
@@ -588,14 +447,6 @@ void CoreOobeHandler::OnOobeConfigurationChanged() {
CallJS("cr.ui.Oobe.updateOobeConfiguration", configuration);
}
-void CoreOobeHandler::OnAccessibilityStatusChanged(
- const AccessibilityStatusEventDetails& details) {
- if (details.notification_type == ACCESSIBILITY_MANAGER_SHUTDOWN)
- accessibility_subscription_.reset();
- else
- UpdateA11yState();
-}
-
void CoreOobeHandler::HandleLaunchHelpApp(double help_topic_id) {
if (!help_app_.get())
help_app_ = new HelpAppLauncher(
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 44940f99887..fc684c7f0a5 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
@@ -16,7 +16,6 @@
#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"
@@ -56,15 +55,10 @@ class CoreOobeView {
const std::string& error_text,
const std::string& help_link_text,
HelpAppLauncher::HelpTopic help_topic_id) = 0;
- virtual void ShowTpmError() = 0;
virtual void ShowSignInUI(const std::string& email) = 0;
virtual void ResetSignInUI(bool force_online) = 0;
virtual void ClearUserPodPassword() = 0;
virtual void RefocusCurrentPod() = 0;
- virtual void ShowPasswordChangedScreen(bool show_password_error,
- const std::string& email) = 0;
- virtual void SetUsageStats(bool checked) = 0;
- virtual void SetTpmPassword(const std::string& tmp_password) = 0;
virtual void ClearErrors() = 0;
virtual void ReloadContent(const base::DictionaryValue& dictionary) = 0;
virtual void ReloadEulaContent(const base::DictionaryValue& dictionary) = 0;
@@ -78,8 +72,6 @@ class CoreOobeView {
virtual void InitDemoModeDetection() = 0;
virtual void StopDemoModeDetection() = 0;
virtual void UpdateKeyboardState() = 0;
- virtual void ShowActiveDirectoryPasswordChangeScreen(
- const std::string& username) = 0;
};
// The core handler for Javascript messages related to the "oobe" view.
@@ -139,15 +131,10 @@ class CoreOobeHandler : public BaseWebUIHandler,
const std::string& error_text,
const std::string& help_link_text,
HelpAppLauncher::HelpTopic help_topic_id) override;
- void ShowTpmError() override;
void ShowSignInUI(const std::string& email) override;
void ResetSignInUI(bool force_online) override;
void ClearUserPodPassword() override;
void RefocusCurrentPod() override;
- void ShowPasswordChangedScreen(bool show_password_error,
- const std::string& email) override;
- void SetUsageStats(bool checked) override;
- void SetTpmPassword(const std::string& tmp_password) override;
void ClearErrors() override;
void ReloadContent(const base::DictionaryValue& dictionary) override;
void ReloadEulaContent(const base::DictionaryValue& dictionary) override;
@@ -158,8 +145,6 @@ class CoreOobeHandler : public BaseWebUIHandler,
void ShowDeviceResetScreen() override;
void ShowEnableAdbSideloadingScreen() override;
void ShowEnableDebuggingScreen() override;
- void ShowActiveDirectoryPasswordChangeScreen(
- const std::string& username) override;
void InitDemoModeDetection() override;
void StopDemoModeDetection() override;
@@ -173,13 +158,6 @@ class CoreOobeHandler : public BaseWebUIHandler,
void OnOobeConfigurationChanged() override;
// Handlers for JS WebUI messages.
- void HandleEnableLargeCursor(bool enabled);
- void HandleEnableHighContrast(bool enabled);
- void HandleEnableVirtualKeyboard(bool enabled);
- void HandleEnableScreenMagnifier(bool enabled);
- void HandleEnableSpokenFeedback(bool /* enabled */);
- void HandleEnableSelectToSpeak(bool /* enabled */);
- void HandleEnableDockedMagnifier(bool /* enabled */);
void HandleHideOobeDialog();
void HandleInitialized();
void HandleSkipUpdateEnrollAfterEula();
@@ -211,9 +189,6 @@ class CoreOobeHandler : public BaseWebUIHandler,
// to tab/shift-tab event.
void HandleRaiseTabKeyEvent(bool reverse);
- // Updates a11y menu state based on the current a11y features state(on/off).
- void UpdateA11yState();
-
// Calls javascript to sync OOBE UI visibility with show_oobe_ui_.
void UpdateOobeUIVisibility();
@@ -226,10 +201,6 @@ class CoreOobeHandler : public BaseWebUIHandler,
// Updates client area size based on the primary screen size.
void UpdateClientAreaSize();
- // Notification of a change in the accessibility settings.
- void OnAccessibilityStatusChanged(
- const AccessibilityStatusEventDetails& details);
-
// True if we should show OOBE instead of login.
bool show_oobe_ui_ = false;
@@ -239,8 +210,6 @@ class CoreOobeHandler : public BaseWebUIHandler,
// Help application used for help dialogs.
scoped_refptr<HelpAppLauncher> help_app_;
- std::unique_ptr<AccessibilityStatusSubscription> accessibility_subscription_;
-
DemoModeDetector demo_mode_detector_;
mojo::Remote<ash::mojom::CrosDisplayConfigController> cros_display_config_;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/debug/debug_overlay_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/debug/debug_overlay_handler.cc
index 1520461230b..5548ccda6a3 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/debug/debug_overlay_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/debug/debug_overlay_handler.cc
@@ -12,6 +12,9 @@
#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/system/sys_info.h"
+#include "base/task/post_task.h"
+#include "base/task/task_traits.h"
+#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "chrome/common/chrome_paths.h"
#include "chromeos/constants/chromeos_switches.h"
@@ -44,9 +47,10 @@ void RunStoreScreenshotOnTaskRunner(
const base::FilePath& screenshot_dir,
const std::string& screenshot_name,
scoped_refptr<base::RefCountedMemory> png_data) {
- base::ThreadTaskRunnerHandle::Get()->PostTask(
- FROM_HERE, base::BindOnce(&StoreScreenshot, screenshot_dir,
- screenshot_name, png_data));
+ base::ThreadPool::PostTask(
+ FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
+ base::BindOnce(&StoreScreenshot, screenshot_dir, screenshot_name,
+ png_data));
}
} // namespace
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.cc
index a0b5afecfe5..b63e52d4391 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.cc
@@ -20,37 +20,30 @@ DeviceDisabledScreenHandler::DeviceDisabledScreenHandler(
}
DeviceDisabledScreenHandler::~DeviceDisabledScreenHandler() {
- if (delegate_)
- delegate_->OnViewDestroyed(this);
+ if (screen_)
+ screen_->OnViewDestroyed(this);
}
-void DeviceDisabledScreenHandler::Show() {
- if (!page_is_ready()) {
- show_on_init_ = true;
- return;
- }
-
- if (delegate_) {
- CallJS("login.DeviceDisabledScreen.setSerialNumberAndEnrollmentDomain",
- delegate_->GetSerialNumber(), delegate_->GetEnrollmentDomain());
- CallJS("login.DeviceDisabledScreen.setMessage", delegate_->GetMessage());
- }
- ShowScreen(kScreenId);
+void DeviceDisabledScreenHandler::Show(const std::string& serial,
+ const std::string& domain,
+ const std::string& message) {
+ base::DictionaryValue screen_data;
+ screen_data.SetStringPath("serial", serial);
+ screen_data.SetStringPath("domain", domain);
+ screen_data.SetStringPath("message", message);
+ ShowScreenWithData(kScreenId, &screen_data);
}
void DeviceDisabledScreenHandler::Hide() {
- show_on_init_ = false;
+ NOTREACHED() << "Device should reboot upon removing device disabled flag";
}
-void DeviceDisabledScreenHandler::SetDelegate(DeviceDisabledScreen* delegate) {
- delegate_ = delegate;
- if (page_is_ready())
- Initialize();
+void DeviceDisabledScreenHandler::Bind(DeviceDisabledScreen* screen) {
+ screen_ = screen;
}
void DeviceDisabledScreenHandler::UpdateMessage(const std::string& message) {
- if (page_is_ready())
- CallJS("login.DeviceDisabledScreen.setMessage", message);
+ CallJS("login.DeviceDisabledScreen.setMessage", message);
}
void DeviceDisabledScreenHandler::DeclareLocalizedValues(
@@ -63,13 +56,6 @@ void DeviceDisabledScreenHandler::DeclareLocalizedValues(
}
void DeviceDisabledScreenHandler::Initialize() {
- if (!page_is_ready() || !delegate_)
- return;
-
- if (show_on_init_) {
- Show();
- show_on_init_ = false;
- }
}
void DeviceDisabledScreenHandler::RegisterMessages() {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.h
index 1cb75a48ab2..ed647dea28b 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/device_disabled_screen_handler.h
@@ -19,9 +19,11 @@ class DeviceDisabledScreenView {
virtual ~DeviceDisabledScreenView() {}
- virtual void Show() = 0;
+ virtual void Show(const std::string& serial,
+ const std::string& domain,
+ const std::string& message) = 0;
virtual void Hide() = 0;
- virtual void SetDelegate(DeviceDisabledScreen* delegate) = 0;
+ virtual void Bind(DeviceDisabledScreen* screen) = 0;
virtual void UpdateMessage(const std::string& message) = 0;
};
@@ -35,9 +37,11 @@ class DeviceDisabledScreenHandler : public DeviceDisabledScreenView,
~DeviceDisabledScreenHandler() override;
// DeviceDisabledScreenActor:
- void Show() override;
+ void Show(const std::string& serial,
+ const std::string& domain,
+ const std::string& message) override;
void Hide() override;
- void SetDelegate(DeviceDisabledScreen* delegate) override;
+ void Bind(DeviceDisabledScreen* screen) override;
void UpdateMessage(const std::string& message) override;
// BaseScreenHandler:
@@ -49,10 +53,7 @@ class DeviceDisabledScreenHandler : public DeviceDisabledScreenView,
// WebUIMessageHandler:
void RegisterMessages() override;
- DeviceDisabledScreen* delegate_ = nullptr;
-
- // Indicates whether the screen should be shown right after initialization.
- bool show_on_init_ = false;
+ DeviceDisabledScreen* screen_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(DeviceDisabledScreenHandler);
};
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 e5f84a27dd2..81308cb95f2 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
@@ -27,7 +27,7 @@
#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/policy/enrollment_requisition_manager.h"
#include "chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.h"
#include "chrome/browser/policy/enrollment_status.h"
#include "chrome/browser/profiles/profile.h"
@@ -412,6 +412,12 @@ void EnrollmentScreenHandler::ShowEnrollmentStatus(
IDS_ENTERPRISE_ENROLLMENT_CONSUMER_ACCOUNT_WITH_PACKAGED_LICENSE,
true);
break;
+ case policy::
+ DM_STATUS_SERVICE_ENTERPRISE_ACCOUNT_IS_NOT_ELIGIBLE_TO_ENROLL:
+ ShowError(
+ IDS_ENTERPRISE_ENROLLMENT_ENTERPRISE_ACCOUNT_IS_NOT_ELIGIBLE_TO_ENROLL,
+ true);
+ break;
case policy::DM_STATUS_SERVICE_ENTERPRISE_TOS_HAS_NOT_BEEN_ACCEPTED:
ShowError(
IDS_ENTERPRISE_ENROLLMENT_ENTERPRISE_TOS_HAS_NOT_BEEN_ACCEPTED,
@@ -772,12 +778,12 @@ void EnrollmentScreenHandler::HandleCompleteLogin(const std::string& user) {
void EnrollmentScreenHandler::OnGetCookiesForCompleteLogin(
const std::string& user,
- const net::CookieStatusList& cookies,
- const net::CookieStatusList& excluded_cookies) {
+ const net::CookieAccessResultList& cookies,
+ const net::CookieAccessResultList& excluded_cookies) {
std::string auth_code;
- for (const auto& cookie_with_status : cookies) {
- if (cookie_with_status.cookie.Name() == "oauth_code") {
- auth_code = cookie_with_status.cookie.Value();
+ for (const auto& cookie_with_access_result : cookies) {
+ if (cookie_with_access_result.cookie.Name() == "oauth_code") {
+ auth_code = cookie_with_access_result.cookie.Value();
break;
}
}
@@ -882,11 +888,7 @@ void EnrollmentScreenHandler::DoShowWithPartition(
if (!app_locale.empty())
screen_data.SetString("hl", app_locale);
- policy::DeviceCloudPolicyManagerChromeOS* policy_manager =
- g_browser_process->platform_part()
- ->browser_policy_connector_chromeos()
- ->GetDeviceCloudPolicyManager();
- const bool cfm = policy_manager && policy_manager->IsRemoraRequisition();
+ const bool cfm = policy::EnrollmentRequisitionManager::IsRemoraRequisition();
screen_data.SetString("flow", cfm ? "cfm" : "enterprise");
ShowScreenWithData(EnrollmentScreenView::kScreenId, &screen_data);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h
index b83224e3d25..4feaf4b6886 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h
@@ -105,8 +105,8 @@ class EnrollmentScreenHandler
void HandleCompleteLogin(const std::string& user);
void OnGetCookiesForCompleteLogin(
const std::string& user,
- const net::CookieStatusList& cookies,
- const net::CookieStatusList& excluded_cookies);
+ const net::CookieAccessResultList& cookies,
+ const net::CookieAccessResultList& excluded_cookies);
void HandleAdCompleteLogin(const std::string& machine_name,
const std::string& distinguished_name,
const std::string& encryption_types,
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc
index 03e3c845076..3040f27e447 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/eula_screen_handler.cc
@@ -8,6 +8,7 @@
#include <string>
#include "base/bind.h"
+#include "base/command_line.h"
#include "base/macros.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/browser_process.h"
@@ -143,7 +144,7 @@ void EulaScreenHandler::Initialize() {
if (!page_is_ready() || !screen_)
return;
- core_oobe_view_->SetUsageStats(screen_->IsUsageStatsEnabled());
+ CallJS("login.EulaScreen.setUsageStats", screen_->IsUsageStatsEnabled());
if (show_on_init_) {
Show();
@@ -152,7 +153,7 @@ void EulaScreenHandler::Initialize() {
}
void EulaScreenHandler::OnPasswordFetched(const std::string& tpm_password) {
- core_oobe_view_->SetTpmPassword(tpm_password);
+ CallJS("login.EulaScreen.setTpmPassword", tpm_password);
}
void EulaScreenHandler::HandleOnLearnMore() {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/fake_update_required_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/fake_update_required_screen_handler.h
index 4dc7fb49bde..956bf1de8c8 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/fake_update_required_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/fake_update_required_screen_handler.h
@@ -39,6 +39,7 @@ class FakeUpdateRequiredScreenHandler : public UpdateRequiredView {
void SetUIState(UpdateRequiredView::UIState ui_state) override;
void SetEnterpriseAndDeviceName(const std::string& enterpriseDomain,
const base::string16& deviceName) override {}
+ void SetEolMessage(const std::string& eolMessage) override {}
UpdateRequiredView::UIState ui_state_;
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 14d58280bee..f22c63fb699 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
@@ -4,45 +4,11 @@
#include "chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.h"
-#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"
-#include "chrome/browser/profiles/profile_manager.h"
-#include "chrome/common/pref_names.h"
#include "chrome/grit/generated_resources.h"
#include "components/login/localized_values_builder.h"
-#include "components/prefs/pref_service.h"
-#include "content/public/browser/device_service.h"
-#include "ui/base/l10n/l10n_util.h"
-
-namespace {
-
-// The max number of fingerprints that can be stored.
-constexpr int kMaxAllowedFingerprints = 3;
-
-// Determines what the newly added fingerprint's name should be.
-std::string GetDefaultFingerprintName(int enrolled_finger_count) {
- DCHECK(enrolled_finger_count < kMaxAllowedFingerprints);
- switch (enrolled_finger_count) {
- case 0:
- return l10n_util::GetStringUTF8(
- IDS_OOBE_FINGERPINT_SETUP_SCREEN_NEW_FINGERPRINT_DEFAULT_NAME_1);
- case 1:
- return l10n_util::GetStringUTF8(
- IDS_OOBE_FINGERPINT_SETUP_SCREEN_NEW_FINGERPRINT_DEFAULT_NAME_2);
- case 2:
- return l10n_util::GetStringUTF8(
- IDS_OOBE_FINGERPINT_SETUP_SCREEN_NEW_FINGERPRINT_DEFAULT_NAME_3);
- default:
- NOTREACHED();
- }
- return std::string();
-}
-
-} // namespace
namespace chromeos {
@@ -52,10 +18,6 @@ FingerprintSetupScreenHandler::FingerprintSetupScreenHandler(
JSCallsContainer* js_calls_container)
: BaseScreenHandler(kScreenId, js_calls_container) {
set_user_acted_method_path("login.FingerprintSetupScreen.userActed");
-
- content::GetDeviceService().BindFingerprint(
- fp_service_.BindNewPipeAndPassReceiver());
- fp_service_->AddFingerprintObserver(receiver_.BindNewPipeAndPassRemote());
}
FingerprintSetupScreenHandler::~FingerprintSetupScreenHandler() = default;
@@ -104,10 +66,6 @@ void FingerprintSetupScreenHandler::DeclareLocalizedValues(
void FingerprintSetupScreenHandler::RegisterMessages() {
BaseScreenHandler::RegisterMessages();
- web_ui()->RegisterMessageCallback(
- "startEnroll",
- base::BindRepeating(&FingerprintSetupScreenHandler::HandleStartEnroll,
- base::Unretained(this)));
}
void FingerprintSetupScreenHandler::Bind(FingerprintSetupScreen* screen) {
@@ -119,70 +77,21 @@ void FingerprintSetupScreenHandler::Show() {
ShowScreen(kScreenId);
}
-void FingerprintSetupScreenHandler::Hide() {
- // Clean up existing fingerprint enroll session.
- if (enroll_session_started_) {
- fp_service_->CancelCurrentEnrollSession(base::BindOnce(
- &FingerprintSetupScreenHandler::OnCancelCurrentEnrollSession,
- weak_ptr_factory_.GetWeakPtr()));
- }
-}
+void FingerprintSetupScreenHandler::Hide() {}
void FingerprintSetupScreenHandler::Initialize() {}
-void FingerprintSetupScreenHandler::OnRestarted() {
- VLOG(1) << "Fingerprint session restarted.";
-}
-
void FingerprintSetupScreenHandler::OnEnrollScanDone(
device::mojom::ScanResult scan_result,
bool enroll_session_complete,
int percent_complete) {
- VLOG(1) << "Receive fingerprint enroll scan result. scan_result="
- << scan_result
- << ", enroll_session_complete=" << enroll_session_complete
- << ", percent_complete=" << percent_complete;
CallJS("login.FingerprintSetupScreen.onEnrollScanDone",
static_cast<int>(scan_result), enroll_session_complete,
percent_complete);
-
- if (enroll_session_complete) {
- enroll_session_started_ = false;
-
- ++enrolled_finger_count_;
- CallJS("login.FingerprintSetupScreen.enableAddAnotherFinger",
- enrolled_finger_count_ < kMaxAllowedFingerprints);
-
- // Update the number of registered fingers, it's fine to override because
- // this is the first time user log in and have no finger registered.
- ProfileManager::GetActiveUserProfile()->GetPrefs()->SetInteger(
- prefs::kQuickUnlockFingerprintRecord, enrolled_finger_count_);
- }
-}
-
-void FingerprintSetupScreenHandler::OnAuthScanDone(
- device::mojom::ScanResult scan_result,
- const base::flat_map<std::string, std::vector<std::string>>& matches) {}
-
-void FingerprintSetupScreenHandler::OnSessionFailed() {
- // TODO(xiaoyinh): Add more user visible information when available.
- LOG(ERROR) << "Fingerprint session failed.";
-}
-
-void FingerprintSetupScreenHandler::HandleStartEnroll(
- const base::ListValue* args) {
- DCHECK(enrolled_finger_count_ < kMaxAllowedFingerprints);
-
- enroll_session_started_ = true;
- fp_service_->StartEnrollSession(
- ProfileHelper::Get()->GetUserIdHashFromProfile(
- ProfileManager::GetActiveUserProfile()),
- GetDefaultFingerprintName(enrolled_finger_count_));
}
-void FingerprintSetupScreenHandler::OnCancelCurrentEnrollSession(bool success) {
- if (!success)
- LOG(ERROR) << "Failed to cancel current fingerprint enroll session.";
+void FingerprintSetupScreenHandler::EnableAddAnotherFinger(bool enable) {
+ CallJS("login.FingerprintSetupScreen.enableAddAnotherFinger", enable);
}
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.h
index 8e752278477..7eef2972b25 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.h
@@ -7,8 +7,6 @@
#include "base/macros.h"
#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
-#include "mojo/public/cpp/bindings/receiver.h"
-#include "mojo/public/cpp/bindings/remote.h"
#include "services/device/public/mojom/fingerprint.mojom.h"
namespace chromeos {
@@ -31,13 +29,19 @@ class FingerprintSetupScreenView {
// Hides the contents of the screen.
virtual void Hide() = 0;
+
+ // Enables adding new finger.
+ virtual void EnableAddAnotherFinger(bool enable) = 0;
+
+ // Trigger update UI state due to enroll status update.
+ virtual void OnEnrollScanDone(device::mojom::ScanResult scan_result,
+ bool enroll_session_complete,
+ int percent_complete) = 0;
};
// The sole implementation of the FingerprintSetupScreenView, using WebUI.
-class FingerprintSetupScreenHandler
- : public BaseScreenHandler,
- public FingerprintSetupScreenView,
- public device::mojom::FingerprintObserver {
+class FingerprintSetupScreenHandler : public BaseScreenHandler,
+ public FingerprintSetupScreenView {
public:
using TView = FingerprintSetupScreenView;
@@ -53,36 +57,17 @@ class FingerprintSetupScreenHandler
void Bind(FingerprintSetupScreen* screen) override;
void Show() override;
void Hide() override;
-
- // BaseScreenHandler:
- void Initialize() override;
-
- // device::mojom::FingerprintObserver:
- void OnRestarted() override;
+ void EnableAddAnotherFinger(bool enable) override;
void OnEnrollScanDone(device::mojom::ScanResult scan_result,
bool enroll_session_complete,
int percent_complete) override;
- void OnAuthScanDone(
- device::mojom::ScanResult scan_result,
- const base::flat_map<std::string, std::vector<std::string>>& matches)
- override;
- void OnSessionFailed() override;
- private:
- // JS callbacks.
- void HandleStartEnroll(const base::ListValue* args);
-
- void OnCancelCurrentEnrollSession(bool success);
+ // BaseScreenHandler:
+ void Initialize() override;
+ private:
FingerprintSetupScreen* screen_ = nullptr;
- mojo::Remote<device::mojom::Fingerprint> fp_service_;
- mojo::Receiver<device::mojom::FingerprintObserver> receiver_{this};
- int enrolled_finger_count_ = 0;
- bool enroll_session_started_ = false;
-
- base::WeakPtrFactory<FingerprintSetupScreenHandler> weak_ptr_factory_{this};
-
DISALLOW_COPY_AND_ASSIGN(FingerprintSetupScreenHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/gaia_password_changed_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_password_changed_screen_handler.cc
new file mode 100644
index 00000000000..b901c35566a
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_password_changed_screen_handler.cc
@@ -0,0 +1,77 @@
+// Copyright 2020 The Chromium 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/gaia_password_changed_screen_handler.h"
+
+#include "base/values.h"
+#include "chrome/browser/chromeos/login/oobe_screen.h"
+#include "chrome/browser/chromeos/login/screens/gaia_password_changed_screen.h"
+#include "chrome/browser/chromeos/login/ui/login_display_host.h"
+#include "chrome/grit/chromium_strings.h"
+#include "chrome/grit/generated_resources.h"
+#include "components/login/localized_values_builder.h"
+#include "ui/chromeos/devicetype_utils.h"
+
+namespace chromeos {
+
+constexpr StaticOobeScreenId GaiaPasswordChangedView::kScreenId;
+
+GaiaPasswordChangedScreenHandler::GaiaPasswordChangedScreenHandler(
+ JSCallsContainer* js_calls_container)
+ : BaseScreenHandler(kScreenId, js_calls_container) {
+ set_user_acted_method_path("login.GaiaPasswordChangedScreen.userActed");
+}
+
+GaiaPasswordChangedScreenHandler::~GaiaPasswordChangedScreenHandler() {
+ if (screen_)
+ screen_->OnViewDestroyed(this);
+}
+
+void GaiaPasswordChangedScreenHandler::DeclareLocalizedValues(
+ ::login::LocalizedValuesBuilder* builder) {
+ builder->Add("nextButtonText", IDS_OFFLINE_LOGIN_NEXT_BUTTON_TEXT);
+ builder->Add("oldPasswordHint", IDS_LOGIN_PASSWORD_CHANGED_OLD_PASSWORD_HINT);
+ builder->Add("oldPasswordIncorrect",
+ IDS_LOGIN_PASSWORD_CHANGED_INCORRECT_OLD_PASSWORD);
+ builder->Add("proceedAnywayButton",
+ IDS_LOGIN_PASSWORD_CHANGED_PROCEED_ANYWAY_BUTTON);
+ builder->Add("forgotOldPasswordButtonText",
+ IDS_LOGIN_PASSWORD_CHANGED_FORGOT_PASSWORD);
+ builder->AddF("passwordChangedTitle", IDS_LOGIN_PASSWORD_CHANGED_TITLE,
+ ui::GetChromeOSDeviceName());
+ builder->Add("passwordChangedProceedAnywayTitle",
+ IDS_LOGIN_PASSWORD_CHANGED_PROCEED_ANYWAY);
+ builder->Add("passwordChangedTryAgain", IDS_LOGIN_PASSWORD_CHANGED_TRY_AGAIN);
+}
+
+void GaiaPasswordChangedScreenHandler::Initialize() {
+ AddCallback("migrateUserData",
+ &GaiaPasswordChangedScreenHandler::HandleMigrateUserData);
+}
+
+void GaiaPasswordChangedScreenHandler::Show(const std::string& email,
+ bool has_error) {
+ base::DictionaryValue data;
+ data.SetStringPath("email", email);
+ data.SetBoolPath("showError", has_error);
+ ShowScreenWithData(kScreenId, &data);
+}
+
+void GaiaPasswordChangedScreenHandler::Bind(GaiaPasswordChangedScreen* screen) {
+ screen_ = screen;
+ BaseScreenHandler::SetBaseScreen(screen_);
+}
+
+void GaiaPasswordChangedScreenHandler::Unbind() {
+ screen_ = nullptr;
+ BaseScreenHandler::SetBaseScreen(nullptr);
+}
+
+void GaiaPasswordChangedScreenHandler::HandleMigrateUserData(
+ const std::string& old_password) {
+ if (screen_)
+ screen_->MigrateUserData(old_password);
+}
+
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/gaia_password_changed_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_password_changed_screen_handler.h
new file mode 100644
index 00000000000..3c6d65fb1e7
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_password_changed_screen_handler.h
@@ -0,0 +1,64 @@
+// Copyright 2020 The Chromium 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_GAIA_PASSWORD_CHANGED_SCREEN_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_GAIA_PASSWORD_CHANGED_SCREEN_HANDLER_H_
+
+#include <string>
+
+#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
+
+namespace chromeos {
+
+class GaiaPasswordChangedScreen;
+
+// Interface for dependency injection between GaiaPasswordChangedScreen and its
+// WebUI representation.
+class GaiaPasswordChangedView {
+ public:
+ constexpr static StaticOobeScreenId kScreenId{"gaia-password-changed"};
+
+ virtual ~GaiaPasswordChangedView() {}
+
+ // Shows the contents of the screen.
+ virtual void Show(const std::string& email, bool has_error) = 0;
+
+ // Binds |screen| to the view.
+ virtual void Bind(GaiaPasswordChangedScreen* screen) = 0;
+
+ // Unbinds the screen from the view.
+ virtual void Unbind() = 0;
+};
+
+class GaiaPasswordChangedScreenHandler : public GaiaPasswordChangedView,
+ public BaseScreenHandler {
+ public:
+ using TView = GaiaPasswordChangedView;
+
+ explicit GaiaPasswordChangedScreenHandler(
+ JSCallsContainer* js_calls_container);
+ GaiaPasswordChangedScreenHandler(const GaiaPasswordChangedScreenHandler&) =
+ delete;
+ GaiaPasswordChangedScreenHandler& operator=(
+ const GaiaPasswordChangedScreenHandler&) = delete;
+ ~GaiaPasswordChangedScreenHandler() override;
+
+ private:
+ void Show(const std::string& email, bool has_error) override;
+ void Bind(GaiaPasswordChangedScreen* screen) override;
+ void Unbind() override;
+
+ void HandleMigrateUserData(const std::string& old_password);
+
+ // BaseScreenHandler:
+ void DeclareLocalizedValues(
+ ::login::LocalizedValuesBuilder* builder) override;
+ void Initialize() override;
+
+ GaiaPasswordChangedScreen* screen_ = nullptr;
+};
+
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_GAIA_PASSWORD_CHANGED_SCREEN_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc
index 64879360d33..1babe0f4d85 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
@@ -54,7 +54,6 @@
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/ash/login_screen_client.h"
-#include "chrome/browser/ui/webui/chromeos/login/active_directory_password_change_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h"
#include "chrome/browser/ui/webui/metrics_handler.h"
@@ -340,14 +339,10 @@ GaiaScreenHandler::GaiaContext::GaiaContext() {}
GaiaScreenHandler::GaiaScreenHandler(
JSCallsContainer* js_calls_container,
CoreOobeView* core_oobe_view,
- const scoped_refptr<NetworkStateInformer>& network_state_informer,
- ActiveDirectoryPasswordChangeScreenHandler*
- active_directory_password_change_screen_handler)
+ const scoped_refptr<NetworkStateInformer>& network_state_informer)
: BaseScreenHandler(kScreenId, js_calls_container),
network_state_informer_(network_state_informer),
- core_oobe_view_(core_oobe_view),
- active_directory_password_change_screen_handler_(
- active_directory_password_change_screen_handler) {
+ core_oobe_view_(core_oobe_view) {
DCHECK(network_state_informer_.get());
}
@@ -427,7 +422,7 @@ void GaiaScreenHandler::LoadGaiaWithPartition(
base::BindOnce(&GaiaScreenHandler::OnSetCookieForLoadGaiaWithPartition,
weak_factory_.GetWeakPtr(), context, partition_name);
if (context.gaps_cookie.empty()) {
- std::move(callback).Run(net::CanonicalCookie::CookieInclusionStatus());
+ std::move(callback).Run(net::CookieInclusionStatus());
return;
}
@@ -465,7 +460,7 @@ void GaiaScreenHandler::LoadGaiaWithPartition(
void GaiaScreenHandler::OnSetCookieForLoadGaiaWithPartition(
const GaiaContext& context,
const std::string& partition_name,
- net::CanonicalCookie::CookieInclusionStatus status) {
+ net::CookieInclusionStatus status) {
std::unique_ptr<std::string> version = std::make_unique<std::string>();
std::unique_ptr<bool> consent = std::make_unique<bool>();
base::OnceClosure get_version_and_consent =
@@ -858,7 +853,9 @@ void GaiaScreenHandler::DoAdAuth(
break;
}
case authpolicy::ERROR_PASSWORD_EXPIRED:
- active_directory_password_change_screen_handler_->ShowScreen(username);
+ LoginDisplayHost::default_host()
+ ->GetWizardController()
+ ->ShowActiveDirectoryPasswordChangeScreen(username);
break;
case authpolicy::ERROR_PARSE_UPN_FAILED:
case authpolicy::ERROR_BAD_USER_NAME:
@@ -965,11 +962,11 @@ void GaiaScreenHandler::ContinueAuthenticationWhenCookiesAvailable() {
}
void GaiaScreenHandler::OnGetCookiesForCompleteAuthentication(
- const net::CookieStatusList& cookies,
- const net::CookieStatusList& excluded_cookies) {
+ const net::CookieAccessResultList& cookies,
+ const net::CookieAccessResultList& excluded_cookies) {
std::string auth_code, gaps_cookie;
- for (const auto& cookie_with_status : cookies) {
- const auto& cookie = cookie_with_status.cookie;
+ for (const auto& cookie_with_access_result : cookies) {
+ const auto& cookie = cookie_with_access_result.cookie;
if (cookie.Name() == kOAUTHCodeCookie)
auth_code = cookie.Value();
else if (cookie.Name() == kGAPSCookie)
@@ -1086,8 +1083,6 @@ void GaiaScreenHandler::HandleShowAddUser(const base::ListValue* args) {
if (args)
args->GetString(0, &email);
set_populated_account(AccountId::FromUserEmail(email));
- if (!email.empty())
- SendReauthReason(AccountId::FromUserEmail(email));
OnShowAddUser();
}
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 02c0cce7974..3b00660c72b 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
@@ -23,6 +23,7 @@
#include "components/user_manager/user_type.h"
#include "net/base/net_errors.h"
#include "net/cookies/canonical_cookie.h"
+#include "net/cookies/cookie_inclusion_status.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
class AccountId;
@@ -38,7 +39,6 @@ class NSSTempCertsCacheChromeOS;
namespace chromeos {
-class ActiveDirectoryPasswordChangeScreenHandler;
class Key;
class SamlPasswordAttributes;
class SigninScreenHandler;
@@ -109,9 +109,7 @@ class GaiaScreenHandler : public BaseScreenHandler,
GaiaScreenHandler(
JSCallsContainer* js_calls_container,
CoreOobeView* core_oobe_view,
- const scoped_refptr<NetworkStateInformer>& network_state_informer,
- ActiveDirectoryPasswordChangeScreenHandler*
- active_directory_password_change_screen_handler);
+ const scoped_refptr<NetworkStateInformer>& network_state_informer);
~GaiaScreenHandler() override;
// GaiaView:
@@ -155,10 +153,9 @@ class GaiaScreenHandler : public BaseScreenHandler,
const std::string& partition_name);
// Called after the GAPS cookie, if present, is added to the cookie store.
- void OnSetCookieForLoadGaiaWithPartition(
- const GaiaContext& context,
- const std::string& partition_name,
- net::CanonicalCookie::CookieInclusionStatus status);
+ void OnSetCookieForLoadGaiaWithPartition(const GaiaContext& context,
+ const std::string& partition_name,
+ net::CookieInclusionStatus status);
// Callback that loads GAIA after version and stat consent information has
// been retrieved.
@@ -332,8 +329,8 @@ class GaiaScreenHandler : public BaseScreenHandler,
void ContinueAuthenticationWhenCookiesAvailable();
void OnGetCookiesForCompleteAuthentication(
- const net::CookieStatusList& cookies,
- const net::CookieStatusList& excluded_cookies);
+ const net::CookieAccessResultList& cookies,
+ const net::CookieAccessResultList& excluded_cookies);
void OnCookieWaitTimeout();
@@ -356,9 +353,6 @@ class GaiaScreenHandler : public BaseScreenHandler,
CoreOobeView* core_oobe_view_ = nullptr;
- ActiveDirectoryPasswordChangeScreenHandler*
- active_directory_password_change_screen_handler_ = nullptr;
-
// Account to pre-populate with.
AccountId populated_account_id_;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/native_window_delegate.h b/chromium/chrome/browser/ui/webui/chromeos/login/native_window_delegate.h
deleted file mode 100644
index f7453e022bd..00000000000
--- a/chromium/chrome/browser/ui/webui/chromeos/login/native_window_delegate.h
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_NATIVE_WINDOW_DELEGATE_H_
-#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_NATIVE_WINDOW_DELEGATE_H_
-
-#include "ui/gfx/native_widget_types.h"
-
-namespace chromeos {
-
-// An interface to get gfx::NativeWindow.
-class NativeWindowDelegate {
- public:
- NativeWindowDelegate() {}
- virtual ~NativeWindowDelegate() {}
-
- // Returns corresponding native window.
- virtual gfx::NativeWindow GetNativeWindow() const = 0;
-};
-
-} // namespace chromeos
-
-#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_NATIVE_WINDOW_DELEGATE_H_
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 9423ee9eb01..29c58fa4b2a 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
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/strings/string_number_conversions.h"
-#include "base/task/post_task.h"
#include "chrome/browser/ui/ash/ash_util.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
@@ -58,8 +57,8 @@ void OobeDisplayChooser::TryToPlaceUiOnTouchDisplay() {
display::Screen::GetScreen()->GetPrimaryDisplay();
if (primary_display.is_valid() && !TouchSupportAvailable(primary_display)) {
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&OobeDisplayChooser::MaybeMoveToTouchDisplay,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&OobeDisplayChooser::MaybeMoveToTouchDisplay,
weak_ptr_factory_.GetWeakPtr()));
}
}
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 a8b92fcbf79..414a359c54e 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc
@@ -31,6 +31,7 @@
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/multidevice_setup/multidevice_setup_service_factory.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
+#include "chrome/browser/chromeos/policy/enrollment_requisition_manager.h"
#include "chrome/browser/chromeos/settings/shutdown_policy_handler.h"
#include "chrome/browser/chromeos/system/input_device_settings.h"
#include "chrome/browser/extensions/tab_helper.h"
@@ -56,6 +57,7 @@
#include "chrome/browser/ui/webui/chromeos/login/error_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/fingerprint_setup_screen_handler.h"
+#include "chrome/browser/ui/webui/chromeos/login/gaia_password_changed_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/gesture_navigation_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/hid_detection_screen_handler.h"
@@ -74,6 +76,7 @@
#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"
+#include "chrome/browser/ui/webui/chromeos/login/tpm_error_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/update_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/user_board_screen_handler.h"
@@ -101,6 +104,7 @@
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/webui/web_ui_util.h"
@@ -192,7 +196,8 @@ void AddAssistantScreensResources(content::WebUIDataSource* source) {
IDR_ASSISTANT_VOICE_MATCH_ANIMATION);
source->AddResourcePath("voice_match_already_setup_animation.json",
IDR_ASSISTANT_VOICE_MATCH_ALREADY_SETUP_ANIMATION);
- source->OverrideContentSecurityPolicyWorkerSrc("worker-src blob: 'self';");
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::WorkerSrc, "worker-src blob: 'self';");
}
void AddGestureNavigationResources(content::WebUIDataSource* source) {
@@ -202,13 +207,15 @@ void AddGestureNavigationResources(content::WebUIDataSource* source) {
IDR_GESTURE_NAVIGATION_GO_BACK_ANIMATION);
source->AddResourcePath("gesture_hotseat_overview.json",
IDR_GESTURE_NAVIGATION_HOTSEAT_OVERVIEW_ANIMATION);
- source->OverrideContentSecurityPolicyWorkerSrc("worker-src blob: 'self';");
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::WorkerSrc, "worker-src blob: 'self';");
}
void AddMarketingOptInResources(content::WebUIDataSource* source) {
source->AddResourcePath("all_set.json",
IDR_MARKETING_OPT_IN_ALL_SET_ANIMATION);
- source->OverrideContentSecurityPolicyWorkerSrc("worker-src blob: 'self';");
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::WorkerSrc, "worker-src blob: 'self';");
}
void AddFingerprintResources(content::WebUIDataSource* source) {
@@ -238,7 +245,9 @@ void AddFingerprintResources(content::WebUIDataSource* source) {
// lottie animations, this update has to be performed manually. As the usage
// increases, set this as the default so manual override is no longer
// required.
- source->OverrideContentSecurityPolicyWorkerSrc("worker-src blob: 'self';");
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::WorkerSrc,
+ "worker-src blob: 'self';");
} else {
source->AddResourcePath("fingerprint_scanner_animation.png", animation_id);
}
@@ -250,10 +259,12 @@ void AddDebuggerResources(content::WebUIDataSource* source) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
bool enable_debugger =
command_line->HasSwitch(::chromeos::switches::kShowOobeDevOverlay);
- // TODO(crbug.com/1073095): Also enable for ChromeOS test images.
- // Enable for ChromeOS-on-linux for developers.
- bool test_mode = !base::SysInfo::IsRunningOnChromeOS();
- if (enable_debugger && test_mode) {
+ // Enable for ChromeOS-on-linux for developers and test images.
+ if (enable_debugger && base::SysInfo::IsRunningOnChromeOS()) {
+ LOG(WARNING) << "OOBE Debug overlay can only be used on test images";
+ base::SysInfo::CrashIfChromeOSNonTestImage();
+ }
+ if (enable_debugger) {
source->AddResourcePath(kDebuggerJSPath, IDR_OOBE_DEBUGGER_JS);
} else {
source->AddResourcePath(kDebuggerJSPath, IDR_OOBE_DEBUGGER_STUB_JS);
@@ -325,8 +336,8 @@ content::WebUIDataSource* CreateOobeUIDataSource(
AddDebuggerResources(source);
source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS);
- source->OverrideContentSecurityPolicyObjectSrc(
- "object-src chrome:;");
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ObjectSrc, "object-src chrome:;");
// Only add a filter when runing as test.
const bool is_running_test = command_line->HasSwitch(::switches::kTestName) ||
@@ -348,14 +359,6 @@ std::string GetDisplayType(const GURL& url) {
return path;
}
-bool IsRemoraRequisitioned() {
- policy::DeviceCloudPolicyManagerChromeOS* policy_manager =
- g_browser_process->platform_part()
- ->browser_policy_connector_chromeos()
- ->GetDeviceCloudPolicyManager();
- return policy_manager && policy_manager->IsRemoraRequisition();
-}
-
} // namespace
// static
@@ -454,13 +457,15 @@ void OobeUI::ConfigureOobeDisplay() {
AddScreenHandler(
std::make_unique<MarketingOptInScreenHandler>(js_calls_container_.get()));
+ AddScreenHandler(std::make_unique<GaiaPasswordChangedScreenHandler>(
+ js_calls_container_.get()));
+
auto password_change_handler =
std::make_unique<ActiveDirectoryPasswordChangeScreenHandler>(
js_calls_container_.get(), core_handler_);
AddScreenHandler(std::make_unique<GaiaScreenHandler>(
- js_calls_container_.get(), core_handler_, network_state_informer_,
- password_change_handler.get()));
+ js_calls_container_.get(), core_handler_, network_state_informer_));
AddScreenHandler(std::move(password_change_handler));
@@ -494,6 +499,9 @@ void OobeUI::ConfigureOobeDisplay() {
AddScreenHandler(std::make_unique<PackagedLicenseScreenHandler>(
js_calls_container_.get()));
+ AddScreenHandler(
+ std::make_unique<TpmErrorScreenHandler>(js_calls_container_.get()));
+
Profile* profile = Profile::FromWebUI(web_ui());
// Set up the chrome://theme/ source, for Chrome logo.
content::URLDataSource::Add(profile, std::make_unique<ThemeSource>(profile));
@@ -514,7 +522,7 @@ void OobeUI::ConfigureOobeDisplay() {
content::URLDataSource::Add(profile,
std::make_unique<chromeos::VideoSource>());
- if (IsRemoraRequisitioned())
+ if (policy::EnrollmentRequisitionManager::IsRemoraRequisition())
oobe_display_chooser_ = std::make_unique<OobeDisplayChooser>();
}
@@ -547,7 +555,7 @@ void OobeUI::BindInterface(
OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url)
: ui::MojoWebUIController(web_ui, true /* enable_chrome_send */) {
// TODO(crbug.com/1082670): Remove excessive logging after investigation.
- LOG(ERROR) << "Creating new OobeUI";
+ LOG(ERROR) << "1082670 : Creating new OobeUI";
display_type_ = GetDisplayType(url);
@@ -648,12 +656,12 @@ void OobeUI::AddScreenHandler(std::unique_ptr<BaseScreenHandler> handler) {
void OobeUI::InitializeHandlers() {
// TODO(crbug.com/1082670): Remove excessive logging after investigation.
- LOG(ERROR) << "OobeUI::InitializeHandlers";
+ LOG(ERROR) << "1082670 : OobeUI::InitializeHandlers";
js_calls_container_->ExecuteDeferredJSCalls(web_ui());
// TODO(crbug.com/1082670): Remove excessive logging after investigation.
- LOG(ERROR) << "OobeUI::Marking as ready and executing callbacks";
+ LOG(ERROR) << "1082670 : OobeUI::Marking as ready and executing callbacks";
ready_ = true;
for (size_t i = 0; i < ready_callbacks_.size(); ++i)
@@ -686,7 +694,8 @@ bool OobeUI::IsScreenInitialized(OobeScreenId screen) {
bool OobeUI::IsJSReady(const base::Closure& display_is_ready_callback) {
// TODO(crbug.com/1082670): Remove excessive logging after investigation.
- LOG(ERROR) << "OobeUI::IsJSReady? = " << ready_;
+ LOG(ERROR) << "1082670 : OobeUI::IsJSReady? = " << ready_;
+
if (!ready_)
ready_callbacks_.push_back(display_is_ready_callback);
return ready_;
@@ -699,8 +708,7 @@ void OobeUI::ShowOobeUI(bool show) {
oobe_display_chooser_->TryToPlaceUiOnTouchDisplay();
}
-void OobeUI::ShowSigninScreen(SigninScreenHandlerDelegate* delegate,
- NativeWindowDelegate* native_window_delegate) {
+void OobeUI::ShowSigninScreen(SigninScreenHandlerDelegate* delegate) {
// Check our device mode.
policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
@@ -712,7 +720,6 @@ void OobeUI::ShowSigninScreen(SigninScreenHandlerDelegate* delegate,
}
signin_screen_handler_->SetDelegate(delegate);
- signin_screen_handler_->SetNativeWindowDelegate(native_window_delegate);
signin_screen_handler_->Show(core_handler_->show_oobe_ui());
}
@@ -723,7 +730,6 @@ void OobeUI::ForwardAccelerator(std::string accelerator_name) {
void OobeUI::ResetSigninScreenHandlerDelegate() {
signin_screen_handler_->SetDelegate(nullptr);
- signin_screen_handler_->SetNativeWindowDelegate(nullptr);
}
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 a87658eadf2..676a0c4ab5c 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/oobe_ui.h
@@ -29,7 +29,6 @@ class DictionaryValue;
namespace chromeos {
class ErrorScreen;
-class NativeWindowDelegate;
class NetworkStateInformer;
class OobeDisplayChooser;
class SigninScreenHandler;
@@ -87,8 +86,7 @@ class OobeUI : public ui::MojoWebUIController {
void ShowOobeUI(bool show);
// Shows the signin screen.
- void ShowSigninScreen(SigninScreenHandlerDelegate* delegate,
- NativeWindowDelegate* native_window_delegate);
+ void ShowSigninScreen(SigninScreenHandlerDelegate* delegate);
// Forwards an accelerator to the webui to be handled.
void ForwardAccelerator(std::string accelerator_name);
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/saml_challenge_key_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/saml_challenge_key_handler.cc
index 499ad8e79e8..489d834c216 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/saml_challenge_key_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/saml_challenge_key_handler.cc
@@ -6,6 +6,7 @@
#include "base/base64.h"
#include "base/bind.h"
+#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/attestation/tpm_challenge_key_result.h"
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 98622fce340..0ae35058be3 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
@@ -71,7 +71,6 @@
#include "chrome/browser/ui/webui/chromeos/login/error_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/l10n_util.h"
-#include "chrome/browser/ui/webui/chromeos/login/native_window_delegate.h"
#include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h"
#include "chrome/common/channel_info.h"
#include "chrome/common/pref_names.h"
@@ -159,12 +158,6 @@ class CallOnReturn {
DISALLOW_COPY_AND_ASSIGN(CallOnReturn);
};
-policy::MinimumVersionPolicyHandler* GetMinimumVersionPolicyHandler() {
- return g_browser_process->platform_part()
- ->browser_policy_connector_chromeos()
- ->GetMinimumVersionPolicyHandler();
-}
-
} // namespace
namespace chromeos {
@@ -323,10 +316,6 @@ void SigninScreenHandler::DeclareLocalizedValues(
builder->Add("offlineLogin", IDS_OFFLINE_LOGIN_HTML);
builder->Add("ownerUserPattern", IDS_LOGIN_POD_OWNER_USER);
builder->Add("removeUser", IDS_LOGIN_POD_REMOVE_USER);
- builder->Add("errorTpmFailureTitle", IDS_LOGIN_ERROR_TPM_FAILURE_TITLE);
- builder->Add("errorTpmFailureReboot", IDS_LOGIN_ERROR_TPM_FAILURE_REBOOT);
- builder->Add("errorTpmFailureRebootButton",
- IDS_LOGIN_ERROR_TPM_FAILURE_REBOOT_BUTTON);
policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
@@ -349,20 +338,9 @@ void SigninScreenHandler::DeclareLocalizedValues(
builder->Add("multiProfilesOwnerPrimaryOnlyMsg",
IDS_MULTI_PROFILES_OWNER_PRIMARY_ONLY_MSG);
- // Strings used by password changed dialog.
- builder->Add("oldPasswordHint", IDS_LOGIN_PASSWORD_CHANGED_OLD_PASSWORD_HINT);
- builder->Add("oldPasswordIncorrect",
- IDS_LOGIN_PASSWORD_CHANGED_INCORRECT_OLD_PASSWORD);
- builder->Add("proceedAnywayButton",
- IDS_LOGIN_PASSWORD_CHANGED_PROCEED_ANYWAY_BUTTON);
+ // Used by SAML password dialog.
builder->Add("nextButtonText", IDS_OFFLINE_LOGIN_NEXT_BUTTON_TEXT);
- builder->Add("forgotOldPasswordButtonText",
- IDS_LOGIN_PASSWORD_CHANGED_FORGOT_PASSWORD);
- builder->AddF("passwordChangedTitle", IDS_LOGIN_PASSWORD_CHANGED_TITLE,
- ui::GetChromeOSDeviceName());
- builder->Add("passwordChangedProceedAnywayTitle",
- IDS_LOGIN_PASSWORD_CHANGED_PROCEED_ANYWAY);
- builder->Add("passwordChangedTryAgain", IDS_LOGIN_PASSWORD_CHANGED_TRY_AGAIN);
+
builder->Add("publicAccountInfoFormat", IDS_LOGIN_PUBLIC_ACCOUNT_INFO_FORMAT);
builder->Add("publicAccountReminder",
IDS_LOGIN_PUBLIC_ACCOUNT_SIGNOUT_REMINDER);
@@ -439,7 +417,6 @@ void SigninScreenHandler::RegisterMessages() {
&SigninScreenHandler::HandleLaunchSAMLPublicSession);
AddRawCallback("offlineLogin", &SigninScreenHandler::HandleOfflineLogin);
AddCallback("rebootSystem", &SigninScreenHandler::HandleRebootSystem);
- AddCallback("removeUser", &SigninScreenHandler::HandleRemoveUser);
AddCallback("toggleEnrollmentScreen",
&SigninScreenHandler::HandleToggleEnrollmentScreen);
AddCallback("toggleEnableDebuggingScreen",
@@ -451,11 +428,7 @@ void SigninScreenHandler::RegisterMessages() {
AddCallback("openInternetDetailDialog",
&SigninScreenHandler::HandleOpenInternetDetailDialog);
AddCallback("loginVisible", &SigninScreenHandler::HandleLoginVisible);
- AddCallback("cancelPasswordChangedFlow",
- &SigninScreenHandler::HandleCancelPasswordChangedFlow);
AddCallback("cancelUserAdding", &SigninScreenHandler::HandleCancelUserAdding);
- AddCallback("migrateUserData", &SigninScreenHandler::HandleMigrateUserData);
- AddCallback("resyncUserData", &SigninScreenHandler::HandleResyncUserData);
AddCallback("loginUIStateChanged",
&SigninScreenHandler::HandleLoginUIStateChanged);
AddCallback("showLoadingTimeoutError",
@@ -492,11 +465,6 @@ void SigninScreenHandler::SetDelegate(SigninScreenHandlerDelegate* delegate) {
delegate_->SetWebUIHandler(this);
}
-void SigninScreenHandler::SetNativeWindowDelegate(
- NativeWindowDelegate* native_window_delegate) {
- native_window_delegate_ = native_window_delegate;
-}
-
void SigninScreenHandler::OnNetworkReady() {
VLOG(1) << "OnNetworkReady() call.";
gaia_screen_handler_->MaybePreloadAuthExtension();
@@ -931,26 +899,10 @@ void SigninScreenHandler::ShowError(int login_attempts,
help_topic_id);
}
-void SigninScreenHandler::ShowErrorScreen(LoginDisplay::SigninError error_id) {
- switch (error_id) {
- case LoginDisplay::TPM_ERROR:
- core_oobe_view_->ShowTpmError();
- break;
- default:
- NOTREACHED() << "Unknown sign in error";
- break;
- }
-}
-
void SigninScreenHandler::ShowSigninUI(const std::string& email) {
core_oobe_view_->ShowSignInUI(email);
}
-void SigninScreenHandler::ShowPasswordChangedDialog(bool show_password_error,
- const std::string& email) {
- core_oobe_view_->ShowPasswordChangedScreen(show_password_error, email);
-}
-
void SigninScreenHandler::ShowWhitelistCheckFailedError() {
gaia_screen_handler_->ShowWhitelistCheckFailedError();
}
@@ -1138,20 +1090,6 @@ void SigninScreenHandler::HandleRebootSystem() {
power_manager::REQUEST_RESTART_FOR_USER, "WebUI signin screen");
}
-void SigninScreenHandler::HandleRemoveUser(const AccountId& account_id) {
- if (delegate_ &&
- (delegate_->IsUserSigninCompleted() || delegate_->IsSigninInProgress())) {
- return;
- }
-
- ProfileMetrics::LogProfileDeleteUser(
- ProfileMetrics::DELETE_PROFILE_USER_MANAGER);
-
- if (!delegate_)
- return;
- delegate_->RemoveUser(account_id);
-}
-
void SigninScreenHandler::HandleToggleEnrollmentScreen() {
if (delegate_)
delegate_->ShowEnterpriseEnrollmentScreen();
@@ -1201,12 +1139,6 @@ void SigninScreenHandler::HandleAccountPickerReady() {
return;
}
- if (delegate_ && !oobe_ui_ && GetMinimumVersionPolicyHandler() &&
- !GetMinimumVersionPolicyHandler()->RequirementsAreSatisfied()) {
- delegate_->ShowUpdateRequiredScreen();
- return;
- }
-
is_account_picker_showing_first_time_ = true;
// The wallpaper may have been set before the instance is initialized, so make
@@ -1250,32 +1182,11 @@ void SigninScreenHandler::HandleLoginVisible(const std::string& source) {
OnPreferencesChanged();
}
-void SigninScreenHandler::HandleCancelPasswordChangedFlow(
- const AccountId& account_id) {
- if (account_id.is_valid()) {
- RecordReauthReason(account_id, ReauthReason::PASSWORD_UPDATE_SKIPPED);
- }
- gaia_screen_handler_->StartClearingCookies(
- base::Bind(&SigninScreenHandler::CancelPasswordChangedFlowInternal,
- weak_factory_.GetWeakPtr()));
-}
-
void SigninScreenHandler::HandleCancelUserAdding() {
if (delegate_)
delegate_->CancelUserAdding();
}
-void SigninScreenHandler::HandleMigrateUserData(
- const std::string& old_password) {
- if (LoginDisplayHost::default_host())
- LoginDisplayHost::default_host()->MigrateUserData(old_password);
-}
-
-void SigninScreenHandler::HandleResyncUserData() {
- if (LoginDisplayHost::default_host())
- LoginDisplayHost::default_host()->ResyncUserData();
-}
-
void SigninScreenHandler::HandleLoginUIStateChanged(const std::string& source,
bool active) {
VLOG(0) << "Login WebUI >> active: " << active << ", "
@@ -1432,14 +1343,6 @@ bool SigninScreenHandler::AllWhitelistedUsersPresent() {
return true;
}
-void SigninScreenHandler::CancelPasswordChangedFlowInternal() {
- if (delegate_)
- ShowImpl();
-
- if (LoginDisplayHost::default_host())
- LoginDisplayHost::default_host()->CancelPasswordChangedFlow();
-}
-
bool SigninScreenHandler::IsGaiaVisible() const {
return IsSigninScreen(GetCurrentScreen()) &&
ui_state_ == UI_STATE_GAIA_SIGNIN;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h
index fd1bcb346e3..f250227407b 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h
@@ -55,7 +55,6 @@ class CoreOobeView;
class ErrorScreensHistogramHelper;
class GaiaScreenHandler;
class LoginFeedback;
-class NativeWindowDelegate;
class User;
class UserContext;
@@ -73,10 +72,7 @@ class LoginDisplayWebUIHandler {
const std::string& error_text,
const std::string& help_link_text,
HelpAppLauncher::HelpTopic help_topic_id) = 0;
- virtual void ShowErrorScreen(LoginDisplay::SigninError error_id) = 0;
virtual void ShowSigninUI(const std::string& email) = 0;
- virtual void ShowPasswordChangedDialog(bool show_password_error,
- const std::string& email) = 0;
virtual void ShowWhitelistCheckFailedError() = 0;
virtual void LoadUsers(const user_manager::UserList& users,
const base::ListValue& users_list) = 0;
@@ -119,16 +115,10 @@ class SigninScreenHandlerDelegate {
// Show wrong hwid screen.
virtual void ShowWrongHWIDScreen() = 0;
- // Show update required screen.
- virtual void ShowUpdateRequiredScreen() = 0;
-
// --------------- Rest of the methods.
// Cancels user adding.
virtual void CancelUserAdding() = 0;
- // Attempts to remove given user.
- virtual void RemoveUser(const AccountId& account_id) = 0;
-
// Let the delegate know about the handler it is supposed to be using.
virtual void SetWebUIHandler(LoginDisplayWebUIHandler* webui_handler) = 0;
@@ -197,8 +187,6 @@ class SigninScreenHandler
// delegate is set before Show() method will be called.
void SetDelegate(SigninScreenHandlerDelegate* delegate);
- void SetNativeWindowDelegate(NativeWindowDelegate* native_window_delegate);
-
// NetworkStateInformer::NetworkStateInformerObserver implementation:
void OnNetworkReady() override;
void UpdateState(NetworkError::ErrorReason reason) override;
@@ -272,9 +260,6 @@ class SigninScreenHandler
const std::string& help_link_text,
HelpAppLauncher::HelpTopic help_topic_id) override;
void ShowSigninUI(const std::string& email) override;
- void ShowPasswordChangedDialog(bool show_password_error,
- const std::string& email) override;
- void ShowErrorScreen(LoginDisplay::SigninError error_id) override;
void ShowWhitelistCheckFailedError() override;
void LoadUsers(const user_manager::UserList& users,
const base::ListValue& users_list) override;
@@ -318,7 +303,6 @@ class SigninScreenHandler
const std::string& input_method);
void HandleOfflineLogin(const base::ListValue* args);
void HandleRebootSystem();
- void HandleRemoveUser(const AccountId& account_id);
void HandleToggleEnrollmentScreen();
void HandleToggleEnrollmentAd();
void HandleToggleEnableDebuggingScreen();
@@ -334,10 +318,7 @@ class SigninScreenHandler
void HandleAccountPickerReady();
void HandleOpenInternetDetailDialog();
void HandleLoginVisible(const std::string& source);
- void HandleCancelPasswordChangedFlow(const AccountId& account_id);
void HandleCancelUserAdding();
- void HandleMigrateUserData(const std::string& password);
- void HandleResyncUserData();
void HandleLoginUIStateChanged(const std::string& source, bool active);
void HandleLoginScreenUpdate();
void HandleShowLoadingTimeoutError();
@@ -409,9 +390,6 @@ class SigninScreenHandler
// A delegate that glues this handler with backend LoginDisplay.
SigninScreenHandlerDelegate* delegate_ = nullptr;
- // A delegate used to get gfx::NativeWindow.
- NativeWindowDelegate* native_window_delegate_ = nullptr;
-
// Whether screen should be shown right after initialization.
bool show_on_init_ = false;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/supervision_transition_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/supervision_transition_screen_handler.cc
index 311bd578880..7d212337687 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/supervision_transition_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/supervision_transition_screen_handler.cc
@@ -13,6 +13,7 @@
#include "chrome/browser/chromeos/arc/session/arc_session_manager.h"
#include "chrome/browser/chromeos/login/oobe_screen.h"
#include "chrome/browser/chromeos/login/screens/supervision_transition_screen.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/ash/login_screen_client.h"
#include "chrome/browser/ui/ash/system_tray_client.h"
@@ -90,7 +91,10 @@ void SupervisionTransitionScreenHandler::Show() {
&SupervisionTransitionScreenHandler::OnSupervisionTransitionFailed,
weak_factory_.GetWeakPtr()));
- registrar_.Init(profile_->GetPrefs());
+ Profile* profile = ProfileManager::GetActiveUserProfile();
+ DCHECK(!ProfileHelper::IsSigninProfile(profile));
+
+ registrar_.Init(profile->GetPrefs());
registrar_.Add(
arc::prefs::kArcSupervisionTransition,
base::BindRepeating(
@@ -106,7 +110,7 @@ void SupervisionTransitionScreenHandler::Show() {
base::DictionaryValue data;
data.SetBoolean("isRemovingSupervision",
- arc::GetSupervisionTransition(profile_) ==
+ arc::GetSupervisionTransition(profile) ==
arc::ArcSupervisionTransition::CHILD_TO_REGULAR);
ShowScreenWithData(kScreenId, &data);
}
@@ -118,8 +122,6 @@ base::OneShotTimer* SupervisionTransitionScreenHandler::GetTimerForTesting() {
}
void SupervisionTransitionScreenHandler::Initialize() {
- profile_ = ProfileManager::GetPrimaryUserProfile();
-
if (!screen_ || !show_on_init_)
return;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/supervision_transition_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/supervision_transition_screen_handler.h
index 5785e0e65fc..76d085f82d7 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/supervision_transition_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/supervision_transition_screen_handler.h
@@ -82,9 +82,6 @@ class SupervisionTransitionScreenHandler
base::TimeTicks screen_shown_time_;
- // The primary user profile.
- Profile* profile_ = nullptr;
-
// Timer used to exit the page when timeout reaches.
base::OneShotTimer timer_;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.cc
index 2e83bfb9b3d..a7bdc97a447 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.cc
@@ -13,6 +13,7 @@
#include "components/login/localized_values_builder.h"
#include "components/user_manager/user_manager.h"
#include "ui/base/l10n/l10n_util.h"
+#include "ui/chromeos/devicetype_utils.h"
namespace {
@@ -111,6 +112,8 @@ void SyncConsentScreenHandler::DeclareLocalizedValues(
builder);
// SplitSettingsSync strings.
+ RememberLocalizedValue("syncConsentScreenSubtitle",
+ IDS_LOGIN_SYNC_CONSENT_SCREEN_SUBTITLE, builder);
RememberLocalizedValue("syncConsentScreenOsSyncName",
IDS_LOGIN_SYNC_CONSENT_SCREEN_OS_SYNC_NAME, builder);
RememberLocalizedValue("syncConsentScreenOsSyncDescription",
@@ -119,6 +122,10 @@ void SyncConsentScreenHandler::DeclareLocalizedValues(
RememberLocalizedValue("syncConsentScreenChromeBrowserSyncName",
IDS_LOGIN_SYNC_CONSENT_SCREEN_CHROME_BROWSER_SYNC_NAME,
builder);
+ RememberLocalizedValue("syncConsentScreenAccept",
+ IDS_LOGIN_SYNC_CONSENT_SCREEN_ACCEPT2, builder);
+ RememberLocalizedValue("syncConsentScreenDecline",
+ IDS_LOGIN_SYNC_CONSENT_SCREEN_DECLINE2, builder);
}
void SyncConsentScreenHandler::Bind(SyncConsentScreen* screen) {
@@ -127,10 +134,10 @@ void SyncConsentScreenHandler::Bind(SyncConsentScreen* screen) {
}
void SyncConsentScreenHandler::Show() {
- bool is_child_account_ =
- user_manager::UserManager::Get()->IsLoggedInAsChildUser();
+ auto* user_manager = user_manager::UserManager::Get();
base::DictionaryValue data;
- data.SetBoolean("isChildAccount", is_child_account_);
+ data.SetBoolean("isChildAccount", user_manager->IsLoggedInAsChildUser());
+ data.SetString("deviceType", ui::GetChromeOSDeviceName());
ShowScreenWithData(kScreenId, &data);
}
@@ -149,6 +156,8 @@ void SyncConsentScreenHandler::RegisterMessages() {
&SyncConsentScreenHandler::HandleContinueWithDefaults);
AddCallback("login.SyncConsentScreen.acceptAndContinue",
&SyncConsentScreenHandler::HandleAcceptAndContinue);
+ AddCallback("login.SyncConsentScreen.declineAndContinue",
+ &SyncConsentScreenHandler::HandleDeclineAndContinue);
}
void SyncConsentScreenHandler::GetAdditionalParameters(
@@ -198,16 +207,26 @@ void SyncConsentScreenHandler::HandleContinueWithDefaults(
void SyncConsentScreenHandler::HandleAcceptAndContinue(
const login::StringList& consent_description,
+ const std::string& consent_confirmation) {
+ Continue(consent_description, consent_confirmation, UserChoice::kAccepted);
+}
+
+void SyncConsentScreenHandler::HandleDeclineAndContinue(
+ const login::StringList& consent_description,
+ const std::string& consent_confirmation) {
+ Continue(consent_description, consent_confirmation, UserChoice::kDeclined);
+}
+
+void SyncConsentScreenHandler::Continue(
+ const login::StringList& consent_description,
const std::string& consent_confirmation,
- bool enable_os_sync,
- bool enable_browser_sync) {
+ UserChoice choice) {
DCHECK(chromeos::features::IsSplitSettingsSyncEnabled());
std::vector<int> consent_description_ids;
int consent_confirmation_id;
GetConsentIDs(known_string_ids_, consent_description, consent_confirmation,
&consent_description_ids, &consent_confirmation_id);
- screen_->OnAcceptAndContinue(consent_description_ids, consent_confirmation_id,
- enable_os_sync, enable_browser_sync);
+ screen_->OnContinue(consent_description_ids, consent_confirmation_id, choice);
SyncConsentScreen::SyncConsentScreenTestDelegate* test_delegate =
screen_->GetDelegateForTesting();
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.h
index af58bff845a..a11e554f091 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/sync_consent_screen_handler.h
@@ -42,6 +42,10 @@ class SyncConsentScreenHandler : public BaseScreenHandler,
public:
using TView = SyncConsentScreenView;
+ // These values are persisted to logs. Entries should not be renumbered and
+ // numeric values should never be reused. Public for testing.
+ enum class UserChoice { kDeclined = 0, kAccepted = 1, kMaxValue = kAccepted };
+
explicit SyncConsentScreenHandler(JSCallsContainer* js_calls_container);
~SyncConsentScreenHandler() override;
@@ -67,10 +71,17 @@ class SyncConsentScreenHandler : public BaseScreenHandler,
void HandleContinueWithDefaults(
const ::login::StringList& consent_description,
const std::string& consent_confirmation);
+
+ // WebUI message handlers for SplitSettingsSync.
void HandleAcceptAndContinue(const ::login::StringList& consent_description,
- const std::string& consent_confirmation,
- bool enable_os_sync,
- bool enable_browser_sync);
+ const std::string& consent_confirmation);
+ void HandleDeclineAndContinue(const ::login::StringList& consent_description,
+ const std::string& consent_confirmation);
+
+ // Helper for the accept and decline cases.
+ void Continue(const ::login::StringList& consent_description,
+ const std::string& consent_confirmation,
+ UserChoice choice);
// Adds resource |resource_id| both to |builder| and to |known_string_ids_|.
void RememberLocalizedValue(const std::string& name,
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc
index 241a06360c0..873c6a473fc 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.cc
@@ -63,6 +63,8 @@ void TermsOfServiceScreenHandler::DeclareLocalizedValues(
IDS_TERMS_OF_SERVICE_SCREEN_BACK_BUTTON);
builder->Add("termsOfServiceAcceptButton",
IDS_TERMS_OF_SERVICE_SCREEN_ACCEPT_BUTTON);
+ builder->Add("termsOfServiceRetryButton",
+ IDS_TERMS_OF_SERVICE_SCREEN_RETRY_BUTTON);
}
void TermsOfServiceScreenHandler::SetScreen(TermsOfServiceScreen* screen) {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/tpm_error_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/tpm_error_screen_handler.cc
new file mode 100644
index 00000000000..16f1e686924
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/tpm_error_screen_handler.cc
@@ -0,0 +1,62 @@
+// Copyright 2020 The Chromium 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/tpm_error_screen_handler.h"
+
+#include "base/values.h"
+#include "chrome/browser/chromeos/login/oobe_screen.h"
+#include "chrome/browser/chromeos/login/screens/tpm_error_screen.h"
+#include "chrome/grit/chromium_strings.h"
+#include "chrome/grit/generated_resources.h"
+#include "components/login/localized_values_builder.h"
+
+namespace chromeos {
+
+constexpr StaticOobeScreenId TpmErrorView::kScreenId;
+
+TpmErrorScreenHandler::TpmErrorScreenHandler(
+ JSCallsContainer* js_calls_container)
+ : BaseScreenHandler(kScreenId, js_calls_container) {
+ set_user_acted_method_path("login.TPMErrorMessageScreen.userActed");
+}
+
+TpmErrorScreenHandler::~TpmErrorScreenHandler() {
+ if (screen_)
+ screen_->OnViewDestroyed(this);
+}
+
+void TpmErrorScreenHandler::DeclareLocalizedValues(
+ ::login::LocalizedValuesBuilder* builder) {
+ builder->Add("errorTpmFailureTitle", IDS_LOGIN_ERROR_TPM_FAILURE_TITLE);
+ builder->Add("errorTpmFailureReboot", IDS_LOGIN_ERROR_TPM_FAILURE_REBOOT);
+ builder->Add("errorTpmFailureRebootButton",
+ IDS_LOGIN_ERROR_TPM_FAILURE_REBOOT_BUTTON);
+}
+
+void TpmErrorScreenHandler::Initialize() {
+ if (show_on_init_) {
+ show_on_init_ = false;
+ Show();
+ }
+}
+
+void TpmErrorScreenHandler::Show() {
+ if (!page_is_ready()) {
+ show_on_init_ = true;
+ return;
+ }
+ ShowScreen(kScreenId);
+}
+
+void TpmErrorScreenHandler::Bind(TpmErrorScreen* screen) {
+ screen_ = screen;
+ BaseScreenHandler::SetBaseScreen(screen_);
+}
+
+void TpmErrorScreenHandler::Unbind() {
+ screen_ = nullptr;
+ BaseScreenHandler::SetBaseScreen(nullptr);
+}
+
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/tpm_error_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/tpm_error_screen_handler.h
new file mode 100644
index 00000000000..a8258774ae7
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/tpm_error_screen_handler.h
@@ -0,0 +1,60 @@
+// Copyright 2020 The Chromium 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_TPM_ERROR_SCREEN_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_TPM_ERROR_SCREEN_HANDLER_H_
+
+#include <string>
+
+#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
+
+namespace chromeos {
+
+class TpmErrorScreen;
+
+// Interface for dependency injection between TpmErrorScreen and its
+// WebUI representation.
+class TpmErrorView {
+ public:
+ constexpr static StaticOobeScreenId kScreenId{"tpm-error-message"};
+
+ virtual ~TpmErrorView() {}
+
+ // Shows the contents of the screen.
+ virtual void Show() = 0;
+
+ // Binds |screen| to the view.
+ virtual void Bind(TpmErrorScreen* screen) = 0;
+
+ // Unbinds the screen from the view.
+ virtual void Unbind() = 0;
+};
+
+class TpmErrorScreenHandler : public TpmErrorView, public BaseScreenHandler {
+ public:
+ using TView = TpmErrorView;
+
+ explicit TpmErrorScreenHandler(JSCallsContainer* js_calls_container);
+ TpmErrorScreenHandler(const TpmErrorScreenHandler&) = delete;
+ TpmErrorScreenHandler& operator=(const TpmErrorScreenHandler&) = delete;
+ ~TpmErrorScreenHandler() override;
+
+ private:
+ void Show() override;
+ void Bind(TpmErrorScreen* screen) override;
+ void Unbind() override;
+
+ // BaseScreenHandler:
+ void DeclareLocalizedValues(
+ ::login::LocalizedValuesBuilder* builder) override;
+ void Initialize() override;
+
+ bool show_on_init_ = false;
+
+ TpmErrorScreen* screen_ = nullptr;
+};
+
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_TPM_ERROR_SCREEN_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.cc
index d938229bbd9..1ba28b56d11 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.cc
@@ -65,6 +65,7 @@ void UpdateRequiredScreenHandler::DeclareLocalizedValues(
IDS_OFFERS_CONSENT_INFOBAR_DISABLE_BUTTON);
builder->Add("noNetworkMessage",
IDS_UPDATE_REQUIRED_SCREEN_NO_NETWORK_MESSAGE);
+ builder->Add("eolAdminMessageTitle", IDS_UPDATE_REQUIRED_EOL_ADMIN_MESSAGE);
}
void UpdateRequiredScreenHandler::Initialize() {
@@ -81,6 +82,10 @@ void UpdateRequiredScreenHandler::SetEnterpriseAndDeviceName(
enterpriseDomain, deviceName);
}
+void UpdateRequiredScreenHandler::SetEolMessage(const std::string& eolMessage) {
+ CallJS("login.UpdateRequiredScreen.setEolMessage", eolMessage);
+}
+
void UpdateRequiredScreenHandler::Show() {
if (!page_is_ready()) {
show_on_init_ = true;
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.h
index 48bffc48e60..6c01540cd95 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.h
@@ -65,6 +65,7 @@ class UpdateRequiredView {
// Set enterprise and device name to be used in strings in the UI.
virtual void SetEnterpriseAndDeviceName(const std::string& enterpriseDomain,
const base::string16& deviceName) = 0;
+ virtual void SetEolMessage(const std::string& eolMessage) = 0;
};
class UpdateRequiredScreenHandler : public UpdateRequiredView,
@@ -90,6 +91,7 @@ class UpdateRequiredScreenHandler : public UpdateRequiredView,
void SetUIState(UpdateRequiredView::UIState ui_state) override;
void SetEnterpriseAndDeviceName(const std::string& enterpriseDomain,
const base::string16& deviceName) override;
+ void SetEolMessage(const std::string& eolMessage) override;
// BaseScreenHandler:
void DeclareLocalizedValues(
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/update_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/update_screen_handler.h
index be45877d228..7f2b3630ab0 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/update_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/update_screen_handler.h
@@ -19,7 +19,7 @@ class UpdateScreen;
// representation. Owned by UpdateScreen.
class UpdateView {
public:
- constexpr static StaticOobeScreenId kScreenId{"update"};
+ constexpr static StaticOobeScreenId kScreenId{"oobe-update"};
virtual ~UpdateView() {}
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.cc
index cf6cf3e7cf3..38efaf95f19 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.cc
@@ -15,6 +15,8 @@
#include "base/task_runner_util.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
+#include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
+#include "chrome/browser/chromeos/accessibility/magnification_manager.h"
#include "chrome/browser/chromeos/login/demo_mode/demo_session.h"
#include "chrome/browser/chromeos/login/screens/welcome_screen.h"
#include "chrome/browser/chromeos/login/ui/input_events_blocker.h"
@@ -47,6 +49,12 @@ WelcomeScreenHandler::WelcomeScreenHandler(JSCallsContainer* js_calls_container,
core_oobe_view_(core_oobe_view) {
set_user_acted_method_path("login.WelcomeScreen.userActed");
DCHECK(core_oobe_view_);
+
+ AccessibilityManager* accessibility_manager = AccessibilityManager::Get();
+ CHECK(accessibility_manager);
+ accessibility_subscription_ = accessibility_manager->RegisterCallback(
+ base::Bind(&WelcomeScreenHandler::OnAccessibilityStatusChanged,
+ base::Unretained(this)));
}
WelcomeScreenHandler::~WelcomeScreenHandler() {
@@ -145,6 +153,17 @@ void WelcomeScreenHandler::DeclareLocalizedValues(
builder->Add("keyboardDropdownTitle", IDS_KEYBOARD_DROPDOWN_TITLE);
builder->Add("keyboardDropdownLabel", IDS_KEYBOARD_DROPDOWN_LABEL);
+ // OOBE accessibility options menu strings shown on each screen.
+ builder->Add("accessibilityLink", IDS_OOBE_ACCESSIBILITY_LINK);
+ builder->Add("spokenFeedbackOption", IDS_OOBE_SPOKEN_FEEDBACK_OPTION);
+ builder->Add("selectToSpeakOption", IDS_OOBE_SELECT_TO_SPEAK_OPTION);
+ builder->Add("largeCursorOption", IDS_OOBE_LARGE_CURSOR_OPTION);
+ builder->Add("highContrastOption", IDS_OOBE_HIGH_CONTRAST_MODE_OPTION);
+ builder->Add("screenMagnifierOption", IDS_OOBE_SCREEN_MAGNIFIER_OPTION);
+ builder->Add("dockedMagnifierOption", IDS_OOBE_DOCKED_MAGNIFIER_OPTION);
+ builder->Add("virtualKeyboardOption", IDS_OOBE_VIRTUAL_KEYBOARD_OPTION);
+ builder->Add("closeAccessibilityMenu", IDS_OOBE_CLOSE_ACCESSIBILITY_MENU);
+
builder->Add("a11ySettingToggleOptionOff",
IDS_A11Y_SETTING_TOGGLE_OPTION_OFF);
builder->Add("a11ySettingToggleOptionOn", IDS_A11Y_SETTING_TOGGLE_OPTION_ON);
@@ -162,6 +181,21 @@ void WelcomeScreenHandler::DeclareJSCallbacks() {
&WelcomeScreenHandler::HandleSetInputMethodId);
AddCallback("WelcomeScreen.setTimezoneId",
&WelcomeScreenHandler::HandleSetTimezoneId);
+
+ AddCallback("WelcomeScreen.enableHighContrast",
+ &WelcomeScreenHandler::HandleEnableHighContrast);
+ AddCallback("WelcomeScreen.enableLargeCursor",
+ &WelcomeScreenHandler::HandleEnableLargeCursor);
+ AddCallback("WelcomeScreen.enableVirtualKeyboard",
+ &WelcomeScreenHandler::HandleEnableVirtualKeyboard);
+ AddCallback("WelcomeScreen.enableScreenMagnifier",
+ &WelcomeScreenHandler::HandleEnableScreenMagnifier);
+ AddCallback("WelcomeScreen.enableSpokenFeedback",
+ &WelcomeScreenHandler::HandleEnableSpokenFeedback);
+ AddCallback("WelcomeScreen.enableSelectToSpeak",
+ &WelcomeScreenHandler::HandleEnableSelectToSpeak);
+ AddCallback("WelcomeScreen.enableDockedMagnifier",
+ &WelcomeScreenHandler::HandleEnableDockedMagnifier);
}
void WelcomeScreenHandler::GetAdditionalParameters(
@@ -227,8 +261,11 @@ void WelcomeScreenHandler::Initialize() {
// Reload localized strings if they are already resolved.
if (screen_ && screen_->language_list())
ReloadLocalizedContent();
+ UpdateA11yState();
}
+// WelcomeScreenHandler, private: ----------------------------------------------
+
void WelcomeScreenHandler::HandleSetLocaleId(const std::string& locale_id) {
if (screen_)
screen_->SetApplicationLocale(locale_id);
@@ -245,7 +282,71 @@ void WelcomeScreenHandler::HandleSetTimezoneId(const std::string& timezone_id) {
screen_->SetTimezone(timezone_id);
}
-// WelcomeScreenHandler, private: ----------------------------------------------
+void WelcomeScreenHandler::HandleEnableHighContrast(bool enabled) {
+ AccessibilityManager::Get()->EnableHighContrast(enabled);
+}
+
+void WelcomeScreenHandler::HandleEnableLargeCursor(bool enabled) {
+ AccessibilityManager::Get()->EnableLargeCursor(enabled);
+}
+
+void WelcomeScreenHandler::HandleEnableVirtualKeyboard(bool enabled) {
+ AccessibilityManager::Get()->EnableVirtualKeyboard(enabled);
+}
+
+void WelcomeScreenHandler::HandleEnableScreenMagnifier(bool enabled) {
+ DCHECK(MagnificationManager::Get());
+ MagnificationManager::Get()->SetMagnifierEnabled(enabled);
+}
+
+void WelcomeScreenHandler::HandleEnableSpokenFeedback(bool /* enabled */) {
+ // Checkbox is initialized on page init and updates when spoken feedback
+ // setting is changed so just toggle spoken feedback here.
+ AccessibilityManager::Get()->EnableSpokenFeedback(
+ !AccessibilityManager::Get()->IsSpokenFeedbackEnabled());
+}
+
+void WelcomeScreenHandler::HandleEnableSelectToSpeak(bool /* enabled */) {
+ // Checkbox is initialized on page init and updates when Select to Speak
+ // setting is changed so just toggle Select to Speak here.
+ AccessibilityManager::Get()->SetSelectToSpeakEnabled(
+ !AccessibilityManager::Get()->IsSelectToSpeakEnabled());
+}
+
+void WelcomeScreenHandler::HandleEnableDockedMagnifier(bool enabled) {
+ // Checkbox is initialized on page init and updates when the docked magnifier
+ // setting is changed so just toggle Select to Speak here.
+ DCHECK(MagnificationManager::Get());
+ MagnificationManager::Get()->SetDockedMagnifierEnabled(enabled);
+}
+
+void WelcomeScreenHandler::OnAccessibilityStatusChanged(
+ const AccessibilityStatusEventDetails& details) {
+ if (details.notification_type == ACCESSIBILITY_MANAGER_SHUTDOWN)
+ accessibility_subscription_.reset();
+ else
+ UpdateA11yState();
+}
+
+void WelcomeScreenHandler::UpdateA11yState() {
+ base::DictionaryValue a11y_info;
+ a11y_info.SetBoolean("highContrastEnabled",
+ AccessibilityManager::Get()->IsHighContrastEnabled());
+ a11y_info.SetBoolean("largeCursorEnabled",
+ AccessibilityManager::Get()->IsLargeCursorEnabled());
+ a11y_info.SetBoolean("spokenFeedbackEnabled",
+ AccessibilityManager::Get()->IsSpokenFeedbackEnabled());
+ a11y_info.SetBoolean("selectToSpeakEnabled",
+ AccessibilityManager::Get()->IsSelectToSpeakEnabled());
+ 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("login.WelcomeScreen.refreshA11yInfo", a11y_info);
+}
// static
std::unique_ptr<base::ListValue> WelcomeScreenHandler::GetTimezoneList() {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.h
index 437027ab74a..6f7a19e6b12 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/welcome_screen_handler.h
@@ -9,6 +9,7 @@
#include <string>
#include "base/macros.h"
+#include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
namespace base {
@@ -80,6 +81,20 @@ class WelcomeScreenHandler : public WelcomeView, public BaseScreenHandler {
void HandleSetLocaleId(const std::string& locale_id);
void HandleSetInputMethodId(const std::string& input_method_id);
void HandleSetTimezoneId(const std::string& timezone_id);
+ void HandleEnableLargeCursor(bool enabled);
+ void HandleEnableHighContrast(bool enabled);
+ void HandleEnableVirtualKeyboard(bool enabled);
+ void HandleEnableScreenMagnifier(bool enabled);
+ void HandleEnableSpokenFeedback(bool /* enabled */);
+ void HandleEnableSelectToSpeak(bool /* enabled */);
+ void HandleEnableDockedMagnifier(bool /* enabled */);
+
+ // Notification of a change in the accessibility settings.
+ void OnAccessibilityStatusChanged(
+ const AccessibilityStatusEventDetails& details);
+
+ // Updates a11y menu state based on the current a11y features state(on/off).
+ void UpdateA11yState();
// Returns available timezones. Caller gets the ownership.
static std::unique_ptr<base::ListValue> GetTimezoneList();
@@ -90,6 +105,8 @@ class WelcomeScreenHandler : public WelcomeView, public BaseScreenHandler {
// Keeps whether screen should be shown right after initialization.
bool show_on_init_ = false;
+ std::unique_ptr<AccessibilityStatusSubscription> accessibility_subscription_;
+
DISALLOW_COPY_AND_ASSIGN(WelcomeScreenHandler);
};
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.cc
index e1b8a87d274..22167c3d0b2 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.cc
@@ -16,11 +16,12 @@ constexpr StaticOobeScreenId WrongHWIDScreenView::kScreenId;
WrongHWIDScreenHandler::WrongHWIDScreenHandler(
JSCallsContainer* js_calls_container)
: BaseScreenHandler(kScreenId, js_calls_container) {
+ set_user_acted_method_path("login.WrongHWIDMessageScreen.userActed");
}
WrongHWIDScreenHandler::~WrongHWIDScreenHandler() {
- if (delegate_)
- delegate_->OnViewDestroyed(this);
+ if (screen_)
+ screen_->OnViewDestroyed(this);
}
void WrongHWIDScreenHandler::Show() {
@@ -34,10 +35,14 @@ void WrongHWIDScreenHandler::Show() {
void WrongHWIDScreenHandler::Hide() {
}
-void WrongHWIDScreenHandler::SetDelegate(WrongHWIDScreen* delegate) {
- delegate_ = delegate;
- if (page_is_ready())
- Initialize();
+void WrongHWIDScreenHandler::Bind(WrongHWIDScreen* screen) {
+ screen_ = screen;
+ BaseScreenHandler::SetBaseScreen(screen_);
+}
+
+void WrongHWIDScreenHandler::Unbind() {
+ screen_ = nullptr;
+ BaseScreenHandler::SetBaseScreen(nullptr);
}
void WrongHWIDScreenHandler::DeclareLocalizedValues(
@@ -52,22 +57,10 @@ void WrongHWIDScreenHandler::DeclareLocalizedValues(
}
void WrongHWIDScreenHandler::Initialize() {
- if (!page_is_ready() || !delegate_)
- return;
-
if (show_on_init_) {
- Show();
show_on_init_ = false;
+ Show();
}
}
-void WrongHWIDScreenHandler::RegisterMessages() {
- AddCallback("wrongHWIDOnSkip", &WrongHWIDScreenHandler::HandleOnSkip);
-}
-
-void WrongHWIDScreenHandler::HandleOnSkip() {
- if (delegate_)
- delegate_->OnExit();
-}
-
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.h b/chromium/chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.h
index c66ca8105d5..09a9b3456b5 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.h
@@ -23,7 +23,12 @@ class WrongHWIDScreenView {
virtual void Show() = 0;
virtual void Hide() = 0;
- virtual void SetDelegate(WrongHWIDScreen* delegate) = 0;
+
+ // Binds |screen| to the view.
+ virtual void Bind(WrongHWIDScreen* screen) = 0;
+
+ // Unbinds the screen from the view.
+ virtual void Unbind() = 0;
};
// WebUI implementation of WrongHWIDScreenActor.
@@ -35,24 +40,19 @@ class WrongHWIDScreenHandler : public WrongHWIDScreenView,
explicit WrongHWIDScreenHandler(JSCallsContainer* js_calls_container);
~WrongHWIDScreenHandler() override;
+ private:
// WrongHWIDScreenActor implementation:
void Show() override;
void Hide() override;
- void SetDelegate(WrongHWIDScreen* delegate) override;
+ void Bind(WrongHWIDScreen* screen) override;
+ void Unbind() override;
// BaseScreenHandler implementation:
void DeclareLocalizedValues(
::login::LocalizedValuesBuilder* builder) override;
void Initialize() override;
- // WebUIMessageHandler implementation:
- void RegisterMessages() override;
-
- private:
- // JS messages handlers.
- void HandleOnSkip();
-
- WrongHWIDScreen* delegate_ = nullptr;
+ WrongHWIDScreen* screen_ = nullptr;
// Keeps whether screen should be shown right after initialization.
bool show_on_init_ = false;
@@ -63,4 +63,3 @@ class WrongHWIDScreenHandler : public WrongHWIDScreenView,
} // namespace chromeos
#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_WRONG_HWID_SCREEN_HANDLER_H_
-
diff --git a/chromium/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.cc
index ace92dd56d2..b84b0101053 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.cc
@@ -22,32 +22,45 @@ MachineLearningInternalsUI::MachineLearningInternalsUI(
content::WebUIDataSource* const source = content::WebUIDataSource::Create(
chrome::kChromeUIMachineLearningInternalsHost);
- source->AddResourcePath(
- "chromeos/services/machine_learning/public/mojom/tensor.mojom-lite.js",
- IDR_MACHINE_LEARNING_INTERNALS_TENSOR_MOJO_JS);
- source->AddResourcePath(
- "chromeos/services/machine_learning/public/mojom/model.mojom-lite.js",
- IDR_MACHINE_LEARNING_INTERNALS_MODEL_MOJO_JS);
- source->AddResourcePath(
- "chromeos/services/machine_learning/public/mojom/"
- "graph_executor.mojom-lite.js",
- IDR_MACHINE_LEARNING_INTERNALS_GRAPH_EXECUTOR_MOJO_JS);
- source->AddResourcePath(
- "chromeos/services/machine_learning/public/"
- "mojom/machine_learning_service.mojom-lite.js",
- IDR_MACHINE_LEARNING_INTERNALS_MACHINE_LEARNING_SERVICE_MOJO_JS);
- source->AddResourcePath(
- "chrome/browser/ui/webui/chromeos/machine_learning/"
- "machine_learning_internals_page_handler.mojom-lite.js",
- IDR_MACHINE_LEARNING_INTERNALS_PAGE_HANDLER_MOJO_JS);
- source->AddResourcePath("machine_learning_internals.js",
- IDR_MACHINE_LEARNING_INTERNALS_JS);
- source->AddResourcePath("machine_learning_internals_utils.js",
- IDR_MACHINE_LEARNING_INTERNALS_UTILS_JS);
- source->AddResourcePath("test_model_tab.js",
- IDR_MACHINE_LEARNING_INTERNALS_TEST_MODEL_TAB_JS);
- source->SetDefaultResource(IDR_MACHINE_LEARNING_INTERNALS_HTML);
+ const std::map<int, std::string> resource_paths = {
+ {IDR_MACHINE_LEARNING_INTERNALS_GRAPH_EXECUTOR_MOJO_JS,
+ "chromeos/services/machine_learning/public/mojom/"
+ "graph_executor.mojom-lite.js"},
+
+ {IDR_MACHINE_LEARNING_INTERNALS_HANDWRITING_RECOGNIZER_MOJO_JS,
+ "chromeos/services/machine_learning/public/mojom/"
+ "handwriting_recognizer.mojom-lite.js"},
+
+ {IDR_MACHINE_LEARNING_INTERNALS_JS, "machine_learning_internals.js"},
+
+ {IDR_MACHINE_LEARNING_INTERNALS_MACHINE_LEARNING_SERVICE_MOJO_JS,
+ "chromeos/services/machine_learning/public/mojom/"
+ "machine_learning_service.mojom-lite.js"},
+
+ {IDR_MACHINE_LEARNING_INTERNALS_MODEL_MOJO_JS,
+ "chromeos/services/machine_learning/public/mojom/model.mojom-lite.js"},
+
+ {IDR_MACHINE_LEARNING_INTERNALS_PAGE_HANDLER_MOJO_JS,
+ "chrome/browser/ui/webui/chromeos/machine_learning/"
+ "machine_learning_internals_page_handler.mojom-lite.js"},
+ {IDR_MACHINE_LEARNING_INTERNALS_TENSOR_MOJO_JS,
+ "chromeos/services/machine_learning/public/mojom/tensor.mojom-lite.js"},
+
+ {IDR_MACHINE_LEARNING_INTERNALS_TEST_MODEL_TAB_JS, "test_model_tab.js"},
+
+ {IDR_MACHINE_LEARNING_INTERNALS_TIME_MOJO_JS,
+ "mojo/public/mojom/base/time.mojom-lite.js"},
+
+ {IDR_MACHINE_LEARNING_INTERNALS_UTILS_JS,
+ "machine_learning_internals_utils.js"},
+ };
+
+ for (const auto& path : resource_paths) {
+ source->AddResourcePath(path.second, path.first);
+ }
+
+ source->SetDefaultResource(IDR_MACHINE_LEARNING_INTERNALS_HTML);
content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source);
}
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 13fe503151a..603514f0d85 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
@@ -26,11 +26,13 @@ namespace network_element {
namespace {
constexpr webui::LocalizedString kElementLocalizedStrings[] = {
+ {"OncType", IDS_NETWORK_TYPE},
{"OncTypeCellular", IDS_NETWORK_TYPE_CELLULAR},
{"OncTypeEthernet", IDS_NETWORK_TYPE_ETHERNET},
{"OncTypeMobile", IDS_NETWORK_TYPE_MOBILE_DATA},
{"OncTypeTether", IDS_NETWORK_TYPE_TETHER},
{"OncTypeVPN", IDS_NETWORK_TYPE_VPN},
+ {"OncTypeWireless", IDS_NETWORK_TYPE_WIRELESS},
{"OncTypeWiFi", IDS_NETWORK_TYPE_WIFI},
{"ipAddressNotAvailable", IDS_NETWORK_IP_ADDRESS_NA},
{"networkListItemConnected", IDS_STATUSBAR_NETWORK_DEVICE_CONNECTED},
diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_logs_message_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/network_logs_message_handler.cc
new file mode 100644
index 00000000000..423901dfc52
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/network_logs_message_handler.cc
@@ -0,0 +1,203 @@
+// Copyright 2020 The Chromium 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/network_logs_message_handler.h"
+
+#include <iostream>
+
+#include "base/files/file_util.h"
+#include "base/strings/stringprintf.h"
+#include "base/system/sys_info.h"
+#include "base/task/task_traits.h"
+#include "base/task/thread_pool.h"
+#include "chrome/browser/chromeos/file_manager/filesystem_api_util.h"
+#include "chrome/browser/chromeos/system_logs/debug_log_writer.h"
+#include "chrome/browser/chromeos/system_logs/system_logs_writer.h"
+#include "chrome/browser/download/download_prefs.h"
+#include "chrome/browser/policy/chrome_policy_conversions_client.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/common/logging_chrome.h"
+#include "chrome/grit/generated_resources.h"
+#include "chromeos/dbus/dbus_thread_manager.h"
+#include "chromeos/dbus/debug_daemon/debug_daemon_client.h"
+#include "components/policy/core/browser/policy_conversions.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_ui.h"
+#include "ui/base/l10n/l10n_util.h"
+
+namespace chromeos {
+
+namespace {
+
+base::FilePath GetDownloadsDirectory(content::WebUI* web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+ const DownloadPrefs* const prefs = DownloadPrefs::FromBrowserContext(profile);
+ base::FilePath path = prefs->DownloadPath();
+ if (file_manager::util::IsUnderNonNativeLocalPath(profile, path))
+ path = prefs->GetDefaultDownloadDirectoryForProfile();
+ return path;
+}
+
+std::string GetJsonPolicies(content::WebUI* web_ui) {
+ auto client = std::make_unique<policy::ChromePolicyConversionsClient>(
+ web_ui->GetWebContents()->GetBrowserContext());
+ return policy::DictionaryPolicyConversions(std::move(client)).ToJSON();
+}
+
+bool WriteTimestampedFile(const base::FilePath& file_path,
+ const std::string& contents) {
+ base::FilePath timestamped_file_path =
+ logging::GenerateTimestampedName(file_path, base::Time::Now());
+ int bytes_written =
+ base::WriteFile(timestamped_file_path, contents.data(), contents.size());
+ return bytes_written > 0;
+}
+
+bool GetBoolOrFalse(const base::Value* dict, const char* keyname) {
+ const base::Value* key = dict->FindKey(keyname);
+ return key && key->GetBool();
+}
+
+} // namespace
+
+NetworkLogsMessageHandler::NetworkLogsMessageHandler() = default;
+
+NetworkLogsMessageHandler::~NetworkLogsMessageHandler() = default;
+
+void NetworkLogsMessageHandler::RegisterMessages() {
+ out_dir_ = GetDownloadsDirectory(web_ui());
+ web_ui()->RegisterMessageCallback(
+ "storeLogs", base::BindRepeating(&NetworkLogsMessageHandler::OnStoreLogs,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "setShillDebugging",
+ base::BindRepeating(&NetworkLogsMessageHandler::OnSetShillDebugging,
+ base::Unretained(this)));
+}
+
+void NetworkLogsMessageHandler::Respond(const std::string& callback_id,
+ const std::string& result,
+ bool is_error) {
+ base::Value response(base::Value::Type::LIST);
+ response.Append(result);
+ response.Append(is_error);
+ ResolveJavascriptCallback(base::Value(callback_id), response);
+}
+
+void NetworkLogsMessageHandler::OnStoreLogs(const base::ListValue* list) {
+ CHECK_EQ(2u, list->GetSize());
+ std::string callback_id;
+ CHECK(list->GetString(0, &callback_id));
+ const base::Value* options;
+ CHECK(list->Get(1, &options));
+ AllowJavascript();
+
+ if (GetBoolOrFalse(options, "systemLogs")) {
+ bool scrub_data = GetBoolOrFalse(options, "filterPII");
+ chromeos::system_logs_writer::WriteSystemLogs(
+ out_dir_, scrub_data,
+ base::BindOnce(&NetworkLogsMessageHandler::OnWriteSystemLogs,
+ weak_factory_.GetWeakPtr(), callback_id,
+ options->Clone()));
+ } else {
+ MaybeWriteDebugLogs(callback_id, options->Clone());
+ }
+}
+
+void NetworkLogsMessageHandler::OnWriteSystemLogs(
+ const std::string& callback_id,
+ base::Value&& options,
+ base::Optional<base::FilePath> syslogs_path) {
+ if (!syslogs_path) {
+ Respond(callback_id, "Error writing system logs file.", /*is_error=*/true);
+ return;
+ }
+ MaybeWriteDebugLogs(callback_id, std::move(options));
+}
+
+void NetworkLogsMessageHandler::MaybeWriteDebugLogs(
+ const std::string& callback_id,
+ base::Value&& options) {
+ if (GetBoolOrFalse(&options, "debugLogs")) {
+ if (!base::SysInfo::IsRunningOnChromeOS()) {
+ Respond(callback_id, "Debug logs unavailable on Linux build.",
+ /*is_error=*/true);
+ return;
+ }
+ bool include_chrome = GetBoolOrFalse(&options, "chromeLogs");
+ chromeos::debug_log_writer::StoreLogs(
+ out_dir_, include_chrome,
+ base::BindOnce(&NetworkLogsMessageHandler::OnWriteDebugLogs,
+ weak_factory_.GetWeakPtr(), callback_id,
+ std::move(options)));
+ } else {
+ MaybeWritePolicies(callback_id, std::move(options));
+ }
+}
+
+void NetworkLogsMessageHandler::OnWriteDebugLogs(
+ const std::string& callback_id,
+ base::Value&& options,
+ base::Optional<base::FilePath> logs_path) {
+ if (!logs_path) {
+ Respond(callback_id, "Error writing debug logs.", /*is_error=*/true);
+ return;
+ }
+ MaybeWritePolicies(callback_id, std::move(options));
+}
+
+void NetworkLogsMessageHandler::MaybeWritePolicies(
+ const std::string& callback_id,
+ base::Value&& options) {
+ if (GetBoolOrFalse(&options, "policies")) {
+ std::string json_policies = GetJsonPolicies(web_ui());
+ base::ThreadPool::PostTaskAndReplyWithResult(
+ FROM_HERE,
+ {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
+ base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
+ base::BindOnce(WriteTimestampedFile, out_dir_.Append("policies.json"),
+ json_policies),
+ base::BindOnce(&NetworkLogsMessageHandler::OnWritePolicies,
+ weak_factory_.GetWeakPtr(), callback_id));
+ } else {
+ OnWriteSystemLogsCompleted(callback_id);
+ }
+}
+
+void NetworkLogsMessageHandler::OnWritePolicies(const std::string& callback_id,
+ bool result) {
+ if (!result) {
+ Respond(callback_id, "Error writing policies.", /*is_error=*/true);
+ return;
+ }
+ OnWriteSystemLogsCompleted(callback_id);
+}
+
+void NetworkLogsMessageHandler::OnWriteSystemLogsCompleted(
+ const std::string& callback_id) {
+ Respond(callback_id,
+ l10n_util::GetStringUTF8(IDS_NETWORK_UI_NETWORK_LOGS_SUCCESS),
+ /*is_error=*/false);
+}
+
+void NetworkLogsMessageHandler::OnSetShillDebugging(
+ const base::ListValue* list) {
+ CHECK_EQ(2u, list->GetSize());
+ std::string callback_id, subsystem;
+ CHECK(list->GetString(0, &callback_id));
+ CHECK(list->GetString(1, &subsystem));
+ AllowJavascript();
+ chromeos::DBusThreadManager::Get()->GetDebugDaemonClient()->SetDebugMode(
+ subsystem,
+ base::BindOnce(&NetworkLogsMessageHandler::OnSetShillDebuggingCompleted,
+ weak_factory_.GetWeakPtr(), callback_id));
+}
+
+void NetworkLogsMessageHandler::OnSetShillDebuggingCompleted(
+ const std::string& callback_id,
+ bool succeeded) {
+ Respond(callback_id, /*result=*/"", !succeeded);
+}
+
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_logs_message_handler.h b/chromium/chrome/browser/ui/webui/chromeos/network_logs_message_handler.h
new file mode 100644
index 00000000000..6ecb291a883
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/network_logs_message_handler.h
@@ -0,0 +1,56 @@
+// Copyright 2020 The Chromium 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_NETWORK_LOGS_MESSAGE_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_NETWORK_LOGS_MESSAGE_HANDLER_H_
+
+#include <string>
+
+#include "base/files/file_path.h"
+#include "base/memory/weak_ptr.h"
+#include "base/optional.h"
+#include "base/values.h"
+#include "content/public/browser/web_ui_message_handler.h"
+
+namespace chromeos {
+
+class NetworkLogsMessageHandler : public content::WebUIMessageHandler {
+ public:
+ NetworkLogsMessageHandler();
+ ~NetworkLogsMessageHandler() override;
+ NetworkLogsMessageHandler(const NetworkLogsMessageHandler&) = delete;
+ NetworkLogsMessageHandler& operator=(const NetworkLogsMessageHandler&) =
+ delete;
+
+ private:
+ // WebUIMessageHandler
+ void RegisterMessages() override;
+
+ void Respond(const std::string& callback_id,
+ const std::string& result,
+ bool is_error);
+ void OnStoreLogs(const base::ListValue* list);
+ void OnWriteSystemLogs(const std::string& callback_id,
+ base::Value&& options,
+ base::Optional<base::FilePath> syslogs_path);
+ void MaybeWriteDebugLogs(const std::string& callback_id,
+ base::Value&& options);
+ void OnWriteDebugLogs(const std::string& callback_id,
+ base::Value&& options,
+ base::Optional<base::FilePath> logs_path);
+ void MaybeWritePolicies(const std::string& callback_id,
+ base::Value&& options);
+ void OnWritePolicies(const std::string& callback_id, bool result);
+ void OnWriteSystemLogsCompleted(const std::string& callback_id);
+ void OnSetShillDebugging(const base::ListValue* list);
+ void OnSetShillDebuggingCompleted(const std::string& callback_id,
+ bool succeeded);
+
+ base::FilePath out_dir_;
+ base::WeakPtrFactory<NetworkLogsMessageHandler> weak_factory_{this};
+};
+
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_NETWORK_LOGS_MESSAGE_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc
index da91385d0c7..410696940e1 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/network_ui.cc
@@ -14,11 +14,15 @@
#include "base/memory/weak_ptr.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
+#include "chrome/browser/chromeos/net/network_health/network_health_localized_strings.h"
+#include "chrome/browser/chromeos/net/network_health/network_health_service.h"
#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/browser/ui/webui/chromeos/network_logs_message_handler.h"
+#include "chrome/browser/ui/webui/chromeos/onc_import_message_handler.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/generated_resources.h"
@@ -29,12 +33,14 @@
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/onc/onc_utils.h"
#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h"
+#include "chromeos/services/network_health/public/mojom/network_health.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 "mojo/public/cpp/bindings/remote.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
#include "ui/base/l10n/l10n_util.h"
@@ -132,29 +138,35 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler {
}
private:
+ void Respond(const std::string& callback_id, const base::Value& response) {
+ AllowJavascript();
+ ResolveJavascriptCallback(base::Value(callback_id), response);
+ }
+
void GetShillNetworkProperties(const base::ListValue* arg_list) {
- std::string guid;
- if (!arg_list->GetString(0, &guid)) {
- NOTREACHED();
- return;
- }
+ CHECK_EQ(2u, arg_list->GetSize());
+ std::string callback_id, guid;
+ CHECK(arg_list->GetString(0, &callback_id));
+ CHECK(arg_list->GetString(1, &guid));
+
std::string service_path;
if (!GetServicePathFromGuid(guid, &service_path)) {
- ErrorCallback(guid, kGetNetworkProperties, "Error.InvalidNetworkGuid",
- nullptr);
+ ErrorCallback(callback_id, guid, kGetNetworkProperties,
+ "Error.InvalidNetworkGuid", nullptr);
return;
}
NetworkHandler::Get()->network_configuration_handler()->GetShillProperties(
service_path,
base::BindOnce(
&NetworkConfigMessageHandler::GetShillNetworkPropertiesSuccess,
- weak_ptr_factory_.GetWeakPtr()),
+ weak_ptr_factory_.GetWeakPtr(), callback_id),
base::Bind(&NetworkConfigMessageHandler::ErrorCallback,
- weak_ptr_factory_.GetWeakPtr(), guid,
+ weak_ptr_factory_.GetWeakPtr(), callback_id, guid,
kGetNetworkProperties));
}
void GetShillNetworkPropertiesSuccess(
+ const std::string& callback_id,
const std::string& service_path,
const base::DictionaryValue& dictionary) {
std::unique_ptr<base::DictionaryValue> dictionary_copy(
@@ -167,47 +179,46 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler {
base::ListValue return_arg_list;
return_arg_list.Append(std::move(dictionary_copy));
-
- AllowJavascript();
- CallJavascriptFunction(
- base::StringPrintf("NetworkUI.%sResult", kGetNetworkProperties),
- return_arg_list);
+ Respond(callback_id, return_arg_list);
}
void GetShillDeviceProperties(const base::ListValue* arg_list) {
- std::string type;
- if (!arg_list->GetString(0, &type)) {
- NOTREACHED();
- return;
- }
+ CHECK_EQ(2u, arg_list->GetSize());
+ std::string callback_id, type;
+ CHECK(arg_list->GetString(0, &callback_id));
+ CHECK(arg_list->GetString(1, &type));
+
const DeviceState* device =
NetworkHandler::Get()->network_state_handler()->GetDeviceStateByType(
onc::NetworkTypePatternFromOncType(type));
if (!device) {
- ErrorCallback(type, kGetDeviceProperties, "Error.InvalidDeviceType",
- nullptr);
+ ErrorCallback(callback_id, type, kGetDeviceProperties,
+ "Error.InvalidDeviceType", nullptr);
return;
}
NetworkHandler::Get()->network_device_handler()->GetDeviceProperties(
device->path(),
base::BindOnce(
&NetworkConfigMessageHandler::GetShillDevicePropertiesSuccess,
- weak_ptr_factory_.GetWeakPtr()),
+ weak_ptr_factory_.GetWeakPtr(), callback_id),
base::Bind(&NetworkConfigMessageHandler::ErrorCallback,
- weak_ptr_factory_.GetWeakPtr(), type, kGetDeviceProperties));
+ weak_ptr_factory_.GetWeakPtr(), callback_id, type,
+ kGetDeviceProperties));
}
void GetShillEthernetEAP(const base::ListValue* arg_list) {
+ CHECK_EQ(1u, arg_list->GetSize());
+ std::string callback_id;
+ CHECK(arg_list->GetString(0, &callback_id));
+
NetworkStateHandler::NetworkStateList list;
NetworkHandler::Get()->network_state_handler()->GetNetworkListByType(
NetworkTypePattern::Primitive(shill::kTypeEthernetEap),
true /* configured_only */, false /* visible_only */, 1 /* limit */,
&list);
- AllowJavascript();
if (list.empty()) {
- CallJavascriptFunction(
- base::StringPrintf("NetworkUI.%sResult", kGetEthernetEAP));
+ Respond(callback_id, base::Value(base::Value::Type::LIST));
return;
}
const NetworkState* eap = list.front();
@@ -215,21 +226,25 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler {
properties.SetStringKey("guid", eap->guid());
properties.SetStringKey("name", eap->name());
properties.SetStringKey("type", eap->type());
- CallJavascriptFunction(
- base::StringPrintf("NetworkUI.%sResult", kGetEthernetEAP), properties);
+ base::Value response(base::Value::Type::LIST);
+ response.Append(std::move(properties));
+ Respond(callback_id, response);
}
void OpenCellularActivationUi(const base::ListValue* arg_list) {
+ CHECK_EQ(1u, arg_list->GetSize());
+ std::string callback_id;
+ CHECK(arg_list->GetString(0, &callback_id));
+
const NetworkState* cellular_network =
NetworkHandler::Get()->network_state_handler()->FirstNetworkByType(
NetworkTypePattern::Cellular());
if (cellular_network)
cellular_setup::OpenCellularSetupDialog(cellular_network->guid());
- AllowJavascript();
- CallJavascriptFunction(
- base::StringPrintf("NetworkUI.%sResult", kOpenCellularActivationUi),
- base::Value(cellular_network != nullptr));
+ base::Value response(base::Value::Type::LIST);
+ response.Append(base::Value(cellular_network != nullptr));
+ Respond(callback_id, response);
}
void ShowNetworkDetails(const base::ListValue* arg_list) {
@@ -257,6 +272,7 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler {
}
void GetShillDevicePropertiesSuccess(
+ const std::string& callback_id,
const std::string& device_path,
const base::DictionaryValue& dictionary) {
std::unique_ptr<base::DictionaryValue> dictionary_copy(
@@ -267,14 +283,11 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler {
base::ListValue return_arg_list;
return_arg_list.Append(std::move(dictionary_copy));
-
- AllowJavascript();
- CallJavascriptFunction(
- base::StringPrintf("NetworkUI.%sResult", kGetDeviceProperties),
- return_arg_list);
+ Respond(callback_id, return_arg_list);
}
- void ErrorCallback(const std::string& guid_or_type,
+ void ErrorCallback(const std::string& callback_id,
+ const std::string& guid_or_type,
const std::string& function_name,
const std::string& error_name,
std::unique_ptr<base::DictionaryValue> /* error_data */) {
@@ -287,11 +300,7 @@ class NetworkConfigMessageHandler : public content::WebUIMessageHandler {
dictionary.SetKey(key, base::Value(guid_or_type));
dictionary.SetKey("ShillError", base::Value(error_name));
return_arg_list.Append(std::move(dictionary));
-
- AllowJavascript();
- CallJavascriptFunction(
- base::StringPrintf("NetworkUI.%sResult", function_name.c_str()),
- return_arg_list);
+ Respond(callback_id, return_arg_list);
}
void AddNetwork(const base::ListValue* args) {
@@ -312,8 +321,21 @@ void NetworkUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) {
localized_strings->SetString("titleText",
l10n_util::GetStringUTF16(IDS_NETWORK_UI_TITLE));
- localized_strings->SetString("titleText",
- l10n_util::GetStringUTF16(IDS_NETWORK_UI_TITLE));
+ localized_strings->SetString(
+ "generalTab", l10n_util::GetStringUTF16(IDS_NETWORK_UI_TAB_GENERAL));
+ localized_strings->SetString(
+ "networkHealthTab",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_TAB_NETWORK_HEALTH));
+ localized_strings->SetString(
+ "networkLogsTab",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_TAB_NETWORK_LOGS));
+ localized_strings->SetString(
+ "networkStateTab",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_TAB_NETWORK_STATE));
+ localized_strings->SetString(
+ "networkSelectTab",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_TAB_NETWORK_SELECT));
+
localized_strings->SetString(
"autoRefreshText",
l10n_util::GetStringUTF16(IDS_NETWORK_UI_AUTO_REFRESH));
@@ -347,6 +369,9 @@ void NetworkUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) {
"networkListsLabel",
l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LISTS));
localized_strings->SetString(
+ "networkHealthLabel",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_HEALTH));
+ localized_strings->SetString(
"visibleNetworksLabel",
l10n_util::GetStringUTF16(IDS_NETWORK_UI_VISIBLE_NETWORKS));
localized_strings->SetString(
@@ -375,11 +400,60 @@ void NetworkUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) {
localized_strings->SetString(
"addNewWifiButtonText",
l10n_util::GetStringUTF16(IDS_NETWORK_UI_ADD_NEW_WIFI_BUTTON_TEXT));
+
+ localized_strings->SetString(
+ "importOncButtonText",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_IMPORT_ONC_BUTTON_TEXT));
+
+ localized_strings->SetString(
+ "addWiFiListItemName",
+ l10n_util::GetStringUTF16(IDS_NETWORK_ADD_WI_FI_LIST_ITEM_NAME));
+
+ // Network logs
+ localized_strings->SetString(
+ "networkLogsDescription",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LOGS_DESCRIPTION));
+ localized_strings->SetString(
+ "networkLogsSystemLogs",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LOGS_SYSTEM_LOGS));
+ localized_strings->SetString(
+ "networkLogsFilterPii",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LOGS_FILTER_PII));
+ localized_strings->SetString(
+ "networkLogsPolicies",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LOGS_POLICIES));
+ localized_strings->SetString(
+ "networkLogsDebugLogs",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LOGS_DEBUG_LOGS));
+ localized_strings->SetString(
+ "networkLogsChromeLogs",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LOGS_CHROME_LOGS));
+ localized_strings->SetString(
+ "networkLogsStoreButton",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LOGS_STORE_BUTTON));
+ localized_strings->SetString(
+ "networkLogsStatus",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LOGS_STATUS));
+ localized_strings->SetString(
+ "networkLogsDebuggingTitle",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LOGS_DEBUGGING_TITLE));
+ localized_strings->SetString(
+ "networkLogsDebuggingDescription",
+ l10n_util::GetStringUTF16(
+ IDS_NETWORK_UI_NETWORK_LOGS_DEBUGGING_DESCRIPTION));
+ localized_strings->SetString(
+ "networkLogsDebuggingNone",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LOGS_DEBUGGING_NONE));
+ localized_strings->SetString(
+ "networkLogsDebuggingUnknown",
+ l10n_util::GetStringUTF16(IDS_NETWORK_UI_NETWORK_LOGS_DEBUGGING_UNKNOWN));
}
NetworkUI::NetworkUI(content::WebUI* web_ui)
: ui::MojoWebUIController(web_ui, /*enable_chrome_send=*/true) {
web_ui->AddMessageHandler(std::make_unique<NetworkConfigMessageHandler>());
+ web_ui->AddMessageHandler(std::make_unique<OncImportMessageHandler>());
+ web_ui->AddMessageHandler(std::make_unique<NetworkLogsMessageHandler>());
// Enable extension API calls in the WebUI.
extensions::TabHelper::CreateForWebContents(web_ui->GetWebContents());
@@ -390,13 +464,23 @@ NetworkUI::NetworkUI(content::WebUI* web_ui)
content::WebUIDataSource* html =
content::WebUIDataSource::Create(chrome::kChromeUINetworkHost);
html->AddLocalizedStrings(localized_strings);
+ network_health::AddLocalizedStrings(html);
network_element::AddLocalizedStrings(html);
-
+ network_element::AddOncLocalizedStrings(html);
html->UseStringsJs();
- html->AddResourcePath("network_ui.css", IDR_NETWORK_UI_CSS);
+
+ html->AddResourcePath("network_ui_browser_proxy.html",
+ IDR_NETWORK_UI_BROWSER_PROXY_HTML);
+ html->AddResourcePath("network_ui_browser_proxy.js",
+ IDR_NETWORK_UI_BROWSER_PROXY_JS);
+ html->AddResourcePath("network_ui.html", IDR_NETWORK_UI_HTML);
html->AddResourcePath("network_ui.js", IDR_NETWORK_UI_JS);
- html->SetDefaultResource(IDR_NETWORK_UI_HTML);
+ html->AddResourcePath("network_state_ui.html", IDR_NETWORK_STATE_UI_HTML);
+ html->AddResourcePath("network_state_ui.js", IDR_NETWORK_STATE_UI_JS);
+ html->AddResourcePath("network_logs_ui.html", IDR_NETWORK_LOGS_UI_HTML);
+ html->AddResourcePath("network_logs_ui.js", IDR_NETWORK_LOGS_UI_JS);
+ html->SetDefaultResource(IDR_NETWORK_UI_PAGE_HTML);
content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(),
html);
@@ -409,6 +493,13 @@ void NetworkUI::BindInterface(
ash::GetNetworkConfigService(std::move(receiver));
}
+void NetworkUI::BindInterface(
+ mojo::PendingReceiver<network_health::mojom::NetworkHealthService>
+ receiver) {
+ network_health::NetworkHealthService::GetInstance()->BindRemote(
+ std::move(receiver));
+}
+
WEB_UI_CONTROLLER_TYPE_IMPL(NetworkUI)
} // 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 8e4fc290ebd..b7bbd7dbae0 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/network_ui.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/network_ui.h
@@ -7,6 +7,7 @@
#include "base/macros.h"
#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom-forward.h"
+#include "chromeos/services/network_health/public/mojom/network_health.mojom-forward.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "ui/webui/mojo_web_ui_controller.h"
@@ -24,11 +25,17 @@ class NetworkUI : public ui::MojoWebUIController {
static void GetLocalizedStrings(base::DictionaryValue* localized_strings);
- // Instantiates implementor of the mojom::CrosNetworkConfig mojo interface
+ // Instantiates implementation of the mojom::CrosNetworkConfig mojo interface
// passing the pending receiver that will be internally bound.
void BindInterface(
mojo::PendingReceiver<network_config::mojom::CrosNetworkConfig> receiver);
+ // Instantiates implementation of the mojom::NetworkHealthService mojo
+ // interface passing the pending receiver that will be bound.
+ void BindInterface(
+ mojo::PendingReceiver<network_health::mojom::NetworkHealthService>
+ receiver);
+
private:
WEB_UI_CONTROLLER_TYPE_DECL();
diff --git a/chromium/chrome/browser/ui/webui/chromeos/onc_import_message_handler.cc b/chromium/chrome/browser/ui/webui/chromeos/onc_import_message_handler.cc
new file mode 100644
index 00000000000..27cd4019b27
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/onc_import_message_handler.cc
@@ -0,0 +1,124 @@
+// Copyright 2020 The Chromium 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/onc_import_message_handler.h"
+
+#include "base/bind.h"
+#include "base/bind_helpers.h"
+#include "base/strings/stringprintf.h"
+#include "base/values.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#include "chrome/browser/net/nss_context.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chromeos/network/onc/onc_certificate_importer_impl.h"
+#include "chromeos/network/onc/onc_parsed_certificates.h"
+#include "chromeos/network/onc/onc_utils.h"
+#include "components/onc/onc_constants.h"
+#include "components/policy/core/browser/policy_conversions.h"
+#include "content/public/browser/browser_task_traits.h"
+#include "content/public/browser/browser_thread.h"
+
+namespace chromeos {
+
+OncImportMessageHandler::OncImportMessageHandler() = default;
+
+OncImportMessageHandler::~OncImportMessageHandler() = default;
+
+void OncImportMessageHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "importONC", base::BindRepeating(&OncImportMessageHandler::OnImportONC,
+ base::Unretained(this)));
+}
+
+void OncImportMessageHandler::Respond(const std::string& callback_id,
+ const std::string& result,
+ bool is_error) {
+ base::Value response(base::Value::Type::LIST);
+ response.Append(result);
+ response.Append(is_error);
+ ResolveJavascriptCallback(base::Value(callback_id), response);
+}
+
+void OncImportMessageHandler::OnImportONC(const base::ListValue* list) {
+ CHECK_EQ(2u, list->GetSize());
+ std::string callback_id, onc_blob;
+ CHECK(list->GetString(0, &callback_id));
+ CHECK(list->GetString(1, &onc_blob));
+ AllowJavascript();
+ GetNSSCertDatabaseForProfile(
+ Profile::FromWebUI(web_ui()),
+ base::Bind(&OncImportMessageHandler::ImportONCToNSSDB,
+ weak_factory_.GetWeakPtr(), callback_id, onc_blob));
+}
+
+void OncImportMessageHandler::ImportONCToNSSDB(const std::string& callback_id,
+ const std::string& onc_blob,
+ net::NSSCertDatabase* nssdb) {
+ const user_manager::User* user =
+ ProfileHelper::Get()->GetUserByProfile(Profile::FromWebUI(web_ui()));
+ if (!user) {
+ Respond(callback_id, "User not found.", /*is_error=*/true);
+ return;
+ }
+
+ std::string result;
+ bool has_error = false;
+
+ ::onc::ONCSource onc_source = ::onc::ONC_SOURCE_USER_IMPORT;
+ base::ListValue network_configs;
+ base::DictionaryValue global_network_config;
+ base::ListValue certificates;
+ if (!onc::ParseAndValidateOncForImport(
+ onc_blob, onc_source, /*passphrase=*/std::string(), &network_configs,
+ &global_network_config, &certificates)) {
+ has_error = true;
+ result += "Errors occurred during ONC parsing.\n";
+ }
+
+ std::string import_error;
+ int num_networks_imported =
+ onc::ImportNetworksForUser(user, network_configs, &import_error);
+ if (!import_error.empty()) {
+ has_error = true;
+ result += "Error importing networks: " + import_error + "\n";
+ }
+ result +=
+ base::StringPrintf("Networks imported: %d\n", num_networks_imported);
+ if (certificates.GetList().empty()) {
+ if (!num_networks_imported)
+ has_error = true;
+ Respond(callback_id, result, has_error);
+ return;
+ }
+
+ auto cert_importer = std::make_unique<onc::CertificateImporterImpl>(
+ content::GetIOThreadTaskRunner({}), nssdb);
+ auto certs = std::make_unique<onc::OncParsedCertificates>(certificates);
+ if (certs->has_error()) {
+ has_error = true;
+ result += "Some certificates could not be parsed.\n";
+ }
+ cert_importer->ImportAllCertificatesUserInitiated(
+ certs->server_or_authority_certificates(), certs->client_certificates(),
+ base::BindOnce(&OncImportMessageHandler::OnCertificatesImported,
+ weak_factory_.GetWeakPtr(), std::move(cert_importer),
+ callback_id, result, has_error));
+}
+
+void OncImportMessageHandler::OnCertificatesImported(
+ std::unique_ptr<onc::CertificateImporterImpl> cert_importer,
+ const std::string& callback_id,
+ const std::string& previous_result,
+ bool has_error,
+ bool cert_import_success) {
+ std::string result = previous_result;
+ if (!cert_import_success) {
+ has_error = true;
+ result += "Some certificates couldn't be imported.\n";
+ }
+ Respond(callback_id, result, has_error);
+ // |cert_importer| will be destroyed when the callback exits.
+}
+
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/onc_import_message_handler.h b/chromium/chrome/browser/ui/webui/chromeos/onc_import_message_handler.h
new file mode 100644
index 00000000000..834850e6f58
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/chromeos/onc_import_message_handler.h
@@ -0,0 +1,57 @@
+// Copyright 2020 The Chromium 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_ONC_IMPORT_MESSAGE_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_ONC_IMPORT_MESSAGE_HANDLER_H_
+
+#include <string>
+
+#include "base/memory/weak_ptr.h"
+#include "content/public/browser/web_ui_message_handler.h"
+
+namespace base {
+class ListValue;
+}
+
+namespace net {
+class NSSCertDatabase;
+}
+
+namespace chromeos {
+
+namespace onc {
+class CertificateImporterImpl;
+}
+
+class OncImportMessageHandler : public content::WebUIMessageHandler {
+ public:
+ OncImportMessageHandler();
+ ~OncImportMessageHandler() override;
+ OncImportMessageHandler(const OncImportMessageHandler&) = delete;
+ OncImportMessageHandler& operator=(const OncImportMessageHandler&) = delete;
+
+ private:
+ // WebUIMessageHandler
+ void RegisterMessages() override;
+
+ void Respond(const std::string& callback_id,
+ const std::string& result,
+ bool is_error);
+ void OnImportONC(const base::ListValue* list);
+ void ImportONCToNSSDB(const std::string& callback_id,
+ const std::string& onc_blob,
+ net::NSSCertDatabase* nssdb);
+ void OnCertificatesImported(
+ std::unique_ptr<onc::CertificateImporterImpl> cert_importer,
+ const std::string& callback_id,
+ const std::string& previous_error,
+ bool has_error,
+ bool cert_import_success);
+
+ base::WeakPtrFactory<OncImportMessageHandler> weak_factory_{this};
+};
+
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_ONC_IMPORT_MESSAGE_HANDLER_H_
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 cc12e4bb71f..c1a0275910c 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/set_time_ui.cc
@@ -33,6 +33,7 @@
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/resources/grit/webui_resources.h"
@@ -173,7 +174,8 @@ SetTimeUI::SetTimeUI(content::WebUI* web_ui) : WebDialogUI(web_ui) {
// Set up the chrome://set-time source.
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUISetTimeHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources chrome://test 'self';");
static constexpr webui::LocalizedString kStrings[] = {
diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc
index 0e64776606e..1fc4d7be1c1 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.cc
@@ -20,7 +20,7 @@ namespace chromeos {
namespace smb_dialog {
namespace {
-constexpr int kSmbCredentialsDialogHeight = 250;
+constexpr int kSmbCredentialsDialogHeight = 230;
void AddSmbCredentialsDialogStrings(content::WebUIDataSource* html_source) {
static const struct {
@@ -135,5 +135,9 @@ void SmbCredentialsDialogUI::OnUpdateCredentials(const std::string& username,
}
}
+bool SmbCredentialsDialog::ShouldShowCloseButton() const {
+ return false;
+}
+
} // namespace smb_dialog
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.h
index b614f60c71c..1836c16f136 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.h
@@ -41,6 +41,7 @@ class SmbCredentialsDialog : public SystemWebDialogDelegate {
// ui::WebDialogDelegate
void GetDialogSize(gfx::Size* size) const override;
std::string GetDialogArgs() const override;
+ bool ShouldShowCloseButton() const override;
private:
const std::string mount_id_;
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 2aa8bca9516..8ffea982338 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
@@ -21,7 +21,7 @@ namespace chromeos {
namespace smb_dialog {
namespace {
-constexpr int kSmbShareDialogHeight = 564;
+constexpr int kSmbShareDialogHeight = 515;
void AddSmbSharesStrings(content::WebUIDataSource* html_source) {
// Add strings specific to smb_dialog.
@@ -96,5 +96,9 @@ SmbShareDialogUI::SmbShareDialogUI(content::WebUI* web_ui)
SmbShareDialogUI::~SmbShareDialogUI() = default;
+bool SmbShareDialog::ShouldShowCloseButton() const {
+ return false;
+}
+
} // namespace smb_dialog
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.h b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.h
index 15ff3f6bee9..8902231aff8 100644
--- a/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.h
+++ b/chromium/chrome/browser/ui/webui/chromeos/smb_shares/smb_share_dialog.h
@@ -23,6 +23,7 @@ class SmbShareDialog : public SystemWebDialogDelegate {
// ui::WebDialogDelegate
void GetDialogSize(gfx::Size* size) const override;
+ bool ShouldShowCloseButton() const override;
DISALLOW_COPY_AND_ASSIGN(SmbShareDialog);
};
diff --git a/chromium/chrome/browser/ui/webui/components/components_handler.cc b/chromium/chrome/browser/ui/webui/components/components_handler.cc
index 504d9bbc6c6..283f8ad5901 100644
--- a/chromium/chrome/browser/ui/webui/components/components_handler.cc
+++ b/chromium/chrome/browser/ui/webui/components/components_handler.cc
@@ -8,7 +8,8 @@
#include <vector>
#include "base/bind.h"
-#include "base/logging.h"
+#include "base/check.h"
+#include "base/notreached.h"
#include "base/values.h"
#include "chrome/grit/generated_resources.h"
#include "components/update_client/crx_update_item.h"
diff --git a/chromium/chrome/browser/ui/webui/components/components_ui.cc b/chromium/chrome/browser/ui/webui/components/components_ui.cc
index cddfc815037..3eaf975d70c 100644
--- a/chromium/chrome/browser/ui/webui/components/components_ui.cc
+++ b/chromium/chrome/browser/ui/webui/components/components_ui.cc
@@ -27,6 +27,7 @@
#include "chrome/grit/theme_resources.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/web_ui_util.h"
@@ -40,7 +41,8 @@ content::WebUIDataSource* CreateComponentsUIHTMLSource(Profile* profile) {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIComponentsHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
static constexpr webui::LocalizedString kStrings[] = {
diff --git a/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc b/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc
index d7a42770c33..04c2f2a0c7d 100644
--- a/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc
+++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_data_fetcher.cc
@@ -7,7 +7,6 @@
#include <string>
#include <utility>
-#include "base/task/post_task.h"
#include "base/values.h"
#include "base/win/windows_version.h"
#include "chrome/browser/win/conflicts/module_database.h"
@@ -483,15 +482,15 @@ void ConflictsDataFetcher::OnModuleDatabaseIdle() {
#if defined(GOOGLE_CHROME_BUILD)
// The state of third-party features must be determined on the UI thread.
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(
OnModuleDataFetched, std::move(on_conflicts_data_fetched_callback_),
std::move(results), std::move(third_party_conflicts_manager_state_)));
#else
// The third-party features are always disabled on Chromium builds.
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(OnConflictsDataFetched,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(OnConflictsDataFetched,
std::move(on_conflicts_data_fetched_callback_),
std::move(results), kNonGoogleChromeBuild));
#endif
diff --git a/chromium/chrome/browser/ui/webui/conflicts/conflicts_ui.cc b/chromium/chrome/browser/ui/webui/conflicts/conflicts_ui.cc
index 38b4f7f1cc1..15d96b0b21d 100644
--- a/chromium/chrome/browser/ui/webui/conflicts/conflicts_ui.cc
+++ b/chromium/chrome/browser/ui/webui/conflicts/conflicts_ui.cc
@@ -16,6 +16,7 @@
#include "chrome/grit/theme_resources.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
@@ -23,7 +24,8 @@ namespace {
content::WebUIDataSource* CreateConflictsUIHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIConflictsHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
source->AddResourcePath("conflicts.js", IDR_ABOUT_CONFLICTS_JS);
diff --git a/chromium/chrome/browser/ui/webui/devtools_ui_data_source.cc b/chromium/chrome/browser/ui/webui/devtools_ui_data_source.cc
index 4a9faa8ce8c..63add823a35 100644
--- a/chromium/chrome/browser/ui/webui/devtools_ui_data_source.cc
+++ b/chromium/chrome/browser/ui/webui/devtools_ui_data_source.cc
@@ -57,6 +57,8 @@ std::string GetMimeTypeForPath(const std::string& path) {
base::CompareCase::INSENSITIVE_ASCII)) {
return "text/css";
} else if (base::EndsWith(filename, ".js",
+ base::CompareCase::INSENSITIVE_ASCII) ||
+ base::EndsWith(filename, ".mjs",
base::CompareCase::INSENSITIVE_ASCII)) {
return "application/javascript";
} else if (base::EndsWith(filename, ".png",
@@ -113,15 +115,20 @@ void DevToolsDataSource::StartDataRequest(
base::CompareCase::INSENSITIVE_ASCII));
std::string path_under_bundled =
path_without_params.substr(bundled_path_prefix.length());
-#if !BUILDFLAG(DEBUG_DEVTOOLS)
- if (!GetCustomDevToolsFrontendURL().SchemeIsFile()) {
+ GURL custom_devtools_frontend = GetCustomDevToolsFrontendURL();
+ if (!custom_devtools_frontend.is_valid()) {
// Fetch from packaged resources.
StartBundledDataRequest(path_under_bundled, std::move(callback));
return;
}
-#endif
- // Fetch from file system.
- StartFileRequest(path_under_bundled, std::move(callback));
+ if (GetCustomDevToolsFrontendURL().SchemeIsFile()) {
+ // Fetch from file system.
+ StartFileRequest(path_under_bundled, std::move(callback));
+ return;
+ }
+ GURL remote_url(custom_devtools_frontend.spec() + path_under_bundled);
+ // Fetch from remote URL.
+ StartCustomDataRequest(remote_url, std::move(callback));
return;
}
@@ -190,10 +197,7 @@ void DevToolsDataSource::StartBundledDataRequest(
scoped_refptr<base::RefCountedMemory> bytes =
content::DevToolsFrontendHost::GetFrontendResourceBytes(path);
- DLOG_IF(WARNING, !bytes)
- << "Unable to find dev tool resource: " << path
- << ". If you compiled with debug_devtools=1, try running with "
- "--debug-devtools.";
+ DLOG_IF(WARNING, !bytes) << "Unable to find DevTools resource: " << path;
std::move(callback).Run(bytes);
}
@@ -303,21 +307,11 @@ void DevToolsDataSource::StartFileRequest(const std::string& path,
GotDataCallback callback) {
base::FilePath base_path;
GURL custom_devtools_frontend = GetCustomDevToolsFrontendURL();
- if (custom_devtools_frontend.SchemeIsFile()) {
- if (!net::FileURLToFilePath(custom_devtools_frontend, &base_path)) {
- std::move(callback).Run(CreateNotFoundResponse());
- return;
- }
- } else {
-#if BUILDFLAG(DEBUG_DEVTOOLS)
- // Use default path for unbundled files when debug_devtools=true
- if (!base::PathService::Get(chrome::DIR_INSPECTOR_DEBUG, &base_path)) {
- std::move(callback).Run(CreateNotFoundResponse());
- return;
- }
-#else
- NOTREACHED();
-#endif
+ DCHECK(custom_devtools_frontend.SchemeIsFile());
+ if (!net::FileURLToFilePath(custom_devtools_frontend, &base_path)) {
+ std::move(callback).Run(CreateNotFoundResponse());
+ LOG(WARNING) << "Unable to find DevTools resource: " << path;
+ return;
}
base::FilePath full_path = base_path.AppendASCII(path);
diff --git a/chromium/chrome/browser/ui/webui/devtools_ui_data_source_unittest.cc b/chromium/chrome/browser/ui/webui/devtools_ui_data_source_unittest.cc
index fe7e72ffe11..464223bd09a 100644
--- a/chromium/chrome/browser/ui/webui/devtools_ui_data_source_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/devtools_ui_data_source_unittest.cc
@@ -96,7 +96,7 @@ class DevToolsUIDataSourceTest : public testing::Test {
private:
void OnDataReceived(scoped_refptr<base::RefCountedMemory> bytes) {
data_received_ = true;
- if (bytes.get() != nullptr) {
+ if (bytes.get()) {
data_ = base::StringPiece(reinterpret_cast<const char*>(bytes->front()),
bytes->size())
.as_string();
@@ -128,7 +128,7 @@ TEST_F(DevToolsUIDataSourceTest, TestDevToolsBundledURLWithQueryParam) {
EXPECT_FALSE(data().empty());
}
-TEST_F(DevToolsUIDataSourceTest, TestDevToolsBundledURLWithSwitch) {
+TEST_F(DevToolsUIDataSourceTest, TestDevToolsBundledFileURLWithSwitch) {
#if defined(OS_WIN)
const char* flag_value = "file://C:/tmp/";
#else
@@ -143,6 +143,17 @@ TEST_F(DevToolsUIDataSourceTest, TestDevToolsBundledURLWithSwitch) {
EXPECT_EQ(data(), "file: devtools_app.html");
}
+TEST_F(DevToolsUIDataSourceTest, TestDevToolsBundledRemoteURLWithSwitch) {
+ const char* flag_value = "http://example.com/example/path/";
+ base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
+ switches::kCustomDevtoolsFrontend, flag_value);
+ const GURL path =
+ DevToolsUrl().Resolve(DevToolsBundledPath(kDevToolsUITestFrontEndUrl));
+ StartRequest(path.path());
+ EXPECT_TRUE(data_received());
+ EXPECT_EQ(data(), "url: http://example.com/example/path/devtools_app.html");
+}
+
TEST_F(DevToolsUIDataSourceTest, TestDevToolsInvalidBundledURL) {
const GURL path =
DevToolsUrl().Resolve(DevToolsBundledPath("invalid_devtools_app.html"));
diff --git a/chromium/chrome/browser/ui/webui/discards/discards.mojom b/chromium/chrome/browser/ui/webui/discards/discards.mojom
index aec7bd7dcff..1b54372b1cb 100644
--- a/chromium/chrome/browser/ui/webui/discards/discards.mojom
+++ b/chromium/chrome/browser/ui/webui/discards/discards.mojom
@@ -9,14 +9,16 @@ import "mojo/public/mojom/base/process_id.mojom";
import "mojo/public/mojom/base/time.mojom";
import "url/mojom/url.mojom";
-// Identical to content::Visibility.
+// Identical to content::Visibility. Sent from browser to the chrome://discards
+// WebUI.
enum LifecycleUnitVisibility {
HIDDEN = 0,
OCCLUDED = 1,
VISIBLE = 2,
};
-// Discard related information about a single tab in a browser.
+// Discard related information about a single tab in a browser. Sent from
+// browser to the chrome://discards WebUI.
struct TabDiscardsInfo {
// The URL associated with the tab. This corresponds to GetLastCommittedURL,
// and is also what is visible in the Omnibox for a given tab.
@@ -29,10 +31,6 @@ struct TabDiscardsInfo {
mojom.LifecycleUnitLoadingState loading_state;
// The state of the LifecycleUnit.
mojom.LifecycleUnitState state;
- // Whether the tab can be frozen.
- bool can_freeze;
- // List of human-readable reasons why a tab can't be frozen.
- array<string> cannot_freeze_reasons;
// Whether the tab can be discarded.
bool can_discard;
// List of human-readable reasons why a tab can't be discarded.
@@ -85,9 +83,6 @@ interface DetailsProvider {
// Invokes a callback when the discard is complete.
DiscardById(int32 tab_id) => ();
- // Freezes a tab given its |tab_id|.
- FreezeById(int32 tab_id);
-
// Loads a tab given its |tab_id|.
LoadById(int32 tab_id);
@@ -98,12 +93,16 @@ interface DetailsProvider {
Discard() => ();
};
-// Represents the momentary state of a Page node.
+// Represents the momentary state of a Page node. Sent from browser to the
+// chrome://discards WebUI via the GraphChangeStream (defined below).
struct PageInfo {
int64 id;
url.mojom.Url main_frame_url;
+ // The id of the frame that "opened" this page, if any.
+ int64 opener_frame_id;
+
// This field is a dictionary of values, where each value is generated by
// a performance_manager::NodeDataDescriber implementation and keyed by the
// name it registered with. The intent is for each describer to describe
@@ -112,46 +111,74 @@ struct PageInfo {
string description_json;
};
-// Represents the momentary state of a Frame node.
+// Represents the momentary state of a Frame node. Sent from browser to the
+// chrome://discards WebUI via the GraphChangeStream (defined below).
struct FrameInfo {
int64 id;
+ // The last committed URL of this frame.
url.mojom.Url url;
+
+ // The ID of the page node this frame is associated with.
int64 page_id;
+
+ // The ID of the parent frame, if there is one. If not, this is a main frame.
int64 parent_frame_id;
+
+ // The ID of the process in which this frame is hosted.
int64 process_id;
// See PageInfo::description_json.
string description_json;
};
-// Represents the momentary state of a Process node.
+// Represents the momentary state of a Process node. Sent from browser to the
+// chrome://discards WebUI via the GraphChangeStream (defined below).
struct ProcessInfo {
int64 id;
+ // The PID of the process associated with this node.
mojo_base.mojom.ProcessId pid;
+
+ // The private memory usage of this process in KB.
uint64 private_footprint_kb;
// See PageInfo::description_json.
string description_json;
};
-// Represents the momentary state of a Worker node.
+// Represents the momentary state of a Worker node. Sent from browser to the
+// chrome://discards WebUI via the GraphChangeStream (defined below).
struct WorkerInfo {
int64 id;
+ // The URL of the worker.
url.mojom.Url url;
+
+ // The ID of the process is which this worker is hosted.
int64 process_id;
+ // An array of frames (by ID) that are clients of this worker (the worker is
+ // doing work on behalf of this frame). See
+ // WorkerNode::GetClientFrames() for details.
array<int64> client_frame_ids;
+
+ // An array of other workers (by ID) that are clients of this worker (the
+ // worker is doing work on behalf of these other workers). See
+ // WorkerNode::GetClientWorkers() for details.
array<int64> client_worker_ids;
+
+ // An array of workers (by ID) that are children of this worker. This can
+ // occur with shared and service workers owning their own dedicated workers.
+ // See WorkerNode::GetChildWorkers() for details.
array<int64> child_worker_ids;
// See PageInfo::description_json.
string description_json;
};
-// Used to transport favicon data.
+// Used to transport favicon data. Sent from browser to the chrome://discards
+// WebUI via the GraphChangeStream (defined below).
struct FavIconInfo {
int64 node_id;
@@ -161,7 +188,11 @@ struct FavIconInfo {
};
// Implement to receive a stream of notifications when performance manager
-// graph nodes are created, changed or deleted.
+// graph nodes are created, changed or deleted. Implemented in Javascript code
+// running in the chrome://discards WebUI, with data routed to it from an
+// observer of the performance_manager::Graph in the browser. The implementation
+// is injected into the browser via the browser-exposed GraphDump interface,
+// defined below.
interface GraphChangeStream {
// The |frame| was created.
FrameCreated(FrameInfo frame);
@@ -190,7 +221,8 @@ interface GraphChangeStream {
};
// This interface allows subscribing to a stream of events that track the state
-// of the performance manager graph.
+// of the performance manager graph. Implemented in browser code, and used from
+// Javascript code running in the chrome://discards WebUI.
interface GraphDump {
// Subscribes |change_subscriber| to a graph change stream.
SubscribeToChanges(pending_remote<GraphChangeStream> change_subscriber);
diff --git a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc
index fdbf79d7a00..95448e0d72c 100644
--- a/chromium/chrome/browser/ui/webui/discards/discards_ui.cc
+++ b/chromium/chrome/browser/ui/webui/discards/discards_ui.cc
@@ -41,6 +41,7 @@
#include "content/public/browser/web_ui_message_handler.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/resources/grit/ui_resources.h"
#include "url/gurl.h"
#include "url/origin.h"
@@ -133,9 +134,6 @@ class DiscardsDetailsProviderImpl : public discards::mojom::DetailsProvider {
GetLifecycleUnitVisibility(lifecycle_unit->GetVisibility());
info->loading_state = lifecycle_unit->GetLoadingState();
info->state = lifecycle_unit->GetState();
- resource_coordinator::DecisionDetails freeze_details;
- info->can_freeze = lifecycle_unit->CanFreeze(&freeze_details);
- info->cannot_freeze_reasons = freeze_details.GetFailureReasonStrings();
resource_coordinator::DecisionDetails discard_details;
info->cannot_discard_reasons = discard_details.GetFailureReasonStrings();
info->discard_reason = lifecycle_unit->GetDiscardReason();
@@ -193,12 +191,6 @@ class DiscardsDetailsProviderImpl : public discards::mojom::DetailsProvider {
std::move(callback).Run();
}
- void FreezeById(int32_t id) override {
- auto* lifecycle_unit = GetLifecycleUnitById(id);
- if (lifecycle_unit)
- lifecycle_unit->Freeze();
- }
-
void LoadById(int32_t id) override {
auto* lifecycle_unit = GetLifecycleUnitById(id);
if (lifecycle_unit)
@@ -225,7 +217,8 @@ DiscardsUI::DiscardsUI(content::WebUI* web_ui)
std::unique_ptr<content::WebUIDataSource> source(
content::WebUIDataSource::Create(chrome::kChromeUIDiscardsHost));
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources chrome://test 'self';");
source->AddResourcePath("discards.js", IDR_DISCARDS_JS);
diff --git a/chromium/chrome/browser/ui/webui/discards/graph_dump_impl.cc b/chromium/chrome/browser/ui/webui/discards/graph_dump_impl.cc
index 2cb540e1ebb..9351afb96c9 100644
--- a/chromium/chrome/browser/ui/webui/discards/graph_dump_impl.cc
+++ b/chromium/chrome/browser/ui/webui/discards/graph_dump_impl.cc
@@ -12,7 +12,6 @@
#include "base/json/json_string_value_serializer.h"
#include "base/macros.h"
#include "base/task/cancelable_task_tracker.h"
-#include "base/task/post_task.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "chrome/browser/favicon/favicon_service_factory.h"
#include "chrome/browser/profiles/profile.h"
@@ -193,31 +192,18 @@ void DiscardsGraphDumpImpl::SubscribeToChanges(
}
// Send creation notifications for all existing nodes.
- for (const performance_manager::ProcessNode* process_node :
- graph_->GetAllProcessNodes())
- SendProcessNotification(process_node, true);
-
- for (const performance_manager::PageNode* page_node :
- graph_->GetAllPageNodes()) {
- SendPageNotification(page_node, true);
- StartPageFaviconRequest(page_node);
-
- // Dispatch preorder frame notifications.
- for (const performance_manager::FrameNode* main_frame_node :
- page_node->GetMainFrameNodes()) {
- ForFrameAndOffspring(
- main_frame_node,
- [this](const performance_manager::FrameNode* frame_node) {
- this->SendFrameNotification(frame_node, true);
- this->StartFrameFaviconRequest(frame_node);
- });
- }
- }
-
- for (const performance_manager::WorkerNode* worker_node :
- graph_->GetAllWorkerNodes()) {
- SendWorkerNotification(worker_node, true);
- }
+ SendNotificationToAllNodes(/* created = */ true);
+
+ // It is entirely possible for there to be circular link references between
+ // nodes that already existed at the point this object was created (the loop
+ // was closed after the two nodes themselves were created). We don't have the
+ // exact order of historical events that led to the current graph state, so we
+ // simply fire off a node changed notification for all nodes after the node
+ // creation. This ensures that all targets exist the second time through, and
+ // any loops are closed. Afterwards any newly created loops will be properly
+ // maintained as node creation/destruction/link events will be fed to the
+ // graph in the proper order.
+ SendNotificationToAllNodes(/* created = */ false);
// Subscribe to subsequent notifications.
graph_->AddFrameNodeObserver(this);
@@ -265,8 +251,8 @@ void DiscardsGraphDumpImpl::OnTakenFromGraph(
// The favicon helper must be deleted on the UI thread.
if (favicon_request_helper_) {
- base::DeleteSoon(FROM_HERE, {content::BrowserThread::UI},
- std::move(favicon_request_helper_));
+ content::GetUIThreadTaskRunner({})->DeleteSoon(
+ FROM_HERE, std::move(favicon_request_helper_));
}
graph_ = nullptr;
@@ -305,6 +291,14 @@ void DiscardsGraphDumpImpl::OnBeforePageNodeRemoved(
RemoveNode(page_node);
}
+void DiscardsGraphDumpImpl::OnOpenerFrameNodeChanged(
+ const performance_manager::PageNode* page_node,
+ const performance_manager::FrameNode*,
+ OpenedType) {
+ DCHECK(HasNode(page_node));
+ SendPageNotification(page_node, false);
+}
+
void DiscardsGraphDumpImpl::OnFaviconUpdated(
const performance_manager::PageNode* page_node) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
@@ -391,13 +385,19 @@ void DiscardsGraphDumpImpl::RemoveNode(const performance_manager::Node* node) {
DCHECK_EQ(1u, erased);
}
+bool DiscardsGraphDumpImpl::HasNode(
+ const performance_manager::Node* node) const {
+ return node_ids_.find(node) != node_ids_.end();
+}
+
int64_t DiscardsGraphDumpImpl::GetNodeId(
- const performance_manager::Node* node) {
+ const performance_manager::Node* node) const {
if (node == nullptr)
return 0;
- DCHECK(node_ids_.find(node) != node_ids_.end());
- return node_ids_[node].GetUnsafeValue();
+ auto it = node_ids_.find(node);
+ DCHECK(it != node_ids_.end());
+ return it->second.GetUnsafeValue();
}
DiscardsGraphDumpImpl::FaviconRequestHelper*
@@ -416,8 +416,8 @@ void DiscardsGraphDumpImpl::StartPageFaviconRequest(
if (!page_node->GetMainFrameUrl().is_valid())
return;
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&FaviconRequestHelper::RequestFavicon,
base::Unretained(EnsureFaviconRequestHelper()),
page_node->GetMainFrameUrl(),
@@ -429,14 +429,44 @@ void DiscardsGraphDumpImpl::StartFrameFaviconRequest(
if (!frame_node->GetURL().is_valid())
return;
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&FaviconRequestHelper::RequestFavicon,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&FaviconRequestHelper::RequestFavicon,
base::Unretained(EnsureFaviconRequestHelper()),
frame_node->GetURL(),
frame_node->GetPageNode()->GetContentsProxy(),
GetNodeId(frame_node)));
}
+void DiscardsGraphDumpImpl::SendNotificationToAllNodes(bool created) {
+ for (const performance_manager::ProcessNode* process_node :
+ graph_->GetAllProcessNodes())
+ SendProcessNotification(process_node, created);
+
+ for (const performance_manager::PageNode* page_node :
+ graph_->GetAllPageNodes()) {
+ SendPageNotification(page_node, created);
+ if (created)
+ StartPageFaviconRequest(page_node);
+
+ // Dispatch preorder frame notifications.
+ for (const performance_manager::FrameNode* main_frame_node :
+ page_node->GetMainFrameNodes()) {
+ ForFrameAndOffspring(
+ main_frame_node,
+ [this, created](const performance_manager::FrameNode* frame_node) {
+ this->SendFrameNotification(frame_node, created);
+ if (created)
+ this->StartFrameFaviconRequest(frame_node);
+ });
+ }
+ }
+
+ for (const performance_manager::WorkerNode* worker_node :
+ graph_->GetAllWorkerNodes()) {
+ SendWorkerNotification(worker_node, created);
+ }
+}
+
void DiscardsGraphDumpImpl::SendFrameNotification(
const performance_manager::FrameNode* frame,
bool created) {
@@ -459,10 +489,11 @@ void DiscardsGraphDumpImpl::SendFrameNotification(
frame_info->description_json =
ToJSON(graph_->GetNodeDataDescriberRegistry()->DescribeNodeData(frame));
- if (created)
+ if (created) {
change_subscriber_->FrameCreated(std::move(frame_info));
- else
+ } else {
change_subscriber_->FrameChanged(std::move(frame_info));
+ }
}
void DiscardsGraphDumpImpl::SendPageNotification(
@@ -474,6 +505,7 @@ void DiscardsGraphDumpImpl::SendPageNotification(
page_info->id = GetNodeId(page_node);
page_info->main_frame_url = page_node->GetMainFrameUrl();
+ page_info->opener_frame_id = GetNodeId(page_node->GetOpenerFrameNode());
page_info->description_json = ToJSON(
graph_->GetNodeDataDescriberRegistry()->DescribeNodeData(page_node));
diff --git a/chromium/chrome/browser/ui/webui/discards/graph_dump_impl.h b/chromium/chrome/browser/ui/webui/discards/graph_dump_impl.h
index 893d7f3faec..de771acc112 100644
--- a/chromium/chrome/browser/ui/webui/discards/graph_dump_impl.h
+++ b/chromium/chrome/browser/ui/webui/discards/graph_dump_impl.h
@@ -99,6 +99,9 @@ class DiscardsGraphDumpImpl : public discards::mojom::GraphDump,
void OnHadFormInteractionChanged(
const performance_manager::FrameNode* frame_node) override {}
// Ignored.
+ void OnIsAudibleChanged(
+ const performance_manager::FrameNode* frame_node) override {}
+ // Ignored.
void OnFirstContentfulPaint(
const performance_manager::FrameNode* frame_node,
base::TimeDelta time_since_navigation_start) override {}
@@ -107,6 +110,10 @@ class DiscardsGraphDumpImpl : public discards::mojom::GraphDump,
void OnPageNodeAdded(const performance_manager::PageNode* page_node) override;
void OnBeforePageNodeRemoved(
const performance_manager::PageNode* page_node) override;
+ void OnOpenerFrameNodeChanged(
+ const performance_manager::PageNode* page_node,
+ const performance_manager::FrameNode* previous_opener,
+ OpenedType previous_opened_type) override;
void OnIsVisibleChanged(
const performance_manager::PageNode* page_node) override {} // Ignored.
void OnIsAudibleChanged(
@@ -186,7 +193,8 @@ class DiscardsGraphDumpImpl : public discards::mojom::GraphDump,
void AddNode(const performance_manager::Node* node);
void RemoveNode(const performance_manager::Node* node);
- int64_t GetNodeId(const performance_manager::Node* node);
+ bool HasNode(const performance_manager::Node* node) const;
+ int64_t GetNodeId(const performance_manager::Node* node) const;
FaviconRequestHelper* EnsureFaviconRequestHelper();
@@ -194,6 +202,7 @@ class DiscardsGraphDumpImpl : public discards::mojom::GraphDump,
void StartFrameFaviconRequest(
const performance_manager::FrameNode* frame_node);
+ void SendNotificationToAllNodes(bool created);
void SendFrameNotification(const performance_manager::FrameNode* frame,
bool created);
void SendPageNotification(const performance_manager::PageNode* page,
diff --git a/chromium/chrome/browser/ui/webui/discards/graph_dump_impl_unittest.cc b/chromium/chrome/browser/ui/webui/discards/graph_dump_impl_unittest.cc
index 32c220349fb..e554f7d7a8d 100644
--- a/chromium/chrome/browser/ui/webui/discards/graph_dump_impl_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/discards/graph_dump_impl_unittest.cc
@@ -212,8 +212,9 @@ TEST_F(DiscardsGraphDumpImplTest, ChangeStream) {
task_environment.RunUntilIdle();
- // Validate that the initial graph state dump is complete.
- EXPECT_EQ(0u, change_stream.num_changes());
+ // Validate that the initial graph state dump is complete. Note that there is
+ // an update for each node as part of the initial state dump.
+ EXPECT_EQ(8u, change_stream.num_changes());
EXPECT_EQ(8u, change_stream.id_set().size());
EXPECT_EQ(2u, change_stream.process_map().size());
@@ -277,7 +278,7 @@ TEST_F(DiscardsGraphDumpImplTest, ChangeStream) {
task_environment.RunUntilIdle();
// Main frame navigation results in a notification for the url.
- EXPECT_EQ(1u, change_stream.num_changes());
+ EXPECT_EQ(9u, change_stream.num_changes());
EXPECT_FALSE(base::Contains(change_stream.id_set(), child_frame_id));
const auto main_page_it = change_stream.page_map().find(
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 2a2e43e6b6b..a37d09a30f4 100644
--- a/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/domain_reliability_internals_ui.cc
@@ -13,6 +13,7 @@
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
DomainReliabilityInternalsUI::DomainReliabilityInternalsUI(
@@ -20,7 +21,8 @@ DomainReliabilityInternalsUI::DomainReliabilityInternalsUI(
: content::WebUIController(web_ui) {
content::WebUIDataSource* html_source = content::WebUIDataSource::Create(
chrome::kChromeUIDomainReliabilityInternalsHost);
- html_source->OverrideContentSecurityPolicyScriptSrc(
+ html_source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
html_source->AddResourcePath("domain_reliability_internals.css",
IDR_DOMAIN_RELIABILITY_INTERNALS_CSS);
diff --git a/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc b/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc
index e63f09137ac..7ca1ee5e2e3 100644
--- a/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/download_internals/download_internals_ui.cc
@@ -13,13 +13,15 @@
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_controller.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
DownloadInternalsUI::DownloadInternalsUI(content::WebUI* web_ui)
: content::WebUIController(web_ui) {
// chrome://download-internals source.
content::WebUIDataSource* html_source =
content::WebUIDataSource::Create(chrome::kChromeUIDownloadInternalsHost);
- html_source->OverrideContentSecurityPolicyScriptSrc(
+ html_source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
// Required resources.
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 1bc52afd2e8..c63615e731e 100644
--- a/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc
+++ b/chromium/chrome/browser/ui/webui/downloads/downloads_list_tracker.cc
@@ -16,8 +16,6 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
-#include "base/value_conversions.h"
-#include "base/values.h"
#include "chrome/browser/download/download_crx_util.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_query.h"
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 c60227d8226..e93f7e8c7aa 100644
--- a/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc
+++ b/chromium/chrome/browser/ui/webui/extensions/extensions_internals_source.cc
@@ -20,8 +20,10 @@
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/activity.h"
+#include "extensions/browser/disable_reason.h"
#include "extensions/browser/event_listener_map.h"
#include "extensions/browser/event_router.h"
+#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/process_manager.h"
#include "extensions/common/manifest_handlers/permissions_parser.h"
@@ -121,6 +123,46 @@ base::Value CreationFlagsToList(int creation_flags) {
return flags_value;
}
+base::Value DisableReasonsToList(int disable_reasons) {
+ base::Value disable_reasons_value(base::Value::Type::LIST);
+ if (disable_reasons &
+ extensions::disable_reason::DISABLE_PERMISSIONS_INCREASE) {
+ disable_reasons_value.Append("DISABLE_PERMISSIONS_INCREASE");
+ }
+ if (disable_reasons & extensions::disable_reason::DISABLE_RELOAD)
+ disable_reasons_value.Append("DISABLE_RELOAD");
+ if (disable_reasons &
+ extensions::disable_reason::DISABLE_UNSUPPORTED_REQUIREMENT) {
+ disable_reasons_value.Append("DISABLE_UNSUPPORTED_REQUIREMENT");
+ }
+ if (disable_reasons & extensions::disable_reason::DISABLE_SIDELOAD_WIPEOUT)
+ disable_reasons_value.Append("DISABLE_SIDELOAD_WIPEOUT");
+ if (disable_reasons & extensions::disable_reason::DISABLE_NOT_VERIFIED)
+ disable_reasons_value.Append("DISABLE_NOT_VERIFIED");
+ if (disable_reasons & extensions::disable_reason::DISABLE_GREYLIST)
+ disable_reasons_value.Append("DISABLE_GREYLIST");
+ if (disable_reasons & extensions::disable_reason::DISABLE_CORRUPTED)
+ disable_reasons_value.Append("DISABLE_CORRUPTED");
+ if (disable_reasons & extensions::disable_reason::DISABLE_REMOTE_INSTALL)
+ disable_reasons_value.Append("DISABLE_REMOTE_INSTALL");
+ if (disable_reasons & extensions::disable_reason::DISABLE_EXTERNAL_EXTENSION)
+ disable_reasons_value.Append("DISABLE_EXTERNAL_EXTENSION");
+ if (disable_reasons &
+ extensions::disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
+ disable_reasons_value.Append("DISABLE_UPDATE_REQUIRED_BY_POLICY");
+ }
+ if (disable_reasons &
+ extensions::disable_reason::DISABLE_CUSTODIAN_APPROVAL_REQUIRED) {
+ disable_reasons_value.Append("DISABLE_CUSTODIAN_APPROVAL_REQUIRED");
+ }
+ if (disable_reasons & extensions::disable_reason::DISABLE_BLOCKED_BY_POLICY)
+ disable_reasons_value.Append("DISABLE_BLOCKED_BY_POLICY");
+ if (disable_reasons &
+ extensions::disable_reason::DISABLE_REMOTELY_FOR_MALWARE) {
+ disable_reasons_value.Append("DISABLE_REMOTELY_FOR_MALWARE");
+ }
+ return disable_reasons_value;
+}
// The JSON we generate looks like this:
// Note:
// - tab_specific permissions can have 0 or more DICT entries with each tab id
@@ -133,6 +175,7 @@ base::Value CreationFlagsToList(int creation_flags) {
//
// [ {
// "creation_flags": [ "ALLOW_FILE_ACCESS", "FROM_WEBSTORE" ],
+// "disable_reasons": ["DISABLE_USER_ACTION"],
// "event_listeners": {
// "count": 2,
// "events": [ {
@@ -190,6 +233,8 @@ base::Value CreationFlagsToList(int creation_flags) {
// DICT
// "creation_flags": LIST
// STRING
+// "disable_reasons": LIST
+// STRING
// "event_listeners": DICT
// "count": INT
// "listeners": LIST
@@ -251,6 +296,7 @@ constexpr base::StringPiece kEventsListenersKey = "event_listeners";
constexpr base::StringPiece kExtraDataKey = "extra_data";
constexpr base::StringPiece kFilterKey = "filter";
constexpr base::StringPiece kInternalsCreationFlagsKey = "creation_flags";
+constexpr base::StringPiece kInternalsDisableReasonsKey = "disable_reasons";
constexpr base::StringPiece kInternalsIdKey = "id";
constexpr base::StringPiece kInternalsNameKey = "name";
constexpr base::StringPiece kInternalsVersionKey = "version";
@@ -389,7 +435,7 @@ void AddEventListenerData(extensions::EventRouter* event_router,
base::Value(listener_entry->listener_url().spec()));
// Add the filter if one exists.
base::Value* const filter = listener_entry->filter();
- if (filter != nullptr) {
+ if (filter) {
listener_data.SetKey(kFilterKey, filter->Clone());
}
listeners_list.Append(std::move(listener_data));
@@ -448,6 +494,7 @@ std::string ExtensionsInternalsSource::WriteToString() const {
->GenerateInstalledExtensionsSet();
extensions::ProcessManager* process_manager =
extensions::ProcessManager::Get(profile_);
+ extensions::ExtensionPrefs* prefs = extensions::ExtensionPrefs::Get(profile_);
base::Value data(base::Value::Type::LIST);
for (const auto& extension : *extensions) {
base::Value extension_data(base::Value::Type::DICTIONARY);
@@ -455,6 +502,9 @@ std::string ExtensionsInternalsSource::WriteToString() const {
extension_data.SetKey(kInternalsCreationFlagsKey,
CreationFlagsToList(extension->creation_flags()));
extension_data.SetKey(
+ kInternalsDisableReasonsKey,
+ DisableReasonsToList(prefs->GetDisableReasons(extension->id())));
+ extension_data.SetKey(
kKeepaliveKey, FormatKeepaliveData(process_manager, extension.get()));
extension_data.SetKey(kLocationKey,
base::Value(LocationToString(extension->location())));
diff --git a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc
index 2f41efa7f34..0b8e0ffe833 100644
--- a/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc
+++ b/chromium/chrome/browser/ui/webui/extensions/extensions_ui.cc
@@ -40,6 +40,7 @@
#include "extensions/common/extension_features.h"
#include "extensions/common/extension_urls.h"
#include "extensions/grit/extensions_browser_resources.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/web_ui_util.h"
@@ -382,7 +383,8 @@ ExtensionsUI::ExtensionsUI(content::WebUI* web_ui)
// Need to allow <object> elements so that the <extensionoptions> browser
// plugin can be loaded within chrome://extensions.
- source->OverrideContentSecurityPolicyObjectSrc("object-src 'self';");
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ObjectSrc, "object-src 'self';");
content::WebUIDataSource::Add(profile, source);
diff --git a/chromium/chrome/browser/ui/webui/flags_ui.cc b/chromium/chrome/browser/ui/webui/flags_ui.cc
index 92050e17926..9cfe2e6ab37 100644
--- a/chromium/chrome/browser/ui/webui/flags_ui.cc
+++ b/chromium/chrome/browser/ui/webui/flags_ui.cc
@@ -33,6 +33,7 @@
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
@@ -62,7 +63,8 @@ namespace {
content::WebUIDataSource* CreateFlagsUIHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIFlagsHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
source->AddString(flags_ui::kVersion, version_info::GetVersionNumber());
diff --git a/chromium/chrome/browser/ui/webui/help/test_version_updater.cc b/chromium/chrome/browser/ui/webui/help/test_version_updater.cc
index d10cc076fae..b159078b28a 100644
--- a/chromium/chrome/browser/ui/webui/help/test_version_updater.cc
+++ b/chromium/chrome/browser/ui/webui/help/test_version_updater.cc
@@ -10,5 +10,6 @@ TestVersionUpdater::~TestVersionUpdater() = default;
void TestVersionUpdater::CheckForUpdate(const StatusCallback& callback,
const PromoteCallback&) {
- callback.Run(status_, progress_, rollback_, version_, update_size_, message_);
+ callback.Run(status_, progress_, rollback_, powerwash_, version_,
+ update_size_, message_);
}
diff --git a/chromium/chrome/browser/ui/webui/help/test_version_updater.h b/chromium/chrome/browser/ui/webui/help/test_version_updater.h
index 2db702d317a..e07e61a3ae2 100644
--- a/chromium/chrome/browser/ui/webui/help/test_version_updater.h
+++ b/chromium/chrome/browser/ui/webui/help/test_version_updater.h
@@ -42,6 +42,7 @@ class TestVersionUpdater : public VersionUpdater {
Status status_ = Status::UPDATED;
int progress_ = 0;
bool rollback_ = false;
+ bool powerwash_ = false;
std::string version_;
int64_t update_size_ = 0;
base::string16 message_;
diff --git a/chromium/chrome/browser/ui/webui/help/version_updater.h b/chromium/chrome/browser/ui/webui/help/version_updater.h
index de48fe833ee..34f7adaa37d 100644
--- a/chromium/chrome/browser/ui/webui/help/version_updater.h
+++ b/chromium/chrome/browser/ui/webui/help/version_updater.h
@@ -58,6 +58,7 @@ class VersionUpdater {
// |progress| should only be non-zero for the UPDATING state.
// |rollback| indicates whether the update is actually a rollback, which
// requires wiping the device upon reboot.
+ // |powerwash| indicates whether the device will be wiped on reboot.
// |version| is the version of the available update and should be empty string
// when update is not available.
// |update_size| is the size of the available update in bytes and should be 0
@@ -66,6 +67,7 @@ class VersionUpdater {
typedef base::Callback<void(Status status,
int progress,
bool rollback,
+ bool powerwash,
const std::string& version,
int64_t update_size,
const base::string16& message)>
diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_basic.cc b/chromium/chrome/browser/ui/webui/help/version_updater_basic.cc
index 93e3f41a76d..2a4c334e2ea 100644
--- a/chromium/chrome/browser/ui/webui/help/version_updater_basic.cc
+++ b/chromium/chrome/browser/ui/webui/help/version_updater_basic.cc
@@ -13,7 +13,8 @@ void VersionUpdaterBasic::CheckForUpdate(
const Status status = UpgradeDetector::GetInstance()->notify_upgrade()
? NEARLY_UPDATED
: DISABLED;
- status_callback.Run(status, 0, false, std::string(), 0, base::string16());
+ status_callback.Run(status, 0, false, false, std::string(), 0,
+ base::string16());
}
VersionUpdater* VersionUpdater::Create(content::WebContents* web_contents) {
diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc
index 23166d7d304..0a0225fee0c 100644
--- a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc
+++ b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos.cc
@@ -51,12 +51,12 @@ enum NetworkStatus {
const bool kDefaultAutoUpdateDisabled = false;
NetworkStatus GetNetworkStatus(bool interactive,
- const chromeos::NetworkState* network) {
+ const chromeos::NetworkState* network,
+ bool metered) {
if (!network || !network->IsConnectedState()) // Offline state.
return NETWORK_STATUS_OFFLINE;
- // Treats tethered networks as cellular networks.
- if (network->IsUsingMobileData() &&
+ if (metered &&
!help_utils_chromeos::IsUpdateOverCellularAllowed(interactive)) {
return NETWORK_STATUS_DISALLOWED;
}
@@ -76,10 +76,11 @@ bool IsAutoUpdateDisabled() {
return update_disabled;
}
-base::string16 GetConnectionTypeAsUTF16(const chromeos::NetworkState* network) {
+base::string16 GetConnectionTypeAsUTF16(const chromeos::NetworkState* network,
+ bool metered) {
const std::string type = network->type();
if (chromeos::NetworkTypePattern::WiFi().MatchesType(type)) {
- if (network->IsUsingMobileData())
+ if (metered)
return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_METERED_WIFI);
return l10n_util::GetStringUTF16(IDS_NETWORK_TYPE_WIFI);
}
@@ -99,7 +100,8 @@ base::string16 GetConnectionTypeAsUTF16(const chromeos::NetworkState* network) {
bool EnsureCanUpdate(bool interactive,
const VersionUpdater::StatusCallback& callback) {
if (IsAutoUpdateDisabled()) {
- callback.Run(VersionUpdater::DISABLED_BY_ADMIN, 0, false, std::string(), 0,
+ callback.Run(VersionUpdater::DISABLED_BY_ADMIN, 0, false, false,
+ std::string(), 0,
l10n_util::GetStringUTF16(IDS_UPGRADE_DISABLED_BY_POLICY));
return false;
}
@@ -108,19 +110,19 @@ bool EnsureCanUpdate(bool interactive,
chromeos::NetworkHandler::Get()->network_state_handler();
const chromeos::NetworkState* network =
network_state_handler->DefaultNetwork();
-
+ const bool metered = network_state_handler->default_network_is_metered();
// Don't allow an update if we're currently offline or connected
// to a network for which updates are disallowed.
- NetworkStatus status = GetNetworkStatus(interactive, network);
+ NetworkStatus status = GetNetworkStatus(interactive, network, metered);
if (status == NETWORK_STATUS_OFFLINE) {
- callback.Run(VersionUpdater::FAILED_OFFLINE, 0, false, std::string(), 0,
- l10n_util::GetStringUTF16(IDS_UPGRADE_OFFLINE));
+ callback.Run(VersionUpdater::FAILED_OFFLINE, 0, false, false, std::string(),
+ 0, l10n_util::GetStringUTF16(IDS_UPGRADE_OFFLINE));
return false;
} else if (status == NETWORK_STATUS_DISALLOWED) {
base::string16 message = l10n_util::GetStringFUTF16(
- IDS_UPGRADE_DISALLOWED, GetConnectionTypeAsUTF16(network));
+ IDS_UPGRADE_DISALLOWED, GetConnectionTypeAsUTF16(network, metered));
callback.Run(VersionUpdater::FAILED_CONNECTION_TYPE_DISALLOWED, 0, false,
- std::string(), 0, message);
+ false, std::string(), 0, message);
return false;
}
@@ -214,7 +216,7 @@ void VersionUpdaterCros::OnSetUpdateOverCellularOneTimePermission(
// TODO(https://crbug.com/927452): invoke callback to signal about page to
// show appropriate error message.
LOG(ERROR) << "Error setting update over cellular one time permission.";
- callback_.Run(VersionUpdater::FAILED, 0, false, std::string(), 0,
+ callback_.Run(VersionUpdater::FAILED, 0, false, false, std::string(), 0,
base::string16());
}
}
@@ -318,8 +320,8 @@ void VersionUpdaterCros::UpdateStatusChanged(
NOTREACHED();
}
- callback_.Run(my_status, progress, status.is_enterprise_rollback(), version,
- size, message);
+ callback_.Run(my_status, progress, status.is_enterprise_rollback(),
+ status.will_powerwash_after_reboot(), version, size, message);
last_operation_ = status.current_operation();
if (check_for_update_when_idle_ &&
@@ -333,5 +335,5 @@ void VersionUpdaterCros::OnUpdateCheck(
// If version updating is not implemented, this binary is the most up-to-date
// possible with respect to automatic updating.
if (result == UpdateEngineClient::UPDATE_RESULT_NOTIMPLEMENTED)
- callback_.Run(UPDATED, 0, false, std::string(), 0, base::string16());
+ callback_.Run(UPDATED, 0, false, false, std::string(), 0, base::string16());
}
diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos_unittest.cc b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos_unittest.cc
index 5115ce9c60a..999a1a67722 100644
--- a/chromium/chrome/browser/ui/webui/help/version_updater_chromeos_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/help/version_updater_chromeos_unittest.cc
@@ -33,6 +33,7 @@ namespace {
void CheckNotification(VersionUpdater::Status /* status */,
int /* progress */,
bool /* rollback */,
+ bool /* powerwash */,
const std::string& /* version */,
int64_t /* size */,
const base::string16& /* message */) {}
diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_mac.mm b/chromium/chrome/browser/ui/webui/help/version_updater_mac.mm
index 4550497b5ab..6680e23b73e 100644
--- a/chromium/chrome/browser/ui/webui/help/version_updater_mac.mm
+++ b/chromium/chrome/browser/ui/webui/help/version_updater_mac.mm
@@ -108,7 +108,7 @@ void VersionUpdaterMac::CheckForUpdate(
} else {
// There is no glue, or the application is on a read-only filesystem.
// Updates and promotions are impossible.
- status_callback_.Run(DISABLED, 0, false, std::string(), 0,
+ status_callback_.Run(DISABLED, 0, false, false, std::string(), 0,
base::string16());
}
}
@@ -231,7 +231,7 @@ void VersionUpdaterMac::UpdateStatus(NSDictionary* dictionary) {
}
if (!status_callback_.is_null())
- status_callback_.Run(status, 0, false, std::string(), 0, message);
+ status_callback_.Run(status, 0, false, false, std::string(), 0, message);
PromotionState promotion_state;
if (!promote_callback_.is_null()) {
diff --git a/chromium/chrome/browser/ui/webui/help/version_updater_win.cc b/chromium/chrome/browser/ui/webui/help/version_updater_win.cc
index f77d46664fd..be910614a29 100644
--- a/chromium/chrome/browser/ui/webui/help/version_updater_win.cc
+++ b/chromium/chrome/browser/ui/webui/help/version_updater_win.cc
@@ -31,7 +31,7 @@ void VersionUpdaterWin::CheckForUpdate(const StatusCallback& callback,
// There is no supported integration with Google Update for Chromium.
callback_ = callback;
- callback_.Run(CHECKING, 0, false, std::string(), 0, base::string16());
+ callback_.Run(CHECKING, 0, false, false, std::string(), 0, base::string16());
DoBeginUpdateCheck(false /* !install_update_if_possible */);
}
@@ -52,18 +52,20 @@ void VersionUpdaterWin::OnUpdateCheckComplete(
// Notify the caller that the update is now beginning and initiate it.
DoBeginUpdateCheck(true /* install_update_if_possible */);
- callback_.Run(UPDATING, 0, false, std::string(), 0, base::string16());
+ callback_.Run(UPDATING, 0, false, false, std::string(), 0, base::string16());
}
void VersionUpdaterWin::OnUpgradeProgress(int progress,
const base::string16& new_version) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- callback_.Run(UPDATING, progress, false, std::string(), 0, base::string16());
+ callback_.Run(UPDATING, progress, false, false, std::string(), 0,
+ base::string16());
}
void VersionUpdaterWin::OnUpgradeComplete(const base::string16& new_version) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- callback_.Run(NEARLY_UPDATED, 0, false, std::string(), 0, base::string16());
+ callback_.Run(NEARLY_UPDATED, 0, false, false, std::string(), 0,
+ base::string16());
}
void VersionUpdaterWin::OnError(GoogleUpdateErrorCode error_code,
@@ -94,7 +96,7 @@ void VersionUpdaterWin::OnError(GoogleUpdateErrorCode error_code,
}
break;
}
- callback_.Run(status, 0, false, std::string(), 0, message);
+ callback_.Run(status, 0, false, false, std::string(), 0, message);
}
void VersionUpdaterWin::DoBeginUpdateCheck(bool install_update_if_possible) {
@@ -107,7 +109,7 @@ void VersionUpdaterWin::DoBeginUpdateCheck(bool install_update_if_possible) {
void VersionUpdaterWin::OnPendingRestartCheck(bool is_update_pending_restart) {
callback_.Run(is_update_pending_restart ? NEARLY_UPDATED : UPDATED, 0, false,
- std::string(), 0, base::string16());
+ false, std::string(), 0, base::string16());
}
VersionUpdater* VersionUpdater::Create(content::WebContents* web_contents) {
diff --git a/chromium/chrome/browser/ui/webui/internals/internals_ui.cc b/chromium/chrome/browser/ui/webui/internals/internals_ui.cc
new file mode 100644
index 00000000000..4a5abeb02fc
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/internals/internals_ui.cc
@@ -0,0 +1,59 @@
+// Copyright 2020 The Chromium 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/internals/internals_ui.h"
+
+#include "chrome/common/url_constants.h"
+#include "chrome/grit/dev_ui_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"
+
+#if defined(OS_ANDROID)
+#include "chrome/browser/ui/webui/internals/query_tiles/query_tiles_internals_ui_message_handler.h"
+#else
+#include "chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.h"
+#include "mojo/public/cpp/bindings/self_owned_receiver.h"
+#endif // defined(OS_ANDROID)
+
+InternalsUI::InternalsUI(content::WebUI* web_ui)
+ : ui::MojoWebUIController(web_ui, /*enable_chrome_send=*/true) {
+ profile_ = Profile::FromWebUI(web_ui);
+ source_ = content::WebUIDataSource::Create(chrome::kChromeUIInternalsHost);
+
+ // Add your sub-URL internals WebUI here.
+#if defined(OS_ANDROID)
+ // chrome://internals/query-tiles
+ AddQueryTilesInternals(web_ui);
+#else
+ // chrome://internals/web-app
+ WebAppInternalsPageHandlerImpl::AddPageResources(source_);
+#endif // defined(OS_ANDROID)
+
+ content::WebUIDataSource::Add(profile_, source_);
+}
+
+InternalsUI::~InternalsUI() = default;
+
+#if defined(OS_ANDROID)
+void InternalsUI::AddQueryTilesInternals(content::WebUI* web_ui) {
+ source_->AddResourcePath("query_tiles_internals.js",
+ IDR_QUERY_TILES_INTERNALS_JS);
+ source_->AddResourcePath("query_tiles_internals_browser_proxy.js",
+ IDR_QUERY_TILES_INTERNALS_BROWSER_PROXY_JS);
+ source_->AddResourcePath("query-tiles", IDR_QUERY_TILES_INTERNALS_HTML);
+ web_ui->AddMessageHandler(
+ std::make_unique<QueryTilesInternalsUIMessageHandler>(profile_));
+}
+#else // defined(OS_ANDROID)
+void InternalsUI::BindInterface(
+ mojo::PendingReceiver<mojom::web_app_internals::WebAppInternalsPageHandler>
+ receiver) {
+ mojo::MakeSelfOwnedReceiver(
+ std::make_unique<WebAppInternalsPageHandlerImpl>(profile_),
+ std::move(receiver));
+}
+#endif // defined(OS_ANDROID)
+
+WEB_UI_CONTROLLER_TYPE_IMPL(InternalsUI)
diff --git a/chromium/chrome/browser/ui/webui/internals/internals_ui.h b/chromium/chrome/browser/ui/webui/internals/internals_ui.h
new file mode 100644
index 00000000000..7339b46df97
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/internals/internals_ui.h
@@ -0,0 +1,48 @@
+// Copyright 2020 The Chromium 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_INTERNALS_INTERNALS_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_INTERNALS_INTERNALS_UI_H_
+
+#include "build/build_config.h"
+#include "chrome/browser/profiles/profile.h"
+#include "content/public/browser/web_ui_data_source.h"
+#include "ui/webui/mojo_web_ui_controller.h"
+
+#if !defined(OS_ANDROID)
+// gn check doesn't understand "#if !defined(OS_ANDROID)" and fails this
+// non-Android include on Android.
+#include "chrome/browser/ui/webui/internals/web_app/web_app_internals.mojom.h" // nogncheck
+#endif
+
+namespace content {
+class WebUI;
+} // namespace content
+
+// Client could put debug WebUI as sub-URL under chrome://internals/.
+// e.g. chrome://internals/your-feature.
+class InternalsUI : public ui::MojoWebUIController {
+ public:
+ explicit InternalsUI(content::WebUI* web_ui);
+ ~InternalsUI() override;
+
+#if !defined(OS_ANDROID)
+ void BindInterface(
+ mojo::PendingReceiver<
+ mojom::web_app_internals::WebAppInternalsPageHandler> receiver);
+#endif // !defined(OS_ANDROID)
+
+ private:
+ WEB_UI_CONTROLLER_TYPE_DECL();
+
+#if defined(OS_ANDROID)
+ // Add resources and message handler for chrome://internals/query-tiles.
+ void AddQueryTilesInternals(content::WebUI* web_ui);
+#endif // defined(OS_ANDROID)
+
+ Profile* profile_;
+ content::WebUIDataSource* source_;
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_INTERNALS_INTERNALS_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/internals/query_tiles/OWNERS b/chromium/chrome/browser/ui/webui/internals/query_tiles/OWNERS
new file mode 100644
index 00000000000..593e722800d
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/internals/query_tiles/OWNERS
@@ -0,0 +1 @@
+file://components/query_tiles/OWNERS
diff --git a/chromium/chrome/browser/ui/webui/internals/query_tiles/query_tiles_internals_ui_message_handler.cc b/chromium/chrome/browser/ui/webui/internals/query_tiles/query_tiles_internals_ui_message_handler.cc
new file mode 100644
index 00000000000..c0bbb708bd5
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/internals/query_tiles/query_tiles_internals_ui_message_handler.cc
@@ -0,0 +1,70 @@
+// Copyright 2020 The Chromium 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/internals/query_tiles/query_tiles_internals_ui_message_handler.h"
+
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "base/bind.h"
+#include "base/values.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/profiles/profile_key.h"
+#include "chrome/browser/query_tiles/tile_service_factory.h"
+#include "components/query_tiles/tile_service.h"
+#include "content/public/browser/web_ui.h"
+
+QueryTilesInternalsUIMessageHandler::QueryTilesInternalsUIMessageHandler(
+ Profile* profile)
+ : tile_service_(query_tiles::TileServiceFactory::GetForKey(
+ profile->GetProfileKey())) {
+ DCHECK(tile_service_);
+}
+
+QueryTilesInternalsUIMessageHandler::~QueryTilesInternalsUIMessageHandler() =
+ default;
+
+void QueryTilesInternalsUIMessageHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "startFetch", base::BindRepeating(
+ &QueryTilesInternalsUIMessageHandler::HandleStartFetch,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "purgeDb",
+ base::BindRepeating(&QueryTilesInternalsUIMessageHandler::HandlePurgeDb,
+ base::Unretained(this)));
+
+ web_ui()->RegisterMessageCallback(
+ "getServiceStatus",
+ base::Bind(&QueryTilesInternalsUIMessageHandler::HandleGetServiceStatus,
+ weak_ptr_factory_.GetWeakPtr()));
+
+ web_ui()->RegisterMessageCallback(
+ "getTileData",
+ base::Bind(&QueryTilesInternalsUIMessageHandler::HandleGetTileData,
+ weak_ptr_factory_.GetWeakPtr()));
+}
+
+void QueryTilesInternalsUIMessageHandler::HandleGetTileData(
+ const base::ListValue* args) {
+ NOTIMPLEMENTED();
+}
+
+void QueryTilesInternalsUIMessageHandler::HandleGetServiceStatus(
+ const base::ListValue* args) {
+ NOTIMPLEMENTED();
+}
+
+void QueryTilesInternalsUIMessageHandler::HandleStartFetch(
+ const base::ListValue* args) {
+ AllowJavascript();
+ tile_service_->StartFetchForTiles(false /*is_from_reduce_mode*/,
+ base::BindOnce([](bool reschedule) {}));
+}
+
+void QueryTilesInternalsUIMessageHandler::HandlePurgeDb(
+ const base::ListValue* args) {
+ tile_service_->PurgeDb();
+}
diff --git a/chromium/chrome/browser/ui/webui/internals/query_tiles/query_tiles_internals_ui_message_handler.h b/chromium/chrome/browser/ui/webui/internals/query_tiles/query_tiles_internals_ui_message_handler.h
new file mode 100644
index 00000000000..1bd47eb5935
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/internals/query_tiles/query_tiles_internals_ui_message_handler.h
@@ -0,0 +1,43 @@
+// Copyright 2020 The Chromium 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_INTERNALS_QUERY_TILES_QUERY_TILES_INTERNALS_UI_MESSAGE_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_INTERNALS_QUERY_TILES_QUERY_TILES_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
+
+class Profile;
+
+namespace query_tiles {
+class TileService;
+}
+
+class QueryTilesInternalsUIMessageHandler
+ : public content::WebUIMessageHandler {
+ public:
+ explicit QueryTilesInternalsUIMessageHandler(Profile* profile);
+ ~QueryTilesInternalsUIMessageHandler() override;
+
+ // content::WebUIMessageHandler implementation.
+ void RegisterMessages() override;
+
+ private:
+ void HandleGetServiceStatus(const base::ListValue* args);
+ void HandleGetTileData(const base::ListValue* args);
+ void HandleStartFetch(const base::ListValue* args);
+ void HandlePurgeDb(const base::ListValue* args);
+
+ query_tiles::TileService* tile_service_;
+
+ base::WeakPtrFactory<QueryTilesInternalsUIMessageHandler> weak_ptr_factory_{
+ this};
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_INTERNALS_QUERY_TILES_QUERY_TILES_INTERNALS_UI_MESSAGE_HANDLER_H_
diff --git a/chromium/chrome/browser/chromeos/net/network_diagnostics/BUILD.gn b/chromium/chrome/browser/ui/webui/internals/web_app/BUILD.gn
index c0f2d7b573f..70ca6d1bce8 100644
--- a/chromium/chrome/browser/chromeos/net/network_diagnostics/BUILD.gn
+++ b/chromium/chrome/browser/ui/webui/internals/web_app/BUILD.gn
@@ -4,8 +4,6 @@
import("//mojo/public/tools/bindings/mojom.gni")
-mojom("network_diagnostics_mojom") {
- sources = [ "network_diagnostics.mojom" ]
-
- deps = [ "//mojo/public/mojom/base" ]
+mojom("mojo_bindings") {
+ sources = [ "web_app_internals.mojom" ]
}
diff --git a/chromium/chrome/browser/ui/webui/internals/web_app/OWNERS b/chromium/chrome/browser/ui/webui/internals/web_app/OWNERS
new file mode 100644
index 00000000000..a74f1031167
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/internals/web_app/OWNERS
@@ -0,0 +1,4 @@
+file://chrome/browser/web_applications/OWNERS
+
+per-file *.mojom=set noparent
+per-file *.mojom=file://ipc/SECURITY_OWNERS
diff --git a/chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals.mojom b/chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals.mojom
new file mode 100644
index 00000000000..0a05fcafaca
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals.mojom
@@ -0,0 +1,30 @@
+// Copyright 2020 The Chromium 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 mojom.web_app_internals;
+
+struct WebApp {
+ // The web app's ID.
+ string id;
+
+ // The web app's name.
+ string name;
+
+ // Debugging info about the web app's internal state.
+ string debug_info;
+};
+
+// Provides access to browser side internal information about installed web apps
+// (also known as PWAs) for chrome://internals/web-app.
+interface WebAppInternalsPageHandler {
+ // Whether the BMO web app backend is enabled.
+ IsBmoEnabled() => (bool is_bmo_enabled);
+
+ // Returns details of all the installed web apps for the current profile.
+ GetWebApps() => (array<WebApp> web_app_list);
+
+ // Returns the prefs used for keeping track of non-user installed web apps.
+ GetExternallyInstalledWebAppPrefs() =>
+ (string externally_installed_web_app_prefs);
+};
diff --git a/chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.cc b/chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.cc
new file mode 100644
index 00000000000..79a536d5d9b
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.cc
@@ -0,0 +1,68 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <sstream>
+
+#include "chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.h"
+
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/web_applications/components/web_app_provider_base.h"
+#include "chrome/browser/web_applications/web_app.h"
+#include "chrome/browser/web_applications/web_app_registrar.h"
+#include "chrome/common/chrome_features.h"
+#include "chrome/common/pref_names.h"
+#include "chrome/grit/dev_ui_browser_resources.h"
+#include "components/prefs/pref_service.h"
+#include "content/public/browser/web_ui_data_source.h"
+
+WebAppInternalsPageHandlerImpl::WebAppInternalsPageHandlerImpl(Profile* profile)
+ : profile_(profile) {}
+
+WebAppInternalsPageHandlerImpl::~WebAppInternalsPageHandlerImpl() = default;
+
+void WebAppInternalsPageHandlerImpl::AddPageResources(
+ content::WebUIDataSource* source) {
+ source->AddResourcePath("web_app_internals.mojom-lite.js",
+ IDR_WEB_APP_INTERNALS_MOJOM_LITE_JS);
+ source->AddResourcePath("web_app_internals.js", IDR_WEB_APP_INTERNALS_JS);
+ source->AddResourcePath("web-app", IDR_WEB_APP_INTERNALS_HTML);
+}
+
+void WebAppInternalsPageHandlerImpl::IsBmoEnabled(
+ IsBmoEnabledCallback callback) {
+ std::move(callback).Run(
+ base::FeatureList::IsEnabled(features::kDesktopPWAsWithoutExtensions));
+}
+
+void WebAppInternalsPageHandlerImpl::GetWebApps(GetWebAppsCallback callback) {
+ auto* provider = web_app::WebAppProviderBase::GetProviderBase(profile_);
+ if (!provider)
+ std::move(callback).Run({});
+
+ web_app::AppRegistrar& registrar_base = provider->registrar();
+ web_app::WebAppRegistrar* registrar = registrar_base.AsWebAppRegistrar();
+ if (!registrar)
+ std::move(callback).Run({});
+
+ std::vector<mojom::web_app_internals::WebAppPtr> result;
+ for (const web_app::WebApp& web_app : registrar->AllApps()) {
+ mojom::web_app_internals::WebAppPtr info(
+ mojom::web_app_internals::WebApp::New());
+ info->name = web_app.name();
+ info->id = web_app.app_id();
+ std::stringstream ss;
+ ss << web_app;
+ info->debug_info = ss.str();
+ result.push_back(std::move(info));
+ }
+
+ std::move(callback).Run(std::move(result));
+}
+
+void WebAppInternalsPageHandlerImpl::GetExternallyInstalledWebAppPrefs(
+ GetExternallyInstalledWebAppPrefsCallback callback) {
+ std::stringstream ss;
+ ss << *profile_->GetPrefs()->GetDictionary(prefs::kWebAppsExtensionIDs);
+ std::move(callback).Run(ss.str());
+}
diff --git a/chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.h b/chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.h
new file mode 100644
index 00000000000..ac2d034f03d
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.h
@@ -0,0 +1,39 @@
+// Copyright 2020 The Chromium 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_INTERNALS_WEB_APP_WEB_APP_INTERNALS_PAGE_HANDLER_IMPL_H_
+#define CHROME_BROWSER_UI_WEBUI_INTERNALS_WEB_APP_WEB_APP_INTERNALS_PAGE_HANDLER_IMPL_H_
+
+#include "chrome/browser/ui/webui/internals/web_app/web_app_internals.mojom.h"
+
+class Profile;
+
+namespace content {
+class WebUIDataSource;
+}
+
+// Handles API requests from chrome://internals/web-app.
+class WebAppInternalsPageHandlerImpl
+ : public mojom::web_app_internals::WebAppInternalsPageHandler {
+ public:
+ explicit WebAppInternalsPageHandlerImpl(Profile* profile);
+ WebAppInternalsPageHandlerImpl(const WebAppInternalsPageHandlerImpl&) =
+ delete;
+ WebAppInternalsPageHandlerImpl& operator=(
+ const WebAppInternalsPageHandlerImpl&) = delete;
+ ~WebAppInternalsPageHandlerImpl() override;
+
+ static void AddPageResources(content::WebUIDataSource* source);
+
+ // mojom::web_app_internals::WebAppInternalsPageHandler:
+ void IsBmoEnabled(IsBmoEnabledCallback callback) override;
+ void GetWebApps(GetWebAppsCallback callback) override;
+ void GetExternallyInstalledWebAppPrefs(
+ GetExternallyInstalledWebAppPrefsCallback callback) override;
+
+ private:
+ Profile* profile_ = nullptr;
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_INTERNALS_WEB_APP_WEB_APP_INTERNALS_PAGE_HANDLER_IMPL_H_
diff --git a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc
index ec670f5dd01..f0f6eca30f7 100644
--- a/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc
+++ b/chromium/chrome/browser/ui/webui/interstitials/interstitial_ui.cc
@@ -21,6 +21,7 @@
#include "chrome/browser/safe_browsing/test_safe_browsing_blocking_page_quiet.h"
#include "chrome/browser/safe_browsing/ui_manager.h"
#include "chrome/browser/ssl/chrome_security_blocking_page_factory.h"
+#include "chrome/browser/ssl/insecure_form/insecure_form_controller_client.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/url_constants.h"
#include "components/captive_portal/core/buildflags.h"
@@ -29,6 +30,7 @@
#include "components/safe_browsing/core/db/database_manager.h"
#include "components/security_interstitials/content/bad_clock_blocking_page.h"
#include "components/security_interstitials/content/blocked_interception_blocking_page.h"
+#include "components/security_interstitials/content/insecure_form_blocking_page.h"
#include "components/security_interstitials/content/legacy_tls_blocking_page.h"
#include "components/security_interstitials/content/mitm_software_blocking_page.h"
#include "components/security_interstitials/content/origin_policy_ui.h"
@@ -51,6 +53,7 @@
#include "net/ssl/ssl_info.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "services/network/public/cpp/origin_policy.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/web_ui_util.h"
@@ -98,9 +101,8 @@ class InterstitialHTMLSource : public content::URLDataSource {
// content::URLDataSource:
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;
+ std::string GetContentSecurityPolicy(
+ const network::mojom::CSPDirectiveName directive) override;
void StartDataRequest(
const GURL& url,
const content::WebContents::Getter& wc_getter,
@@ -264,14 +266,27 @@ std::unique_ptr<LookalikeUrlBlockingPage> CreateLookalikeInterstitialPage(
content::WebContents* web_contents) {
GURL request_url("https://example.net");
GURL safe_url("https://example.com");
-
+ std::string url_param;
+ if (net::GetValueForKeyInQuery(web_contents->GetURL(), "no-safe-url",
+ &url_param)) {
+ safe_url = GURL();
+ }
return std::make_unique<LookalikeUrlBlockingPage>(
- web_contents, safe_url, ukm::kInvalidSourceId,
+ web_contents, safe_url, request_url, ukm::kInvalidSourceId,
LookalikeUrlMatchType::kNone,
std::make_unique<LookalikeUrlControllerClient>(web_contents, request_url,
safe_url));
}
+std::unique_ptr<security_interstitials::InsecureFormBlockingPage>
+CreateInsecureFormPage(content::WebContents* web_contents) {
+ GURL request_url("http://example.com");
+ return std::make_unique<security_interstitials::InsecureFormBlockingPage>(
+ web_contents, request_url,
+ std::make_unique<InsecureFormControllerClient>(web_contents,
+ request_url));
+}
+
std::unique_ptr<safe_browsing::SafeBrowsingBlockingPage>
CreateSafeBrowsingBlockingPage(content::WebContents* web_contents) {
safe_browsing::SBThreatType threat_type =
@@ -451,17 +466,18 @@ std::string InterstitialHTMLSource::GetSource() {
return chrome::kChromeUIInterstitialHost;
}
-std::string InterstitialHTMLSource::GetContentSecurityPolicyScriptSrc() {
- // 'unsafe-inline' is added to script-src.
- return "script-src chrome://resources 'self' 'unsafe-inline';";
-}
-
-std::string InterstitialHTMLSource::GetContentSecurityPolicyStyleSrc() {
- return "style-src 'self' 'unsafe-inline';";
-}
+std::string InterstitialHTMLSource::GetContentSecurityPolicy(
+ const network::mojom::CSPDirectiveName directive) {
+ if (directive == network::mojom::CSPDirectiveName::ScriptSrc) {
+ // 'unsafe-inline' is added to script-src.
+ return "script-src chrome://resources 'self' 'unsafe-inline';";
+ } else if (directive == network::mojom::CSPDirectiveName::StyleSrc) {
+ return "style-src 'self' 'unsafe-inline';";
+ } else if (directive == network::mojom::CSPDirectiveName::ImgSrc) {
+ return "img-src data:;";
+ }
-std::string InterstitialHTMLSource::GetContentSecurityPolicyImgSrc() {
- return "img-src data:;";
+ return content::URLDataSource::GetContentSecurityPolicy(directive);
}
void InterstitialHTMLSource::StartDataRequest(
@@ -506,6 +522,8 @@ void InterstitialHTMLSource::StartDataRequest(
#endif
} else if (path_without_query == "/origin_policy") {
interstitial_delegate = CreateOriginPolicyInterstitialPage(web_contents);
+ } else if (path_without_query == "/insecure_form") {
+ interstitial_delegate = CreateInsecureFormPage(web_contents);
}
if (path_without_query == "/quietsafebrowsing") {
diff --git a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals.mojom b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals.mojom
index 061c1e82179..4b4101df90b 100644
--- a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals.mojom
+++ b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals.mojom
@@ -60,10 +60,10 @@ interface InterventionsInternalsPageHandler {
// Inject the client side page object.
SetClientPage(pending_remote<InterventionsInternalsPage> page);
- // Change the status of ignoring blacklist to |ignored|. |ignored| will
- // indicate whether the blacklist decision would be ignored when deciding if a
+ // Change the status of ignoring blocklist to |ignored|. |ignored| will
+ // indicate whether the blocklist decision would be ignored when deciding if a
// preview should be shown or not.
- SetIgnorePreviewsBlacklistDecision(bool ignored);
+ SetIgnorePreviewsBlocklistDecision(bool ignored);
};
interface InterventionsInternalsPage {
@@ -72,20 +72,20 @@ interface InterventionsInternalsPage {
// publishes it on the javscript side.
LogNewMessage(MessageLog log);
- // Notify the page that |host| has been blacklisted at |time|. The method is
+ // Notify the page that |host| has been blocklisted at |time|. The method is
// called by InterventionsInternalsPageHandler when PreviewsUIService receives
- // new blacklisted host.
- OnBlacklistedHost(string host, int64 time);
+ // new blocklisted host.
+ OnBlocklistedHost(string host, int64 time);
- // Notify the page that user blacklisted status has changed to |blacklisted|.
+ // Notify the page that user blocklisted status has changed to |blocklisted|.
// The method is called by InterventionsInternalsPageHandler when user's
- // blacklist status changes.
- OnUserBlacklistedStatusChange(bool blacklisted);
+ // blocklist status changes.
+ OnUserBlocklistedStatusChange(bool blocklisted);
- // Notify the page that the blacklist is cleared at |time|. The method is
+ // Notify the page that the blocklist is cleared at |time|. The method is
// called by InterventionsInternalsPageHandler when PreviewsUIService clears
- // the blacklist.
- OnBlacklistCleared(int64 time);
+ // the blocklist.
+ OnBlocklistCleared(int64 time);
// Notify the page on the new estimated effective connection type is |type|.
// Also reports the session's maximum intervention effective connection type
@@ -94,8 +94,8 @@ interface InterventionsInternalsPage {
// changes.
UpdateEffectiveConnectionType(string type, string max_intervention_type);
- // Notify the page on whether the blacklist decision is considered or ignored.
+ // Notify the page on whether the blocklist decision is considered or ignored.
// This method is called by InterventionsInternalsPageHandler when the status
- // of ignore blacklist decision is updated to |ignored|.
- OnIgnoreBlacklistDecisionStatusChanged(bool ignored);
+ // of ignore blocklist decision is updated to |ignored|.
+ OnIgnoreBlocklistDecisionStatusChanged(bool ignored);
};
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 a956bd2e948..fbce5852614 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
@@ -62,7 +62,7 @@ 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";
+const char kIgnorePreviewsBlocklistFlagHtmlId[] = "ignore-previews-blocklist";
const char kDataSaverAltConfigHtmlId[] =
"data-reduction-proxy-server-experiment";
@@ -76,8 +76,8 @@ 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[] =
- "chrome://flags/#ignore-previews-blacklist";
+const char kIgnorePreviewsBlocklistLink[] =
+ "chrome://flags/#ignore-previews-blocklist";
const char kDataSaverAltConfigLink[] =
"chrome://flags/#enable-data-reduction-proxy-server-experiment";
@@ -184,35 +184,35 @@ void InterventionsInternalsPageHandler::OnNewMessageLogAdded(
page_->LogNewMessage(std::move(mojo_message_ptr));
}
-void InterventionsInternalsPageHandler::SetIgnorePreviewsBlacklistDecision(
+void InterventionsInternalsPageHandler::SetIgnorePreviewsBlocklistDecision(
bool ignored) {
- previews_ui_service_->SetIgnorePreviewsBlacklistDecision(ignored);
+ previews_ui_service_->SetIgnorePreviewsBlocklistDecision(ignored);
}
void InterventionsInternalsPageHandler::OnLastObserverRemove() {
- // Reset the status of ignoring PreviewsBlackList decisions to default value.
- previews_ui_service_->SetIgnorePreviewsBlacklistDecision(
- previews::switches::ShouldIgnorePreviewsBlacklist());
+ // Reset the status of ignoring PreviewsBlockList decisions to default value.
+ previews_ui_service_->SetIgnorePreviewsBlocklistDecision(
+ previews::switches::ShouldIgnorePreviewsBlocklist());
}
-void InterventionsInternalsPageHandler::OnIgnoreBlacklistDecisionStatusChanged(
+void InterventionsInternalsPageHandler::OnIgnoreBlocklistDecisionStatusChanged(
bool ignored) {
- page_->OnIgnoreBlacklistDecisionStatusChanged(ignored);
+ page_->OnIgnoreBlocklistDecisionStatusChanged(ignored);
}
-void InterventionsInternalsPageHandler::OnNewBlacklistedHost(
+void InterventionsInternalsPageHandler::OnNewBlocklistedHost(
const std::string& host,
base::Time time) {
- page_->OnBlacklistedHost(host, time.ToJavaTime());
+ page_->OnBlocklistedHost(host, time.ToJavaTime());
}
-void InterventionsInternalsPageHandler::OnUserBlacklistedStatusChange(
- bool blacklisted) {
- page_->OnUserBlacklistedStatusChange(blacklisted);
+void InterventionsInternalsPageHandler::OnUserBlocklistedStatusChange(
+ bool blocklisted) {
+ page_->OnUserBlocklistedStatusChange(blocklisted);
}
-void InterventionsInternalsPageHandler::OnBlacklistCleared(base::Time time) {
- page_->OnBlacklistCleared(time.ToJavaTime());
+void InterventionsInternalsPageHandler::OnBlocklistCleared(base::Time time) {
+ page_->OnBlocklistCleared(time.ToJavaTime());
}
void InterventionsInternalsPageHandler::GetPreviewsEnabled(
@@ -317,14 +317,14 @@ void InterventionsInternalsPageHandler::GetPreviewsFlagsDetails(
ect_status->htmlId = kEctFlagHtmlId;
flags.push_back(std::move(ect_status));
- auto ignore_previews_blacklist = mojom::PreviewsFlag::New();
- ignore_previews_blacklist->description =
- flag_descriptions::kIgnorePreviewsBlacklistName;
- ignore_previews_blacklist->link = kIgnorePreviewsBlacklistLink;
- ignore_previews_blacklist->value =
- GetEnabledStateForSwitch(previews::switches::kIgnorePreviewsBlacklist);
- ignore_previews_blacklist->htmlId = kIgnorePreviewsBlacklistFlagHtmlId;
- flags.push_back(std::move(ignore_previews_blacklist));
+ auto ignore_previews_blocklist = mojom::PreviewsFlag::New();
+ ignore_previews_blocklist->description =
+ flag_descriptions::kIgnorePreviewsBlocklistName;
+ ignore_previews_blocklist->link = kIgnorePreviewsBlocklistLink;
+ ignore_previews_blocklist->value =
+ GetEnabledStateForSwitch(previews::switches::kIgnorePreviewsBlocklist);
+ ignore_previews_blocklist->htmlId = kIgnorePreviewsBlocklistFlagHtmlId;
+ flags.push_back(std::move(ignore_previews_blocklist));
auto alt_config_status = mojom::PreviewsFlag::New();
alt_config_status->description =
diff --git a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.h b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.h
index b892a1efe74..c47656ccd0e 100644
--- a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.h
+++ b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.h
@@ -37,15 +37,15 @@ class InterventionsInternalsPageHandler
GetPreviewsFlagsDetailsCallback callback) override;
void SetClientPage(
mojo::PendingRemote<mojom::InterventionsInternalsPage> page) override;
- void SetIgnorePreviewsBlacklistDecision(bool ignore) override;
+ void SetIgnorePreviewsBlocklistDecision(bool ignore) override;
// previews::PreviewsLoggerObserver:
void OnNewMessageLogAdded(
const previews::PreviewsLogger::MessageLog& message) override;
- void OnNewBlacklistedHost(const std::string& host, base::Time time) override;
- void OnUserBlacklistedStatusChange(bool blacklisted) override;
- void OnBlacklistCleared(base::Time time) override;
- void OnIgnoreBlacklistDecisionStatusChanged(bool ignored) override;
+ void OnNewBlocklistedHost(const std::string& host, base::Time time) override;
+ void OnUserBlocklistedStatusChange(bool blocklisted) override;
+ void OnBlocklistCleared(base::Time time) override;
+ void OnIgnoreBlocklistDecisionStatusChanged(bool ignored) override;
void OnLastObserverRemove() override;
private:
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 b5a0ddeb2ff..f61271fc5fd 100644
--- a/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc
@@ -30,7 +30,7 @@
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
-#include "components/blacklist/opt_out_blacklist/opt_out_blacklist_data.h"
+#include "components/blocklist/opt_out_blocklist/opt_out_blocklist_data.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_switches.h"
#include "components/previews/content/previews_decider_impl.h"
#include "components/previews/content/previews_ui_service.h"
@@ -74,8 +74,8 @@ constexpr char kResourceLoadingHintsFlagHtmlId[] =
constexpr char kDeferAllScriptFlagHtmlId[] = "defer-all-script-flag";
constexpr char kNoScriptFlagHtmlId[] = "noscript-flag";
constexpr char kEctFlagHtmlId[] = "ect-flag";
-constexpr char kIgnorePreviewsBlacklistFlagHtmlId[] =
- "ignore-previews-blacklist";
+constexpr char kIgnorePreviewsBlocklistFlagHtmlId[] =
+ "ignore-previews-blocklist";
constexpr char kDataSaverAltConfigHtmlId[] =
"data-reduction-proxy-server-experiment";
@@ -89,8 +89,8 @@ constexpr char kDeferAllScriptFlagLink[] =
constexpr char kNoScriptFlagLink[] = "chrome://flags/#enable-noscript-previews";
constexpr char kEctFlagLink[] =
"chrome://flags/#force-effective-connection-type";
-constexpr char kIgnorePreviewsBlacklistLink[] =
- "chrome://flags/#ignore-previews-blacklist";
+constexpr char kIgnorePreviewsBlocklistLink[] =
+ "chrome://flags/#ignore-previews-blocklist";
constexpr char kDataSaverAltConfigLink[] =
"chrome://flags/#enable-data-reduction-proxy-server-experiment";
@@ -141,23 +141,23 @@ class TestInterventionsInternalsPage
public:
TestInterventionsInternalsPage(
mojo::PendingReceiver<mojom::InterventionsInternalsPage> receiver)
- : receiver_(this, std::move(receiver)), blacklist_ignored_(false) {}
+ : receiver_(this, std::move(receiver)), blocklist_ignored_(false) {}
- ~TestInterventionsInternalsPage() override {}
+ ~TestInterventionsInternalsPage() override = default;
// mojom::InterventionsInternalsPage:
void LogNewMessage(mojom::MessageLogPtr message) override {
message_ = std::make_unique<mojom::MessageLogPtr>(std::move(message));
}
- void OnBlacklistedHost(const std::string& host, int64_t time) override {
- host_blacklisted_ = host;
- host_blacklisted_time_ = time;
+ void OnBlocklistedHost(const std::string& host, int64_t time) override {
+ host_blocklisted_ = host;
+ host_blocklisted_time_ = time;
}
- void OnUserBlacklistedStatusChange(bool blacklisted) override {
- user_blacklisted_ = blacklisted;
+ void OnUserBlocklistedStatusChange(bool blocklisted) override {
+ user_blocklisted_ = blocklisted;
}
- void OnBlacklistCleared(int64_t time) override {
- blacklist_cleared_time_ = time;
+ void OnBlocklistCleared(int64_t time) override {
+ blocklist_cleared_time_ = time;
}
void UpdateEffectiveConnectionType(
const std::string& type,
@@ -166,21 +166,21 @@ class TestInterventionsInternalsPage
// TODO(thanhdle): Add integration test to test behavior of the pipeline end
// to end. crbug.com/777936
}
- void OnIgnoreBlacklistDecisionStatusChanged(bool ignored) override {
- blacklist_ignored_ = ignored;
+ void OnIgnoreBlocklistDecisionStatusChanged(bool ignored) override {
+ blocklist_ignored_ = ignored;
}
// Expose passed in message in LogNewMessage for testing.
mojom::MessageLogPtr* message() const { return message_.get(); }
- // Expose passed in blacklist events info for testing.
- std::string host_blacklisted() const { return host_blacklisted_; }
- int64_t host_blacklisted_time() const { return host_blacklisted_time_; }
- bool user_blacklisted() const { return user_blacklisted_; }
- int64_t blacklist_cleared_time() const { return blacklist_cleared_time_; }
+ // Expose passed in blocklist events info for testing.
+ std::string host_blocklisted() const { return host_blocklisted_; }
+ int64_t host_blocklisted_time() const { return host_blocklisted_time_; }
+ bool user_blocklisted() const { return user_blocklisted_; }
+ int64_t blocklist_cleared_time() const { return blocklist_cleared_time_; }
- // Expose the passed in blacklist ignore status for testing.
- bool blacklist_ignored() const { return blacklist_ignored_; }
+ // Expose the passed in blocklist ignore status for testing.
+ bool blocklist_ignored() const { return blocklist_ignored_; }
private:
mojo::Receiver<mojom::InterventionsInternalsPage> receiver_;
@@ -188,14 +188,14 @@ class TestInterventionsInternalsPage
// The MessageLogPtr passed in LogNewMessage method.
std::unique_ptr<mojom::MessageLogPtr> message_;
- // Received blacklist events info.
- std::string host_blacklisted_;
- int64_t host_blacklisted_time_;
- int64_t user_blacklisted_;
- int64_t blacklist_cleared_time_;
+ // Received blocklist events info.
+ std::string host_blocklisted_;
+ int64_t host_blocklisted_time_;
+ int64_t user_blocklisted_;
+ int64_t blocklist_cleared_time_;
- // Whether to ignore previews blacklist decisions.
- bool blacklist_ignored_;
+ // Whether to ignore previews blocklist decisions.
+ bool blocklist_ignored_;
};
// Mock class to test interaction between the PageHandler and the
@@ -224,10 +224,10 @@ class TestPreviewsDeciderImpl : public previews::PreviewsDeciderImpl {
// previews::PreviewsDeciderImpl:
void Initialize(
previews::PreviewsUIService* previews_ui_service,
- std::unique_ptr<blacklist::OptOutStore> previews_opt_out_store,
+ std::unique_ptr<blocklist::OptOutStore> previews_opt_out_store,
std::unique_ptr<previews::PreviewsOptimizationGuide> previews_opt_guide,
const previews::PreviewsIsEnabledCallback& is_enabled_callback,
- blacklist::BlacklistData::AllowedTypesAndVersions allowed_previews)
+ blocklist::BlocklistData::AllowedTypesAndVersions allowed_previews)
override {}
};
@@ -244,22 +244,22 @@ class TestPreviewsUIService : public previews::PreviewsUIService {
nullptr, /* previews_opt_guide */
base::BindRepeating(&MockedPreviewsIsEnabled),
std::move(logger),
- blacklist::BlacklistData::AllowedTypesAndVersions(),
+ blocklist::BlocklistData::AllowedTypesAndVersions(),
test_network_quality_tracker),
- blacklist_ignored_(false) {}
- ~TestPreviewsUIService() override {}
+ blocklist_ignored_(false) {}
+ ~TestPreviewsUIService() override = default;
// previews::PreviewsUIService:
- void SetIgnorePreviewsBlacklistDecision(bool ignored) override {
- blacklist_ignored_ = ignored;
+ void SetIgnorePreviewsBlocklistDecision(bool ignored) override {
+ blocklist_ignored_ = ignored;
}
- // Exposed blacklist ignored state.
- bool blacklist_ignored() const { return blacklist_ignored_; }
+ // Exposed blocklist ignored state.
+ bool blocklist_ignored() const { return blocklist_ignored_; }
private:
- // Whether the blacklist decisions are ignored or not.
- bool blacklist_ignored_;
+ // Whether the blocklist decisions are ignored or not.
+ bool blocklist_ignored_;
};
class InterventionsInternalsPageHandlerTest : public testing::Test {
@@ -534,33 +534,33 @@ TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsEctForceFieldtrialValue) {
}
TEST_F(InterventionsInternalsPageHandlerTest,
- GetFlagsIgnorePreviewsBlacklistDisabledValue) {
+ GetFlagsIgnorePreviewsBlocklistDisabledValue) {
// Disabled by default.
page_handler_->GetPreviewsFlagsDetails(
base::BindOnce(&MockGetPreviewsFlagsCallback));
- auto ignore_previews_blacklist =
- passed_in_flags.find(kIgnorePreviewsBlacklistFlagHtmlId);
+ auto ignore_previews_blocklist =
+ passed_in_flags.find(kIgnorePreviewsBlocklistFlagHtmlId);
- ASSERT_NE(passed_in_flags.end(), ignore_previews_blacklist);
- EXPECT_EQ(flag_descriptions::kIgnorePreviewsBlacklistName,
- ignore_previews_blacklist->second->description);
- EXPECT_EQ(kDisabledFlagValue, ignore_previews_blacklist->second->value);
- EXPECT_EQ(kIgnorePreviewsBlacklistLink,
- ignore_previews_blacklist->second->link);
+ ASSERT_NE(passed_in_flags.end(), ignore_previews_blocklist);
+ EXPECT_EQ(flag_descriptions::kIgnorePreviewsBlocklistName,
+ ignore_previews_blocklist->second->description);
+ EXPECT_EQ(kDisabledFlagValue, ignore_previews_blocklist->second->value);
+ EXPECT_EQ(kIgnorePreviewsBlocklistLink,
+ ignore_previews_blocklist->second->link);
}
TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsNoScriptDisabledValue) {
page_handler_->GetPreviewsFlagsDetails(
base::BindOnce(&MockGetPreviewsFlagsCallback));
- auto ignore_previews_blacklist =
- passed_in_flags.find(kIgnorePreviewsBlacklistFlagHtmlId);
+ auto ignore_previews_blocklist =
+ passed_in_flags.find(kIgnorePreviewsBlocklistFlagHtmlId);
- ASSERT_NE(passed_in_flags.end(), ignore_previews_blacklist);
- EXPECT_EQ(flag_descriptions::kIgnorePreviewsBlacklistName,
- ignore_previews_blacklist->second->description);
- EXPECT_EQ(kDisabledFlagValue, ignore_previews_blacklist->second->value);
- EXPECT_EQ(kIgnorePreviewsBlacklistLink,
- ignore_previews_blacklist->second->link);
+ ASSERT_NE(passed_in_flags.end(), ignore_previews_blocklist);
+ EXPECT_EQ(flag_descriptions::kIgnorePreviewsBlocklistName,
+ ignore_previews_blocklist->second->description);
+ EXPECT_EQ(kDisabledFlagValue, ignore_previews_blocklist->second->value);
+ EXPECT_EQ(kIgnorePreviewsBlocklistLink,
+ ignore_previews_blocklist->second->link);
}
TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsNoScriptDefaultValue) {
@@ -844,7 +844,7 @@ TEST_F(InterventionsInternalsPageHandlerTest, ObserverIsRemovedWhenDestroyed) {
EXPECT_TRUE(logger_->RemovedObserverIsCalled());
}
-TEST_F(InterventionsInternalsPageHandlerTest, OnNewBlacklistedHostPostToPage) {
+TEST_F(InterventionsInternalsPageHandlerTest, OnNewBlocklistedHostPostToPage) {
const std::string hosts[] = {
"example_0.com",
"example_1.com",
@@ -853,75 +853,75 @@ TEST_F(InterventionsInternalsPageHandlerTest, OnNewBlacklistedHostPostToPage) {
for (auto expected_host : hosts) {
base::Time expected_time = base::Time::Now();
- page_handler_->OnNewBlacklistedHost(expected_host, expected_time);
+ page_handler_->OnNewBlocklistedHost(expected_host, expected_time);
base::RunLoop().RunUntilIdle();
- EXPECT_EQ(expected_host, page_->host_blacklisted());
- EXPECT_EQ(expected_time.ToJavaTime(), page_->host_blacklisted_time());
+ EXPECT_EQ(expected_host, page_->host_blocklisted());
+ EXPECT_EQ(expected_time.ToJavaTime(), page_->host_blocklisted_time());
}
}
-TEST_F(InterventionsInternalsPageHandlerTest, OnUserBlacklistedPostToPage) {
- page_handler_->OnUserBlacklistedStatusChange(true /* blacklisted */);
+TEST_F(InterventionsInternalsPageHandlerTest, OnUserBlocklistedPostToPage) {
+ page_handler_->OnUserBlocklistedStatusChange(true /* blocklisted */);
base::RunLoop().RunUntilIdle();
- EXPECT_TRUE(page_->user_blacklisted());
+ EXPECT_TRUE(page_->user_blocklisted());
- page_handler_->OnUserBlacklistedStatusChange(false /* blacklisted */);
+ page_handler_->OnUserBlocklistedStatusChange(false /* blocklisted */);
base::RunLoop().RunUntilIdle();
- EXPECT_FALSE(page_->user_blacklisted());
+ EXPECT_FALSE(page_->user_blocklisted());
}
-TEST_F(InterventionsInternalsPageHandlerTest, OnBlacklistClearedPostToPage) {
+TEST_F(InterventionsInternalsPageHandlerTest, OnBlocklistClearedPostToPage) {
base::Time times[] = {
base::Time::FromJsTime(-413696806000), // Nov 21 1956 20:13:14 UTC
base::Time::FromJsTime(758620800000), // Jan 15 1994 08:00:00 UTC
base::Time::FromJsTime(1581696550000), // Feb 14 2020 16:09:10 UTC
};
for (auto expected_time : times) {
- page_handler_->OnBlacklistCleared(expected_time);
+ page_handler_->OnBlocklistCleared(expected_time);
base::RunLoop().RunUntilIdle();
- EXPECT_EQ(expected_time.ToJavaTime(), page_->blacklist_cleared_time());
+ EXPECT_EQ(expected_time.ToJavaTime(), page_->blocklist_cleared_time());
}
}
TEST_F(InterventionsInternalsPageHandlerTest,
- SetIgnorePreviewsBlacklistDecisionCallsUIServiceCorrectly) {
- page_handler_->SetIgnorePreviewsBlacklistDecision(true /* ignored */);
- EXPECT_TRUE(previews_ui_service_->blacklist_ignored());
+ SetIgnorePreviewsBlocklistDecisionCallsUIServiceCorrectly) {
+ page_handler_->SetIgnorePreviewsBlocklistDecision(true /* ignored */);
+ EXPECT_TRUE(previews_ui_service_->blocklist_ignored());
- page_handler_->SetIgnorePreviewsBlacklistDecision(false /* ignored */);
- EXPECT_FALSE(previews_ui_service_->blacklist_ignored());
+ page_handler_->SetIgnorePreviewsBlocklistDecision(false /* ignored */);
+ EXPECT_FALSE(previews_ui_service_->blocklist_ignored());
}
TEST_F(InterventionsInternalsPageHandlerTest,
- PageUpdateOnBlacklistIgnoredChange) {
- page_handler_->OnIgnoreBlacklistDecisionStatusChanged(true /* ignored */);
+ PageUpdateOnBlocklistIgnoredChange) {
+ page_handler_->OnIgnoreBlocklistDecisionStatusChanged(true /* ignored */);
base::RunLoop().RunUntilIdle();
- EXPECT_TRUE(page_->blacklist_ignored());
+ EXPECT_TRUE(page_->blocklist_ignored());
- page_handler_->OnIgnoreBlacklistDecisionStatusChanged(false /* ignored */);
+ page_handler_->OnIgnoreBlocklistDecisionStatusChanged(false /* ignored */);
base::RunLoop().RunUntilIdle();
- EXPECT_FALSE(page_->blacklist_ignored());
+ EXPECT_FALSE(page_->blocklist_ignored());
}
TEST_F(InterventionsInternalsPageHandlerTest,
- IgnoreBlacklistReversedOnLastObserverRemovedCalled) {
- ASSERT_FALSE(previews::switches::ShouldIgnorePreviewsBlacklist());
+ IgnoreBlocklistReversedOnLastObserverRemovedCalled) {
+ ASSERT_FALSE(previews::switches::ShouldIgnorePreviewsBlocklist());
page_handler_->OnLastObserverRemove();
base::RunLoop().RunUntilIdle();
- EXPECT_FALSE(page_->blacklist_ignored());
+ EXPECT_FALSE(page_->blocklist_ignored());
}
TEST_F(InterventionsInternalsPageHandlerTest,
- IgnoreBlacklistReversedOnLastObserverRemovedCalledIgnoreViaFlag) {
+ IgnoreBlocklistReversedOnLastObserverRemovedCalledIgnoreViaFlag) {
base::test::ScopedCommandLine scoped_command_line;
base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine();
- command_line->AppendSwitch(previews::switches::kIgnorePreviewsBlacklist);
- ASSERT_TRUE(previews::switches::ShouldIgnorePreviewsBlacklist());
+ command_line->AppendSwitch(previews::switches::kIgnorePreviewsBlocklist);
+ ASSERT_TRUE(previews::switches::ShouldIgnorePreviewsBlocklist());
page_handler_->OnLastObserverRemove();
base::RunLoop().RunUntilIdle();
- EXPECT_FALSE(page_->blacklist_ignored());
+ EXPECT_FALSE(page_->blocklist_ignored());
}
} // namespace
diff --git a/chromium/chrome/browser/ui/webui/invalidations_ui.cc b/chromium/chrome/browser/ui/webui/invalidations_ui.cc
index 092f8425c2e..4846cedb319 100644
--- a/chromium/chrome/browser/ui/webui/invalidations_ui.cc
+++ b/chromium/chrome/browser/ui/webui/invalidations_ui.cc
@@ -13,13 +13,15 @@
#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/network/public/mojom/content_security_policy.mojom.h"
content::WebUIDataSource* CreateInvalidationsHTMLSource() {
// This is done once per opening of the page
// This method does not fire when refreshing the page
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIInvalidationsHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
source->AddResourcePath("about_invalidations.js", IDR_ABOUT_INVALIDATIONS_JS);
source->SetDefaultResource(IDR_ABOUT_INVALIDATIONS_HTML);
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 69169417236..40ac82d0f33 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
@@ -351,7 +351,12 @@ class LocalDiscoveryUITest : public WebUIBrowserTest {
// a DCHECK during TestServiceDiscoveryClient construction.
media_router::DualMediaSinkService::SetInstanceForTest(
new media_router::NoopDualMediaSinkService());
- feature_list_.InitAndDisableFeature(media_router::kDialMediaRouteProvider);
+ // The Media Route Providers must be disabled because they rely on the
+ // presence of a valid DualMediaSinkService.
+ // TODO(crbug.com/1028753): Enable the Media Route Provider features.
+ feature_list_.InitWithFeatures(
+ {}, /* disabled_features */ {media_router::kDialMediaRouteProvider,
+ media_router::kCastMediaRouteProvider});
WebUIBrowserTest::SetUp();
}
diff --git a/chromium/chrome/browser/ui/webui/management_ui.cc b/chromium/chrome/browser/ui/webui/management_ui.cc
index 4254c9ddf6b..17da74ee390 100644
--- a/chromium/chrome/browser/ui/webui/management_ui.cc
+++ b/chromium/chrome/browser/ui/webui/management_ui.cc
@@ -59,6 +59,8 @@ content::WebUIDataSource* CreateManagementUIHtmlSource(Profile* profile) {
IDS_MANAGEMENT_REPORT_DEVICE_NETWORK_INTERFACES},
{kManagementReportUsers, IDS_MANAGEMENT_REPORT_DEVICE_USERS},
{kManagementReportCrashReports, IDS_MANAGEMENT_REPORT_DEVICE_CRASH_REPORTS},
+ {kManagementReportAppInfoAndActivity,
+ IDS_MANAGEMENT_REPORT_APP_INFO_AND_ACTIVITY},
{kManagementPrinting, IDS_MANAGEMENT_REPORT_PRINTING},
{kManagementCrostini, IDS_MANAGEMENT_CROSTINI},
{kManagementCrostiniContainerConfiguration,
@@ -95,17 +97,21 @@ content::WebUIDataSource* CreateManagementUIHtmlSource(Profile* profile) {
{kManagementExtensionReportUserBrowsingData,
IDS_MANAGEMENT_EXTENSION_REPORT_USER_BROWSING_DATA},
{kThreatProtectionTitle, IDS_MANAGEMENT_THREAT_PROTECTION},
- {kManagementDataLossPreventionName,
- IDS_MANAGEMENT_DATA_LOSS_PREVENTION_NAME},
- {kManagementDataLossPreventionPermissions,
- IDS_MANAGEMENT_DATA_LOSS_PREVENTION_PERMISSIONS},
- {kManagementMalwareScanningName, IDS_MANAGEMENT_MALWARE_SCANNING_NAME},
- {kManagementMalwareScanningPermissions,
- IDS_MANAGEMENT_MALWARE_SCANNING_PERMISSIONS},
- {kManagementEnterpriseReportingName,
- IDS_MANAGEMENT_ENTERPRISE_REPORTING_NAME},
- {kManagementEnterpriseReportingPermissions,
- IDS_MANAGEMENT_ENTERPRISE_REPORTING_PERMISSIONS},
+ {"connectorEvent", IDS_MANAGEMENT_CONNECTORS_EVENT},
+ {"connectorVisibleData", IDS_MANAGEMENT_CONNECTORS_VISIBLE_DATA},
+ {kManagementEnterpriseReportingEvent,
+ IDS_MANAGEMENT_ENTERPRISE_REPORTING_EVENT},
+ {kManagementEnterpriseReportingVisibleData,
+ IDS_MANAGEMENT_ENTERPRISE_REPORTING_VISIBLE_DATA},
+ {kManagementOnFileAttachedEvent, IDS_MANAGEMENT_FILE_ATTACHED_EVENT},
+ {kManagementOnFileAttachedVisibleData,
+ IDS_MANAGEMENT_FILE_ATTACHED_VISIBLE_DATA},
+ {kManagementOnFileDownloadedEvent, IDS_MANAGEMENT_FILE_DOWNLOADED_EVENT},
+ {kManagementOnFileDownloadedVisibleData,
+ IDS_MANAGEMENT_FILE_DOWNLOADED_VISIBLE_DATA},
+ {kManagementOnBulkDataEntryEvent, IDS_MANAGEMENT_TEXT_ENTERED_EVENT},
+ {kManagementOnBulkDataEntryVisibleData,
+ IDS_MANAGEMENT_TEXT_ENTERED_VISIBLE_DATA},
};
AddLocalizedStringsBulk(source, kLocalizedStrings);
diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler.cc b/chromium/chrome/browser/ui/webui/management_ui_handler.cc
index e8dff0d2dc4..f5aeff7fa6b 100644
--- a/chromium/chrome/browser/ui/webui/management_ui_handler.cc
+++ b/chromium/chrome/browser/ui/webui/management_ui_handler.cc
@@ -113,10 +113,21 @@ const char kManagementDataLossPreventionPermissions[] =
const char kManagementMalwareScanningName[] = "managementMalwareScanningName";
const char kManagementMalwareScanningPermissions[] =
"managementMalwareScanningPermissions";
-const char kManagementEnterpriseReportingName[] =
- "managementEnterpriseReportingName";
-const char kManagementEnterpriseReportingPermissions[] =
- "managementEnterpriseReportingPermissions";
+const char kManagementEnterpriseReportingEvent[] =
+ "managementEnterpriseReportingEvent";
+const char kManagementEnterpriseReportingVisibleData[] =
+ "managementEnterpriseReportingVisibleData";
+
+const char kManagementOnFileAttachedEvent[] = "managementOnFileAttachedEvent";
+const char kManagementOnFileAttachedVisibleData[] =
+ "managementOnFileAttachedVisibleData";
+const char kManagementOnFileDownloadedEvent[] =
+ "managementOnFileDownloadedEvent";
+const char kManagementOnFileDownloadedVisibleData[] =
+ "managementOnFileDownloadedVisibleData";
+const char kManagementOnBulkDataEntryEvent[] = "managementOnBulkDataEntryEvent";
+const char kManagementOnBulkDataEntryVisibleData[] =
+ "managementOnBulkDataEntryVisibleData";
const char kReportingTypeDevice[] = "device";
const char kReportingTypeExtensions[] = "extensions";
@@ -140,6 +151,8 @@ const char kManagementReportNetworkInterfaces[] =
"managementReportNetworkInterfaces";
const char kManagementReportUsers[] = "managementReportUsers";
const char kManagementReportCrashReports[] = "managementReportCrashReports";
+const char kManagementReportAppInfoAndActivity[] =
+ "managementReportAppInfoAndActivity";
const char kManagementReportExtensions[] = "managementReportExtensions";
const char kManagementReportAndroidApplications[] =
"managementReportAndroidApplications";
@@ -186,6 +199,7 @@ enum class DeviceReportingType {
kDeviceStatistics,
kDevice,
kCrashReport,
+ kAppInfoAndActivity,
kLogs,
kPrint,
kCrostini,
@@ -208,6 +222,8 @@ std::string ToJSDeviceReportingType(const DeviceReportingType& type) {
return "device";
case DeviceReportingType::kCrashReport:
return "crash report";
+ case DeviceReportingType::kAppInfoAndActivity:
+ return "app info and activity";
case DeviceReportingType::kLogs:
return "logs";
case DeviceReportingType::kPrint:
@@ -538,6 +554,11 @@ void ManagementUIHandler::AddDeviceReportingInfo(
AddDeviceReportingElement(report_sources, kManagementReportCrashReports,
DeviceReportingType::kCrashReport);
}
+ if (collector->ShouldReportAppInfoAndActivity()) {
+ AddDeviceReportingElement(report_sources,
+ kManagementReportAppInfoAndActivity,
+ DeviceReportingType::kAppInfoAndActivity);
+ }
if (uploader->upload_enabled()) {
AddDeviceReportingElement(report_sources, kManagementLogUploadEnabled,
DeviceReportingType::kLogs);
@@ -578,8 +599,10 @@ void ManagementUIHandler::AddDeviceReportingInfo(
chromeos::NetworkHandler* network_handler = chromeos::NetworkHandler::Get();
base::Value proxy_settings(base::Value::Type::DICTIONARY);
- // |ui_proxy_config_service| may be missing in tests.
- if (network_handler->has_ui_proxy_config_service()) {
+ // |ui_proxy_config_service| may be missing in tests. If the device is offline
+ // (no network connected) the |DefaultNetwork| is null.
+ if (network_handler->has_ui_proxy_config_service() &&
+ network_handler->network_state_handler()->DefaultNetwork()) {
// Check if proxy is enforced by user policy, a forced install extension or
// ONC policies. This will only read managed settings.
network_handler->ui_proxy_config_service()->MergeEnforcedProxyConfig(
@@ -682,41 +705,44 @@ base::Value ManagementUIHandler::GetThreatProtectionInfo(
const policy::PolicyService* policy_service = GetPolicyService();
const auto& chrome_policies = policy_service->GetPolicies(
policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string()));
- // CheckContentCompliance is a int-enum policy. The accepted values are
- // defined in the enum CheckContentComplianceValues.
- auto* check_content_compliance_value =
- chrome_policies.GetValue(policy::key::kCheckContentCompliance);
- if (check_content_compliance_value &&
- check_content_compliance_value->GetInt() > safe_browsing::CHECK_NONE &&
- check_content_compliance_value->GetInt() <=
- safe_browsing::CHECK_CONTENT_COMPLIANCE_MAX) {
+
+ auto* on_file_attached =
+ chrome_policies.GetValue(policy::key::kOnFileAttachedEnterpriseConnector);
+ if (on_file_attached && on_file_attached->is_list() &&
+ !on_file_attached->GetList().empty()) {
+ base::Value value(base::Value::Type::DICTIONARY);
+ value.SetStringKey("title", kManagementOnFileAttachedEvent);
+ value.SetStringKey("permission", kManagementOnFileAttachedVisibleData);
+ info.Append(std::move(value));
+ }
+
+ auto* on_file_downloaded = chrome_policies.GetValue(
+ policy::key::kOnFileDownloadedEnterpriseConnector);
+ if (on_file_downloaded && on_file_downloaded->is_list() &&
+ !on_file_downloaded->GetList().empty()) {
base::Value value(base::Value::Type::DICTIONARY);
- value.SetStringKey("title", kManagementDataLossPreventionName);
- value.SetStringKey("permission", kManagementDataLossPreventionPermissions);
+ value.SetStringKey("title", kManagementOnFileDownloadedEvent);
+ value.SetStringKey("permission", kManagementOnFileDownloadedVisibleData);
info.Append(std::move(value));
}
- // SendFilesForMalwareCheck is a int-enum policy. The accepted values are
- // defined in the enum SendFilesForMalwareCheckValues.
- auto* send_files_for_malware_check_value =
- chrome_policies.GetValue(policy::key::kSendFilesForMalwareCheck);
- if (send_files_for_malware_check_value &&
- send_files_for_malware_check_value->GetInt() >
- safe_browsing::DO_NOT_SCAN &&
- send_files_for_malware_check_value->GetInt() <=
- safe_browsing::SEND_FILES_FOR_MALWARE_CHECK_MAX) {
+ auto* on_bulk_data_entry = chrome_policies.GetValue(
+ policy::key::kOnBulkDataEntryEnterpriseConnector);
+ if (on_bulk_data_entry && on_bulk_data_entry->is_list() &&
+ !on_bulk_data_entry->GetList().empty()) {
base::Value value(base::Value::Type::DICTIONARY);
- value.SetStringKey("title", kManagementMalwareScanningName);
- value.SetStringKey("permission", kManagementMalwareScanningPermissions);
+ value.SetStringKey("title", kManagementOnBulkDataEntryEvent);
+ value.SetStringKey("permission", kManagementOnBulkDataEntryVisibleData);
info.Append(std::move(value));
}
- auto* unsafe_event_reporting_value =
- chrome_policies.GetValue(policy::key::kUnsafeEventsReportingEnabled);
- if (unsafe_event_reporting_value && unsafe_event_reporting_value->GetBool()) {
+ auto* on_security_event = chrome_policies.GetValue(
+ policy::key::kOnSecurityEventEnterpriseConnector);
+ if (on_security_event && on_security_event->is_list() &&
+ !on_security_event->GetList().empty()) {
base::Value value(base::Value::Type::DICTIONARY);
- value.SetStringKey("title", kManagementEnterpriseReportingName);
- value.SetStringKey("permission", kManagementEnterpriseReportingPermissions);
+ value.SetStringKey("title", kManagementEnterpriseReportingEvent);
+ value.SetStringKey("permission", kManagementEnterpriseReportingVisibleData);
info.Append(std::move(value));
}
diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler.h b/chromium/chrome/browser/ui/webui/management_ui_handler.h
index 188d8d417a2..5612c90b3ac 100644
--- a/chromium/chrome/browser/ui/webui/management_ui_handler.h
+++ b/chromium/chrome/browser/ui/webui/management_ui_handler.h
@@ -33,6 +33,7 @@ extern const char kManagementReportHardwareStatus[];
extern const char kManagementReportNetworkInterfaces[];
extern const char kManagementReportUsers[];
extern const char kManagementReportCrashReports[];
+extern const char kManagementReportAppInfoAndActivity[];
extern const char kManagementPrinting[];
extern const char kManagementCrostini[];
extern const char kManagementCrostiniContainerConfiguration[];
@@ -59,8 +60,14 @@ extern const char kManagementDataLossPreventionName[];
extern const char kManagementDataLossPreventionPermissions[];
extern const char kManagementMalwareScanningName[];
extern const char kManagementMalwareScanningPermissions[];
-extern const char kManagementEnterpriseReportingName[];
-extern const char kManagementEnterpriseReportingPermissions[];
+extern const char kManagementEnterpriseReportingEvent[];
+extern const char kManagementEnterpriseReportingVisibleData[];
+extern const char kManagementOnFileAttachedEvent[];
+extern const char kManagementOnFileAttachedVisibleData[];
+extern const char kManagementOnFileDownloadedEvent[];
+extern const char kManagementOnFileDownloadedVisibleData[];
+extern const char kManagementOnBulkDataEntryEvent[];
+extern const char kManagementOnBulkDataEntryVisibleData[];
extern const char kPolicyKeyReportMachineIdData[];
extern const char kPolicyKeyReportUserIdData[];
diff --git a/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc b/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc
index 5da0346aaec..8973b687a5a 100644
--- a/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/management_ui_handler_unittest.cc
@@ -7,6 +7,7 @@
#include <string>
#include "base/files/file_path.h"
+#include "base/json/json_reader.h"
#include "base/memory/scoped_refptr.h"
#include "base/strings/utf_string_conversions.h"
@@ -48,7 +49,9 @@
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chromeos/cryptohome/async_method_caller.h"
+#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/power/power_manager_client.h"
+#include "chromeos/dbus/shill/shill_service_client.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/proxy/proxy_config_handler.h"
#include "chromeos/network/proxy/ui_proxy_config_service.h"
@@ -64,6 +67,7 @@
#include "components/proxy_config/proxy_config_pref_names.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
+#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"
#include "ui/chromeos/devicetype_utils.h"
#endif // defined(OS_CHROMEOS)
@@ -96,13 +100,15 @@ class TestDeviceStatusCollector : public policy::DeviceStatusCollector {
bool report_nics,
bool report_users,
bool report_hw_status,
- bool report_crash_info)
+ bool report_crash_info,
+ bool report_app_info_and_activity)
: policy::DeviceStatusCollector(local_state, nullptr),
report_activity_times_(report_activity_times),
report_nics_(report_nics),
report_users_(report_users),
report_hw_status_(report_hw_status),
- report_crash_info_(report_crash_info) {}
+ report_crash_info_(report_crash_info),
+ report_app_info_and_activity_(report_app_info_and_activity) {}
~TestDeviceStatusCollector() override = default;
bool ShouldReportActivityTimes() const override {
@@ -114,8 +120,12 @@ class TestDeviceStatusCollector : public policy::DeviceStatusCollector {
bool ShouldReportCrashReportInfo() const override {
return report_crash_info_;
}
+ bool ShouldReportAppInfoAndActivity() const override {
+ return report_app_info_and_activity_;
+ }
- // empty methods that need to be implemented but are of no use for this case.
+ // empty methods that need to be implemented but are of no use for this
+ // case.
void GetStatusAsync(
const policy::StatusCollectorCallback& callback) override {}
void OnSubmittedSuccessfully() override {}
@@ -126,6 +136,7 @@ class TestDeviceStatusCollector : public policy::DeviceStatusCollector {
bool report_users_;
bool report_hw_status_;
bool report_crash_info_;
+ bool report_app_info_and_activity_;
};
class TestDeviceCloudPolicyManagerChromeOS
@@ -242,19 +253,29 @@ class ManagementUIHandlerTests : public TestingBaseClass {
std::make_unique<base::Value>(true), nullptr);
}
void SetPolicyValue(const char* policy_key,
- policy::PolicyMap& policies,
- int value) {
+ int value,
+ policy::PolicyMap& policies) {
policies.Set(policy_key, policy::POLICY_LEVEL_MANDATORY,
policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD,
std::make_unique<base::Value>(value), nullptr);
}
void SetPolicyValue(const char* policy_key,
- policy::PolicyMap& policies,
- bool value) {
+ bool value,
+ policy::PolicyMap& policies) {
policies.Set(policy_key, policy::POLICY_LEVEL_MANDATORY,
policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD,
std::make_unique<base::Value>(value), nullptr);
}
+ void SetConnectorPolicyValue(const char* policy_key,
+ const std::string& value,
+ policy::PolicyMap& policies) {
+ auto policy_value = base::JSONReader::Read(value);
+ EXPECT_TRUE(policy_value.has_value());
+ policies.Set(policy_key, policy::POLICY_LEVEL_MANDATORY,
+ policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD,
+ std::make_unique<base::Value>(std::move(policy_value.value())),
+ nullptr);
+ }
base::string16 ExtractPathFromDict(const base::Value& data,
const std::string path) {
@@ -286,6 +307,7 @@ class ManagementUIHandlerTests : public TestingBaseClass {
bool report_users;
bool report_hw_status;
bool report_crash_info;
+ bool report_app_info_and_activity;
bool upload_enabled;
bool printing_send_username_and_filename;
bool crostini_report_usage;
@@ -306,6 +328,7 @@ class ManagementUIHandlerTests : public TestingBaseClass {
setup_config_.report_users = default_value;
setup_config_.report_hw_status = default_value;
setup_config_.report_crash_info = default_value;
+ setup_config_.report_app_info_and_activity = default_value;
setup_config_.upload_enabled = default_value;
setup_config_.printing_send_username_and_filename = default_value;
setup_config_.crostini_report_usage = default_value;
@@ -328,6 +351,11 @@ class ManagementUIHandlerTests : public TestingBaseClass {
crostini_features_ = std::make_unique<crostini::FakeCrostiniFeatures>();
SetUpConnectManager();
chromeos::NetworkHandler::Initialize();
+ // The |DeviceSettingsTestBase| setup above instantiates
+ // |FakeShillManagerClient| with a default environment which will post
+ // tasks on the current thread to setup a initial network configuration with
+ // a connected default network.
+ base::RunLoop().RunUntilIdle();
}
void TearDown() override {
chromeos::NetworkHandler::Shutdown();
@@ -355,8 +383,8 @@ class ManagementUIHandlerTests : public TestingBaseClass {
new TestDeviceStatusCollector(
&local_state_, GetTestConfig().report_activity_times,
GetTestConfig().report_nics, GetTestConfig().report_users,
- GetTestConfig().report_hw_status,
- GetTestConfig().report_crash_info);
+ GetTestConfig().report_hw_status, GetTestConfig().report_crash_info,
+ GetTestConfig().report_app_info_and_activity);
settings_.device_settings()->SetTrustedStatus(
chromeos::CrosSettingsProvider::TRUSTED);
settings_.device_settings()->SetBoolean(chromeos::kSystemLogUploadEnabled,
@@ -528,8 +556,8 @@ AssertionResult ReportingElementsToBeEQ(
}
if (!tmp_expected.empty()) {
AssertionResult result = AssertionFailure();
- result
- << " the following messageId and reportingTypes could not be matched {";
+ result << " the following messageId and reportingTypes could not be "
+ "matched {";
for (const auto& element : tmp_expected) {
result << " messageId: " << element.first << ", reportingType "
<< element.second;
@@ -795,6 +823,7 @@ TEST_F(ManagementUIHandlerTests, AllEnabledDeviceReportingInfo) {
{kManagementReportHardwareStatus, "device statistics"},
{kManagementReportNetworkInterfaces, "device"},
{kManagementReportCrashReports, "crash report"},
+ {kManagementReportAppInfoAndActivity, "app info and activity"},
{kManagementLogUploadEnabled, "logs"},
{kManagementPrinting, "print"},
{kManagementCrostini, "crostini"},
@@ -816,6 +845,7 @@ TEST_F(ManagementUIHandlerTests,
{kManagementReportHardwareStatus, "device statistics"},
{kManagementReportNetworkInterfaces, "device"},
{kManagementReportCrashReports, "crash report"},
+ {kManagementReportAppInfoAndActivity, "app info and activity"},
{kManagementLogUploadEnabled, "logs"},
{kManagementPrinting, "print"},
{kManagementCrostiniContainerConfiguration, "crostini"},
@@ -868,6 +898,39 @@ TEST_F(ManagementUIHandlerTests, ProxyServerShowReport) {
expected_elements);
}
+TEST_F(ManagementUIHandlerTests, ProxyServerShowReportDeviceOffline) {
+ PrefProxyConfigTrackerImpl::RegisterProfilePrefs(user_prefs_.registry());
+ chromeos::NetworkHandler::Get()->InitializePrefServices(&user_prefs_,
+ &local_state_);
+ // Simulate network disconnected state.
+ chromeos::NetworkStateHandler::NetworkStateList networks;
+ chromeos::NetworkHandler::Get()
+ ->network_state_handler()
+ ->GetNetworkListByType(chromeos::NetworkTypePattern::Default(),
+ true, // configured_only
+ false, // visible_only,
+ 0, // no limit to number of results
+ &networks);
+ chromeos::ShillServiceClient::TestInterface* service =
+ chromeos::DBusThreadManager::Get()
+ ->GetShillServiceClient()
+ ->GetTestInterface();
+ for (const auto* const network : networks) {
+ service->SetServiceProperty(network->path(), shill::kStateProperty,
+ base::Value(shill::kStateOffline));
+ }
+ base::RunLoop().RunUntilIdle();
+
+ ResetTestConfig(false);
+ const base::Value info = SetUpForReportingInfo();
+
+ const std::map<std::string, std::string> expected_elements = {};
+
+ ASSERT_PRED_FORMAT2(ReportingElementsToBeEQ, info.GetList(),
+ expected_elements);
+ chromeos::NetworkHandler::Get()->NetworkHandler::ShutdownPrefServices();
+}
+
TEST_F(ManagementUIHandlerTests, ProxyServerHideReportForDirectProxy) {
PrefProxyConfigTrackerImpl::RegisterProfilePrefs(user_prefs_.registry());
chromeos::NetworkHandler::Get()->InitializePrefServices(&user_prefs_,
@@ -885,6 +948,7 @@ TEST_F(ManagementUIHandlerTests, ProxyServerHideReportForDirectProxy) {
const std::map<std::string, std::string> expected_elements = {};
ASSERT_PRED_FORMAT2(ReportingElementsToBeEQ, info.GetList(),
expected_elements);
+ chromeos::NetworkHandler::Get()->NetworkHandler::ShutdownPrefServices();
}
#endif
@@ -918,7 +982,7 @@ TEST_F(ManagementUIHandlerTests, CloudReportingPolicy) {
policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string());
EXPECT_CALL(policy_service_, GetPolicies(_))
.WillRepeatedly(ReturnRef(chrome_policies));
- SetPolicyValue(policy::key::kCloudReportingEnabled, chrome_policies, true);
+ SetPolicyValue(policy::key::kCloudReportingEnabled, true, chrome_policies);
const std::set<std::string> expected_messages = {
kManagementExtensionReportMachineName, kManagementExtensionReportUsername,
@@ -1020,10 +1084,15 @@ TEST_F(ManagementUIHandlerTests, ThreatReportingInfo) {
base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description")));
// When policies are set to uninteresting values, nothing to report.
- SetPolicyValue(policy::key::kCheckContentCompliance, chrome_policies, 0);
- SetPolicyValue(policy::key::kSendFilesForMalwareCheck, chrome_policies, 0);
- SetPolicyValue(policy::key::kUnsafeEventsReportingEnabled, chrome_policies,
- false);
+ SetConnectorPolicyValue(policy::key::kOnFileAttachedEnterpriseConnector, "[]",
+ chrome_policies);
+ SetConnectorPolicyValue(policy::key::kOnFileDownloadedEnterpriseConnector,
+ "[]", chrome_policies);
+ SetConnectorPolicyValue(policy::key::kOnBulkDataEntryEnterpriseConnector,
+ "[]", chrome_policies);
+ SetConnectorPolicyValue(policy::key::kOnSecurityEventEnterpriseConnector,
+ "[]", chrome_policies);
+
info = handler_.GetThreatProtectionInfo(profile_known_domain.get());
info.GetAsDictionary(&threat_protection_info);
EXPECT_TRUE(threat_protection_info->FindListKey("info")->GetList().empty());
@@ -1032,13 +1101,22 @@ TEST_F(ManagementUIHandlerTests, ThreatReportingInfo) {
base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description")));
// When policies are set to values that enable the feature, report it.
- SetPolicyValue(policy::key::kCheckContentCompliance, chrome_policies, 1);
- SetPolicyValue(policy::key::kSendFilesForMalwareCheck, chrome_policies, 2);
- SetPolicyValue(policy::key::kUnsafeEventsReportingEnabled, chrome_policies,
- true);
+ SetConnectorPolicyValue(policy::key::kOnFileAttachedEnterpriseConnector,
+ "[{\"service_provider\":\"google\"}]",
+ chrome_policies);
+ SetConnectorPolicyValue(policy::key::kOnFileDownloadedEnterpriseConnector,
+ "[{\"service_provider\":\"google\"}]",
+ chrome_policies);
+ SetConnectorPolicyValue(policy::key::kOnBulkDataEntryEnterpriseConnector,
+ "[{\"service_provider\":\"google\"}]",
+ chrome_policies);
+ SetConnectorPolicyValue(policy::key::kOnSecurityEventEnterpriseConnector,
+ "[{\"service_provider\":\"google\"}]",
+ chrome_policies);
+
info = handler_.GetThreatProtectionInfo(profile_no_domain.get());
info.GetAsDictionary(&threat_protection_info);
- EXPECT_EQ(3u, threat_protection_info->FindListKey("info")->GetList().size());
+ EXPECT_EQ(4u, threat_protection_info->FindListKey("info")->GetList().size());
EXPECT_EQ(
l10n_util::GetStringUTF16(IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION),
base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description")));
@@ -1046,20 +1124,26 @@ TEST_F(ManagementUIHandlerTests, ThreatReportingInfo) {
base::Value expected_info(base::Value::Type::LIST);
{
base::Value value(base::Value::Type::DICTIONARY);
- value.SetStringKey("title", kManagementDataLossPreventionName);
- value.SetStringKey("permission", kManagementDataLossPreventionPermissions);
+ value.SetStringKey("title", kManagementOnFileAttachedEvent);
+ value.SetStringKey("permission", kManagementOnFileAttachedVisibleData);
+ expected_info.Append(std::move(value));
+ }
+ {
+ base::Value value(base::Value::Type::DICTIONARY);
+ value.SetStringKey("title", kManagementOnFileDownloadedEvent);
+ value.SetStringKey("permission", kManagementOnFileDownloadedVisibleData);
expected_info.Append(std::move(value));
}
{
base::Value value(base::Value::Type::DICTIONARY);
- value.SetStringKey("title", kManagementMalwareScanningName);
- value.SetStringKey("permission", kManagementMalwareScanningPermissions);
+ value.SetStringKey("title", kManagementOnBulkDataEntryEvent);
+ value.SetStringKey("permission", kManagementOnBulkDataEntryVisibleData);
expected_info.Append(std::move(value));
}
{
base::Value value(base::Value::Type::DICTIONARY);
- value.SetStringKey("title", kManagementEnterpriseReportingName);
- value.SetStringKey("permission", kManagementEnterpriseReportingPermissions);
+ value.SetStringKey("title", kManagementEnterpriseReportingEvent);
+ value.SetStringKey("permission", kManagementEnterpriseReportingVisibleData);
expected_info.Append(std::move(value));
}
diff --git a/chromium/chrome/browser/ui/webui/media/media_feeds_ui.cc b/chromium/chrome/browser/ui/webui/media/media_feeds_ui.cc
index 9fe5e0b04b8..5ef3915cd3f 100644
--- a/chromium/chrome/browser/ui/webui/media/media_feeds_ui.cc
+++ b/chromium/chrome/browser/ui/webui/media/media_feeds_ui.cc
@@ -64,13 +64,16 @@ void MediaFeedsUI::GetMediaFeeds(GetMediaFeedsCallback callback) {
void MediaFeedsUI::GetItemsForMediaFeed(int64_t feed_id,
GetItemsForMediaFeedCallback callback) {
- GetMediaHistoryService()->GetItemsForMediaFeedForDebug(feed_id,
- std::move(callback));
+ GetMediaHistoryService()->GetMediaFeedItems(
+ media_history::MediaHistoryKeyedService::GetMediaFeedItemsRequest::
+ CreateItemsForDebug(feed_id),
+ std::move(callback));
}
void MediaFeedsUI::FetchMediaFeed(int64_t feed_id,
FetchMediaFeedCallback callback) {
- GetMediaFeedsService()->FetchMediaFeed(feed_id, std::move(callback));
+ GetMediaFeedsService()->FetchMediaFeed(feed_id, /*bypass_cache=*/false,
+ nullptr, std::move(callback));
}
void MediaFeedsUI::GetDebugInformation(GetDebugInformationCallback callback) {
@@ -81,6 +84,11 @@ void MediaFeedsUI::GetDebugInformation(GetDebugInformationCallback callback) {
info->safe_search_pref_value =
GetProfile()->GetPrefs()->GetBoolean(prefs::kMediaFeedsSafeSearchEnabled);
+ info->background_fetching_feature_enabled =
+ base::FeatureList::IsEnabled(media::kMediaFeedsBackgroundFetching);
+ info->background_fetching_pref_value = GetProfile()->GetPrefs()->GetBoolean(
+ prefs::kMediaFeedsBackgroundFetching);
+
std::move(callback).Run(std::move(info));
}
@@ -93,6 +101,15 @@ void MediaFeedsUI::SetSafeSearchEnabledPref(
std::move(callback).Run();
}
+void MediaFeedsUI::SetBackgroundFetchingPref(
+ bool value,
+ SetBackgroundFetchingPrefCallback callback) {
+ GetProfile()->GetPrefs()->SetBoolean(prefs::kMediaFeedsBackgroundFetching,
+ value);
+
+ std::move(callback).Run();
+}
+
media_history::MediaHistoryKeyedService*
MediaFeedsUI::GetMediaHistoryService() {
media_history::MediaHistoryKeyedService* service =
diff --git a/chromium/chrome/browser/ui/webui/media/media_feeds_ui.h b/chromium/chrome/browser/ui/webui/media/media_feeds_ui.h
index 73de089c839..dc382578d43 100644
--- a/chromium/chrome/browser/ui/webui/media/media_feeds_ui.h
+++ b/chromium/chrome/browser/ui/webui/media/media_feeds_ui.h
@@ -40,6 +40,9 @@ class MediaFeedsUI : public ui::MojoWebUIController,
void SetSafeSearchEnabledPref(
bool value,
SetSafeSearchEnabledPrefCallback callback) override;
+ void SetBackgroundFetchingPref(
+ bool value,
+ SetBackgroundFetchingPrefCallback callback) override;
private:
media_history::MediaHistoryKeyedService* GetMediaHistoryService();
diff --git a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc
index a8a4beaa73a..d7564825f8e 100644
--- a/chromium/chrome/browser/ui/webui/memory_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/memory_internals_ui.cc
@@ -17,7 +17,6 @@
#include "base/process/process_handle.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/task/post_task.h"
#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiling_host/profiling_process_host.h"
@@ -209,8 +208,8 @@ void MemoryInternalsDOMHandler::HandleRequestProcessList(
// This is called on the UI thread, the child process iterator must run on
// the IO thread, while the render process iterator must run on the UI thread.
- base::PostTask(
- FROM_HERE, {content::BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&MemoryInternalsDOMHandler::GetChildProcessesOnIOThread,
weak_factory_.GetWeakPtr(), std::move(callback_id)));
}
@@ -297,8 +296,8 @@ void MemoryInternalsDOMHandler::GetChildProcessesOnIOThread(
}
}
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&MemoryInternalsDOMHandler::GetProfiledPids,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&MemoryInternalsDOMHandler::GetProfiledPids,
dom_handler, callback_id, std::move(result)));
}
@@ -311,8 +310,8 @@ void MemoryInternalsDOMHandler::GetProfiledPids(
// The supervisor hasn't started, so return an empty list.
if (!supervisor->HasStarted()) {
- base::PostTask(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&MemoryInternalsDOMHandler::ReturnProcessListOnUIThread,
weak_factory_.GetWeakPtr(), callback_id,
std::move(children), std::vector<base::ProcessId>()));
diff --git a/chromium/chrome/browser/ui/webui/nacl_ui.cc b/chromium/chrome/browser/ui/webui/nacl_ui.cc
index c3f6b40f6eb..c784e81a33b 100644
--- a/chromium/chrome/browser/ui/webui/nacl_ui.cc
+++ b/chromium/chrome/browser/ui/webui/nacl_ui.cc
@@ -43,6 +43,7 @@
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "content/public/common/webplugininfo.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(OS_WIN)
@@ -60,7 +61,8 @@ namespace {
content::WebUIDataSource* CreateNaClUIHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUINaClHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
source->UseStringsJs();
source->AddResourcePath("about_nacl.css", IDR_ABOUT_NACL_CSS);
diff --git a/chromium/chrome/browser/ui/webui/nearby_internals/OWNERS b/chromium/chrome/browser/ui/webui/nearby_internals/OWNERS
new file mode 100644
index 00000000000..19414dc942a
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/nearby_internals/OWNERS
@@ -0,0 +1,4 @@
+file://chrome/browser/nearby_sharing/OWNERS
+khorimoto@chromium.org
+
+# COMPONENT: OS>Systems>Multidevice>Nearby
diff --git a/chromium/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui.cc b/chromium/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui.cc
new file mode 100644
index 00000000000..bcbd409aa3f
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui.cc
@@ -0,0 +1,44 @@
+// Copyright 2020 The Chromium 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/nearby_internals/nearby_internals_ui.h"
+
+#include "base/containers/span.h"
+#include "base/feature_list.h"
+#include "chrome/browser/browser_features.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/webui/webui_util.h"
+#include "chrome/common/webui_url_constants.h"
+#include "chrome/grit/nearby_internals_resources.h"
+#include "chrome/grit/nearby_internals_resources_map.h"
+#include "content/public/browser/web_ui.h"
+#include "content/public/browser/web_ui_data_source.h"
+#include "ui/base/webui/web_ui_util.h"
+
+namespace {
+constexpr char kNearbyInternalsGeneratedPath[] =
+ "@out_folder@/gen/chrome/browser/resources/nearby_internals/";
+} // namespace
+
+NearbyInternalsUI::NearbyInternalsUI(content::WebUI* web_ui)
+ : ui::MojoWebUIController(web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+ // Nearby Sharing is not available to incognito or guest profiles.
+ DCHECK(profile->IsRegularProfile());
+ DCHECK(base::FeatureList::IsEnabled(features::kNearbySharing));
+
+ content::WebUIDataSource* html_source =
+ content::WebUIDataSource::Create(chrome::kChromeUINearbyInternalsHost);
+
+ webui::SetupWebUIDataSource(
+ html_source,
+ base::make_span(kNearbyInternalsResources, kNearbyInternalsResourcesSize),
+ kNearbyInternalsGeneratedPath, IDR_NEARBY_INTERNALS_INDEX_HTML);
+
+ content::WebUIDataSource::Add(profile, html_source);
+}
+
+NearbyInternalsUI::~NearbyInternalsUI() = default;
+
+WEB_UI_CONTROLLER_TYPE_IMPL(NearbyInternalsUI)
diff --git a/chromium/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui.h b/chromium/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui.h
new file mode 100644
index 00000000000..60073afcea2
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/nearby_internals/nearby_internals_ui.h
@@ -0,0 +1,22 @@
+// Copyright 2020 The Chromium 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_NEARBY_INTERNALS_NEARBY_INTERNALS_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_NEARBY_INTERNALS_NEARBY_INTERNALS_UI_H_
+
+#include "ui/webui/mojo_web_ui_controller.h"
+
+// The WebUI controller for chrome://nearby-sharing-internals.
+class NearbyInternalsUI : public ui::MojoWebUIController {
+ public:
+ explicit NearbyInternalsUI(content::WebUI* web_ui);
+ NearbyInternalsUI(const NearbyInternalsUI&) = delete;
+ NearbyInternalsUI& operator=(const NearbyInternalsUI&) = delete;
+ ~NearbyInternalsUI() override;
+
+ private:
+ WEB_UI_CONTROLLER_TYPE_DECL();
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_NEARBY_INTERNALS_NEARBY_INTERNALS_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/nearby_share/OWNERS b/chromium/chrome/browser/ui/webui/nearby_share/OWNERS
new file mode 100644
index 00000000000..72feb28bcca
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/nearby_share/OWNERS
@@ -0,0 +1,3 @@
+file://chrome/browser/nearby_sharing/OWNERS
+
+# COMPONENT: UI>Browser>Sharing>Nearby
diff --git a/chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui.cc b/chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui.cc
new file mode 100644
index 00000000000..e058ccdf390
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui.cc
@@ -0,0 +1,52 @@
+// Copyright 2020 The Chromium 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/nearby_share/nearby_share_dialog_ui.h"
+
+#include <string>
+
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/webui/webui_util.h"
+#include "chrome/common/webui_url_constants.h"
+#include "chrome/grit/generated_resources.h"
+#include "chrome/grit/nearby_share_dialog_resources.h"
+#include "chrome/grit/nearby_share_dialog_resources_map.h"
+#include "chrome/grit/theme_resources.h"
+#include "content/public/browser/web_ui.h"
+#include "content/public/browser/web_ui_data_source.h"
+#include "ui/base/resource/resource_bundle.h"
+#include "ui/base/webui/web_ui_util.h"
+
+namespace {
+
+constexpr char kNearbyShareGeneratedPath[] =
+ "@out_folder@/gen/chrome/browser/resources/nearby_share/";
+
+} // namespace
+
+namespace nearby_share {
+
+NearbyShareDialogUI::NearbyShareDialogUI(content::WebUI* web_ui)
+ : ui::MojoWebUIController(web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+ // Nearby Share is not available to incognito or guest profiles.
+ DCHECK(profile->IsRegularProfile());
+
+ content::WebUIDataSource* html_source =
+ content::WebUIDataSource::Create(chrome::kChromeUINearbyShareHost);
+
+ webui::SetupWebUIDataSource(html_source,
+ base::make_span(kNearbyShareDialogResources,
+ kNearbyShareDialogResourcesSize),
+ kNearbyShareGeneratedPath,
+ IDR_NEARBY_SHARE_NEARBY_SHARE_DIALOG_HTML);
+
+ content::WebUIDataSource::Add(profile, html_source);
+}
+
+NearbyShareDialogUI::~NearbyShareDialogUI() = default;
+
+WEB_UI_CONTROLLER_TYPE_IMPL(NearbyShareDialogUI)
+
+} // namespace nearby_share
diff --git a/chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui.h b/chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui.h
new file mode 100644
index 00000000000..5a9ba400ba0
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui.h
@@ -0,0 +1,26 @@
+// Copyright 2020 The Chromium 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_NEARBY_SHARE_NEARBY_SHARE_DIALOG_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_NEARBY_SHARE_NEARBY_SHARE_DIALOG_UI_H_
+
+#include "ui/webui/mojo_web_ui_controller.h"
+
+namespace nearby_share {
+
+// The WebUI controller for chrome://nearby.
+class NearbyShareDialogUI : public ui::MojoWebUIController {
+ public:
+ explicit NearbyShareDialogUI(content::WebUI* web_ui);
+ NearbyShareDialogUI(const NearbyShareDialogUI&) = delete;
+ NearbyShareDialogUI& operator=(const NearbyShareDialogUI&) = delete;
+ ~NearbyShareDialogUI() override;
+
+ private:
+ WEB_UI_CONTROLLER_TYPE_DECL();
+};
+
+} // namespace nearby_share
+
+#endif // CHROME_BROWSER_UI_WEBUI_NEARBY_SHARE_NEARBY_SHARE_DIALOG_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui_browsertest.cc b/chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui_browsertest.cc
new file mode 100644
index 00000000000..a991a02feb9
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui_browsertest.cc
@@ -0,0 +1,50 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/test/scoped_feature_list.h"
+#include "chrome/browser/browser_features.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/tabs/tab_strip_model.h"
+#include "chrome/common/webui_url_constants.h"
+#include "chrome/test/base/in_process_browser_test.h"
+#include "chrome/test/base/ui_test_utils.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/test/browser_test.h"
+#include "content/public/test/browser_test_utils.h"
+#include "url/gurl.h"
+
+namespace {
+
+class NearbyShareDialogUITest : public InProcessBrowserTest {
+ public:
+ NearbyShareDialogUITest() {
+ scoped_feature_list_.InitWithFeatures({features::kNearbySharing}, {});
+ }
+ ~NearbyShareDialogUITest() override = default;
+
+ private:
+ base::test::ScopedFeatureList scoped_feature_list_;
+};
+
+} // namespace
+
+IN_PROC_BROWSER_TEST_F(NearbyShareDialogUITest, RendersComponent) {
+ // First, check that navigation succeeds.
+ GURL kUrl(content::GetWebUIURL(chrome::kChromeUINearbyShareHost));
+ ui_test_utils::NavigateToURL(browser(), kUrl);
+ content::WebContents* web_contents =
+ browser()->tab_strip_model()->GetActiveWebContents();
+ ASSERT_TRUE(web_contents);
+ EXPECT_EQ(kUrl, web_contents->GetLastCommittedURL());
+ EXPECT_FALSE(web_contents->IsCrashed());
+
+ // Assert that we render the nearby-share-app component.
+ int num_nearby_share_app = -1;
+ ASSERT_TRUE(content::ExecuteScriptAndExtractInt(
+ web_contents,
+ "domAutomationController.send("
+ "document.getElementsByTagName('nearby-share-app').length)",
+ &num_nearby_share_app));
+ EXPECT_EQ(1, num_nearby_share_app);
+}
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 434c438bb2b..bb8debc7d6e 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
@@ -12,21 +12,14 @@
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
-#include "base/files/file_util.h"
#include "base/memory/weak_ptr.h"
-#include "base/task/post_task.h"
-#include "base/task/thread_pool.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/net/net_export_helper.h"
-#include "chrome/browser/policy/chrome_policy_conversions_client.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/net_internals_resources.h"
-#include "components/onc/onc_constants.h"
-#include "components/policy/core/browser/policy_conversions.h"
#include "components/prefs/pref_member.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
@@ -38,23 +31,9 @@
#include "content/public/browser/web_ui_message_handler.h"
#include "net/log/net_log_util.h"
#include "services/network/expect_ct_reporter.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
-#if defined(OS_CHROMEOS)
-#include "chrome/browser/chromeos/file_manager/filesystem_api_util.h"
-#include "chrome/browser/chromeos/profiles/profile_helper.h"
-#include "chrome/browser/chromeos/system_logs/debug_log_writer.h"
-#include "chrome/browser/chromeos/system_logs/system_logs_writer.h"
-#include "chrome/browser/net/nss_context.h"
-#include "chrome/common/logging_chrome.h"
-#include "chromeos/dbus/dbus_thread_manager.h"
-#include "chromeos/dbus/debug_daemon/debug_daemon_client.h"
-#include "chromeos/network/onc/onc_certificate_importer_impl.h"
-#include "chromeos/network/onc/onc_parsed_certificates.h"
-#include "chromeos/network/onc/onc_utils.h"
-#include "components/policy/core/browser/policy_conversions.h"
-#endif
-
using content::BrowserThread;
namespace {
@@ -62,7 +41,8 @@ namespace {
content::WebUIDataSource* CreateNetInternalsHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUINetInternalsHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
source->SetDefaultResource(IDR_NET_INTERNALS_INDEX_HTML);
@@ -73,28 +53,6 @@ content::WebUIDataSource* CreateNetInternalsHTMLSource() {
void IgnoreBoolCallback(bool result) {}
-#if defined(OS_CHROMEOS)
-base::FilePath GetDownloadsDirectory(content::WebUI* web_ui) {
- Profile* profile = Profile::FromWebUI(web_ui);
- const DownloadPrefs* const prefs = DownloadPrefs::FromBrowserContext(profile);
- base::FilePath path = prefs->DownloadPath();
- if (file_manager::util::IsUnderNonNativeLocalPath(profile, path))
- path = prefs->GetDefaultDownloadDirectoryForProfile();
- return path;
-}
-
-std::string GetJsonPolicies(content::WebUI* web_ui) {
- auto client = std::make_unique<policy::ChromePolicyConversionsClient>(
- web_ui->GetWebContents()->GetBrowserContext());
- return policy::DictionaryPolicyConversions(std::move(client)).ToJSON();
-}
-
-void WriteTimestampedFile(base::FilePath file_path, std::string contents) {
- file_path = logging::GenerateTimestampedName(file_path, base::Time::Now());
- base::WriteFile(file_path, contents.data(), contents.size());
-}
-#endif
-
// This class receives javascript messages from the renderer.
// Note that the WebUI infrastructure runs on the UI thread, therefore all of
// this class's methods are expected to run on the UI thread.
@@ -116,20 +74,6 @@ class NetInternalsMessageHandler
// If the renderer is displaying a log file, the message will be ignored.
void SendJavascriptCommand(const std::string& command, base::Value arg);
-#if defined(OS_CHROMEOS)
- // Callback to |GetNSSCertDatabaseForProfile| used to retrieve the database
- // to which user's ONC defined certificates should be imported.
- // It parses and imports |onc_blob|.
- void ImportONCFileToNSSDB(const std::string& onc_blob,
- const std::string& passcode,
- net::NSSCertDatabase* nssdb);
-
- // Called back by the CertificateImporter when a certificate import finished.
- // |previous_error| contains earlier errors during this import.
- void OnCertificatesImported(const std::string& previous_error,
- bool cert_import_success);
-#endif
-
void OnExpectCTTestReportCallback(bool success);
//--------------------------------
@@ -147,27 +91,6 @@ class NetInternalsMessageHandler
void OnExpectCTTestReport(const base::ListValue* list);
void OnCloseIdleSockets(const base::ListValue* list);
void OnFlushSocketPools(const base::ListValue* list);
-#if defined(OS_CHROMEOS)
- void OnWritePolicyLogsCompleted(const base::FilePath& path,
- bool should_compress,
- bool combined,
- const char* received_event);
- void OnImportONCFile(const base::ListValue* list);
- void OnStoreDebugLogs(bool combined,
- const char* received_event,
- const base::ListValue* list);
- void OnStoreDebugLogsCompleted(const char* received_event,
- const base::FilePath& log_path,
- bool succeeded);
- void OnStoreFeedbackSystemLogs(const char* received_event,
- const base::ListValue* list);
- void OnStoreFeedbackSystemLogsCompleted(
- const char* received_event,
- base::Optional<base::FilePath> system_logs_path);
- void OnSetNetworkDebugMode(const base::ListValue* list);
- void OnSetNetworkDebugModeCompleted(const std::string& subsystem,
- bool succeeded);
-#endif
content::WebUI* web_ui_;
@@ -223,31 +146,6 @@ void NetInternalsMessageHandler::RegisterMessages() {
"flushSocketPools",
base::BindRepeating(&NetInternalsMessageHandler::OnFlushSocketPools,
base::Unretained(this)));
-#if defined(OS_CHROMEOS)
- web_ui()->RegisterMessageCallback(
- "importONCFile",
- base::BindRepeating(&NetInternalsMessageHandler::OnImportONCFile,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
- "storeDebugLogs",
- base::BindRepeating(&NetInternalsMessageHandler::OnStoreDebugLogs,
- base::Unretained(this), false /* combined */,
- "receivedStoreDebugLogs"));
- web_ui()->RegisterMessageCallback(
- "storeCombinedDebugLogs",
- base::BindRepeating(&NetInternalsMessageHandler::OnStoreDebugLogs,
- base::Unretained(this), true /* combined */,
- "receivedStoreCombinedDebugLogs"));
- web_ui()->RegisterMessageCallback(
- "storeFeedbackSystemLogs",
- base::BindRepeating(
- &NetInternalsMessageHandler::OnStoreFeedbackSystemLogs,
- base::Unretained(this), "receivedStoreFeedbackSystemLogs"));
- web_ui()->RegisterMessageCallback(
- "setNetworkDebugMode",
- base::BindRepeating(&NetInternalsMessageHandler::OnSetNetworkDebugMode,
- base::Unretained(this)));
-#endif
}
void NetInternalsMessageHandler::SendJavascriptCommand(
@@ -321,12 +219,17 @@ void NetInternalsMessageHandler::OnHSTSAdd(const base::ListValue* list) {
void NetInternalsMessageHandler::OnExpectCTQuery(const base::ListValue* list) {
// |list| should be: [<domain to query>].
std::string domain;
- bool domain_result = list->GetString(0, &domain);
- DCHECK(domain_result);
+ bool result = list->GetString(0, &domain);
+ DCHECK(result);
+
+ url::Origin origin = url::Origin::Create(GURL("https://" + domain));
GetNetworkContext()->GetExpectCTState(
- domain, base::BindOnce(&NetInternalsMessageHandler::SendJavascriptCommand,
- this->AsWeakPtr(), "receivedExpectCTResult"));
+ domain,
+ net::NetworkIsolationKey(origin /* top_frame_site */,
+ origin /* frame_site */),
+ base::BindOnce(&NetInternalsMessageHandler::SendJavascriptCommand,
+ this->AsWeakPtr(), "receivedExpectCTResult"));
}
void NetInternalsMessageHandler::OnExpectCTAdd(const base::ListValue* list) {
@@ -339,6 +242,7 @@ void NetInternalsMessageHandler::OnExpectCTAdd(const base::ListValue* list) {
// name.
return;
}
+
std::string report_uri_str;
result = list->GetString(1, &report_uri_str);
DCHECK(result);
@@ -346,9 +250,14 @@ void NetInternalsMessageHandler::OnExpectCTAdd(const base::ListValue* list) {
result = list->GetBoolean(2, &enforce);
DCHECK(result);
+ url::Origin origin = url::Origin::Create(GURL("https://" + domain));
+
base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
- GetNetworkContext()->AddExpectCT(domain, expiry, enforce,
- GURL(report_uri_str), base::DoNothing());
+ GetNetworkContext()->AddExpectCT(
+ domain, expiry, enforce, GURL(report_uri_str),
+ net::NetworkIsolationKey(origin /* top_frame_site */,
+ origin /* frame_site */),
+ base::DoNothing());
}
void NetInternalsMessageHandler::OnExpectCTTestReport(
@@ -383,186 +292,6 @@ void NetInternalsMessageHandler::OnCloseIdleSockets(
GetNetworkContext()->CloseIdleConnections(base::NullCallback());
}
-#if defined(OS_CHROMEOS)
-void NetInternalsMessageHandler::ImportONCFileToNSSDB(
- const std::string& onc_blob,
- const std::string& passcode,
- net::NSSCertDatabase* nssdb) {
- const user_manager::User* user =
- chromeos::ProfileHelper::Get()->GetUserByProfile(
- Profile::FromWebUI(web_ui()));
-
- if (!user) {
- std::string error = "User not found.";
- SendJavascriptCommand("receivedONCFileParse", base::Value(error));
- return;
- }
-
- std::string error;
- onc::ONCSource onc_source = onc::ONC_SOURCE_USER_IMPORT;
- base::ListValue network_configs;
- base::DictionaryValue global_network_config;
- base::ListValue certificates;
- if (!chromeos::onc::ParseAndValidateOncForImport(onc_blob,
- onc_source,
- passcode,
- &network_configs,
- &global_network_config,
- &certificates)) {
- error = "Errors occurred during the ONC parsing. ";
- }
-
- std::string network_error;
- chromeos::onc::ImportNetworksForUser(user, network_configs, &network_error);
- if (!network_error.empty())
- error += network_error;
-
- chromeos::onc::CertificateImporterImpl cert_importer(
- base::CreateSingleThreadTaskRunner({BrowserThread::IO}), nssdb);
- auto certs =
- std::make_unique<chromeos::onc::OncParsedCertificates>(certificates);
- if (certs->has_error())
- error += "Some certificates couldn't be parsed. ";
- cert_importer.ImportAllCertificatesUserInitiated(
- certs->server_or_authority_certificates(), certs->client_certificates(),
- base::BindOnce(&NetInternalsMessageHandler::OnCertificatesImported,
- AsWeakPtr(), error /* previous_error */));
-}
-
-void NetInternalsMessageHandler::OnCertificatesImported(
- const std::string& previous_error,
- bool cert_import_success) {
- std::string error = previous_error;
- if (!cert_import_success)
- error += "Some certificates couldn't be imported. ";
-
- SendJavascriptCommand("receivedONCFileParse", base::Value(error));
-}
-
-void NetInternalsMessageHandler::OnImportONCFile(
- const base::ListValue* list) {
- std::string onc_blob;
- std::string passcode;
- if (list->GetSize() != 2 ||
- !list->GetString(0, &onc_blob) ||
- !list->GetString(1, &passcode)) {
- NOTREACHED();
- }
-
- GetNSSCertDatabaseForProfile(
- Profile::FromWebUI(web_ui()),
- base::Bind(&NetInternalsMessageHandler::ImportONCFileToNSSDB, AsWeakPtr(),
- onc_blob, passcode));
-}
-
-void NetInternalsMessageHandler::OnStoreDebugLogs(bool combined,
- const char* received_event,
- const base::ListValue* list) {
- DCHECK(list);
-
- SendJavascriptCommand(received_event, base::Value("Creating log file..."));
-
- base::FilePath path = GetDownloadsDirectory(web_ui());
- std::string json_policies = GetJsonPolicies(web_ui());
- base::ThreadPool::PostTaskAndReply(
- FROM_HERE,
- {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
- base::TaskShutdownBehavior::BLOCK_SHUTDOWN},
- base::BindOnce(WriteTimestampedFile, path.Append("policies.json"),
- json_policies),
- base::BindOnce(&NetInternalsMessageHandler::OnWritePolicyLogsCompleted,
- AsWeakPtr(), path, true /* should_compress */, combined,
- received_event));
-}
-
-void NetInternalsMessageHandler::OnWritePolicyLogsCompleted(
- const base::FilePath& path,
- bool should_compress,
- bool combined,
- const char* received_event) {
- if (combined) {
- chromeos::DebugLogWriter::StoreCombinedLogs(
- path,
- base::BindOnce(&NetInternalsMessageHandler::OnStoreDebugLogsCompleted,
- AsWeakPtr(), received_event));
- } else {
- chromeos::DebugLogWriter::StoreLogs(
- path, should_compress,
- base::BindOnce(&NetInternalsMessageHandler::OnStoreDebugLogsCompleted,
- AsWeakPtr(), received_event));
- }
-}
-
-void NetInternalsMessageHandler::OnStoreDebugLogsCompleted(
- const char* received_event,
- const base::FilePath& log_path,
- bool succeeded) {
- std::string status;
- if (succeeded)
- status = "Created log file: " + log_path.BaseName().AsUTF8Unsafe();
- else
- status = "Failed to create log file";
- SendJavascriptCommand(received_event, base::Value(status));
-}
-
-void NetInternalsMessageHandler::OnStoreFeedbackSystemLogs(
- const char* received_event,
- const base::ListValue* list) {
- DCHECK(list);
- SendJavascriptCommand(received_event,
- base::Value("Creating system logs file..."));
-
- base::FilePath downloads_path = GetDownloadsDirectory(web_ui());
- std::string json_policies = GetJsonPolicies(web_ui());
-
- // Write the policies file to disk as a blocking task, then call
- // system_logs_writer::WriteSystemLogs to asynchronously write the system
- // logs and respond when complete.
- base::ThreadPool::PostTaskAndReply(
- FROM_HERE,
- {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
- base::TaskShutdownBehavior::BLOCK_SHUTDOWN},
- base::BindOnce(WriteTimestampedFile,
- downloads_path.Append("policies.json"), json_policies),
- base::BindOnce(
- chromeos::system_logs_writer::WriteSystemLogs, downloads_path,
- base::BindOnce(
- &NetInternalsMessageHandler::OnStoreFeedbackSystemLogsCompleted,
- AsWeakPtr(), received_event)));
-}
-
-void NetInternalsMessageHandler::OnStoreFeedbackSystemLogsCompleted(
- const char* received_event,
- base::Optional<base::FilePath> system_logs_path) {
- std::string status = system_logs_path
- ? "Created system_logs file: " +
- system_logs_path->BaseName().AsUTF8Unsafe()
- : "Failed to create system logs file.";
- SendJavascriptCommand(received_event, base::Value(status));
-}
-
-void NetInternalsMessageHandler::OnSetNetworkDebugMode(
- const base::ListValue* list) {
- std::string subsystem;
- if (list->GetSize() != 1 || !list->GetString(0, &subsystem))
- NOTREACHED();
- chromeos::DBusThreadManager::Get()->GetDebugDaemonClient()->SetDebugMode(
- subsystem,
- base::BindOnce(
- &NetInternalsMessageHandler::OnSetNetworkDebugModeCompleted,
- AsWeakPtr(), subsystem));
-}
-
-void NetInternalsMessageHandler::OnSetNetworkDebugModeCompleted(
- const std::string& subsystem,
- bool succeeded) {
- std::string status = succeeded ? "Debug mode is changed to "
- : "Failed to change debug mode to ";
- status += subsystem;
- SendJavascriptCommand("receivedSetNetworkDebugMode", base::Value(status));
-}
-#endif // defined(OS_CHROMEOS)
-
network::mojom::NetworkContext*
NetInternalsMessageHandler::GetNetworkContext() {
return content::BrowserContext::GetDefaultStoragePartition(
diff --git a/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page.mojom b/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page.mojom
index a16ed18a086..8be851977a7 100644
--- a/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page.mojom
+++ b/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page.mojom
@@ -194,23 +194,36 @@ enum DoodleImageType {
STATIC,
};
-// The contents of simple and animated doodles.
-struct ImageDoodleContent {
+// An image doodle in either dark or light mode.
+struct ImageDoodle {
// Doodle image encoded as data URL.
url.mojom.Url image_url;
- // URL opened in new tab when the doodle is clicked.
- url.mojom.Url on_click_url;
// URL pointing to animated content (e.g. gif). Only set for animated doodles.
url.mojom.Url? animation_url;
+ // Dimensions of the original image in pixels.
+ uint32 width;
+ uint32 height;
+ // Color of the background the doodle was designed for. If the NTP background
+ // differs from that color we show the doodle in a box of that color.
+ skia.mojom.SkColor background_color;
// Specification of the share button.
DoodleShareButton share_button;
- // URL displayed to users, which they can use to share the doodle.
- url.mojom.Url share_url;
// URLs to be pinged when an image has been shown.
url.mojom.Url image_impression_log_url;
url.mojom.Url? animation_impression_log_url;
};
+// The contents of simple and animated doodles.
+struct ImageDoodleContent {
+ // Doodles for respective modes.
+ ImageDoodle light;
+ ImageDoodle? dark;
+ // URL opened in new tab when the doodle is clicked.
+ url.mojom.Url on_click_url;
+ // URL displayed to users, which they can use to share the doodle.
+ url.mojom.Url share_url;
+};
+
// The contents of interactive doodles.
struct InteractiveDoodleContent {
// URL pointing to doodle page.
@@ -261,6 +274,33 @@ enum CustomizeDialogAction {
SHORTCUTS_VISIBILITY_TOGGLE_CLICKED,
};
+// Action the user performed while using voice search. Used for metrics logging
+// only. Actions correspond to items in NTPLoggingEventType.
+enum VoiceSearchAction {
+ ACTIVATE_SEARCH_BOX,
+ ACTIVATE_KEYBOARD,
+ CLOSE_OVERLAY,
+ QUERY_SUBMITTED,
+ SUPPORT_LINK_CLICKED,
+ TRY_AGAIN_LINK,
+ TRY_AGAIN_MIC_BUTTON,
+};
+
+// Errors occurred while using voice search. Errors correspond to items in
+// NTPLoggingEventType.
+enum VoiceSearchError {
+ ABORTED,
+ NO_SPEECH,
+ AUDIO_CAPTURE,
+ NETWORK,
+ NOT_ALLOWED,
+ LANGUAGE_NOT_SUPPORTED,
+ NO_MATCH,
+ SERVICE_NOT_ALLOWED,
+ BAD_GRAMMAR,
+ OTHER,
+};
+
// Used by the WebUI page to bootstrap bidirectional communication.
interface PageHandlerFactory {
// The WebUI page's |BrowserProxy| singleton calls this method when the page
@@ -361,6 +401,10 @@ interface PageHandler {
string? share_id);
// Logs that a link on a promo has been clicked.
OnPromoLinkClicked();
+ // Logs an action performed while using voice search.
+ OnVoiceSearchAction(VoiceSearchAction action);
+ // Logs an error occurred while using voice search.
+ OnVoiceSearchError(VoiceSearchError error);
// ======= REALBOX =======
// Queries autocomplete matches from the browser.
diff --git a/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.cc b/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.cc
index 90498b1ccaa..7ee153fc40a 100644
--- a/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.cc
+++ b/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.cc
@@ -32,7 +32,6 @@
#include "chrome/browser/search/chrome_colors/chrome_colors_factory.h"
#include "chrome/browser/search/chrome_colors/chrome_colors_service.h"
#include "chrome/browser/search/instant_service.h"
-#include "chrome/browser/search/instant_service_factory.h"
#include "chrome/browser/search/one_google_bar/one_google_bar_service_factory.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/search_provider_logos/logo_service_factory.h"
@@ -235,6 +234,55 @@ ntp_tiles::NTPTileImpression MakeNTPTileImpression(
/*url_for_rappor=*/GURL() /* unused */);
}
+SkColor ParseHexColor(const std::string& color) {
+ SkColor result;
+ if (color.size() == 7 && color[0] == '#' &&
+ base::HexStringToUInt(color.substr(1), &result)) {
+ return SkColorSetA(result, 255);
+ }
+ return SK_ColorTRANSPARENT;
+}
+
+new_tab_page::mojom::ImageDoodlePtr MakeImageDoodle(
+ search_provider_logos::LogoType type,
+ const std::string& data,
+ const std::string& mime_type,
+ const GURL& animated_url,
+ int width_px,
+ int height_px,
+ const std::string& background_color,
+ int share_button_x,
+ int share_button_y,
+ const std::string& share_button_icon,
+ const std::string& share_button_bg,
+ GURL log_url,
+ GURL cta_log_url) {
+ auto doodle = new_tab_page::mojom::ImageDoodle::New();
+ std::string base64;
+ base::Base64Encode(data, &base64);
+ doodle->image_url = GURL(base::StringPrintf(
+ "data:%s;base64,%s", mime_type.c_str(), base64.c_str()));
+ if (type == search_provider_logos::LogoType::ANIMATED) {
+ doodle->animation_url = animated_url;
+ }
+ doodle->width = width_px;
+ doodle->height = height_px;
+ doodle->background_color = ParseHexColor(background_color);
+ doodle->share_button = new_tab_page::mojom::DoodleShareButton::New();
+ doodle->share_button->x = share_button_x;
+ doodle->share_button->y = share_button_y;
+ doodle->share_button->icon_url = GURL(base::StringPrintf(
+ "data:image/png;base64,%s", share_button_icon.c_str()));
+ doodle->share_button->background_color = ParseHexColor(share_button_bg);
+ if (type == search_provider_logos::LogoType::ANIMATED) {
+ doodle->image_impression_log_url = cta_log_url;
+ doodle->animation_impression_log_url = log_url;
+ } else {
+ doodle->image_impression_log_url = log_url;
+ }
+ return doodle;
+}
+
} // namespace
NewTabPageHandler::NewTabPageHandler(
@@ -242,11 +290,13 @@ NewTabPageHandler::NewTabPageHandler(
pending_page_handler,
mojo::PendingRemote<new_tab_page::mojom::Page> pending_page,
Profile* profile,
+ InstantService* instant_service,
content::WebContents* web_contents,
+ NTPUserDataLogger* logger,
const base::Time& ntp_navigation_start_time)
: chrome_colors_service_(
chrome_colors::ChromeColorsFactory::GetForProfile(profile)),
- instant_service_(InstantServiceFactory::GetForProfile(profile)),
+ instant_service_(instant_service),
ntp_background_service_(
NtpBackgroundServiceFactory::GetForProfile(profile)),
logo_service_(LogoServiceFactory::GetForProfile(profile)),
@@ -263,7 +313,7 @@ NewTabPageHandler::NewTabPageHandler(
BitmapFetcherServiceFactory::GetForBrowserContext(profile)),
web_contents_(web_contents),
ntp_navigation_start_time_(ntp_navigation_start_time),
- logger_(NTPUserDataLogger::GetOrCreateFromWebContents(web_contents)),
+ logger_(logger),
page_{std::move(pending_page)},
receiver_{this, std::move(pending_page_handler)} {
CHECK(instant_service_);
@@ -725,6 +775,73 @@ void NewTabPageHandler::OnPromoLinkClicked() {
LogEvent(NTP_MIDDLE_SLOT_PROMO_LINK_CLICKED);
}
+void NewTabPageHandler::OnVoiceSearchAction(
+ new_tab_page::mojom::VoiceSearchAction action) {
+ NTPLoggingEventType event;
+ switch (action) {
+ case new_tab_page::mojom::VoiceSearchAction::ACTIVATE_SEARCH_BOX:
+ event = NTP_VOICE_ACTION_ACTIVATE_SEARCH_BOX;
+ break;
+ case new_tab_page::mojom::VoiceSearchAction::ACTIVATE_KEYBOARD:
+ event = NTP_VOICE_ACTION_ACTIVATE_KEYBOARD;
+ break;
+ case new_tab_page::mojom::VoiceSearchAction::CLOSE_OVERLAY:
+ event = NTP_VOICE_ACTION_CLOSE_OVERLAY;
+ break;
+ case new_tab_page::mojom::VoiceSearchAction::QUERY_SUBMITTED:
+ event = NTP_VOICE_ACTION_QUERY_SUBMITTED;
+ break;
+ case new_tab_page::mojom::VoiceSearchAction::SUPPORT_LINK_CLICKED:
+ event = NTP_VOICE_ACTION_SUPPORT_LINK_CLICKED;
+ break;
+ case new_tab_page::mojom::VoiceSearchAction::TRY_AGAIN_LINK:
+ event = NTP_VOICE_ACTION_TRY_AGAIN_LINK;
+ break;
+ case new_tab_page::mojom::VoiceSearchAction::TRY_AGAIN_MIC_BUTTON:
+ event = NTP_VOICE_ACTION_TRY_AGAIN_MIC_BUTTON;
+ break;
+ }
+ LogEvent(event);
+}
+
+void NewTabPageHandler::OnVoiceSearchError(
+ new_tab_page::mojom::VoiceSearchError error) {
+ NTPLoggingEventType event;
+ switch (error) {
+ case new_tab_page::mojom::VoiceSearchError::ABORTED:
+ event = NTP_VOICE_ERROR_ABORTED;
+ break;
+ case new_tab_page::mojom::VoiceSearchError::NO_SPEECH:
+ event = NTP_VOICE_ERROR_NO_SPEECH;
+ break;
+ case new_tab_page::mojom::VoiceSearchError::AUDIO_CAPTURE:
+ event = NTP_VOICE_ERROR_AUDIO_CAPTURE;
+ break;
+ case new_tab_page::mojom::VoiceSearchError::NETWORK:
+ event = NTP_VOICE_ERROR_NETWORK;
+ break;
+ case new_tab_page::mojom::VoiceSearchError::NOT_ALLOWED:
+ event = NTP_VOICE_ERROR_NOT_ALLOWED;
+ break;
+ case new_tab_page::mojom::VoiceSearchError::LANGUAGE_NOT_SUPPORTED:
+ event = NTP_VOICE_ERROR_LANGUAGE_NOT_SUPPORTED;
+ break;
+ case new_tab_page::mojom::VoiceSearchError::NO_MATCH:
+ event = NTP_VOICE_ERROR_NO_MATCH;
+ break;
+ case new_tab_page::mojom::VoiceSearchError::SERVICE_NOT_ALLOWED:
+ event = NTP_VOICE_ERROR_SERVICE_NOT_ALLOWED;
+ break;
+ case new_tab_page::mojom::VoiceSearchError::BAD_GRAMMAR:
+ event = NTP_VOICE_ERROR_BAD_GRAMMAR;
+ break;
+ case new_tab_page::mojom::VoiceSearchError::OTHER:
+ event = NTP_VOICE_ERROR_OTHER;
+ break;
+ }
+ LogEvent(event);
+}
+
void NewTabPageHandler::QueryAutocomplete(const base::string16& input,
bool prevent_inline_autocomplete) {
if (!autocomplete_controller_) {
@@ -879,7 +996,7 @@ void NewTabPageHandler::OpenAutocompleteMatch(
web_contents_->OpenURL(
content::OpenURLParams(match.destination_url, content::Referrer(),
- disposition, ui::PAGE_TRANSITION_LINK, false));
+ disposition, match.transition, false));
}
void NewTabPageHandler::DeleteAutocompleteMatch(uint8_t line) {
@@ -1144,40 +1261,28 @@ void NewTabPageHandler::OnLogoAvailable(
std::move(callback).Run(nullptr);
return;
}
- SkColor doodle_share_button_background_color;
- if (logo->metadata.share_button_bg.size() != 7 ||
- logo->metadata.share_button_bg[0] != '#' ||
- !base::HexStringToUInt(logo->metadata.share_button_bg.substr(1),
- &doodle_share_button_background_color)) {
- std::move(callback).Run(nullptr);
- return;
- }
auto image_doodle_content = new_tab_page::mojom::ImageDoodleContent::New();
- std::string base64;
- base::Base64Encode(logo->encoded_image->data(), &base64);
- image_doodle_content->image_url = GURL(base::StringPrintf(
- "data:%s;base64,%s", logo->metadata.mime_type.c_str(), base64.c_str()));
- image_doodle_content->on_click_url = logo->metadata.on_click_url;
- if (logo->metadata.type == search_provider_logos::LogoType::ANIMATED) {
- image_doodle_content->animation_url = logo->metadata.animated_url;
+ image_doodle_content->light = MakeImageDoodle(
+ logo->metadata.type, logo->encoded_image->data(),
+ logo->metadata.mime_type, logo->metadata.animated_url,
+ logo->metadata.width_px, logo->metadata.height_px, "#ffffff",
+ logo->metadata.share_button_x, logo->metadata.share_button_y,
+ logo->metadata.share_button_icon, logo->metadata.share_button_bg,
+ logo->metadata.log_url, logo->metadata.cta_log_url);
+ if (logo->dark_encoded_image) {
+ image_doodle_content->dark = MakeImageDoodle(
+ logo->metadata.type, logo->dark_encoded_image->data(),
+ logo->metadata.dark_mime_type, logo->metadata.dark_animated_url,
+ logo->metadata.dark_width_px, logo->metadata.dark_height_px,
+ logo->metadata.dark_background_color,
+ logo->metadata.dark_share_button_x,
+ logo->metadata.dark_share_button_y,
+ logo->metadata.dark_share_button_icon,
+ logo->metadata.dark_share_button_bg, logo->metadata.dark_log_url,
+ logo->metadata.dark_cta_log_url);
}
- image_doodle_content->share_button =
- new_tab_page::mojom::DoodleShareButton::New();
- image_doodle_content->share_button->x = logo->metadata.share_button_x;
- image_doodle_content->share_button->y = logo->metadata.share_button_y;
- image_doodle_content->share_button->icon_url = GURL(base::StringPrintf(
- "data:image/png;base64,%s", logo->metadata.share_button_icon.c_str()));
- image_doodle_content->share_button->background_color =
- SkColorSetA(doodle_share_button_background_color, 255);
+ image_doodle_content->on_click_url = logo->metadata.on_click_url;
image_doodle_content->share_url = logo->metadata.short_link;
- if (logo->metadata.type == search_provider_logos::LogoType::ANIMATED) {
- image_doodle_content->image_impression_log_url =
- logo->metadata.cta_log_url;
- image_doodle_content->animation_impression_log_url =
- logo->metadata.log_url;
- } else {
- image_doodle_content->image_impression_log_url = logo->metadata.log_url;
- }
doodle->content = new_tab_page::mojom::DoodleContent::NewImageDoodle(
std::move(image_doodle_content));
} else if (logo->metadata.type ==
diff --git a/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.h b/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.h
index 252dda345db..a2d572d868a 100644
--- a/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.h
+++ b/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.h
@@ -60,7 +60,9 @@ class NewTabPageHandler : public new_tab_page::mojom::PageHandler,
pending_page_handler,
mojo::PendingRemote<new_tab_page::mojom::Page> pending_page,
Profile* profile,
+ InstantService* instant_service,
content::WebContents* web_contents,
+ NTPUserDataLogger* logger,
const base::Time& ntp_navigation_start_time);
~NewTabPageHandler() override;
@@ -120,6 +122,9 @@ class NewTabPageHandler : public new_tab_page::mojom::PageHandler,
const std::string& doodle_id,
const base::Optional<std::string>& share_id) override;
void OnPromoLinkClicked() override;
+ void OnVoiceSearchAction(
+ new_tab_page::mojom::VoiceSearchAction action) override;
+ void OnVoiceSearchError(new_tab_page::mojom::VoiceSearchError error) override;
void QueryAutocomplete(const base::string16& input,
bool prevent_inline_autocomplete) override;
void StopAutocomplete(bool clear_result) override;
diff --git a/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler_unittest.cc b/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler_unittest.cc
new file mode 100644
index 00000000000..7624cacbf63
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler_unittest.cc
@@ -0,0 +1,106 @@
+// Copyright 2020 The Chromium 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/new_tab_page/new_tab_page_handler.h"
+#include "chrome/browser/search/instant_service.h"
+#include "chrome/browser/ui/search/ntp_user_data_logger.h"
+#include "chrome/browser/ui/webui/new_tab_page/new_tab_page.mojom.h"
+#include "chrome/common/search/omnibox.mojom.h"
+#include "chrome/test/base/testing_profile.h"
+#include "content/public/test/browser_task_environment.h"
+#include "content/public/test/test_web_contents_factory.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "url/gurl.h"
+
+namespace {
+
+class MockInstantService : public InstantService {
+ public:
+ explicit MockInstantService(Profile* profile) : InstantService(profile) {}
+ ~MockInstantService() override = default;
+
+ MOCK_METHOD1(AddObserver, void(InstantServiceObserver*));
+ MOCK_METHOD0(UpdateNtpTheme, void());
+};
+
+class MockNTPUserDataLogger : public NTPUserDataLogger {
+ public:
+ MockNTPUserDataLogger() : NTPUserDataLogger(nullptr) {}
+ ~MockNTPUserDataLogger() override = default;
+};
+
+class MockPage : public new_tab_page::mojom::Page {
+ public:
+ MockPage() = default;
+ ~MockPage() override = default;
+
+ mojo::PendingRemote<new_tab_page::mojom::Page> BindAndGetRemote() {
+ DCHECK(!receiver_.is_bound());
+ return receiver_.BindNewPipeAndPassRemote();
+ }
+
+ MOCK_METHOD1(SetMostVisitedInfo,
+ void(new_tab_page::mojom::MostVisitedInfoPtr));
+ MOCK_METHOD1(SetTheme, void(new_tab_page::mojom::ThemePtr));
+ MOCK_METHOD1(SetFakeboxFocused, void(bool));
+ MOCK_METHOD1(SetFakeboxVisible, void(bool));
+ MOCK_METHOD1(AutocompleteResultChanged,
+ void(search::mojom::AutocompleteResultPtr));
+ MOCK_METHOD3(AutocompleteMatchImageAvailable,
+ void(uint32_t, const GURL&, const std::string&));
+
+ mojo::Receiver<new_tab_page::mojom::Page> receiver_{this};
+};
+
+} // namespace
+
+class NewTabPageHandlerTest : public testing::Test {
+ public:
+ NewTabPageHandlerTest()
+ : mock_instant_service_(&profile_),
+ web_contents_(factory_.CreateWebContents(&profile_)) {}
+
+ ~NewTabPageHandlerTest() override = default;
+
+ void SetUp() override {
+ EXPECT_CALL(mock_instant_service_, AddObserver)
+ .WillOnce(DoAll(testing::SaveArg<0>(&instant_service_observer_)));
+ EXPECT_CALL(mock_instant_service_, UpdateNtpTheme());
+ handler_ = std::make_unique<NewTabPageHandler>(
+ mojo::PendingReceiver<new_tab_page::mojom::PageHandler>(),
+ mock_page_.BindAndGetRemote(), &profile_, &mock_instant_service_,
+ web_contents_, &logger_, base::Time::Now());
+ EXPECT_EQ(handler_.get(), instant_service_observer_);
+ }
+
+ void TearDown() override { testing::Test::TearDown(); }
+
+ protected:
+ testing::NiceMock<MockPage> mock_page_;
+ // NOTE: The initialization order of these members matters.
+ content::BrowserTaskEnvironment task_environment_;
+ TestingProfile profile_;
+ MockInstantService mock_instant_service_;
+ content::TestWebContentsFactory factory_;
+ content::WebContents* web_contents_; // Weak. Owned by factory_.
+ MockNTPUserDataLogger logger_;
+ std::unique_ptr<NewTabPageHandler> handler_;
+ InstantServiceObserver* instant_service_observer_;
+};
+
+TEST_F(NewTabPageHandlerTest, SetMostVisitedInfo) {
+ EXPECT_CALL(mock_page_, SetMostVisitedInfo(testing::_));
+ InstantMostVisitedInfo info;
+ instant_service_observer_->MostVisitedInfoChanged(info);
+}
+
+TEST_F(NewTabPageHandlerTest, SetTheme) {
+ EXPECT_CALL(mock_page_, SetTheme(testing::_));
+ NtpTheme theme;
+ instant_service_observer_->NtpThemeChanged(theme);
+}
diff --git a/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc b/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc
index a055b15e57b..f2051be3574 100644
--- a/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc
+++ b/chromium/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc
@@ -12,6 +12,7 @@
#include "chrome/browser/search/instant_service_factory.h"
#include "chrome/browser/search/ntp_features.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
+#include "chrome/browser/ui/search/ntp_user_data_logger.h"
#include "chrome/browser/ui/search/omnibox_mojo_utils.h"
#include "chrome/browser/ui/webui/favicon_source.h"
#include "chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.h"
@@ -25,11 +26,11 @@
#include "chrome/grit/new_tab_page_resources_map.h"
#include "components/favicon_base/favicon_url_parser.h"
#include "components/google/core/common/google_util.h"
-#include "components/omnibox/common/omnibox_features.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
@@ -63,9 +64,6 @@ content::WebUIDataSource* CreateNewTabPageUiHtmlSource(Profile* profile) {
ntp_features::IsRealboxEnabled() &&
base::FeatureList::IsEnabled(ntp_features::kWebUIRealbox);
source->AddBoolean("realboxEnabled", realbox_enabled);
- source->AddBoolean("suggestionTransparencyEnabled",
- base::FeatureList::IsEnabled(
- omnibox::kOmniboxSuggestionTransparencyOptions));
source->AddBoolean(
"realboxMatchOmniboxTheme",
base::FeatureList::IsEnabled(ntp_features::kRealboxMatchOmniboxTheme));
@@ -78,6 +76,13 @@ content::WebUIDataSource* CreateNewTabPageUiHtmlSource(Profile* profile) {
source->AddBoolean(
"iframeOneGoogleBarEnabled",
base::FeatureList::IsEnabled(ntp_features::kIframeOneGoogleBar));
+ source->AddBoolean(
+ "oneGoogleBarModalOverlaysEnabled",
+ base::FeatureList::IsEnabled(ntp_features::kOneGoogleBarModalOverlays));
+
+ source->AddBoolean(
+ "themeModeDoodlesEnabled",
+ base::FeatureList::IsEnabled(ntp_features::kWebUIThemeModeDoodles));
static constexpr webui::LocalizedString kStrings[] = {
{"doneButton", IDS_DONE},
@@ -188,8 +193,6 @@ content::WebUIDataSource* CreateNewTabPageUiHtmlSource(Profile* profile) {
{omnibox::kSearchIconResourceName, IDR_WEBUI_IMAGES_ICON_SEARCH}};
webui::AddResourcePathsBulk(source, kImages);
- source->AddResourcePath("skcolor.mojom-lite.js",
- IDR_NEW_TAB_PAGE_SKCOLOR_MOJO_LITE_JS);
source->AddResourcePath("new_tab_page.mojom-lite.js",
IDR_NEW_TAB_PAGE_MOJO_LITE_JS);
source->AddResourcePath("omnibox.mojom-lite.js",
@@ -206,13 +209,15 @@ content::WebUIDataSource* CreateNewTabPageUiHtmlSource(Profile* profile) {
// TODO(crbug.com/1076506): remove when changing to iframed OneGoogleBar.
// Needs to happen after |webui::SetupWebUIDataSource()| since also overrides
// script-src.
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources chrome://test 'self' 'unsafe-inline' "
"https:;");
// Allow embedding of iframes from the One Google Bar and
// chrome-untrusted://new-tab-page for other external content and resources.
- source->OverrideContentSecurityPolicyChildSrc(
- base::StringPrintf("child-src https://*.google.com/ %s %s;",
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ChildSrc,
+ base::StringPrintf("child-src https: %s %s;",
google_util::CommandLineGoogleBaseURL().spec().c_str(),
chrome::kChromeUIUntrustedNewTabPageUrl));
@@ -280,7 +285,9 @@ void NewTabPageUI::CreatePageHandler(
DCHECK(pending_page.is_valid());
page_handler_ = std::make_unique<NewTabPageHandler>(
std::move(pending_page_handler), std::move(pending_page), profile_,
- web_contents_, navigation_start_time_);
+ instant_service_, web_contents_,
+ NTPUserDataLogger::GetOrCreateFromWebContents(web_contents_),
+ navigation_start_time_);
}
void NewTabPageUI::NtpThemeChanged(const NtpTheme& theme) {
diff --git a/chromium/chrome/browser/ui/webui/new_tab_page/untrusted_source.cc b/chromium/chrome/browser/ui/webui/new_tab_page/untrusted_source.cc
index 07e3f7d95de..d4cbd26c6d8 100644
--- a/chromium/chrome/browser/ui/webui/new_tab_page/untrusted_source.cc
+++ b/chromium/chrome/browser/ui/webui/new_tab_page/untrusted_source.cc
@@ -11,6 +11,7 @@
#include "base/files/file_util.h"
#include "base/i18n/rtl.h"
#include "base/memory/ref_counted_memory.h"
+#include "base/memory/scoped_refptr.h"
#include "base/metrics/histogram_macros.h"
#include "base/optional.h"
#include "base/strings/string_piece.h"
@@ -19,6 +20,7 @@
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/search/ntp_features.h"
#include "chrome/browser/search/one_google_bar/one_google_bar_data.h"
#include "chrome/browser/search/one_google_bar/one_google_bar_service_factory.h"
#include "chrome/browser/search/promos/promo_data.h"
@@ -28,6 +30,7 @@
#include "chrome/grit/new_tab_page_resources.h"
#include "content/public/common/url_constants.h"
#include "net/base/url_util.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/template_expressions.h"
#include "url/url_util.h"
@@ -39,7 +42,8 @@ constexpr int kMaxUriDecodeLen = 2048;
std::string FormatTemplate(int resource_id,
const ui::TemplateReplacements& replacements) {
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
- base::RefCountedMemory* bytes = bundle.LoadDataResourceBytes(resource_id);
+ scoped_refptr<base::RefCountedMemory> bytes =
+ bundle.LoadDataResourceBytes(resource_id);
base::StringPiece string_piece(reinterpret_cast<const char*>(bytes->front()),
bytes->size());
return ui::ReplaceTemplateExpressions(
@@ -81,12 +85,21 @@ UntrustedSource::UntrustedSource(Profile* profile)
UntrustedSource::~UntrustedSource() = default;
-std::string UntrustedSource::GetContentSecurityPolicyScriptSrc() {
- return "script-src 'self' 'unsafe-inline' https:;";
-}
+std::string UntrustedSource::GetContentSecurityPolicy(
+ network::mojom::CSPDirectiveName directive) {
+ if (directive == network::mojom::CSPDirectiveName::ScriptSrc) {
+ return "script-src 'self' 'unsafe-inline' https:;";
+ } else if (directive == network::mojom::CSPDirectiveName::ChildSrc) {
+ return "child-src https:;";
+ } else if (directive == network::mojom::CSPDirectiveName::DefaultSrc) {
+ // TODO(https://crbug.com/1085325): Audit and tighten CSP.
+ return std::string();
+ } else if (directive == network::mojom::CSPDirectiveName::FrameAncestors) {
+ return base::StringPrintf("frame-ancestors %s",
+ chrome::kChromeUINewTabPageURL);
+ }
-std::string UntrustedSource::GetContentSecurityPolicyChildSrc() {
- return "child-src https:;";
+ return content::URLDataSource::GetContentSecurityPolicy(directive);
}
std::string UntrustedSource::GetSource() {
@@ -135,14 +148,13 @@ void UntrustedSource::StartDataRequest(
bundle.LoadDataResourceBytes(IDR_NEW_TAB_PAGE_UNTRUSTED_PROMO_JS));
return;
}
- if ((path == "image" || path == "iframe") && url_param.is_valid() &&
+ if (path == "image" && url_param.is_valid() &&
(url_param.SchemeIs(url::kHttpsScheme) ||
url_param.SchemeIs(content::kChromeUIUntrustedScheme))) {
ui::TemplateReplacements replacements;
replacements["url"] = url_param.spec();
- int resource_id = path == "image" ? IDR_NEW_TAB_PAGE_UNTRUSTED_IMAGE_HTML
- : IDR_NEW_TAB_PAGE_UNTRUSTED_IFRAME_HTML;
- std::string html = FormatTemplate(resource_id, replacements);
+ std::string html =
+ FormatTemplate(IDR_NEW_TAB_PAGE_UNTRUSTED_IMAGE_HTML, replacements);
std::move(callback).Run(base::RefCountedString::TakeString(&html));
return;
}
@@ -210,11 +222,6 @@ bool UntrustedSource::AllowCaching() {
return false;
}
-std::string UntrustedSource::GetContentSecurityPolicyFrameAncestors() {
- return base::StringPrintf("frame-ancestors %s",
- chrome::kChromeUINewTabPageURL);
-}
-
bool UntrustedSource::ShouldReplaceExistingSource() {
return false;
}
@@ -230,8 +237,7 @@ bool UntrustedSource::ShouldServiceRequest(
return path == "one-google-bar" || path == "one_google_bar.js" ||
path == "promo" || path == "promo.js" || path == "image" ||
path == "background_image" || path == "custom_background_image" ||
- path == "background_image.js" || path == "iframe" ||
- path == "background.jpg";
+ path == "background_image.js" || path == "background.jpg";
}
void UntrustedSource::OnOneGoogleBarDataUpdated() {
@@ -249,6 +255,10 @@ void UntrustedSource::OnOneGoogleBarDataUpdated() {
if (data.has_value()) {
ui::TemplateReplacements replacements;
replacements["textdirection"] = base::i18n::IsRTL() ? "rtl" : "ltr";
+ replacements["modalOverlays"] =
+ base::FeatureList::IsEnabled(ntp_features::kOneGoogleBarModalOverlays)
+ ? "modal-overlays"
+ : "";
replacements["barHtml"] = data->bar_html;
replacements["inHeadScript"] = data->in_head_script;
replacements["inHeadStyle"] = data->in_head_style;
diff --git a/chromium/chrome/browser/ui/webui/new_tab_page/untrusted_source.h b/chromium/chrome/browser/ui/webui/new_tab_page/untrusted_source.h
index 5a689dbaf25..ecb0a5bbde5 100644
--- a/chromium/chrome/browser/ui/webui/new_tab_page/untrusted_source.h
+++ b/chromium/chrome/browser/ui/webui/new_tab_page/untrusted_source.h
@@ -39,8 +39,6 @@ class Profile;
// * repeatY: (optional) CSS background-repeat-y property.
// * positionX: (optional) CSS background-position-x property.
// * positionY: (optional) CSS background-position-y property.
-// * chrome-untrusted://new-tab-page/iframe?<url>: Behaves like an iframe with
-// src set to <url>.
// Each of those helpers only accept URLs with HTTPS or chrome-untrusted:.
class UntrustedSource : public content::URLDataSource,
public OneGoogleBarServiceObserver,
@@ -52,8 +50,8 @@ class UntrustedSource : public content::URLDataSource,
UntrustedSource& operator=(const UntrustedSource&) = delete;
// content::URLDataSource:
- std::string GetContentSecurityPolicyScriptSrc() override;
- std::string GetContentSecurityPolicyChildSrc() override;
+ std::string GetContentSecurityPolicy(
+ network::mojom::CSPDirectiveName directive) override;
std::string GetSource() override;
void StartDataRequest(
const GURL& url,
@@ -61,7 +59,6 @@ class UntrustedSource : public content::URLDataSource,
content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override;
bool AllowCaching() override;
- std::string GetContentSecurityPolicyFrameAncestors() override;
bool ShouldReplaceExistingSource() override;
bool ShouldServiceRequest(const GURL& url,
content::BrowserContext* browser_context,
diff --git a/chromium/chrome/browser/ui/webui/new_tab_page/webui_ntp_browsertest.cc b/chromium/chrome/browser/ui/webui/new_tab_page/webui_ntp_browsertest.cc
new file mode 100644
index 00000000000..e68b5daa040
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/new_tab_page/webui_ntp_browsertest.cc
@@ -0,0 +1,79 @@
+// Copyright 2020 The Chromium 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/search/ntp_features.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/browser_commands.h"
+#include "chrome/common/webui_url_constants.h"
+#include "chrome/test/base/in_process_browser_test.h"
+#include "chrome/test/base/ui_test_utils.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/test/browser_test.h"
+#include "content/public/test/browser_test_utils.h"
+#include "net/dns/mock_host_resolver.h"
+
+class WebUiNtpBrowserTest : public InProcessBrowserTest {
+ public:
+ WebUiNtpBrowserTest() {
+ feature_list_.InitAndEnableFeature(ntp_features::kWebUI);
+ }
+ ~WebUiNtpBrowserTest() override = default;
+
+ void SetUpCommandLine(base::CommandLine* command_line) override {
+ embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
+ ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
+ }
+
+ void SetUpOnMainThread() override {
+ host_resolver()->AddRule("*", "127.0.0.1");
+ embedded_test_server()->StartAcceptingConnections();
+ }
+
+ private:
+ base::test::ScopedFeatureList feature_list_;
+};
+
+// Verify that the WebUI NTP commits in a SiteInstance with the WebUI URL.
+IN_PROC_BROWSER_TEST_F(WebUiNtpBrowserTest, VerifyWebUiNtpSiteInstance) {
+ GURL ntp_url(chrome::kChromeUINewTabURL);
+ ui_test_utils::NavigateToURL(browser(), ntp_url);
+
+ content::WebContents* web_contents =
+ browser()->tab_strip_model()->GetActiveWebContents();
+ ASSERT_EQ(ntp_url, web_contents->GetLastCommittedURL());
+
+ GURL webui_ntp_url(chrome::kChromeUINewTabPageURL);
+ ASSERT_EQ(webui_ntp_url,
+ web_contents->GetMainFrame()->GetSiteInstance()->GetSiteURL());
+}
+
+// Verify that the WebUI NTP uses process-per-site.
+IN_PROC_BROWSER_TEST_F(WebUiNtpBrowserTest, ProcessPerSite) {
+ std::vector<content::WebContents*> tabs;
+
+ // Open a few NTPs.
+ for (size_t i = 0; i < 3; i++) {
+ content::WebContentsAddedObserver tab_observer;
+ chrome::NewTab(browser());
+
+ // Wait for the new tab.
+ auto* tab = tab_observer.GetWebContents();
+ ASSERT_TRUE(WaitForLoadStop(tab));
+
+ // Sanity check: the NTP should be a WebUI NTP (and not chrome://newtab/ or
+ // some other NTP).
+ EXPECT_EQ(GURL(chrome::kChromeUINewTabPageURL).spec(),
+ EvalJs(tab, "window.location.href",
+ content::EXECUTE_SCRIPT_DEFAULT_OPTIONS,
+ /*world_id=*/1));
+
+ tabs.push_back(tab);
+ }
+
+ // Verify that all NTPs share a process.
+ for (size_t i = 1; i < tabs.size(); i++) {
+ EXPECT_EQ(tabs[0]->GetMainFrame()->GetProcess(),
+ tabs[i]->GetMainFrame()->GetProcess());
+ }
+}
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 8b3cd017605..b1c4b61fe52 100644
--- a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc
+++ b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.cc
@@ -22,6 +22,7 @@
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
+#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/apps/app_service/app_icon_source.h"
#include "chrome/browser/apps/app_service/app_launch_params.h"
@@ -53,13 +54,12 @@
#include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
#include "chrome/browser/ui/webui/ntp/new_tab_ui.h"
#include "chrome/browser/web_applications/components/app_registry_controller.h"
-#include "chrome/browser/web_applications/components/app_shortcut_manager.h"
-#include "chrome/browser/web_applications/components/file_handler_manager.h"
#include "chrome/browser/web_applications/components/install_finalizer.h"
#include "chrome/browser/web_applications/components/web_app_constants.h"
#include "chrome/browser/web_applications/components/web_app_provider_base.h"
#include "chrome/browser/web_applications/extensions/bookmark_app_finalizer_utils.h"
#include "chrome/browser/web_applications/extensions/bookmark_app_util.h"
+#include "chrome/browser/web_applications/os_integration_manager.h"
#include "chrome/browser/web_applications/web_app_icon_manager.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/common/buildflags.h"
@@ -969,15 +969,12 @@ void AppLauncherHandler::HandleInstallAppLocally(const base::ListValue* args) {
web_app_provider_->registry_controller().SetAppIsLocallyInstalled(app_id,
true);
- web_app::AppShortcutManager& shortcut_manager =
- web_app_provider_->shortcut_manager();
- if (shortcut_manager.CanCreateShortcuts()) {
- shortcut_manager.CreateShortcuts(
- app_id, /*add_to_desktop=*/true,
- base::BindOnce(
- &AppLauncherHandler::OnShortcutsCreatedRegisterOsIntegration,
- weak_ptr_factory_.GetWeakPtr(), app_id));
- }
+ web_app_provider_->registry_controller().SetAppInstallTime(app_id,
+ base::Time::Now());
+ web_app_provider_->os_integration_manager().InstallOsHooks(
+ app_id, base::BindOnce(&AppLauncherHandler::OnOsHooksInstalled,
+ weak_ptr_factory_.GetWeakPtr(), app_id));
+
// Use the appAdded to update the app icon's color to no longer be
// greyscale.
std::unique_ptr<base::DictionaryValue> app_info = GetWebAppInfo(app_id);
@@ -1198,13 +1195,10 @@ void AppLauncherHandler::PromptToEnableApp(const std::string& extension_id) {
extension_enable_flow_->StartForWebContents(web_ui()->GetWebContents());
}
-void AppLauncherHandler::OnShortcutsCreatedRegisterOsIntegration(
- const web_app::AppId& app_id,
- bool shortcuts_created) {
+void AppLauncherHandler::OnOsHooksInstalled(const web_app::AppId& app_id,
+ bool shortcuts_created) {
LOCAL_HISTOGRAM_BOOLEAN("Apps.Launcher.InstallLocallyShortcutsCreated",
shortcuts_created);
- web_app_provider_->file_handler_manager().EnableAndRegisterOsFileHandlers(
- app_id);
}
void AppLauncherHandler::OnExtensionUninstallDialogClosed(
diff --git a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.h b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.h
index c5d99409710..6efbad522c7 100644
--- a/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.h
+++ b/chromium/chrome/browser/ui/webui/ntp/app_launcher_handler.h
@@ -174,10 +174,8 @@ class AppLauncherHandler
// Prompts the user to re-enable the app for |extension_id|.
void PromptToEnableApp(const std::string& extension_id);
- // Registers file handlers for |app_id|, after shortcuts have been
- // created.
- void OnShortcutsCreatedRegisterOsIntegration(const web_app::AppId& app_id,
- bool shortcuts_created);
+ // Records result to UMA after OS Hooks are installed.
+ void OnOsHooksInstalled(const web_app::AppId& app_id, bool shortcuts_created);
// ExtensionUninstallDialog::Delegate:
void OnExtensionUninstallDialogClosed(bool did_start_uninstall,
@@ -264,7 +262,7 @@ class AppLauncherHandler
// Used for favicon loading tasks.
base::CancelableTaskTracker cancelable_task_tracker_;
- // Used to register file handlers after shortcuts have been created.
+ // Used for passing callbacks.
base::WeakPtrFactory<AppLauncherHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(AppLauncherHandler);
diff --git a/chromium/chrome/browser/ui/webui/ntp/cookie_controls_handler.cc b/chromium/chrome/browser/ui/webui/ntp/cookie_controls_handler.cc
index 41fd80239ea..d072d8378c1 100644
--- a/chromium/chrome/browser/ui/webui/ntp/cookie_controls_handler.cc
+++ b/chromium/chrome/browser/ui/webui/ntp/cookie_controls_handler.cc
@@ -62,10 +62,9 @@ void CookieControlsHandler::HandleObserveCookieControlsSettingsChanges(
SendCookieControlsUIChanges();
}
-const char* CookieControlsHandler::GetEnforcementIcon(Profile* profile) {
- CookieControlsService* service =
- CookieControlsServiceFactory::GetForProfile(profile);
- switch (service->GetCookieControlsEnforcement()) {
+const char* CookieControlsHandler::GetEnforcementIcon(
+ CookieControlsEnforcement enforcement) {
+ switch (enforcement) {
case CookieControlsEnforcement::kEnforcedByPolicy:
return kPolicyIcon;
case CookieControlsEnforcement::kEnforcedByExtension:
@@ -86,11 +85,11 @@ void CookieControlsHandler::OnThirdPartyCookieBlockingPolicyChanged() {
}
void CookieControlsHandler::SendCookieControlsUIChanges() {
- Profile* profile = Profile::FromWebUI(web_ui());
base::DictionaryValue dict;
dict.SetBoolKey("enforced", service_->ShouldEnforceCookieControls());
dict.SetBoolKey("checked", service_->GetToggleCheckedValue());
- dict.SetStringKey("icon", CookieControlsHandler::GetEnforcementIcon(profile));
+ dict.SetStringKey(
+ "icon", GetEnforcementIcon(service_->GetCookieControlsEnforcement()));
bool use_new_cookie_page =
base::FeatureList::IsEnabled(features::kPrivacySettingsRedesign);
dict.SetString("cookieSettingsUrl",
diff --git a/chromium/chrome/browser/ui/webui/ntp/cookie_controls_handler.h b/chromium/chrome/browser/ui/webui/ntp/cookie_controls_handler.h
index f7dbf79d4bd..ff781518a0b 100644
--- a/chromium/chrome/browser/ui/webui/ntp/cookie_controls_handler.h
+++ b/chromium/chrome/browser/ui/webui/ntp/cookie_controls_handler.h
@@ -16,7 +16,7 @@ namespace base {
class ListValue;
} // namespace base
-// Handles requests for prefs::kCookieControlsMode retrival/update.
+// Communicates with the incognito ntp to show a third-party cookie control.
class CookieControlsHandler : public content::WebUIMessageHandler,
public CookieControlsService::Observer {
public:
@@ -30,7 +30,7 @@ class CookieControlsHandler : public content::WebUIMessageHandler,
void HandleCookieControlsToggleChanged(const base::ListValue* args);
void HandleObserveCookieControlsSettingsChanges(const base::ListValue* args);
- static const char* GetEnforcementIcon(Profile* profile);
+ static const char* GetEnforcementIcon(CookieControlsEnforcement enforcement);
// CookieControlsService::Observer
void OnThirdPartyCookieBlockingPrefChanged() override;
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 6d549a735e1..466de0c664d 100644
--- a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc
+++ b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.cc
@@ -30,6 +30,7 @@
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/native_theme/native_theme.h"
#include "url/gurl.h"
@@ -59,7 +60,10 @@ NewTabUI::NewTabUI(content::WebUI* web_ui) : content::WebUIController(web_ui) {
if (!profile->IsGuestSession()) {
web_ui->AddMessageHandler(std::make_unique<ThemeHandler>());
- web_ui->AddMessageHandler(std::make_unique<CookieControlsHandler>(profile));
+ if (profile->IsOffTheRecord()) {
+ web_ui->AddMessageHandler(
+ std::make_unique<CookieControlsHandler>(profile));
+ }
}
// content::URLDataSource assumes the ownership of the html source.
@@ -187,23 +191,23 @@ bool NewTabUI::NewTabHTMLSource::ShouldReplaceExistingSource() {
return false;
}
-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() {
- return "style-src 'self' chrome://resources 'unsafe-inline' chrome://theme;";
-}
-
-std::string NewTabUI::NewTabHTMLSource::GetContentSecurityPolicyImgSrc() {
- return "img-src chrome-search://thumb chrome-search://thumb2 "
- "chrome-search://theme chrome://theme data:;";
-}
+std::string NewTabUI::NewTabHTMLSource::GetContentSecurityPolicy(
+ network::mojom::CSPDirectiveName directive) {
+ if (directive == network::mojom::CSPDirectiveName::ScriptSrc) {
+ // 'unsafe-inline' and google resources are added to script-src.
+ return "script-src chrome://resources 'self' 'unsafe-eval' 'unsafe-inline' "
+ "*.google.com *.gstatic.com;";
+ } else if (directive == network::mojom::CSPDirectiveName::StyleSrc) {
+ return "style-src 'self' chrome://resources 'unsafe-inline' "
+ "chrome://theme;";
+ } else if (directive == network::mojom::CSPDirectiveName::ImgSrc) {
+ return "img-src chrome-search://thumb chrome-search://thumb2 "
+ "chrome-search://theme chrome://theme data:;";
+ } else if (directive == network::mojom::CSPDirectiveName::ChildSrc) {
+ return "child-src chrome-search://most-visited;";
+ }
-std::string NewTabUI::NewTabHTMLSource::GetContentSecurityPolicyChildSrc() {
- return "child-src chrome-search://most-visited;";
+ return content::URLDataSource::GetContentSecurityPolicy(directive);
}
NewTabUI::NewTabHTMLSource::~NewTabHTMLSource() {}
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 97e6443b656..fe04e036f11 100644
--- a/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h
+++ b/chromium/chrome/browser/ui/webui/ntp/new_tab_ui.h
@@ -62,10 +62,8 @@ class NewTabUI : public content::WebUIController {
content::URLDataSource::GotDataCallback callback) 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;
+ std::string GetContentSecurityPolicy(
+ network::mojom::CSPDirectiveName directive) override;
private:
// Pointer back to the original profile.
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 f796da4afea..89cd233b135 100644
--- a/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc
+++ b/chromium/chrome/browser/ui/webui/ntp/ntp_resource_cache.cc
@@ -98,8 +98,8 @@ SkColor GetThemeColor(const ui::ThemeProvider& tp, int id) {
// If web contents are being inverted because the system is in high-contrast
// mode, any system theme colors we use must be inverted too to cancel out.
return ui::NativeTheme::GetInstanceForNativeUi()
- ->GetHighContrastColorScheme() ==
- ui::NativeTheme::HighContrastColorScheme::kDark
+ ->GetPlatformHighContrastColorScheme() ==
+ ui::NativeTheme::PlatformHighContrastColorScheme::kDark
? color_utils::InvertColor(color)
: color;
}
@@ -295,6 +295,13 @@ void NTPResourceCache::CreateNewTabIncognitoHTML() {
? "true"
: "false";
+ // Ensure passing off-the-record profile; |profile_| is not an OTR profile.
+ DCHECK(!profile_->IsOffTheRecord());
+ DCHECK(profile_->HasPrimaryOTRProfile());
+ CookieControlsService* cookie_controls_service =
+ CookieControlsServiceFactory::GetForProfile(
+ profile_->GetPrimaryOTRProfile());
+
replacements["incognitoTabDescription"] =
l10n_util::GetStringUTF8(IDS_NEW_TAB_OTR_SUBTITLE);
replacements["incognitoTabHeading"] =
@@ -308,29 +315,18 @@ void NTPResourceCache::CreateNewTabIncognitoHTML() {
replacements["learnMoreLink"] = kLearnMoreIncognitoUrl;
replacements["title"] = l10n_util::GetStringUTF8(IDS_NEW_TAB_TITLE);
replacements["hideCookieControls"] =
- CookieControlsServiceFactory::GetForProfile(profile_)
- ->ShouldHideCookieControlsUI()
- ? "hidden"
- : "";
+ cookie_controls_service->ShouldHideCookieControlsUI() ? "hidden" : "";
replacements["cookieControlsTitle"] =
l10n_util::GetStringUTF8(IDS_NEW_TAB_OTR_THIRD_PARTY_COOKIE);
replacements["cookieControlsDescription"] =
l10n_util::GetStringUTF8(IDS_NEW_TAB_OTR_THIRD_PARTY_COOKIE_SUBLABEL);
- // Ensure passing off-the-record profile; |profile_| might not be incognito.
- DCHECK(profile_->HasPrimaryOTRProfile());
replacements["cookieControlsToggleChecked"] =
- CookieControlsServiceFactory::GetForProfile(
- profile_->GetPrimaryOTRProfile())
- ->GetToggleCheckedValue()
- ? "checked"
- : "";
+ cookie_controls_service->GetToggleCheckedValue() ? "checked" : "";
replacements["hideTooltipIcon"] =
- CookieControlsServiceFactory::GetForProfile(profile_)
- ->ShouldEnforceCookieControls()
- ? ""
- : "hidden";
+ cookie_controls_service->ShouldEnforceCookieControls() ? "" : "hidden";
replacements["cookieControlsToolTipIcon"] =
- CookieControlsHandler::GetEnforcementIcon(profile_);
+ CookieControlsHandler::GetEnforcementIcon(
+ cookie_controls_service->GetCookieControlsEnforcement());
replacements["cookieControlsTooltipText"] = l10n_util::GetStringUTF8(
IDS_NEW_TAB_OTR_COOKIE_CONTROLS_CONTROLLED_TOOLTIP_TEXT);
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 c2a62bd570c..96de4f8d4c8 100644
--- a/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/ntp_tiles_internals_ui.cc
@@ -29,6 +29,7 @@
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
namespace {
@@ -125,7 +126,8 @@ void ChromeNTPTilesInternalsMessageHandlerClient::CallJavascriptFunctionVector(
content::WebUIDataSource* CreateNTPTilesInternalsHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUINTPTilesInternalsHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
source->AddResourcePath("ntp_tiles_internals.js", IDR_NTP_TILES_INTERNALS_JS);
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 c6e3c553d56..bb23cde4f20 100644
--- a/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc
+++ b/chromium/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc
@@ -128,7 +128,7 @@ template <>
struct TypeConverter<mojom::AutocompleteMatchPtr, AutocompleteMatch> {
static mojom::AutocompleteMatchPtr Convert(const AutocompleteMatch& input) {
mojom::AutocompleteMatchPtr result(mojom::AutocompleteMatch::New());
- if (input.provider != NULL) {
+ if (input.provider) {
result->provider_name = std::string(input.provider->GetName());
result->provider_done = input.provider->done();
}
@@ -162,7 +162,7 @@ struct TypeConverter<mojom::AutocompleteMatchPtr, AutocompleteMatch> {
result->type = AutocompleteMatchType::ToString(input.type);
result->is_search_type = AutocompleteMatch::IsSearchType(input.type);
result->has_tab_match = input.has_tab_match;
- if (input.associated_keyword.get() != NULL) {
+ if (input.associated_keyword.get()) {
result->associated_keyword =
base::UTF16ToUTF8(input.associated_keyword->keyword);
}
diff --git a/chromium/chrome/browser/ui/webui/policy_ui.cc b/chromium/chrome/browser/ui/webui/policy_ui.cc
index 7509acf1b70..13d09970fe3 100644
--- a/chromium/chrome/browser/ui/webui/policy_ui.cc
+++ b/chromium/chrome/browser/ui/webui/policy_ui.cc
@@ -25,6 +25,7 @@ content::WebUIDataSource* CreatePolicyUIHtmlSource() {
static constexpr webui::LocalizedString kStrings[] = {
// Localized strings (alphabetical order).
+ {"copyPoliciesJSON", IDS_COPY_POLICIES_JSON},
{"exportPoliciesJSON", IDS_EXPORT_POLICIES_JSON},
{"filterPlaceholder", IDS_POLICY_FILTER_PLACEHOLDER},
{"hideExpandedStatus", IDS_POLICY_HIDE_EXPANDED_STATUS},
@@ -57,6 +58,7 @@ content::WebUIDataSource* CreatePolicyUIHtmlSource() {
{"noPoliciesSet", IDS_POLICY_NO_POLICIES_SET},
{"offHoursActive", IDS_POLICY_OFFHOURS_ACTIVE},
{"offHoursNotActive", IDS_POLICY_OFFHOURS_NOT_ACTIVE},
+ {"policyCopyValue", IDS_POLICY_COPY_VALUE},
{"policiesPushOff", IDS_POLICY_PUSH_POLICIES_OFF},
{"policiesPushOn", IDS_POLICY_PUSH_POLICIES_ON},
{"policyLearnMore", IDS_POLICY_LEARN_MORE},
@@ -91,5 +93,4 @@ PolicyUI::PolicyUI(content::WebUI* web_ui) : WebUIController(web_ui) {
CreatePolicyUIHtmlSource());
}
-PolicyUI::~PolicyUI() {
-}
+PolicyUI::~PolicyUI() = default;
diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc
index d649be05f2f..9efd2c88830 100644
--- a/chromium/chrome/browser/ui/webui/policy_ui_handler.cc
+++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.cc
@@ -68,6 +68,8 @@
#include "content/public/browser/web_contents.h"
#include "extensions/buildflags/buildflags.h"
#include "google_apis/gaia/gaia_auth_util.h"
+#include "ui/base/clipboard/clipboard_buffer.h"
+#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/time_format.h"
#include "ui/base/webui/web_ui_util.h"
@@ -564,6 +566,9 @@ void MachineLevelUserCloudPolicyStatusProvider::GetStatus(
refresh_scheduler ? refresh_scheduler->GetActualRefreshDelay()
: policy::CloudPolicyRefreshScheduler::
kDefaultRefreshDelayMs)));
+ dict->SetBoolean(
+ "policiesPushAvailable",
+ refresh_scheduler ? refresh_scheduler->invalidations_available() : false);
if (dmTokenStorage) {
dict->SetString("enrollmentToken",
@@ -810,6 +815,7 @@ void PolicyUIHandler::AddCommonLocalizedStringsToSource(
{"levelRecommended", IDS_POLICY_LEVEL_RECOMMENDED},
{"error", IDS_POLICY_LABEL_ERROR},
{"deprecated", IDS_POLICY_LABEL_DEPRECATED},
+ {"future", IDS_POLICY_LABEL_FUTURE},
{"ignored", IDS_POLICY_LABEL_IGNORED},
{"notSpecified", IDS_POLICY_NOT_SPECIFIED},
{"ok", IDS_POLICY_OK},
@@ -939,6 +945,10 @@ void PolicyUIHandler::RegisterMessages() {
"reloadPolicies",
base::BindRepeating(&PolicyUIHandler::HandleReloadPolicies,
base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "copyPoliciesJSON",
+ base::BindRepeating(&PolicyUIHandler::HandleCopyPoliciesJson,
+ base::Unretained(this)));
}
#if BUILDFLAG(ENABLE_EXTENSIONS)
@@ -1178,13 +1188,13 @@ void PolicyUIHandler::HandleReloadPolicies(const base::ListValue* args) {
&PolicyUIHandler::OnRefreshPoliciesDone, weak_factory_.GetWeakPtr()));
}
-void DoWritePoliciesToJSONFile(const base::FilePath& path,
- const std::string& data) {
- base::WriteFile(path, data.c_str(), data.size());
+void PolicyUIHandler::HandleCopyPoliciesJson(const base::ListValue* args) {
+ std::string policies_json = GetPoliciesAsJson();
+ ui::ScopedClipboardWriter scw(ui::ClipboardBuffer::kCopyPaste);
+ scw.WriteText(base::UTF8ToUTF16(policies_json));
}
-void PolicyUIHandler::WritePoliciesToJSONFile(
- const base::FilePath& path) const {
+std::string PolicyUIHandler::GetPoliciesAsJson() const {
auto client = std::make_unique<policy::ChromePolicyConversionsClient>(
web_ui()->GetWebContents()->GetBrowserContext());
base::Value dict =
@@ -1241,6 +1251,17 @@ void PolicyUIHandler::WritePoliciesToJSONFile(
base::JSONWriter::WriteWithOptions(
dict, base::JSONWriter::OPTIONS_PRETTY_PRINT, &json_policies);
+ return json_policies;
+}
+
+void DoWritePoliciesToJSONFile(const base::FilePath& path,
+ const std::string& data) {
+ base::WriteFile(path, data.c_str(), data.size());
+}
+
+void PolicyUIHandler::WritePoliciesToJSONFile(
+ const base::FilePath& path) const {
+ std::string json_policies = GetPoliciesAsJson();
base::ThreadPool::PostTask(
FROM_HERE,
{base::MayBlock(), base::TaskPriority::BEST_EFFORT,
diff --git a/chromium/chrome/browser/ui/webui/policy_ui_handler.h b/chromium/chrome/browser/ui/webui/policy_ui_handler.h
index e73ced252f6..58401981694 100644
--- a/chromium/chrome/browser/ui/webui/policy_ui_handler.h
+++ b/chromium/chrome/browser/ui/webui/policy_ui_handler.h
@@ -89,6 +89,7 @@ class PolicyUIHandler : public content::WebUIMessageHandler,
void HandleExportPoliciesJson(const base::ListValue* args);
void HandleListenPoliciesUpdates(const base::ListValue* args);
void HandleReloadPolicies(const base::ListValue* args);
+ void HandleCopyPoliciesJson(const base::ListValue* args);
// Send information about the current policy values to the UI. For each policy
// whose value has been set, a dictionary containing the value and additional
@@ -106,6 +107,9 @@ class PolicyUIHandler : public content::WebUIMessageHandler,
// information is sent.
void SendStatus();
+ // Build a JSON string of all the policies.
+ std::string GetPoliciesAsJson() const;
+
void WritePoliciesToJSONFile(const base::FilePath& path) const;
void OnRefreshPoliciesDone();
diff --git a/chromium/chrome/browser/ui/webui/predictors/predictors_handler.cc b/chromium/chrome/browser/ui/webui/predictors/predictors_handler.cc
index 366c9e40cb3..dea6997da32 100644
--- a/chromium/chrome/browser/ui/webui/predictors/predictors_handler.cc
+++ b/chromium/chrome/browser/ui/webui/predictors/predictors_handler.cc
@@ -46,7 +46,7 @@ void PredictorsHandler::RegisterMessages() {
void PredictorsHandler::RequestAutocompleteActionPredictorDb(
const base::ListValue* args) {
- const bool enabled = (autocomplete_action_predictor_ != NULL);
+ const bool enabled = !!autocomplete_action_predictor_;
base::DictionaryValue dict;
dict.SetBoolean("enabled", enabled);
if (enabled) {
diff --git a/chromium/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc b/chromium/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc
index 1ee0076b9c6..879004c790d 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc
+++ b/chromium/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc
@@ -36,7 +36,8 @@ void FakePrintRenderFrame::PrintPreview(base::Value settings) {}
void FakePrintRenderFrame::OnPrintPreviewDialogClosed() {}
void FakePrintRenderFrame::PrintFrameContent(
- mojom::PrintFrameContentParamsPtr params) {}
+ mojom::PrintFrameContentParamsPtr params,
+ PrintFrameContentCallback callback) {}
void FakePrintRenderFrame::PrintingDone(bool success) {}
diff --git a/chromium/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h b/chromium/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h
index 2bd75746885..10f46664d83 100644
--- a/chromium/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h
+++ b/chromium/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h
@@ -33,7 +33,8 @@ class FakePrintRenderFrame : public mojom::PrintRenderFrame {
bool has_selection) override;
void PrintPreview(base::Value settings) override;
void OnPrintPreviewDialogClosed() override;
- void PrintFrameContent(mojom::PrintFrameContentParamsPtr params) override;
+ void PrintFrameContent(mojom::PrintFrameContentParamsPtr params,
+ PrintFrameContentCallback callback) override;
void PrintingDone(bool success) override;
void SetPrintingEnabled(bool enabled) override;
void PrintNodeUnderContextMenu() override;
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 13b13ff3ae5..3ea4c1a66ac 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
@@ -13,7 +13,6 @@
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
@@ -162,8 +161,8 @@ void LocalPrinterHandlerChromeos::GetDefaultPrinter(DefaultPrinterCallback cb) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// TODO(crbug.com/660898): Add default printers to ChromeOS.
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(std::move(cb), ""));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(std::move(cb), ""));
}
void LocalPrinterHandlerChromeos::StartGetPrinters(
@@ -197,8 +196,8 @@ void LocalPrinterHandlerChromeos::StartGetCapability(
printers_manager_->GetPrinter(printer_name);
if (!printer) {
// If the printer was removed, the lookup will fail.
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(std::move(cb), base::Value()));
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(std::move(cb), base::Value()));
return;
}
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 89955ca893c..5f148db042a 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
@@ -47,9 +47,8 @@ scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
#elif defined(OS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
- return base::CreateSingleThreadTaskRunner({content::BrowserThread::UI,
- base::MayBlock(),
- base::TaskPriority::USER_VISIBLE});
+ return content::GetUIThreadTaskRunner(
+ {base::MayBlock(), base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
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 deefb421385..a61439ed8ca 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
@@ -83,7 +83,7 @@
#include "chrome/browser/device_identity/device_oauth2_token_service_factory.h"
#include "chrome/browser/ui/settings_window_manager_chromeos.h"
#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h"
-#include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h"
+#include "chrome/browser/ui/webui/signin/inline_login_dialog_chromeos.h"
#include "chromeos/printing/printer_configuration.h"
#include "components/signin/public/identity_manager/scope_set.h"
#endif
@@ -802,9 +802,8 @@ void PrintPreviewHandler::HandleSignin(const base::ListValue* args) {
// account management flows will go through native UIs and not through a
// tabbed browser window.
if (add_account) {
- chromeos::InlineLoginHandlerDialogChromeOS::Show(
- chromeos::InlineLoginHandlerDialogChromeOS::Source::
- kPrintPreviewDialog);
+ chromeos::InlineLoginDialogChromeOS::Show(
+ chromeos::InlineLoginDialogChromeOS::Source::kPrintPreviewDialog);
} else {
chrome::SettingsWindowManager::GetInstance()->ShowOSSettings(
profile, chromeos::settings::mojom::kMyAccountsSubpagePath);
@@ -1385,19 +1384,21 @@ void PrintPreviewHandler::SendManipulateSettingsForTest(
#if defined(OS_CHROMEOS)
void PrintPreviewHandler::HandleRequestPrinterStatusUpdate(
const base::ListValue* args) {
- CHECK_EQ(1U, args->GetList().size());
+ CHECK_EQ(2U, args->GetSize());
+
+ const std::string& callback_id = args->GetList()[0].GetString();
+ const std::string& printer_id = args->GetList()[1].GetString();
+
PrinterHandler* handler = GetPrinterHandler(PrinterType::kLocal);
handler->StartPrinterStatusRequest(
- args->GetList()[0].GetString(),
- base::BindOnce(&PrintPreviewHandler::OnPrinterStatusUpdated,
- weak_factory_.GetWeakPtr()));
+ printer_id, base::BindOnce(&PrintPreviewHandler::OnPrinterStatusUpdated,
+ weak_factory_.GetWeakPtr(), callback_id));
}
void PrintPreviewHandler::OnPrinterStatusUpdated(
+ const std::string& callback_id,
const base::Value& cups_printer_status) {
- // "printer-status-update" will also trigger non-PrintPreview UI for
- // consuming fresh printer statuses.
- FireWebUIListener("printer-status-update", cups_printer_status);
+ ResolveJavascriptCallback(base::Value(callback_id), cups_printer_status);
}
#endif
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 0250e8bca9b..735f18a95e7 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
@@ -315,8 +315,9 @@ class PrintPreviewHandler : public content::WebUIMessageHandler,
// Called to initiate a status request for a printer.
void HandleRequestPrinterStatusUpdate(const base::ListValue* args);
- // Invokes Web UI Listener "printer-status-update" with new printer status.
- void OnPrinterStatusUpdated(const base::Value& cups_printer_status);
+ // Resolves callback with printer status.
+ void OnPrinterStatusUpdated(const std::string& callback_id,
+ const base::Value& cups_printer_status);
#endif
// A count of how many requests received to regenerate preview data.
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 43cddc1495e..1d226233cce 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
@@ -25,11 +25,11 @@
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
-#include "base/task/post_task.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
+#include "chrome/browser/pdf/pdf_extension_util.h"
#include "chrome/browser/printing/background_printing_manager.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/print_preview_data_service.h"
@@ -37,6 +37,7 @@
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/webui/metrics_handler.h"
+#include "chrome/browser/ui/webui/plural_string_handler.h"
#include "chrome/browser/ui/webui/print_preview/print_preview_handler.h"
#include "chrome/browser/ui/webui/theme_source.h"
#include "chrome/browser/ui/webui/webui_util.h"
@@ -46,6 +47,7 @@
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/component_extension_resources.h"
#include "chrome/grit/generated_resources.h"
+#include "chrome/grit/print_preview_pdf_resources.h"
#include "chrome/grit/print_preview_resources.h"
#include "chrome/grit/print_preview_resources_map.h"
#include "chromeos/constants/chromeos_features.h"
@@ -59,8 +61,9 @@
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui_data_source.h"
#include "extensions/common/constants.h"
-#include "printing/page_size_margins.h"
+#include "printing/mojom/print.mojom.h"
#include "printing/print_job_constants.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/gfx/geometry/rect.h"
@@ -77,7 +80,6 @@
#include "chrome/browser/ui/webui/managed_ui_handler.h"
#endif
-using content::BrowserThread;
using content::WebContents;
namespace printing {
@@ -106,8 +108,8 @@ void StopWorker(int document_cookie) {
std::unique_ptr<PrinterQuery> printer_query =
queue->PopPrinterQuery(document_cookie);
if (printer_query) {
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query)));
}
}
@@ -290,12 +292,6 @@ void AddPrintPreviewStrings(content::WebUIDataSource* source) {
{"printButton", IDS_PRINT_PREVIEW_PRINT_BUTTON},
{"printDestinationsTitle", IDS_PRINT_PREVIEW_PRINT_DESTINATIONS_TITLE},
{"printPagesLabel", IDS_PRINT_PREVIEW_PRINT_PAGES_LABEL},
- {"printPreviewPageLabelPlural", IDS_PRINT_PREVIEW_PAGE_LABEL_PLURAL},
- {"printPreviewPageLabelSingular", IDS_PRINT_PREVIEW_PAGE_LABEL_SINGULAR},
- {"printPreviewSheetsLabelPlural", IDS_PRINT_PREVIEW_SHEETS_LABEL_PLURAL},
- {"printPreviewSheetsLabelSingular",
- IDS_PRINT_PREVIEW_SHEETS_LABEL_SINGULAR},
- {"printPreviewSummaryFormatShort", IDS_PRINT_PREVIEW_SUMMARY_FORMAT_SHORT},
{"printToGoogleDrive", IDS_PRINT_PREVIEW_PRINT_TO_GOOGLE_DRIVE},
{"printToPDF", IDS_PRINT_PREVIEW_PRINT_TO_PDF},
{"printerSharingInviteText", IDS_PRINT_PREVIEW_INVITE_TEXT},
@@ -331,9 +327,25 @@ void AddPrintPreviewStrings(content::WebUIDataSource* source) {
{"pinErrorMessage", IDS_PRINT_PREVIEW_PIN_ERROR_MESSAGE},
{"pinPlaceholder", IDS_PRINT_PREVIEW_PIN_PLACEHOLDER},
{"printerEulaURL", IDS_PRINT_PREVIEW_EULA_URL},
- {"sheetsLimitErrorMessage", IDS_PRINT_PREVIEW_SHEETS_LIMIT_ERROR_MESSAGE},
- {"sheetsLimitLabelSingular", IDS_PRINT_PREVIEW_SHEETS_LIMIT_LABEL_SINGULAR},
- {"sheetsLimitLabelPlural", IDS_PRINT_PREVIEW_SHEETS_LIMIT_LABEL_PLURAL},
+ {"printerStatusConnectingToDevice",
+ IDS_PRINT_PREVIEW_PRINTER_STATUS_CONNECTING_TO_DEVICE},
+ {"printerStatusDeviceError", IDS_PRINT_PREVIEW_PRINTER_STATUS_DEVICE_ERROR},
+ {"printerStatusDoorOpen", IDS_PRINT_PREVIEW_PRINTER_STATUS_DOOR_OPEN},
+ {"printerStatusLowOnInk", IDS_PRINT_PREVIEW_PRINTER_STATUS_LOW_ON_INK},
+ {"printerStatusLowOnPaper", IDS_PRINT_PREVIEW_PRINTER_STATUS_LOW_ON_PAPER},
+ {"printerStatusOutOfInk", IDS_PRINT_PREVIEW_PRINTER_STATUS_OUT_OF_INK},
+ {"printerStatusOutOfPaper", IDS_PRINT_PREVIEW_PRINTER_STATUS_OUT_OF_PAPER},
+ {"printerStatusOutputAlmostFull",
+ IDS_PRINT_PREVIEW_PRINTER_STATUS_OUPUT_ALMOST_FULL},
+ {"printerStatusOutputFull", IDS_PRINT_PREVIEW_PRINTER_STATUS_OUPUT_FULL},
+ {"printerStatusPaperJam", IDS_PRINT_PREVIEW_PRINTER_STATUS_PAPER_JAM},
+ {"printerStatusPaused", IDS_PRINT_PREVIEW_PRINTER_STATUS_PAUSED},
+ {"printerStatusPrinterQueueFull",
+ IDS_PRINT_PREVIEW_PRINTER_STATUS_PRINTER_QUEUE_FULL},
+ {"printerStatusPrinterUnreachable",
+ IDS_PRINT_PREVIEW_PRINTER_STATUS_PRINTER_UNREACHABLE},
+ {"printerStatusStopped", IDS_PRINT_PREVIEW_PRINTER_STATUS_STOPPED},
+ {"printerStatusTrayMissing", IDS_PRINT_PREVIEW_PRINTER_STATUS_TRAY_MISSING},
#endif
#if defined(OS_MACOSX)
{"openPdfInPreviewOption", IDS_PRINT_PREVIEW_OPEN_PDF_IN_PREVIEW_APP},
@@ -351,6 +363,13 @@ void AddPrintPreviewStrings(content::WebUIDataSource* source) {
l10n_util::GetStringFUTF16(
IDS_PRINT_PREVIEW_SYSTEM_DIALOG_OPTION, shortcut_text));
#endif
+
+ // Register strings for the PDF viewer, so that $i18n{} replacements work.
+ base::Value pdf_strings(base::Value::Type::DICTIONARY);
+ pdf_extension_util::AddStrings(
+ pdf_extension_util::PdfViewerContext::kPrintPreview, &pdf_strings);
+ pdf_extension_util::AddAdditionalData(&pdf_strings);
+ source->AddLocalizedStrings(base::Value::AsDictionaryValue(pdf_strings));
}
void AddPrintPreviewFlags(content::WebUIDataSource* source, Profile* profile) {
@@ -381,39 +400,41 @@ void AddPrintPreviewFlags(content::WebUIDataSource* source, Profile* profile) {
void SetupPrintPreviewPlugin(content::WebUIDataSource* source) {
static constexpr webui::ResourcePath kPdfResources[] = {
- {"pdf/bookmark_type.js", IDR_PDF_BOOKMARK_TYPE_JS},
- {"pdf/browser_api.js", IDR_PDF_BROWSER_API_JS},
- {"pdf/constants.js", IDR_PDF_CONSTANTS_JS},
- {"pdf/controller.js", IDR_PDF_CONTROLLER_JS},
- {"pdf/elements/icons.js", IDR_PDF_ICONS_JS},
- {"pdf/elements/shared-vars.js", IDR_PDF_SHARED_VARS_JS},
- {"pdf/elements/viewer-error-screen.js", IDR_PDF_VIEWER_ERROR_SCREEN_JS},
- {"pdf/elements/viewer-page-indicator.js",
- IDR_PRINT_PREVIEW_PDF_VIEWER_PAGE_INDICATOR_JS},
- {"pdf/elements/viewer-zoom-button.js", IDR_PDF_VIEWER_ZOOM_BUTTON_JS},
- {"pdf/elements/viewer-zoom-toolbar.js", IDR_PDF_VIEWER_ZOOM_SELECTOR_JS},
- {"pdf/gesture_detector.js", IDR_PDF_GESTURE_DETECTOR_JS},
- {"pdf/index.css", IDR_PDF_INDEX_CSS},
- {"pdf/index.html", IDR_PRINT_PREVIEW_PDF_INDEX_PP_HTML},
- {"pdf/main_pp.js", IDR_PRINT_PREVIEW_PDF_MAIN_PP_JS},
- {"pdf/main_util.js", IDR_PDF_MAIN_UTIL_JS},
- {"pdf/metrics.js", IDR_PDF_METRICS_JS},
- {"pdf/navigator.js", IDR_PDF_NAVIGATOR_JS},
- {"pdf/open_pdf_params_parser.js", IDR_PDF_OPEN_PDF_PARAMS_PARSER_JS},
- {"pdf/pdf_scripting_api.js", IDR_PDF_PDF_SCRIPTING_API_JS},
- {"pdf/pdf_viewer.js", IDR_PDF_PDF_VIEWER_JS},
- {"pdf/toolbar_manager.js", IDR_PDF_TOOLBAR_MANAGER_JS},
- {"pdf/viewport.js", IDR_PDF_VIEWPORT_JS},
- {"pdf/viewport_scroller.js", IDR_PDF_VIEWPORT_SCROLLER_JS},
- {"pdf/zoom_manager.js", IDR_PDF_ZOOM_MANAGER_JS},
+ {"pdf/browser_api.js", IDR_PDF_BROWSER_API_JS},
+ {"pdf/constants.js", IDR_PDF_CONSTANTS_JS},
+ {"pdf/controller.js", IDR_PDF_CONTROLLER_JS},
+ {"pdf/elements/icons.js", IDR_PDF_ICONS_JS},
+ {"pdf/elements/shared-vars.js", IDR_PDF_SHARED_VARS_JS},
+ {"pdf/elements/viewer-error-screen.js", IDR_PDF_VIEWER_ERROR_SCREEN_JS},
+ {"pdf/elements/viewer-page-indicator.js",
+ IDR_PRINT_PREVIEW_PDF_VIEWER_PAGE_INDICATOR_JS},
+ {"pdf/elements/viewer-zoom-button.js", IDR_PDF_VIEWER_ZOOM_BUTTON_JS},
+ {"pdf/elements/viewer-zoom-toolbar.js", IDR_PDF_VIEWER_ZOOM_SELECTOR_JS},
+ {"pdf/gesture_detector.js", IDR_PDF_GESTURE_DETECTOR_JS},
+ {"pdf/index.css", IDR_PDF_INDEX_CSS},
+ {"pdf/index.html", IDR_PRINT_PREVIEW_PDF_INDEX_PP_HTML},
+ {"pdf/main.js", IDR_PDF_MAIN_JS},
+ {"pdf/metrics.js", IDR_PDF_METRICS_JS},
+ {"pdf/open_pdf_params_parser.js", IDR_PDF_OPEN_PDF_PARAMS_PARSER_JS},
+ {"pdf/pdf_scripting_api.js", IDR_PDF_PDF_SCRIPTING_API_JS},
+ {"pdf/pdf_viewer_base.js", IDR_PDF_PDF_VIEWER_BASE_JS},
+ {"pdf/pdf_viewer.js", IDR_PRINT_PREVIEW_PDF_PDF_VIEWER_PP_JS},
+ {"pdf/pdf_viewer_shared_style.js", IDR_PDF_PDF_VIEWER_SHARED_STYLE_JS},
+ {"pdf/pdf_viewer_utils.js", IDR_PDF_PDF_VIEWER_UTILS_JS},
+ {"pdf/toolbar_manager.js", IDR_PDF_TOOLBAR_MANAGER_JS},
+ {"pdf/viewport.js", IDR_PDF_VIEWPORT_JS},
+ {"pdf/viewport_scroller.js", IDR_PDF_VIEWPORT_SCROLLER_JS},
+ {"pdf/zoom_manager.js", IDR_PDF_ZOOM_MANAGER_JS},
};
webui::AddResourcePathsBulk(source, kPdfResources);
source->SetRequestFilter(base::BindRepeating(&ShouldHandleRequestCallback),
base::BindRepeating(&HandleRequestCallback));
- source->OverrideContentSecurityPolicyChildSrc("child-src 'self';");
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ChildSrc, "child-src 'self';");
source->DisableDenyXFrameOptions();
- source->OverrideContentSecurityPolicyObjectSrc("object-src 'self';");
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ObjectSrc, "object-src 'self';");
}
content::WebUIDataSource* CreatePrintPreviewUISource(Profile* profile) {
@@ -440,6 +461,19 @@ PrintPreviewHandler* CreatePrintPreviewHandlers(content::WebUI* web_ui) {
PrintPreviewHandler* handler_ptr = handler.get();
web_ui->AddMessageHandler(std::move(handler));
web_ui->AddMessageHandler(std::make_unique<MetricsHandler>());
+
+ // Add a handler to provide pluralized strings.
+ auto plural_string_handler = std::make_unique<PluralStringHandler>();
+ plural_string_handler->AddLocalizedString(
+ "printPreviewPageSummaryLabel", IDS_PRINT_PREVIEW_PAGE_SUMMARY_LABEL);
+ plural_string_handler->AddLocalizedString(
+ "printPreviewSheetSummaryLabel", IDS_PRINT_PREVIEW_SHEET_SUMMARY_LABEL);
+#if defined(OS_CHROMEOS)
+ plural_string_handler->AddLocalizedString(
+ "sheetsLimitErrorMessage", IDS_PRINT_PREVIEW_SHEETS_LIMIT_ERROR_MESSAGE);
+#endif
+ web_ui->AddMessageHandler(std::move(plural_string_handler));
+
return handler_ptr;
}
@@ -624,10 +658,6 @@ void PrintPreviewUI::OnInitiatorClosed() {
}
}
-void PrintPreviewUI::OnPrintPreviewCancelled(int request_id) {
- handler_->OnPrintPreviewCancelled(request_id);
-}
-
void PrintPreviewUI::OnPrintPreviewRequest(int request_id) {
if (!initial_preview_start_time_.is_null()) {
base::UmaHistogramTimes(
@@ -638,7 +668,7 @@ void PrintPreviewUI::OnPrintPreviewRequest(int request_id) {
}
void PrintPreviewUI::OnDidStartPreview(
- const PrintHostMsg_DidStartPreview_Params& params,
+ const mojom::DidStartPreviewParams& params,
int request_id) {
DCHECK_GT(params.page_count, 0);
DCHECK(!params.pages_to_render.empty());
@@ -656,7 +686,7 @@ void PrintPreviewUI::OnDidStartPreview(
}
void PrintPreviewUI::OnDidGetDefaultPageLayout(
- const PageSizeMargins& page_layout,
+ const mojom::PageSizeMargins& page_layout,
const gfx::Rect& printable_area,
bool has_custom_page_size_style,
int request_id) {
@@ -729,10 +759,6 @@ void PrintPreviewUI::OnPrintPreviewFailed(int request_id) {
handler_->OnPrintPreviewFailed(request_id);
}
-void PrintPreviewUI::OnInvalidPrinterSettings(int request_id) {
- handler_->OnInvalidPrinterSettings(request_id);
-}
-
void PrintPreviewUI::OnHidePreviewDialog() {
WebContents* preview_dialog = web_ui()->GetWebContents();
BackgroundPrintingManager* background_printing_manager =
@@ -776,6 +802,19 @@ void PrintPreviewUI::PrintPreviewFailed(int32_t document_cookie,
OnPrintPreviewFailed(request_id);
}
+void PrintPreviewUI::PrintPreviewCancelled(int32_t document_cookie,
+ int32_t request_id) {
+ // Always need to stop the worker.
+ StopWorker(document_cookie);
+ handler_->OnPrintPreviewCancelled(request_id);
+}
+
+void PrintPreviewUI::PrinterSettingsInvalid(int32_t document_cookie,
+ int32_t request_id) {
+ StopWorker(document_cookie);
+ handler_->OnInvalidPrinterSettings(request_id);
+}
+
// static
void PrintPreviewUI::SetDelegateForTesting(TestDelegate* delegate) {
g_test_delegate = delegate;
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 89ade79356c..32bc87ad8a1 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
@@ -21,10 +21,10 @@
#include "chrome/browser/ui/webui/constrained_web_dialog_ui.h"
#include "components/printing/common/print.mojom.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
+#include "printing/mojom/print.mojom-forward.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
-struct PrintHostMsg_DidStartPreview_Params;
struct PrintHostMsg_PreviewIds;
struct PrintHostMsg_RequestPrintPreview_Params;
@@ -41,7 +41,6 @@ class Rect;
namespace printing {
class PrintPreviewHandler;
-struct PageSizeMargins;
class PrintPreviewUI : public ConstrainedWebDialogUI,
public mojom::PrintPreviewUI {
@@ -62,6 +61,10 @@ class PrintPreviewUI : public ConstrainedWebDialogUI,
void SetOptionsFromDocument(const mojom::OptionsFromDocumentParamsPtr params,
int32_t request_id) override;
void PrintPreviewFailed(int32_t document_cookie, int32_t request_id) override;
+ void PrintPreviewCancelled(int32_t document_cookie,
+ int32_t request_id) override;
+ void PrinterSettingsInvalid(int32_t document_cookie,
+ int32_t request_id) override;
bool IsBound() const;
@@ -138,12 +141,12 @@ class PrintPreviewUI : public ConstrainedWebDialogUI,
virtual void OnPrintPreviewRequest(int request_id);
// Notifies the Web UI about the properties of the request preview.
- void OnDidStartPreview(const PrintHostMsg_DidStartPreview_Params& params,
+ void OnDidStartPreview(const mojom::DidStartPreviewParams& params,
int request_id);
// Notifies the Web UI of the default page layout according to the currently
// selected printer and page size.
- void OnDidGetDefaultPageLayout(const PageSizeMargins& page_layout,
+ void OnDidGetDefaultPageLayout(const mojom::PageSizeMargins& page_layout,
const gfx::Rect& printable_area,
bool has_custom_page_size_style,
int request_id);
@@ -172,18 +175,10 @@ class PrintPreviewUI : public ConstrainedWebDialogUI,
// closed, which may occur for several reasons, e.g. tab closure or crash.
void OnPrintPreviewDialogClosed();
- // Notifies the Web UI that the preview request identified by |request_id|
- // was cancelled.
- void OnPrintPreviewCancelled(int request_id);
-
// Notifies the Web UI that initiator is closed, so we can disable all the
// controls that need the initiator for generating the preview data.
void OnInitiatorClosed();
- // Notifies the Web UI that the printer is unavailable or its settings are
- // invalid. |request_id| is the preview request id with the invalid printer.
- void OnInvalidPrinterSettings(int request_id);
-
// Notifies the Web UI to cancel the pending preview request.
virtual void OnCancelPendingPreviewRequest();
diff --git a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.cc b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.cc
index 22ea3e49882..ea3df0ae1a1 100644
--- a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.cc
+++ b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.cc
@@ -7,23 +7,37 @@
#include <string>
#include "base/bind.h"
-#include "base/bind_helpers.h"
+#include "base/feature_list.h"
#include "base/values.h"
+#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/quota_internals/quota_internals_proxy.h"
#include "chrome/browser/ui/webui/quota_internals/quota_internals_types.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_ui.h"
+#include "content/public/common/content_features.h"
using content::BrowserContext;
+namespace {
+
+bool IsStoragePressureEnabled() {
+#if defined(OS_ANDROID)
+ return false;
+#else
+ return base::FeatureList::IsEnabled(features::kStoragePressureUI);
+#endif
+}
+
+} // namespace
+
namespace quota_internals {
QuotaInternalsHandler::QuotaInternalsHandler() {}
QuotaInternalsHandler::~QuotaInternalsHandler() {
if (proxy_.get())
- proxy_->handler_ = NULL;
+ proxy_->handler_ = nullptr;
}
void QuotaInternalsHandler::RegisterMessages() {
@@ -75,6 +89,13 @@ void QuotaInternalsHandler::ReportStatistics(const Statistics& stats) {
SendMessage("StatisticsUpdated", dict);
}
+void QuotaInternalsHandler::ReportStoragePressureFlag() {
+ base::DictionaryValue flag_enabled;
+ flag_enabled.SetBoolean("isStoragePressureEnabled",
+ IsStoragePressureEnabled());
+ SendMessage("StoragePressureFlagUpdated", flag_enabled);
+}
+
void QuotaInternalsHandler::SendMessage(const std::string& message,
const base::Value& value) {
web_ui()->CallJavascriptFunctionUnsafe("cr.quota.messageHandler",
@@ -84,6 +105,7 @@ void QuotaInternalsHandler::SendMessage(const std::string& message,
void QuotaInternalsHandler::OnRequestInfo(const base::ListValue*) {
if (!proxy_.get())
proxy_ = new QuotaInternalsProxy(this);
+ ReportStoragePressureFlag();
proxy_->RequestInfo(
BrowserContext::GetDefaultStoragePartition(
Profile::FromWebUI(web_ui()))->GetQuotaManager());
diff --git a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.h b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.h
index 9e74b93ce4d..1469f488491 100644
--- a/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.h
+++ b/chromium/chrome/browser/ui/webui/quota_internals/quota_internals_handler.h
@@ -42,6 +42,7 @@ class QuotaInternalsHandler : public content::WebUIMessageHandler {
void ReportPerHostInfo(const std::vector<PerHostStorageInfo>& hosts);
void ReportPerOriginInfo(const std::vector<PerOriginStorageInfo>& origins);
void ReportStatistics(const Statistics& stats);
+ void ReportStoragePressureFlag();
private:
void OnRequestInfo(const base::ListValue*);
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 db85c160a40..1e06e9b105b 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
@@ -8,7 +8,6 @@
#include <string>
#include "base/bind.h"
-#include "base/task/post_task.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"
@@ -27,8 +26,8 @@ void QuotaInternalsProxy::RequestInfo(
scoped_refptr<storage::QuotaManager> quota_manager) {
DCHECK(quota_manager.get());
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
- base::PostTask(
- FROM_HERE, {BrowserThread::IO},
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE,
base::BindOnce(&QuotaInternalsProxy::RequestInfo, this, quota_manager));
return;
}
@@ -71,8 +70,8 @@ void QuotaInternalsProxy::TriggerStoragePressure(
scoped_refptr<storage::QuotaManager> quota_manager) {
DCHECK(quota_manager.get());
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
- base::PostTask(FROM_HERE, {BrowserThread::IO},
- base::BindOnce(&QuotaInternalsProxy::TriggerStoragePressure,
+ content::GetIOThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&QuotaInternalsProxy::TriggerStoragePressure,
this, origin, quota_manager));
return;
}
@@ -86,8 +85,8 @@ QuotaInternalsProxy::~QuotaInternalsProxy() = default;
if (!handler_) \
return; \
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { \
- base::PostTask(FROM_HERE, {BrowserThread::UI}, \
- base::BindOnce(&QuotaInternalsProxy::func, this, arg)); \
+ content::GetUIThreadTaskRunner({})->PostTask( \
+ FROM_HERE, base::BindOnce(&QuotaInternalsProxy::func, this, arg)); \
return; \
} \
\
diff --git a/chromium/chrome/browser/ui/webui/sandbox/sandbox_handler.cc b/chromium/chrome/browser/ui/webui/sandbox/sandbox_handler.cc
index 186ef33a6d4..747c8494454 100644
--- a/chromium/chrome/browser/ui/webui/sandbox/sandbox_handler.cc
+++ b/chromium/chrome/browser/ui/webui/sandbox/sandbox_handler.cc
@@ -8,7 +8,6 @@
#include "base/bind.h"
#include "base/numerics/safe_conversions.h"
-#include "base/task/post_task.h"
#include "base/values.h"
#include "content/public/browser/browser_child_process_host_iterator.h"
#include "content/public/browser/browser_task_traits.h"
@@ -27,44 +26,6 @@ using content::RenderProcessHost;
namespace sandbox_handler {
namespace {
-// This only includes OS_WIN included SandboxType values.
-std::string GetSandboxTypeInEnglish(content::SandboxType sandbox_type) {
- switch (sandbox_type) {
- case content::SandboxType::kNoSandbox:
- return "Unsandboxed";
- case content::SandboxType::kNoSandboxAndElevatedPrivileges:
- return "Unsandboxed (Elevated)";
- case content::SandboxType::kXrCompositing:
- return "XR Compositing";
- case content::SandboxType::kRenderer:
- return "Renderer";
- case content::SandboxType::kUtility:
- return "Utility";
- case content::SandboxType::kGpu:
- return "GPU";
- case content::SandboxType::kPpapi:
- return "PPAPI";
- case content::SandboxType::kNetwork:
- return "Network";
- case content::SandboxType::kCdm:
- return "CDM";
- case content::SandboxType::kPrintCompositor:
- return "Print Compositor";
- case content::SandboxType::kAudio:
- return "Audio";
- case content::SandboxType::kSpeechRecognition:
- return "Speech Recognition";
- case content::SandboxType::kProxyResolver:
- return "Proxy Resolver";
- case content::SandboxType::kPdfConversion:
- return "PDF Conversion";
- case content::SandboxType::kSharingService:
- return "Sharing";
- case content::SandboxType::kVideoCapture:
- return "Video Capture";
- }
-}
-
base::Value FetchBrowserChildProcesses() {
// The |BrowserChildProcessHostIterator| must only be used on the IO thread.
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
@@ -85,7 +46,8 @@ base::Value FetchBrowserChildProcesses() {
proc.SetPath("metricsName", base::Value(process_data.metrics_name));
proc.SetPath(
"sandboxType",
- base::Value(GetSandboxTypeInEnglish(process_data.sandbox_type)));
+ base::Value(service_manager::SandboxWin::GetSandboxTypeInEnglish(
+ process_data.sandbox_type)));
browser_processes.Append(std::move(proc));
}
@@ -136,9 +98,8 @@ void SandboxHandler::HandleRequestSandboxDiagnostics(
AllowJavascript();
- base::PostTaskAndReplyWithResult(
- FROM_HERE, {content::BrowserThread::IO},
- base::BindOnce(&FetchBrowserChildProcesses),
+ content::GetIOThreadTaskRunner({})->PostTaskAndReplyWithResult(
+ FROM_HERE, base::BindOnce(&FetchBrowserChildProcesses),
base::BindOnce(&SandboxHandler::FetchBrowserChildProcessesCompleted,
weak_ptr_factory_.GetWeakPtr()));
}
@@ -157,8 +118,8 @@ void SandboxHandler::FetchBrowserChildProcessesCompleted(
void SandboxHandler::FetchSandboxDiagnosticsCompleted(
base::Value sandbox_policies) {
sandbox_policies_ = std::move(sandbox_policies);
- base::PostTask(FROM_HERE, {content::BrowserThread::UI},
- base::BindOnce(&SandboxHandler::GetRendererProcessesAndFinish,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&SandboxHandler::GetRendererProcessesAndFinish,
weak_ptr_factory_.GetWeakPtr()));
}
diff --git a/chromium/chrome/browser/ui/webui/sandbox/sandbox_internals_ui.cc b/chromium/chrome/browser/ui/webui/sandbox/sandbox_internals_ui.cc
index 40567210a5a..481b12ba8bf 100644
--- a/chromium/chrome/browser/ui/webui/sandbox/sandbox_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/sandbox/sandbox_internals_ui.cc
@@ -25,8 +25,8 @@
#endif
#if defined(OS_LINUX)
+#include "content/public/browser/zygote_host/zygote_host_linux.h"
#include "services/service_manager/sandbox/sandbox.h"
-#include "services/service_manager/zygote/zygote_host_linux.h"
#endif
namespace {
@@ -35,7 +35,7 @@ namespace {
static void SetSandboxStatusData(content::WebUIDataSource* source) {
// Get expected sandboxing status of renderers.
const int status =
- service_manager::ZygoteHost::GetInstance()->GetRendererSandboxStatus();
+ content::ZygoteHost::GetInstance()->GetRendererSandboxStatus();
source->AddBoolean("suid", status & service_manager::SandboxLinux::kSUID);
source->AddBoolean("userNs", status & service_manager::SandboxLinux::kUserNS);
diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.cc b/chromium/chrome/browser/ui/webui/settings/about_handler.cc
index 9f615ac73cb..a1bb190d093 100644
--- a/chromium/chrome/browser/ui/webui/settings/about_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/about_handler.cc
@@ -101,15 +101,12 @@ struct RegulatoryLabel {
// Returns message that informs user that for update it's better to
// connect to a network of one of the allowed types.
base::string16 GetAllowedConnectionTypesMessage() {
- const chromeos::NetworkState* network = chromeos::NetworkHandler::Get()
- ->network_state_handler()
- ->DefaultNetwork();
- const bool mobile_data =
- network && network->IsConnectedState() && network->IsUsingMobileData();
-
if (help_utils_chromeos::IsUpdateOverCellularAllowed(
- true /* interactive */)) {
- return mobile_data
+ /*interactive=*/true)) {
+ const bool metered = chromeos::NetworkHandler::Get()
+ ->network_state_handler()
+ ->default_network_is_metered();
+ return metered
? l10n_util::GetStringUTF16(
IDS_UPGRADE_NETWORK_LIST_CELLULAR_ALLOWED_NOT_AUTOMATIC)
: l10n_util::GetStringUTF16(
@@ -652,6 +649,7 @@ void AboutHandler::RequestUpdate() {
void AboutHandler::SetUpdateStatus(VersionUpdater::Status status,
int progress,
bool rollback,
+ bool powerwash,
const std::string& version,
int64_t size,
const base::string16& message) {
@@ -663,6 +661,7 @@ void AboutHandler::SetUpdateStatus(VersionUpdater::Status status,
event->SetString("message", message);
event->SetInteger("progress", progress);
event->SetBoolean("rollback", rollback);
+ event->SetBoolean("powerwash", powerwash);
event->SetString("version", version);
// DictionaryValue does not support int64_t, so convert to string.
event->SetString("size", base::NumberToString(size));
diff --git a/chromium/chrome/browser/ui/webui/settings/about_handler.h b/chromium/chrome/browser/ui/webui/settings/about_handler.h
index 4b8bf98b5a3..bc71e2da278 100644
--- a/chromium/chrome/browser/ui/webui/settings/about_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/about_handler.h
@@ -135,6 +135,7 @@ class AboutHandler : public settings::SettingsPageUIHandler,
void SetUpdateStatus(VersionUpdater::Status status,
int progress,
bool rollback,
+ bool powerwash,
const std::string& version,
int64_t size,
const base::string16& fail_message);
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/about_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/about_section.cc
index ea9dc60efd8..a90a99bfebb 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/about_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/about_section.cc
@@ -4,11 +4,11 @@
#include "chrome/browser/ui/webui/settings/chromeos/about_section.h"
+#include "base/feature_list.h"
#include "base/i18n/message_formatter.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/system/sys_info.h"
-#include "build/branding_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/chromeos/arc/arc_util.h"
@@ -19,10 +19,13 @@
#include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h"
#include "chrome/browser/ui/webui/webui_util.h"
#include "chrome/common/channel_info.h"
+#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
+#include "chromeos/constants/chromeos_features.h"
#include "chromeos/dbus/constants/dbus_switches.h"
+#include "components/prefs/pref_service.h"
#include "components/strings/grit/components_chromium_strings.h"
#include "components/strings/grit/components_strings.h"
#include "components/user_manager/user_manager.h"
@@ -44,16 +47,14 @@ const std::vector<SearchConcept>& GetAboutSearchConcepts() {
mojom::SearchResultIcon::kChrome,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
- {.subpage = mojom::Subpage::kDetailedBuildInfo},
- {IDS_OS_SETTINGS_TAG_ABOUT_CHROME_OS_DETAILED_BUILD_ALT1,
- SearchConcept::kAltTagEnd}},
- {IDS_OS_SETTINGS_TAG_ABOUT_CHROME_OS,
+ {.subpage = mojom::Subpage::kDetailedBuildInfo}},
+ {IDS_SETTINGS_ABOUT_OS,
mojom::kAboutChromeOsDetailsSubpagePath,
mojom::SearchResultIcon::kChrome,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kAboutChromeOsDetails}},
- {IDS_OS_SETTINGS_TAG_ABOUT_CHROME_OS_VERSION,
+ {IDS_OS_SETTINGS_TAG_OS_VERSION,
mojom::kAboutChromeOsDetailsSubpagePath,
mojom::SearchResultIcon::kChrome,
mojom::SearchResultDefaultRank::kMedium,
@@ -62,13 +63,67 @@ const std::vector<SearchConcept>& GetAboutSearchConcepts() {
{IDS_OS_SETTINGS_TAG_ABOUT_CHROME_OS_CHANNEL,
mojom::kDetailedBuildInfoSubpagePath,
mojom::SearchResultIcon::kChrome,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kChangeChromeChannel}},
+ {IDS_OS_SETTINGS_TAG_ABOUT_OS_UPDATE,
+ mojom::kAboutChromeOsDetailsSubpagePath,
+ mojom::SearchResultIcon::kChrome,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kCheckForOsUpdate}},
+ {IDS_OS_SETTINGS_TAG_ABOUT_HELP,
+ mojom::kAboutChromeOsDetailsSubpagePath,
+ mojom::SearchResultIcon::kChrome,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kGetHelpWithChromeOs}},
+ });
+ return *tags;
+}
+
+const std::vector<SearchConcept>& GetAboutReleaseNotesSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_ABOUT_RELEASE_NOTES,
+ mojom::kAboutChromeOsDetailsSubpagePath,
+ mojom::SearchResultIcon::kChrome,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kSeeWhatsNew},
+ {IDS_OS_SETTINGS_TAG_ABOUT_RELEASE_NOTES_ALT1,
+ SearchConcept::kAltTagEnd}},
+ });
+ return *tags;
+}
+
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
+const std::vector<SearchConcept>& GetAboutTermsOfServiceSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_ABOUT_TERMS_OF_SERVICE,
+ mojom::kAboutChromeOsDetailsSubpagePath,
+ mojom::SearchResultIcon::kChrome,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kTermsOfService}},
});
return *tags;
}
+const std::vector<SearchConcept>& GetAboutReportIssueSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_ABOUT_REPORT_ISSUE,
+ mojom::kAboutChromeOsDetailsSubpagePath,
+ mojom::SearchResultIcon::kChrome,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kReportAnIssue},
+ {IDS_OS_SETTINGS_TAG_ABOUT_REPORT_ISSUE_ALT1,
+ SearchConcept::kAltTagEnd}},
+ });
+ return *tags;
+}
+#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
+
// Returns the link to the safety info for the device (if it exists).
std::string GetSafetyInfoLink() {
const std::vector<std::string> board =
@@ -99,10 +154,33 @@ bool IsDeviceManaged() {
} // namespace
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
+AboutSection::AboutSection(Profile* profile,
+ SearchTagRegistry* search_tag_registry,
+ PrefService* pref_service)
+ : AboutSection(profile, search_tag_registry) {
+ pref_service_ = pref_service;
+
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetAboutTermsOfServiceSearchConcepts());
+
+ pref_change_registrar_.Init(pref_service_);
+ pref_change_registrar_.Add(
+ prefs::kUserFeedbackAllowed,
+ base::BindRepeating(&AboutSection::UpdateReportIssueSearchTags,
+ base::Unretained(this)));
+ UpdateReportIssueSearchTags();
+}
+#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
+
AboutSection::AboutSection(Profile* profile,
SearchTagRegistry* search_tag_registry)
: OsSettingsSection(profile, search_tag_registry) {
- registry()->AddSearchTags(GetAboutSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetAboutSearchConcepts());
+
+ if (base::FeatureList::IsEnabled(features::kReleaseNotes))
+ updater.AddSearchTags(GetAboutReleaseNotesSearchConcepts());
}
AboutSection::~AboutSection() = default;
@@ -270,5 +348,58 @@ void AboutSection::AddHandlers(content::WebUI* web_ui) {
web_ui->AddMessageHandler(std::make_unique<::settings::AboutHandler>());
}
+int AboutSection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_ABOUT_OS;
+}
+
+mojom::Section AboutSection::GetSection() const {
+ return mojom::Section::kAboutChromeOs;
+}
+
+mojom::SearchResultIcon AboutSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kChrome;
+}
+
+std::string AboutSection::GetSectionPath() const {
+ return mojom::kAboutChromeOsSectionPath;
+}
+
+void AboutSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ // About Chrome OS.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_ABOUT_OS, mojom::Subpage::kAboutChromeOsDetails,
+ mojom::SearchResultIcon::kChrome, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kAboutChromeOsDetailsSubpagePath);
+ static constexpr mojom::Setting kAboutChromeOsDetailsSettings[] = {
+ mojom::Setting::kCheckForOsUpdate, mojom::Setting::kSeeWhatsNew,
+ mojom::Setting::kGetHelpWithChromeOs, mojom::Setting::kReportAnIssue,
+ mojom::Setting::kTermsOfService};
+ RegisterNestedSettingBulk(mojom::Subpage::kAboutChromeOsDetails,
+ kAboutChromeOsDetailsSettings, generator);
+
+ // Detailed build info.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_ABOUT_PAGE_DETAILED_BUILD_INFO,
+ mojom::Subpage::kDetailedBuildInfo, mojom::Subpage::kAboutChromeOsDetails,
+ mojom::SearchResultIcon::kChrome, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kDetailedBuildInfoSubpagePath);
+ static constexpr mojom::Setting kDetailedBuildInfoSettings[] = {
+ mojom::Setting::kChangeChromeChannel,
+ mojom::Setting::kCopyDetailedBuildInfo};
+ RegisterNestedSettingBulk(mojom::Subpage::kDetailedBuildInfo,
+ kDetailedBuildInfoSettings, generator);
+}
+
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
+void AboutSection::UpdateReportIssueSearchTags() {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
+ if (pref_service_->GetBoolean(prefs::kUserFeedbackAllowed))
+ updater.AddSearchTags(GetAboutReportIssueSearchConcepts());
+ else
+ updater.RemoveSearchTags(GetAboutReportIssueSearchConcepts());
+}
+#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
+
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/about_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/about_section.h
index 0e619e80d91..506f0b67d56 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/about_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/about_section.h
@@ -5,7 +5,9 @@
#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_ABOUT_SECTION_H_
#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_ABOUT_SECTION_H_
+#include "build/branding_buildflags.h"
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_section.h"
+#include "components/prefs/pref_change_registrar.h"
namespace content {
class WebUIDataSource;
@@ -19,6 +21,11 @@ class SearchTagRegistry;
// Provides UI strings and search tags for the settings "About Chrome OS" page.
class AboutSection : public OsSettingsSection {
public:
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
+ AboutSection(Profile* profile,
+ SearchTagRegistry* search_tag_registry,
+ PrefService* pref_service);
+#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
AboutSection(Profile* profile, SearchTagRegistry* search_tag_registry);
~AboutSection() override;
@@ -26,6 +33,18 @@ class AboutSection : public OsSettingsSection {
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
+
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
+ void UpdateReportIssueSearchTags();
+
+ PrefService* pref_service_;
+ PrefChangeRegistrar pref_change_registrar_;
+#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
};
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_section.cc
index 1e7b9bf8b08..a38be955b4e 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_section.cc
@@ -23,6 +23,7 @@
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/common/content_features.h"
#include "media/base/media_switches.h"
+#include "ui/accessibility/accessibility_features.h"
#include "ui/accessibility/accessibility_switches.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
@@ -82,16 +83,18 @@ const std::vector<SearchConcept>& GetA11ySearchConcepts() {
{IDS_OS_SETTINGS_TAG_A11Y_MONO_AUDIO,
mojom::kManageAccessibilitySubpagePath,
mojom::SearchResultIcon::kA11y,
- mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultDefaultRank::kLow,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kMonoAudio},
{IDS_OS_SETTINGS_TAG_A11Y_MONO_AUDIO_ALT1, SearchConcept::kAltTagEnd}},
{IDS_OS_SETTINGS_TAG_A11Y_TEXT_TO_SPEECH,
- mojom::kManageAccessibilitySubpagePath,
+ mojom::kTextToSpeechSubpagePath,
mojom::SearchResultIcon::kA11y,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
- {.subpage = mojom::Subpage::kManageAccessibility}},
+ {.subpage = mojom::Subpage::kTextToSpeech},
+ {IDS_OS_SETTINGS_TAG_A11Y_TEXT_TO_SPEECH_ALT1,
+ SearchConcept::kAltTagEnd}},
{IDS_OS_SETTINGS_TAG_A11Y_CAPTIONS,
mojom::kCaptionsSubpagePath,
mojom::SearchResultIcon::kA11y,
@@ -262,11 +265,43 @@ const std::vector<SearchConcept>& GetA11yLabelsSearchConcepts() {
return *tags;
}
+const std::vector<SearchConcept>& GetA11yLiveCaptionSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_A11Y_LIVE_CAPTIONS,
+ mojom::kManageAccessibilitySubpagePath,
+ mojom::SearchResultIcon::kA11y,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kLiveCaptions}},
+ });
+ return *tags;
+}
+
+const std::vector<SearchConcept>& GetA11yCursorColorSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_A11Y_CURSOR_COLOR,
+ mojom::kManageAccessibilitySubpagePath,
+ mojom::SearchResultIcon::kA11y,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kEnableCursorColor}},
+ });
+ return *tags;
+}
+
bool AreExperimentalA11yLabelsAllowed() {
return base::FeatureList::IsEnabled(
::features::kExperimentalAccessibilityLabels);
}
+bool AreLiveCaptionsAllowed() {
+ return base::FeatureList::IsEnabled(media::kLiveCaption);
+}
+
+bool IsCursorColorAllowed() {
+ return features::IsAccessibilityCursorColorEnabled();
+}
+
bool IsSwitchAccessAllowed() {
return base::CommandLine::ForCurrentProcess()->HasSwitch(
::switches::kEnableExperimentalAccessibilitySwitchAccess);
@@ -285,7 +320,8 @@ AccessibilitySection::AccessibilitySection(
PrefService* pref_service)
: OsSettingsSection(profile, search_tag_registry),
pref_service_(pref_service) {
- registry()->AddSearchTags(GetA11ySearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetA11ySearchConcepts());
pref_change_registrar_.Init(pref_service_);
pref_change_registrar_.Add(
@@ -323,6 +359,13 @@ void AccessibilitySection::AddLoadTimeData(
IDS_SETTINGS_LARGE_MOUSE_CURSOR_SIZE_DEFAULT_LABEL},
{"largeMouseCursorSizeLargeLabel",
IDS_SETTINGS_LARGE_MOUSE_CURSOR_SIZE_LARGE_LABEL},
+ {"cursorColorEnabledLabel", IDS_SETTINGS_CURSOR_COLOR_ENABLED_LABEL},
+ {"cursorColorOptionsLabel", IDS_SETTINGS_CURSOR_COLOR_OPTIONS_LABEL},
+ {"cursorColorRed", IDS_SETTINGS_CURSOR_COLOR_RED},
+ {"cursorColorOrange", IDS_SETTINGS_CURSOR_COLOR_ORANGE},
+ {"cursorColorGreen", IDS_SETTINGS_CURSOR_COLOR_GREEN},
+ {"cursorColorBlue", IDS_SETTINGS_CURSOR_COLOR_BLUE},
+ {"cursorColorPurple", IDS_SETTINGS_CURSOR_COLOR_PURPLE},
{"highContrastLabel", IDS_SETTINGS_HIGH_CONTRAST_LABEL},
{"stickyKeysLabel", IDS_SETTINGS_STICKY_KEYS_LABEL},
{"chromeVoxLabel", IDS_SETTINGS_CHROMEVOX_LABEL},
@@ -473,6 +516,10 @@ void AccessibilitySection::AddLoadTimeData(
IDS_SETTINGS_A11Y_TABLET_MODE_SHELF_BUTTONS_LABEL},
{"tabletModeShelfNavigationButtonsSettingDescription",
IDS_SETTINGS_A11Y_TABLET_MODE_SHELF_BUTTONS_DESCRIPTION},
+ {"captionsEnableLiveCaptionTitle",
+ IDS_SETTINGS_CAPTIONS_ENABLE_LIVE_CAPTION_TITLE},
+ {"captionsEnableLiveCaptionSubtitle",
+ IDS_SETTINGS_CAPTIONS_ENABLE_LIVE_CAPTION_SUBTITLE},
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings);
@@ -495,8 +542,10 @@ void AccessibilitySection::AddLoadTimeData(
html_source->AddString("tabletModeShelfNavigationButtonsLearnMoreUrl",
chrome::kTabletModeGesturesLearnMoreURL);
- html_source->AddBoolean("enableLiveCaption",
- base::FeatureList::IsEnabled(media::kLiveCaption));
+ html_source->AddBoolean("enableLiveCaption", AreLiveCaptionsAllowed());
+
+ html_source->AddBoolean("showExperimentalAccessibilityCursorColor",
+ IsCursorColorAllowed());
::settings::AddCaptionSubpageStrings(html_source);
}
@@ -510,33 +559,132 @@ void AccessibilitySection::AddHandlers(content::WebUI* web_ui) {
std::make_unique<::settings::FontHandler>(profile()));
}
+int AccessibilitySection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_ACCESSIBILITY;
+}
+
+mojom::Section AccessibilitySection::GetSection() const {
+ return mojom::Section::kAccessibility;
+}
+
+mojom::SearchResultIcon AccessibilitySection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kA11y;
+}
+
+std::string AccessibilitySection::GetSectionPath() const {
+ return mojom::kAccessibilitySectionPath;
+}
+
+void AccessibilitySection::RegisterHierarchy(
+ HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSetting(mojom::Setting::kA11yQuickSettings);
+
+ // Manage accessibility.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_ACCESSIBILITY_MANAGE_ACCESSIBILITY_FEATURES,
+ mojom::Subpage::kManageAccessibility, mojom::SearchResultIcon::kA11y,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kManageAccessibilitySubpagePath);
+ static constexpr mojom::Setting kManageAccessibilitySettings[] = {
+ mojom::Setting::kChromeVox,
+ mojom::Setting::kSelectToSpeak,
+ mojom::Setting::kHighContrastMode,
+ mojom::Setting::kFullscreenMagnifier,
+ mojom::Setting::kDockedMagnifier,
+ mojom::Setting::kStickyKeys,
+ mojom::Setting::kOnScreenKeyboard,
+ mojom::Setting::kDictation,
+ mojom::Setting::kSpeakToType,
+ mojom::Setting::kEnableSwitchAccess,
+ mojom::Setting::kHighlightTextCaret,
+ mojom::Setting::kAutoClickWhenCursorStops,
+ mojom::Setting::kLargeCursor,
+ mojom::Setting::kHighlightCursorWhileMoving,
+ mojom::Setting::kTabletNavigationButtons,
+ mojom::Setting::kMonoAudio,
+ mojom::Setting::kStartupSound,
+ mojom::Setting::kGetImageDescriptionsFromGoogle,
+ mojom::Setting::kLiveCaptions,
+ mojom::Setting::kEnableCursorColor,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kManageAccessibility,
+ kManageAccessibilitySettings, generator);
+
+ // Text-to-Speech.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_MANAGE_TTS_SETTINGS, mojom::Subpage::kTextToSpeech,
+ mojom::SearchResultIcon::kA11y, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kTextToSpeechSubpagePath);
+ static constexpr mojom::Setting kTextToSpeechSettings[] = {
+ mojom::Setting::kTextToSpeechRate, mojom::Setting::kTextToSpeechPitch,
+ mojom::Setting::kTextToSpeechVolume, mojom::Setting::kTextToSpeechVoice,
+ mojom::Setting::kTextToSpeechEngines,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kTextToSpeech,
+ kTextToSpeechSettings, generator);
+
+ // Switch access.
+ generator->RegisterTopLevelSubpage(IDS_SETTINGS_MANAGE_SWITCH_ACCESS_SETTINGS,
+ mojom::Subpage::kSwitchAccessOptions,
+ mojom::SearchResultIcon::kA11y,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kSwitchAccessOptionsSubpagePath);
+ static constexpr mojom::Setting kSwitchAccessSettings[] = {
+ mojom::Setting::kSwitchActionAssignment,
+ mojom::Setting::kSwitchActionAutoScan,
+ mojom::Setting::kSwitchActionAutoScanKeyboard,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kSwitchAccessOptions,
+ kSwitchAccessSettings, generator);
+
+ // Captions.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_CAPTIONS, mojom::Subpage::kCaptions,
+ mojom::SearchResultIcon::kA11y, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kCaptionsSubpagePath);
+}
+
void AccessibilitySection::UpdateSearchTags() {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
if (accessibility_state_utils::IsScreenReaderEnabled() &&
AreExperimentalA11yLabelsAllowed()) {
- registry()->AddSearchTags(GetA11yLabelsSearchConcepts());
+ updater.AddSearchTags(GetA11yLabelsSearchConcepts());
} else {
- registry()->RemoveSearchTags(GetA11yLabelsSearchConcepts());
+ updater.RemoveSearchTags(GetA11yLabelsSearchConcepts());
}
- registry()->RemoveSearchTags(GetA11ySwitchAccessSearchConcepts());
- registry()->RemoveSearchTags(GetA11ySwitchAccessOnSearchConcepts());
- registry()->RemoveSearchTags(GetA11ySwitchAccessKeyboardSearchConcepts());
+ updater.RemoveSearchTags(GetA11ySwitchAccessSearchConcepts());
+ updater.RemoveSearchTags(GetA11ySwitchAccessOnSearchConcepts());
+ updater.RemoveSearchTags(GetA11ySwitchAccessKeyboardSearchConcepts());
+
+ if (AreLiveCaptionsAllowed()) {
+ updater.AddSearchTags(GetA11yLiveCaptionSearchConcepts());
+ } else {
+ updater.RemoveSearchTags(GetA11yLiveCaptionSearchConcepts());
+ }
+
+ if (IsCursorColorAllowed()) {
+ updater.AddSearchTags(GetA11yCursorColorSearchConcepts());
+ } else {
+ updater.RemoveSearchTags(GetA11yCursorColorSearchConcepts());
+ }
if (!IsSwitchAccessAllowed())
return;
- registry()->AddSearchTags(GetA11ySwitchAccessSearchConcepts());
+ updater.AddSearchTags(GetA11ySwitchAccessSearchConcepts());
if (!pref_service_->GetBoolean(
ash::prefs::kAccessibilitySwitchAccessEnabled)) {
return;
}
- registry()->AddSearchTags(GetA11ySwitchAccessOnSearchConcepts());
+ updater.AddSearchTags(GetA11ySwitchAccessOnSearchConcepts());
if (pref_service_->GetBoolean(
ash::prefs::kAccessibilitySwitchAccessAutoScanEnabled)) {
- registry()->AddSearchTags(GetA11ySwitchAccessKeyboardSearchConcepts());
+ updater.AddSearchTags(GetA11ySwitchAccessKeyboardSearchConcepts());
}
}
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_section.h
index 546454007b1..77f82db40d3 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/accessibility_section.h
@@ -31,6 +31,11 @@ class AccessibilitySection : public OsSettingsSection {
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
void UpdateSearchTags();
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 0d6b946d6c3..69266feb260 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
@@ -17,10 +17,10 @@
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/webui/chromeos/account_manager_welcome_dialog.h"
-#include "chrome/browser/ui/webui/chromeos/account_migration_welcome_dialog.h"
+#include "chrome/browser/ui/webui/chromeos/account_manager/account_manager_welcome_dialog.h"
+#include "chrome/browser/ui/webui/chromeos/account_manager/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/browser/ui/webui/signin/inline_login_dialog_chromeos.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/components/account_manager/account_manager_factory.h"
#include "components/signin/public/identity_manager/consent_level.h"
@@ -343,8 +343,8 @@ base::ListValue AccountManagerUIHandler::GetSecondaryGaiaAccounts(
void AccountManagerUIHandler::HandleAddAccount(const base::ListValue* args) {
AllowJavascript();
- InlineLoginHandlerDialogChromeOS::Show(
- InlineLoginHandlerDialogChromeOS::Source::kSettingsAddAccountButton);
+ InlineLoginDialogChromeOS::Show(
+ InlineLoginDialogChromeOS::Source::kSettingsAddAccountButton);
}
void AccountManagerUIHandler::HandleReauthenticateAccount(
@@ -354,9 +354,9 @@ void AccountManagerUIHandler::HandleReauthenticateAccount(
CHECK(!args->GetList().empty());
const std::string& account_email = args->GetList()[0].GetString();
- InlineLoginHandlerDialogChromeOS::Show(
+ InlineLoginDialogChromeOS::Show(
account_email,
- InlineLoginHandlerDialogChromeOS::Source::kSettingsReauthAccountButton);
+ InlineLoginDialogChromeOS::Source::kSettingsReauthAccountButton);
}
void AccountManagerUIHandler::HandleMigrateAccount(
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.cc
index 276327a54c8..fd4f14a6d09 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.cc
@@ -4,13 +4,34 @@
#include "chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.h"
+#include "ash/public/cpp/ambient/ambient_backend_controller.h"
+#include "ash/public/cpp/ambient/common/ambient_settings.h"
#include "base/bind.h"
+#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
namespace chromeos {
namespace settings {
+namespace {
+
+// Width and height of the preview image for personal album.
+constexpr int kBannerWidth = 512;
+constexpr int kBannderHeight = 512;
+
+ash::AmbientModeTopicSource ExtractTopicSource(const base::ListValue* args) {
+ CHECK_EQ(args->GetSize(), 1U);
+ ash::AmbientModeTopicSource topic_source =
+ static_cast<ash::AmbientModeTopicSource>(args->GetList()[0].GetInt());
+ // Check the |topic_source| has valid value.
+ CHECK_GE(topic_source, ash::AmbientModeTopicSource::kMinValue);
+ CHECK_LE(topic_source, ash::AmbientModeTopicSource::kMaxValue);
+ return topic_source;
+}
+
+} // namespace
+
AmbientModeHandler::AmbientModeHandler() = default;
AmbientModeHandler::~AmbientModeHandler() = default;
@@ -22,36 +43,94 @@ void AmbientModeHandler::RegisterMessages() {
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
- "onTopicSourceSelectedChanged",
- base::BindRepeating(&AmbientModeHandler::HandleTopicSourceSelectedChanged,
+ "setSelectedTopicSource",
+ base::BindRepeating(&AmbientModeHandler::HandleSetSelectedTopicSource,
+ base::Unretained(this)));
+
+ web_ui()->RegisterMessageCallback(
+ "requestPhotosContainers",
+ base::BindRepeating(&AmbientModeHandler::RequestPhotosContainers,
base::Unretained(this)));
+
+ web_ui()->RegisterMessageCallback(
+ "setSelectedPhotosContainers",
+ base::BindRepeating(
+ &AmbientModeHandler::HandleSetSelectedPhotosContainers,
+ base::Unretained(this)));
}
void AmbientModeHandler::OnJavascriptAllowed() {
- if (topic_source_.has_value())
- SendTopicSource();
+ GetSettings();
+
+ // Prefetch albums.
+ FetchPersonalAlbums();
+}
+
+void AmbientModeHandler::OnJavascriptDisallowed() {
+ weak_factory_.InvalidateWeakPtrs();
}
void AmbientModeHandler::HandleInitialized(const base::ListValue* args) {
CHECK(args);
CHECK(args->empty());
+ init_from_ambient_mode_page_ = true;
AllowJavascript();
- GetSettings();
}
-void AmbientModeHandler::HandleTopicSourceSelectedChanged(
+void AmbientModeHandler::RequestPhotosContainers(const base::ListValue* args) {
+ // TODO(b/159747583): Handle deep linking to ambientMode/photos page.
+ // For now it will not load the page contents if visited directly.
+ if (!init_from_ambient_mode_page_)
+ return;
+
+ ash::AmbientModeTopicSource topic_source = ExtractTopicSource(args);
+ DCHECK_EQ(topic_source, settings_->topic_source);
+
+ if (topic_source == ash::AmbientModeTopicSource::kGooglePhotos) {
+ FetchPersonalAlbums();
+ }
+ SendPhotosContainers();
+}
+
+void AmbientModeHandler::HandleSetSelectedTopicSource(
const base::ListValue* args) {
- CHECK_EQ(args->GetSize(), 1U);
- int topic_source;
- CHECK(base::StringToInt(args->GetList()[0].GetString(), &topic_source));
- // Check the |topic_source| has valid value.
- CHECK_GE(topic_source,
- static_cast<int>(ash::AmbientModeTopicSource::kMinValue));
- CHECK_LE(topic_source,
- static_cast<int>(ash::AmbientModeTopicSource::kMaxValue));
+ ash::AmbientModeTopicSource topic_source = ExtractTopicSource(args);
+ settings_->topic_source = topic_source;
+ UpdateSettings();
+}
- UpdateSettings(static_cast<ash::AmbientModeTopicSource>(topic_source));
+void AmbientModeHandler::HandleSetSelectedPhotosContainers(
+ const base::ListValue* args) {
+ switch (settings_->topic_source) {
+ case ash::AmbientModeTopicSource::kGooglePhotos:
+ // For Google Photos, we will populate the |selected_album_ids| with IDs
+ // of selected albums.
+ settings_->selected_album_ids.clear();
+ for (const auto& value : args->GetList()) {
+ std::string name = value.GetString();
+ auto it = std::find_if(
+ personal_albums_.albums.begin(), personal_albums_.albums.end(),
+ [name](const auto& album) { return album.album_name == name; });
+ CHECK(it != personal_albums_.albums.end());
+ settings_->selected_album_ids.emplace_back(it->album_id);
+ }
+ break;
+ case ash::AmbientModeTopicSource::kArtGallery:
+ // For Art gallery, we set the corresponding setting to be enabled or not
+ // based on the selections.
+ for (auto& art_setting : settings_->art_settings) {
+ std::string title = art_setting.title;
+ auto it = std::find_if(
+ args->GetList().begin(), args->GetList().end(),
+ [title](const auto& value) { return value.GetString() == title; });
+ const bool checked = it != args->GetList().end();
+ art_setting.enabled = checked;
+ }
+ break;
+ }
+
+ UpdateSettings();
}
void AmbientModeHandler::GetSettings() {
@@ -60,37 +139,63 @@ void AmbientModeHandler::GetSettings() {
}
void AmbientModeHandler::OnGetSettings(
- base::Optional<ash::AmbientModeTopicSource> topic_source) {
- if (!topic_source.has_value()) {
+ const base::Optional<ash::AmbientSettings>& settings) {
+ if (!settings) {
// TODO(b/152921891): Retry a small fixed number of times, then only retry
// when user confirms in the error message dialog.
return;
}
- topic_source_ = topic_source;
- if (!IsJavascriptAllowed())
- return;
-
+ settings_ = settings;
SendTopicSource();
}
void AmbientModeHandler::SendTopicSource() {
+ DCHECK(settings_);
FireWebUIListener("topic-source-changed",
- base::Value(
+ base::Value(static_cast<int>(settings_->topic_source)));
+}
- static_cast<int>(topic_source_.value())));
+void AmbientModeHandler::SendPhotosContainers() {
+ DCHECK(settings_);
+
+ base::Value dictionary(base::Value::Type::DICTIONARY);
+ base::Value containers(base::Value::Type::LIST);
+ switch (settings_->topic_source) {
+ case ash::AmbientModeTopicSource::kGooglePhotos:
+ for (const auto& album : personal_albums_.albums) {
+ base::Value value(base::Value::Type::DICTIONARY);
+ value.SetKey("title", base::Value(album.album_name));
+ value.SetKey("checked",
+ base::Value(base::Contains(settings_->selected_album_ids,
+ album.album_id)));
+ containers.Append(std::move(value));
+ }
+ break;
+ case ash::AmbientModeTopicSource::kArtGallery:
+ for (const auto& setting : settings_->art_settings) {
+ base::Value value(base::Value::Type::DICTIONARY);
+ value.SetKey("title", base::Value(setting.title));
+ value.SetKey("checked", base::Value(setting.enabled));
+ containers.Append(std::move(value));
+ }
+ break;
+ }
+
+ dictionary.SetKey("topicSource",
+ base::Value(static_cast<int>(settings_->topic_source)));
+ dictionary.SetKey("topicContainers", std::move(containers));
+ FireWebUIListener("photos-containers-changed", std::move(dictionary));
}
-void AmbientModeHandler::UpdateSettings(
- ash::AmbientModeTopicSource topic_source) {
+void AmbientModeHandler::UpdateSettings() {
+ DCHECK(settings_);
ash::AmbientBackendController::Get()->UpdateSettings(
- topic_source, base::BindOnce(&AmbientModeHandler::OnUpdateSettings,
- weak_factory_.GetWeakPtr(), topic_source));
+ *settings_, base::BindOnce(&AmbientModeHandler::OnUpdateSettings,
+ weak_factory_.GetWeakPtr()));
}
-void AmbientModeHandler::OnUpdateSettings(
- ash::AmbientModeTopicSource topic_source,
- bool success) {
+void AmbientModeHandler::OnUpdateSettings(bool success) {
if (success)
return;
@@ -98,5 +203,31 @@ void AmbientModeHandler::OnUpdateSettings(
// when user confirms in the error message dialog.
}
+void AmbientModeHandler::FetchPersonalAlbums() {
+ // TODO: Add a helper function to get all the albums.
+ ash::AmbientBackendController::Get()->FetchPersonalAlbums(
+ kBannerWidth, kBannderHeight, /*num_albums=*/100, /*resume_token=*/"",
+ base::BindOnce(&AmbientModeHandler::OnPersonalAlbumsFetched,
+ weak_factory_.GetWeakPtr()));
+}
+
+void AmbientModeHandler::OnPersonalAlbumsFetched(
+ ash::PersonalAlbums personal_albums) {
+ personal_albums_ = std::move(personal_albums);
+
+ // If the |topic_source| is not |kGooglePhotos|, no need to refresh the
+ // photos subpage.
+ // |settings_| could be null because we call GetSettings() and
+ // FetchPersonalAlbums() in OnJavascriptAllowed(). |settings_| is populated by
+ // OnGetSettings(), which could be called later. The purpose to call
+ // FetchPersonalAlbums() is to prefetch albums, which takes several seconds,
+ // This improves the experience when we click into the ambientMode/photos page
+ // to show the albums list faster.
+ if (settings_ &&
+ settings_->topic_source == ash::AmbientModeTopicSource::kGooglePhotos) {
+ SendPhotosContainers();
+ }
+}
+
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.h
index 8e26f721b60..ac0c6441433 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/ambient_mode_handler.h
@@ -12,6 +12,10 @@
#include "base/optional.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
+namespace ash {
+struct AmbientSettings;
+} // namespace ash
+
namespace base {
class ListValue;
} // namespace base
@@ -31,34 +35,52 @@ class AmbientModeHandler : public ::settings::SettingsPageUIHandler {
// settings::SettingsPageUIHandler:
void RegisterMessages() override;
void OnJavascriptAllowed() override;
- void OnJavascriptDisallowed() override {}
+ void OnJavascriptDisallowed() override;
private:
// WebUI call to signal js side is ready.
void HandleInitialized(const base::ListValue* args);
+ // WebUI call to request photos containers, e.g. personal albums or art
+ // categories.
+ void RequestPhotosContainers(const base::ListValue* args);
+
// WebUI call to sync topic source with server.
- void HandleTopicSourceSelectedChanged(const base::ListValue* args);
+ void HandleSetSelectedTopicSource(const base::ListValue* args);
+
+ // WebUI call to sync photos containers with server.
+ void HandleSetSelectedPhotosContainers(const base::ListValue* args);
// Retrieve the initial settings from server.
void GetSettings();
// Called when the initial settings is retrieved.
- void OnGetSettings(base::Optional<ash::AmbientModeTopicSource> topic_source);
+ void OnGetSettings(const base::Optional<ash::AmbientSettings>& settings);
// Send the "topic-source-changed" WebUIListener event when the initial
// settings is retrieved.
void SendTopicSource();
- // Update the selected topic source to server.
- void UpdateSettings(ash::AmbientModeTopicSource topic_source);
+ // Send the "photos-containers-changed" WebUIListener event when the personal
+ // albums are retrieved.
+ void SendPhotosContainers();
+
+ // Update the local |settings_| to server.
+ void UpdateSettings();
// Called when the settings is updated.
- // |topic_source| is the value to retry if the update was failed.
- void OnUpdateSettings(ash::AmbientModeTopicSource topic_source, bool success);
+ void OnUpdateSettings(bool success);
+
+ void FetchPersonalAlbums();
+
+ void OnPersonalAlbumsFetched(ash::PersonalAlbums personal_albums);
+
+ // Whether the Javascript is inited from the ambientMode page.
+ bool init_from_ambient_mode_page_ = false;
+
+ base::Optional<ash::AmbientSettings> settings_;
- // The topic source, i.e. from which category the photos will be displayed.
- base::Optional<ash::AmbientModeTopicSource> topic_source_;
+ ash::PersonalAlbums personal_albums_;
base::WeakPtrFactory<AmbientModeHandler> weak_factory_{this};
};
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/apps_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/apps_section.cc
index 7ae2a6a8724..6d8ebbc5421 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/apps_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/apps_section.cc
@@ -4,6 +4,7 @@
#include "chrome/browser/ui/webui/settings/chromeos/apps_section.h"
+#include "base/feature_list.h"
#include "base/no_destructor.h"
#include "chrome/browser/chromeos/arc/arc_util.h"
#include "chrome/browser/chromeos/plugin_vm/plugin_vm_pref_names.h"
@@ -17,6 +18,7 @@
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/grit/os_settings_resources.h"
+#include "chromeos/constants/chromeos_features.h"
#include "components/arc/arc_prefs.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/web_ui_data_source.h"
@@ -39,7 +41,7 @@ const std::vector<SearchConcept>& GetAppsSearchConcepts() {
{IDS_OS_SETTINGS_TAG_APPS_MANAGEMENT,
mojom::kAppManagementSubpagePath,
mojom::SearchResultIcon::kAppsGrid,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kAppManagement},
{IDS_OS_SETTINGS_TAG_APPS_MANAGEMENT_ALT1, SearchConcept::kAltTagEnd}},
@@ -143,7 +145,8 @@ AppsSection::AppsSection(Profile* profile,
: OsSettingsSection(profile, search_tag_registry),
pref_service_(pref_service),
arc_app_list_prefs_(arc_app_list_prefs) {
- registry()->AddSearchTags(GetAppsSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetAppsSearchConcepts());
if (arc::IsArcAllowedForProfile(profile)) {
pref_change_registrar_.Init(pref_service_);
@@ -179,17 +182,11 @@ void AppsSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
"app-management/types.mojom-lite.js",
IDR_OS_SETTINGS_APP_MANAGEMENT_TYPES_MOJO_LITE_JS);
html_source->AddResourcePath(
- "app-management/bitmap.mojom-lite.js",
- IDR_OS_SETTINGS_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS);
- html_source->AddResourcePath(
"app-management/file_path.mojom-lite.js",
IDR_OS_SETTINGS_APP_MANAGEMENT_FILE_PATH_MOJO_LITE_JS);
html_source->AddResourcePath(
"app-management/image.mojom-lite.js",
IDR_OS_SETTINGS_APP_MANAGEMENT_IMAGE_MOJO_LITE_JS);
- html_source->AddResourcePath(
- "app-management/image_info.mojom-lite.js",
- IDR_OS_SETTINGS_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS);
// We have 2 variants of Android apps settings. Default case, when the Play
// Store app exists we show expandable section that allows as to
@@ -220,6 +217,57 @@ void AppsSection::AddHandlers(content::WebUI* web_ui) {
}
}
+int AppsSection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_APPS_TITLE;
+}
+
+mojom::Section AppsSection::GetSection() const {
+ return mojom::Section::kApps;
+}
+
+mojom::SearchResultIcon AppsSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kAppsGrid;
+}
+
+std::string AppsSection::GetSectionPath() const {
+ return mojom::kAppsSectionPath;
+}
+
+void AppsSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ // Manage apps.
+ generator->RegisterTopLevelSubpage(IDS_SETTINGS_APPS_LINK_TEXT,
+ mojom::Subpage::kAppManagement,
+ mojom::SearchResultIcon::kAppsGrid,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kAppManagementSubpagePath);
+ // Note: The subpage name in the UI is updated dynamically based on the app
+ // being shown, but we use a generic "App details" string here.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_APP_DETAILS_TITLE, mojom::Subpage::kAppDetails,
+ mojom::Subpage::kAppManagement, mojom::SearchResultIcon::kAppsGrid,
+ mojom::SearchResultDefaultRank::kMedium, mojom::kAppDetailsSubpagePath);
+ generator->RegisterNestedSubpage(IDS_SETTINGS_APPS_PLUGIN_VM_SHARED_PATHS,
+ mojom::Subpage::kPluginVmSharedPaths,
+ mojom::Subpage::kAppManagement,
+ mojom::SearchResultIcon::kAppsGrid,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kPluginVmSharedPathsSubpagePath);
+
+ // Google Play Store.
+ generator->RegisterTopLevelSubpage(IDS_SETTINGS_ANDROID_APPS_LABEL,
+ mojom::Subpage::kGooglePlayStore,
+ mojom::SearchResultIcon::kGooglePlay,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kGooglePlayStoreSubpagePath);
+ static constexpr mojom::Setting kGooglePlayStoreSettings[] = {
+ mojom::Setting::kManageAndroidPreferences,
+ mojom::Setting::kRemovePlayStore,
+ mojom::Setting::kTurnOnPlayStore,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kGooglePlayStore,
+ kGooglePlayStoreSettings, generator);
+}
+
void AppsSection::OnAppRegistered(const std::string& app_id,
const ArcAppListPrefs::AppInfo& app_info) {
UpdateAndroidSearchTags();
@@ -264,34 +312,52 @@ void AppsSection::AddPluginVmLoadTimeData(
IDS_SETTINGS_APPS_PLUGIN_VM_SHARED_PATHS_INSTRUCTIONS_REMOVE},
{"pluginVmSharedPathsRemoveSharing",
IDS_SETTINGS_APPS_PLUGIN_VM_SHARED_PATHS_REMOVE_SHARING},
+ {"pluginVmSharedPathsListEmptyMessage",
+ IDS_SETTINGS_APPS_PLUGIN_VM_SHARED_PATHS_LIST_EMPTY_MESSAGE},
+ {"pluginVmPermissionDialogCameraLabel",
+ IDS_SETTINGS_APPS_PLUGIN_VM_PERMISSION_DIALOG_CAMERA_LABEL},
+ {"pluginVmPermissionDialogMicrophoneLabel",
+ IDS_SETTINGS_APPS_PLUGIN_VM_PERMISSION_DIALOG_MICROPHONE_LABEL},
+ {"pluginVmPermissionDialogRelaunchButton",
+ IDS_SETTINGS_APPS_PLUGIN_VM_PERMISSION_DIALOG_RELAUNCH_BUTTON},
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings);
html_source->AddBoolean("showPluginVm",
ShowPluginVm(profile(), *pref_service_));
+ html_source->AddBoolean(
+ "showPluginVmCameraPermissions",
+ base::FeatureList::IsEnabled(
+ chromeos::features::kPluginVmShowCameraPermissions));
+ html_source->AddBoolean(
+ "showPluginVmMicrophonePermissions",
+ base::FeatureList::IsEnabled(
+ chromeos::features::kPluginVmShowMicrophonePermissions));
}
void AppsSection::UpdateAndroidSearchTags() {
- registry()->RemoveSearchTags(GetAndroidNoPlayStoreSearchConcepts());
- registry()->RemoveSearchTags(GetAndroidPlayStoreDisabledSearchConcepts());
- registry()->RemoveSearchTags(GetAndroidPlayStoreSearchConcepts());
- registry()->RemoveSearchTags(GetAndroidSettingsSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
+ updater.RemoveSearchTags(GetAndroidNoPlayStoreSearchConcepts());
+ updater.RemoveSearchTags(GetAndroidPlayStoreDisabledSearchConcepts());
+ updater.RemoveSearchTags(GetAndroidPlayStoreSearchConcepts());
+ updater.RemoveSearchTags(GetAndroidSettingsSearchConcepts());
if (!arc::IsPlayStoreAvailable()) {
- registry()->AddSearchTags(GetAndroidNoPlayStoreSearchConcepts());
+ updater.AddSearchTags(GetAndroidNoPlayStoreSearchConcepts());
return;
}
if (!arc::IsArcPlayStoreEnabledForProfile(profile())) {
- registry()->AddSearchTags(GetAndroidPlayStoreDisabledSearchConcepts());
+ updater.AddSearchTags(GetAndroidPlayStoreDisabledSearchConcepts());
return;
}
- registry()->AddSearchTags(GetAndroidPlayStoreSearchConcepts());
+ updater.AddSearchTags(GetAndroidPlayStoreSearchConcepts());
if (arc_app_list_prefs_ &&
arc_app_list_prefs_->IsRegistered(arc::kSettingsAppId)) {
- registry()->AddSearchTags(GetAndroidSettingsSearchConcepts());
+ updater.AddSearchTags(GetAndroidSettingsSearchConcepts());
}
}
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/apps_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/apps_section.h
index ba926ba1652..d5217f6c693 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/apps_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/apps_section.h
@@ -33,6 +33,11 @@ class AppsSection : public OsSettingsSection, public ArcAppListPrefs::Observer {
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
// ArcAppListPrefs::Observer:
void OnAppRegistered(const std::string& app_id,
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.cc
index 9b6fad55c74..2de04401ca6 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.cc
@@ -17,6 +17,8 @@
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/web_ui_data_source.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
+#include "device/bluetooth/bluetooth_device.h"
+#include "device/bluetooth/chromeos/bluetooth_utils.h"
#include "device/bluetooth/dbus/bluez_dbus_manager.h"
#include "device/bluetooth/strings/grit/bluetooth_strings.h"
#include "ui/base/l10n/l10n_util.h"
@@ -28,37 +30,12 @@ namespace {
const std::vector<SearchConcept>& GetBluetoothSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- {IDS_OS_SETTINGS_TAG_BLUETOOTH_PAIR,
- mojom::kBluetoothDevicesSubpagePath,
- mojom::SearchResultIcon::kBluetooth,
- mojom::SearchResultDefaultRank::kHigh,
- mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kBluetoothPairDevice}},
- {IDS_OS_SETTINGS_TAG_BLUETOOTH_CONNECT,
- mojom::kBluetoothDevicesSubpagePath,
- mojom::SearchResultIcon::kBluetooth,
- mojom::SearchResultDefaultRank::kHigh,
- mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kBluetoothConnectToDevice}},
{IDS_OS_SETTINGS_TAG_BLUETOOTH,
mojom::kBluetoothDevicesSubpagePath,
mojom::SearchResultIcon::kBluetooth,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kBluetoothDevices}},
- {IDS_OS_SETTINGS_TAG_BLUETOOTH_DISCONNECT,
- mojom::kBluetoothDevicesSubpagePath,
- mojom::SearchResultIcon::kBluetooth,
- mojom::SearchResultDefaultRank::kHigh,
- mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kBluetoothDisconnectFromDevice}},
- {IDS_OS_SETTINGS_TAG_BLUETOOTH_UNPAIR,
- mojom::kBluetoothDevicesSubpagePath,
- mojom::SearchResultIcon::kBluetooth,
- mojom::SearchResultDefaultRank::kHigh,
- mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kBluetoothUnpairDevice},
- {IDS_OS_SETTINGS_TAG_BLUETOOTH_UNPAIR_ALT1, SearchConcept::kAltTagEnd}},
});
return *tags;
}
@@ -68,7 +45,7 @@ const std::vector<SearchConcept>& GetBluetoothOnSearchConcepts() {
{IDS_OS_SETTINGS_TAG_BLUETOOTH_TURN_OFF,
mojom::kBluetoothDevicesSubpagePath,
mojom::SearchResultIcon::kBluetooth,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kBluetoothOnOff},
{IDS_OS_SETTINGS_TAG_BLUETOOTH_TURN_OFF_ALT1,
@@ -82,7 +59,7 @@ const std::vector<SearchConcept>& GetBluetoothOffSearchConcepts() {
{IDS_OS_SETTINGS_TAG_BLUETOOTH_TURN_ON,
mojom::kBluetoothDevicesSubpagePath,
mojom::SearchResultIcon::kBluetooth,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kBluetoothOnOff},
{IDS_OS_SETTINGS_TAG_BLUETOOTH_TURN_ON_ALT1, SearchConcept::kAltTagEnd}},
@@ -90,6 +67,55 @@ const std::vector<SearchConcept>& GetBluetoothOffSearchConcepts() {
return *tags;
}
+const std::vector<SearchConcept>& GetBluetoothConnectableSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_BLUETOOTH_CONNECT,
+ mojom::kBluetoothDevicesSubpagePath,
+ mojom::SearchResultIcon::kBluetooth,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kBluetoothConnectToDevice}},
+ });
+ return *tags;
+}
+
+const std::vector<SearchConcept>& GetBluetoothConnectedSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_BLUETOOTH_DISCONNECT,
+ mojom::kBluetoothDevicesSubpagePath,
+ mojom::SearchResultIcon::kBluetooth,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kBluetoothDisconnectFromDevice}},
+ });
+ return *tags;
+}
+
+const std::vector<SearchConcept>& GetBluetoothPairableSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_BLUETOOTH_PAIR,
+ mojom::kBluetoothDevicesSubpagePath,
+ mojom::SearchResultIcon::kBluetooth,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kBluetoothPairDevice}},
+ });
+ return *tags;
+}
+
+const std::vector<SearchConcept>& GetBluetoothPairedSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_BLUETOOTH_UNPAIR,
+ mojom::kBluetoothDevicesSubpagePath,
+ mojom::SearchResultIcon::kBluetooth,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kBluetoothUnpairDevice},
+ {IDS_OS_SETTINGS_TAG_BLUETOOTH_UNPAIR_ALT1, SearchConcept::kAltTagEnd}},
+ });
+ return *tags;
+}
+
} // namespace
BluetoothSection::BluetoothSection(Profile* profile,
@@ -165,6 +191,40 @@ void BluetoothSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
chromeos::bluetooth_dialog::AddLocalizedStrings(html_source);
}
+int BluetoothSection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_BLUETOOTH;
+}
+
+mojom::Section BluetoothSection::GetSection() const {
+ return mojom::Section::kBluetooth;
+}
+
+mojom::SearchResultIcon BluetoothSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kBluetooth;
+}
+
+std::string BluetoothSection::GetSectionPath() const {
+ return mojom::kBluetoothSectionPath;
+}
+
+void BluetoothSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSubpage(IDS_SETTINGS_BLUETOOTH,
+ mojom::Subpage::kBluetoothDevices,
+ mojom::SearchResultIcon::kBluetooth,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kBluetoothDevicesSubpagePath);
+ static constexpr mojom::Setting kBluetoothDevicesSettings[] = {
+ mojom::Setting::kBluetoothOnOff,
+ mojom::Setting::kBluetoothConnectToDevice,
+ mojom::Setting::kBluetoothDisconnectFromDevice,
+ mojom::Setting::kBluetoothPairDevice,
+ mojom::Setting::kBluetoothUnpairDevice,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kBluetoothDevices,
+ kBluetoothDevicesSettings, generator);
+ generator->RegisterTopLevelAltSetting(mojom::Setting::kBluetoothOnOff);
+}
+
void BluetoothSection::AdapterPresentChanged(device::BluetoothAdapter* adapter,
bool present) {
UpdateSearchTags();
@@ -175,6 +235,21 @@ void BluetoothSection::AdapterPoweredChanged(device::BluetoothAdapter* adapter,
UpdateSearchTags();
}
+void BluetoothSection::DeviceAdded(device::BluetoothAdapter* adapter,
+ device::BluetoothDevice* device) {
+ UpdateSearchTags();
+}
+
+void BluetoothSection::DeviceChanged(device::BluetoothAdapter* adapter,
+ device::BluetoothDevice* device) {
+ UpdateSearchTags();
+}
+
+void BluetoothSection::DeviceRemoved(device::BluetoothAdapter* adapter,
+ device::BluetoothDevice* device) {
+ UpdateSearchTags();
+}
+
void BluetoothSection::OnFetchBluetoothAdapter(
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter) {
bluetooth_adapter_ = bluetooth_adapter;
@@ -183,20 +258,60 @@ void BluetoothSection::OnFetchBluetoothAdapter(
}
void BluetoothSection::UpdateSearchTags() {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
// Start with no search tags, then add them below if appropriate.
- registry()->RemoveSearchTags(GetBluetoothSearchConcepts());
- registry()->RemoveSearchTags(GetBluetoothOnSearchConcepts());
- registry()->RemoveSearchTags(GetBluetoothOffSearchConcepts());
+ updater.RemoveSearchTags(GetBluetoothSearchConcepts());
+ updater.RemoveSearchTags(GetBluetoothOnSearchConcepts());
+ updater.RemoveSearchTags(GetBluetoothOffSearchConcepts());
+ updater.RemoveSearchTags(GetBluetoothConnectableSearchConcepts());
+ updater.RemoveSearchTags(GetBluetoothConnectedSearchConcepts());
+ updater.RemoveSearchTags(GetBluetoothPairableSearchConcepts());
+ updater.RemoveSearchTags(GetBluetoothPairedSearchConcepts());
if (!bluetooth_adapter_->IsPresent())
return;
- registry()->AddSearchTags(GetBluetoothSearchConcepts());
+ updater.AddSearchTags(GetBluetoothSearchConcepts());
+
+ if (!bluetooth_adapter_->IsPowered()) {
+ updater.AddSearchTags(GetBluetoothOffSearchConcepts());
+ return;
+ }
+
+ updater.AddSearchTags(GetBluetoothOnSearchConcepts());
+
+ // Filter devices so that only those shown in the UI are returned. Note that
+ // passing |max_devices| of 0 indicates that there is no maximum.
+ device::BluetoothAdapter::DeviceList devices =
+ device::FilterBluetoothDeviceList(bluetooth_adapter_->GetDevices(),
+ device::BluetoothFilterType::KNOWN,
+ /*max_devices=*/0);
+
+ bool connectable_device_exists = false;
+ bool connected_device_exists = false;
+ bool pairable_device_exists = false;
+ bool paired_device_exists = false;
+ for (const device::BluetoothDevice* device : devices) {
+ // Note: Device must be paired to be connectable.
+ if (device->IsPaired() && device->IsConnectable() && !device->IsConnected())
+ connectable_device_exists = true;
+ if (device->IsConnected())
+ connected_device_exists = true;
+ if (device->IsPairable() && !device->IsPaired())
+ pairable_device_exists = true;
+ if (device->IsPaired())
+ paired_device_exists = true;
+ }
- if (bluetooth_adapter_->IsPowered())
- registry()->AddSearchTags(GetBluetoothOnSearchConcepts());
- else
- registry()->AddSearchTags(GetBluetoothOffSearchConcepts());
+ if (connectable_device_exists)
+ updater.AddSearchTags(GetBluetoothConnectableSearchConcepts());
+ if (connected_device_exists)
+ updater.AddSearchTags(GetBluetoothConnectedSearchConcepts());
+ if (pairable_device_exists)
+ updater.AddSearchTags(GetBluetoothPairableSearchConcepts());
+ if (paired_device_exists)
+ updater.AddSearchTags(GetBluetoothPairedSearchConcepts());
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.h
index 0586828bb1f..e187a244e2b 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/bluetooth_section.h
@@ -31,12 +31,23 @@ class BluetoothSection : public OsSettingsSection,
private:
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
// device::BluetoothAdapter::Observer:
void AdapterPresentChanged(device::BluetoothAdapter* adapter,
bool present) override;
void AdapterPoweredChanged(device::BluetoothAdapter* adapter,
bool powered) override;
+ void DeviceAdded(device::BluetoothAdapter* adapter,
+ device::BluetoothDevice* device) override;
+ void DeviceChanged(device::BluetoothAdapter* adapter,
+ device::BluetoothDevice* device) override;
+ void DeviceRemoved(device::BluetoothAdapter* adapter,
+ device::BluetoothDevice* device) override;
void OnFetchBluetoothAdapter(
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter);
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator.cc
index 7c8d870bb91..5fd2a36e803 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator.cc
@@ -17,6 +17,7 @@
#include "chrome/browser/profiles/profile.h"
#include "chromeos/cryptohome/cryptohome_util.h"
#include "chromeos/dbus/cryptohome/cryptohome_client.h"
+#include "chromeos/dbus/dlcservice/dlcservice_client.h"
#include "components/arc/arc_service_manager.h"
#include "components/arc/session/arc_bridge_service.h"
#include "components/arc/storage_manager/arc_storage_manager.h"
@@ -392,6 +393,32 @@ void OtherUsersSizeCalculator::OnGetOtherUserSize(
NotifySizeCalculated(other_users_total_bytes);
}
+DlcsSizeCalculator::DlcsSizeCalculator()
+ : SizeCalculator(CalculationType::kDlcs) {}
+
+DlcsSizeCalculator::~DlcsSizeCalculator() = default;
+
+void DlcsSizeCalculator::PerformCalculation() {
+ DlcserviceClient::Get()->GetExistingDlcs(base::BindOnce(
+ &DlcsSizeCalculator::OnGetExistingDlcs, weak_ptr_factory_.GetWeakPtr()));
+}
+
+void DlcsSizeCalculator::OnGetExistingDlcs(
+ const std::string& err,
+ const dlcservice::DlcsWithContent& dlcs_with_content) {
+ if (err != dlcservice::kErrorNone) {
+ NotifySizeCalculated(0);
+ return;
+ }
+ base::ListValue dlc_metadata_list;
+ int64_t dlc_total_size_in_bytes = 0;
+ for (int i = 0; i < dlcs_with_content.dlc_infos_size(); i++) {
+ const auto& dlc_info = dlcs_with_content.dlc_infos(i);
+ dlc_total_size_in_bytes += dlc_info.used_bytes_on_disk();
+ }
+ NotifySizeCalculated(dlc_total_size_in_bytes);
+}
+
} // namespace calculator
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator.h b/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator.h
index 8f483f50b95..23fc718f6f6 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator.h
@@ -25,6 +25,10 @@
class Profile;
+namespace dlcservice {
+class DlcsWithContent;
+} // namespace dlcservice
+
namespace chromeos {
namespace settings {
namespace calculator {
@@ -42,7 +46,8 @@ class SizeCalculator {
kAppsExtensions,
kCrostini,
kOtherUsers,
- kLast = kOtherUsers,
+ kDlcs,
+ kLast = kDlcs,
kSystem,
};
@@ -289,6 +294,27 @@ class OtherUsersSizeCalculator : public SizeCalculator {
base::WeakPtrFactory<OtherUsersSizeCalculator> weak_ptr_factory_{this};
};
+// Class handling the calculation of all DLC size.
+class DlcsSizeCalculator : public SizeCalculator {
+ public:
+ DlcsSizeCalculator();
+ ~DlcsSizeCalculator() override;
+
+ DlcsSizeCalculator(const DlcsSizeCalculator&) = delete;
+ DlcsSizeCalculator& operator=(const DlcsSizeCalculator&) = delete;
+
+ private:
+ friend class DlcsSizeTestAPI;
+
+ void PerformCalculation() override;
+
+ // Callback to update the total size of existing DLCs.
+ void OnGetExistingDlcs(const std::string& err,
+ const dlcservice::DlcsWithContent& dlcs_with_content);
+
+ base::WeakPtrFactory<DlcsSizeCalculator> weak_ptr_factory_{this};
+};
+
} // namespace calculator
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator_test_api.h b/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator_test_api.h
index 2e0850df244..4a15d946c26 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator_test_api.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/calculator/size_calculator_test_api.h
@@ -149,6 +149,25 @@ class OtherUsersSizeTestAPI {
OtherUsersSizeCalculator* other_users_size_calculator_;
};
+class DlcsSizeTestAPI {
+ public:
+ explicit DlcsSizeTestAPI(StorageHandler* handler,
+ DlcsSizeCalculator* dlcs_size_calculator) {
+ dlcs_size_calculator_ = dlcs_size_calculator;
+ dlcs_size_calculator_->AddObserver(handler);
+ }
+
+ void StartCalculation() { dlcs_size_calculator_->StartCalculation(); }
+
+ void SimulateOnGetExistingDlcs(
+ const std::string& err,
+ const dlcservice::DlcsWithContent& dlcs_with_content) {
+ dlcs_size_calculator_->OnGetExistingDlcs(err, dlcs_with_content);
+ }
+
+ private:
+ DlcsSizeCalculator* dlcs_size_calculator_;
+};
} // namespace calculator
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/constants/constants_util.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/constants/constants_util.cc
index d5bdaf20d53..263d760b558 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/constants/constants_util.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/constants/constants_util.cc
@@ -17,7 +17,7 @@ std::vector<T> All() {
int32_t max_value = static_cast<int32_t>(T::kMaxValue);
std::vector<T> all;
- for (int32_t i = min_value; i < max_value; ++i) {
+ for (int32_t i = min_value; i <= max_value; ++i) {
T current = static_cast<T>(i);
// Not every value between the min and max values is valid:
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom b/chromium/chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom
index b1837490f1c..ecb574c87e6 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom
@@ -49,6 +49,7 @@ enum Subpage {
// MultiDevice section.
kMultiDeviceFeatures = 200,
kSmartLock = 201,
+ kNearbyShare = 202,
// People section.
kMyAccounts = 300,
@@ -61,19 +62,19 @@ enum Subpage {
kKerberos = 307,
// Device section.
- kDevice = 400,
- kPointers = 401,
- kKeyboard = 402,
- kStylus = 403,
- kDisplay = 404,
- kStorage = 405,
- kExternalStorage = 406,
- kDlc = 407,
- kPower = 408,
+ kPointers = 400,
+ kKeyboard = 401,
+ kStylus = 402,
+ kDisplay = 403,
+ kStorage = 404,
+ kExternalStorage = 405,
+ kDlc = 406,
+ kPower = 407,
// Personalization section.
kChangePicture = 500,
kAmbientMode = 501,
+ kAmbientModePhotos= 502,
// Search and Assistant section.
kAssistant = 600,
@@ -91,7 +92,6 @@ enum Subpage {
kCrostiniBackupAndRestore = 803,
kCrostiniDevelopAndroidApps = 804,
kCrostiniPortForwarding = 805,
- kCrostiniDiskResize = 806,
// Note: Deprecated Plugin VM section has no subpages.
@@ -104,6 +104,7 @@ enum Subpage {
kLanguagesAndInputDetails = 1200,
kManageInputMethods = 1201,
kSmartInputs = 1202,
+ kInputMethodOptions = 1203,
// Files section.
kNetworkFileShares = 1300,
@@ -143,6 +144,7 @@ const string kBluetoothDevicesSubpagePath = "bluetoothDevices";
const string kMultiDeviceSectionPath = "multidevice";
const string kMultiDeviceFeaturesSubpagePath = "multidevice/features";
const string kSmartLockSubpagePath = "multidevice/features/smartLock";
+const string kNearbyShareSubpagePath = "multidevice/nearbyshare";
// People section.
const string kPeopleSectionPath = "osPeople";
@@ -151,7 +153,7 @@ const string kSyncSubpagePath = "osSync";
const string kSyncDeprecatedSubpagePath = "syncSetup";
const string kSyncDeprecatedAdvancedSubpagePath = "syncSetup/advanced";
const string kSecurityAndSignInSubpagePath = "lockScreen";
-const string kFingerprintSubpathPath = "lockScreen/fingerprint";
+const string kFingerprintSubpagePath = "lockScreen/fingerprint";
const string kManageOtherPeopleSubpagePath = "accounts";
const string kKerberosSubpagePath = "kerberosAccounts";
@@ -170,6 +172,7 @@ const string kPowerSubpagePath = "power";
const string kPersonalizationSectionPath = "personalization";
const string kChangePictureSubpagePath = "changePicture";
const string kAmbientModeSubpagePath = "ambientMode";
+const string kAmbientModePhotosSubpagePath = "ambientMode/photos";
// Search and Assistant section.
const string kSearchAndAssistantSectionPath = "osSearch";
@@ -191,7 +194,6 @@ const string kCrostiniUsbPreferencesSubpagePath = "crostini/sharedUsbDevices";
const string kCrostiniBackupAndRestoreSubpagePath = "crostini/exportImport";
const string kCrostiniDevelopAndroidAppsSubpagePath = "crostini/androidAdb";
const string kCrostiniPortForwardingSubpagePath = "crostini/portForwarding";
-const string kCrostiniDiskResizeSubpagePath = "crostini/diskResize";
// Date and Time section.
const string kDateAndTimeSectionPath = "dateTime";
@@ -204,7 +206,8 @@ const string kPrivacyAndSecuritySectionPath = "osPrivacy";
const string kLanguagesAndInputSectionPath = "osLanguages";
const string kLanguagesAndInputDetailsSubpagePath = "osLanguages/details";
const string kManageInputMethodsSubpagePath = "osLanguages/inputMethods";
-const string kSmartInputsSubagePath = "osLanguages/smartInputs";
+const string kSmartInputsSubpagePath = "osLanguages/smartInputs";
+const string kInputMethodOptionsSubpagePath = "osLanguages/inputMethodOptions";
// Files section.
const string kFilesSectionPath = "files";
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/constants/routes_util.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/constants/routes_util.cc
index 957b28fd7cc..d2fa7499076 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/constants/routes_util.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/constants/routes_util.cc
@@ -37,13 +37,14 @@ bool IsOSSettingsSubPage(const std::string& sub_page) {
chromeos::settings::mojom::kMultiDeviceSectionPath,
chromeos::settings::mojom::kMultiDeviceFeaturesSubpagePath,
chromeos::settings::mojom::kSmartLockSubpagePath,
+ chromeos::settings::mojom::kNearbyShareSubpagePath,
// People section.
chromeos::settings::mojom::kPeopleSectionPath,
chromeos::settings::mojom::kMyAccountsSubpagePath,
chromeos::settings::mojom::kSyncSubpagePath,
chromeos::settings::mojom::kSecurityAndSignInSubpagePath,
- chromeos::settings::mojom::kFingerprintSubpathPath,
+ chromeos::settings::mojom::kFingerprintSubpagePath,
chromeos::settings::mojom::kManageOtherPeopleSubpagePath,
chromeos::settings::mojom::kKerberosSubpagePath,
@@ -82,7 +83,6 @@ bool IsOSSettingsSubPage(const std::string& sub_page) {
chromeos::settings::mojom::kCrostiniBackupAndRestoreSubpagePath,
chromeos::settings::mojom::kCrostiniDevelopAndroidAppsSubpagePath,
chromeos::settings::mojom::kCrostiniPortForwardingSubpagePath,
- chromeos::settings::mojom::kCrostiniDiskResizeSubpagePath,
// Date and Time section.
chromeos::settings::mojom::kDateAndTimeSectionPath,
@@ -95,7 +95,8 @@ bool IsOSSettingsSubPage(const std::string& sub_page) {
chromeos::settings::mojom::kLanguagesAndInputSectionPath,
chromeos::settings::mojom::kLanguagesAndInputDetailsSubpagePath,
chromeos::settings::mojom::kManageInputMethodsSubpagePath,
- chromeos::settings::mojom::kSmartInputsSubagePath,
+ chromeos::settings::mojom::kSmartInputsSubpagePath,
+ chromeos::settings::mojom::kInputMethodOptionsSubpagePath,
// Files section.
chromeos::settings::mojom::kFilesSectionPath,
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom b/chromium/chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom
index 634b625b075..19339269f3b 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom
@@ -16,7 +16,7 @@ enum Setting {
kDisconnectWifiNetwork = 5,
kPreferWifiNetwork = 6,
kForgetWifiNetwork = 7,
- kConfigureWifi = 8,
+ kWifiAddNetwork = 8,
kWifiAutoConfigureIp = 9,
kWifiDns = 10,
kWifiProxy = 11,
@@ -31,7 +31,9 @@ enum Setting {
kCellularProxy = 20,
kCellularAutoConnectToNetwork = 21,
kInstantTetheringOnOff = 22,
- kDisconnectTetherNetwork = 22,
+ kDisconnectTetherNetwork = 23,
+ kWifiMetered = 24,
+ kCellularMetered = 25,
// Bluetooth section.
kBluetoothOnOff = 100,
@@ -49,11 +51,12 @@ enum Setting {
kMessagesSetUp = 205,
kMessagesOnOff = 206,
kForgetPhone = 207,
+ kNearbyShareOnOff = 208,
// People section.
kAddAccount = 300,
kRemoveAccount = 301,
- kSyncOnOff = 302,
+ kSplitSyncOnOff = 302,
kLockScreen = 303,
kChangeAuthPin = 304,
kGuestBrowsing = 305,
@@ -67,6 +70,10 @@ enum Setting {
kAddFingerprint = 313,
kRemoveFingerprint = 314,
kSetUpParentalControls = 315,
+ kNonSplitSyncEncryptionOptions = 316,
+ kAutocompleteSearchesAndUrls = 317,
+ kMakeSearchesAndBrowsingBetter = 318,
+ kGoogleDriveSearchSuggestions = 319,
// Device section.
kTouchpadTapToClick = 400,
@@ -91,16 +98,26 @@ enum Setting {
kStylusLatestNoteOnLockScreen = 419,
kDisplayOrientation = 420,
kDisplayArrangement = 421,
- kPowerIdleBehavior = 422,
+ kPowerIdleBehaviorWhileCharging = 422,
kPowerSource = 423,
kSleepWhenLaptopLidClosed = 424,
kDisplayResolution = 425,
kDisplayRefreshRate = 426,
+ kRemoveDlc = 427,
+ kDisplayMirroring = 428,
+ kAllowWindowsToSpanDisplays = 429,
+ kAmbientColors = 430,
+ kTouchscreenCalibration = 431,
+ kNightLightColorTemperature = 432,
+ kPowerIdleBehaviorWhileOnBattery = 433,
+ kDisplayOverscan = 434,
// Personalization section.
kOpenWallpaper = 500,
kAmbientModeOnOff = 501,
kAmbientModeSource = 502,
+ kChangeDeviceAccountImage = 503,
+ kAmbientModeUpdatePhotosContainers = 504,
// Search and Assistant section.
kPreferredSearchEngine = 600,
@@ -110,6 +127,7 @@ enum Setting {
kAssistantOkGoogle = 604,
kAssistantNotifications = 605,
kAssistantVoiceInput = 606,
+ kTrainAssistantVoiceModel = 607,
// Apps section.
kManageAndroidPreferences = 700,
@@ -141,6 +159,7 @@ enum Setting {
kAddLanguage = 1200,
kShowInputOptionsInShelf = 1201,
kShowPersonalInformationSuggestions = 1202,
+ kShowEmojiSuggestions = 1203,
// Files section.
kGoogleDriveConnection = 1300,
@@ -178,6 +197,8 @@ enum Setting {
kSwitchActionAutoScan = 1524,
kSwitchActionAutoScanKeyboard = 1525,
kGetImageDescriptionsFromGoogle = 1526,
+ kLiveCaptions = 1527,
+ kEnableCursorColor = 1528,
// Reset section.
kPowerwash = 1600,
@@ -185,4 +206,9 @@ enum Setting {
// About Chrome OS section.
kChangeChromeChannel = 1700,
kCopyDetailedBuildInfo = 1701,
+ kCheckForOsUpdate = 1702,
+ kSeeWhatsNew = 1703,
+ kGetHelpWithChromeOs = 1704,
+ kReportAnIssue = 1705,
+ kTermsOfService = 1706,
};
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 bf1d6db4c78..5c934d15a17 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.cc
@@ -104,6 +104,11 @@ void CrostiniHandler::RegisterMessages() {
base::BindRepeating(&CrostiniHandler::HandleQueryArcAdbRequest,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback(
+ "getCanChangeArcAdbSideloading",
+ base::BindRepeating(
+ &CrostiniHandler::HandleCanChangeArcAdbSideloadingRequest,
+ weak_ptr_factory_.GetWeakPtr()));
+ web_ui()->RegisterMessageCallback(
"enableArcAdbSideload",
base::BindRepeating(&CrostiniHandler::HandleEnableArcAdbRequest,
weak_ptr_factory_.GetWeakPtr()));
@@ -191,6 +196,20 @@ void CrostiniHandler::OnJavascriptAllowed() {
}
crostini::CrostiniExportImport::GetForProfile(profile_)->AddObserver(this);
crostini::CrostiniPortForwarder::GetForProfile(profile_)->AddObserver(this);
+
+ // Observe ADB sideloading device policy and react to its changes
+ adb_sideloading_device_policy_subscription_ =
+ chromeos::CrosSettings::Get()->AddSettingsObserver(
+ chromeos::kDeviceCrostiniArcAdbSideloadingAllowed,
+ base::BindRepeating(&CrostiniHandler::FetchCanChangeAdbSideloading,
+ weak_ptr_factory_.GetWeakPtr()));
+
+ // Observe ADB sideloading user policy and react to its changes
+ pref_change_registrar_.Init(profile_->GetPrefs());
+ pref_change_registrar_.Add(
+ crostini::prefs::kCrostiniArcAdbSideloadingUserPref,
+ base::BindRepeating(&CrostiniHandler::FetchCanChangeAdbSideloading,
+ weak_ptr_factory_.GetWeakPtr()));
}
void CrostiniHandler::OnJavascriptDisallowed() {
@@ -206,6 +225,9 @@ void CrostiniHandler::OnJavascriptDisallowed() {
crostini::CrostiniExportImport::GetForProfile(profile_)->RemoveObserver(this);
crostini::CrostiniPortForwarder::GetForProfile(profile_)->RemoveObserver(
this);
+
+ adb_sideloading_device_policy_subscription_.reset();
+ pref_change_registrar_.RemoveAll();
}
void CrostiniHandler::HandleRequestCrostiniInstallerView(
@@ -437,7 +459,15 @@ void CrostiniHandler::OnQueryAdbSideload(
void CrostiniHandler::HandleEnableArcAdbRequest(const base::ListValue* args) {
CHECK_EQ(0U, args->GetList().size());
- if (!CheckEligibilityToChangeArcAdbSideloading())
+
+ crostini::CrostiniFeatures::Get()->CanChangeAdbSideloading(
+ profile_, base::BindOnce(&CrostiniHandler::OnCanEnableArcAdbSideloading,
+ weak_ptr_factory_.GetWeakPtr()));
+}
+
+void CrostiniHandler::OnCanEnableArcAdbSideloading(
+ bool can_change_adb_sideloading) {
+ if (!can_change_adb_sideloading)
return;
LogEvent(CrostiniSettingsEvent::kEnableAdbSideloading);
@@ -451,7 +481,15 @@ void CrostiniHandler::HandleEnableArcAdbRequest(const base::ListValue* args) {
void CrostiniHandler::HandleDisableArcAdbRequest(const base::ListValue* args) {
CHECK_EQ(0U, args->GetList().size());
- if (!CheckEligibilityToChangeArcAdbSideloading())
+
+ crostini::CrostiniFeatures::Get()->CanChangeAdbSideloading(
+ profile_, base::BindOnce(&CrostiniHandler::OnCanDisableArcAdbSideloading,
+ weak_ptr_factory_.GetWeakPtr()));
+}
+
+void CrostiniHandler::OnCanDisableArcAdbSideloading(
+ bool can_change_adb_sideloading) {
+ if (!can_change_adb_sideloading)
return;
LogEvent(CrostiniSettingsEvent::kDisableAdbSideloading);
@@ -464,10 +502,6 @@ void CrostiniHandler::HandleDisableArcAdbRequest(const base::ListValue* args) {
power_manager::REQUEST_RESTART_FOR_USER, "disable adb sideloading");
}
-bool CrostiniHandler::CheckEligibilityToChangeArcAdbSideloading() const {
- return crostini::CrostiniFeatures::Get()->CanChangeAdbSideloading(profile_);
-}
-
void CrostiniHandler::LaunchTerminal() {
crostini::LaunchCrostiniApp(
profile_, crostini::GetTerminalId(),
@@ -502,6 +536,26 @@ void CrostiniHandler::HandleQueryArcAdbRequest(const base::ListValue* args) {
weak_ptr_factory_.GetWeakPtr()));
}
+void CrostiniHandler::HandleCanChangeArcAdbSideloadingRequest(
+ const base::ListValue* args) {
+ AllowJavascript();
+ CHECK_EQ(0U, args->GetList().size());
+
+ FetchCanChangeAdbSideloading();
+}
+
+void CrostiniHandler::FetchCanChangeAdbSideloading() {
+ crostini::CrostiniFeatures::Get()->CanChangeAdbSideloading(
+ profile_, base::BindOnce(&CrostiniHandler::OnCanChangeArcAdbSideloading,
+ weak_ptr_factory_.GetWeakPtr()));
+}
+
+void CrostiniHandler::OnCanChangeArcAdbSideloading(
+ bool can_change_arc_adb_sideloading) {
+ FireWebUIListener("crostini-can-change-arc-adb-sideload-changed",
+ base::Value(can_change_arc_adb_sideloading));
+}
+
void CrostiniHandler::HandleCrostiniUpgraderDialogStatusRequest(
const base::ListValue* args) {
AllowJavascript();
@@ -536,6 +590,11 @@ void CrostiniHandler::HandleAddCrostiniPortForward(
int protocol_type = args->GetList()[4].GetInt();
std::string label = args->GetList()[5].GetString();
+ if (!crostini::CrostiniFeatures::Get()->IsPortForwardingAllowed(profile_)) {
+ OnPortForwardComplete(callback_id, false);
+ return;
+ }
+
crostini::CrostiniPortForwarder::GetForProfile(profile_)->AddPort(
crostini::ContainerId(std::move(vm_name), std::move(container_name)),
port_number,
@@ -559,6 +618,11 @@ void CrostiniHandler::HandleRemoveCrostiniPortForward(
int protocol_type;
CHECK(args->GetInteger(4, &protocol_type));
+ if (!crostini::CrostiniFeatures::Get()->IsPortForwardingAllowed(profile_)) {
+ OnPortForwardComplete(callback_id, false);
+ return;
+ }
+
crostini::CrostiniPortForwarder::GetForProfile(profile_)->RemovePort(
crostini::ContainerId(std::move(vm_name), std::move(container_name)),
port_number,
@@ -574,6 +638,10 @@ void CrostiniHandler::HandleRemoveAllCrostiniPortForwards(
std::string vm_name = args_list[0].GetString();
std::string container_name = args_list[1].GetString();
+ if (!crostini::CrostiniFeatures::Get()->IsPortForwardingAllowed(profile_)) {
+ return;
+ }
+
crostini::CrostiniPortForwarder::GetForProfile(profile_)->RemoveAllPorts(
crostini::ContainerId(std::move(vm_name), std::move(container_name)));
}
@@ -593,6 +661,11 @@ void CrostiniHandler::HandleActivateCrostiniPortForward(
int protocol_type;
CHECK(args->GetInteger(4, &protocol_type));
+ if (!crostini::CrostiniFeatures::Get()->IsPortForwardingAllowed(profile_)) {
+ OnPortForwardComplete(callback_id, false);
+ return;
+ }
+
crostini::CrostiniPortForwarder::GetForProfile(profile_)->ActivatePort(
crostini::ContainerId(std::move(vm_name), std::move(container_name)),
port_number,
@@ -616,6 +689,11 @@ void CrostiniHandler::HandleDeactivateCrostiniPortForward(
int protocol_type;
CHECK(args->GetInteger(4, &protocol_type));
+ if (!crostini::CrostiniFeatures::Get()->IsPortForwardingAllowed(profile_)) {
+ OnPortForwardComplete(callback_id, false);
+ return;
+ }
+
crostini::CrostiniPortForwarder::GetForProfile(profile_)->DeactivatePort(
crostini::ContainerId(std::move(vm_name), std::move(container_name)),
port_number,
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 b1f5b8162bc..5867245850c 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_handler.h
@@ -11,9 +11,11 @@
#include "chrome/browser/chromeos/crostini/crostini_export_import.h"
#include "chrome/browser/chromeos/crostini/crostini_manager.h"
#include "chrome/browser/chromeos/crostini/crostini_port_forwarder.h"
+#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/usb/cros_usb_detector.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "chromeos/dbus/session_manager/session_manager_client.h"
+#include "components/prefs/pref_change_registrar.h"
class Profile;
@@ -83,8 +85,14 @@ class CrostiniHandler : public ::settings::SettingsPageUIHandler,
void HandleQueryArcAdbRequest(const base::ListValue* args);
// Handle a request for enabling adb sideloading in ARC.
void HandleEnableArcAdbRequest(const base::ListValue* args);
+ // Called after establishing whether enabling adb sideloading is allowed for
+ // the user and device
+ void OnCanEnableArcAdbSideloading(bool can_change_adb_sideloading);
// Handle a request for disabling adb sideloading in ARC.
void HandleDisableArcAdbRequest(const base::ListValue* args);
+ // Called after establishing whether disabling adb sideloading is allowed for
+ // the user and device
+ void OnCanDisableArcAdbSideloading(bool can_change_adb_sideloading);
// Launch the Crostini terminal.
void LaunchTerminal();
// Handle a request for showing the container upgrade view.
@@ -93,9 +101,6 @@ class CrostiniHandler : public ::settings::SettingsPageUIHandler,
void OnQueryAdbSideload(
SessionManagerClient::AdbSideloadResponseCode response_code,
bool enabled);
- // Returns whether the current user can change adb sideloading configuration
- // on current device.
- bool CheckEligibilityToChangeArcAdbSideloading() const;
// Handle a request for the CrostiniUpgraderDialog status.
void HandleCrostiniUpgraderDialogStatusRequest(const base::ListValue* args);
// Handle a request for the availability of a container upgrade.
@@ -142,8 +147,17 @@ class CrostiniHandler : public ::settings::SettingsPageUIHandler,
void HandleSetCrostiniMicSharingEnabled(const base::ListValue* args);
// Handles a request for getting the permissions for Crostini Mic access.
void HandleGetCrostiniMicSharingEnabled(const base::ListValue* args);
+ // Handle a request for checking permission for changing ARC adb sideloading.
+ void HandleCanChangeArcAdbSideloadingRequest(const base::ListValue* args);
+ // Get permission of changing ARC adb sideloading
+ void FetchCanChangeAdbSideloading();
+ // Callback of FetchCanChangeAdbSideloading.
+ void OnCanChangeArcAdbSideloading(bool can_change_arc_adb_sideloading);
Profile* profile_;
+ std::unique_ptr<chromeos::CrosSettings::ObserverSubscription>
+ adb_sideloading_device_policy_subscription_;
+ PrefChangeRegistrar pref_change_registrar_;
// weak_ptr_factory_ should always be last member.
base::WeakPtrFactory<CrostiniHandler> weak_ptr_factory_{this};
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_section.cc
index f25ce803272..546c2ff9270 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_section.cc
@@ -36,21 +36,15 @@ namespace chromeos {
namespace settings {
namespace {
-const std::vector<SearchConcept>& GetCrostiniSearchConcepts() {
+const std::vector<SearchConcept>& GetCrostiniOptedInSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_CROSTINI,
mojom::kCrostiniDetailsSubpagePath,
mojom::SearchResultIcon::kPenguin,
- mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultDefaultRank::kHigh,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kCrostiniDetails},
{IDS_OS_SETTINGS_TAG_CROSTINI_ALT1, SearchConcept::kAltTagEnd}},
- });
- return *tags;
-}
-
-const std::vector<SearchConcept>& GetCrostiniOptedInSearchConcepts() {
- static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_CROSTINI_USB_PREFERENCES,
mojom::kCrostiniUsbPreferencesSubpagePath,
mojom::SearchResultIcon::kPenguin,
@@ -88,6 +82,13 @@ const std::vector<SearchConcept>& GetCrostiniOptedInSearchConcepts() {
const std::vector<SearchConcept>& GetCrostiniOptedOutSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_CROSTINI,
+ mojom::kCrostiniSectionPath,
+ mojom::SearchResultIcon::kPenguin,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSection,
+ {.section = mojom::Section::kCrostini},
+ {IDS_OS_SETTINGS_TAG_CROSTINI_ALT1, SearchConcept::kAltTagEnd}},
{IDS_OS_SETTINGS_TAG_CROSTINI_SETUP,
mojom::kCrostiniSectionPath,
mojom::SearchResultIcon::kPenguin,
@@ -205,10 +206,6 @@ bool IsAdbSideloadingAllowed() {
return base::FeatureList::IsEnabled(features::kArcAdbSideloadingFeature);
}
-bool IsPortForwardingAllowed() {
- return base::FeatureList::IsEnabled(features::kCrostiniPortForwarding);
-}
-
bool IsDiskResizingAllowed() {
return base::FeatureList::IsEnabled(features::kCrostiniDiskResizing);
}
@@ -320,16 +317,22 @@ void CrostiniSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
IDS_SETTINGS_CROSTINI_PORT_FORWARDING_ADD_PORT_BUTTON_DESCRIPTION},
{"crostiniPortForwardingAddPortDialogTitle",
IDS_SETTINGS_CROSTINI_PORT_FORWARDING_ADD_PORT_DIALOG_TITLE},
- {"crostiniPortForwardingAddPortDialogLabel",
- IDS_SETTINGS_CROSTINI_PORT_FORWARDING_ADD_PORT_DIALOG_LABEL},
+ {"crostiniPortForwardingAddPortDialogPortNumberLabel",
+ IDS_SETTINGS_CROSTINI_PORT_FORWARDING_ADD_PORT_DIALOG_PORT_NUMBER_LABEL},
+ {"crostiniPortForwardingAddPortDialogLabelLabel",
+ IDS_SETTINGS_CROSTINI_PORT_FORWARDING_ADD_PORT_DIALOG_LABEL_LABEL},
{"crostiniPortForwardingTCP", IDS_SETTINGS_CROSTINI_PORT_FORWARDING_TCP},
{"crostiniPortForwardingUDP", IDS_SETTINGS_CROSTINI_PORT_FORWARDING_UDP},
{"crostiniPortForwardingAddError",
IDS_SETTINGS_CROSTINI_PORT_FORWARDING_ADD_ERROR},
+ {"crostiniPortForwardingAddExisting",
+ IDS_SETTINGS_CROSTINI_PORT_FORWARDING_ADD_EXISTING},
{"crostiniPortForwardingRemoveAllPorts",
IDS_SETTINGS_CROSTINI_PORT_FORWARDING_REMOVE_ALL_PORTS},
{"crostiniPortForwardingRemovePort",
IDS_SETTINGS_CROSTINI_PORT_FORWARDING_REMOVE_PORT},
+ {"crostiniPortForwardingActivatePortError",
+ IDS_SETTINGS_CROSTINI_PORT_FORWARDING_ACTIVATE_PORT_ERROR},
{"crostiniPortForwardingToggleAriaLabel",
IDS_SETTINGS_CROSTINI_PORT_FORWARDING_TOGGLE_PORT_ARIA_LABEL},
{"crostiniPortForwardingRemoveAllPortsAriaLabel",
@@ -432,9 +435,6 @@ void CrostiniSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
chromeos::ProfileHelper::IsOwnerProfile(profile()));
html_source->AddBoolean("isEnterpriseManaged",
IsDeviceManaged() || IsProfileManaged(profile()));
- html_source->AddBoolean(
- "canChangeAdbSideloading",
- crostini::CrostiniFeatures::Get()->CanChangeAdbSideloading(profile()));
html_source->AddBoolean("showCrostiniContainerUpgrade",
IsContainerUpgradeAllowed());
html_source->AddBoolean("showCrostiniDiskResize", IsDiskResizingAllowed());
@@ -448,6 +448,89 @@ void CrostiniSection::AddHandlers(content::WebUI* web_ui) {
}
}
+int CrostiniSection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_CROSTINI_TITLE;
+}
+
+mojom::Section CrostiniSection::GetSection() const {
+ return mojom::Section::kCrostini;
+}
+
+mojom::SearchResultIcon CrostiniSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kPenguin;
+}
+
+std::string CrostiniSection::GetSectionPath() const {
+ return mojom::kCrostiniSectionPath;
+}
+
+void CrostiniSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSetting(mojom::Setting::kSetUpCrostini);
+
+ // Crostini details.
+ generator->RegisterTopLevelSubpage(IDS_SETTINGS_CROSTINI_LABEL,
+ mojom::Subpage::kCrostiniDetails,
+ mojom::SearchResultIcon::kPenguin,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kCrostiniDetailsSubpagePath);
+ static constexpr mojom::Setting kCrostiniDetailsSettings[] = {
+ mojom::Setting::kCrostiniContainerUpgrade,
+ mojom::Setting::kCrostiniDiskResize,
+ mojom::Setting::kCrostiniMicAccess,
+ mojom::Setting::kUninstallCrostini,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kCrostiniDetails,
+ kCrostiniDetailsSettings, generator);
+
+ // Manage shared folders.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_CROSTINI_SHARED_PATHS,
+ mojom::Subpage::kCrostiniManageSharedFolders,
+ mojom::Subpage::kCrostiniDetails, mojom::SearchResultIcon::kPenguin,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kCrostiniManageSharedFoldersSubpagePath);
+
+ // USB preferences.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_CROSTINI_SHARED_USB_DEVICES_LABEL,
+ mojom::Subpage::kCrostiniUsbPreferences, mojom::Subpage::kCrostiniDetails,
+ mojom::SearchResultIcon::kPenguin,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kCrostiniUsbPreferencesSubpagePath);
+
+ // Backup and restore.
+ generator->RegisterNestedSubpage(IDS_SETTINGS_CROSTINI_EXPORT_IMPORT_TITLE,
+ mojom::Subpage::kCrostiniBackupAndRestore,
+ mojom::Subpage::kCrostiniDetails,
+ mojom::SearchResultIcon::kPenguin,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kCrostiniBackupAndRestoreSubpagePath);
+ static constexpr mojom::Setting kCrostiniBackupAndRestoreSettings[] = {
+ mojom::Setting::kBackupLinuxAppsAndFiles,
+ mojom::Setting::kRestoreLinuxAppsAndFiles,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kCrostiniBackupAndRestore,
+ kCrostiniBackupAndRestoreSettings, generator);
+
+ // Develop Android apps.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_CROSTINI_ARC_ADB_TITLE,
+ mojom::Subpage::kCrostiniDevelopAndroidApps,
+ mojom::Subpage::kCrostiniDetails, mojom::SearchResultIcon::kPenguin,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kCrostiniDevelopAndroidAppsSubpagePath);
+ generator->RegisterNestedSetting(mojom::Setting::kCrostiniAdbDebugging,
+ mojom::Subpage::kCrostiniDevelopAndroidApps);
+
+ // Port forwarding.
+ generator->RegisterNestedSubpage(IDS_SETTINGS_CROSTINI_PORT_FORWARDING,
+ mojom::Subpage::kCrostiniPortForwarding,
+ mojom::Subpage::kCrostiniDetails,
+ mojom::SearchResultIcon::kPenguin,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kCrostiniPortForwardingSubpagePath);
+}
+
bool CrostiniSection::IsCrostiniAllowed() {
return crostini::CrostiniFeatures::Get()->IsUIAllowed(profile(),
/*check_policy=*/false);
@@ -461,48 +544,51 @@ bool CrostiniSection::IsContainerUpgradeAllowed() {
return crostini::ShouldAllowContainerUpgrade(profile());
}
+bool CrostiniSection::IsPortForwardingAllowed() {
+ return crostini::CrostiniFeatures::Get()->IsPortForwardingAllowed(profile());
+}
+
void CrostiniSection::UpdateSearchTags() {
- registry()->RemoveSearchTags(GetCrostiniSearchConcepts());
- registry()->RemoveSearchTags(GetCrostiniOptedInSearchConcepts());
- registry()->RemoveSearchTags(GetCrostiniOptedOutSearchConcepts());
- registry()->RemoveSearchTags(GetCrostiniExportImportSearchConcepts());
- registry()->RemoveSearchTags(GetCrostiniAdbSideloadingSearchConcepts());
- registry()->RemoveSearchTags(GetCrostiniPortForwardingSearchConcepts());
- registry()->RemoveSearchTags(GetCrostiniContainerUpgradeSearchConcepts());
- registry()->RemoveSearchTags(GetCrostiniDiskResizingSearchConcepts());
- registry()->RemoveSearchTags(GetCrostiniMicSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
+ updater.RemoveSearchTags(GetCrostiniOptedInSearchConcepts());
+ updater.RemoveSearchTags(GetCrostiniOptedOutSearchConcepts());
+ updater.RemoveSearchTags(GetCrostiniExportImportSearchConcepts());
+ updater.RemoveSearchTags(GetCrostiniAdbSideloadingSearchConcepts());
+ updater.RemoveSearchTags(GetCrostiniPortForwardingSearchConcepts());
+ updater.RemoveSearchTags(GetCrostiniContainerUpgradeSearchConcepts());
+ updater.RemoveSearchTags(GetCrostiniDiskResizingSearchConcepts());
+ updater.RemoveSearchTags(GetCrostiniMicSearchConcepts());
if (!IsCrostiniAllowed())
return;
- registry()->AddSearchTags(GetCrostiniSearchConcepts());
-
if (!pref_service_->GetBoolean(crostini::prefs::kCrostiniEnabled)) {
- registry()->AddSearchTags(GetCrostiniOptedOutSearchConcepts());
+ updater.AddSearchTags(GetCrostiniOptedOutSearchConcepts());
return;
}
- registry()->AddSearchTags(GetCrostiniOptedInSearchConcepts());
+ updater.AddSearchTags(GetCrostiniOptedInSearchConcepts());
if (IsExportImportAllowed())
- registry()->AddSearchTags(GetCrostiniExportImportSearchConcepts());
+ updater.AddSearchTags(GetCrostiniExportImportSearchConcepts());
if (IsAdbSideloadingAllowed() &&
pref_service_->GetBoolean(arc::prefs::kArcEnabled)) {
- registry()->AddSearchTags(GetCrostiniAdbSideloadingSearchConcepts());
+ updater.AddSearchTags(GetCrostiniAdbSideloadingSearchConcepts());
}
if (IsPortForwardingAllowed())
- registry()->AddSearchTags(GetCrostiniPortForwardingSearchConcepts());
+ updater.AddSearchTags(GetCrostiniPortForwardingSearchConcepts());
if (IsContainerUpgradeAllowed())
- registry()->AddSearchTags(GetCrostiniContainerUpgradeSearchConcepts());
+ updater.AddSearchTags(GetCrostiniContainerUpgradeSearchConcepts());
if (IsDiskResizingAllowed())
- registry()->AddSearchTags(GetCrostiniDiskResizingSearchConcepts());
+ updater.AddSearchTags(GetCrostiniDiskResizingSearchConcepts());
if (IsMicSettingAllowed())
- registry()->AddSearchTags(GetCrostiniMicSearchConcepts());
+ updater.AddSearchTags(GetCrostiniMicSearchConcepts());
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_section.h
index ee51c4be36f..e7caf6a65ea 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/crostini_section.h
@@ -31,10 +31,16 @@ class CrostiniSection : public OsSettingsSection {
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
bool IsCrostiniAllowed();
bool IsExportImportAllowed();
bool IsContainerUpgradeAllowed();
+ bool IsPortForwardingAllowed();
void UpdateSearchTags();
PrefService* pref_service_;
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 6031f1951fa..74b1ac7cc36 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
@@ -27,6 +27,7 @@
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/printing/cups_printers_manager.h"
#include "chrome/browser/chromeos/printing/ppd_provider_factory.h"
+#include "chrome/browser/chromeos/printing/print_management/print_management_uma.h"
#include "chrome/browser/chromeos/printing/printer_configurer.h"
#include "chrome/browser/chromeos/printing/printer_event_tracker.h"
#include "chrome/browser/chromeos/printing/printer_event_tracker_factory.h"
@@ -241,15 +242,15 @@ Printer::PpdReference GetPpdReference(const base::Value* info) {
Printer::PpdReference ret;
- if (user_supplied_ppd_url != nullptr) {
+ if (user_supplied_ppd_url) {
ret.user_supplied_ppd_url = user_supplied_ppd_url->GetString();
}
- if (effective_make_and_model != nullptr) {
+ if (effective_make_and_model) {
ret.effective_make_and_model = effective_make_and_model->GetString();
}
- if (autoconf != nullptr) {
+ if (autoconf) {
ret.autoconf = autoconf->GetBool();
}
@@ -998,6 +999,7 @@ void CupsPrintersHandler::HandleStartDiscovery(const base::ListValue* args) {
UMA_HISTOGRAM_COUNTS_100(
"Printing.CUPS.PrintersDiscovered",
discovered_printers_.size() + automatic_printers_.size());
+ printers_manager_->RecordNearbyNetworkPrinterCounts();
// Scan completes immediately right now. Emit done.
FireWebUIListener("on-printer-discovery-done");
}
@@ -1328,7 +1330,8 @@ void CupsPrintersHandler::HandleOpenPrintManagementApp(
DCHECK(args->empty());
DCHECK(
base::FeatureList::IsEnabled(chromeos::features::kPrintJobManagementApp));
- chrome::ShowPrintManagementApp(profile_);
+ chrome::ShowPrintManagementApp(profile_,
+ PrintManagementAppEntryPoint::kSettings);
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc
index 36193fc66fa..00cd8e56cb4 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler_unittest.cc
@@ -10,13 +10,17 @@
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/json/json_string_value_serializer.h"
+#include "base/test/metrics/histogram_tester.h"
+#include "base/test/scoped_feature_list.h"
#include "base/values.h"
+#include "chrome/browser/chromeos/printing/print_management/print_management_uma.h"
#include "chrome/browser/chromeos/printing/printing_stubs.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_core_service_factory.h"
#include "chrome/browser/download/download_core_service_impl.h"
#include "chrome/browser/ui/chrome_select_file_policy.h"
#include "chrome/test/base/testing_profile.h"
+#include "chromeos/constants/chromeos_features.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/debug_daemon/debug_daemon_client.h"
#include "content/public/test/browser_task_environment.h"
@@ -192,6 +196,8 @@ class CupsPrintersHandlerTest : public testing::Test {
~CupsPrintersHandlerTest() override = default;
void SetUp() override {
+ scoped_feature_list_.InitWithFeatures(
+ {chromeos::features::kPrintJobManagementApp}, {});
printers_handler_ = CupsPrintersHandler::CreateForTesting(
&profile_, base::MakeRefCounted<FakePpdProvider>(),
std::make_unique<StubPrinterConfigurer>(), &printers_manager_);
@@ -201,11 +207,13 @@ class CupsPrintersHandlerTest : public testing::Test {
protected:
// Must outlive |profile_|.
+ base::HistogramTester histogram_tester_;
content::BrowserTaskEnvironment task_environment_;
TestingProfile profile_;
content::TestWebUI web_ui_;
std::unique_ptr<CupsPrintersHandler> printers_handler_;
TestCupsPrintersManager printers_manager_;
+ base::test::ScopedFeatureList scoped_feature_list_;
};
TEST_F(CupsPrintersHandlerTest, RemoveCorrectPrinter) {
@@ -253,5 +261,24 @@ TEST_F(CupsPrintersHandlerTest, VerifyOnlyPpdFilesAllowed) {
web_ui_.HandleReceivedMessage("selectPPDFile",
&base::Value::AsListValue(args));
}
+
+TEST_F(CupsPrintersHandlerTest, VerifyPrintManagementAppEntryPointHistogram) {
+ base::Value args(base::Value::Type::LIST);
+ web_ui_.HandleReceivedMessage("openPrintManagementApp",
+ &base::Value::AsListValue(args));
+ histogram_tester_.ExpectBucketCount(
+ "Printing.Cups.PrintManagementAppEntryPoint",
+ PrintManagementAppEntryPoint::kSettings, 1);
+ histogram_tester_.ExpectBucketCount(
+ "Printing.Cups.PrintManagementAppEntryPoint",
+ PrintManagementAppEntryPoint::kNotification, 0);
+ histogram_tester_.ExpectBucketCount(
+ "Printing.Cups.PrintManagementAppEntryPoint",
+ PrintManagementAppEntryPoint::kLauncher, 0);
+ histogram_tester_.ExpectBucketCount(
+ "Printing.Cups.PrintManagementAppEntryPoint",
+ PrintManagementAppEntryPoint::kBrowser, 0);
+}
+
} // namespace settings.
} // namespace chromeos.
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 dac0db6e52d..0c1df37cc1e 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
@@ -58,7 +58,7 @@ bool IsTimezoneAutomaticDetectionUserEditable() {
if (IsSystemTimezoneAutomaticDetectionManaged()) {
return GetSystemTimezoneAutomaticDetectionPolicyValue() ==
- enterprise_management::SystemTimezoneProto::USERS_DECIDE;
+ enterprise_management::SystemTimezoneProto::USERS_DECIDE;
}
return true;
@@ -156,7 +156,7 @@ void DateTimeHandler::HandleShowParentAccessForTimeZone(
base::BindOnce(&DateTimeHandler::OnParentAccessValidation,
weak_ptr_factory_.GetWeakPtr()),
ash::ParentAccessRequestReason::kChangeTimezone, false /* extra_dimmer */,
- base::Time());
+ base::Time::Now());
}
void DateTimeHandler::OnParentAccessValidation(bool success) {
@@ -166,10 +166,9 @@ void DateTimeHandler::OnParentAccessValidation(bool success) {
void DateTimeHandler::NotifyTimezoneAutomaticDetectionPolicy() {
bool managed = !IsTimezoneAutomaticDetectionUserEditable();
- bool force_enabled = managed &&
- g_browser_process->platform_part()
- ->GetTimezoneResolverManager()
- ->ShouldApplyResolvedTimezone();
+ bool force_enabled = managed && g_browser_process->platform_part()
+ ->GetTimezoneResolverManager()
+ ->ShouldApplyResolvedTimezone();
FireWebUIListener("time-zone-auto-detect-policy", base::Value(managed),
base::Value(force_enabled));
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_section.cc
index 529689f68dc..8899d28d0e1 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_section.cc
@@ -19,6 +19,7 @@
#include "chromeos/settings/cros_settings_names.h"
#include "chromeos/settings/system_settings_provider.h"
#include "chromeos/settings/timezone_settings.h"
+#include "components/user_manager/user_manager.h"
#include "content/public/browser/web_ui_data_source.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
@@ -71,18 +72,23 @@ const std::vector<SearchConcept>& GetNoFineGrainedTimeZoneSearchConcepts() {
return *tags;
}
+bool IsFineGrainedTimeZoneEnabled() {
+ SystemSettingsProvider provider;
+ return provider.Get(chromeos::kFineGrainedTimeZoneResolveEnabled)->GetBool();
+}
+
} // namespace
DateTimeSection::DateTimeSection(Profile* profile,
SearchTagRegistry* search_tag_registry)
: OsSettingsSection(profile, search_tag_registry) {
- registry()->AddSearchTags(GetDateTimeSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetDateTimeSearchConcepts());
- SystemSettingsProvider provider;
- if (provider.Get(chromeos::kFineGrainedTimeZoneResolveEnabled)->GetBool())
- registry()->AddSearchTags(GetFineGrainedTimeZoneSearchConcepts());
+ if (IsFineGrainedTimeZoneEnabled())
+ updater.AddSearchTags(GetFineGrainedTimeZoneSearchConcepts());
else
- registry()->AddSearchTags(GetNoFineGrainedTimeZoneSearchConcepts());
+ updater.AddSearchTags(GetNoFineGrainedTimeZoneSearchConcepts());
}
DateTimeSection::~DateTimeSection() = default;
@@ -127,11 +133,49 @@ void DateTimeSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
html_source->AddBoolean(
"timeActionsProtectedForChild",
base::FeatureList::IsEnabled(features::kParentAccessCodeForTimeChange));
+
+ bool is_child = user_manager::UserManager::Get()->GetActiveUser()->IsChild();
+ html_source->AddBoolean("isChild", is_child);
}
void DateTimeSection::AddHandlers(content::WebUI* web_ui) {
web_ui->AddMessageHandler(std::make_unique<DateTimeHandler>());
}
+int DateTimeSection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_DATE_TIME;
+}
+
+mojom::Section DateTimeSection::GetSection() const {
+ return mojom::Section::kDateAndTime;
+}
+
+mojom::SearchResultIcon DateTimeSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kClock;
+}
+
+std::string DateTimeSection::GetSectionPath() const {
+ return mojom::kDateAndTimeSectionPath;
+}
+
+void DateTimeSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSetting(mojom::Setting::k24HourClock);
+
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_TIME_ZONE_SUBPAGE_TITLE, mojom::Subpage::kTimeZone,
+ mojom::SearchResultIcon::kClock, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kTimeZoneSubpagePath);
+
+ // When fine-grained time zone is enabled, users change the time zone on the
+ // time zone subpage; otherwise, the setting is directly embedded in the
+ // section.
+ if (IsFineGrainedTimeZoneEnabled()) {
+ generator->RegisterNestedSetting(mojom::Setting::kChangeTimeZone,
+ mojom::Subpage::kTimeZone);
+ } else {
+ generator->RegisterTopLevelSetting(mojom::Setting::kChangeTimeZone);
+ }
+}
+
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_section.h
index 2c1d8e0f5c3..7eef9df9516 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/date_time_section.h
@@ -26,6 +26,11 @@ class DateTimeSection : public OsSettingsSection {
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
};
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler.cc
index 38eb1b57fef..c90f34eff69 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler.cc
@@ -36,28 +36,32 @@ DlcHandler::~DlcHandler() = default;
void DlcHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(
- "getDlcList", base::BindRepeating(&DlcHandler::HandleGetDlcList,
- weak_ptr_factory_.GetWeakPtr()));
+ "dlcSubpageReady", base::BindRepeating(&DlcHandler::HandleDlcSubpageReady,
+ base::Unretained(this)));
web_ui()->RegisterMessageCallback(
- "purgeDlc", base::BindRepeating(&DlcHandler::HandlePurgeDlc,
- weak_ptr_factory_.GetWeakPtr()));
+ "purgeDlc",
+ base::BindRepeating(&DlcHandler::HandlePurgeDlc, base::Unretained(this)));
+}
+
+void DlcHandler::OnJavascriptAllowed() {
+ dlcservice_client_observer_.Add(DlcserviceClient::Get());
}
void DlcHandler::OnJavascriptDisallowed() {
+ dlcservice_client_observer_.RemoveAll();
+
// Ensure that pending callbacks do not complete and cause JS to be evaluated.
weak_ptr_factory_.InvalidateWeakPtrs();
}
-void DlcHandler::HandleGetDlcList(const base::ListValue* args) {
- AllowJavascript();
- CHECK_EQ(1U, args->GetSize());
- const base::Value* callback_id;
- CHECK(args->Get(0, &callback_id));
+void DlcHandler::OnDlcStateChanged(const dlcservice::DlcState& dlc_state) {
+ FetchDlcList();
+}
- DlcserviceClient::Get()->GetExistingDlcs(
- base::BindOnce(&DlcHandler::GetDlcListCallback,
- weak_ptr_factory_.GetWeakPtr(), callback_id->Clone()));
+void DlcHandler::HandleDlcSubpageReady(const base::ListValue* args) {
+ AllowJavascript();
+ FetchDlcList();
}
void DlcHandler::HandlePurgeDlc(const base::ListValue* args) {
@@ -74,16 +78,18 @@ void DlcHandler::HandlePurgeDlc(const base::ListValue* args) {
weak_ptr_factory_.GetWeakPtr(), callback_id->Clone()));
}
-void DlcHandler::GetDlcListCallback(
- const base::Value& callback_id,
+void DlcHandler::FetchDlcList() {
+ DlcserviceClient::Get()->GetExistingDlcs(
+ base::BindOnce(&DlcHandler::SendDlcList, weak_ptr_factory_.GetWeakPtr()));
+}
+
+void DlcHandler::SendDlcList(
const std::string& err,
const dlcservice::DlcsWithContent& dlcs_with_content) {
- if (err == dlcservice::kErrorNone) {
- ResolveJavascriptCallback(callback_id,
- DlcsWithContentToListValue(dlcs_with_content));
- return;
- }
- ResolveJavascriptCallback(callback_id, base::ListValue());
+ FireWebUIListener("dlc-list-changed",
+ err == dlcservice::kErrorNone
+ ? DlcsWithContentToListValue(dlcs_with_content)
+ : base::ListValue());
}
void DlcHandler::PurgeDlcCallback(const base::Value& callback_id,
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler.h
index 27afcaf2de6..cbd3f798c74 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler.h
@@ -6,6 +6,7 @@
#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_DEVICE_DLC_HANDLER_H_
#include "base/memory/weak_ptr.h"
+#include "base/scoped_observer.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "chromeos/dbus/dlcservice/dlcservice_client.h"
@@ -17,7 +18,8 @@ namespace chromeos {
namespace settings {
// Chrome OS Downloaded Content settings page UI handler.
-class DlcHandler : public ::settings::SettingsPageUIHandler {
+class DlcHandler : public ::settings::SettingsPageUIHandler,
+ public DlcserviceClient::Observer {
public:
DlcHandler();
DlcHandler(const DlcHandler&) = delete;
@@ -26,22 +28,32 @@ class DlcHandler : public ::settings::SettingsPageUIHandler {
// SettingsPageUIHandler:
void RegisterMessages() override;
- void OnJavascriptAllowed() override {}
+ void OnJavascriptAllowed() override;
void OnJavascriptDisallowed() override;
+ // DlcserviceClient::Observer:
+ void OnDlcStateChanged(const dlcservice::DlcState& dlc_state) override;
+
private:
- // Handler to get the latest list of DLCs.
- void HandleGetDlcList(const base::ListValue* args);
+ // Handler called when DLC subpage is attached.
+ void HandleDlcSubpageReady(const base::ListValue* args);
// Handler to purge a DLC.
void HandlePurgeDlc(const base::ListValue* args);
- void GetDlcListCallback(const base::Value& callback_id,
- const std::string& err,
- const dlcservice::DlcsWithContent& dlcs_with_content);
+ // Fetches the latest DLC list from DlcserviceClient, passing SendDlcList() as
+ // the callback.
+ void FetchDlcList();
+
+ // Sends DLC list to web UIs listening in on 'dlc-list-changed' events.
+ void SendDlcList(const std::string& err,
+ const dlcservice::DlcsWithContent& dlcs_with_content);
void PurgeDlcCallback(const base::Value& callback_id, const std::string& err);
+ ScopedObserver<DlcserviceClient, DlcserviceClient::Observer>
+ dlcservice_client_observer_{this};
+
base::WeakPtrFactory<DlcHandler> weak_ptr_factory_{this};
};
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler_unittest.cc
index cb4dbc5dde8..b99ed70fcde 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_dlc_handler_unittest.cc
@@ -42,14 +42,14 @@ class DlcHandlerTest : public testing::Test {
void SetUp() override {
test_web_ui_ = std::make_unique<content::TestWebUI>();
+ chromeos::DlcserviceClient::InitializeFake();
+ fake_dlcservice_client_ = static_cast<chromeos::FakeDlcserviceClient*>(
+ chromeos::DlcserviceClient::Get());
+
handler_ = std::make_unique<TestDlcHandler>();
handler_->set_web_ui(test_web_ui_.get());
handler_->RegisterMessages();
handler_->AllowJavascriptForTesting();
-
- chromeos::DlcserviceClient::InitializeFake();
- fake_dlcservice_client_ = static_cast<chromeos::FakeDlcserviceClient*>(
- chromeos::DlcserviceClient::Get());
}
void TearDown() override {
@@ -70,12 +70,12 @@ class DlcHandlerTest : public testing::Test {
return *test_web_ui_->call_data()[index];
}
- base::Value::ConstListView CallGetDlcListAndReturnList() {
+ base::Value::ConstListView NotifyDlcSubpageReadyAndReturnDlcList() {
size_t call_data_count_before_call = test_web_ui()->call_data().size();
base::ListValue args;
args.AppendString("handlerFunctionName");
- test_web_ui()->HandleReceivedMessage("getDlcList", &args);
+ test_web_ui()->HandleReceivedMessage("dlcSubpageReady", &args);
task_environment_.RunUntilIdle();
EXPECT_EQ(call_data_count_before_call + 1u,
@@ -83,9 +83,9 @@ class DlcHandlerTest : public testing::Test {
const content::TestWebUI::CallData& call_data =
CallDataAtIndex(call_data_count_before_call);
- EXPECT_EQ("cr.webUIResponse", call_data.function_name());
- EXPECT_EQ("handlerFunctionName", call_data.arg1()->GetString());
- return call_data.arg3()->GetList();
+ EXPECT_EQ("cr.webUIListenerCallback", call_data.function_name());
+ EXPECT_EQ("dlc-list-changed", call_data.arg1()->GetString());
+ return call_data.arg2()->GetList();
}
bool CallPurgeDlcAndReturnSuccess() {
@@ -108,26 +108,45 @@ class DlcHandlerTest : public testing::Test {
}
};
-TEST_F(DlcHandlerTest, GetDlcList) {
+TEST_F(DlcHandlerTest, SendDlcListOnDlcStatusChange) {
+ size_t call_data_count_before_call = test_web_ui()->call_data().size();
+ fake_dlcservice_client_->set_dlcs_with_content(CreateDlcModuleListOfSize(2u));
+
+ dlcservice::DlcState dlc_state;
+ dlc_state.set_state(dlcservice::DlcState::INSTALLING);
+ fake_dlcservice_client_->NotifyObserversForTest(dlc_state);
+ task_environment_.RunUntilIdle();
+
+ EXPECT_EQ(call_data_count_before_call + 1u,
+ test_web_ui()->call_data().size());
+
+ const content::TestWebUI::CallData& call_data =
+ CallDataAtIndex(call_data_count_before_call);
+ EXPECT_EQ("cr.webUIListenerCallback", call_data.function_name());
+ EXPECT_EQ("dlc-list-changed", call_data.arg1()->GetString());
+ EXPECT_EQ(call_data.arg2()->GetList().size(), 2u);
+}
+
+TEST_F(DlcHandlerTest, CorrectlyReturnsDlcMetadataListOnSubpageReady) {
fake_dlcservice_client_->set_dlcs_with_content(CreateDlcModuleListOfSize(2u));
fake_dlcservice_client_->SetGetExistingDlcsError(dlcservice::kErrorInternal);
- EXPECT_EQ(CallGetDlcListAndReturnList().size(), 0u);
+ EXPECT_EQ(NotifyDlcSubpageReadyAndReturnDlcList().size(), 0u);
fake_dlcservice_client_->SetGetExistingDlcsError(
dlcservice::kErrorNeedReboot);
- EXPECT_EQ(CallGetDlcListAndReturnList().size(), 0u);
+ EXPECT_EQ(NotifyDlcSubpageReadyAndReturnDlcList().size(), 0u);
fake_dlcservice_client_->SetGetExistingDlcsError(
dlcservice::kErrorInvalidDlc);
- EXPECT_EQ(CallGetDlcListAndReturnList().size(), 0u);
+ EXPECT_EQ(NotifyDlcSubpageReadyAndReturnDlcList().size(), 0u);
fake_dlcservice_client_->SetGetExistingDlcsError(
dlcservice::kErrorAllocation);
- EXPECT_EQ(CallGetDlcListAndReturnList().size(), 0u);
+ EXPECT_EQ(NotifyDlcSubpageReadyAndReturnDlcList().size(), 0u);
fake_dlcservice_client_->SetGetExistingDlcsError(dlcservice::kErrorNone);
- EXPECT_EQ(CallGetDlcListAndReturnList().size(), 2u);
+ EXPECT_EQ(NotifyDlcSubpageReadyAndReturnDlcList().size(), 2u);
}
TEST_F(DlcHandlerTest, PurgeDlc) {
@@ -157,7 +176,7 @@ TEST_F(DlcHandlerTest, FormattedCorrectly) {
fake_dlcservice_client_->set_dlcs_with_content(dlcs_with_content);
- auto result_list = CallGetDlcListAndReturnList();
+ auto result_list = NotifyDlcSubpageReadyAndReturnDlcList();
EXPECT_EQ(1UL, result_list.size());
EXPECT_EQ("fake id", result_list[0].FindKey("id")->GetString());
EXPECT_EQ("fake name", result_list[0].FindKey("name")->GetString());
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_section.cc
index 440b8feb397..7921e8838dd 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_section.cc
@@ -48,7 +48,7 @@ const std::vector<SearchConcept>& GetDeviceSearchConcepts() {
{IDS_OS_SETTINGS_TAG_KEYBOARD,
mojom::kKeyboardSubpagePath,
mojom::SearchResultIcon::kKeyboard,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kKeyboard}},
{IDS_OS_SETTINGS_TAG_KEYBOARD_AUTO_REPEAT,
@@ -81,7 +81,7 @@ const std::vector<SearchConcept>& GetDeviceSearchConcepts() {
{IDS_OS_SETTINGS_TAG_STORAGE,
mojom::kStorageSubpagePath,
mojom::SearchResultIcon::kHardDrive,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kStorage},
{IDS_OS_SETTINGS_TAG_STORAGE_ALT1, IDS_OS_SETTINGS_TAG_STORAGE_ALT2,
@@ -89,7 +89,7 @@ const std::vector<SearchConcept>& GetDeviceSearchConcepts() {
{IDS_OS_SETTINGS_TAG_DISPLAY_NIGHT_LIGHT,
mojom::kDisplaySubpagePath,
mojom::SearchResultIcon::kDisplay,
- mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultDefaultRank::kLow,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kNightLight},
{IDS_OS_SETTINGS_TAG_DISPLAY_NIGHT_LIGHT_ALT1,
@@ -98,7 +98,7 @@ const std::vector<SearchConcept>& GetDeviceSearchConcepts() {
{IDS_OS_SETTINGS_TAG_DISPLAY,
mojom::kDisplaySubpagePath,
mojom::SearchResultIcon::kDisplay,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kDisplay},
{IDS_OS_SETTINGS_TAG_DISPLAY_ALT1, IDS_OS_SETTINGS_TAG_DISPLAY_ALT2,
@@ -121,13 +121,22 @@ const std::vector<SearchConcept>& GetDeviceSearchConcepts() {
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kKeyboardFunctionKeys}},
- {IDS_OS_SETTINGS_TAG_POWER_IDLE,
+ {IDS_OS_SETTINGS_TAG_POWER_IDLE_WHILE_CHARGING,
mojom::kPowerSubpagePath,
mojom::SearchResultIcon::kPower,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kPowerIdleBehavior},
- {IDS_OS_SETTINGS_TAG_POWER_IDLE_ALT1, SearchConcept::kAltTagEnd}},
+ {.setting = mojom::Setting::kPowerIdleBehaviorWhileCharging},
+ {IDS_OS_SETTINGS_TAG_POWER_IDLE_WHILE_CHARGING_ALT1,
+ SearchConcept::kAltTagEnd}},
+ {IDS_OS_SETTINGS_TAG_POWER_IDLE_WHILE_ON_BATTERY,
+ mojom::kPowerSubpagePath,
+ mojom::SearchResultIcon::kPower,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kPowerIdleBehaviorWhileOnBattery},
+ {IDS_OS_SETTINGS_TAG_POWER_IDLE_WHILE_ON_BATTERY_ALT1,
+ SearchConcept::kAltTagEnd}},
});
return *tags;
}
@@ -155,7 +164,7 @@ const std::vector<SearchConcept>& GetTouchpadSearchConcepts() {
{IDS_OS_SETTINGS_TAG_TOUCHPAD,
mojom::kPointersSubpagePath,
mojom::SearchResultIcon::kLaptop,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kPointers},
{IDS_OS_SETTINGS_TAG_TOUCHPAD_ALT1, SearchConcept::kAltTagEnd}},
@@ -210,7 +219,7 @@ const std::vector<SearchConcept>& GetMouseSearchConcepts() {
{IDS_OS_SETTINGS_TAG_MOUSE,
mojom::kPointersSubpagePath,
mojom::SearchResultIcon::kMouse,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kPointers}},
{IDS_OS_SETTINGS_TAG_MOUSE_SCROLL_ACCELERATION,
@@ -281,36 +290,30 @@ const std::vector<SearchConcept>& GetDisplayArrangementSearchConcepts() {
const std::vector<SearchConcept>& GetDisplayMirrorSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- // TODO(khorimoto): Add "Display mirror" search concepts.
+ {IDS_OS_SETTINGS_TAG_MIRRORING,
+ mojom::kDisplaySubpagePath,
+ mojom::SearchResultIcon::kDisplay,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kDisplayMirroring}},
});
return *tags;
}
const std::vector<SearchConcept>& GetDisplayUnifiedDesktopSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- // TODO(khorimoto): Add "Display with Unified Desktop" search concepts.
- });
- return *tags;
-}
-
-const std::vector<SearchConcept>& GetDisplayMultipleSearchConcepts() {
- static const base::NoDestructor<std::vector<SearchConcept>> tags({
- // TODO(khorimoto): Add "Display multiple" search concepts.
+ {IDS_OS_SETTINGS_TAG_UNIFIED_DESKTOP,
+ mojom::kDisplaySubpagePath,
+ mojom::SearchResultIcon::kDisplay,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kAllowWindowsToSpanDisplays}},
});
return *tags;
}
const std::vector<SearchConcept>& GetDisplayExternalSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- {IDS_OS_SETTINGS_TAG_DISPLAY_ORIENTATION,
- mojom::kDisplaySubpagePath,
- mojom::SearchResultIcon::kDisplay,
- mojom::SearchResultDefaultRank::kMedium,
- mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kDisplayOrientation},
- {IDS_OS_SETTINGS_TAG_DISPLAY_ORIENTATION_ALT1,
- IDS_OS_SETTINGS_TAG_DISPLAY_ORIENTATION_ALT2,
- SearchConcept::kAltTagEnd}},
{IDS_OS_SETTINGS_TAG_DISPLAY_RESOLUTION,
mojom::kDisplaySubpagePath,
mojom::SearchResultIcon::kDisplay,
@@ -320,6 +323,12 @@ const std::vector<SearchConcept>& GetDisplayExternalSearchConcepts() {
{IDS_OS_SETTINGS_TAG_DISPLAY_RESOLUTION_ALT1,
IDS_OS_SETTINGS_TAG_DISPLAY_RESOLUTION_ALT2,
SearchConcept::kAltTagEnd}},
+ {IDS_OS_SETTINGS_TAG_DISPLAY_OVERSCAN,
+ mojom::kDisplaySubpagePath,
+ mojom::SearchResultIcon::kDisplay,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kDisplayOverscan}},
});
return *tags;
}
@@ -342,28 +351,74 @@ GetDisplayExternalWithRefreshSearchConcepts() {
const std::vector<SearchConcept>& GetDisplayOrientationSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- // TODO(khorimoto): Add "Display orientation" search concepts.
+ {IDS_OS_SETTINGS_TAG_DISPLAY_ORIENTATION,
+ mojom::kDisplaySubpagePath,
+ mojom::SearchResultIcon::kDisplay,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kDisplayOrientation},
+ {IDS_OS_SETTINGS_TAG_DISPLAY_ORIENTATION_ALT1,
+ SearchConcept::kAltTagEnd}},
});
return *tags;
}
const std::vector<SearchConcept>& GetDisplayAmbientSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- // TODO(khorimoto): Add "Display ambient" search concepts.
+ {IDS_OS_SETTINGS_TAG_DISPLAY_AMBIENT_COLORS,
+ mojom::kDisplaySubpagePath,
+ mojom::SearchResultIcon::kDisplay,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kAmbientColors}},
});
return *tags;
}
const std::vector<SearchConcept>& GetDisplayTouchCalibrationSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- // TODO(khorimoto): Add "Display touch calibration" search concepts.
+ {IDS_OS_SETTINGS_TAG_DISPLAY_TOUCHSCREEN_CALIBRATION,
+ mojom::kDisplaySubpagePath,
+ mojom::SearchResultIcon::kDisplay,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kTouchscreenCalibration}},
});
return *tags;
}
const std::vector<SearchConcept>& GetDisplayNightLightOnSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- // TODO(khorimoto): Add "Display Night Light on" search concepts.
+ {IDS_OS_SETTINGS_TAG_NIGHT_LIGHT_COLOR_TEMPERATURE,
+ mojom::kDisplaySubpagePath,
+ mojom::SearchResultIcon::kDisplay,
+ mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kNightLightColorTemperature}},
+ });
+ return *tags;
+}
+
+const std::vector<SearchConcept>& GetDlcSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_DOWNLOADED_CONTENT,
+ mojom::kDlcSubpagePath,
+ mojom::SearchResultIcon::kHardDrive,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSubpage,
+ {.subpage = mojom::Subpage::kDlc},
+ {IDS_OS_SETTINGS_TAG_DOWNLOADED_CONTENT_ALT1,
+ SearchConcept::kAltTagEnd}},
+ {IDS_OS_SETTINGS_TAG_REMOVE_DOWNLOADED_CONTENT,
+ mojom::kDlcSubpagePath,
+ mojom::SearchResultIcon::kHardDrive,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kRemoveDlc},
+ {IDS_OS_SETTINGS_TAG_REMOVE_DOWNLOADED_CONTENT_ALT1,
+ IDS_OS_SETTINGS_TAG_REMOVE_DOWNLOADED_CONTENT_ALT2,
+ IDS_OS_SETTINGS_TAG_REMOVE_DOWNLOADED_CONTENT_ALT3,
+ SearchConcept::kAltTagEnd}},
});
return *tags;
}
@@ -694,10 +749,11 @@ DeviceSection::DeviceSection(Profile* profile,
PrefService* pref_service)
: OsSettingsSection(profile, search_tag_registry),
pref_service_(pref_service) {
- registry()->AddSearchTags(GetDeviceSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetDeviceSearchConcepts());
if (features::ShouldShowExternalStorageSettings(profile))
- registry()->AddSearchTags(GetExternalStorageSearchConcepts());
+ updater.AddSearchTags(GetExternalStorageSearchConcepts());
PowerManagerClient* power_manager_client = PowerManagerClient::Get();
if (power_manager_client) {
@@ -739,6 +795,14 @@ DeviceSection::DeviceSection(Profile* profile,
OnNightLightEnabledChanged(
ash::NightLightController::GetInstance()->GetEnabled());
}
+
+ // DLC settings search tags are added/removed dynamically.
+ DlcserviceClient* dlcservice_client = DlcserviceClient::Get();
+ if (features::ShouldShowDlcSettings() && dlcservice_client) {
+ dlcservice_client->AddObserver(this);
+ dlcservice_client->GetExistingDlcs(base::BindOnce(
+ &DeviceSection::OnGetExistingDlcs, weak_ptr_factory_.GetWeakPtr()));
+ }
}
DeviceSection::~DeviceSection() {
@@ -753,6 +817,10 @@ DeviceSection::~DeviceSection() {
ash::NightLightController::GetInstance();
if (night_light_controller)
night_light_controller->RemoveObserver(this);
+
+ DlcserviceClient* dlcservice_client = DlcserviceClient::Get();
+ if (features::ShouldShowDlcSettings() && dlcservice_client)
+ dlcservice_client->RemoveObserver(this);
}
void DeviceSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
@@ -797,18 +865,140 @@ void DeviceSection::AddHandlers(content::WebUI* web_ui) {
std::make_unique<chromeos::settings::StylusHandler>());
}
+int DeviceSection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_DEVICE_TITLE;
+}
+
+mojom::Section DeviceSection::GetSection() const {
+ return mojom::Section::kDevice;
+}
+
+mojom::SearchResultIcon DeviceSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kLaptop;
+}
+
+std::string DeviceSection::GetSectionPath() const {
+ return mojom::kDeviceSectionPath;
+}
+
+void DeviceSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ // Pointers.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_MOUSE_AND_TOUCHPAD_TITLE, mojom::Subpage::kPointers,
+ mojom::SearchResultIcon::kMouse, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kPointersSubpagePath);
+ static constexpr mojom::Setting kPointersSettings[] = {
+ mojom::Setting::kTouchpadTapToClick,
+ mojom::Setting::kTouchpadTapDragging,
+ mojom::Setting::kTouchpadReverseScrolling,
+ mojom::Setting::kTouchpadAcceleration,
+ mojom::Setting::kTouchpadScrollAcceleration,
+ mojom::Setting::kTouchpadSpeed,
+ mojom::Setting::kMouseSwapPrimaryButtons,
+ mojom::Setting::kMouseReverseScrolling,
+ mojom::Setting::kMouseAcceleration,
+ mojom::Setting::kMouseScrollAcceleration,
+ mojom::Setting::kMouseSpeed,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kPointers, kPointersSettings,
+ generator);
+
+ // Keyboard.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_KEYBOARD_TITLE, mojom::Subpage::kKeyboard,
+ mojom::SearchResultIcon::kKeyboard,
+ mojom::SearchResultDefaultRank::kMedium, mojom::kKeyboardSubpagePath);
+ static constexpr mojom::Setting kKeyboardSettings[] = {
+ mojom::Setting::kKeyboardFunctionKeys,
+ mojom::Setting::kKeyboardAutoRepeat,
+ mojom::Setting::kKeyboardShortcuts,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kKeyboard, kKeyboardSettings,
+ generator);
+
+ // Stylus.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_STYLUS_TITLE, mojom::Subpage::kStylus,
+ mojom::SearchResultIcon::kStylus, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kStylusSubpagePath);
+ static constexpr mojom::Setting kStylusSettings[] = {
+ mojom::Setting::kStylusToolsInShelf,
+ mojom::Setting::kStylusNoteTakingApp,
+ mojom::Setting::kStylusNoteTakingFromLockScreen,
+ mojom::Setting::kStylusLatestNoteOnLockScreen,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kStylus, kStylusSettings,
+ generator);
+
+ // Display.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_DISPLAY_TITLE, mojom::Subpage::kDisplay,
+ mojom::SearchResultIcon::kDisplay,
+ mojom::SearchResultDefaultRank::kMedium, mojom::kDisplaySubpagePath);
+ static constexpr mojom::Setting kDisplaySettings[] = {
+ mojom::Setting::kDisplaySize,
+ mojom::Setting::kNightLight,
+ mojom::Setting::kDisplayOrientation,
+ mojom::Setting::kDisplayArrangement,
+ mojom::Setting::kDisplayResolution,
+ mojom::Setting::kDisplayRefreshRate,
+ mojom::Setting::kDisplayMirroring,
+ mojom::Setting::kAllowWindowsToSpanDisplays,
+ mojom::Setting::kAmbientColors,
+ mojom::Setting::kTouchscreenCalibration,
+ mojom::Setting::kNightLightColorTemperature,
+ mojom::Setting::kDisplayOverscan,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kDisplay, kDisplaySettings,
+ generator);
+
+ // Storage.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_STORAGE_TITLE, mojom::Subpage::kStorage,
+ mojom::SearchResultIcon::kHardDrive,
+ mojom::SearchResultDefaultRank::kMedium, mojom::kStorageSubpagePath);
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_STORAGE_EXTERNAL, mojom::Subpage::kExternalStorage,
+ mojom::Subpage::kStorage, mojom::SearchResultIcon::kHardDrive,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kExternalStorageSubpagePath);
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_DLC_SUBPAGE_TITLE, mojom::Subpage::kDlc,
+ mojom::Subpage::kStorage, mojom::SearchResultIcon::kHardDrive,
+ mojom::SearchResultDefaultRank::kMedium, mojom::kDlcSubpagePath);
+ generator->RegisterNestedSetting(mojom::Setting::kRemoveDlc,
+ mojom::Subpage::kDlc);
+
+ // Power.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_POWER_TITLE, mojom::Subpage::kPower,
+ mojom::SearchResultIcon::kPower, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kPowerSubpagePath);
+ static constexpr mojom::Setting kPowerSettings[] = {
+ mojom::Setting::kPowerIdleBehaviorWhileCharging,
+ mojom::Setting::kPowerIdleBehaviorWhileOnBattery,
+ mojom::Setting::kPowerSource,
+ mojom::Setting::kSleepWhenLaptopLidClosed,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kPower, kPowerSettings, generator);
+}
+
void DeviceSection::TouchpadExists(bool exists) {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
if (exists)
- registry()->AddSearchTags(GetTouchpadSearchConcepts());
+ updater.AddSearchTags(GetTouchpadSearchConcepts());
else
- registry()->RemoveSearchTags(GetTouchpadSearchConcepts());
+ updater.RemoveSearchTags(GetTouchpadSearchConcepts());
}
void DeviceSection::MouseExists(bool exists) {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
if (exists)
- registry()->AddSearchTags(GetMouseSearchConcepts());
+ updater.AddSearchTags(GetMouseSearchConcepts());
else
- registry()->RemoveSearchTags(GetMouseSearchConcepts());
+ updater.RemoveSearchTags(GetMouseSearchConcepts());
}
void DeviceSection::OnDeviceListsComplete() {
@@ -828,12 +1018,32 @@ void DeviceSection::OnDisplayConfigChanged() {
void DeviceSection::PowerChanged(
const power_manager::PowerSupplyProperties& properties) {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
if (properties.battery_state() !=
power_manager::PowerSupplyProperties_BatteryState_NOT_PRESENT) {
- registry()->AddSearchTags(GetPowerWithBatterySearchConcepts());
+ updater.AddSearchTags(GetPowerWithBatterySearchConcepts());
}
}
+void DeviceSection::OnGetExistingDlcs(
+ const std::string& err,
+ const dlcservice::DlcsWithContent& dlcs_with_content) {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
+ if (err != dlcservice::kErrorNone ||
+ dlcs_with_content.dlc_infos_size() == 0) {
+ updater.RemoveSearchTags(GetDlcSearchConcepts());
+ return;
+ }
+ updater.AddSearchTags(GetDlcSearchConcepts());
+}
+
+void DeviceSection::OnDlcStateChanged(const dlcservice::DlcState& dlc_state) {
+ DlcserviceClient::Get()->GetExistingDlcs(base::BindOnce(
+ &DeviceSection::OnGetExistingDlcs, weak_ptr_factory_.GetWeakPtr()));
+}
+
void DeviceSection::OnGetDisplayUnitInfoList(
std::vector<ash::mojom::DisplayUnitInfoPtr> display_unit_info_list) {
cros_display_config_->GetDisplayLayoutInfo(base::BindOnce(
@@ -863,73 +1073,71 @@ void DeviceSection::OnGetDisplayLayoutInfo(
ash::mojom::DisplayLayoutMode::kUnified;
}
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
// Arrangement UI.
if (has_multiple_displays || is_mirrored)
- registry()->AddSearchTags(GetDisplayArrangementSearchConcepts());
+ updater.AddSearchTags(GetDisplayArrangementSearchConcepts());
else
- registry()->RemoveSearchTags(GetDisplayArrangementSearchConcepts());
+ updater.RemoveSearchTags(GetDisplayArrangementSearchConcepts());
// Mirror toggle.
if (is_mirrored || (!unified_desktop_mode && has_multiple_displays))
- registry()->AddSearchTags(GetDisplayMirrorSearchConcepts());
+ updater.AddSearchTags(GetDisplayMirrorSearchConcepts());
else
- registry()->RemoveSearchTags(GetDisplayMirrorSearchConcepts());
+ updater.RemoveSearchTags(GetDisplayMirrorSearchConcepts());
// Unified Desktop toggle.
if (unified_desktop_mode ||
(IsUnifiedDesktopAvailable() && has_multiple_displays && !is_mirrored)) {
- registry()->AddSearchTags(GetDisplayUnifiedDesktopSearchConcepts());
+ updater.AddSearchTags(GetDisplayUnifiedDesktopSearchConcepts());
} else {
- registry()->RemoveSearchTags(GetDisplayUnifiedDesktopSearchConcepts());
+ updater.RemoveSearchTags(GetDisplayUnifiedDesktopSearchConcepts());
}
- // Multiple displays UI.
- if (has_multiple_displays)
- registry()->AddSearchTags(GetDisplayMultipleSearchConcepts());
- else
- registry()->RemoveSearchTags(GetDisplayMultipleSearchConcepts());
-
// External display settings.
if (has_external_display)
- registry()->AddSearchTags(GetDisplayExternalSearchConcepts());
+ updater.AddSearchTags(GetDisplayExternalSearchConcepts());
else
- registry()->RemoveSearchTags(GetDisplayExternalSearchConcepts());
+ updater.RemoveSearchTags(GetDisplayExternalSearchConcepts());
// Refresh Rate dropdown.
if (has_external_display && IsListAllDisplayModesEnabled())
- registry()->AddSearchTags(GetDisplayExternalWithRefreshSearchConcepts());
+ updater.AddSearchTags(GetDisplayExternalWithRefreshSearchConcepts());
else
- registry()->RemoveSearchTags(GetDisplayExternalWithRefreshSearchConcepts());
+ updater.RemoveSearchTags(GetDisplayExternalWithRefreshSearchConcepts());
// Orientation settings.
if (!unified_desktop_mode)
- registry()->AddSearchTags(GetDisplayOrientationSearchConcepts());
+ updater.AddSearchTags(GetDisplayOrientationSearchConcepts());
else
- registry()->RemoveSearchTags(GetDisplayOrientationSearchConcepts());
+ updater.RemoveSearchTags(GetDisplayOrientationSearchConcepts());
// Ambient color settings.
if (DoesDeviceSupportAmbientColor() && has_internal_display)
- registry()->AddSearchTags(GetDisplayAmbientSearchConcepts());
+ updater.AddSearchTags(GetDisplayAmbientSearchConcepts());
else
- registry()->RemoveSearchTags(GetDisplayAmbientSearchConcepts());
+ updater.RemoveSearchTags(GetDisplayAmbientSearchConcepts());
// Touch calibration settings.
if (IsTouchCalibrationAvailable())
- registry()->AddSearchTags(GetDisplayTouchCalibrationSearchConcepts());
+ updater.AddSearchTags(GetDisplayTouchCalibrationSearchConcepts());
else
- registry()->RemoveSearchTags(GetDisplayTouchCalibrationSearchConcepts());
+ updater.RemoveSearchTags(GetDisplayTouchCalibrationSearchConcepts());
// Night Light on settings.
if (ash::NightLightController::GetInstance()->GetEnabled())
- registry()->AddSearchTags(GetDisplayNightLightOnSearchConcepts());
+ updater.AddSearchTags(GetDisplayNightLightOnSearchConcepts());
else
- registry()->RemoveSearchTags(GetDisplayNightLightOnSearchConcepts());
+ updater.RemoveSearchTags(GetDisplayNightLightOnSearchConcepts());
}
void DeviceSection::OnGotSwitchStates(
base::Optional<PowerManagerClient::SwitchStates> result) {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
if (result && result->lid_state != PowerManagerClient::LidState::NOT_PRESENT)
- registry()->AddSearchTags(GetPowerWithLaptopLidSearchConcepts());
+ updater.AddSearchTags(GetPowerWithLaptopLidSearchConcepts());
}
void DeviceSection::UpdateStylusSearchTags() {
@@ -937,13 +1145,15 @@ void DeviceSection::UpdateStylusSearchTags() {
if (!ui::DeviceDataManager::GetInstance()->AreDeviceListsComplete())
return;
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
// TODO(https://crbug.com/1071905): Only show stylus settings if a stylus has
// been set up. HasStylusInput() will return true for any stylus-compatible
// device, even if it doesn't have a stylus.
if (ash::stylus_utils::HasStylusInput())
- registry()->AddSearchTags(GetStylusSearchConcepts());
+ updater.AddSearchTags(GetStylusSearchConcepts());
else
- registry()->RemoveSearchTags(GetStylusSearchConcepts());
+ updater.RemoveSearchTags(GetStylusSearchConcepts());
}
void DeviceSection::AddDevicePointersStrings(
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/device_section.h
index 255f63a4963..541b8dbaafc 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_section.h
@@ -13,6 +13,7 @@
#include "base/optional.h"
#include "chrome/browser/chromeos/system/pointer_device_observer.h"
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_section.h"
+#include "chromeos/dbus/dlcservice/dlcservice_client.h"
#include "chromeos/dbus/power/power_manager_client.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
@@ -24,6 +25,10 @@ namespace content {
class WebUIDataSource;
} // namespace content
+namespace dlcservice {
+class DlcsWithContent;
+} // namespace dlcservice
+
namespace chromeos {
namespace settings {
@@ -35,7 +40,8 @@ class DeviceSection : public OsSettingsSection,
public ui::InputDeviceEventObserver,
public ash::NightLightController::Observer,
public ash::mojom::CrosDisplayConfigObserver,
- public PowerManagerClient::Observer {
+ public PowerManagerClient::Observer,
+ public DlcserviceClient::Observer {
public:
DeviceSection(Profile* profile,
SearchTagRegistry* search_tag_registry,
@@ -46,6 +52,11 @@ class DeviceSection : public OsSettingsSection,
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
// system::PointerDeviceObserver::Observer:
void TouchpadExists(bool exists) override;
@@ -63,6 +74,9 @@ class DeviceSection : public OsSettingsSection,
// PowerManagerClient::Observer:
void PowerChanged(const power_manager::PowerSupplyProperties& proto) override;
+ // DlcserviceClient::Observer:
+ void OnDlcStateChanged(const dlcservice::DlcState& dlc_state) override;
+
void OnGotSwitchStates(
base::Optional<PowerManagerClient::SwitchStates> result);
@@ -74,6 +88,9 @@ class DeviceSection : public OsSettingsSection,
std::vector<ash::mojom::DisplayUnitInfoPtr> display_unit_info_list,
ash::mojom::DisplayLayoutInfoPtr display_layout_info);
+ void OnGetExistingDlcs(const std::string& err,
+ const dlcservice::DlcsWithContent& dlcs_with_content);
+
void AddDevicePointersStrings(content::WebUIDataSource* html_source);
PrefService* pref_service_;
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc
index 584226636b8..e3961f58389 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc
@@ -48,6 +48,8 @@ const char* CalculationTypeToEventName(
return "storage-crostini-size-changed";
case calculator::SizeCalculator::CalculationType::kOtherUsers:
return "storage-other-users-size-changed";
+ case calculator::SizeCalculator::CalculationType::kDlcs:
+ return "storage-dlcs-size-changed";
}
NOTREACHED();
return "";
@@ -63,6 +65,7 @@ StorageHandler::StorageHandler(Profile* profile,
apps_size_calculator_(profile),
crostini_size_calculator_(profile),
other_users_size_calculator_(),
+ dlcs_size_calculator_(),
profile_(profile),
source_name_(html_source->GetSource()),
arc_observer_(this),
@@ -115,6 +118,7 @@ void StorageHandler::OnJavascriptAllowed() {
apps_size_calculator_.AddObserver(this);
crostini_size_calculator_.AddObserver(this);
other_users_size_calculator_.AddObserver(this);
+ dlcs_size_calculator_.AddObserver(this);
}
void StorageHandler::OnJavascriptDisallowed() {
@@ -133,6 +137,9 @@ int64_t StorageHandler::RoundByteSize(int64_t bytes) {
return -1;
}
+ if (bytes == 0)
+ return 0;
+
// Subtract one to the original number of bytes.
bytes--;
// Set all the lower bits to 1.
@@ -164,6 +171,7 @@ void StorageHandler::HandleUpdateStorageInfo(const base::ListValue* args) {
apps_size_calculator_.StartCalculation();
crostini_size_calculator_.StartCalculation();
other_users_size_calculator_.StartCalculation();
+ dlcs_size_calculator_.StartCalculation();
}
void StorageHandler::HandleOpenMyFiles(const base::ListValue* unused_args) {
@@ -259,6 +267,7 @@ void StorageHandler::StopObservingEvents() {
apps_size_calculator_.RemoveObserver(this);
crostini_size_calculator_.RemoveObserver(this);
other_users_size_calculator_.RemoveObserver(this);
+ dlcs_size_calculator_.RemoveObserver(this);
}
void StorageHandler::UpdateStorageItem(
@@ -282,6 +291,12 @@ void StorageHandler::UpdateStorageItem(
bool no_other_users = (total_bytes == 0);
FireWebUIListener(CalculationTypeToEventName(calculation_type),
base::Value(message), base::Value(no_other_users));
+ } else if (calculation_type ==
+ calculator::SizeCalculator::CalculationType::kDlcs) {
+ bool dlcs_exist = (total_bytes > 0);
+ FireWebUIListener(CalculationTypeToEventName(calculation_type),
+ base::Value(dlcs_exist), base::Value(message));
+
} else {
FireWebUIListener(CalculationTypeToEventName(calculation_type),
base::Value(message));
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h
index cdd352797a6..d6b4e79a376 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.h
@@ -113,6 +113,7 @@ class StorageHandler : public ::settings::SettingsPageUIHandler,
calculator::AppsSizeCalculator apps_size_calculator_;
calculator::CrostiniSizeCalculator crostini_size_calculator_;
calculator::OtherUsersSizeCalculator other_users_size_calculator_;
+ calculator::DlcsSizeCalculator dlcs_size_calculator_;
// Controls if the size of each storage item has been calculated.
std::bitset<calculator::SizeCalculator::kCalculationTypeCount>
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler_unittest.cc
index 57c1ab89f3c..86e80c50226 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/device_storage_handler_unittest.cc
@@ -23,6 +23,7 @@
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile_manager.h"
+#include "chromeos/dbus/dlcservice/fake_dlcservice_client.h"
#include "components/arc/arc_service_manager.h"
#include "components/arc/test/fake_arc_session.h"
#include "content/public/browser/web_ui_data_source.h"
@@ -96,6 +97,8 @@ class StorageHandlerTest : public testing::Test {
other_users_size_test_api_ =
std::make_unique<calculator::OtherUsersSizeTestAPI>(
handler_.get(), new calculator::OtherUsersSizeCalculator());
+ dlcs_size_test_api_ = std::make_unique<calculator::DlcsSizeTestAPI>(
+ handler_.get(), new calculator::DlcsSizeCalculator());
// Create and register My files directory.
// By emulating chromeos running, GetMyFilesFolderForProfile will return the
@@ -109,6 +112,10 @@ class StorageHandlerTest : public testing::Test {
file_manager::util::GetDownloadsMountPointName(profile_),
storage::kFileSystemTypeNativeLocal, storage::FileSystemMountOption(),
my_files_path));
+
+ chromeos::DlcserviceClient::InitializeFake();
+ fake_dlcservice_client_ = static_cast<chromeos::FakeDlcserviceClient*>(
+ chromeos::DlcserviceClient::Get());
}
void TearDown() override {
@@ -119,7 +126,9 @@ class StorageHandlerTest : public testing::Test {
apps_size_test_api_.reset();
crostini_size_test_api_.reset();
other_users_size_test_api_.reset();
+ dlcs_size_test_api_.reset();
chromeos::disks::DiskMountManager::Shutdown();
+ chromeos::DlcserviceClient::Shutdown();
storage::ExternalMountPoints::GetSystemInstance()->RevokeAllFileSystems();
}
@@ -148,8 +157,11 @@ class StorageHandlerTest : public testing::Test {
!data->arg1()->GetAsString(&name)) {
continue;
}
- if (name == event_name)
+ if (name == event_name) {
+ if (name == "storage-dlcs-size-changed")
+ return data->arg3();
return data->arg2();
+ }
}
return nullptr;
}
@@ -191,6 +203,7 @@ class StorageHandlerTest : public testing::Test {
content::BrowserTaskEnvironment task_environment_;
std::unique_ptr<TestingProfileManager> profile_manager_;
Profile* profile_;
+ chromeos::FakeDlcserviceClient* fake_dlcservice_client_;
std::unique_ptr<calculator::SizeStatTestAPI> size_stat_test_api_;
std::unique_ptr<calculator::MyFilesSizeTestAPI> my_files_size_test_api_;
std::unique_ptr<calculator::BrowsingDataSizeTestAPI>
@@ -198,6 +211,7 @@ class StorageHandlerTest : public testing::Test {
std::unique_ptr<calculator::AppsSizeTestAPI> apps_size_test_api_;
std::unique_ptr<calculator::CrostiniSizeTestAPI> crostini_size_test_api_;
std::unique_ptr<calculator::OtherUsersSizeTestAPI> other_users_size_test_api_;
+ std::unique_ptr<calculator::DlcsSizeTestAPI> dlcs_size_test_api_;
private:
std::unique_ptr<arc::ArcServiceManager> arc_service_manager_;
@@ -341,6 +355,26 @@ TEST_F(StorageHandlerTest, MyFilesSize) {
EXPECT_EQ("81.4 KB", callback->GetString());
}
+TEST_F(StorageHandlerTest, DlcsSize) {
+ dlcservice::DlcsWithContent dlcs_with_content;
+ auto* dlc_info = dlcs_with_content.add_dlc_infos();
+ dlc_info->set_used_bytes_on_disk(1);
+ dlc_info = dlcs_with_content.add_dlc_infos();
+ dlc_info->set_used_bytes_on_disk(2);
+ fake_dlcservice_client_->set_dlcs_with_content(dlcs_with_content);
+
+ // Calculate DLC size.
+ dlcs_size_test_api_->StartCalculation();
+ task_environment_.RunUntilIdle();
+
+ const base::Value* callback =
+ GetWebUICallbackMessage("storage-dlcs-size-changed");
+ ASSERT_TRUE(callback) << "No 'storage-dlcs-size-changed' callback";
+
+ // Check return value.
+ EXPECT_EQ("3 B", callback->GetString());
+}
+
TEST_F(StorageHandlerTest, AppsExtensionsSize) {
// The data for apps and extensions apps_size_test_api_installed from the
// webstore is stored in the Extensions folder. Add data at a random location
@@ -449,10 +483,22 @@ TEST_F(StorageHandlerTest, SystemSize) {
ASSERT_FALSE(GetWebUICallbackMessage("storage-system-size-changed"));
// Simulate crostini size callback.
- crostini_size_test_api_->SimulateOnGetCrostiniSize(70 * GB);
+ crostini_size_test_api_->SimulateOnGetCrostiniSize(50 * GB);
callback = GetWebUICallbackMessage("storage-crostini-size-changed");
ASSERT_TRUE(callback) << "No 'storage-crostini-size-changed' callback";
- EXPECT_EQ("70.0 GB", callback->GetString());
+ EXPECT_EQ("50.0 GB", callback->GetString());
+ ASSERT_FALSE(GetWebUICallbackMessage("storage-system-size-changed"));
+
+ // Simulate DLC size callback
+ dlcservice::DlcsWithContent dlcs_with_content;
+ auto* dlc_info = dlcs_with_content.add_dlc_infos();
+ dlc_info->set_used_bytes_on_disk(20 * GB);
+ dlc_info = dlcs_with_content.add_dlc_infos();
+ dlcs_size_test_api_->SimulateOnGetExistingDlcs(dlcservice::kErrorNone,
+ dlcs_with_content);
+ callback = GetWebUICallbackMessage("storage-dlcs-size-changed");
+ ASSERT_TRUE(callback) << "No 'storage-dlcs-size-changed' callback";
+ EXPECT_EQ("20.0 GB", callback->GetString());
ASSERT_FALSE(GetWebUICallbackMessage("storage-system-size-changed"));
// Simulate other users size callback. No callback message until the sizes of
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fake_hierarchy.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_hierarchy.cc
new file mode 100644
index 00000000000..3cf8646c001
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_hierarchy.cc
@@ -0,0 +1,53 @@
+// Copyright 2020 The Chromium 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/fake_hierarchy.h"
+
+#include <utility>
+
+#include "chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.h"
+
+namespace chromeos {
+namespace settings {
+
+FakeHierarchy::FakeHierarchy(const OsSettingsSections* sections)
+ : Hierarchy(sections) {}
+
+FakeHierarchy::~FakeHierarchy() = default;
+
+void FakeHierarchy::AddSubpageMetadata(
+ int name_message_id,
+ mojom::Section section,
+ mojom::Subpage subpage,
+ mojom::SearchResultIcon icon,
+ mojom::SearchResultDefaultRank default_rank,
+ const std::string& url_path_with_parameters,
+ base::Optional<mojom::Subpage> parent_subpage) {
+ auto pair = subpage_map_.emplace(
+ std::piecewise_construct, std::forward_as_tuple(subpage),
+ std::forward_as_tuple(name_message_id, section, subpage, icon,
+ default_rank, url_path_with_parameters, this));
+ DCHECK(pair.second);
+ pair.first->second.parent_subpage = parent_subpage;
+}
+
+void FakeHierarchy::AddSettingMetadata(
+ mojom::Section section,
+ mojom::Setting setting,
+ base::Optional<mojom::Subpage> parent_subpage) {
+ auto pair = setting_map_.emplace(setting, section);
+ DCHECK(pair.second);
+ pair.first->second.primary.second = parent_subpage;
+}
+
+std::string FakeHierarchy::ModifySearchResultUrl(
+ mojom::Section section,
+ mojom::SearchResultType type,
+ OsSettingsIdentifier id,
+ const std::string& url_to_modify) const {
+ return FakeOsSettingsSection::ModifySearchResultUrl(section, url_to_modify);
+}
+
+} // namespace settings
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fake_hierarchy.h b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_hierarchy.h
new file mode 100644
index 00000000000..d0fbf813ff3
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_hierarchy.h
@@ -0,0 +1,50 @@
+// Copyright 2020 The Chromium 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_FAKE_HIERARCHY_H_
+#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_FAKE_HIERARCHY_H_
+
+#include "base/optional.h"
+#include "chrome/browser/ui/webui/settings/chromeos/hierarchy.h"
+
+namespace chromeos {
+namespace settings {
+
+class OsSettingsSections;
+
+// Fake Hierarchy implementation. Note that this class currently does not
+// provide "alternate settings location" functionality.
+class FakeHierarchy : public Hierarchy {
+ public:
+ explicit FakeHierarchy(const OsSettingsSections* sections);
+ FakeHierarchy(const FakeHierarchy& other) = delete;
+ FakeHierarchy& operator=(const FakeHierarchy& other) = delete;
+ ~FakeHierarchy() override;
+
+ void AddSubpageMetadata(
+ int name_message_id,
+ mojom::Section section,
+ mojom::Subpage subpage,
+ mojom::SearchResultIcon icon,
+ mojom::SearchResultDefaultRank default_rank,
+ const std::string& url_path_with_parameters,
+ base::Optional<mojom::Subpage> parent_subpage = base::nullopt);
+ void AddSettingMetadata(
+ mojom::Section section,
+ mojom::Setting setting,
+ base::Optional<mojom::Subpage> parent_subpage = base::nullopt);
+
+ private:
+ // Hierarchy:
+ std::string ModifySearchResultUrl(
+ mojom::Section section,
+ mojom::SearchResultType type,
+ OsSettingsIdentifier id,
+ const std::string& url_to_modify) const override;
+};
+
+} // namespace settings
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_FAKE_HIERARCHY_H_
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.cc
new file mode 100644
index 00000000000..473287ebec0
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.cc
@@ -0,0 +1,52 @@
+// Copyright 2020 The Chromium 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/fake_os_settings_section.h"
+
+#include <sstream>
+
+#include "chrome/grit/generated_resources.h"
+
+namespace chromeos {
+namespace settings {
+
+FakeOsSettingsSection::FakeOsSettingsSection(mojom::Section section)
+ : section_(section) {}
+
+FakeOsSettingsSection::~FakeOsSettingsSection() = default;
+
+int FakeOsSettingsSection::GetSectionNameMessageId() const {
+ return IDS_INTERNAL_APP_SETTINGS;
+}
+
+mojom::Section FakeOsSettingsSection::GetSection() const {
+ return section_;
+}
+
+mojom::SearchResultIcon FakeOsSettingsSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kWifi;
+}
+
+std::string FakeOsSettingsSection::GetSectionPath() const {
+ return std::string();
+}
+
+std::string FakeOsSettingsSection::ModifySearchResultUrl(
+ mojom::SearchResultType type,
+ OsSettingsIdentifier id,
+ const std::string& url_to_modify) const {
+ return ModifySearchResultUrl(section_, url_to_modify);
+}
+
+// static
+std::string FakeOsSettingsSection::ModifySearchResultUrl(
+ mojom::Section section,
+ const std::string& url_to_modify) {
+ std::stringstream ss;
+ ss << section << "::" << url_to_modify;
+ return ss.str();
+}
+
+} // namespace settings
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.h
new file mode 100644
index 00000000000..4a58417228a
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.h
@@ -0,0 +1,56 @@
+// Copyright 2020 The Chromium 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_FAKE_OS_SETTINGS_SECTION_H_
+#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_FAKE_OS_SETTINGS_SECTION_H_
+
+#include "chrome/browser/ui/webui/settings/chromeos/os_settings_section.h"
+
+namespace chromeos {
+namespace settings {
+
+// Fake OsSettingsSection implementation.
+class FakeOsSettingsSection : public OsSettingsSection {
+ public:
+ explicit FakeOsSettingsSection(mojom::Section section);
+ ~FakeOsSettingsSection() override;
+
+ FakeOsSettingsSection(const FakeOsSettingsSection& other) = delete;
+ FakeOsSettingsSection& operator=(const FakeOsSettingsSection& other) = delete;
+
+ mojom::Section section() { return section_; }
+
+ // OsSettingsSection:
+ void AddLoadTimeData(content::WebUIDataSource* html_source) override {}
+ void RegisterHierarchy(HierarchyGenerator* generator) const override {}
+
+ // Returns the settings app name as a default value.
+ int GetSectionNameMessageId() const override;
+
+ mojom::Section GetSection() const override;
+
+ // These functions return arbitrary dummy values.
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+
+ // Prepends the section name and "::" to the URL in |concept|. For example, if
+ // the URL is "networkDetails" and the section is mojom::Section::kNetwork,
+ // the returned URL is "Section::kNetwork::networkDetails".
+ std::string ModifySearchResultUrl(
+ mojom::SearchResultType type,
+ OsSettingsIdentifier id,
+ const std::string& url_to_modify) const override;
+
+ // Static function used to implement the function above.
+ static std::string ModifySearchResultUrl(mojom::Section section,
+ const std::string& url_to_modify);
+
+ private:
+ const mojom::Section section_;
+};
+
+} // namespace settings
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_FAKE_OS_SETTINGS_SECTION_H_
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_sections.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_sections.cc
new file mode 100644
index 00000000000..253d965f65e
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_sections.cc
@@ -0,0 +1,24 @@
+// Copyright 2020 The Chromium 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/fake_os_settings_sections.h"
+
+#include "chrome/browser/ui/webui/settings/chromeos/constants/constants_util.h"
+#include "chrome/browser/ui/webui/settings/chromeos/fake_os_settings_section.h"
+
+namespace chromeos {
+namespace settings {
+
+FakeOsSettingsSections::FakeOsSettingsSections() : OsSettingsSections() {
+ for (const auto& section : constants::AllSections()) {
+ auto fake_section = std::make_unique<FakeOsSettingsSection>(section);
+ sections_map_[section] = fake_section.get();
+ sections_.push_back(std::move(fake_section));
+ }
+}
+
+FakeOsSettingsSections::~FakeOsSettingsSections() = default;
+
+} // namespace settings
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_sections.h b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_sections.h
new file mode 100644
index 00000000000..2c148a72a69
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/fake_os_settings_sections.h
@@ -0,0 +1,26 @@
+// Copyright 2020 The Chromium 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_FAKE_OS_SETTINGS_SECTIONS_H_
+#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_FAKE_OS_SETTINGS_SECTIONS_H_
+
+#include "chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h"
+
+namespace chromeos {
+namespace settings {
+
+// Collection of FakeOsSettingsSections.
+class FakeOsSettingsSections : public OsSettingsSections {
+ public:
+ FakeOsSettingsSections();
+ FakeOsSettingsSections(const FakeOsSettingsSections& other) = delete;
+ FakeOsSettingsSections& operator=(const FakeOsSettingsSections& other) =
+ delete;
+ ~FakeOsSettingsSections() override;
+};
+
+} // namespace settings
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_FAKE_OS_SETTINGS_SECTIONS_H_
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/files_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/files_section.cc
index 3b1788101b1..7163b682b59 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/files_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/files_section.cc
@@ -52,7 +52,8 @@ const std::vector<SearchConcept>& GetFilesSearchConcepts() {
FilesSection::FilesSection(Profile* profile,
SearchTagRegistry* search_tag_registry)
: OsSettingsSection(profile, search_tag_registry) {
- registry()->AddSearchTags(GetFilesSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetFilesSearchConcepts());
}
FilesSection::~FilesSection() = default;
@@ -102,5 +103,31 @@ void FilesSection::AddHandlers(content::WebUI* web_ui) {
profile(), base::DoNothing()));
}
+int FilesSection::GetSectionNameMessageId() const {
+ return IDS_OS_SETTINGS_FILES;
+}
+
+mojom::Section FilesSection::GetSection() const {
+ return mojom::Section::kFiles;
+}
+
+mojom::SearchResultIcon FilesSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kFolder;
+}
+
+std::string FilesSection::GetSectionPath() const {
+ return mojom::kFilesSectionPath;
+}
+
+void FilesSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSetting(mojom::Setting::kGoogleDriveConnection);
+
+ // Network file shares.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_DOWNLOADS_SMB_SHARES, mojom::Subpage::kNetworkFileShares,
+ mojom::SearchResultIcon::kFolder, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kNetworkFileSharesSubpagePath);
+}
+
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/files_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/files_section.h
index 635bcb9abc0..38b9dc0b236 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/files_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/files_section.h
@@ -26,6 +26,11 @@ class FilesSection : public OsSettingsSection {
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
};
} // namespace settings
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 9ef5ec87581..337e66bd4bb 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,8 +6,8 @@
#include <utility>
-#include "ash/public/cpp/assistant/assistant_settings.h"
#include "ash/public/cpp/assistant/assistant_setup.h"
+#include "ash/public/cpp/assistant/controller/assistant_controller.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/values.h"
@@ -74,7 +74,7 @@ void GoogleAssistantHandler::RegisterMessages() {
void GoogleAssistantHandler::HandleShowGoogleAssistantSettings(
const base::ListValue* args) {
CHECK_EQ(0U, args->GetSize());
- ash::OpenAssistantSettings();
+ ash::AssistantController::Get()->OpenAssistantSettings();
}
void GoogleAssistantHandler::HandleRetrainVoiceModel(
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/hierarchy.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/hierarchy.cc
new file mode 100644
index 00000000000..7eef6651e04
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/hierarchy.cc
@@ -0,0 +1,318 @@
+// Copyright 2020 The Chromium 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/hierarchy.h"
+
+#include <utility>
+
+#include "base/strings/utf_string_conversions.h"
+#include "chrome/browser/ui/webui/settings/chromeos/constants/constants_util.h"
+#include "chrome/browser/ui/webui/settings/chromeos/os_settings_section.h"
+#include "chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h"
+#include "chrome/grit/generated_resources.h"
+#include "ui/base/l10n/l10n_util.h"
+
+namespace chromeos {
+namespace settings {
+namespace {
+
+// Used to generate localized names.
+constexpr double kDummyRelevanceScore = 0;
+
+} // namespace
+
+class Hierarchy::PerSectionHierarchyGenerator
+ : public OsSettingsSection::HierarchyGenerator {
+ public:
+ PerSectionHierarchyGenerator(mojom::Section section,
+ bool* only_contains_link_to_subpage,
+ Hierarchy* hierarchy)
+ : section_(section),
+ only_contains_link_to_subpage_(only_contains_link_to_subpage),
+ hierarchy_(hierarchy) {}
+
+ void RegisterTopLevelSubpage(
+ int name_message_id,
+ mojom::Subpage subpage,
+ mojom::SearchResultIcon icon,
+ mojom::SearchResultDefaultRank default_rank,
+ const std::string& url_path_with_parameters) override {
+ Hierarchy::SubpageMetadata& metadata = GetSubpageMetadata(
+ name_message_id, subpage, icon, default_rank, url_path_with_parameters);
+ CHECK_EQ(section_, metadata.section)
+ << "Subpage registered in multiple sections: " << subpage;
+
+ ++num_top_level_subpages_so_far_;
+
+ // If there are multiple top-level subpages, the section contains more than
+ // just a link to a subpage.
+ if (num_top_level_subpages_so_far_ > 1u)
+ *only_contains_link_to_subpage_ = false;
+ }
+
+ void RegisterNestedSubpage(
+ int name_message_id,
+ mojom::Subpage subpage,
+ mojom::Subpage parent_subpage,
+ mojom::SearchResultIcon icon,
+ mojom::SearchResultDefaultRank default_rank,
+ const std::string& url_path_with_parameters) override {
+ Hierarchy::SubpageMetadata& metadata = GetSubpageMetadata(
+ name_message_id, subpage, icon, default_rank, url_path_with_parameters);
+ CHECK_EQ(section_, metadata.section)
+ << "Subpage registered in multiple sections: " << subpage;
+ CHECK(!metadata.parent_subpage)
+ << "Subpage has multiple registered parent subpages: " << subpage;
+ metadata.parent_subpage = parent_subpage;
+ }
+
+ void RegisterTopLevelSetting(mojom::Setting setting) override {
+ Hierarchy::SettingMetadata& metadata = GetSettingMetadata(setting);
+ CHECK_EQ(section_, metadata.primary.first)
+ << "Setting registered in multiple primary sections: " << setting;
+ CHECK(!metadata.primary.second)
+ << "Setting registered in multiple primary locations: " << setting;
+
+ // If a top-level setting exists, the section contains more than just a link
+ // link to a subpage.
+ *only_contains_link_to_subpage_ = false;
+ }
+
+ void RegisterNestedSetting(mojom::Setting setting,
+ mojom::Subpage subpage) override {
+ Hierarchy::SettingMetadata& metadata = GetSettingMetadata(setting);
+ CHECK_EQ(section_, metadata.primary.first)
+ << "Setting registered in multiple primary sections: " << setting;
+ CHECK(!metadata.primary.second)
+ << "Setting registered in multiple primary locations: " << setting;
+ metadata.primary.second = subpage;
+ }
+
+ void RegisterTopLevelAltSetting(mojom::Setting setting) override {
+ Hierarchy::SettingMetadata& metadata = GetSettingMetadata(setting);
+ CHECK(metadata.primary.first != section_ || metadata.primary.second)
+ << "Setting's primary and alternate locations are identical: "
+ << setting;
+ for (const auto& alternate : metadata.alternates) {
+ CHECK(alternate.first != section_ || alternate.second)
+ << "Setting has multiple identical alternate locations: " << setting;
+ }
+ metadata.alternates.emplace_back(section_, /*subpage=*/base::nullopt);
+
+ // If a top-level setting exists, the section contains more than just a link
+ // link to a subpage.
+ *only_contains_link_to_subpage_ = false;
+ }
+
+ void RegisterNestedAltSetting(mojom::Setting setting,
+ mojom::Subpage subpage) override {
+ Hierarchy::SettingMetadata& metadata = GetSettingMetadata(setting);
+ CHECK(metadata.primary.first != section_ ||
+ metadata.primary.second != subpage)
+ << "Setting's primary and alternate locations are identical: "
+ << setting;
+ for (const auto& alternate : metadata.alternates) {
+ CHECK(alternate.first != section_ || alternate.second != subpage)
+ << "Setting has multiple identical alternate locations: " << setting;
+ }
+ metadata.alternates.emplace_back(section_, subpage);
+ }
+
+ private:
+ Hierarchy::SubpageMetadata& GetSubpageMetadata(
+ int name_message_id,
+ mojom::Subpage subpage,
+ mojom::SearchResultIcon icon,
+ mojom::SearchResultDefaultRank default_rank,
+ const std::string& url_path_with_parameters) {
+ auto& subpage_map = hierarchy_->subpage_map_;
+
+ auto it = subpage_map.find(subpage);
+
+ // Metadata already exists; return it.
+ if (it != subpage_map.end())
+ return it->second;
+
+ // Metadata does not exist yet; insert then return it.
+ auto pair = subpage_map.emplace(
+ std::piecewise_construct, std::forward_as_tuple(subpage),
+ std::forward_as_tuple(name_message_id, section_, subpage, icon,
+ default_rank, url_path_with_parameters,
+ hierarchy_));
+ CHECK(pair.second);
+ return pair.first->second;
+ }
+
+ Hierarchy::SettingMetadata& GetSettingMetadata(mojom::Setting setting) {
+ auto& settings_map = hierarchy_->setting_map_;
+
+ auto it = settings_map.find(setting);
+
+ // Metadata already exists; return it.
+ if (it != settings_map.end())
+ return it->second;
+
+ // Metadata does not exist yet; insert then return it.
+ auto pair = settings_map.emplace(setting, section_);
+ CHECK(pair.second);
+ return pair.first->second;
+ }
+
+ size_t num_top_level_subpages_so_far_ = 0u;
+ mojom::Section section_;
+ bool* only_contains_link_to_subpage_;
+ Hierarchy* hierarchy_;
+};
+
+// Note: |only_contains_link_to_subpage| starts out as true and is set to false
+// if other content is added.
+Hierarchy::SectionMetadata::SectionMetadata(mojom::Section section,
+ const Hierarchy* hierarchy)
+ : only_contains_link_to_subpage(true),
+ section_(section),
+ hierarchy_(hierarchy) {}
+
+Hierarchy::SectionMetadata::~SectionMetadata() = default;
+
+mojom::SearchResultPtr Hierarchy::SectionMetadata::ToSearchResult(
+ double relevance_score) const {
+ return hierarchy_->sections_->GetSection(section_)
+ ->GenerateSectionSearchResult(relevance_score);
+}
+
+Hierarchy::SubpageMetadata::SubpageMetadata(
+ int name_message_id,
+ mojom::Section section,
+ mojom::Subpage subpage,
+ mojom::SearchResultIcon icon,
+ mojom::SearchResultDefaultRank default_rank,
+ const std::string& url_path_with_parameters,
+ const Hierarchy* hierarchy)
+ : section(section),
+ subpage_(subpage),
+ name_message_id_(name_message_id),
+ icon_(icon),
+ default_rank_(default_rank),
+ unmodified_url_path_with_parameters_(url_path_with_parameters),
+ hierarchy_(hierarchy) {}
+
+Hierarchy::SubpageMetadata::~SubpageMetadata() = default;
+
+mojom::SearchResultPtr Hierarchy::SubpageMetadata::ToSearchResult(
+ double relevance_score) const {
+ return mojom::SearchResult::New(
+ /*result_text=*/l10n_util::GetStringUTF16(name_message_id_),
+ /*canonical_result_text=*/l10n_util::GetStringUTF16(name_message_id_),
+ hierarchy_->ModifySearchResultUrl(
+ section, mojom::SearchResultType::kSubpage, {.subpage = subpage_},
+ unmodified_url_path_with_parameters_),
+ icon_, relevance_score,
+ hierarchy_->GenerateAncestorHierarchyStrings(subpage_), default_rank_,
+ /*was_generated_from_text_match=*/false,
+ mojom::SearchResultType::kSubpage,
+ mojom::SearchResultIdentifier::NewSubpage(subpage_));
+}
+
+Hierarchy::SettingMetadata::SettingMetadata(mojom::Section primary_section)
+ : primary(primary_section, /*subpage=*/base::nullopt) {}
+
+Hierarchy::SettingMetadata::~SettingMetadata() = default;
+
+Hierarchy::Hierarchy(const OsSettingsSections* sections) : sections_(sections) {
+ for (const auto& section : constants::AllSections()) {
+ auto pair = section_map_.emplace(std::piecewise_construct,
+ std::forward_as_tuple(section),
+ std::forward_as_tuple(section, this));
+ CHECK(pair.second);
+
+ PerSectionHierarchyGenerator generator(
+ section, &pair.first->second.only_contains_link_to_subpage, this);
+ sections->GetSection(section)->RegisterHierarchy(&generator);
+ }
+}
+
+Hierarchy::~Hierarchy() = default;
+
+const Hierarchy::SectionMetadata& Hierarchy::GetSectionMetadata(
+ mojom::Section section) const {
+ const auto it = section_map_.find(section);
+ CHECK(it != section_map_.end())
+ << "Section missing from settings hierarchy: " << section;
+ return it->second;
+}
+
+const Hierarchy::SubpageMetadata& Hierarchy::GetSubpageMetadata(
+ mojom::Subpage subpage) const {
+ const auto it = subpage_map_.find(subpage);
+ CHECK(it != subpage_map_.end())
+ << "Subpage missing from settings hierarchy: " << subpage;
+ return it->second;
+}
+
+const Hierarchy::SettingMetadata& Hierarchy::GetSettingMetadata(
+ mojom::Setting setting) const {
+ const auto it = setting_map_.find(setting);
+ CHECK(it != setting_map_.end())
+ << "Setting missing from settings hierarchy: " << setting;
+ return it->second;
+}
+
+std::string Hierarchy::ModifySearchResultUrl(
+ mojom::Section section,
+ mojom::SearchResultType type,
+ OsSettingsIdentifier id,
+ const std::string& url_to_modify) const {
+ return sections_->GetSection(section)->ModifySearchResultUrl(type, id,
+ url_to_modify);
+}
+
+std::vector<base::string16> Hierarchy::GenerateAncestorHierarchyStrings(
+ mojom::Subpage subpage) const {
+ const SubpageMetadata& subpage_metadata = GetSubpageMetadata(subpage);
+
+ // Top-level subpage; simply return section hierarchy.
+ if (!subpage_metadata.parent_subpage)
+ return GenerateHierarchyStrings(subpage_metadata.section);
+
+ // Nested subpage; use recursive call, then append parent subpage name itself.
+ std::vector<base::string16> hierarchy_strings =
+ GenerateAncestorHierarchyStrings(*subpage_metadata.parent_subpage);
+ hierarchy_strings.push_back(
+ GetSubpageMetadata(*subpage_metadata.parent_subpage)
+ .ToSearchResult(kDummyRelevanceScore)
+ ->result_text);
+ return hierarchy_strings;
+}
+
+std::vector<base::string16> Hierarchy::GenerateAncestorHierarchyStrings(
+ mojom::Setting setting) const {
+ const SettingMetadata& setting_metadata = GetSettingMetadata(setting);
+
+ // Top-level setting; simply return section hierarchy.
+ if (!setting_metadata.primary.second)
+ return GenerateHierarchyStrings(setting_metadata.primary.first);
+
+ // Nested setting; use subpage ancestors, then append subpage name itself.
+ std::vector<base::string16> hierarchy_strings =
+ GenerateAncestorHierarchyStrings(*setting_metadata.primary.second);
+ hierarchy_strings.push_back(
+ GetSubpageMetadata(*setting_metadata.primary.second)
+ .ToSearchResult(kDummyRelevanceScore)
+ ->result_text);
+ return hierarchy_strings;
+}
+
+std::vector<base::string16> Hierarchy::GenerateHierarchyStrings(
+ mojom::Section section) const {
+ std::vector<base::string16> hierarchy_strings;
+ hierarchy_strings.push_back(
+ l10n_util::GetStringUTF16(IDS_INTERNAL_APP_SETTINGS));
+ hierarchy_strings.push_back(GetSectionMetadata(section)
+ .ToSearchResult(kDummyRelevanceScore)
+ ->result_text);
+ return hierarchy_strings;
+}
+
+} // namespace settings
+} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/hierarchy.h b/chromium/chrome/browser/ui/webui/settings/chromeos/hierarchy.h
new file mode 100644
index 00000000000..14b915670d4
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/hierarchy.h
@@ -0,0 +1,171 @@
+// Copyright 2020 The Chromium 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_HIERARCHY_H_
+#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_HIERARCHY_H_
+
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include "base/optional.h"
+#include "base/strings/string16.h"
+#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h"
+#include "chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom.h"
+#include "chrome/browser/ui/webui/settings/chromeos/os_settings_identifier.h"
+#include "chrome/browser/ui/webui/settings/chromeos/search/search.mojom.h"
+
+namespace chromeos {
+namespace settings {
+
+class OsSettingsSections;
+
+// Tracks the OS settings page hierarchy. Settings is composed of a group of
+// sections containing subpages and/or settings, and this class provides
+// metadata for where these subpages/settings reside and what localized strings
+// are used to describe them.
+//
+// A subpage can either be a direct child of a section or can be a nested
+// subpage, meaning that its parent is another subpage.
+//
+// A setting can either be embedded as a direct child of a section or can be
+// a child of a subpage. Additionally, some settings appear in multiple places.
+// For example, the Wi-Fi on/off toggle appears in both the top-level Network
+// section as well as the Wi-Fi subpage. In cases like this, we consider the
+// "primary" location as the more-targeted one - in this example, the Wi-Fi
+// subpage is the primary location of the toggle since it is more specific to
+// Wi-Fi, and the alternate location is the one embedded in the Network section.
+class Hierarchy {
+ public:
+ explicit Hierarchy(const OsSettingsSections* sections);
+ Hierarchy(const Hierarchy& other) = delete;
+ Hierarchy& operator=(const Hierarchy& other) = delete;
+ virtual ~Hierarchy();
+
+ class SectionMetadata {
+ public:
+ SectionMetadata(mojom::Section section, const Hierarchy* hierarchy);
+ ~SectionMetadata();
+
+ // Whether the only contents of the section is a link to a subpage.
+ bool only_contains_link_to_subpage;
+
+ // Generates a search result for this section, using the canonical search
+ // tag as the search result text. |relevance_score| must be passed by the
+ // client, since this result is being created manually instead of via query
+ // matching.
+ mojom::SearchResultPtr ToSearchResult(double relevance_score) const;
+
+ private:
+ mojom::Section section_;
+ const Hierarchy* hierarchy_;
+ };
+
+ class SubpageMetadata {
+ public:
+ SubpageMetadata(int name_message_id,
+ mojom::Section section,
+ mojom::Subpage subpage,
+ mojom::SearchResultIcon icon,
+ mojom::SearchResultDefaultRank default_rank,
+ const std::string& url_path_with_parameters,
+ const Hierarchy* hierarchy);
+ ~SubpageMetadata();
+
+ // The section in which the subpage appears.
+ mojom::Section section;
+
+ // The parent subpage, if applicable. Only applies to nested subpages.
+ base::Optional<mojom::Subpage> parent_subpage;
+
+ // Generates a search result for this subpage, using the canonical search
+ // tag as the search result text. |relevance_score| must be passed by the
+ // client, since this result is being created manually instead of via query
+ // matching.
+ mojom::SearchResultPtr ToSearchResult(double relevance_score) const;
+
+ private:
+ mojom::Subpage subpage_;
+
+ // Message ID corresponding to the localized string used to describe this
+ // subpage.
+ int name_message_id_;
+
+ // Icon used for this subpage.
+ mojom::SearchResultIcon icon_;
+
+ // Default rank; used to order returned results.
+ mojom::SearchResultDefaultRank default_rank_;
+
+ // Static URL path, which may need to be modified via
+ // |modify_url_callback_|.
+ std::string unmodified_url_path_with_parameters_;
+
+ const Hierarchy* hierarchy_;
+ };
+
+ // The location of a setting, which includes its section and, if applicable,
+ // its subpage. Some settings are embedded directly into the section and have
+ // no associated subpage.
+ using SettingLocation =
+ std::pair<mojom::Section, base::Optional<mojom::Subpage>>;
+
+ struct SettingMetadata {
+ explicit SettingMetadata(mojom::Section primary_section);
+ ~SettingMetadata();
+
+ // The primary location, as described above.
+ SettingLocation primary;
+
+ // Alternate locations, as described above. Empty if the setting has no
+ // alternate location.
+ std::vector<SettingLocation> alternates;
+ };
+
+ const SectionMetadata& GetSectionMetadata(mojom::Section section) const;
+ const SubpageMetadata& GetSubpageMetadata(mojom::Subpage subpage) const;
+ const SettingMetadata& GetSettingMetadata(mojom::Setting setting) const;
+
+ // Generates a list of names of the ancestor sections/subpages for |subpage|.
+ // The list contains the Settings app name, the section name and, if
+ // applicable, parent subpage names. Names returned in this list are all
+ // localized string16s which can be displayed in the UI (e.g., as
+ // breadcrumbs).
+ //
+ // Example 1 - Wi-Fi Networks subpage (no parent subpage):
+ // ["Settings", "Network"]
+ // Example 2 - External storage (has parent subpage):
+ // ["Settings", "Device", "Storage management"]
+ std::vector<base::string16> GenerateAncestorHierarchyStrings(
+ mojom::Subpage subpage) const;
+
+ // Same as above, but for settings.
+ std::vector<base::string16> GenerateAncestorHierarchyStrings(
+ mojom::Setting setting) const;
+
+ protected:
+ std::unordered_map<mojom::Section, SectionMetadata> section_map_;
+ std::unordered_map<mojom::Subpage, SubpageMetadata> subpage_map_;
+ std::unordered_map<mojom::Setting, SettingMetadata> setting_map_;
+
+ private:
+ class PerSectionHierarchyGenerator;
+
+ // Generates an array with the Settings app name and |section|'s name.
+ std::vector<base::string16> GenerateHierarchyStrings(
+ mojom::Section section) const;
+
+ virtual std::string ModifySearchResultUrl(
+ mojom::Section section,
+ mojom::SearchResultType type,
+ OsSettingsIdentifier id,
+ const std::string& url_to_modify) const;
+
+ const OsSettingsSections* sections_;
+};
+
+} // namespace settings
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_HIERARCHY_H_
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_section.cc
index c21b0002fb8..69248ed127e 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_section.cc
@@ -8,11 +8,13 @@
#include "ash/public/cpp/network_config_service.h"
#include "base/bind.h"
#include "base/no_destructor.h"
+#include "base/strings/stringprintf.h"
#include "chrome/browser/ui/webui/chromeos/network_element_localized_strings_provider.h"
#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h"
#include "chrome/browser/ui/webui/settings/chromeos/internet_handler.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h"
#include "chrome/browser/ui/webui/webui_util.h"
+#include "chrome/common/chrome_features.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/chromium_strings.h"
@@ -32,7 +34,7 @@ const std::vector<SearchConcept>& GetNetworkSearchConcepts() {
{IDS_OS_SETTINGS_TAG_NETWORK_SETTINGS,
mojom::kNetworkSectionPath,
mojom::SearchResultIcon::kWifi,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSection,
{.section = mojom::Section::kNetwork},
{IDS_OS_SETTINGS_TAG_NETWORK_SETTINGS_ALT1, SearchConcept::kAltTagEnd}},
@@ -57,7 +59,7 @@ const std::vector<SearchConcept>& GetEthernetConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_CONFIGURE_IP_AUTOMATICALLY,
mojom::kEthernetDetailsSubpagePath,
mojom::SearchResultIcon::kEthernet,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kEthernetAutoConfigureIp},
{IDS_OS_SETTINGS_TAG_CONFIGURE_IP_AUTOMATICALLY_ALT1,
@@ -66,7 +68,7 @@ const std::vector<SearchConcept>& GetEthernetConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_NAME_SERVERS,
mojom::kEthernetDetailsSubpagePath,
mojom::SearchResultIcon::kEthernet,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kEthernetDns},
{IDS_OS_SETTINGS_TAG_NAME_SERVERS_ALT1,
@@ -74,7 +76,7 @@ const std::vector<SearchConcept>& GetEthernetConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_PROXY,
mojom::kEthernetDetailsSubpagePath,
mojom::SearchResultIcon::kEthernet,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kEthernetProxy},
{IDS_OS_SETTINGS_TAG_PROXY_ALT1, IDS_OS_SETTINGS_TAG_PROXY_ALT2,
@@ -92,12 +94,11 @@ const std::vector<SearchConcept>& GetWifiSearchConcepts() {
mojom::SearchResultDefaultRank::kHigh,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kWifiNetworks},
- {IDS_OS_SETTINGS_TAG_WIFI_ALT1, IDS_OS_SETTINGS_TAG_WIFI_ALT2,
- SearchConcept::kAltTagEnd}},
+ {IDS_OS_SETTINGS_TAG_WIFI_ALT1, SearchConcept::kAltTagEnd}},
{IDS_OS_SETTINGS_TAG_KNOWN_NETWORKS,
mojom::kKnownNetworksSubpagePath,
mojom::SearchResultIcon::kWifi,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kKnownNetworks},
{IDS_OS_SETTINGS_TAG_KNOWN_NETWORKS_ALT1,
@@ -115,6 +116,12 @@ const std::vector<SearchConcept>& GetWifiOnSearchConcepts() {
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kWifiOnOff},
{IDS_OS_SETTINGS_TAG_WIFI_TURN_OFF_ALT1, SearchConcept::kAltTagEnd}},
+ {IDS_OS_SETTINGS_TAG_ADD_WIFI,
+ mojom::kWifiNetworksSubpagePath,
+ mojom::SearchResultIcon::kWifi,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kWifiAddNetwork}},
});
return *tags;
}
@@ -143,17 +150,11 @@ const std::vector<SearchConcept>& GetWifiConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_PREFER_WIFI_NETWORK,
mojom::kWifiDetailsSubpagePath,
mojom::SearchResultIcon::kWifi,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kPreferWifiNetwork},
{IDS_OS_SETTINGS_TAG_PREFER_WIFI_NETWORK_ALT1,
SearchConcept::kAltTagEnd}},
- {IDS_OS_SETTINGS_TAG_WIFI_CONFIGURE,
- mojom::kWifiDetailsSubpagePath,
- mojom::SearchResultIcon::kWifi,
- mojom::SearchResultDefaultRank::kMedium,
- mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kConfigureWifi}},
{IDS_OS_SETTINGS_TAG_FORGET_WIFI,
mojom::kWifiDetailsSubpagePath,
mojom::SearchResultIcon::kWifi,
@@ -163,7 +164,7 @@ const std::vector<SearchConcept>& GetWifiConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_CONFIGURE_IP_AUTOMATICALLY,
mojom::kWifiDetailsSubpagePath,
mojom::SearchResultIcon::kWifi,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kWifiAutoConfigureIp},
{IDS_OS_SETTINGS_TAG_CONFIGURE_IP_AUTOMATICALLY_ALT1,
@@ -172,7 +173,7 @@ const std::vector<SearchConcept>& GetWifiConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_NAME_SERVERS,
mojom::kWifiDetailsSubpagePath,
mojom::SearchResultIcon::kWifi,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kWifiDns},
{IDS_OS_SETTINGS_TAG_NAME_SERVERS_ALT1,
@@ -180,7 +181,7 @@ const std::vector<SearchConcept>& GetWifiConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_PROXY,
mojom::kWifiDetailsSubpagePath,
mojom::SearchResultIcon::kWifi,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kWifiProxy},
{IDS_OS_SETTINGS_TAG_PROXY_ALT1, IDS_OS_SETTINGS_TAG_PROXY_ALT2,
@@ -189,7 +190,7 @@ const std::vector<SearchConcept>& GetWifiConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_AUTO_CONNECT_NETWORK,
mojom::kWifiDetailsSubpagePath,
mojom::SearchResultIcon::kWifi,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kWifiAutoConnectToNetwork},
{IDS_OS_SETTINGS_TAG_AUTO_CONNECT_NETWORK_ALT1,
@@ -198,6 +199,18 @@ const std::vector<SearchConcept>& GetWifiConnectedSearchConcepts() {
return *tags;
}
+const std::vector<SearchConcept>& GetWifiMeteredSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_SETTINGS_INTERNET_NETWORK_METERED,
+ mojom::kWifiDetailsSubpagePath,
+ mojom::SearchResultIcon::kWifi,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kWifiMetered}},
+ });
+ return *tags;
+}
+
const std::vector<SearchConcept>& GetCellularSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_CELLULAR,
@@ -207,14 +220,7 @@ const std::vector<SearchConcept>& GetCellularSearchConcepts() {
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kCellularDetails},
{IDS_OS_SETTINGS_TAG_CELLULAR_ALT1, IDS_OS_SETTINGS_TAG_CELLULAR_ALT2,
- IDS_OS_SETTINGS_TAG_CELLULAR_ALT3, IDS_OS_SETTINGS_TAG_CELLULAR_ALT4,
- SearchConcept::kAltTagEnd}},
- });
- return *tags;
-}
-
-const std::vector<SearchConcept>& GetCellularOnSearchConcepts() {
- static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ IDS_OS_SETTINGS_TAG_CELLULAR_ALT3, SearchConcept::kAltTagEnd}},
{IDS_OS_SETTINGS_TAG_CELLULAR_SIM_LOCK,
mojom::kCellularDetailsSubpagePath,
mojom::SearchResultIcon::kCellular,
@@ -228,6 +234,18 @@ const std::vector<SearchConcept>& GetCellularOnSearchConcepts() {
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kCellularRoaming}},
+ {IDS_OS_SETTINGS_TAG_CELLULAR_APN,
+ mojom::kCellularDetailsSubpagePath,
+ mojom::SearchResultIcon::kCellular,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kCellularApn}},
+ });
+ return *tags;
+}
+
+const std::vector<SearchConcept>& GetCellularOnSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_CELLULAR_TURN_OFF,
mojom::kNetworkSectionPath,
mojom::SearchResultIcon::kCellular,
@@ -235,12 +253,6 @@ const std::vector<SearchConcept>& GetCellularOnSearchConcepts() {
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kMobileOnOff},
{IDS_OS_SETTINGS_TAG_CELLULAR_TURN_OFF_ALT1, SearchConcept::kAltTagEnd}},
- {IDS_OS_SETTINGS_TAG_CELLULAR_APN,
- mojom::kCellularDetailsSubpagePath,
- mojom::SearchResultIcon::kCellular,
- mojom::SearchResultDefaultRank::kMedium,
- mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kCellularApn}},
});
return *tags;
}
@@ -269,7 +281,7 @@ const std::vector<SearchConcept>& GetCellularConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_CONFIGURE_IP_AUTOMATICALLY,
mojom::kCellularDetailsSubpagePath,
mojom::SearchResultIcon::kCellular,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kCellularAutoConfigureIp},
{IDS_OS_SETTINGS_TAG_CONFIGURE_IP_AUTOMATICALLY_ALT1,
@@ -278,7 +290,7 @@ const std::vector<SearchConcept>& GetCellularConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_NAME_SERVERS,
mojom::kCellularDetailsSubpagePath,
mojom::SearchResultIcon::kCellular,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kCellularDns},
{IDS_OS_SETTINGS_TAG_NAME_SERVERS_ALT1,
@@ -286,7 +298,7 @@ const std::vector<SearchConcept>& GetCellularConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_PROXY,
mojom::kCellularDetailsSubpagePath,
mojom::SearchResultIcon::kCellular,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kCellularProxy},
{IDS_OS_SETTINGS_TAG_PROXY_ALT1, IDS_OS_SETTINGS_TAG_PROXY_ALT2,
@@ -295,7 +307,7 @@ const std::vector<SearchConcept>& GetCellularConnectedSearchConcepts() {
{IDS_OS_SETTINGS_TAG_AUTO_CONNECT_NETWORK,
mojom::kCellularDetailsSubpagePath,
mojom::SearchResultIcon::kCellular,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kCellularAutoConnectToNetwork},
{IDS_OS_SETTINGS_TAG_AUTO_CONNECT_NETWORK_ALT1,
@@ -304,6 +316,18 @@ const std::vector<SearchConcept>& GetCellularConnectedSearchConcepts() {
return *tags;
}
+const std::vector<SearchConcept>& GetCellularMeteredSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_SETTINGS_INTERNET_NETWORK_METERED,
+ mojom::kCellularDetailsSubpagePath,
+ mojom::SearchResultIcon::kCellular,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kCellularMetered}},
+ });
+ return *tags;
+}
+
const std::vector<SearchConcept>& GetInstantTetheringSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_INSTANT_MOBILE_NETWORKS,
@@ -374,6 +398,52 @@ const std::vector<SearchConcept>& GetVpnConnectedSearchConcepts() {
return *tags;
}
+const std::vector<mojom::Setting>& GetEthernetDetailsSettings() {
+ static const base::NoDestructor<std::vector<mojom::Setting>> settings({
+ mojom::Setting::kConfigureEthernet,
+ mojom::Setting::kEthernetAutoConfigureIp,
+ mojom::Setting::kEthernetDns,
+ mojom::Setting::kEthernetProxy,
+ });
+ return *settings;
+}
+
+const std::vector<mojom::Setting>& GetWifiDetailsSettings() {
+ static const base::NoDestructor<std::vector<mojom::Setting>> settings({
+ mojom::Setting::kDisconnectWifiNetwork,
+ mojom::Setting::kPreferWifiNetwork,
+ mojom::Setting::kForgetWifiNetwork,
+ mojom::Setting::kWifiAutoConfigureIp,
+ mojom::Setting::kWifiDns,
+ mojom::Setting::kWifiProxy,
+ mojom::Setting::kWifiAutoConnectToNetwork,
+ mojom::Setting::kWifiMetered,
+ });
+ return *settings;
+}
+
+const std::vector<mojom::Setting>& GetCellularDetailsSettings() {
+ static const base::NoDestructor<std::vector<mojom::Setting>> settings({
+ mojom::Setting::kCellularSimLock,
+ mojom::Setting::kCellularRoaming,
+ mojom::Setting::kCellularApn,
+ mojom::Setting::kDisconnectCellularNetwork,
+ mojom::Setting::kCellularAutoConfigureIp,
+ mojom::Setting::kCellularDns,
+ mojom::Setting::kCellularProxy,
+ mojom::Setting::kCellularAutoConnectToNetwork,
+ mojom::Setting::kCellularMetered,
+ });
+ return *settings;
+}
+
+const std::vector<mojom::Setting>& GetTetherDetailsSettings() {
+ static const base::NoDestructor<std::vector<mojom::Setting>> settings({
+ mojom::Setting::kDisconnectTetherNetwork,
+ });
+ return *settings;
+}
+
bool IsConnected(network_config::mojom::ConnectionStateType connection_state) {
return connection_state ==
network_config::mojom::ConnectionStateType::kOnline ||
@@ -381,13 +451,49 @@ bool IsConnected(network_config::mojom::ConnectionStateType connection_state) {
network_config::mojom::ConnectionStateType::kConnected;
}
+bool IsPartOfDetailsSubpage(mojom::SearchResultType type,
+ OsSettingsIdentifier id,
+ mojom::Subpage details_subpage) {
+ switch (type) {
+ case mojom::SearchResultType::kSection:
+ // Applies to a section, not a details subpage.
+ return false;
+
+ case mojom::SearchResultType::kSubpage:
+ return id.subpage == details_subpage;
+
+ case mojom::SearchResultType::kSetting: {
+ const mojom::Setting& setting = id.setting;
+ switch (details_subpage) {
+ case mojom::Subpage::kEthernetDetails:
+ return base::Contains(GetEthernetDetailsSettings(), setting);
+ case mojom::Subpage::kWifiDetails:
+ return base::Contains(GetWifiDetailsSettings(), setting);
+ case mojom::Subpage::kCellularDetails:
+ return base::Contains(GetCellularDetailsSettings(), setting);
+ case mojom::Subpage::kTetherDetails:
+ return base::Contains(GetTetherDetailsSettings(), setting);
+ default:
+ return false;
+ }
+ }
+ }
+}
+
+std::string GetDetailsSubpageUrl(const std::string& url_to_modify,
+ const std::string& guid) {
+ return base::StringPrintf("%s?guid=%s", url_to_modify.c_str(), guid.c_str());
+}
+
} // namespace
InternetSection::InternetSection(Profile* profile,
SearchTagRegistry* search_tag_registry)
: OsSettingsSection(profile, search_tag_registry) {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
// General network search tags are always added.
- registry()->AddSearchTags(GetNetworkSearchConcepts());
+ updater.AddSearchTags(GetNetworkSearchConcepts());
// Receive updates when devices (e.g., Ethernet, Wi-Fi) go on/offline.
ash::GetNetworkConfigService(
@@ -396,7 +502,7 @@ InternetSection::InternetSection(Profile* profile,
// Fetch initial list of devices and active networks.
FetchDeviceList();
- FetchActiveNetworks();
+ FetchNetworkList();
}
InternetSection::~InternetSection() = default;
@@ -414,6 +520,7 @@ void InternetSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
{"internetConfigName", IDS_SETTINGS_INTERNET_CONFIG_NAME},
{"internetDetailPageTitle", IDS_SETTINGS_INTERNET_DETAIL},
{"internetDeviceEnabling", IDS_SETTINGS_INTERNET_DEVICE_ENABLING},
+ {"internetDeviceDisabling", IDS_SETTINGS_INTERNET_DEVICE_DISABLING},
{"internetDeviceInitializing", IDS_SETTINGS_INTERNET_DEVICE_INITIALIZING},
{"internetJoinType", IDS_SETTINGS_INTERNET_JOIN_TYPE},
{"internetKnownNetworksPageTitle", IDS_SETTINGS_INTERNET_KNOWN_NETWORKS},
@@ -461,6 +568,7 @@ void InternetSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
{"networkConnectNotAllowed", IDS_SETTINGS_INTERNET_CONNECT_NOT_ALLOWED},
{"networkIPAddress", IDS_SETTINGS_INTERNET_NETWORK_IP_ADDRESS},
{"networkIPConfigAuto", IDS_SETTINGS_INTERNET_NETWORK_IP_CONFIG_AUTO},
+ {"networkMetered", IDS_SETTINGS_INTERNET_NETWORK_METERED},
{"networkNameserversLearnMore", IDS_LEARN_MORE},
{"networkPrefer", IDS_SETTINGS_INTERNET_NETWORK_PREFER},
{"networkPrimaryUserControlled",
@@ -477,6 +585,8 @@ void InternetSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
{"networkSectionProxyExpandA11yLabel",
IDS_SETTINGS_INTERNET_NETWORK_SECTION_PROXY_ACCESSIBILITY_LABEL},
{"networkShared", IDS_SETTINGS_INTERNET_NETWORK_SHARED},
+ {"networkSharedOwner", IDS_SETTINGS_INTERNET_NETWORK_SHARED_OWNER},
+ {"networkSharedNotOwner", IDS_SETTINGS_INTERNET_NETWORK_SHARED_NOT_OWNER},
{"networkVpnBuiltin", IDS_NETWORK_TYPE_VPN_BUILTIN},
{"networkOutOfRange", IDS_SETTINGS_INTERNET_WIFI_NETWORK_OUT_OF_RANGE},
{"cellularContactSpecificCarrier",
@@ -535,14 +645,17 @@ void InternetSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
html_source->AddBoolean("showTechnologyBadge",
!ash::features::IsSeparateNetworkIconsEnabled());
+ html_source->AddBoolean(
+ "showMeteredToggle",
+ base::FeatureList::IsEnabled(features::kMeteredShowToggle));
html_source->AddString("networkGoogleNameserversLearnMoreUrl",
chrome::kGoogleNameserversLearnMoreURL);
html_source->AddString(
- "networkSyncedShared",
+ "networkNotSynced",
l10n_util::GetStringFUTF16(
- IDS_SETTINGS_INTERNET_NETWORK_SYNCED_SHARED,
+ IDS_SETTINGS_INTERNET_NETWORK_NOT_SYNCED,
GetHelpUrlWithBoard(chrome::kWifiSyncLearnMoreURL)));
html_source->AddString(
"networkSyncedUser",
@@ -550,6 +663,11 @@ void InternetSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
IDS_SETTINGS_INTERNET_NETWORK_SYNCED_USER,
GetHelpUrlWithBoard(chrome::kWifiSyncLearnMoreURL)));
html_source->AddString(
+ "networkSyncedDevice",
+ l10n_util::GetStringFUTF16(
+ IDS_SETTINGS_INTERNET_NETWORK_SYNCED_DEVICE,
+ GetHelpUrlWithBoard(chrome::kWifiSyncLearnMoreURL)));
+ html_source->AddString(
"internetNoNetworksMobileData",
l10n_util::GetStringFUTF16(
IDS_SETTINGS_INTERNET_LOOKING_FOR_MOBILE_NETWORK,
@@ -560,13 +678,140 @@ void InternetSection::AddHandlers(content::WebUI* web_ui) {
web_ui->AddMessageHandler(std::make_unique<InternetHandler>(profile()));
}
+int InternetSection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_INTERNET;
+}
+
+mojom::Section InternetSection::GetSection() const {
+ return mojom::Section::kNetwork;
+}
+
+mojom::SearchResultIcon InternetSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kWifi;
+}
+
+std::string InternetSection::GetSectionPath() const {
+ return mojom::kNetworkSectionPath;
+}
+
+void InternetSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ // Ethernet details.
+ generator->RegisterTopLevelSubpage(IDS_SETTINGS_INTERNET_ETHERNET_DETAILS,
+ mojom::Subpage::kEthernetDetails,
+ mojom::SearchResultIcon::kEthernet,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kEthernetDetailsSubpagePath);
+ RegisterNestedSettingBulk(mojom::Subpage::kEthernetDetails,
+ GetEthernetDetailsSettings(), generator);
+
+ // Wi-Fi networks.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_INTERNET_WIFI_NETWORKS, mojom::Subpage::kWifiNetworks,
+ mojom::SearchResultIcon::kWifi, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kWifiNetworksSubpagePath);
+ static constexpr mojom::Setting kWifiNetworksSettings[] = {
+ mojom::Setting::kWifiOnOff,
+ mojom::Setting::kWifiAddNetwork,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kWifiNetworks,
+ kWifiNetworksSettings, generator);
+ generator->RegisterTopLevelAltSetting(mojom::Setting::kWifiOnOff);
+
+ // Wi-Fi details.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_INTERNET_WIFI_DETAILS, mojom::Subpage::kWifiDetails,
+ mojom::Subpage::kWifiNetworks, mojom::SearchResultIcon::kWifi,
+ mojom::SearchResultDefaultRank::kMedium, mojom::kWifiDetailsSubpagePath);
+ RegisterNestedSettingBulk(mojom::Subpage::kWifiDetails,
+ GetWifiDetailsSettings(), generator);
+
+ // Known networks.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_INTERNET_KNOWN_NETWORKS, mojom::Subpage::kKnownNetworks,
+ mojom::Subpage::kWifiNetworks, mojom::SearchResultIcon::kWifi,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kKnownNetworksSubpagePath);
+ generator->RegisterNestedAltSetting(mojom::Setting::kPreferWifiNetwork,
+ mojom::Subpage::kKnownNetworks);
+ generator->RegisterNestedAltSetting(mojom::Setting::kForgetWifiNetwork,
+ mojom::Subpage::kKnownNetworks);
+
+ // Mobile data. If Instant Tethering is available, a mobile data subpage is
+ // available which lists both Cellular and Instant Tethering networks. If
+ // Instant Tethering is not available, there is no mobile data subpage.
+ generator->RegisterTopLevelSubpage(IDS_SETTINGS_INTERNET_MOBILE_DATA_NETWORKS,
+ mojom::Subpage::kMobileDataNetworks,
+ mojom::SearchResultIcon::kCellular,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kMobileDataNetworksSubpagePath);
+ static constexpr mojom::Setting kMobileDataNetworksSettings[] = {
+ mojom::Setting::kMobileOnOff,
+ mojom::Setting::kInstantTetheringOnOff,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kMobileDataNetworks,
+ kMobileDataNetworksSettings, generator);
+ generator->RegisterTopLevelAltSetting(mojom::Setting::kMobileOnOff);
+
+ // Cellular details. Cellular details are considered a child of the mobile
+ // data subpage. However, note that if Instant Tethering is not available,
+ // clicking on "Mobile data" at the Network section navigates users directly
+ // to the cellular details page and skips over the mobile data subpage.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_INTERNET_CELLULAR_DETAILS, mojom::Subpage::kCellularDetails,
+ mojom::Subpage::kMobileDataNetworks, mojom::SearchResultIcon::kCellular,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kCellularDetailsSubpagePath);
+ RegisterNestedSettingBulk(mojom::Subpage::kCellularDetails,
+ GetCellularDetailsSettings(), generator);
+
+ // Instant Tethering. Although this is a multi-device feature, its UI resides
+ // in the network section.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_INTERNET_INSTANT_TETHERING_DETAILS,
+ mojom::Subpage::kTetherDetails, mojom::Subpage::kMobileDataNetworks,
+ mojom::SearchResultIcon::kInstantTethering,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kTetherDetailsSubpagePath);
+ RegisterNestedSettingBulk(mojom::Subpage::kTetherDetails,
+ GetTetherDetailsSettings(), generator);
+
+ // VPN.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_INTERNET_VPN_DETAILS, mojom::Subpage::kVpnDetails,
+ mojom::SearchResultIcon::kWifi, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kVpnDetailsSubpagePath);
+}
+
+std::string InternetSection::ModifySearchResultUrl(
+ mojom::SearchResultType type,
+ OsSettingsIdentifier id,
+ const std::string& url_to_modify) const {
+ if (IsPartOfDetailsSubpage(type, id, mojom::Subpage::kEthernetDetails))
+ return GetDetailsSubpageUrl(url_to_modify, *connected_ethernet_guid_);
+
+ if (IsPartOfDetailsSubpage(type, id, mojom::Subpage::kWifiDetails))
+ return GetDetailsSubpageUrl(url_to_modify, *connected_wifi_guid_);
+
+ if (IsPartOfDetailsSubpage(type, id, mojom::Subpage::kCellularDetails))
+ return GetDetailsSubpageUrl(url_to_modify, *cellular_guid_);
+
+ if (IsPartOfDetailsSubpage(type, id, mojom::Subpage::kTetherDetails))
+ return GetDetailsSubpageUrl(url_to_modify, *connected_tether_guid_);
+
+ if (IsPartOfDetailsSubpage(type, id, mojom::Subpage::kVpnDetails))
+ return GetDetailsSubpageUrl(url_to_modify, *connected_vpn_guid_);
+
+ // URL does not need to be modified; use default implementation.
+ return OsSettingsSection::ModifySearchResultUrl(type, id, url_to_modify);
+}
+
void InternetSection::OnDeviceStateListChanged() {
FetchDeviceList();
}
void InternetSection::OnActiveNetworksChanged(
std::vector<network_config::mojom::NetworkStatePropertiesPtr> networks) {
- OnActiveNetworks(std::move(networks));
+ FetchNetworkList();
}
void InternetSection::FetchDeviceList() {
@@ -579,40 +824,43 @@ void InternetSection::OnDeviceList(
using network_config::mojom::DeviceStateType;
using network_config::mojom::NetworkType;
- registry()->RemoveSearchTags(GetWifiSearchConcepts());
- registry()->RemoveSearchTags(GetWifiOnSearchConcepts());
- registry()->RemoveSearchTags(GetWifiOffSearchConcepts());
- registry()->RemoveSearchTags(GetCellularSearchConcepts());
- registry()->RemoveSearchTags(GetCellularOnSearchConcepts());
- registry()->RemoveSearchTags(GetCellularOffSearchConcepts());
- registry()->RemoveSearchTags(GetInstantTetheringSearchConcepts());
- registry()->RemoveSearchTags(GetInstantTetheringOnSearchConcepts());
- registry()->RemoveSearchTags(GetInstantTetheringOffSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
+ updater.RemoveSearchTags(GetWifiSearchConcepts());
+ updater.RemoveSearchTags(GetWifiOnSearchConcepts());
+ updater.RemoveSearchTags(GetWifiOffSearchConcepts());
+ updater.RemoveSearchTags(GetCellularOnSearchConcepts());
+ updater.RemoveSearchTags(GetCellularOffSearchConcepts());
+ updater.RemoveSearchTags(GetInstantTetheringSearchConcepts());
+ updater.RemoveSearchTags(GetInstantTetheringOnSearchConcepts());
+ updater.RemoveSearchTags(GetInstantTetheringOffSearchConcepts());
for (const auto& device : devices) {
switch (device->type) {
case NetworkType::kWiFi:
- registry()->AddSearchTags(GetWifiSearchConcepts());
+ updater.AddSearchTags(GetWifiSearchConcepts());
if (device->device_state == DeviceStateType::kEnabled)
- registry()->AddSearchTags(GetWifiOnSearchConcepts());
+ updater.AddSearchTags(GetWifiOnSearchConcepts());
else if (device->device_state == DeviceStateType::kDisabled)
- registry()->AddSearchTags(GetWifiOffSearchConcepts());
+ updater.AddSearchTags(GetWifiOffSearchConcepts());
break;
case NetworkType::kCellular:
- registry()->AddSearchTags(GetCellularSearchConcepts());
+ // Note: Cellular search concepts all point to the cellular details
+ // page, which is only available if a cellular network exists. This
+ // check is in OnNetworkList().
if (device->device_state == DeviceStateType::kEnabled)
- registry()->AddSearchTags(GetCellularOnSearchConcepts());
+ updater.AddSearchTags(GetCellularOnSearchConcepts());
else if (device->device_state == DeviceStateType::kDisabled)
- registry()->AddSearchTags(GetCellularOffSearchConcepts());
+ updater.AddSearchTags(GetCellularOffSearchConcepts());
break;
case NetworkType::kTether:
- registry()->AddSearchTags(GetInstantTetheringSearchConcepts());
+ updater.AddSearchTags(GetInstantTetheringSearchConcepts());
if (device->device_state == DeviceStateType::kEnabled)
- registry()->AddSearchTags(GetInstantTetheringOnSearchConcepts());
+ updater.AddSearchTags(GetInstantTetheringOnSearchConcepts());
else if (device->device_state == DeviceStateType::kDisabled)
- registry()->AddSearchTags(GetInstantTetheringOffSearchConcepts());
+ updater.AddSearchTags(GetInstantTetheringOffSearchConcepts());
break;
default:
@@ -623,48 +871,76 @@ void InternetSection::OnDeviceList(
}
}
-void InternetSection::FetchActiveNetworks() {
+void InternetSection::FetchNetworkList() {
cros_network_config_->GetNetworkStateList(
network_config::mojom::NetworkFilter::New(
- network_config::mojom::FilterType::kActive,
+ network_config::mojom::FilterType::kVisible,
network_config::mojom::NetworkType::kAll,
network_config::mojom::kNoLimit),
- base::Bind(&InternetSection::OnActiveNetworks, base::Unretained(this)));
+ base::Bind(&InternetSection::OnNetworkList, base::Unretained(this)));
}
-void InternetSection::OnActiveNetworks(
+void InternetSection::OnNetworkList(
std::vector<network_config::mojom::NetworkStatePropertiesPtr> networks) {
using network_config::mojom::NetworkType;
- registry()->RemoveSearchTags(GetEthernetConnectedSearchConcepts());
- registry()->RemoveSearchTags(GetWifiConnectedSearchConcepts());
- registry()->RemoveSearchTags(GetCellularConnectedSearchConcepts());
- registry()->RemoveSearchTags(GetInstantTetheringConnectedSearchConcepts());
- registry()->RemoveSearchTags(GetVpnConnectedSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
+ updater.RemoveSearchTags(GetEthernetConnectedSearchConcepts());
+ updater.RemoveSearchTags(GetWifiConnectedSearchConcepts());
+ updater.RemoveSearchTags(GetWifiMeteredSearchConcepts());
+ updater.RemoveSearchTags(GetCellularSearchConcepts());
+ updater.RemoveSearchTags(GetCellularConnectedSearchConcepts());
+ updater.RemoveSearchTags(GetCellularMeteredSearchConcepts());
+ updater.RemoveSearchTags(GetInstantTetheringConnectedSearchConcepts());
+ updater.RemoveSearchTags(GetVpnConnectedSearchConcepts());
+
+ cellular_guid_.reset();
+
+ connected_ethernet_guid_.reset();
+ connected_wifi_guid_.reset();
+ connected_tether_guid_.reset();
+ connected_vpn_guid_.reset();
for (const auto& network : networks) {
+ // Special case: Some cellular search functionality is available even if the
+ // network is not connected.
+ if (network->type == NetworkType::kCellular) {
+ cellular_guid_ = network->guid;
+ updater.AddSearchTags(GetCellularSearchConcepts());
+ }
+
if (!IsConnected(network->connection_state))
continue;
switch (network->type) {
case NetworkType::kEthernet:
- registry()->AddSearchTags(GetEthernetConnectedSearchConcepts());
+ connected_ethernet_guid_ = network->guid;
+ updater.AddSearchTags(GetEthernetConnectedSearchConcepts());
break;
case NetworkType::kWiFi:
- registry()->AddSearchTags(GetWifiConnectedSearchConcepts());
+ connected_wifi_guid_ = network->guid;
+ updater.AddSearchTags(GetWifiConnectedSearchConcepts());
+ if (base::FeatureList::IsEnabled(features::kMeteredShowToggle))
+ updater.AddSearchTags(GetWifiMeteredSearchConcepts());
break;
case NetworkType::kCellular:
- registry()->AddSearchTags(GetCellularConnectedSearchConcepts());
+ // Note: GUID is set above.
+ updater.AddSearchTags(GetCellularConnectedSearchConcepts());
+ if (base::FeatureList::IsEnabled(features::kMeteredShowToggle))
+ updater.AddSearchTags(GetCellularMeteredSearchConcepts());
break;
case NetworkType::kTether:
- registry()->AddSearchTags(GetInstantTetheringConnectedSearchConcepts());
+ connected_tether_guid_ = network->guid;
+ updater.AddSearchTags(GetInstantTetheringConnectedSearchConcepts());
break;
case NetworkType::kVPN:
- registry()->AddSearchTags(GetVpnConnectedSearchConcepts());
+ connected_vpn_guid_ = network->guid;
+ updater.AddSearchTags(GetVpnConnectedSearchConcepts());
break;
default:
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_section.h
index f467529b810..cbe35474631 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/internet_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/internet_section.h
@@ -5,8 +5,10 @@
#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_INTERNET_SECTION_H_
#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_INTERNET_SECTION_H_
+#include <string>
#include <vector>
+#include "base/optional.h"
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_section.h"
#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h"
#include "mojo/public/cpp/bindings/receiver.h"
@@ -34,6 +36,15 @@ class InternetSection
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
+ std::string ModifySearchResultUrl(
+ mojom::SearchResultType type,
+ OsSettingsIdentifier id,
+ const std::string& url_to_modify) const override;
// network_config::mojom::CrosNetworkConfigObserver:
void OnActiveNetworksChanged(
@@ -51,10 +62,19 @@ class InternetSection
void OnDeviceList(
std::vector<network_config::mojom::DeviceStatePropertiesPtr> devices);
- void FetchActiveNetworks();
- void OnActiveNetworks(
+ void FetchNetworkList();
+ void OnNetworkList(
std::vector<network_config::mojom::NetworkStatePropertiesPtr> networks);
+ // Null if no cellular network exists.
+ base::Optional<std::string> cellular_guid_;
+
+ // Note: If not connected, the below fields are null.
+ base::Optional<std::string> connected_ethernet_guid_;
+ base::Optional<std::string> connected_wifi_guid_;
+ base::Optional<std::string> connected_tether_guid_;
+ base::Optional<std::string> connected_vpn_guid_;
+
mojo::Receiver<network_config::mojom::CrosNetworkConfigObserver> receiver_{
this};
mojo::Remote<network_config::mojom::CrosNetworkConfig> cros_network_config_;
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/languages_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/languages_section.cc
index 0007f1a6a8b..78321bd8c64 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/languages_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/languages_section.cc
@@ -7,6 +7,7 @@
#include "base/feature_list.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
+#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_features_util.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h"
#include "chrome/browser/ui/webui/settings/languages_handler.h"
@@ -14,6 +15,8 @@
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/constants/chromeos_features.h"
+#include "chromeos/constants/chromeos_pref_names.h"
+#include "components/prefs/pref_service.h"
#include "content/public/browser/web_ui_data_source.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
@@ -57,7 +60,7 @@ const std::vector<SearchConcept>& GetLanguagesSearchConcepts() {
const std::vector<SearchConcept>& GetSmartInputsSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_LANGUAGES_SMART_INPUTS,
- mojom::kSmartInputsSubagePath,
+ mojom::kSmartInputsSubpagePath,
mojom::SearchResultIcon::kGlobe,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
@@ -69,7 +72,7 @@ const std::vector<SearchConcept>& GetSmartInputsSearchConcepts() {
const std::vector<SearchConcept>& GetAssistivePersonalInfoSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_LANGUAGES_PERSONAL_INFORMATION_SUGGESTIONS,
- mojom::kSmartInputsSubagePath,
+ mojom::kSmartInputsSubpagePath,
mojom::SearchResultIcon::kGlobe,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
@@ -78,13 +81,26 @@ const std::vector<SearchConcept>& GetAssistivePersonalInfoSearchConcepts() {
return *tags;
}
+const std::vector<SearchConcept>& GetEmojiSuggestionSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_LANGUAGES_EMOJI_SUGGESTIONS,
+ mojom::kSmartInputsSubpagePath,
+ mojom::SearchResultIcon::kGlobe,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kShowEmojiSuggestions}},
+ });
+ return *tags;
+}
+
bool IsAssistivePersonalInfoAllowed() {
return !features::IsGuestModeActive() &&
base::FeatureList::IsEnabled(
::chromeos::features::kAssistPersonalInfo);
}
-void AddSmartInputsStrings(content::WebUIDataSource* html_source) {
+void AddSmartInputsStrings(content::WebUIDataSource* html_source,
+ bool is_emoji_suggestion_allowed) {
static constexpr webui::LocalizedString kLocalizedStrings[] = {
{"smartInputsTitle", IDS_SETTINGS_SMART_INPUTS_TITLE},
{"personalInfoSuggestionTitle",
@@ -94,11 +110,71 @@ void AddSmartInputsStrings(content::WebUIDataSource* html_source) {
{"showPersonalInfoSuggestion",
IDS_SETTINGS_SMART_INPUTS_SHOW_PERSONAL_INFO},
{"managePersonalInfo", IDS_SETTINGS_SMART_INPUTS_MANAGE_PERSONAL_INFO},
+ {"emojiSuggestionTitle",
+ IDS_SETTINGS_SMART_INPUTS_EMOJI_SUGGESTION_TITLE},
+ {"emojiSuggestionDescription",
+ IDS_SETTINGS_SMART_INPUTS_EMOJI_SUGGESTION_DESCRIPTION},
+ {"showEmojiSuggestion", IDS_SETTINGS_SMART_INPUTS_SHOW_EMOJI_SUGGESTION},
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings);
html_source->AddBoolean("allowAssistivePersonalInfo",
IsAssistivePersonalInfoAllowed());
+ html_source->AddBoolean("allowEmojiSuggestion", is_emoji_suggestion_allowed);
+}
+
+void AddInputMethodOptionsStrings(content::WebUIDataSource* html_source) {
+ static constexpr webui::LocalizedString kLocalizedStrings[] = {
+ {"inputMethodOptionsBasicSectionTitle",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_BASIC},
+ {"inputMethodOptionsAdvancedSectionTitle",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_ADVANCED},
+ {"inputMethodOptionsPhysicalKeyboardSectionTitle",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_PHYSICAL_KEYBOARD},
+ {"inputMethodOptionsVirtualKeyboardSectionTitle",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_VIRTUAL_KEYBOARD},
+ {"inputMethodOptionsEnableDoubleSpacePeriod",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_ENABLE_DOUBLE_SPACE_PERIOD},
+ {"inputMethodOptionsEnableGestureTyping",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_ENABLE_GESTURE_TYPING},
+ {"inputMethodOptionsEnablePrediction",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_ENABLE_PREDICTION},
+ {"inputMethodOptionsEnableSoundOnKeypress",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_ENABLE_SOUND_ON_KEYPRESS},
+ {"inputMethodOptionsEnableCapitalization",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_ENABLE_CAPITALIZATION},
+ {"inputMethodOptionsAutoCorrection",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_AUTO_CORRECTION},
+ {"inputMethodOptionsXkbLayout",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_XKB_LAYOUT},
+ {"inputMethodOptionsEditUserDict",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_EDIT_USER_DICT},
+ {"inputMethodOptionsPinyinChinesePunctuation",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_PINYIN_CHINESE_PUNCTUATION},
+ {"inputMethodOptionsPinyinDefaultChinese",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_PINYIN_DEFAULT_CHINESE},
+ {"inputMethodOptionsPinyinEnableFuzzy",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_PINYIN_ENABLE_FUZZY},
+ {"inputMethodOptionsPinyinEnableLowerPaging",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_PINYIN_ENABLE_LOWER_PAGING},
+ {"inputMethodOptionsPinyinEnableUpperPaging",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_PINYIN_ENABLE_UPPER_PAGING},
+ {"inputMethodOptionsPinyinFullWidthCharacter",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_PINYIN_FULL_WIDTH_CHARACTER},
+ {"inputMethodOptionsAutoCorrectionOff",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_AUTO_CORRECTION_OFF},
+ {"inputMethodOptionsAutoCorrectionModest",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_AUTO_CORRECTION_MODEST},
+ {"inputMethodOptionsAutoCorrectionAggressive",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_AUTO_CORRECTION_AGGRESSIVE},
+ {"inputMethodOptionsUsKeyboard",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_KEYBOARD_US},
+ {"inputMethodOptionsDvorakKeyboard",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_KEYBOARD_DVORAK},
+ {"inputMethodOptionsColemakKeyboard",
+ IDS_SETTINGS_INPUT_METHOD_OPTIONS_KEYBOARD_COLEMAK},
+ };
+ AddLocalizedStringsBulk(html_source, kLocalizedStrings);
}
} // namespace
@@ -106,11 +182,15 @@ void AddSmartInputsStrings(content::WebUIDataSource* html_source) {
LanguagesSection::LanguagesSection(Profile* profile,
SearchTagRegistry* search_tag_registry)
: OsSettingsSection(profile, search_tag_registry) {
- registry()->AddSearchTags(GetLanguagesSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetLanguagesSearchConcepts());
- if (IsAssistivePersonalInfoAllowed()) {
- registry()->AddSearchTags(GetSmartInputsSearchConcepts());
- registry()->AddSearchTags(GetAssistivePersonalInfoSearchConcepts());
+ if (IsAssistivePersonalInfoAllowed() || IsEmojiSuggestionAllowed()) {
+ updater.AddSearchTags(GetSmartInputsSearchConcepts());
+ if (IsAssistivePersonalInfoAllowed())
+ updater.AddSearchTags(GetAssistivePersonalInfoSearchConcepts());
+ if (IsEmojiSuggestionAllowed())
+ updater.AddSearchTags(GetEmojiSuggestionSearchConcepts());
}
}
@@ -149,11 +229,15 @@ void LanguagesSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
{"moveUp", IDS_SETTINGS_LANGUAGES_LANGUAGES_LIST_MOVE_UP},
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings);
- AddSmartInputsStrings(html_source);
+ AddSmartInputsStrings(html_source, IsEmojiSuggestionAllowed());
+ AddInputMethodOptionsStrings(html_source);
html_source->AddString(
"languagesLearnMoreURL",
base::ASCIIToUTF16(chrome::kLanguageSettingsLearnMoreUrl));
+ html_source->AddBoolean("imeOptionsInSettings",
+ base::FeatureList::IsEnabled(
+ ::chromeos::features::kImeOptionsInSettings));
}
void LanguagesSection::AddHandlers(content::WebUI* web_ui) {
@@ -161,5 +245,71 @@ void LanguagesSection::AddHandlers(content::WebUI* web_ui) {
std::make_unique<::settings::LanguagesHandler>(profile()));
}
+int LanguagesSection::GetSectionNameMessageId() const {
+ return IDS_OS_SETTINGS_LANGUAGES_AND_INPUT_PAGE_TITLE;
+}
+
+mojom::Section LanguagesSection::GetSection() const {
+ return mojom::Section::kLanguagesAndInput;
+}
+
+mojom::SearchResultIcon LanguagesSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kGlobe;
+}
+
+std::string LanguagesSection::GetSectionPath() const {
+ return mojom::kLanguagesAndInputSectionPath;
+}
+
+bool LanguagesSection::IsEmojiSuggestionAllowed() const {
+ return base::FeatureList::IsEnabled(
+ ::chromeos::features::kEmojiSuggestAddition) &&
+ profile()->GetPrefs()->GetBoolean(
+ ::chromeos::prefs::kEmojiSuggestionEnterpriseAllowed);
+}
+
+void LanguagesSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ // Languages and input details.
+ generator->RegisterTopLevelSubpage(
+ IDS_OS_SETTINGS_LANGUAGES_AND_INPUT_PAGE_TITLE,
+ mojom::Subpage::kLanguagesAndInputDetails,
+ mojom::SearchResultIcon::kGlobe, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kLanguagesAndInputDetailsSubpagePath);
+ static constexpr mojom::Setting kLanguagesAndInputDetailsSettings[] = {
+ mojom::Setting::kAddLanguage,
+ mojom::Setting::kShowInputOptionsInShelf,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kLanguagesAndInputDetails,
+ kLanguagesAndInputDetailsSettings, generator);
+
+ // Manage input methods.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_LANGUAGES_MANAGE_INPUT_METHODS_TITLE,
+ mojom::Subpage::kManageInputMethods,
+ mojom::Subpage::kLanguagesAndInputDetails,
+ mojom::SearchResultIcon::kGlobe, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kManageInputMethodsSubpagePath);
+
+ // Input method options.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_LANGUAGES_INPUT_METHOD_OPTIONS_TITLE,
+ mojom::Subpage::kInputMethodOptions,
+ mojom::Subpage::kLanguagesAndInputDetails,
+ mojom::SearchResultIcon::kGlobe, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kInputMethodOptionsSubpagePath);
+
+ // Smart inputs.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_SMART_INPUTS_TITLE, mojom::Subpage::kSmartInputs,
+ mojom::SearchResultIcon::kGlobe, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kSmartInputsSubpagePath);
+ static constexpr mojom::Setting kSmartInputsFeaturesSettings[] = {
+ mojom::Setting::kShowPersonalInformationSuggestions,
+ mojom::Setting::kShowEmojiSuggestions,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kSmartInputs,
+ kSmartInputsFeaturesSettings, generator);
+}
+
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/languages_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/languages_section.h
index d8a742babc2..9236455754d 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/languages_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/languages_section.h
@@ -28,6 +28,13 @@ class LanguagesSection : public OsSettingsSection {
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
+
+ bool IsEmojiSuggestionAllowed() const;
};
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/main_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/main_section.cc
index 9afd5882393..0868f9c866a 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/main_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/main_section.cc
@@ -39,8 +39,6 @@ void AddSearchInSettingsStrings(content::WebUIDataSource* html_source) {
{"searchNoResults", IDS_SEARCH_NO_RESULTS},
{"searchResults", IDS_SEARCH_RESULTS},
{"searchResultSelected", IDS_OS_SEARCH_RESULT_ROW_A11Y_RESULT_SELECTED},
- {"searchResultsOne", IDS_OS_SEARCH_BOX_A11Y_ONE_RESULT},
- {"searchResultsNumber", IDS_OS_SEARCH_BOX_A11Y_RESULT_COUNT},
// TODO(dpapad): IDS_DOWNLOAD_CLEAR_SEARCH and IDS_HISTORY_CLEAR_SEARCH
// are identical, merge them to one and re-use here.
{"clearSearch", IDS_DOWNLOAD_CLEAR_SEARCH},
@@ -98,6 +96,10 @@ void MainSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
{"settings", IDS_SETTINGS_SETTINGS},
{"settingsAltPageTitle", IDS_SETTINGS_ALT_PAGE_TITLE},
{"subpageArrowRoleDescription", IDS_SETTINGS_SUBPAGE_BUTTON},
+ {"subpageBackButtonAriaLabel",
+ IDS_SETTINGS_SUBPAGE_BACK_BUTTON_ARIA_LABEL},
+ {"subpageBackButtonAriaRoleDescription",
+ IDS_SETTINGS_SUBPAGE_BACK_BUTTON_ARIA_ROLE_DESCRIPTION},
{"notValidWebAddress", IDS_SETTINGS_NOT_VALID_WEB_ADDRESS},
{"notValidWebAddressForContentType",
IDS_SETTINGS_NOT_VALID_WEB_ADDRESS_FOR_CONTENT_TYPE},
@@ -143,11 +145,6 @@ void MainSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
html_source->AddResourcePath("search/search.mojom-lite.js",
IDR_OS_SETTINGS_SEARCH_MOJOM_LITE_JS);
- html_source->AddString("browserSettingsBannerText",
- l10n_util::GetStringFUTF16(
- IDS_SETTINGS_BROWSER_SETTINGS_BANNER,
- base::ASCIIToUTF16(chrome::kChromeUISettingsURL)));
-
AddSearchInSettingsStrings(html_source);
AddChromeOSUserStrings(html_source);
@@ -162,6 +159,32 @@ void MainSection::AddHandlers(content::WebUI* web_ui) {
std::make_unique<::settings::BrowserLifetimeHandler>());
}
+int MainSection::GetSectionNameMessageId() const {
+ NOTIMPLEMENTED();
+ return 0;
+}
+
+mojom::Section MainSection::GetSection() const {
+ NOTIMPLEMENTED();
+ return mojom::Section::kMinValue;
+}
+
+mojom::SearchResultIcon MainSection::GetSectionIcon() const {
+ NOTIMPLEMENTED();
+ return mojom::SearchResultIcon::kMinValue;
+}
+
+std::string MainSection::GetSectionPath() const {
+ NOTIMPLEMENTED();
+ return std::string();
+}
+
+void MainSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ // MainSection is a container for common resources/functionality shared
+ // between sections and does not have its own subpages/settings.
+ NOTIMPLEMENTED();
+}
+
void MainSection::AddChromeOSUserStrings(
content::WebUIDataSource* html_source) {
const user_manager::User* user =
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/main_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/main_section.h
index 7f8d9de7d5c..fab6b9bfdc3 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/main_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/main_section.h
@@ -26,6 +26,11 @@ class MainSection : public OsSettingsSection {
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
void AddChromeOSUserStrings(content::WebUIDataSource* html_source);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_section.cc
index 7ce85eaf234..da38e8b2896 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_section.cc
@@ -4,19 +4,25 @@
#include "chrome/browser/ui/webui/settings/chromeos/multidevice_section.h"
+#include "base/feature_list.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
+#include "chrome/browser/browser_features.h"
#include "chrome/browser/chromeos/android_sms/android_sms_service.h"
+#include "chrome/browser/nearby_sharing/nearby_sharing_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/settings/chromeos/multidevice_handler.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h"
+#include "chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.h"
#include "chrome/browser/ui/webui/webui_util.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/generated_resources.h"
+#include "chromeos/constants/chromeos_features.h"
#include "chromeos/services/multidevice_setup/public/cpp/prefs.h"
#include "chromeos/services/multidevice_setup/public/cpp/url_provider.h"
#include "chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom.h"
+#include "components/prefs/pref_service.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "ui/base/l10n/l10n_util.h"
@@ -27,8 +33,22 @@ namespace chromeos {
namespace settings {
namespace {
-const std::vector<SearchConcept>& GetMultiDeviceSearchConcepts() {
+const std::vector<SearchConcept>& GetMultiDeviceOptedInSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_MULTIDEVICE_SMART_LOCK_OPTIONS,
+ mojom::kSmartLockSubpagePath,
+ mojom::SearchResultIcon::kLock,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSubpage,
+ {.subpage = mojom::Subpage::kSmartLock}},
+ {IDS_OS_SETTINGS_TAG_MULTIDEVICE_FORGET,
+ mojom::kMultiDeviceFeaturesSubpagePath,
+ mojom::SearchResultIcon::kPhone,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kForgetPhone},
+ {IDS_OS_SETTINGS_TAG_MULTIDEVICE_FORGET_ALT1,
+ SearchConcept::kAltTagEnd}},
{IDS_OS_SETTINGS_TAG_MULTIDEVICE_MESSAGES,
mojom::kMultiDeviceFeaturesSubpagePath,
mojom::SearchResultIcon::kMessages,
@@ -40,54 +60,78 @@ const std::vector<SearchConcept>& GetMultiDeviceSearchConcepts() {
{IDS_OS_SETTINGS_TAG_MULTIDEVICE,
mojom::kMultiDeviceFeaturesSubpagePath,
mojom::SearchResultIcon::kPhone,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kMultiDeviceFeatures},
- {IDS_OS_SETTINGS_TAG_MULTIDEVICE_ALT1,
- IDS_OS_SETTINGS_TAG_MULTIDEVICE_ALT2,
- IDS_OS_SETTINGS_TAG_MULTIDEVICE_ALT3, SearchConcept::kAltTagEnd}},
+ {IDS_OS_SETTINGS_TAG_MULTIDEVICE_ALT1, SearchConcept::kAltTagEnd}},
{IDS_OS_SETTINGS_TAG_MULTIDEVICE_SMART_LOCK,
mojom::kMultiDeviceFeaturesSubpagePath,
mojom::SearchResultIcon::kLock,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
- {.subpage = mojom::Subpage::kSmartLock},
- {IDS_OS_SETTINGS_TAG_MULTIDEVICE_SMART_LOCK_ALT1,
- SearchConcept::kAltTagEnd}},
+ {.subpage = mojom::Subpage::kSmartLock}},
});
return *tags;
}
-const std::vector<SearchConcept>& GetMultiDeviceOptedInSearchConcepts() {
+const std::vector<SearchConcept>& GetMultiDeviceOptedOutSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags([] {
+ // Special-case: The "set up" search tag also includes the names of the
+ // multi-device features as a way to increase discoverability of these
+ // features.
+ SearchConcept set_up_concept{
+ IDS_OS_SETTINGS_TAG_MULTIDEVICE_SET_UP,
+ mojom::kMultiDeviceSectionPath,
+ mojom::SearchResultIcon::kPhone,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kSetUpMultiDevice},
+ {IDS_OS_SETTINGS_TAG_MULTIDEVICE,
+ IDS_OS_SETTINGS_TAG_MULTIDEVICE_MESSAGES,
+ IDS_OS_SETTINGS_TAG_MULTIDEVICE_SMART_LOCK, SearchConcept::kAltTagEnd},
+ };
+
+ // If Instant Tethering is available, also include that in the list.
+ if (base::FeatureList::IsEnabled(features::kInstantTethering)) {
+ set_up_concept.alt_tag_ids[3] = IDS_OS_SETTINGS_TAG_INSTANT_TETHERING;
+ set_up_concept.alt_tag_ids[4] = SearchConcept::kAltTagEnd;
+ }
+
+ return std::vector<SearchConcept>{set_up_concept};
+ }());
+ return *tags;
+}
+
+const std::vector<SearchConcept>& GetNearbyShareOnSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- {IDS_OS_SETTINGS_TAG_MULTIDEVICE_SMART_LOCK_OPTIONS,
- mojom::kSmartLockSubpagePath,
- mojom::SearchResultIcon::kLock,
+ {IDS_OS_SETTINGS_TAG_MULTIDEVICE_NEARBY_SHARE,
+ mojom::kNearbyShareSubpagePath,
+ mojom::SearchResultIcon::kNearbyShare,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
- {.subpage = mojom::Subpage::kSmartLock},
- {IDS_OS_SETTINGS_TAG_MULTIDEVICE_SMART_LOCK_OPTIONS_ALT1,
- SearchConcept::kAltTagEnd}},
- {IDS_OS_SETTINGS_TAG_MULTIDEVICE_FORGET,
- mojom::kMultiDeviceFeaturesSubpagePath,
- mojom::SearchResultIcon::kPhone,
+ {.subpage = mojom::Subpage::kNearbyShare}},
+ {IDS_OS_SETTINGS_TAG_NEARBY_SHARE_TURN_OFF,
+ mojom::kNearbyShareSubpagePath,
+ mojom::SearchResultIcon::kNearbyShare,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kForgetPhone},
- {IDS_OS_SETTINGS_TAG_MULTIDEVICE_FORGET_ALT1,
+ {.setting = mojom::Setting::kNearbyShareOnOff},
+ {IDS_OS_SETTINGS_TAG_NEARBY_SHARE_TURN_OFF_ALT1,
SearchConcept::kAltTagEnd}},
});
return *tags;
}
-const std::vector<SearchConcept>& GetMultiDeviceOptedOutSearchConcepts() {
+const std::vector<SearchConcept>& GetNearbyShareOffSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- {IDS_OS_SETTINGS_TAG_MULTIDEVICE_SET_UP,
+ {IDS_OS_SETTINGS_TAG_NEARBY_SHARE_TURN_ON,
mojom::kMultiDeviceSectionPath,
- mojom::SearchResultIcon::kPhone,
+ mojom::SearchResultIcon::kNearbyShare,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kSetUpMultiDevice}},
+ {.setting = mojom::Setting::kNearbyShareOnOff},
+ {IDS_OS_SETTINGS_TAG_NEARBY_SHARE_TURN_ON_ALT1,
+ SearchConcept::kAltTagEnd}},
});
return *tags;
}
@@ -121,13 +165,21 @@ MultiDeviceSection::MultiDeviceSection(
multidevice_setup_client_(multidevice_setup_client),
android_sms_service_(android_sms_service),
pref_service_(pref_service) {
+ if (base::FeatureList::IsEnabled(::features::kNearbySharing)) {
+ pref_change_registrar_.Init(pref_service_);
+ pref_change_registrar_.Add(
+ ::prefs::kNearbySharingEnabledPrefName,
+ base::BindRepeating(&MultiDeviceSection::OnNearbySharingEnabledChanged,
+ base::Unretained(this)));
+ OnNearbySharingEnabledChanged();
+ }
+
// Note: |multidevice_setup_client_| is null when multi-device features are
// prohibited by policy.
if (!multidevice_setup_client_)
return;
multidevice_setup_client_->AddObserver(this);
- registry()->AddSearchTags(GetMultiDeviceSearchConcepts());
OnHostStatusChanged(multidevice_setup_client_->GetHostStatus());
}
@@ -214,6 +266,7 @@ void MultiDeviceSection::AddLoadTimeData(
GetHelpUrlWithBoard(chrome::kEasyUnlockLearnMoreUrl)));
AddEasyUnlockStrings(html_source);
+ ::settings::AddNearbyShareData(html_source);
}
void MultiDeviceSection::AddHandlers(content::WebUI* web_ui) {
@@ -231,15 +284,96 @@ void MultiDeviceSection::AddHandlers(content::WebUI* web_ui) {
: nullptr));
}
+int MultiDeviceSection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_MULTIDEVICE;
+}
+
+mojom::Section MultiDeviceSection::GetSection() const {
+ return mojom::Section::kMultiDevice;
+}
+
+mojom::SearchResultIcon MultiDeviceSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kPhone;
+}
+
+std::string MultiDeviceSection::GetSectionPath() const {
+ return mojom::kMultiDeviceSectionPath;
+}
+
+void MultiDeviceSection::RegisterHierarchy(
+ HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSetting(mojom::Setting::kSetUpMultiDevice);
+ generator->RegisterTopLevelSetting(mojom::Setting::kVerifyMultiDeviceSetup);
+
+ // MultiDevice features.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_MULTIDEVICE, mojom::Subpage::kMultiDeviceFeatures,
+ mojom::SearchResultIcon::kPhone, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kMultiDeviceFeaturesSubpagePath);
+ static constexpr mojom::Setting kMultiDeviceFeaturesSettings[] = {
+ mojom::Setting::kMultiDeviceOnOff,
+ mojom::Setting::kMessagesSetUp,
+ mojom::Setting::kMessagesOnOff,
+ mojom::Setting::kForgetPhone,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kMultiDeviceFeatures,
+ kMultiDeviceFeaturesSettings, generator);
+ generator->RegisterTopLevelAltSetting(mojom::Setting::kMultiDeviceOnOff);
+ // Note: Instant Tethering is part of the Network section, but it has an
+ // alternate setting within the MultiDevice section.
+ generator->RegisterNestedAltSetting(mojom::Setting::kInstantTetheringOnOff,
+ mojom::Subpage::kMultiDeviceFeatures);
+
+ // Smart Lock.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_EASY_UNLOCK_SECTION_TITLE, mojom::Subpage::kSmartLock,
+ mojom::Subpage::kMultiDeviceFeatures, mojom::SearchResultIcon::kLock,
+ mojom::SearchResultDefaultRank::kMedium, mojom::kSmartLockSubpagePath);
+ static constexpr mojom::Setting kSmartLockSettings[] = {
+ mojom::Setting::kSmartLockOnOff,
+ mojom::Setting::kSmartLockUnlockOrSignIn,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kSmartLock, kSmartLockSettings,
+ generator);
+ generator->RegisterNestedAltSetting(mojom::Setting::kSmartLockOnOff,
+ mojom::Subpage::kMultiDeviceFeatures);
+
+ // Nearby Share, registered regardless of the flag.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_NEARBY_SHARE_TITLE, mojom::Subpage::kNearbyShare,
+ mojom::SearchResultIcon::kNearbyShare,
+ mojom::SearchResultDefaultRank::kMedium, mojom::kNearbyShareSubpagePath);
+ static constexpr mojom::Setting kNearbyShareSettings[] = {
+ mojom::Setting::kNearbyShareOnOff,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kNearbyShare, kNearbyShareSettings,
+ generator);
+ generator->RegisterTopLevelAltSetting(mojom::Setting::kNearbyShareOnOff);
+}
+
void MultiDeviceSection::OnHostStatusChanged(
const multidevice_setup::MultiDeviceSetupClient::HostStatusWithDevice&
host_status_with_device) {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
if (IsOptedIn(host_status_with_device.first)) {
- registry()->RemoveSearchTags(GetMultiDeviceOptedOutSearchConcepts());
- registry()->AddSearchTags(GetMultiDeviceOptedInSearchConcepts());
+ updater.RemoveSearchTags(GetMultiDeviceOptedOutSearchConcepts());
+ updater.AddSearchTags(GetMultiDeviceOptedInSearchConcepts());
+ } else {
+ updater.RemoveSearchTags(GetMultiDeviceOptedInSearchConcepts());
+ updater.AddSearchTags(GetMultiDeviceOptedOutSearchConcepts());
+ }
+}
+
+void MultiDeviceSection::OnNearbySharingEnabledChanged() {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
+ if (pref_service_->GetBoolean(::prefs::kNearbySharingEnabledPrefName)) {
+ updater.RemoveSearchTags(GetNearbyShareOffSearchConcepts());
+ updater.AddSearchTags(GetNearbyShareOnSearchConcepts());
} else {
- registry()->RemoveSearchTags(GetMultiDeviceOptedInSearchConcepts());
- registry()->AddSearchTags(GetMultiDeviceOptedOutSearchConcepts());
+ updater.RemoveSearchTags(GetNearbyShareOnSearchConcepts());
+ updater.AddSearchTags(GetNearbyShareOffSearchConcepts());
}
}
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_section.h
index d35711a2c9d..2c608c9e03c 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/multidevice_section.h
@@ -7,6 +7,7 @@
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_section.h"
#include "chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client.h"
+#include "components/prefs/pref_change_registrar.h"
class PrefService;
@@ -43,15 +44,24 @@ class MultiDeviceSection
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
// multidevice_setup::MultiDeviceSetupClient::Observer:
void OnHostStatusChanged(
const multidevice_setup::MultiDeviceSetupClient::HostStatusWithDevice&
host_status_with_device) override;
+ // Nearby Share enabled pref change observer.
+ void OnNearbySharingEnabledChanged();
+
multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client_;
android_sms::AndroidSmsService* android_sms_service_;
PrefService* pref_service_;
+ PrefChangeRegistrar pref_change_registrar_;
};
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_identifier.h b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_identifier.h
new file mode 100644
index 00000000000..df287c3a928
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_identifier.h
@@ -0,0 +1,24 @@
+// Copyright 2020 The Chromium 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_OS_SETTINGS_IDENTIFIER_H_
+#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_OS_SETTINGS_IDENTIFIER_H_
+
+#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h"
+#include "chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom.h"
+
+namespace chromeos {
+namespace settings {
+
+// Uniquely identifies a settings item (section, subpage, or setting).
+union OsSettingsIdentifier {
+ mojom::Section section;
+ mojom::Subpage subpage;
+ mojom::Setting setting;
+};
+
+} // namespace settings
+} // namespace chromeos
+
+#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_OS_SETTINGS_IDENTIFIER_H_
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.cc
index ce568062640..95cd5692e5c 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.cc
@@ -7,6 +7,7 @@
#include "base/bind.h"
#include "base/feature_list.h"
#include "chrome/browser/chromeos/local_search_service/local_search_service.h"
+#include "chrome/browser/ui/webui/settings/chromeos/hierarchy.h"
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_handler.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h"
@@ -40,10 +41,12 @@ OsSettingsManager::OsSettingsManager(
arc_app_list_prefs,
identity_manager,
android_sms_service,
- printers_manager)) {
+ printers_manager)),
+ hierarchy_(std::make_unique<Hierarchy>(sections_.get())) {
if (base::FeatureList::IsEnabled(features::kNewOsSettingsSearch)) {
search_handler_ = std::make_unique<SearchHandler>(
- search_tag_registry_.get(), local_search_service);
+ search_tag_registry_.get(), sections_.get(), hierarchy_.get(),
+ local_search_service);
}
}
@@ -64,6 +67,7 @@ void OsSettingsManager::Shutdown() {
// Note: These must be deleted in the opposite order of their creation to
// prevent against UAF violations.
search_handler_.reset();
+ hierarchy_.reset();
sections_.reset();
search_tag_registry_.reset();
}
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.h b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.h
index b60dbcbd181..78a9008a482 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager.h
@@ -46,6 +46,7 @@ class MultiDeviceSetupClient;
namespace settings {
+class Hierarchy;
class OsSettingsSections;
class SearchHandler;
class SearchTagRegistry;
@@ -104,14 +105,17 @@ class OsSettingsManager : public KeyedService {
// Note: Returns null when the kNewOsSettingsSearch flag is disabled.
SearchHandler* search_handler() { return search_handler_.get(); }
+ const Hierarchy* hierarchy() const { return hierarchy_.get(); }
+
private:
- FRIEND_TEST_ALL_PREFIXES(OsSettingsManagerTest, Sections);
+ FRIEND_TEST_ALL_PREFIXES(OsSettingsManagerTest, Initialization);
// KeyedService:
void Shutdown() override;
std::unique_ptr<SearchTagRegistry> search_tag_registry_;
std::unique_ptr<OsSettingsSections> sections_;
+ std::unique_ptr<Hierarchy> hierarchy_;
std::unique_ptr<SearchHandler> search_handler_;
};
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc
index a238deaf5fb..71e5abc2b2f 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc
@@ -9,6 +9,7 @@
#include "chrome/browser/chromeos/local_search_service/local_search_service_factory.h"
#include "chrome/browser/chromeos/multidevice_setup/multidevice_setup_client_factory.h"
#include "chrome/browser/chromeos/printing/cups_printers_manager_factory.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
@@ -53,13 +54,23 @@ OsSettingsManagerFactory::~OsSettingsManagerFactory() = default;
KeyedService* OsSettingsManagerFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
Profile* profile = Profile::FromBrowserContext(context);
+
+ // Edge case: KerberosCredentialsManagerFactory::Get(profile) returns the
+ // instance associated with the primary profile, even if |profile| is not the
+ // primary profile, which can cause issues in multi-profile environments.
+ // Only call Get() if the profile is primary; see https://crbug.com/1103140.
+ KerberosCredentialsManager* kerberos_credentials_manager =
+ ProfileHelper::IsPrimaryProfile(profile)
+ ? KerberosCredentialsManagerFactory::Get(profile)
+ : nullptr;
+
return new OsSettingsManager(
profile,
local_search_service::LocalSearchServiceFactory::GetForProfile(profile),
multidevice_setup::MultiDeviceSetupClientFactory::GetForProfile(profile),
ProfileSyncServiceFactory::GetForProfile(profile),
SupervisedUserServiceFactory::GetForProfile(profile),
- KerberosCredentialsManagerFactory::Get(profile),
+ kerberos_credentials_manager,
ArcAppListPrefsFactory::GetForBrowserContext(profile),
IdentityManagerFactory::GetForProfile(profile),
android_sms::AndroidSmsServiceFactory::GetForBrowserContext(profile),
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc
index ec50ed54481..dd20db6da77 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc
@@ -4,9 +4,12 @@
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_manager.h"
+#include "base/metrics/histogram_base.h"
#include "base/no_destructor.h"
+#include "base/test/metrics/histogram_enum_reader.h"
#include "chrome/browser/ui/webui/settings/chromeos/constants/constants_util.h"
#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h"
+#include "chrome/browser/ui/webui/settings/chromeos/hierarchy.h"
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.h"
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h"
#include "chrome/test/base/testing_browser_process.h"
@@ -40,12 +43,55 @@ class OsSettingsManagerTest : public testing::Test {
OsSettingsManager* manager_;
};
-TEST_F(OsSettingsManagerTest, Sections) {
- // For each mojom::Section value, there should be an associated
- // OsSettingsSection class registered.
+TEST_F(OsSettingsManagerTest, Initialization) {
+ base::Optional<base::HistogramEnumEntryMap> sections_enum_entry_map =
+ base::ReadEnumFromEnumsXml("OsSettingsSection");
+ ASSERT_TRUE(sections_enum_entry_map);
for (const auto& section : constants::AllSections()) {
+ // For each mojom::Section value, there should be an associated
+ // OsSettingsSection class registered.
EXPECT_TRUE(manager_->sections_->GetSection(section))
<< "No OsSettingsSection instance created for " << section << ".";
+
+ // Each mojom::Section should be registered in the hierarchy.
+ const Hierarchy::SectionMetadata& metadata =
+ manager_->hierarchy_->GetSectionMetadata(section);
+
+ // Only the "About Chrome OS" section contains only a link to a subpage.
+ EXPECT_EQ(metadata.only_contains_link_to_subpage,
+ section == mojom::Section::kAboutChromeOs);
+
+ EXPECT_TRUE(
+ base::Contains(*sections_enum_entry_map, static_cast<int32_t>(section)))
+ << "Missing OsSettingsSection enums.xml entry for " << section;
+ }
+
+ base::Optional<base::HistogramEnumEntryMap> subpages_enum_entry_map =
+ base::ReadEnumFromEnumsXml("OsSettingsSubpage");
+ ASSERT_TRUE(subpages_enum_entry_map);
+ for (const auto& subpage : constants::AllSubpages()) {
+ // Each mojom::Subpage should be registered in the hierarchy. Note that
+ // GetSubpageMetadata() internally CHECK()s that the metadata exists before
+ // returning it.
+ manager_->hierarchy_->GetSubpageMetadata(subpage);
+
+ EXPECT_TRUE(
+ base::Contains(*subpages_enum_entry_map, static_cast<int32_t>(subpage)))
+ << "Missing OsSettingsSubpage enums.xml entry for " << subpage;
+ }
+
+ base::Optional<base::HistogramEnumEntryMap> settings_enum_entry_map =
+ base::ReadEnumFromEnumsXml("OsSetting");
+ ASSERT_TRUE(settings_enum_entry_map);
+ for (const auto& setting : constants::AllSettings()) {
+ // Each mojom::Setting should be registered in the hierarchy. Note that
+ // GetSettingMetadata() internally CHECK()s that the metadata exists before
+ // returning it.
+ manager_->hierarchy_->GetSettingMetadata(setting);
+
+ EXPECT_TRUE(
+ base::Contains(*settings_enum_entry_map, static_cast<int32_t>(setting)))
+ << "Missing OsSetting enums.xml entry for " << setting;
}
}
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_section.cc
index af60b362b5f..02bdc340841 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_section.cc
@@ -7,6 +7,8 @@
#include "base/check.h"
#include "base/strings/utf_string_conversions.h"
#include "base/system/sys_info.h"
+#include "chrome/grit/generated_resources.h"
+#include "ui/base/l10n/l10n_util.h"
namespace chromeos {
namespace settings {
@@ -18,6 +20,15 @@ base::string16 OsSettingsSection::GetHelpUrlWithBoard(
"&b=" + base::SysInfo::GetLsbReleaseBoard());
}
+// static
+void OsSettingsSection::RegisterNestedSettingBulk(
+ mojom::Subpage subpage,
+ const base::span<const mojom::Setting>& settings,
+ HierarchyGenerator* generator) {
+ for (const auto& setting : settings)
+ generator->RegisterNestedSetting(setting, subpage);
+}
+
OsSettingsSection::~OsSettingsSection() = default;
OsSettingsSection::OsSettingsSection(Profile* profile,
@@ -27,5 +38,33 @@ OsSettingsSection::OsSettingsSection(Profile* profile,
DCHECK(search_tag_registry);
}
+OsSettingsSection::OsSettingsSection() = default;
+
+std::string OsSettingsSection::ModifySearchResultUrl(
+ mojom::SearchResultType type,
+ OsSettingsIdentifier id,
+ const std::string& url_to_modify) const {
+ // Default case for static URLs which do not need to be modified.
+ return url_to_modify;
+}
+
+mojom::SearchResultPtr OsSettingsSection::GenerateSectionSearchResult(
+ double relevance_score) const {
+ return mojom::SearchResult::New(
+ /*result_text=*/l10n_util::GetStringUTF16(GetSectionNameMessageId()),
+ /*canonical_result_text=*/
+ l10n_util::GetStringUTF16(GetSectionNameMessageId()),
+ ModifySearchResultUrl(mojom::SearchResultType::kSection,
+ {.section = GetSection()}, GetSectionPath()),
+ GetSectionIcon(), relevance_score,
+ std::vector<base::string16>{
+ l10n_util::GetStringUTF16(IDS_INTERNAL_APP_SETTINGS),
+ l10n_util::GetStringUTF16(GetSectionNameMessageId())},
+ mojom::SearchResultDefaultRank::kMedium,
+ /*was_generated_from_text_match=*/false,
+ mojom::SearchResultType::kSection,
+ mojom::SearchResultIdentifier::NewSection(GetSection()));
+}
+
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_section.h
index 3e8b5b23bcd..b4406ff4c3e 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_section.h
@@ -8,7 +8,11 @@
#include <string>
#include <vector>
+#include "base/containers/span.h"
#include "base/strings/string16.h"
+#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h"
+#include "chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom.h"
+#include "chrome/browser/ui/webui/settings/chromeos/search/search.mojom.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_concept.h"
class Profile;
@@ -38,6 +42,57 @@ class SearchTagRegistry;
// (i.e., browser to JS IPC mechanisms) to the page.
class OsSettingsSection {
public:
+ // Used to construct a hierarchy of this section (i.e., which settings and
+ // subpages are part of this section). See RegisterHierarchy() below.
+ //
+ // Note on primary vs. alternate setting locations: Some settings are located
+ // in multiple spots of settings. For example, the Wi-Fi on/off toggle appears
+ // in both the top-level Network section as well as the Wi-Fi subpage. In
+ // cases like this, we consider the "primary" location as the more-targeted
+ // one - in this example, the Wi-Fi subpage is the primary location of the
+ // toggle since it is more specific to Wi-Fi, and the alternate location is
+ // the one embedded in the Network section.
+ class HierarchyGenerator {
+ public:
+ virtual ~HierarchyGenerator() = default;
+
+ // Registers a subpage whose parent is this section.
+ virtual void RegisterTopLevelSubpage(
+ int name_message_id,
+ mojom::Subpage subpage,
+ mojom::SearchResultIcon icon,
+ mojom::SearchResultDefaultRank default_rank,
+ const std::string& url_path_with_parameters) = 0;
+
+ // Registers a subpage whose paernt is another subpage in this section.
+ virtual void RegisterNestedSubpage(
+ int name_message_id,
+ mojom::Subpage subpage,
+ mojom::Subpage parent_subpage,
+ mojom::SearchResultIcon icon,
+ mojom::SearchResultDefaultRank default_rank,
+ const std::string& url_path_with_parameters) = 0;
+
+ // Registers a setting embedded directly in the section (i.e., not within a
+ // subpage). This functions is for primary locations (see above).
+ virtual void RegisterTopLevelSetting(mojom::Setting setting) = 0;
+
+ // Registers a setting embedded within a subpage in this section. This
+ // function is for primary locations (see above).
+ virtual void RegisterNestedSetting(mojom::Setting setting,
+ mojom::Subpage subpage) = 0;
+
+ // Register an alternate location for a setting embedded directly in the
+ // section (i.e., not within a subpage). This function is for alternate
+ // locations (see above).
+ virtual void RegisterTopLevelAltSetting(mojom::Setting setting) = 0;
+
+ // Registers a setting embedded within a subpage in this section. This
+ // function is for alternate locations (see above).
+ virtual void RegisterNestedAltSetting(mojom::Setting setting,
+ mojom::Subpage subpage) = 0;
+ };
+
virtual ~OsSettingsSection();
OsSettingsSection(const OsSettingsSection& other) = delete;
@@ -51,12 +106,51 @@ class OsSettingsSection {
// derived type requires one or more handlers for this section.
virtual void AddHandlers(content::WebUI* web_ui) {}
+ // Provides the message ID for the name of this section.
+ virtual int GetSectionNameMessageId() const = 0;
+
+ // Provides the Section enum for this section.
+ virtual mojom::Section GetSection() const = 0;
+
+ // Provides the icon for this section.
+ virtual mojom::SearchResultIcon GetSectionIcon() const = 0;
+
+ // Provides the path for this section.
+ virtual std::string GetSectionPath() const = 0;
+
+ // Registers the subpages and/or settings which reside in this section.
+ virtual void RegisterHierarchy(HierarchyGenerator* generator) const = 0;
+
+ // Modifies a URL to be used by settings search. Some URLs require dynamic
+ // content (e.g., network detail settings use the GUID of the network as a URL
+ // parameter to route to details for a specific network). By default, this
+ // function simply returns |url_to_modify|, which provides functionality for
+ // static URLs.
+ virtual std::string ModifySearchResultUrl(
+ mojom::SearchResultType type,
+ OsSettingsIdentifier id,
+ const std::string& url_to_modify) const;
+
+ // Generates a search result corresponding to this section. |relevance_score|
+ // must be passed by the client, since this result is being created manually
+ // instead of via query matching.
+ mojom::SearchResultPtr GenerateSectionSearchResult(
+ double relevance_score) const;
+
protected:
static base::string16 GetHelpUrlWithBoard(const std::string& original_url);
+ static void RegisterNestedSettingBulk(
+ mojom::Subpage,
+ const base::span<const mojom::Setting>& settings,
+ HierarchyGenerator* generator);
OsSettingsSection(Profile* profile, SearchTagRegistry* search_tag_registry);
+ // Used by tests.
+ OsSettingsSection();
+
Profile* profile() { return profile_; }
+ const Profile* profile() const { return profile_; }
SearchTagRegistry* registry() { return search_tag_registry_; }
private:
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_sections.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_sections.cc
index 6239b2466c5..334128e8509 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_sections.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_sections.cc
@@ -4,6 +4,7 @@
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h"
+#include "build/branding_buildflags.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/settings/chromeos/about_section.h"
#include "chrome/browser/ui/webui/settings/chromeos/accessibility_section.h"
@@ -125,16 +126,26 @@ OsSettingsSections::OsSettingsSections(
sections_map_[mojom::Section::kReset] = reset_section.get();
sections_.push_back(std::move(reset_section));
+#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
+ auto about_section = std::make_unique<AboutSection>(
+ profile, search_tag_registry, profile->GetPrefs());
+#else
auto about_section =
std::make_unique<AboutSection>(profile, search_tag_registry);
+#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
sections_map_[mojom::Section::kAboutChromeOs] = about_section.get();
sections_.push_back(std::move(about_section));
}
+OsSettingsSections::OsSettingsSections() = default;
+
OsSettingsSections::~OsSettingsSections() = default;
-OsSettingsSection* OsSettingsSections::GetSection(mojom::Section section) {
- return sections_map_[section];
+const OsSettingsSection* OsSettingsSections::GetSection(
+ mojom::Section section) const {
+ const auto it = sections_map_.find(section);
+ CHECK(it != sections_map_.end());
+ return it->second;
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h
index 44ddc68a34d..d1526481464 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h
@@ -54,15 +54,18 @@ class OsSettingsSections {
CupsPrintersManager* printers_manager);
OsSettingsSections(const OsSettingsSections& other) = delete;
OsSettingsSections& operator=(const OsSettingsSections& other) = delete;
- ~OsSettingsSections();
+ virtual ~OsSettingsSections();
- OsSettingsSection* GetSection(mojom::Section section);
+ const OsSettingsSection* GetSection(mojom::Section section) const;
std::vector<std::unique_ptr<OsSettingsSection>>& sections() {
return sections_;
}
- private:
+ protected:
+ // Used by tests.
+ OsSettingsSections();
+
std::unordered_map<mojom::Section, OsSettingsSection*> sections_map_;
std::vector<std::unique_ptr<OsSettingsSection>> sections_;
};
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 97f2eeab8a9..8bddd59808d 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
@@ -68,6 +68,10 @@ 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("chromeos/os_settings_v3.html",
+ IDR_OS_SETTINGS_OS_SETTINGS_V3_HTML);
+ html_source->AddResourcePath("chromeos/os_settings.js",
+ IDR_OS_SETTINGS_SETTINGS_ROLLUP_JS);
#else
webui::SetupWebUIDataSource(
html_source,
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc
index 273e9456b69..fb9df81bbf4 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/parental_controls_handler.cc
@@ -14,10 +14,10 @@
#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 "chromeos/constants/chromeos_features.h"
+#include "components/services/app_service/public/cpp/app_registry_cache.h"
+#include "components/services/app_service/public/cpp/app_update.h"
+#include "components/services/app_service/public/mojom/types.mojom.h"
#include "ui/base/page_transition_types.h"
#include "ui/base/window_open_disposition.h"
#include "ui/display/types/display_constants.h"
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/people_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/people_section.cc
index 45486f9eed4..e5bb33b3244 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/people_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/people_section.cc
@@ -47,6 +47,7 @@
#include "components/user_manager/user_manager.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/chromeos/resources/grit/ui_chromeos_resources.h"
@@ -68,7 +69,9 @@ const std::vector<SearchConcept>& GetPeopleSearchConcepts() {
mojom::SearchResultIcon::kLock,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kChangeAuthPin}},
+ {.setting = mojom::Setting::kChangeAuthPin},
+ {IDS_OS_SETTINGS_TAG_LOCK_SCREEN_PIN_OR_PASSWORD_ALT1,
+ SearchConcept::kAltTagEnd}},
{IDS_OS_SETTINGS_TAG_USERNAMES_AND_PHOTOS,
mojom::kManageOtherPeopleSubpagePath,
mojom::SearchResultIcon::kAvatar,
@@ -110,12 +113,6 @@ const std::vector<SearchConcept>& GetPeopleSearchConcepts() {
{.setting = mojom::Setting::kLockScreen},
{IDS_OS_SETTINGS_TAG_LOCK_SCREEN_WHEN_WAKING_ALT1,
SearchConcept::kAltTagEnd}},
- {IDS_OS_SETTINGS_TAG_SYNC,
- mojom::kSyncSubpagePath,
- mojom::SearchResultIcon::kSync,
- mojom::SearchResultDefaultRank::kMedium,
- mojom::SearchResultType::kSubpage,
- {.subpage = mojom::Subpage::kSync}},
{IDS_OS_SETTINGS_TAG_PEOPLE_ACCOUNTS_REMOVE,
mojom::kMyAccountsSubpagePath,
mojom::SearchResultIcon::kAvatar,
@@ -145,27 +142,83 @@ const std::vector<SearchConcept>& GetPeopleSearchConcepts() {
return *tags;
}
-const std::vector<SearchConcept>& GetSyncOnSearchConcepts() {
+const std::vector<SearchConcept>& GetNonSplitSyncSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_SYNC_AND_GOOGLE_SERVICES,
+ mojom::kSyncDeprecatedSubpagePath,
+ mojom::SearchResultIcon::kSync,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSubpage,
+ {.subpage = mojom::Subpage::kSyncDeprecated}},
+ {IDS_OS_SETTINGS_TAG_SYNC_MANAGEMENT,
+ mojom::kSyncDeprecatedAdvancedSubpagePath,
+ mojom::SearchResultIcon::kSync,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSubpage,
+ {.subpage = mojom::Subpage::kSyncDeprecatedAdvanced}},
+ {IDS_OS_SETTINGS_TAG_SYNC_ENCRYPTION_OPTIONS,
+ mojom::kSyncDeprecatedSubpagePath,
+ mojom::SearchResultIcon::kSync,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kNonSplitSyncEncryptionOptions},
+ {IDS_OS_SETTINGS_TAG_SYNC_ENCRYPTION_OPTIONS_ALT1,
+ SearchConcept::kAltTagEnd}},
+ {IDS_OS_SETTINGS_TAG_AUTOCOMPLETE_SEARCHES_AND_URLS,
+ mojom::kSyncDeprecatedSubpagePath,
+ mojom::SearchResultIcon::kSync,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kAutocompleteSearchesAndUrls}},
+ {IDS_OS_SETTINGS_TAG_MAKE_SEARCHES_AND_BROWSER_BETTER,
+ mojom::kSyncDeprecatedSubpagePath,
+ mojom::SearchResultIcon::kSync,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kMakeSearchesAndBrowsingBetter}},
+ {IDS_OS_SETTINGS_TAG_GOOGLE_DRIVE_SEARCH_SUGGESTIONS,
+ mojom::kSyncDeprecatedSubpagePath,
+ mojom::SearchResultIcon::kSync,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kGoogleDriveSearchSuggestions}},
+ });
+ return *tags;
+}
+
+const std::vector<SearchConcept>& GetSplitSyncSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_SYNC,
+ mojom::kSyncSubpagePath,
+ mojom::SearchResultIcon::kSync,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultType::kSubpage,
+ {.subpage = mojom::Subpage::kSync}},
+ });
+ return *tags;
+}
+
+const std::vector<SearchConcept>& GetSplitSyncOnSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_SYNC_TURN_OFF,
mojom::kSyncSubpagePath,
mojom::SearchResultIcon::kSync,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kSyncOnOff},
+ {.setting = mojom::Setting::kSplitSyncOnOff},
{IDS_OS_SETTINGS_TAG_SYNC_TURN_OFF_ALT1, SearchConcept::kAltTagEnd}},
});
return *tags;
}
-const std::vector<SearchConcept>& GetSyncOffSearchConcepts() {
+const std::vector<SearchConcept>& GetSplitSyncOffSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_SYNC_TURN_ON,
mojom::kSyncSubpagePath,
mojom::SearchResultIcon::kSync,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kSyncOnOff},
+ {.setting = mojom::Setting::kSplitSyncOnOff},
{IDS_OS_SETTINGS_TAG_SYNC_TURN_ON_ALT1, SearchConcept::kAltTagEnd}},
});
return *tags;
@@ -176,25 +229,25 @@ const std::vector<SearchConcept>& GetKerberosSearchConcepts() {
{IDS_OS_SETTINGS_TAG_KERBEROS_ADD,
mojom::kKerberosSubpagePath,
mojom::SearchResultIcon::kAvatar,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kAddKerberosTicket}},
{IDS_OS_SETTINGS_TAG_KERBEROS_REMOVE,
mojom::kKerberosSubpagePath,
mojom::SearchResultIcon::kAvatar,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kRemoveKerberosTicket}},
{IDS_OS_SETTINGS_TAG_KERBEROS,
mojom::kKerberosSubpagePath,
mojom::SearchResultIcon::kAvatar,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kKerberos}},
{IDS_OS_SETTINGS_TAG_KERBEROS_ACTIVE,
mojom::kKerberosSubpagePath,
mojom::SearchResultIcon::kAvatar,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kSetActiveKerberosTicket}},
});
@@ -204,19 +257,19 @@ const std::vector<SearchConcept>& GetKerberosSearchConcepts() {
const std::vector<SearchConcept>& GetFingerprintSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_FINGERPRINT_REMOVE,
- mojom::kFingerprintSubpathPath,
+ mojom::kFingerprintSubpagePath,
mojom::SearchResultIcon::kFingerprint,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kRemoveFingerprint}},
{IDS_OS_SETTINGS_TAG_FINGERPRINT_ADD,
- mojom::kFingerprintSubpathPath,
+ mojom::kFingerprintSubpagePath,
mojom::SearchResultIcon::kFingerprint,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kAddFingerprint}},
{IDS_OS_SETTINGS_TAG_FINGERPRINT,
- mojom::kFingerprintSubpathPath,
+ mojom::kFingerprintSubpagePath,
mojom::SearchResultIcon::kFingerprint,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
@@ -243,7 +296,11 @@ void AddAccountManagerPageStrings(content::WebUIDataSource* html_source) {
static constexpr webui::LocalizedString kLocalizedStrings[] = {
{"accountManagerDescription", IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION},
{"accountManagerChildDescription",
- IDS_SETTINGS_ACCOUNT_MANAGER_CHILD_DESCRIPTION_2},
+ IDS_SETTINGS_ACCOUNT_MANAGER_CHILD_DESCRIPTION},
+ {"accountManagerChildFirstMessage",
+ IDS_SETTINGS_ACCOUNT_MANAGER_CHILD_FIRST_MESSAGE},
+ {"accountManagerChildSecondMessage",
+ IDS_SETTINGS_ACCOUNT_MANAGER_CHILD_SECOND_MESSAGE},
{"accountListHeader", IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER},
{"accountManagerPrimaryAccountTooltip",
IDS_SETTINGS_ACCOUNT_MANAGER_PRIMARY_ACCOUNT_TOOLTIP},
@@ -431,7 +488,8 @@ void AddFingerprintStrings(content::WebUIDataSource* html_source,
// lottie animations, this update has to be performed manually. As the usage
// increases, set this as the default so manual override is no longer
// required.
- html_source->OverrideContentSecurityPolicyWorkerSrc(
+ html_source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::WorkerSrc,
"worker-src blob: 'self';");
html_source->AddResourcePath("finger_print.json",
IDR_LOGIN_FINGER_PRINT_TABLET_ANIMATION);
@@ -531,8 +589,8 @@ void AddSyncControlsStrings(content::WebUIDataSource* html_source) {
html_source->AddBoolean("splitSettingsSyncEnabled",
chromeos::features::IsSplitSettingsSyncEnabled());
- html_source->AddBoolean("splitSyncConsent",
- chromeos::features::IsSplitSyncConsentEnabled());
+ html_source->AddBoolean("useBrowserSyncConsent",
+ chromeos::features::ShouldUseBrowserSyncConsent());
html_source->AddBoolean(
"syncSetupFriendlySettings",
base::FeatureList::IsEnabled(::features::kSyncSetupFriendlySettings));
@@ -581,6 +639,7 @@ void AddParentalControlStrings(content::WebUIDataSource* html_source,
bool is_child = user_manager::UserManager::Get()->IsLoggedInAsChildUser();
html_source->AddBoolean("isChild", is_child);
+ base::string16 tooltip;
if (is_child) {
std::string custodian = supervised_user_service->GetCustodianName();
std::string second_custodian =
@@ -596,9 +655,10 @@ void AddParentalControlStrings(content::WebUIDataSource* html_source,
IDS_SETTINGS_ACCOUNT_MANAGER_CHILD_MANAGED_BY_TWO_PARENTS_TOOLTIP,
base::UTF8ToUTF16(custodian), base::UTF8ToUTF16(second_custodian));
}
- html_source->AddString("accountManagerPrimaryAccountChildManagedTooltip",
- child_managed_tooltip);
+ tooltip = child_managed_tooltip;
}
+ html_source->AddString("accountManagerPrimaryAccountChildManagedTooltip",
+ tooltip);
}
} // namespace
@@ -621,7 +681,8 @@ PeopleSection::PeopleSection(
if (features::IsGuestModeActive())
return;
- registry()->AddSearchTags(GetPeopleSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetPeopleSearchConcepts());
if (kerberos_credentials_manager_) {
// Kerberos search tags are added/removed dynamically.
@@ -629,28 +690,34 @@ PeopleSection::PeopleSection(
OnKerberosEnabledStateChanged();
}
- if (sync_service_ && chromeos::features::IsSplitSettingsSyncEnabled()) {
- // Sync search tags are added/removed dynamically.
- sync_service_->AddObserver(this);
- OnStateChanged(sync_service_);
+ if (chromeos::features::IsSplitSettingsSyncEnabled()) {
+ if (sync_service_) {
+ updater.AddSearchTags(GetSplitSyncSearchConcepts());
+
+ // Sync search tags are added/removed dynamically.
+ sync_service_->AddObserver(this);
+ OnStateChanged(sync_service_);
+ }
+ } else {
+ updater.AddSearchTags(GetNonSplitSyncSearchConcepts());
}
// Parental control search tags are added if necessary and do not update
// dynamically during a user session.
if (features::ShouldShowParentalControlSettings(profile))
- registry()->AddSearchTags(GetParentalSearchConcepts());
+ updater.AddSearchTags(GetParentalSearchConcepts());
// Fingerprint search tags are added if necessary and do not update
// dynamically during a user session.
if (AreFingerprintSettingsAllowed())
- registry()->AddSearchTags(GetFingerprintSearchConcepts());
+ updater.AddSearchTags(GetFingerprintSearchConcepts());
}
PeopleSection::~PeopleSection() {
if (kerberos_credentials_manager_)
kerberos_credentials_manager_->RemoveObserver(this);
- if (sync_service_ && chromeos::features::IsSplitSettingsSyncEnabled())
+ if (chromeos::features::IsSplitSettingsSyncEnabled() && sync_service_)
sync_service_->RemoveObserver(this);
}
@@ -678,7 +745,7 @@ void PeopleSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
html_source->AddBoolean("isAccountManagerEnabled",
chromeos::IsAccountManagerAvailable(profile()));
- if (chromeos::features::IsSplitSyncConsentEnabled()) {
+ if (chromeos::features::ShouldUseBrowserSyncConsent()) {
static constexpr webui::LocalizedString kTurnOffStrings[] = {
{"syncDisconnect", IDS_SETTINGS_PEOPLE_SYNC_TURN_OFF},
{"syncDisconnectTitle",
@@ -785,24 +852,144 @@ void PeopleSection::AddHandlers(content::WebUI* web_ui) {
}
}
+int PeopleSection::GetSectionNameMessageId() const {
+ return IDS_OS_SETTINGS_PEOPLE;
+}
+
+mojom::Section PeopleSection::GetSection() const {
+ return mojom::Section::kPeople;
+}
+
+mojom::SearchResultIcon PeopleSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kAvatar;
+}
+
+std::string PeopleSection::GetSectionPath() const {
+ return mojom::kPeopleSectionPath;
+}
+
+void PeopleSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSetting(mojom::Setting::kSetUpParentalControls);
+
+ // My accounts.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_ACCOUNT_MANAGER_PAGE_TITLE, mojom::Subpage::kMyAccounts,
+ mojom::SearchResultIcon::kAvatar, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kMyAccountsSubpagePath);
+ static constexpr mojom::Setting kMyAccountsSettings[] = {
+ mojom::Setting::kAddAccount,
+ mojom::Setting::kRemoveAccount,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kMyAccounts, kMyAccountsSettings,
+ generator);
+
+ // Combined browser/OS sync.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_SYNC_SYNC_AND_NON_PERSONALIZED_SERVICES,
+ mojom::Subpage::kSyncDeprecated, mojom::SearchResultIcon::kSync,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kSyncDeprecatedSubpagePath);
+ static constexpr mojom::Setting kSyncDeprecatedSettings[] = {
+ mojom::Setting::kNonSplitSyncEncryptionOptions,
+ mojom::Setting::kAutocompleteSearchesAndUrls,
+ mojom::Setting::kMakeSearchesAndBrowsingBetter,
+ mojom::Setting::kGoogleDriveSearchSuggestions,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kSyncDeprecated,
+ kSyncDeprecatedSettings, generator);
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_SYNC_ADVANCED_PAGE_TITLE,
+ mojom::Subpage::kSyncDeprecatedAdvanced, mojom::Subpage::kSyncDeprecated,
+ mojom::SearchResultIcon::kSync, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kSyncDeprecatedAdvancedSubpagePath);
+
+ // OS sync.
+ generator->RegisterTopLevelSubpage(
+ IDS_OS_SETTINGS_SYNC_PAGE_TITLE, mojom::Subpage::kSync,
+ mojom::SearchResultIcon::kSync, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kSyncSubpagePath);
+ generator->RegisterNestedSetting(mojom::Setting::kSplitSyncOnOff,
+ mojom::Subpage::kSync);
+
+ // Security and sign-in.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_PEOPLE_LOCK_SCREEN_TITLE_LOGIN_LOCK,
+ mojom::Subpage::kSecurityAndSignIn, mojom::SearchResultIcon::kLock,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kSecurityAndSignInSubpagePath);
+ static constexpr mojom::Setting kSecurityAndSignInSettings[] = {
+ mojom::Setting::kLockScreen,
+ mojom::Setting::kChangeAuthPin,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kSecurityAndSignIn,
+ kSecurityAndSignInSettings, generator);
+
+ // Fingerprint.
+ generator->RegisterNestedSubpage(
+ IDS_SETTINGS_PEOPLE_LOCK_SCREEN_FINGERPRINT_SUBPAGE_TITLE,
+ mojom::Subpage::kFingerprint, mojom::Subpage::kSecurityAndSignIn,
+ mojom::SearchResultIcon::kFingerprint,
+ mojom::SearchResultDefaultRank::kMedium, mojom::kFingerprintSubpagePath);
+ static constexpr mojom::Setting kFingerprintSettings[] = {
+ mojom::Setting::kAddFingerprint,
+ mojom::Setting::kRemoveFingerprint,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kFingerprint, kFingerprintSettings,
+ generator);
+
+ // Manage other people.
+ generator->RegisterTopLevelSubpage(IDS_SETTINGS_PEOPLE_MANAGE_OTHER_PEOPLE,
+ mojom::Subpage::kManageOtherPeople,
+ mojom::SearchResultIcon::kAvatar,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kManageOtherPeopleSubpagePath);
+ static constexpr mojom::Setting kManageOtherPeopleSettings[] = {
+ mojom::Setting::kGuestBrowsing,
+ mojom::Setting::kShowUsernamesAndPhotosAtSignIn,
+ mojom::Setting::kRestrictSignIn,
+ mojom::Setting::kAddToUserWhitelist,
+ mojom::Setting::kRemoveFromUserWhitelist,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kManageOtherPeople,
+ kManageOtherPeopleSettings, generator);
+
+ // Kerberos.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_KERBEROS_ACCOUNTS_PAGE_TITLE, mojom::Subpage::kKerberos,
+ mojom::SearchResultIcon::kAvatar, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kKerberosSubpagePath);
+ static constexpr mojom::Setting kKerberosSettings[] = {
+ mojom::Setting::kAddKerberosTicket,
+ mojom::Setting::kRemoveKerberosTicket,
+ mojom::Setting::kSetActiveKerberosTicket,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kKerberos, kKerberosSettings,
+ generator);
+}
+
void PeopleSection::OnStateChanged(syncer::SyncService* sync_service) {
DCHECK(chromeos::features::IsSplitSettingsSyncEnabled());
DCHECK_EQ(sync_service, sync_service_);
+
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
if (sync_service_->IsEngineInitialized() &&
sync_service_->GetUserSettings()->IsOsSyncFeatureEnabled()) {
- registry()->AddSearchTags(GetSyncOnSearchConcepts());
- registry()->RemoveSearchTags(GetSyncOffSearchConcepts());
+ updater.AddSearchTags(GetSplitSyncOnSearchConcepts());
+ updater.RemoveSearchTags(GetSplitSyncOffSearchConcepts());
} else {
- registry()->RemoveSearchTags(GetSyncOnSearchConcepts());
- registry()->AddSearchTags(GetSyncOffSearchConcepts());
+ updater.RemoveSearchTags(GetSplitSyncOnSearchConcepts());
+ updater.AddSearchTags(GetSplitSyncOffSearchConcepts());
}
}
void PeopleSection::OnKerberosEnabledStateChanged() {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
if (kerberos_credentials_manager_->IsKerberosEnabled())
- registry()->AddSearchTags(GetKerberosSearchConcepts());
+ updater.AddSearchTags(GetKerberosSearchConcepts());
else
- registry()->RemoveSearchTags(GetKerberosSearchConcepts());
+ updater.RemoveSearchTags(GetKerberosSearchConcepts());
}
void PeopleSection::AddKerberosAccountsPageStrings(
@@ -833,8 +1020,10 @@ void PeopleSection::AddKerberosAccountsPageStrings(
// 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",
- kerberos_credentials_manager_->IsKerberosEnabled());
+ html_source->AddBoolean(
+ "isKerberosEnabled",
+ kerberos_credentials_manager_ != nullptr &&
+ kerberos_credentials_manager_->IsKerberosEnabled());
PrefService* local_state = g_browser_process->local_state();
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/people_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/people_section.h
index d10c6805d22..51e8a4b3ea8 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/people_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/people_section.h
@@ -54,6 +54,11 @@ class PeopleSection : public OsSettingsSection,
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
// syncer::SyncServiceObserver:
void OnStateChanged(syncer::SyncService* sync_service) override;
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/personalization_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/personalization_section.cc
index e7b9d760bc5..dfbbaf17853 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/personalization_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/personalization_section.cc
@@ -48,7 +48,7 @@ const std::vector<SearchConcept>& GetPersonalizationSearchConcepts() {
{IDS_OS_SETTINGS_TAG_CHANGE_DEVICE_ACCOUNT_IMAGE,
mojom::kChangePictureSubpagePath,
mojom::SearchResultIcon::kAvatar,
- mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kChangePicture},
{IDS_OS_SETTINGS_TAG_CHANGE_DEVICE_ACCOUNT_IMAGE_ALT1,
@@ -60,6 +60,7 @@ const std::vector<SearchConcept>& GetPersonalizationSearchConcepts() {
return *tags;
}
+// TODO(b/159766700): Add search concepts for |kAmbientModePhotosSubpagePath|.
const std::vector<SearchConcept>& GetAmbientModeSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_AMBIENT_MODE,
@@ -122,10 +123,11 @@ PersonalizationSection::PersonalizationSection(
if (features::IsGuestModeActive())
return;
- registry()->AddSearchTags(GetPersonalizationSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetPersonalizationSearchConcepts());
if (IsAmbientModeAllowed()) {
- registry()->AddSearchTags(GetAmbientModeSearchConcepts());
+ updater.AddSearchTags(GetAmbientModeSearchConcepts());
pref_change_registrar_.Init(pref_service_);
pref_change_registrar_.Add(
@@ -197,13 +199,69 @@ void PersonalizationSection::AddHandlers(content::WebUI* web_ui) {
}
}
+int PersonalizationSection::GetSectionNameMessageId() const {
+ return IDS_OS_SETTINGS_PERSONALIZATION;
+}
+
+mojom::Section PersonalizationSection::GetSection() const {
+ return mojom::Section::kPersonalization;
+}
+
+mojom::SearchResultIcon PersonalizationSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kPaintbrush;
+}
+
+std::string PersonalizationSection::GetSectionPath() const {
+ return mojom::kPersonalizationSectionPath;
+}
+
+void PersonalizationSection::RegisterHierarchy(
+ HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSetting(mojom::Setting::kOpenWallpaper);
+
+ // Change picture.
+ generator->RegisterTopLevelSubpage(
+ IDS_OS_SETTINGS_CHANGE_PICTURE_TITLE, mojom::Subpage::kChangePicture,
+ mojom::SearchResultIcon::kAvatar, mojom::SearchResultDefaultRank::kMedium,
+ mojom::kChangePictureSubpagePath);
+ generator->RegisterNestedSetting(mojom::Setting::kChangeDeviceAccountImage,
+ mojom::Subpage::kChangePicture);
+
+ // Ambient mode.
+ generator->RegisterTopLevelSubpage(
+ IDS_OS_SETTINGS_AMBIENT_MODE_TITLE, mojom::Subpage::kAmbientMode,
+ mojom::SearchResultIcon::kWallpaper,
+ mojom::SearchResultDefaultRank::kMedium, mojom::kAmbientModeSubpagePath);
+ static constexpr mojom::Setting kAmbientModeSettings[] = {
+ mojom::Setting::kAmbientModeOnOff,
+ mojom::Setting::kAmbientModeSource,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kAmbientMode, kAmbientModeSettings,
+ generator);
+
+ // Note: The subpage name in the UI is updated dynamically based on the topic
+ // source.
+ // TODO(b/159766700): Create a string for the page title and strings for the
+ // search.
+ generator->RegisterNestedSubpage(
+ IDS_OS_SETTINGS_AMBIENT_MODE_TITLE, mojom::Subpage::kAmbientModePhotos,
+ mojom::Subpage::kAmbientMode, mojom::SearchResultIcon::kWallpaper,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kAmbientModePhotosSubpagePath);
+ generator->RegisterNestedSetting(
+ mojom::Setting::kAmbientModeUpdatePhotosContainers,
+ mojom::Subpage::kAmbientModePhotos);
+}
+
void PersonalizationSection::OnAmbientModeEnabledStateChanged() {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
if (pref_service_->GetBoolean(ash::ambient::prefs::kAmbientModeEnabled)) {
- registry()->AddSearchTags(GetAmbientModeOnSearchConcepts());
- registry()->RemoveSearchTags(GetAmbientModeOffSearchConcepts());
+ updater.AddSearchTags(GetAmbientModeOnSearchConcepts());
+ updater.RemoveSearchTags(GetAmbientModeOffSearchConcepts());
} else {
- registry()->RemoveSearchTags(GetAmbientModeOnSearchConcepts());
- registry()->AddSearchTags(GetAmbientModeOffSearchConcepts());
+ updater.RemoveSearchTags(GetAmbientModeOnSearchConcepts());
+ updater.AddSearchTags(GetAmbientModeOffSearchConcepts());
}
}
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/personalization_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/personalization_section.h
index b50653c34e6..f704a53d971 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/personalization_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/personalization_section.h
@@ -33,6 +33,11 @@ class PersonalizationSection : public OsSettingsSection {
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
// ash::AmbientModeService::Observer:
void OnAmbientModeEnabledStateChanged();
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 715782b0b11..38bf2e61ebc 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
@@ -27,11 +27,24 @@ void PluginVmHandler::RegisterMessages() {
"getPluginVmSharedPathsDisplayText",
base::BindRepeating(
&PluginVmHandler::HandleGetPluginVmSharedPathsDisplayText,
- weak_ptr_factory_.GetWeakPtr()));
+ base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"removePluginVmSharedPath",
base::BindRepeating(&PluginVmHandler::HandleRemovePluginVmSharedPath,
- weak_ptr_factory_.GetWeakPtr()));
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "wouldPermissionChangeRequireRelaunch",
+ base::BindRepeating(
+ &PluginVmHandler::HandleWouldPermissionChangeRequireRelaunch,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "setPluginVmPermission",
+ base::BindRepeating(&PluginVmHandler::HandleSetPluginVmPermission,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "relaunchPluginVm",
+ base::BindRepeating(&PluginVmHandler::HandleRelaunchPluginVm,
+ base::Unretained(this)));
}
void PluginVmHandler::HandleGetPluginVmSharedPathsDisplayText(
@@ -68,5 +81,42 @@ void PluginVmHandler::HandleRemovePluginVmSharedPath(
path));
}
+void PluginVmHandler::HandleWouldPermissionChangeRequireRelaunch(
+ const base::ListValue* args) {
+ AllowJavascript();
+ CHECK_EQ(3U, args->GetSize());
+ std::string callback_id = args->GetList()[0].GetString();
+ plugin_vm::PermissionType permission_type =
+ static_cast<plugin_vm::PermissionType>(args->GetList()[1].GetInt());
+ DCHECK(permission_type == plugin_vm::PermissionType::kCamera ||
+ permission_type == plugin_vm::PermissionType::kMicrophone);
+ plugin_vm::PluginVmManager* manager =
+ plugin_vm::PluginVmManagerFactory::GetForProfile(profile_);
+ bool current_value = manager->GetPermission(permission_type);
+ bool proposed_value = args->GetList()[2].GetBool();
+ bool requires_relaunch = proposed_value != current_value &&
+ manager->IsRelaunchNeededForNewPermissions();
+
+ ResolveJavascriptCallback(base::Value(callback_id),
+ base::Value(requires_relaunch));
+}
+
+void PluginVmHandler::HandleSetPluginVmPermission(const base::ListValue* args) {
+ CHECK_EQ(2U, args->GetSize());
+ plugin_vm::PermissionType permission_type =
+ static_cast<plugin_vm::PermissionType>(args->GetList()[0].GetInt());
+ bool proposed_value = args->GetList()[1].GetBool();
+ DCHECK(permission_type == plugin_vm::PermissionType::kCamera ||
+ permission_type == plugin_vm::PermissionType::kMicrophone);
+ plugin_vm::PluginVmManagerFactory::GetForProfile(profile_)->SetPermission(
+ permission_type, proposed_value);
+}
+
+void PluginVmHandler::HandleRelaunchPluginVm(const base::ListValue* args) {
+ CHECK_EQ(0U, args->GetList().size());
+ plugin_vm::PluginVmManagerFactory::GetForProfile(profile_)
+ ->RelaunchPluginVm();
+}
+
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h
index d57b34da1db..e1d77e24424 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/plugin_vm_handler.h
@@ -8,6 +8,8 @@
#include <vector>
#include "base/memory/weak_ptr.h"
+#include "chrome/browser/chromeos/plugin_vm/plugin_vm_manager.h"
+#include "chrome/browser/chromeos/plugin_vm/plugin_vm_manager_factory.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
class Profile;
@@ -32,8 +34,16 @@ class PluginVmHandler : public ::settings::SettingsPageUIHandler {
void HandleGetPluginVmSharedPathsDisplayText(const base::ListValue* args);
// Remove a specified path from being shared.
void HandleRemovePluginVmSharedPath(const base::ListValue* args);
+ // Checks if Plugin VM would need to be relaunched if the proposed changes are
+ // made.
+ void HandleWouldPermissionChangeRequireRelaunch(const base::ListValue* args);
+ // Sets the specified permission to the value proposed.
+ void HandleSetPluginVmPermission(const base::ListValue* args);
+ // Relaunches Plugin VM.
+ void HandleRelaunchPluginVm(const base::ListValue* args);
Profile* profile_;
+
// weak_ptr_factory_ should always be last member.
base::WeakPtrFactory<PluginVmHandler> weak_ptr_factory_{this};
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/printing_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/printing_section.cc
index 3415a894f61..168efe1d2d6 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/printing_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/printing_section.cc
@@ -28,10 +28,7 @@ const std::vector<SearchConcept>& GetPrintingSearchConcepts() {
mojom::SearchResultIcon::kPrinter,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kAddPrinter},
- {IDS_OS_SETTINGS_TAG_PRINTING_ADD_PRINTER_ALT1,
- IDS_OS_SETTINGS_TAG_PRINTING_ADD_PRINTER_ALT2,
- SearchConcept::kAltTagEnd}},
+ {.setting = mojom::Setting::kAddPrinter}},
{IDS_OS_SETTINGS_TAG_PRINTING_SAVED_PRINTERS,
mojom::kPrintingDetailsSubpagePath,
mojom::SearchResultIcon::kPrinter,
@@ -41,7 +38,7 @@ const std::vector<SearchConcept>& GetPrintingSearchConcepts() {
{IDS_OS_SETTINGS_TAG_PRINTING,
mojom::kPrintingDetailsSubpagePath,
mojom::SearchResultIcon::kPrinter,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kPrintingDetails},
{IDS_OS_SETTINGS_TAG_PRINTING_ALT1, IDS_OS_SETTINGS_TAG_PRINTING_ALT2,
@@ -76,9 +73,10 @@ PrintingSection::PrintingSection(Profile* profile,
CupsPrintersManager* printers_manager)
: OsSettingsSection(profile, search_tag_registry),
printers_manager_(printers_manager) {
- registry()->AddSearchTags(GetPrintingSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetPrintingSearchConcepts());
if (IsPrintManagementEnabled())
- registry()->AddSearchTags(GetPrintingManagementSearchConcepts());
+ updater.AddSearchTags(GetPrintingManagementSearchConcepts());
}
PrintingSection::~PrintingSection() = default;
@@ -246,5 +244,38 @@ void PrintingSection::AddHandlers(content::WebUI* web_ui) {
std::make_unique<CupsPrintersHandler>(profile(), printers_manager_));
}
+int PrintingSection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_PRINTING;
+}
+
+mojom::Section PrintingSection::GetSection() const {
+ return mojom::Section::kPrinting;
+}
+
+mojom::SearchResultIcon PrintingSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kPrinter;
+}
+
+std::string PrintingSection::GetSectionPath() const {
+ return mojom::kPrintingSectionPath;
+}
+
+void PrintingSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSetting(mojom::Setting::kPrintJobs);
+
+ // Printing details.
+ generator->RegisterTopLevelSubpage(IDS_SETTINGS_PRINTING_CUPS_PRINTERS,
+ mojom::Subpage::kPrintingDetails,
+ mojom::SearchResultIcon::kPrinter,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kPrintingDetailsSubpagePath);
+ static constexpr mojom::Setting kPrintingDetailsSettings[] = {
+ mojom::Setting::kAddPrinter,
+ mojom::Setting::kSavedPrinters,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kPrintingDetails,
+ kPrintingDetailsSettings, generator);
+}
+
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/printing_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/printing_section.h
index b231aeec420..ddef65c546e 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/printing_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/printing_section.h
@@ -31,6 +31,11 @@ class PrintingSection : public OsSettingsSection {
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
CupsPrintersManager* printers_manager_;
};
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/privacy_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/privacy_section.cc
index 94e70f481b3..85c6dea6016 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/privacy_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/privacy_section.cc
@@ -13,6 +13,7 @@
#include "chrome/common/chrome_features.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
+#include "chromeos/constants/chromeos_features.h"
#include "content/public/browser/web_ui_data_source.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
@@ -32,7 +33,7 @@ const std::vector<SearchConcept>& GetPrivacySearchConcepts() {
{IDS_OS_SETTINGS_TAG_PRIVACY,
mojom::kPrivacyAndSecuritySectionPath,
mojom::SearchResultIcon::kShield,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSection,
{.section = mojom::Section::kPrivacyAndSecurity}},
{IDS_OS_SETTINGS_TAG_PRIVACY_WIFI_SLEEP,
@@ -68,9 +69,10 @@ const std::vector<SearchConcept>& GetPrivacyGoogleChromeSearchConcepts() {
PrivacySection::PrivacySection(Profile* profile,
SearchTagRegistry* search_tag_registry)
: OsSettingsSection(profile, search_tag_registry) {
- registry()->AddSearchTags(GetPrivacySearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetPrivacySearchConcepts());
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
- registry()->AddSearchTags(GetPrivacyGoogleChromeSearchConcepts());
+ updater.AddSearchTags(GetPrivacyGoogleChromeSearchConcepts());
#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
}
@@ -84,6 +86,9 @@ void PrivacySection::AddLoadTimeData(content::WebUIDataSource* html_source) {
{"wakeOnWifi", IDS_SETTINGS_WAKE_ON_WIFI_DESCRIPTION},
{"enableContentProtectionAttestation",
IDS_SETTINGS_ENABLE_CONTENT_PROTECTION_ATTESTATION},
+ {"enableSuggestedContent", IDS_SETTINGS_ENABLE_SUGGESTED_CONTENT_TITLE},
+ {"enableSuggestedContentDesc",
+ IDS_SETTINGS_ENABLE_SUGGESTED_CONTENT_DESC},
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings);
@@ -91,10 +96,40 @@ void PrivacySection::AddLoadTimeData(content::WebUIDataSource* html_source) {
"privacySettingsRedesignEnabled",
base::FeatureList::IsEnabled(::features::kPrivacySettingsRedesign));
+ html_source->AddBoolean("suggestedContentToggleEnabled",
+ base::FeatureList::IsEnabled(
+ ::chromeos::features::kSuggestedContentToggle));
+
+ html_source->AddString("suggestedContentLearnMoreURL",
+ chrome::kSuggestedContentLearnMoreURL);
+
html_source->AddString("syncAndGoogleServicesLearnMoreURL",
chrome::kSyncAndGoogleServicesLearnMoreURL);
::settings::AddPersonalizationOptionsStrings(html_source);
}
+int PrivacySection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_PRIVACY;
+}
+
+mojom::Section PrivacySection::GetSection() const {
+ return mojom::Section::kPrivacyAndSecurity;
+}
+
+mojom::SearchResultIcon PrivacySection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kShield;
+}
+
+std::string PrivacySection::GetSectionPath() const {
+ return mojom::kPrivacyAndSecuritySectionPath;
+}
+
+void PrivacySection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSetting(mojom::Setting::kVerifiedAccess);
+ generator->RegisterTopLevelSetting(mojom::Setting::kKeepWifiOnDuringSleep);
+ generator->RegisterTopLevelSetting(
+ mojom::Setting::kUsageStatsAndCrashReports);
+}
+
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/privacy_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/privacy_section.h
index 3c5ba842681..4acbc9d465c 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/privacy_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/privacy_section.h
@@ -26,6 +26,11 @@ class PrivacySection : public OsSettingsSection {
private:
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
};
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/reset_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/reset_section.cc
index 1275fb0e188..21216088ddc 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/reset_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/reset_section.cc
@@ -56,8 +56,9 @@ bool IsPowerwashAllowed() {
ResetSection::ResetSection(Profile* profile,
SearchTagRegistry* search_tag_registry)
: OsSettingsSection(profile, search_tag_registry) {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
if (IsPowerwashAllowed())
- registry()->AddSearchTags(GetResetSearchConcepts());
+ updater.AddSearchTags(GetResetSearchConcepts());
}
ResetSection::~ResetSection() = default;
@@ -94,5 +95,25 @@ void ResetSection::AddHandlers(content::WebUI* web_ui) {
std::make_unique<::settings::ResetSettingsHandler>(profile()));
}
+int ResetSection::GetSectionNameMessageId() const {
+ return IDS_SETTINGS_RESET;
+}
+
+mojom::Section ResetSection::GetSection() const {
+ return mojom::Section::kReset;
+}
+
+mojom::SearchResultIcon ResetSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kReset;
+}
+
+std::string ResetSection::GetSectionPath() const {
+ return mojom::kResetSectionPath;
+}
+
+void ResetSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSetting(mojom::Setting::kPowerwash);
+}
+
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/reset_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/reset_section.h
index ee99e0554c7..90287737e66 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/reset_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/reset_section.h
@@ -28,6 +28,11 @@ class ResetSection : public OsSettingsSection {
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
};
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search.mojom b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search.mojom
index 4be5d33c332..d63ae03274c 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search.mojom
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search.mojom
@@ -30,6 +30,22 @@ enum SearchResultDefaultRank {
kLow,
};
+// Behavior used when determining whether to return parent results for a query.
+// Results are returned based on whether text for those results matches the
+// user's query, but we also support returning a result for the parent of the
+// original result. In this context, a "parent" refers to a section or subpage
+// which contains a child subpage or setting. For example,
+// Subpage::kWifiNetworks is a subpage whose parent is Section::kNetwork, and
+// Setting::kWifiOnOff is a setting whose parent is Subpage::kWifiNetworks.
+enum ParentResultBehavior {
+ // Returns parent results as long as the number of maximum results is not
+ // exceeded.
+ kAllowParentResults,
+
+ // Does not return parent results.
+ kDoNotIncludeParentResults,
+};
+
// Identifier for the result; each result describes one section, subpage, or
// setting.
union SearchResultIdentifier {
@@ -44,6 +60,12 @@ struct SearchResult {
// directly (i.e., not an ID but rather the actual text).
mojo_base.mojom.String16 result_text;
+ // String for the "canonical" version of this result. Some search results use
+ // alternate text (e.g., "Monitor" instead of "Display"). Note that it is
+ // often the case that |result_text| and |canonical_result_text| are the same
+ // string.
+ mojo_base.mojom.String16 canonical_result_text;
+
// The URL path containing the relevant setting, which may or may not contain
// URL parameters. For example, the Wi-Fi list settings page is
// chrome://os-settings/networks?type=WiFi, so the field would be
@@ -57,29 +79,57 @@ struct SearchResult {
// string match.
double relevance_score;
- // List of names of the sections/subpages for this result, which may contain
- // names of sections and/or subpages. Names are all localized String16s, ready
- // to be displayed directly (e.g., as breadcrumbs).
+ // List of names of the ancestor sections/subpages for this result. The list
+ // contains the Settings app name and, if applicable, the ancestor section and
+ // subpage names. Names are all localized String16s which can be displayed in
+ // the UI (e.g., as breadcrumbs).
//
- // Example 1 - Wi-Fi subpage: ["Settings", "Network", "Wi-Fi"]
- // Example 2 - External storage: ["Settings", "Device", "Storage management",
- // "External storage preferences"]
+ // Example 1 - Wi-Fi subpage: ["Settings", "Network"]
+ // Example 2 - External storage: ["Settings", "Device", "Storage management"]
array<mojo_base.mojom.String16> settings_page_hierarchy;
// Default ranking, which is used to break ties when searching for results.
SearchResultDefaultRank default_rank;
+ // True if this result was generated due to a text match; this field can be
+ // false if it was constructed due to a ParentResultBehavior.
+ bool was_generated_from_text_match;
+
// The type and identifier for this search result. The value of the |type|
// field indicates the union member used by |id|.
SearchResultType type;
SearchResultIdentifier id;
};
+// Used to observe changes to search results.
+interface SearchResultsObserver {
+ // Called when the availability of one or more search results has changed. In
+ // this context, "availability" refers to whether a search result can be
+ // returned based on the user's current state. E.g., "Cellular" results are
+ // only shown if the device has an attached modem, so this function would be
+ // called whenever the user plugs in or unplugs a USB modem. Clients can use
+ // this function to ensure that they do not show "stale" results which are no
+ // longer actionable by the user.
+ OnSearchResultAvailabilityChanged();
+};
+
// Provides settings search results. Implemented in the browser process;
// intended to be called from settings JS and Launcher C++.
interface SearchHandler {
// Searches settings for the given query and returns a list of results, sorted
// from most relevant to least relevant. An empty array indicates no relevant
// results.
- Search(mojo_base.mojom.String16 query) => (array<SearchResult> results);
+ //
+ // This function returns an array with a maximum size of |max_num_results|,
+ // but the array may contain fewer elements if there are fewer results.
+ // Clients should never pass a value of 0 for |max_num_results|, since that
+ // would return an empty result array.
+ Search(mojo_base.mojom.String16 query,
+ uint32 max_num_results,
+ ParentResultBehavior parent_result_behavior) =>
+ (array<SearchResult> results);
+
+ // Adds an observer of search results. Disconnected observers are discarded;
+ // to stop observing, close the connection.
+ Observe(pending_remote<SearchResultsObserver> observer);
};
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_concept.h b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_concept.h
index b3763fb0fd3..639dc470ce3 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_concept.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_concept.h
@@ -7,6 +7,7 @@
#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h"
#include "chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom.h"
+#include "chrome/browser/ui/webui/settings/chromeos/os_settings_identifier.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search.mojom.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_result_icon.mojom.h"
@@ -58,7 +59,7 @@ struct SearchConcept {
// The type and identifier for this search result. The value of the |type|
// field indicates the union member used by |id|.
mojom::SearchResultType type;
- Identifier id;
+ OsSettingsIdentifier id;
// Alternate message IDs (from os_settings_search_tag_strings.grdp)
// corresponding to this concept. These IDs refer to messages which represent
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler.cc
index 47c0052bbf0..1bde04057b2 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler.cc
@@ -4,12 +4,14 @@
#include "chrome/browser/ui/webui/settings/chromeos/search/search_handler.h"
+#include <algorithm>
+
#include "base/strings/string_number_conversions.h"
-#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/chromeos/local_search_service/local_search_service.h"
+#include "chrome/browser/ui/webui/settings/chromeos/hierarchy.h"
+#include "chrome/browser/ui/webui/settings/chromeos/os_settings_sections.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_concept.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_result_icon.mojom.h"
-#include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h"
#include "chrome/grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
@@ -17,30 +19,42 @@ namespace chromeos {
namespace settings {
namespace {
-const int32_t kLocalSearchServiceMaxResults = 10;
+bool ContainsSectionResult(const std::vector<mojom::SearchResultPtr>& results,
+ mojom::Section section) {
+ return std::find_if(
+ results.begin(), results.end(), [section](const auto& result) {
+ return result->type == mojom::SearchResultType::kSection &&
+ section == result->id->get_section();
+ }) != results.end();
+}
-// TODO(https://crbug.com/1071700): Delete this function.
-std::vector<base::string16> GenerateDummySettingsHierarchy(
- const char* url_path_with_parameters) {
- std::vector<base::string16> hierarchy;
- hierarchy.push_back(l10n_util::GetStringUTF16(IDS_INTERNAL_APP_SETTINGS));
- hierarchy.push_back(base::ASCIIToUTF16(url_path_with_parameters));
- return hierarchy;
+bool ContainsSubpageResult(const std::vector<mojom::SearchResultPtr>& results,
+ mojom::Subpage subpage) {
+ return std::find_if(
+ results.begin(), results.end(), [subpage](const auto& result) {
+ return result->type == mojom::SearchResultType::kSubpage &&
+ subpage == result->id->get_subpage();
+ }) != results.end();
}
} // namespace
-// static
-const size_t SearchHandler::kNumMaxResults = 5;
-
SearchHandler::SearchHandler(
SearchTagRegistry* search_tag_registry,
+ OsSettingsSections* sections,
+ Hierarchy* hierarchy,
local_search_service::LocalSearchService* local_search_service)
: search_tag_registry_(search_tag_registry),
+ sections_(sections),
+ hierarchy_(hierarchy),
index_(local_search_service->GetIndex(
- local_search_service::IndexId::kCrosSettings)) {}
+ local_search_service::IndexId::kCrosSettings)) {
+ search_tag_registry_->AddObserver(this);
+}
-SearchHandler::~SearchHandler() = default;
+SearchHandler::~SearchHandler() {
+ search_tag_registry_->RemoveObserver(this);
+}
void SearchHandler::BindInterface(
mojo::PendingReceiver<mojom::SearchHandler> pending_receiver) {
@@ -48,10 +62,19 @@ void SearchHandler::BindInterface(
}
std::vector<mojom::SearchResultPtr> SearchHandler::Search(
- const base::string16& query) {
+ const base::string16& query,
+ uint32_t max_num_results,
+ mojom::ParentResultBehavior parent_result_behavior) {
+ // Search for 5x the maximum set of results. If there are many matches for
+ // a query, it may be the case that |index_| returns some matches with higher
+ // SearchResultDefaultRank values later in the list. Requesting up to 5x the
+ // maximum number ensures that such results will be returned and can be ranked
+ // accordingly when sorted.
+ uint32_t max_local_search_service_results = 5 * max_num_results;
+
std::vector<local_search_service::Result> local_search_service_results;
local_search_service::ResponseStatus response_status = index_->Find(
- query, kLocalSearchServiceMaxResults, &local_search_service_results);
+ query, max_local_search_service_results, &local_search_service_results);
if (response_status != local_search_service::ResponseStatus::kSuccess) {
LOG(ERROR) << "Cannot search; LocalSearchService returned "
@@ -60,41 +83,149 @@ std::vector<mojom::SearchResultPtr> SearchHandler::Search(
return {};
}
- return GenerateSearchResultsArray(local_search_service_results);
+ return GenerateSearchResultsArray(local_search_service_results,
+ max_num_results, parent_result_behavior);
}
void SearchHandler::Search(const base::string16& query,
+ uint32_t max_num_results,
+ mojom::ParentResultBehavior parent_result_behavior,
SearchCallback callback) {
- std::move(callback).Run(Search(query));
+ std::move(callback).Run(
+ Search(query, max_num_results, parent_result_behavior));
+}
+
+void SearchHandler::Observe(
+ mojo::PendingRemote<mojom::SearchResultsObserver> observer) {
+ observers_.Add(std::move(observer));
+}
+
+void SearchHandler::OnRegistryUpdated() {
+ for (auto& observer : observers_)
+ observer->OnSearchResultAvailabilityChanged();
}
std::vector<mojom::SearchResultPtr> SearchHandler::GenerateSearchResultsArray(
const std::vector<local_search_service::Result>&
- local_search_service_results) {
+ local_search_service_results,
+ uint32_t max_num_results,
+ mojom::ParentResultBehavior parent_result_behavior) const {
std::vector<mojom::SearchResultPtr> search_results;
for (const auto& result : local_search_service_results) {
mojom::SearchResultPtr result_ptr = ResultToSearchResult(result);
if (result_ptr)
search_results.push_back(std::move(result_ptr));
+ }
- // Limit the number of results to return.
- if (search_results.size() == kNumMaxResults)
- break;
+ std::sort(search_results.begin(), search_results.end(), CompareSearchResults);
+
+ // Now that the results have been sorted, limit the size of to
+ // |max_num_results|.
+ search_results.resize(
+ std::min(static_cast<size_t>(max_num_results), search_results.size()));
+
+ if (parent_result_behavior ==
+ mojom::ParentResultBehavior::kAllowParentResults) {
+ AddParentResults(max_num_results, &search_results);
}
return search_results;
}
-mojom::SearchResultPtr SearchHandler::ResultToSearchResult(
- const local_search_service::Result& result) {
- int message_id;
+void SearchHandler::AddParentResults(
+ uint32_t max_num_results,
+ std::vector<mojom::SearchResultPtr>* search_results) const {
+ auto it = search_results->begin();
+ while (search_results->size() < max_num_results &&
+ it != search_results->end()) {
+ const mojom::SearchResultPtr& result = *it;
+ switch (result->type) {
+ case mojom::SearchResultType::kSection:
+ // Sections have no parents; nothing to do.
+ break;
- // The result's ID is expected to be a stringified int.
- if (!base::StringToInt(result.id, &message_id))
- return nullptr;
+ case mojom::SearchResultType::kSubpage: {
+ const Hierarchy::SubpageMetadata& metadata =
+ hierarchy_->GetSubpageMetadata(result->id->get_subpage());
+
+ // Nested subpage.
+ if (metadata.parent_subpage) {
+ it = AddSubpageResultIfPossible(it, *metadata.parent_subpage,
+ result->relevance_score,
+ search_results);
+ break;
+ }
+
+ // Top-level subpage.
+ it = AddSectionResultIfPossible(it, result, metadata.section,
+ search_results);
+ break;
+ }
+
+ case mojom::SearchResultType::kSetting: {
+ const Hierarchy::SettingMetadata& metadata =
+ hierarchy_->GetSettingMetadata(result->id->get_setting());
+
+ // Nested setting.
+ if (metadata.primary.second) {
+ it = AddSubpageResultIfPossible(it, *metadata.primary.second,
+ result->relevance_score,
+ search_results);
+ break;
+ }
+
+ // Top-level setting.
+ it = AddSectionResultIfPossible(it, result, metadata.primary.first,
+ search_results);
+ break;
+ }
+ }
+ ++it;
+ }
+}
+
+std::vector<mojom::SearchResultPtr>::iterator
+SearchHandler::AddSectionResultIfPossible(
+ const std::vector<mojom::SearchResultPtr>::iterator& curr_position,
+ const mojom::SearchResultPtr& child_result,
+ mojom::Section section,
+ std::vector<mojom::SearchResultPtr>* results) const {
+ // If |results| already includes |section|, do not add it again.
+ if (ContainsSectionResult(*results, section))
+ return curr_position;
+
+ mojom::SearchResultPtr section_result =
+ hierarchy_->GetSectionMetadata(section).ToSearchResult(
+ child_result->relevance_score);
+
+ // Don't add a result for a parent section if it has the exact same text as
+ // the child result, since this results in a broken-looking UI.
+ if (section_result->result_text == child_result->result_text)
+ return curr_position;
+
+ return results->insert(curr_position + 1, std::move(section_result));
+}
+
+std::vector<mojom::SearchResultPtr>::iterator
+SearchHandler::AddSubpageResultIfPossible(
+ const std::vector<mojom::SearchResultPtr>::iterator& curr_position,
+ mojom::Subpage subpage,
+ double relevance_score,
+ std::vector<mojom::SearchResultPtr>* results) const {
+ // If |results| already includes |subpage|, do not add it again.
+ if (ContainsSubpageResult(*results, subpage))
+ return curr_position;
+
+ return results->insert(
+ curr_position + 1,
+ hierarchy_->GetSubpageMetadata(subpage).ToSearchResult(relevance_score));
+}
+
+mojom::SearchResultPtr SearchHandler::ResultToSearchResult(
+ const local_search_service::Result& result) const {
const SearchConcept* concept =
- search_tag_registry_->GetCanonicalTagMetadata(message_id);
+ search_tag_registry_->GetTagMetadata(result.id);
// If the concept was not registered, no metadata is available. This can occur
// if the search tag was dynamically unregistered during the asynchronous
@@ -102,29 +233,85 @@ mojom::SearchResultPtr SearchHandler::ResultToSearchResult(
if (!concept)
return nullptr;
+ // |result| is expected to have one position, whose ID is a stringified int.
+ DCHECK_EQ(1u, result.positions.size());
+ int content_id;
+ if (!base::StringToInt(result.positions[0].content_id, &content_id))
+ return nullptr;
+
+ std::string url;
mojom::SearchResultIdentifierPtr result_id;
+ std::vector<base::string16> hierarchy_strings;
switch (concept->type) {
- case mojom::SearchResultType::kSection:
- result_id =
- mojom::SearchResultIdentifier::NewSection(concept->id.section);
+ case mojom::SearchResultType::kSection: {
+ mojom::Section section = concept->id.section;
+ url = GetModifiedUrl(*concept, section);
+ result_id = mojom::SearchResultIdentifier::NewSection(section);
+ hierarchy_strings.push_back(
+ l10n_util::GetStringUTF16(IDS_INTERNAL_APP_SETTINGS));
break;
- case mojom::SearchResultType::kSubpage:
- result_id =
- mojom::SearchResultIdentifier::NewSubpage(concept->id.subpage);
+ }
+ case mojom::SearchResultType::kSubpage: {
+ mojom::Subpage subpage = concept->id.subpage;
+ url = GetModifiedUrl(*concept,
+ hierarchy_->GetSubpageMetadata(subpage).section);
+ result_id = mojom::SearchResultIdentifier::NewSubpage(subpage);
+ hierarchy_strings = hierarchy_->GenerateAncestorHierarchyStrings(subpage);
break;
- case mojom::SearchResultType::kSetting:
- result_id =
- mojom::SearchResultIdentifier::NewSetting(concept->id.setting);
+ }
+ case mojom::SearchResultType::kSetting: {
+ mojom::Setting setting = concept->id.setting;
+ url = GetModifiedUrl(
+ *concept, hierarchy_->GetSettingMetadata(setting).primary.first);
+ result_id = mojom::SearchResultIdentifier::NewSetting(setting);
+ hierarchy_strings = hierarchy_->GenerateAncestorHierarchyStrings(setting);
break;
+ }
}
- // TODO(https://crbug.com/1071700): Generate real hierarchy instead of using
- // GenerateDummySettingsHierarchy().
return mojom::SearchResult::New(
- l10n_util::GetStringUTF16(message_id), concept->url_path_with_parameters,
- concept->icon, result.score,
- GenerateDummySettingsHierarchy(concept->url_path_with_parameters),
- concept->default_rank, concept->type, std::move(result_id));
+ /*result_text=*/l10n_util::GetStringUTF16(content_id),
+ /*canonical_result_text=*/
+ l10n_util::GetStringUTF16(concept->canonical_message_id), url,
+ concept->icon, result.score, hierarchy_strings, concept->default_rank,
+ /*was_generated_from_text_match=*/true, concept->type,
+ std::move(result_id));
+}
+
+std::string SearchHandler::GetModifiedUrl(const SearchConcept& concept,
+ mojom::Section section) const {
+ return sections_->GetSection(section)->ModifySearchResultUrl(
+ concept.type, concept.id, concept.url_path_with_parameters);
+}
+
+// static
+bool SearchHandler::CompareSearchResults(const mojom::SearchResultPtr& first,
+ const mojom::SearchResultPtr& second) {
+ // Compute the difference between the results' default rankings. Note that
+ // kHigh is declared before kMedium which is declared before kLow, so a
+ // negative value indicates that |first| is ranked higher than |second| and a
+ // positive value indicates that |second| is ranked higher than |first|.
+ int32_t default_rank_diff = static_cast<int32_t>(first->default_rank) -
+ static_cast<int32_t>(second->default_rank);
+ if (default_rank_diff < 0)
+ return true;
+ if (default_rank_diff > 0)
+ return false;
+
+ // At this point, the default ranks are equal, so compare relevance scores. A
+ // higher relevance score indicates a better text match, so the reverse is
+ // true this time.
+ if (first->relevance_score > second->relevance_score)
+ return true;
+ if (first->relevance_score < second->relevance_score)
+ return false;
+
+ // Default rank and relevance scores are equal, so prefer the result which is
+ // higher on the hierarchy. kSection is declared before kSubpage which is
+ // declared before kSetting, so follow the same pattern from default ranks
+ // above. Note that if the types are equal, this will return false, which
+ // induces a strict weak ordering.
+ return static_cast<int32_t>(first->type) < static_cast<int32_t>(second->type);
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler.h b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler.h
index 8247cccaa9d..2425c2b56ac 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler.h
@@ -7,12 +7,16 @@
#include <vector>
+#include "base/gtest_prod_util.h"
#include "base/optional.h"
#include "chrome/browser/chromeos/local_search_service/index.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search.mojom.h"
+#include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/remote.h"
+#include "mojo/public/cpp/bindings/remote_set.h"
namespace local_search_service {
class LocalSearchService;
@@ -21,7 +25,9 @@ class LocalSearchService;
namespace chromeos {
namespace settings {
-class SearchTagRegistry;
+class Hierarchy;
+class OsSettingsSections;
+struct SearchConcept;
// Handles search queries for Chrome OS settings. Search() is expected to be
// invoked by the settings UI as well as the the Launcher search UI. Search
@@ -29,14 +35,13 @@ class SearchTagRegistry;
// indexed in the LocalSearchService and cross-referencing results with
// SearchTagRegistry.
//
-// SearchHandler returns at most |kNumMaxResults| results; searches which do not
-// provide any matches result in an empty results array.
-class SearchHandler : public mojom::SearchHandler {
+// Searches which do not provide any matches result in an empty results array.
+class SearchHandler : public mojom::SearchHandler,
+ public SearchTagRegistry::Observer {
public:
- // Maximum number of results returned by a Search() call.
- static const size_t kNumMaxResults;
-
SearchHandler(SearchTagRegistry* search_tag_registry,
+ OsSettingsSections* sections,
+ Hierarchy* hierarchy,
local_search_service::LocalSearchService* local_search_service);
~SearchHandler() override;
@@ -47,23 +52,64 @@ class SearchHandler : public mojom::SearchHandler {
mojo::PendingReceiver<mojom::SearchHandler> pending_receiver);
// Synchronous search implementation (for in-process clients).
- std::vector<mojom::SearchResultPtr> Search(const base::string16& query);
+ std::vector<mojom::SearchResultPtr> Search(
+ const base::string16& query,
+ uint32_t max_num_results,
+ mojom::ParentResultBehavior parent_result_behavior);
// mojom::SearchHandler:
- void Search(const base::string16& query, SearchCallback callback) override;
+ void Search(const base::string16& query,
+ uint32_t max_num_results,
+ mojom::ParentResultBehavior parent_result_behavior,
+ SearchCallback callback) override;
+ void Observe(
+ mojo::PendingRemote<mojom::SearchResultsObserver> observer) override;
private:
+ FRIEND_TEST_ALL_PREFIXES(SearchHandlerTest, CompareSearchResults);
+
+ // SearchTagRegistry::Observer:
+ void OnRegistryUpdated() override;
+
std::vector<mojom::SearchResultPtr> GenerateSearchResultsArray(
const std::vector<local_search_service::Result>&
- local_search_service_results);
+ local_search_service_results,
+ uint32_t max_num_results,
+ mojom::ParentResultBehavior parent_result_behavior) const;
+
+ void AddParentResults(
+ uint32_t max_num_results,
+ std::vector<mojom::SearchResultPtr>* search_results) const;
+
+ std::vector<mojom::SearchResultPtr>::iterator AddSectionResultIfPossible(
+ const std::vector<mojom::SearchResultPtr>::iterator& position,
+ const mojom::SearchResultPtr& child_result,
+ mojom::Section section,
+ std::vector<mojom::SearchResultPtr>* results) const;
+
+ std::vector<mojom::SearchResultPtr>::iterator AddSubpageResultIfPossible(
+ const std::vector<mojom::SearchResultPtr>::iterator& position,
+ mojom::Subpage subpage,
+ double relevance_score,
+ std::vector<mojom::SearchResultPtr>* results) const;
+
mojom::SearchResultPtr ResultToSearchResult(
- const local_search_service::Result& result);
+ const local_search_service::Result& result) const;
+ std::string GetModifiedUrl(const SearchConcept& concept,
+ mojom::Section section) const;
+
+ // Returns true if |first| should be ranked before |second|.
+ static bool CompareSearchResults(const mojom::SearchResultPtr& first,
+ const mojom::SearchResultPtr& second);
SearchTagRegistry* search_tag_registry_;
+ OsSettingsSections* sections_;
+ Hierarchy* hierarchy_;
local_search_service::Index* index_;
- // Note: Expected to have multiple clients, so a ReceiverSet is used.
+ // Note: Expected to have multiple clients, so ReceiverSet/RemoteSet are used.
mojo::ReceiverSet<mojom::SearchHandler> receivers_;
+ mojo::RemoteSet<mojom::SearchResultsObserver> observers_;
};
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler_unittest.cc
index f2c9d42af8d..d0ecd2baef6 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_handler_unittest.cc
@@ -10,17 +10,41 @@
#include "base/test/task_environment.h"
#include "chrome/browser/chromeos/local_search_service/local_search_service.h"
#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h"
+#include "chrome/browser/ui/webui/settings/chromeos/fake_hierarchy.h"
+#include "chrome/browser/ui/webui/settings/chromeos/fake_os_settings_sections.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search.mojom-test-utils.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/constants/chromeos_features.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "ui/base/l10n/l10n_util.h"
namespace chromeos {
namespace settings {
namespace {
+class FakeObserver : public mojom::SearchResultsObserver {
+ public:
+ FakeObserver() = default;
+ ~FakeObserver() override = default;
+
+ mojo::PendingRemote<mojom::SearchResultsObserver> GenerateRemote() {
+ mojo::PendingRemote<mojom::SearchResultsObserver> remote;
+ receiver_.Bind(remote.InitWithNewPipeAndPassReceiver());
+ return remote;
+ }
+
+ size_t num_calls() const { return num_calls_; }
+
+ private:
+ // mojom::SearchResultsObserver:
+ void OnSearchResultAvailabilityChanged() override { ++num_calls_; }
+
+ size_t num_calls_ = 0;
+ mojo::Receiver<mojom::SearchResultsObserver> receiver_{this};
+};
+
// Note: Copied from printing_section.cc but does not need to stay in sync with
// it.
const std::vector<SearchConcept>& GetPrintingSearchConcepts() {
@@ -30,10 +54,7 @@ const std::vector<SearchConcept>& GetPrintingSearchConcepts() {
mojom::SearchResultIcon::kPrinter,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kAddPrinter},
- {IDS_OS_SETTINGS_TAG_PRINTING_ADD_PRINTER_ALT1,
- IDS_OS_SETTINGS_TAG_PRINTING_ADD_PRINTER_ALT2,
- SearchConcept::kAltTagEnd}},
+ {.setting = mojom::Setting::kAddPrinter}},
{IDS_OS_SETTINGS_TAG_PRINTING_SAVED_PRINTERS,
mojom::kPrintingDetailsSubpagePath,
mojom::SearchResultIcon::kPrinter,
@@ -43,7 +64,7 @@ const std::vector<SearchConcept>& GetPrintingSearchConcepts() {
{IDS_OS_SETTINGS_TAG_PRINTING,
mojom::kPrintingDetailsSubpagePath,
mojom::SearchResultIcon::kPrinter,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kLow,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kPrintingDetails},
{IDS_OS_SETTINGS_TAG_PRINTING_ALT1, IDS_OS_SETTINGS_TAG_PRINTING_ALT2,
@@ -52,13 +73,30 @@ const std::vector<SearchConcept>& GetPrintingSearchConcepts() {
return *tags;
}
+// Creates a result with some default values.
+mojom::SearchResultPtr CreateDummyResult() {
+ return mojom::SearchResult::New(
+ /*result_text=*/base::string16(),
+ /*canonical_result_text=*/base::string16(), /*url=*/"",
+ mojom::SearchResultIcon::kPrinter, /*relevance_score=*/0.5,
+ /*hierarchy_strings=*/std::vector<base::string16>(),
+ mojom::SearchResultDefaultRank::kMedium,
+ /*was_generated_from_text_match=*/false,
+ mojom::SearchResultType::kSection,
+ mojom::SearchResultIdentifier::NewSection(mojom::Section::kPrinting));
+}
+
} // namespace
class SearchHandlerTest : public testing::Test {
protected:
SearchHandlerTest()
: search_tag_registry_(&local_search_service_),
- handler_(&search_tag_registry_, &local_search_service_) {}
+ fake_hierarchy_(&fake_sections_),
+ handler_(&search_tag_registry_,
+ &fake_sections_,
+ &fake_hierarchy_,
+ &local_search_service_) {}
~SearchHandlerTest() override = default;
// testing::Test:
@@ -66,37 +104,209 @@ class SearchHandlerTest : public testing::Test {
scoped_feature_list_.InitAndEnableFeature(
chromeos::features::kNewOsSettingsSearch);
handler_.BindInterface(handler_remote_.BindNewPipeAndPassReceiver());
+
+ fake_hierarchy_.AddSubpageMetadata(
+ IDS_SETTINGS_PRINTING_CUPS_PRINTERS, mojom::Section::kPrinting,
+ mojom::Subpage::kPrintingDetails, mojom::SearchResultIcon::kPrinter,
+ mojom::SearchResultDefaultRank::kMedium,
+ mojom::kPrintingDetailsSubpagePath);
+ fake_hierarchy_.AddSettingMetadata(mojom::Section::kPrinting,
+ mojom::Setting::kAddPrinter);
+ fake_hierarchy_.AddSettingMetadata(mojom::Section::kPrinting,
+ mojom::Setting::kSavedPrinters);
+
+ handler_remote_->Observe(observer_.GenerateRemote());
+ handler_remote_.FlushForTesting();
+ }
+
+ void AddSearchTags(const std::vector<SearchConcept>& search_tags) {
+ SearchTagRegistry::ScopedTagUpdater updater =
+ search_tag_registry_.StartUpdate();
+ updater.AddSearchTags(search_tags);
+ }
+
+ void RemoveSearchTags(const std::vector<SearchConcept>& search_tags) {
+ SearchTagRegistry::ScopedTagUpdater updater =
+ search_tag_registry_.StartUpdate();
+ updater.RemoveSearchTags(search_tags);
}
base::test::TaskEnvironment task_environment_;
base::test::ScopedFeatureList scoped_feature_list_;
local_search_service::LocalSearchService local_search_service_;
SearchTagRegistry search_tag_registry_;
+ FakeOsSettingsSections fake_sections_;
+ FakeHierarchy fake_hierarchy_;
SearchHandler handler_;
mojo::Remote<mojom::SearchHandler> handler_remote_;
+ FakeObserver observer_;
};
TEST_F(SearchHandlerTest, AddAndRemove) {
- // Add printing search tags to registry and search for "Printing".
- search_tag_registry_.AddSearchTags(GetPrintingSearchConcepts());
+ // Add printing search tags to registry and search for "Print".
+ AddSearchTags(GetPrintingSearchConcepts());
+ handler_remote_.FlushForTesting();
+ EXPECT_EQ(1u, observer_.num_calls());
+
std::vector<mojom::SearchResultPtr> search_results;
+
+ // 3 results should be available for a "Print" query.
mojom::SearchHandlerAsyncWaiter(handler_remote_.get())
- .Search(base::ASCIIToUTF16("Printing"), &search_results);
+ .Search(base::ASCIIToUTF16("Print"),
+ /*max_num_results=*/3u,
+ mojom::ParentResultBehavior::kDoNotIncludeParentResults,
+ &search_results);
+ EXPECT_EQ(search_results.size(), 3u);
- // Multiple results should be available.
- EXPECT_GT(search_results.size(), 0u);
+ // Limit results to 1 max and ensure that only 1 result is returned.
+ mojom::SearchHandlerAsyncWaiter(handler_remote_.get())
+ .Search(base::ASCIIToUTF16("Print"),
+ /*max_num_results=*/1u,
+ mojom::ParentResultBehavior::kDoNotIncludeParentResults,
+ &search_results);
+ EXPECT_EQ(search_results.size(), 1u);
// Search for a query which should return no results.
mojom::SearchHandlerAsyncWaiter(handler_remote_.get())
- .Search(base::ASCIIToUTF16("QueryWithNoResults"), &search_results);
+ .Search(base::ASCIIToUTF16("QueryWithNoResults"),
+ /*max_num_results=*/3u,
+ mojom::ParentResultBehavior::kDoNotIncludeParentResults,
+ &search_results);
EXPECT_TRUE(search_results.empty());
// Remove printing search tags to registry and verify that no results are
// returned for "Printing".
- search_tag_registry_.RemoveSearchTags(GetPrintingSearchConcepts());
+ RemoveSearchTags(GetPrintingSearchConcepts());
mojom::SearchHandlerAsyncWaiter(handler_remote_.get())
- .Search(base::ASCIIToUTF16("Printing"), &search_results);
+ .Search(base::ASCIIToUTF16("Print"),
+ /*max_num_results=*/3u,
+ mojom::ParentResultBehavior::kDoNotIncludeParentResults,
+ &search_results);
EXPECT_TRUE(search_results.empty());
+ EXPECT_EQ(2u, observer_.num_calls());
+}
+
+TEST_F(SearchHandlerTest, UrlModification) {
+ // Add printing search tags to registry and search for "Saved".
+ AddSearchTags(GetPrintingSearchConcepts());
+ std::vector<mojom::SearchResultPtr> search_results;
+ mojom::SearchHandlerAsyncWaiter(handler_remote_.get())
+ .Search(base::ASCIIToUTF16("Saved"),
+ /*max_num_results=*/3u,
+ mojom::ParentResultBehavior::kDoNotIncludeParentResults,
+ &search_results);
+
+ // Only the "saved printers" item should be returned.
+ EXPECT_EQ(search_results.size(), 1u);
+
+ // The URL should have bee modified according to the FakeOsSettingSection
+ // scheme.
+ EXPECT_EQ(
+ std::string("Section::kPrinting::") + mojom::kPrintingDetailsSubpagePath,
+ search_results[0]->url_path_with_parameters);
+}
+
+TEST_F(SearchHandlerTest, AltTagMatch) {
+ // Add printing search tags to registry.
+ AddSearchTags(GetPrintingSearchConcepts());
+ std::vector<mojom::SearchResultPtr> search_results;
+
+ // Search for "CUPS". The IDS_OS_SETTINGS_TAG_PRINTING result has an alternate
+ // tag "CUPS" (referring to the Unix printing protocol), so we should receive
+ // one match.
+ mojom::SearchHandlerAsyncWaiter(handler_remote_.get())
+ .Search(base::ASCIIToUTF16("CUPS"),
+ /*max_num_results=*/3u,
+ mojom::ParentResultBehavior::kDoNotIncludeParentResults,
+ &search_results);
+ EXPECT_EQ(search_results.size(), 1u);
+
+ // Verify the result text and canonical restult text.
+ EXPECT_EQ(l10n_util::GetStringUTF16(IDS_OS_SETTINGS_TAG_PRINTING_ALT2),
+ search_results[0]->result_text);
+ EXPECT_EQ(l10n_util::GetStringUTF16(IDS_OS_SETTINGS_TAG_PRINTING),
+ search_results[0]->canonical_result_text);
+}
+
+TEST_F(SearchHandlerTest, AllowParentResult) {
+ // Add printing search tags to registry.
+ AddSearchTags(GetPrintingSearchConcepts());
+ std::vector<mojom::SearchResultPtr> search_results;
+
+ // Search for "Saved", which should only apply to the "saved printers" item.
+ // Pass the kAllowParentResults flag, which should also cause its parent
+ // subpage item to be returned.
+ mojom::SearchHandlerAsyncWaiter(handler_remote_.get())
+ .Search(base::ASCIIToUTF16("Saved"),
+ /*max_num_results=*/3u,
+ mojom::ParentResultBehavior::kAllowParentResults,
+ &search_results);
+ EXPECT_EQ(search_results.size(), 2u);
+ EXPECT_FALSE(search_results[1]->was_generated_from_text_match);
+}
+
+TEST_F(SearchHandlerTest, DefaultRank) {
+ // Add printing search tags to registry.
+ AddSearchTags(GetPrintingSearchConcepts());
+ std::vector<mojom::SearchResultPtr> search_results;
+
+ // Search for "Print". Only the IDS_OS_SETTINGS_TAG_PRINTING result
+ // contains the word "Printing", but the other results have the similar word
+ // "Printer". Thus, "Printing" has a higher relevance score.
+ mojom::SearchHandlerAsyncWaiter(handler_remote_.get())
+ .Search(base::ASCIIToUTF16("Print"),
+ /*max_num_results=*/3u,
+ mojom::ParentResultBehavior::kAllowParentResults,
+ &search_results);
+ EXPECT_EQ(search_results.size(), 3u);
+
+ // Since the IDS_OS_SETTINGS_TAG_PRINTING result has a default rank of kLow,
+ // it should be the *last* result returned even though it has a higher
+ // relevance score.
+ EXPECT_EQ(l10n_util::GetStringUTF16(IDS_OS_SETTINGS_TAG_PRINTING),
+ search_results[2]->result_text);
+}
+
+// Regression test for https://crbug.com/1090184.
+TEST_F(SearchHandlerTest, CompareSearchResults) {
+ // Create two equal dummy results.
+ mojom::SearchResultPtr a = CreateDummyResult();
+ mojom::SearchResultPtr b = CreateDummyResult();
+
+ // CompareSearchResults() returns whether |a| < |b|; since they are equal, it
+ // should return false regardless of the order of parameters.
+ EXPECT_FALSE(SearchHandler::CompareSearchResults(a, b));
+ EXPECT_FALSE(SearchHandler::CompareSearchResults(b, a));
+
+ // Differ only on default rank.
+ a = CreateDummyResult();
+ a->default_rank = mojom::SearchResultDefaultRank::kLow;
+ b = CreateDummyResult();
+ b->default_rank = mojom::SearchResultDefaultRank::kHigh;
+
+ // Comparison value should differ.
+ EXPECT_NE(SearchHandler::CompareSearchResults(b, a),
+ SearchHandler::CompareSearchResults(a, b));
+
+ // Differ only on relevance score.
+ a = CreateDummyResult();
+ a->relevance_score = 0;
+ b = CreateDummyResult();
+ b->relevance_score = 1;
+
+ // Comparison value should differ.
+ EXPECT_NE(SearchHandler::CompareSearchResults(b, a),
+ SearchHandler::CompareSearchResults(a, b));
+
+ // Differ only on type.
+ a = CreateDummyResult();
+ a->type = mojom::SearchResultType::kSection;
+ b = CreateDummyResult();
+ b->type = mojom::SearchResultType::kSubpage;
+
+ // Comparison value should differ.
+ EXPECT_NE(SearchHandler::CompareSearchResults(b, a),
+ SearchHandler::CompareSearchResults(a, b));
}
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_result_icon.mojom b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_result_icon.mojom
index 5f5b099b176..6be31452dc6 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_result_icon.mojom
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_result_icon.mojom
@@ -30,6 +30,7 @@ enum SearchResultIcon {
kMagnifyingGlass,
kMessages,
kMouse,
+ kNearbyShare,
kPaintbrush,
kPenguin,
kPhone,
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.cc
index e3b1b3a7b24..618022b76ba 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.cc
@@ -4,9 +4,11 @@
#include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h"
+#include <algorithm>
+#include <sstream>
+
#include "base/feature_list.h"
#include "base/strings/string_number_conversions.h"
-#include "chrome/browser/chromeos/local_search_service/index.h"
#include "chrome/browser/chromeos/local_search_service/local_search_service.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_concept.h"
#include "chromeos/constants/chromeos_features.h"
@@ -16,36 +18,85 @@ namespace chromeos {
namespace settings {
namespace {
-std::vector<local_search_service::Data> ConceptVectorToDataVector(
- const std::vector<SearchConcept>& search_tags) {
- std::vector<local_search_service::Data> data_list;
-
- for (const auto& concept : search_tags) {
- std::vector<base::string16> search_tags;
-
- // Add the canonical tag.
- search_tags.push_back(
- l10n_util::GetStringUTF16(concept.canonical_message_id));
-
- // Add all alternate tags.
- for (size_t i = 0; i < SearchConcept::kMaxAltTagsPerConcept; ++i) {
- int curr_alt_tag = concept.alt_tag_ids[i];
- if (curr_alt_tag == SearchConcept::kAltTagEnd)
- break;
- search_tags.push_back(l10n_util::GetStringUTF16(curr_alt_tag));
- }
+std::vector<int> GetMessageIds(const SearchConcept* concept) {
+ // Start with only the canonical ID.
+ std::vector<int> alt_tag_message_ids{concept->canonical_message_id};
- // Note: A stringified version of the canonical tag message ID is used as
- // the identifier for this search data.
- data_list.emplace_back(base::NumberToString(concept.canonical_message_id),
- search_tags);
+ // Add alternate IDs, if they exist.
+ for (size_t i = 0; i < SearchConcept::kMaxAltTagsPerConcept; ++i) {
+ int curr_alt_tag_message_id = concept->alt_tag_ids[i];
+ if (curr_alt_tag_message_id == SearchConcept::kAltTagEnd)
+ break;
+ alt_tag_message_ids.push_back(curr_alt_tag_message_id);
}
- return data_list;
+ return alt_tag_message_ids;
}
} // namespace
+SearchTagRegistry::ScopedTagUpdater::ScopedTagUpdater(
+ SearchTagRegistry* registry)
+ : registry_(registry) {}
+
+SearchTagRegistry::ScopedTagUpdater::ScopedTagUpdater(ScopedTagUpdater&&) =
+ default;
+
+SearchTagRegistry::ScopedTagUpdater::~ScopedTagUpdater() {
+ std::vector<const SearchConcept*> pending_adds;
+ std::vector<const SearchConcept*> pending_removals;
+
+ for (const auto& map_entry : pending_updates_) {
+ const std::string& result_id = map_entry.first;
+ const SearchConcept* concept = map_entry.second.first;
+ bool is_pending_add = map_entry.second.second;
+
+ // If tag metadata is present for this tag, it has already been added and is
+ // present in LocalSearchService.
+ bool is_concept_already_added =
+ registry_->GetTagMetadata(result_id) != nullptr;
+
+ // Only add concepts which are intended to be added and have not yet been
+ // added; only remove concepts which are intended to be removed and have
+ // already been added.
+ if (is_pending_add && !is_concept_already_added)
+ pending_adds.push_back(concept);
+ if (!is_pending_add && is_concept_already_added)
+ pending_removals.push_back(concept);
+ }
+
+ if (!pending_adds.empty())
+ registry_->AddSearchTags(pending_adds);
+ if (!pending_removals.empty())
+ registry_->RemoveSearchTags(pending_removals);
+}
+
+void SearchTagRegistry::ScopedTagUpdater::AddSearchTags(
+ const std::vector<SearchConcept>& search_tags) {
+ ProcessPendingSearchTags(search_tags, /*is_pending_add=*/true);
+}
+
+void SearchTagRegistry::ScopedTagUpdater::RemoveSearchTags(
+ const std::vector<SearchConcept>& search_tags) {
+ ProcessPendingSearchTags(search_tags, /*is_pending_add=*/false);
+}
+
+void SearchTagRegistry::ScopedTagUpdater::ProcessPendingSearchTags(
+ const std::vector<SearchConcept>& search_tags,
+ bool is_pending_add) {
+ for (const auto& concept : search_tags) {
+ std::string result_id = ToResultId(concept);
+ auto it = pending_updates_.find(result_id);
+ if (it == pending_updates_.end()) {
+ pending_updates_.emplace(std::piecewise_construct,
+ std::forward_as_tuple(result_id),
+ std::forward_as_tuple(&concept, is_pending_add));
+ } else {
+ it->second.second = is_pending_add;
+ }
+ }
+}
+
SearchTagRegistry::SearchTagRegistry(
local_search_service::LocalSearchService* local_search_service)
: index_(local_search_service->GetIndex(
@@ -53,8 +104,20 @@ SearchTagRegistry::SearchTagRegistry(
SearchTagRegistry::~SearchTagRegistry() = default;
+void SearchTagRegistry::AddObserver(Observer* observer) {
+ observer_list_.AddObserver(observer);
+}
+
+void SearchTagRegistry::RemoveObserver(Observer* observer) {
+ observer_list_.RemoveObserver(observer);
+}
+
+SearchTagRegistry::ScopedTagUpdater SearchTagRegistry::StartUpdate() {
+ return ScopedTagUpdater(this);
+}
+
void SearchTagRegistry::AddSearchTags(
- const std::vector<SearchConcept>& search_tags) {
+ const std::vector<const SearchConcept*>& search_tags) {
if (!base::FeatureList::IsEnabled(features::kNewOsSettingsSearch))
return;
@@ -63,31 +126,82 @@ void SearchTagRegistry::AddSearchTags(
// Add each concept to the map. Note that it is safe to take the address of
// each concept because all concepts are allocated via static
// base::NoDestructor objects in the Get*SearchConcepts() helper functions.
- for (const auto& concept : search_tags)
- canonical_id_to_metadata_map_[concept.canonical_message_id] = &concept;
+ for (const auto* concept : search_tags)
+ result_id_to_metadata_list_map_[ToResultId(*concept)] = concept;
+
+ NotifyRegistryUpdated();
}
void SearchTagRegistry::RemoveSearchTags(
- const std::vector<SearchConcept>& search_tags) {
+ const std::vector<const SearchConcept*>& search_tags) {
if (!base::FeatureList::IsEnabled(features::kNewOsSettingsSearch))
return;
- std::vector<std::string> ids;
- for (const auto& concept : search_tags) {
- canonical_id_to_metadata_map_.erase(concept.canonical_message_id);
- ids.push_back(base::NumberToString(concept.canonical_message_id));
+ std::vector<std::string> data_ids;
+ for (const auto* concept : search_tags) {
+ std::string result_id = ToResultId(*concept);
+ result_id_to_metadata_list_map_.erase(result_id);
+ data_ids.push_back(std::move(result_id));
}
- index_->Delete(ids);
+ index_->Delete(data_ids);
+
+ NotifyRegistryUpdated();
}
-const SearchConcept* SearchTagRegistry::GetCanonicalTagMetadata(
- int canonical_message_id) const {
- const auto it = canonical_id_to_metadata_map_.find(canonical_message_id);
- if (it == canonical_id_to_metadata_map_.end())
+const SearchConcept* SearchTagRegistry::GetTagMetadata(
+ const std::string& result_id) const {
+ const auto it = result_id_to_metadata_list_map_.find(result_id);
+ if (it == result_id_to_metadata_list_map_.end())
return nullptr;
return it->second;
}
+// static
+std::string SearchTagRegistry::ToResultId(const SearchConcept& concept) {
+ std::stringstream ss;
+ switch (concept.type) {
+ case mojom::SearchResultType::kSection:
+ ss << concept.id.section;
+ break;
+ case mojom::SearchResultType::kSubpage:
+ ss << concept.id.subpage;
+ break;
+ case mojom::SearchResultType::kSetting:
+ ss << concept.id.setting;
+ break;
+ }
+ ss << "," << concept.canonical_message_id;
+ return ss.str();
+}
+
+std::vector<local_search_service::Data>
+SearchTagRegistry::ConceptVectorToDataVector(
+ const std::vector<const SearchConcept*>& search_tags) {
+ std::vector<local_search_service::Data> data_list;
+
+ for (const auto* concept : search_tags) {
+ // Create a list of Content objects, which use the stringified version of
+ // message IDs as identifiers.
+ std::vector<local_search_service::Content> content_list;
+ for (int message_id : GetMessageIds(concept)) {
+ content_list.emplace_back(
+ /*id=*/base::NumberToString(message_id),
+ /*content=*/l10n_util::GetStringUTF16(message_id));
+ }
+
+ // Compute an identifier for this result; the same ID format it used in
+ // GetTagMetadata().
+ data_list.emplace_back(ToResultId(*concept), std::move(content_list));
+ }
+
+ return data_list;
+}
+
+void SearchTagRegistry::NotifyRegistryUpdated() {
+ for (auto& observer : observer_list_)
+ observer.OnRegistryUpdated();
+}
+
} // namespace settings
} // namespace chromeos
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h
index c1c7a947f87..abd1f83b1fa 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h
@@ -6,8 +6,13 @@
#define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_SEARCH_SEARCH_TAG_REGISTRY_H_
#include <unordered_map>
+#include <utility>
#include <vector>
+#include "base/gtest_prod_util.h"
+#include "base/observer_list.h"
+#include "base/observer_list_types.h"
+#include "chrome/browser/chromeos/local_search_service/index.h"
#include "chrome/browser/ui/webui/settings/chromeos/os_settings_section.h"
namespace local_search_service {
@@ -21,27 +26,82 @@ namespace settings {
struct SearchConcept;
// Processes all registered search tags by adding/removing them from
-// LocalSearchService and providing metadata via GetCanonicalTagMetadata().
+// LocalSearchService and providing metadata via GetTagMetadata().
class SearchTagRegistry {
public:
+ class Observer : public base::CheckedObserver {
+ public:
+ ~Observer() override = default;
+ virtual void OnRegistryUpdated() = 0;
+ };
+
+ class ScopedTagUpdater {
+ public:
+ ScopedTagUpdater(ScopedTagUpdater&&);
+ ScopedTagUpdater(const ScopedTagUpdater&) = delete;
+ ScopedTagUpdater& operator=(const ScopedTagUpdater&) = delete;
+ ~ScopedTagUpdater();
+
+ void AddSearchTags(const std::vector<SearchConcept>& search_tags);
+ void RemoveSearchTags(const std::vector<SearchConcept>& search_tags);
+
+ private:
+ friend class SearchTagRegistry;
+
+ explicit ScopedTagUpdater(SearchTagRegistry* registry);
+
+ void ProcessPendingSearchTags(const std::vector<SearchConcept>& search_tags,
+ bool is_pending_add);
+
+ SearchTagRegistry* registry_;
+
+ // A SearchConcept along with a bool of the pending update state. If the
+ // bool is true, the concept should be added; if the bool is false, the
+ // concept should be removed.
+ using ConceptWithShouldAddBool = std::pair<const SearchConcept*, bool>;
+ std::unordered_map<std::string, ConceptWithShouldAddBool> pending_updates_;
+ };
+
SearchTagRegistry(
local_search_service::LocalSearchService* local_search_service);
SearchTagRegistry(const SearchTagRegistry& other) = delete;
SearchTagRegistry& operator=(const SearchTagRegistry& other) = delete;
virtual ~SearchTagRegistry();
- void AddSearchTags(const std::vector<SearchConcept>& search_tags);
- void RemoveSearchTags(const std::vector<SearchConcept>& search_tags);
+ void AddObserver(Observer* observer);
+ void RemoveObserver(Observer* observer);
- // Returns the tag metadata associated with |canonical_message_id|, which must
- // be one of the canonical IDS_OS_SETTINGS_TAG_* identifiers used for a search
- // tag. If no metadata is available or if |canonical_message_id| instead
- // refers to an alternate tag's ID, null is returned.
- const SearchConcept* GetCanonicalTagMetadata(int canonical_message_id) const;
+ // Starts a tag update, which allows clients to add/remove search tags. The
+ // ScopedTagUpdater object is returned by value and only updates tags when it
+ // goes out of scope, so clients should not hold onto it outside the scope of
+ // a function.
+ ScopedTagUpdater StartUpdate();
+ // Returns the tag metadata associated with |result_id|, which is the ID
+ // returned by the LocalSearchService. If no metadata is available, null is
+ // returned.
+ const SearchConcept* GetTagMetadata(const std::string& result_id) const;
private:
+ FRIEND_TEST_ALL_PREFIXES(SearchTagRegistryTest, AddAndRemove);
+
+ static std::string ToResultId(const SearchConcept& concept);
+
+ void AddSearchTags(const std::vector<const SearchConcept*>& search_tags);
+ void RemoveSearchTags(const std::vector<const SearchConcept*>& search_tags);
+
+ std::vector<local_search_service::Data> ConceptVectorToDataVector(
+ const std::vector<const SearchConcept*>& search_tags);
+ void NotifyRegistryUpdated();
+
+ // Index used by the LocalSearchService for string matching.
local_search_service::Index* index_;
- std::unordered_map<int, const SearchConcept*> canonical_id_to_metadata_map_;
+
+ // In-memory cache of all results which have been added to the
+ // LocalSearchService. Contents are kept in sync with |index_|.
+ std::unordered_map<std::string, const SearchConcept*>
+ result_id_to_metadata_list_map_;
+
+ base::ObserverList<Observer> observer_list_;
};
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry_unittest.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry_unittest.cc
index 6eff74b2583..1aebe00ce35 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry_unittest.cc
@@ -5,19 +5,31 @@
#include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h"
#include "base/no_destructor.h"
-#include "base/test/scoped_feature_list.h"
#include "chrome/browser/chromeos/local_search_service/index.h"
#include "chrome/browser/chromeos/local_search_service/local_search_service.h"
#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_concept.h"
#include "chrome/grit/generated_resources.h"
-#include "chromeos/constants/chromeos_features.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace settings {
namespace {
+class FakeObserver : public SearchTagRegistry::Observer {
+ public:
+ FakeObserver() = default;
+ ~FakeObserver() override = default;
+
+ size_t num_calls() const { return num_calls_; }
+
+ private:
+ // SearchTagRegistry::Observer:
+ void OnRegistryUpdated() override { ++num_calls_; }
+
+ size_t num_calls_ = 0;
+};
+
// Note: Copied from printing_section.cc but does not need to stay in sync with
// it.
const std::vector<SearchConcept>& GetPrintingSearchConcepts() {
@@ -27,10 +39,7 @@ const std::vector<SearchConcept>& GetPrintingSearchConcepts() {
mojom::SearchResultIcon::kPrinter,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kAddPrinter},
- {IDS_OS_SETTINGS_TAG_PRINTING_ADD_PRINTER_ALT1,
- IDS_OS_SETTINGS_TAG_PRINTING_ADD_PRINTER_ALT2,
- SearchConcept::kAltTagEnd}},
+ {.setting = mojom::Setting::kAddPrinter}},
{IDS_OS_SETTINGS_TAG_PRINTING_SAVED_PRINTERS,
mojom::kPrintingDetailsSubpagePath,
mojom::SearchResultIcon::kPrinter,
@@ -40,7 +49,7 @@ const std::vector<SearchConcept>& GetPrintingSearchConcepts() {
{IDS_OS_SETTINGS_TAG_PRINTING,
mojom::kPrintingDetailsSubpagePath,
mojom::SearchResultIcon::kPrinter,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kPrintingDetails},
{IDS_OS_SETTINGS_TAG_PRINTING_ALT1, IDS_OS_SETTINGS_TAG_PRINTING_ALT2,
@@ -58,37 +67,61 @@ class SearchTagRegistryTest : public testing::Test {
// testing::Test:
void SetUp() override {
- scoped_feature_list_.InitAndEnableFeature(
- chromeos::features::kNewOsSettingsSearch);
+ search_tag_registry_.AddObserver(&observer_);
index_ = local_search_service_.GetIndex(
local_search_service::IndexId::kCrosSettings);
}
- base::test::ScopedFeatureList scoped_feature_list_;
+ void TearDown() override { search_tag_registry_.RemoveObserver(&observer_); }
+
local_search_service::LocalSearchService local_search_service_;
SearchTagRegistry search_tag_registry_;
+ FakeObserver observer_;
local_search_service::Index* index_;
};
TEST_F(SearchTagRegistryTest, AddAndRemove) {
// Add search tags; size of the index should increase.
- search_tag_registry_.AddSearchTags(GetPrintingSearchConcepts());
+ {
+ SearchTagRegistry::ScopedTagUpdater updater =
+ search_tag_registry_.StartUpdate();
+ updater.AddSearchTags(GetPrintingSearchConcepts());
+
+ // Nothing should have happened yet, since |updater| has not gone out of
+ // scope.
+ EXPECT_EQ(0u, index_->GetSize());
+ EXPECT_EQ(0u, observer_.num_calls());
+ }
+ // Now that it went out of scope, the update should have occurred.
EXPECT_EQ(3u, index_->GetSize());
+ EXPECT_EQ(1u, observer_.num_calls());
- // Tags added should be available via GetCanonicalTagMetadata().
+ std::string first_tag_id =
+ SearchTagRegistry::ToResultId(GetPrintingSearchConcepts()[0]);
+
+ // Tags added should be available via GetTagMetadata().
const SearchConcept* add_printer_concept =
- search_tag_registry_.GetCanonicalTagMetadata(
- IDS_OS_SETTINGS_TAG_PRINTING_ADD_PRINTER);
+ search_tag_registry_.GetTagMetadata(first_tag_id);
ASSERT_TRUE(add_printer_concept);
EXPECT_EQ(mojom::Setting::kAddPrinter, add_printer_concept->id.setting);
// Remove search tag; size should go back to 0.
- search_tag_registry_.RemoveSearchTags(GetPrintingSearchConcepts());
+ {
+ SearchTagRegistry::ScopedTagUpdater updater =
+ search_tag_registry_.StartUpdate();
+ updater.RemoveSearchTags(GetPrintingSearchConcepts());
+
+ // Tags should not have been removed yet, since |updater| has not gone out
+ // of scope.
+ EXPECT_EQ(3u, index_->GetSize());
+ EXPECT_EQ(1u, observer_.num_calls());
+ }
+ // Now that it went out of scope, the update should have occurred.
EXPECT_EQ(0u, index_->GetSize());
+ EXPECT_EQ(2u, observer_.num_calls());
- // The tag should no longer be accessible via GetCanonicalTagMetadata().
- add_printer_concept = search_tag_registry_.GetCanonicalTagMetadata(
- IDS_OS_SETTINGS_TAG_PRINTING_ADD_PRINTER);
+ // The tag should no longer be accessible via GetTagMetadata().
+ add_printer_concept = search_tag_registry_.GetTagMetadata(first_tag_id);
ASSERT_FALSE(add_printer_concept);
}
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/search_section.cc b/chromium/chrome/browser/ui/webui/settings/chromeos/search_section.cc
index 958071d8716..6f8763df333 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/search_section.cc
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/search_section.cc
@@ -9,6 +9,7 @@
#include "ash/public/cpp/assistant/assistant_state.h"
#include "base/no_destructor.h"
+#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/chromeos/assistant/assistant_util.h"
#include "chrome/browser/profiles/profile.h"
@@ -19,10 +20,14 @@
#include "chrome/browser/ui/webui/webui_util.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
+#include "chromeos/components/quick_answers/quick_answers_client.h"
#include "chromeos/constants/chromeos_features.h"
#include "chromeos/services/assistant/public/cpp/assistant_prefs.h"
#include "chromeos/services/assistant/public/cpp/features.h"
+#include "components/language/core/browser/pref_names.h"
+#include "components/prefs/pref_service.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "third_party/icu/source/common/unicode/locid.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/chromeos/devicetype_utils.h"
@@ -48,60 +53,45 @@ const std::vector<SearchConcept>& GetAssistantSearchConcepts() {
{IDS_OS_SETTINGS_TAG_ASSISTANT,
mojom::kAssistantSubpagePath,
mojom::SearchResultIcon::kAssistant,
- mojom::SearchResultDefaultRank::kHigh,
+ mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kAssistant}},
- {IDS_OS_SETTINGS_TAG_ASSISTANT_QUICK_ANSWERS,
+ });
+ return *tags;
+}
+
+const std::vector<SearchConcept>& GetAssistantOnSearchConcepts() {
+ static const base::NoDestructor<std::vector<SearchConcept>> tags({
+ {IDS_OS_SETTINGS_TAG_ASSISTANT_TURN_OFF,
mojom::kAssistantSubpagePath,
mojom::SearchResultIcon::kAssistant,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kAssistantQuickAnswers}},
+ {.setting = mojom::Setting::kAssistantOnOff},
+ {IDS_OS_SETTINGS_TAG_ASSISTANT_TURN_OFF_ALT1,
+ SearchConcept::kAltTagEnd}},
{IDS_OS_SETTINGS_TAG_ASSISTANT_PREFERRED_INPUT,
mojom::kAssistantSubpagePath,
mojom::SearchResultIcon::kAssistant,
- mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultDefaultRank::kLow,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kAssistantVoiceInput}},
- {IDS_OS_SETTINGS_TAG_ASSISTANT_OK_GOOGLE,
- mojom::kAssistantSubpagePath,
- mojom::SearchResultIcon::kAssistant,
- mojom::SearchResultDefaultRank::kMedium,
- mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kAssistantOkGoogle},
- {IDS_OS_SETTINGS_TAG_ASSISTANT_OK_GOOGLE_ALT1,
- IDS_OS_SETTINGS_TAG_ASSISTANT_OK_GOOGLE_ALT2,
- SearchConcept::kAltTagEnd}},
{IDS_OS_SETTINGS_TAG_ASSISTANT_NOTIFICATIONS,
mojom::kAssistantSubpagePath,
mojom::SearchResultIcon::kAssistant,
- mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultDefaultRank::kLow,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kAssistantNotifications}},
{IDS_OS_SETTINGS_TAG_ASSISTANT_RELATED_INFO,
mojom::kAssistantSubpagePath,
mojom::SearchResultIcon::kAssistant,
- mojom::SearchResultDefaultRank::kMedium,
+ mojom::SearchResultDefaultRank::kLow,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kAssistantRelatedInfo}},
});
return *tags;
}
-const std::vector<SearchConcept>& GetAssistantOnSearchConcepts() {
- static const base::NoDestructor<std::vector<SearchConcept>> tags({
- {IDS_OS_SETTINGS_TAG_ASSISTANT_TURN_OFF,
- mojom::kAssistantSubpagePath,
- mojom::SearchResultIcon::kAssistant,
- mojom::SearchResultDefaultRank::kMedium,
- mojom::SearchResultType::kSetting,
- {.setting = mojom::Setting::kAssistantOnOff},
- {IDS_OS_SETTINGS_TAG_ASSISTANT_TURN_OFF_ALT1,
- SearchConcept::kAltTagEnd}},
- });
- return *tags;
-}
-
const std::vector<SearchConcept>& GetAssistantOffSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_ASSISTANT_TURN_ON,
@@ -117,21 +107,39 @@ const std::vector<SearchConcept>& GetAssistantOffSearchConcepts() {
const std::vector<SearchConcept>& GetAssistantQuickAnswersSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- // TODO(khorimoto): Add "Assistant Quick Answers" search concepts.
+ {IDS_OS_SETTINGS_TAG_ASSISTANT_QUICK_ANSWERS,
+ mojom::kAssistantSubpagePath,
+ mojom::SearchResultIcon::kAssistant,
+ mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kAssistantQuickAnswers}},
});
return *tags;
}
const std::vector<SearchConcept>& GetAssistantHotwordDspSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- // TODO(khorimoto): Add "Assistant hotword DSP" search concepts.
+ {IDS_OS_SETTINGS_TAG_ASSISTANT_OK_GOOGLE,
+ mojom::kAssistantSubpagePath,
+ mojom::SearchResultIcon::kAssistant,
+ mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kAssistantOkGoogle},
+ {IDS_OS_SETTINGS_TAG_ASSISTANT_OK_GOOGLE_ALT1,
+ IDS_OS_SETTINGS_TAG_ASSISTANT_OK_GOOGLE_ALT2,
+ SearchConcept::kAltTagEnd}},
});
return *tags;
}
const std::vector<SearchConcept>& GetAssistantVoiceMatchSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
- // TODO(khorimoto): Add "Assistant hotword DSP" search concepts.
+ {IDS_OS_SETTINGS_TAG_ASSISTANT_TRAIN_VOICE_MODEL,
+ mojom::kAssistantSubpagePath,
+ mojom::SearchResultIcon::kAssistant,
+ mojom::SearchResultDefaultRank::kLow,
+ mojom::SearchResultType::kSetting,
+ {.setting = mojom::Setting::kTrainAssistantVoiceModel}},
});
return *tags;
}
@@ -140,10 +148,6 @@ bool IsVoiceMatchAllowed() {
return !assistant::features::IsVoiceMatchDisabled();
}
-bool AreQuickAnswersAllowed() {
- return features::IsQuickAnswersSettingToggleEnabled();
-}
-
void AddGoogleAssistantStrings(content::WebUIDataSource* html_source) {
static constexpr webui::LocalizedString kLocalizedStrings[] = {
{"googleAssistantPageTitle", IDS_SETTINGS_GOOGLE_ASSISTANT},
@@ -186,7 +190,6 @@ void AddGoogleAssistantStrings(content::WebUIDataSource* html_source) {
html_source->AddBoolean("hotwordDspAvailable", IsHotwordDspAvailable());
html_source->AddBoolean("voiceMatchDisabled", !IsVoiceMatchAllowed());
- html_source->AddBoolean("quickAnswersAvailable", AreQuickAnswersAllowed());
}
} // namespace
@@ -194,11 +197,12 @@ void AddGoogleAssistantStrings(content::WebUIDataSource* html_source) {
SearchSection::SearchSection(Profile* profile,
SearchTagRegistry* search_tag_registry)
: OsSettingsSection(profile, search_tag_registry) {
- registry()->AddSearchTags(GetSearchPageSearchConcepts());
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+ updater.AddSearchTags(GetSearchPageSearchConcepts());
ash::AssistantState* assistant_state = ash::AssistantState::Get();
if (IsAssistantAllowed() && assistant_state) {
- registry()->AddSearchTags(GetAssistantSearchConcepts());
+ updater.AddSearchTags(GetAssistantSearchConcepts());
assistant_state->AddObserver(this);
UpdateAssistantSearchTags();
@@ -226,6 +230,7 @@ void SearchSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
const bool is_assistant_allowed = IsAssistantAllowed();
html_source->AddBoolean("isAssistantAllowed", is_assistant_allowed);
+ html_source->AddBoolean("quickAnswersAvailable", IsQuickAnswersAllowed());
html_source->AddLocalizedString("osSearchPageTitle",
is_assistant_allowed
? IDS_SETTINGS_SEARCH_AND_ASSISTANT
@@ -248,6 +253,44 @@ void SearchSection::AddHandlers(content::WebUI* web_ui) {
std::make_unique<chromeos::settings::GoogleAssistantHandler>());
}
+int SearchSection::GetSectionNameMessageId() const {
+ return IsAssistantAllowed() ? IDS_SETTINGS_SEARCH_AND_ASSISTANT
+ : IDS_SETTINGS_SEARCH;
+}
+
+mojom::Section SearchSection::GetSection() const {
+ return mojom::Section::kSearchAndAssistant;
+}
+
+mojom::SearchResultIcon SearchSection::GetSectionIcon() const {
+ return mojom::SearchResultIcon::kMagnifyingGlass;
+}
+
+std::string SearchSection::GetSectionPath() const {
+ return mojom::kSearchAndAssistantSectionPath;
+}
+
+void SearchSection::RegisterHierarchy(HierarchyGenerator* generator) const {
+ generator->RegisterTopLevelSetting(mojom::Setting::kPreferredSearchEngine);
+
+ // Assistant.
+ generator->RegisterTopLevelSubpage(
+ IDS_SETTINGS_GOOGLE_ASSISTANT, mojom::Subpage::kAssistant,
+ mojom::SearchResultIcon::kAssistant,
+ mojom::SearchResultDefaultRank::kMedium, mojom::kAssistantSubpagePath);
+ static constexpr mojom::Setting kAssistantSettings[] = {
+ mojom::Setting::kAssistantOnOff,
+ mojom::Setting::kAssistantRelatedInfo,
+ mojom::Setting::kAssistantQuickAnswers,
+ mojom::Setting::kAssistantOkGoogle,
+ mojom::Setting::kAssistantNotifications,
+ mojom::Setting::kAssistantVoiceInput,
+ mojom::Setting::kTrainAssistantVoiceModel,
+ };
+ RegisterNestedSettingBulk(mojom::Subpage::kAssistant, kAssistantSettings,
+ generator);
+}
+
void SearchSection::OnAssistantConsentStatusChanged(int consent_status) {
UpdateAssistantSearchTags();
}
@@ -264,19 +307,40 @@ void SearchSection::OnAssistantHotwordEnabled(bool enabled) {
UpdateAssistantSearchTags();
}
-bool SearchSection::IsAssistantAllowed() {
+bool SearchSection::IsAssistantAllowed() const {
// NOTE: This will be false when the flag is disabled.
return ::assistant::IsAssistantAllowedForProfile(profile()) ==
chromeos::assistant::AssistantAllowedState::ALLOWED;
}
+bool SearchSection::IsQuickAnswersAllowed() const {
+ if (!features::IsQuickAnswersSettingToggleEnabled())
+ return false;
+
+ const PrefService* prefs = profile()->GetPrefs();
+ std::string pref_locale =
+ prefs->GetString(language::prefs::kApplicationLocale);
+ // Also accept runtime locale which maybe an approximation of user's pref
+ // locale.
+ const std::string kRuntimeLocale = icu::Locale::getDefault().getName();
+
+ base::ReplaceChars(pref_locale, "-", "_", &pref_locale);
+ if (!::chromeos::quick_answers::QuickAnswersClient::
+ IsQuickAnswersAllowedForLocale(pref_locale, kRuntimeLocale))
+ return false;
+
+ return true;
+}
+
void SearchSection::UpdateAssistantSearchTags() {
+ SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
+
// Start without any Assistant search concepts, then add if needed below.
- registry()->RemoveSearchTags(GetAssistantOnSearchConcepts());
- registry()->RemoveSearchTags(GetAssistantOffSearchConcepts());
- registry()->RemoveSearchTags(GetAssistantQuickAnswersSearchConcepts());
- registry()->RemoveSearchTags(GetAssistantHotwordDspSearchConcepts());
- registry()->RemoveSearchTags(GetAssistantVoiceMatchSearchConcepts());
+ updater.RemoveSearchTags(GetAssistantOnSearchConcepts());
+ updater.RemoveSearchTags(GetAssistantOffSearchConcepts());
+ updater.RemoveSearchTags(GetAssistantQuickAnswersSearchConcepts());
+ updater.RemoveSearchTags(GetAssistantHotwordDspSearchConcepts());
+ updater.RemoveSearchTags(GetAssistantVoiceMatchSearchConcepts());
ash::AssistantState* assistant_state = ash::AssistantState::Get();
@@ -284,26 +348,26 @@ void SearchSection::UpdateAssistantSearchTags() {
// off, none of the sub-features are enabled.
if (!assistant_state->settings_enabled() ||
!assistant_state->settings_enabled().value()) {
- registry()->AddSearchTags(GetAssistantOffSearchConcepts());
+ updater.AddSearchTags(GetAssistantOffSearchConcepts());
return;
}
- registry()->AddSearchTags(GetAssistantOnSearchConcepts());
+ updater.AddSearchTags(GetAssistantOnSearchConcepts());
- if (AreQuickAnswersAllowed() && assistant_state->context_enabled() &&
+ if (IsQuickAnswersAllowed() && assistant_state->context_enabled() &&
assistant_state->context_enabled().value()) {
- registry()->AddSearchTags(GetAssistantQuickAnswersSearchConcepts());
+ updater.AddSearchTags(GetAssistantQuickAnswersSearchConcepts());
}
if (IsHotwordDspAvailable())
- registry()->AddSearchTags(GetAssistantHotwordDspSearchConcepts());
+ updater.AddSearchTags(GetAssistantHotwordDspSearchConcepts());
if (IsVoiceMatchAllowed() && assistant_state->hotword_enabled() &&
assistant_state->hotword_enabled().value() &&
assistant_state->consent_status() &&
assistant_state->consent_status().value() ==
assistant::prefs::ConsentStatus::kActivityControlAccepted) {
- registry()->AddSearchTags(GetAssistantVoiceMatchSearchConcepts());
+ updater.AddSearchTags(GetAssistantVoiceMatchSearchConcepts());
}
}
diff --git a/chromium/chrome/browser/ui/webui/settings/chromeos/search_section.h b/chromium/chrome/browser/ui/webui/settings/chromeos/search_section.h
index d53c8d0e1ff..1de2bc61d26 100644
--- a/chromium/chrome/browser/ui/webui/settings/chromeos/search_section.h
+++ b/chromium/chrome/browser/ui/webui/settings/chromeos/search_section.h
@@ -30,6 +30,11 @@ class SearchSection : public OsSettingsSection,
// OsSettingsSection:
void AddLoadTimeData(content::WebUIDataSource* html_source) override;
void AddHandlers(content::WebUI* web_ui) override;
+ int GetSectionNameMessageId() const override;
+ mojom::Section GetSection() const override;
+ mojom::SearchResultIcon GetSectionIcon() const override;
+ std::string GetSectionPath() const override;
+ void RegisterHierarchy(HierarchyGenerator* generator) const override;
// ash::AssistantStateObserver:
void OnAssistantConsentStatusChanged(int consent_status) override;
@@ -37,7 +42,8 @@ class SearchSection : public OsSettingsSection,
void OnAssistantSettingsEnabled(bool enabled) override;
void OnAssistantHotwordEnabled(bool enabled) override;
- bool IsAssistantAllowed();
+ bool IsAssistantAllowed() const;
+ bool IsQuickAnswersAllowed() const;
void UpdateAssistantSearchTags();
};
diff --git a/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.cc b/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.cc
index e2f4c5719c7..b3fd20ec805 100644
--- a/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.cc
+++ b/chromium/chrome/browser/ui/webui/settings/custom_home_pages_table_model.cc
@@ -45,9 +45,8 @@ struct CustomHomePagesTableModel::Entry {
CustomHomePagesTableModel::CustomHomePagesTableModel(Profile* profile)
: profile_(profile),
- observer_(NULL),
- num_outstanding_title_lookups_(0) {
-}
+ observer_(nullptr),
+ num_outstanding_title_lookups_(0) {}
CustomHomePagesTableModel::~CustomHomePagesTableModel() {
}
diff --git a/chromium/chrome/browser/ui/webui/settings/recent_site_settings_helper_unittest.cc b/chromium/chrome/browser/ui/webui/settings/recent_site_settings_helper_unittest.cc
index 7984c581713..8d765b17cbe 100644
--- a/chromium/chrome/browser/ui/webui/settings/recent_site_settings_helper_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/recent_site_settings_helper_unittest.cc
@@ -20,10 +20,8 @@ namespace {
ContentSetting kBlocked = ContentSetting::CONTENT_SETTING_BLOCK;
ContentSetting kAllowed = ContentSetting::CONTENT_SETTING_ALLOW;
ContentSetting kDefault = ContentSetting::CONTENT_SETTING_DEFAULT;
-site_settings::SiteSettingSource kEmbargo =
- site_settings::SiteSettingSource::kEmbargo;
-site_settings::SiteSettingSource kPreference =
- site_settings::SiteSettingSource::kPreference;
+SiteSettingSource kEmbargo = site_settings::SiteSettingSource::kEmbargo;
+SiteSettingSource kPreference = site_settings::SiteSettingSource::kPreference;
ContentSettingsType kNotifications = ContentSettingsType::NOTIFICATIONS;
ContentSettingsType kPlugins = ContentSettingsType::PLUGINS;
ContentSettingsType kPopups = ContentSettingsType::POPUPS;
diff --git a/chromium/chrome/browser/ui/webui/settings/safety_check_handler.cc b/chromium/chrome/browser/ui/webui/settings/safety_check_handler.cc
index fabe2039537..81877f13bcf 100644
--- a/chromium/chrome/browser/ui/webui/settings/safety_check_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/safety_check_handler.cc
@@ -455,6 +455,9 @@ base::string16 SafetyCheckHandler::GetStringForPasswords(
case PasswordsStatus::kError:
return l10n_util::GetStringUTF16(
IDS_SETTINGS_CHECK_PASSWORDS_ERROR_GENERIC);
+ case PasswordsStatus::kFeatureUnavailable:
+ return l10n_util::GetStringUTF16(
+ IDS_SETTINGS_SAFETY_CHECK_PASSWORDS_FEATURE_UNAVAILABLE);
}
}
@@ -571,6 +574,7 @@ void SafetyCheckHandler::DetermineIfNoPasswordsOrSafe(
void SafetyCheckHandler::OnVersionUpdaterResult(VersionUpdater::Status status,
int progress,
bool rollback,
+ bool powerwash,
const std::string& version,
int64_t update_size,
const base::string16& message) {
@@ -632,6 +636,9 @@ void SafetyCheckHandler::OnStateChanged(
Done(0), Total(0));
break;
case BulkLeakCheckService::State::kTokenRequestFailure:
+ OnPasswordsCheckResult(PasswordsStatus::kFeatureUnavailable,
+ Compromised(0), Done(0), Total(0));
+ break;
case BulkLeakCheckService::State::kHashingFailure:
case BulkLeakCheckService::State::kServiceError:
OnPasswordsCheckResult(PasswordsStatus::kError, Compromised(0), Done(0),
diff --git a/chromium/chrome/browser/ui/webui/settings/safety_check_handler.h b/chromium/chrome/browser/ui/webui/settings/safety_check_handler.h
index 0c73407ae34..8e6d9336183 100644
--- a/chromium/chrome/browser/ui/webui/settings/safety_check_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/safety_check_handler.h
@@ -30,7 +30,7 @@
// software.
class SafetyCheckHandler
: public settings::SettingsPageUIHandler,
- public password_manager::BulkLeakCheckService::Observer,
+ public password_manager::BulkLeakCheckServiceInterface::Observer,
public safety_check::SafetyCheck::SafetyCheckHandlerInterface {
public:
// The following enum represent the state of the safety check parent
@@ -70,8 +70,9 @@ class SafetyCheckHandler
kSignedOut = 5,
kQuotaLimit = 6,
kError = 7,
+ kFeatureUnavailable = 8,
// New enum values must go above here.
- kMaxValue = kError,
+ kMaxValue = kFeatureUnavailable,
};
enum class ExtensionsStatus {
kChecking = 0,
@@ -192,6 +193,7 @@ class SafetyCheckHandler
void OnVersionUpdaterResult(VersionUpdater::Status status,
int progress,
bool rollback,
+ bool powerwash,
const std::string& version,
int64_t update_size,
const base::string16& message);
@@ -235,12 +237,12 @@ class SafetyCheckHandler
std::unique_ptr<safety_check::UpdateCheckHelper> update_helper_;
std::unique_ptr<VersionUpdater> version_updater_;
- password_manager::BulkLeakCheckService* leak_service_ = nullptr;
+ password_manager::BulkLeakCheckServiceInterface* leak_service_ = nullptr;
extensions::PasswordsPrivateDelegate* passwords_delegate_ = nullptr;
extensions::ExtensionPrefs* extension_prefs_ = nullptr;
extensions::ExtensionServiceInterface* extension_service_ = nullptr;
- ScopedObserver<password_manager::BulkLeakCheckService,
- password_manager::BulkLeakCheckService::Observer>
+ ScopedObserver<password_manager::BulkLeakCheckServiceInterface,
+ password_manager::BulkLeakCheckServiceInterface::Observer>
observed_leak_check_{this};
base::WeakPtrFactory<SafetyCheckHandler> weak_ptr_factory_{this};
};
diff --git a/chromium/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc
index c6e18dd2c36..9a790eea198 100644
--- a/chromium/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc
@@ -793,6 +793,25 @@ TEST_F(SafetyCheckHandlerTest, CheckPasswords_Error) {
SafetyCheckHandler::PasswordsStatus::kError, 1);
}
+TEST_F(SafetyCheckHandlerTest, CheckPasswords_FeatureUnavailable) {
+ safety_check_->PerformSafetyCheck();
+ EXPECT_TRUE(test_passwords_delegate_.StartPasswordCheckTriggered());
+ static_cast<password_manager::BulkLeakCheckService::Observer*>(
+ safety_check_.get())
+ ->OnStateChanged(
+ password_manager::BulkLeakCheckService::State::kTokenRequestFailure);
+ const base::DictionaryValue* event =
+ GetSafetyCheckStatusChangedWithDataIfExists(
+ kPasswords,
+ static_cast<int>(
+ SafetyCheckHandler::PasswordsStatus::kFeatureUnavailable));
+ ASSERT_TRUE(event);
+ VerifyDisplayString(event, "Password check is not available in Chromium");
+ histogram_tester_.ExpectBucketCount(
+ "Settings.SafetyCheck.PasswordsResult",
+ SafetyCheckHandler::PasswordsStatus::kFeatureUnavailable, 1);
+}
+
TEST_F(SafetyCheckHandlerTest, CheckPasswords_RunningOneCompromised) {
test_passwords_delegate_.SetNumCompromisedCredentials(1);
safety_check_->PerformSafetyCheck();
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 8335deec5b6..831c737b3fa 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
@@ -254,8 +254,8 @@ void ClearBrowsingDataHandler::HandleClearBrowsingData(
if (!prefs->GetBoolean(prefs::kClearPluginLSODataEnabled))
site_data_mask &= ~ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PLUGIN_DATA;
- int remove_mask = 0;
- int origin_mask = 0;
+ uint64_t remove_mask = 0;
+ uint64_t origin_mask = 0;
std::vector<BrowsingDataType> data_type_vector;
const base::ListValue* data_type_list = nullptr;
CHECK(args->GetList(1, &data_type_list));
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler_browsertest.cc b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler_browsertest.cc
index 98dca3b412e..28c96790a03 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler_browsertest.cc
@@ -7,6 +7,7 @@
#include "base/values.h"
#include "chrome/browser/ui/web_applications/web_app_controller_browsertest.h"
+#include "chrome/browser/web_applications/test/web_app_test.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
@@ -98,13 +99,10 @@ IN_PROC_BROWSER_TEST_P(ClearBrowsingDataHandlerBrowserTest, GetInstalledApps) {
ASSERT_EQ(url.host(), *(installed_app.FindStringKey("registerableDomain")));
}
-INSTANTIATE_TEST_SUITE_P(
- All,
- ClearBrowsingDataHandlerBrowserTest,
- ::testing::Values(
- web_app::ControllerType::kHostedAppController,
- web_app::ControllerType::kUnifiedControllerWithBookmarkApp,
- web_app::ControllerType::kUnifiedControllerWithWebApp),
- web_app::ControllerTypeParamToString);
+INSTANTIATE_TEST_SUITE_P(All,
+ ClearBrowsingDataHandlerBrowserTest,
+ ::testing::Values(web_app::ProviderType::kBookmarkApps,
+ web_app::ProviderType::kWebApps),
+ web_app::ProviderTypeParamToString);
} // namespace settings
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 eff2694ecfd..ccb1ccca58c 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
@@ -99,8 +99,9 @@
#include "components/prefs/pref_service.h"
#include "components/user_manager/user_manager.h"
#include "ui/chromeos/devicetype_utils.h"
-#else
+#else // !defined(OS_CHROMEOS)
#include "chrome/browser/ui/webui/settings/system_handler.h"
+#include "ui/accessibility/accessibility_features.h"
#endif
#if defined(OS_WIN)
@@ -156,6 +157,9 @@ void AddCommonStrings(content::WebUIDataSource* html_source, Profile* profile) {
{"settings", IDS_SETTINGS_SETTINGS},
{"settingsAltPageTitle", IDS_SETTINGS_ALT_PAGE_TITLE},
{"subpageArrowRoleDescription", IDS_SETTINGS_SUBPAGE_BUTTON},
+ {"subpageBackButtonAriaLabel", IDS_SETTINGS_SUBPAGE_BACK_BUTTON_ARIA_LABEL},
+ {"subpageBackButtonAriaRoleDescription",
+ IDS_SETTINGS_SUBPAGE_BACK_BUTTON_ARIA_ROLE_DESCRIPTION},
{"notValid", IDS_SETTINGS_NOT_VALID},
{"notValidWebAddress", IDS_SETTINGS_NOT_VALID_WEB_ADDRESS},
{"notValidWebAddressForContentType",
@@ -203,6 +207,9 @@ void AddA11yStrings(content::WebUIDataSource* html_source) {
{"manageAccessibilityFeatures",
IDS_SETTINGS_ACCESSIBILITY_MANAGE_ACCESSIBILITY_FEATURES},
{"androidAppsManageAppLinks", IDS_SETTINGS_ANDROID_APPS_MANAGE_APP_LINKS},
+#else // !defined(OS_CHROMEOS)
+ {"focusHighlightLabel",
+ IDS_SETTINGS_ACCESSIBILITY_FOCUS_HIGHLIGHT_DESCRIPTION},
#endif
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings);
@@ -215,6 +222,12 @@ void AddA11yStrings(content::WebUIDataSource* html_source) {
"showExperimentalA11yLabels",
base::FeatureList::IsEnabled(features::kExperimentalAccessibilityLabels));
+#if !defined(OS_CHROMEOS)
+ html_source->AddBoolean(
+ "showFocusHighlightOption",
+ base::FeatureList::IsEnabled(features::kAccessibilityFocusHighlight));
+#endif
+
html_source->AddBoolean("enableLiveCaption",
base::FeatureList::IsEnabled(media::kLiveCaption));
@@ -460,7 +473,7 @@ void AddChromeCleanupStrings(content::WebUIDataSource* html_source) {
IDS_SETTINGS_RESET_CLEANUP_EXPLANATION_CURRENTLY_REMOVING},
{"chromeCleanupExplanationScanError",
IDS_SETTINGS_RESET_CLEANUP_EXPLANATION_SCAN_ERROR},
- {"chromeCleanupFindButtonLable",
+ {"chromeCleanupFindButtonLabel",
IDS_SETTINGS_RESET_CLEANUP_FIND_BUTTON_LABEL},
{"chromeCleanupLinkShowItems",
IDS_SETTINGS_RESET_CLEANUP_LINK_SHOW_FILES},
@@ -769,6 +782,7 @@ void AddAutofillStrings(content::WebUIDataSource* html_source,
static constexpr webui::LocalizedString kLocalizedStrings[] = {
{"autofillPageTitle", IDS_SETTINGS_AUTOFILL},
{"passwords", IDS_SETTINGS_PASSWORDS},
+ {"passwordsDevice", IDS_SETTINGS_DEVICE_PASSWORDS},
{"checkPasswords", IDS_SETTINGS_CHECK_PASSWORDS},
{"checkPasswordsCanceled", IDS_SETTINGS_CHECK_PASSWORDS_CANCELED},
{"checkedPasswords", IDS_SETTINGS_CHECKED_PASSWORDS},
@@ -817,8 +831,7 @@ void AddAutofillStrings(content::WebUIDataSource* html_source,
IDS_SETTINGS_COMPROMISED_EDIT_PASSWORD_APP},
{"alreadyChangedPasswordLink",
IDS_SETTINGS_COMPROMISED_ALREADY_CHANGED_PASSWORD},
- {"editDisclaimerTitle",
- IDS_SETTINGS_COMPROMISED_EDIT_DISCLAIMER_TITLE},
+ {"editDisclaimerTitle", IDS_SETTINGS_COMPROMISED_EDIT_DISCLAIMER_TITLE},
{"editDisclaimerDescription",
IDS_SETTINGS_COMPROMISED_EDIT_DISCLAIMER_DESCRIPTION},
{"creditCards", IDS_AUTOFILL_PAYMENT_METHODS},
@@ -846,6 +859,8 @@ void AddAutofillStrings(content::WebUIDataSource* html_source,
{"creditCardType", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_TYPE_COLUMN_LABEL},
{"creditCardExpiration", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_DATE},
{"creditCardName", IDS_SETTINGS_NAME_ON_CREDIT_CARD},
+ {"creditCardNickname", IDS_SETTINGS_CREDIT_CARD_NICKNAME},
+ {"creditCardNicknameInvalid", IDS_SETTINGS_CREDIT_CARD_NICKNAME_INVALID},
{"creditCardNumber", IDS_SETTINGS_CREDIT_CARD_NUMBER},
{"creditCardExpirationMonth", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_MONTH},
{"creditCardExpirationYear", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_YEAR},
@@ -874,6 +889,10 @@ void AddAutofillStrings(content::WebUIDataSource* html_source,
IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_SIGNED_OUT_ENABLED_DESC},
{"savedPasswordsHeading", IDS_SETTINGS_PASSWORDS_SAVED_HEADING},
{"passwordExceptionsHeading", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_HEADING},
+ {"deviceOnlyPasswordsHeading",
+ IDS_SETTINGS_DEVICE_PASSWORDS_ON_DEVICE_ONLY_HEADING},
+ {"deviceAndAccountPasswordsHeading",
+ IDS_SETTINGS_DEVICE_PASSWORDS_ON_DEVICE_AND_ACCOUNT_HEADING},
{"deletePasswordException", IDS_SETTINGS_PASSWORDS_DELETE_EXCEPTION},
{"removePassword", IDS_SETTINGS_PASSWORD_REMOVE},
{"searchPasswords", IDS_SETTINGS_PASSWORD_SEARCH},
@@ -882,6 +901,10 @@ void AddAutofillStrings(content::WebUIDataSource* html_source,
{"passwordDetailsTitle", IDS_SETTINGS_PASSWORDS_VIEW_DETAILS_TITLE},
{"passwordViewDetails", IDS_SETTINGS_PASSWORD_DETAILS},
{"copyPassword", IDS_SETTINGS_PASSWORD_COPY},
+ {"passwordStoredOnDevice", IDS_SETTINGS_PASSWORD_STORED_ON_DEVICE},
+ {"passwordStoredInAccount", IDS_SETTINGS_PASSWORD_STORED_IN_ACCOUNT},
+ {"passwordStoredInAccountAndOnDevice",
+ IDS_SETTINGS_PASSWORD_STORED_IN_ACCOUNT_AND_ON_DEVICE},
{"editPasswordWebsiteLabel", IDS_SETTINGS_PASSWORDS_WEBSITE},
{"editPasswordUsernameLabel", IDS_SETTINGS_PASSWORDS_USERNAME},
{"editPasswordPasswordLabel", IDS_SETTINGS_PASSWORDS_PASSWORD},
@@ -895,11 +918,38 @@ void AddAutofillStrings(content::WebUIDataSource* html_source,
{"optOutAccountStorageLabel",
IDS_SETTINGS_PASSWORDS_OPT_OUT_ACCOUNT_STORAGE_LABEL},
{"undoRemovePassword", IDS_SETTINGS_PASSWORD_UNDO},
+ {"movePasswordToAccount", IDS_SETTINGS_PASSWORD_MOVE_TO_ACCOUNT},
{"passwordDeleted", IDS_SETTINGS_PASSWORD_DELETED_PASSWORD},
{"passwordDeletedFromDevice",
IDS_SETTINGS_PASSWORD_DELETED_PASSWORD_FROM_DEVICE},
{"passwordDeletedFromAccount",
IDS_SETTINGS_PASSWORD_DELETED_PASSWORD_FROM_ACCOUNT},
+ {"passwordDeletedFromAccountAndDevice",
+ IDS_SETTINGS_PASSWORD_DELETED_PASSWORD_FROM_ACCOUNT_AND_DEVICE},
+ {"passwordMoveToAccountDialogTitle",
+ IDS_SETTINGS_PASSWORD_MOVE_TO_ACCOUNT_DIALOG_TITLE},
+ {"passwordMoveToAccountDialogBody",
+ IDS_SETTINGS_PASSWORD_MOVE_TO_ACCOUNT_DIALOG_BODY},
+ {"passwordMoveToAccountDialogMoveButtonText",
+ IDS_SETTINGS_PASSWORD_MOVE_TO_ACCOUNT_DIALOG_MOVE_BUTTON_TEXT},
+ {"passwordMoveToAccountDialogCancelButtonText",
+ IDS_SETTINGS_PASSWORD_MOVE_TO_ACCOUNT_DIALOG_CANCEL_BUTTON_TEXT},
+ {"passwordRemoveDialogTitle", IDS_SETTINGS_PASSWORD_REMOVE_DIALOG_TITLE},
+ {"passwordRemoveDialogBody", IDS_SETTINGS_PASSWORD_REMOVE_DIALOG_BODY},
+ {"passwordRemoveDialogRemoveButtonText",
+ IDS_SETTINGS_PASSWORD_REMOVE_DIALOG_REMOVE_BUTTON_TEXT},
+ {"passwordRemoveDialogCancelButtonText",
+ IDS_SETTINGS_PASSWORD_REMOVE_DIALOG_CANCEL_BUTTON_TEXT},
+ {"passwordRemoveDialogFromAccountCheckboxLabel",
+ IDS_SETTINGS_PASSWORD_REMOVE_DIALOG_FROM_ACCOUNT_CHECKBOX_LABEL},
+ {"passwordRemoveDialogFromDeviceCheckboxLabel",
+ IDS_SETTINGS_PASSWORD_REMOVE_DIALOG_FROM_DEVICE_CHECKBOX_LABEL},
+ {"devicePasswordsLinkLabelSingular",
+ IDS_SETTINGS_DEVICE_PASSWORDS_LINK_LABEL_SINGULAR},
+ {"devicePasswordsLinkLabelPlural",
+ IDS_SETTINGS_DEVICE_PASSWORDS_LINK_LABEL_PLURAL},
+ {"devicePasswordsLinkSubLabel",
+ IDS_SETTINGS_DEVICE_PASSWORDS_LINK_SUB_LABEL},
{"passwordRowMoreActionsButton", IDS_SETTINGS_PASSWORD_ROW_MORE_ACTIONS},
{"passwordRowFederatedMoreActionsButton",
IDS_SETTINGS_PASSWORD_ROW_FEDERATED_MORE_ACTIONS},
@@ -916,6 +966,8 @@ void AddAutofillStrings(content::WebUIDataSource* html_source,
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ENOUGH_SPACE},
{"exportPasswordsFailTipsAnotherFolder",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ANOTHER_FOLDER},
+ {"managePasswordsPlaintext",
+ IDS_SETTINGS_PASSWORDS_MANAGE_PASSWORDS_PLAINTEXT},
{"savedToThisDeviceOnly",
IDS_SETTINGS_PAYMENTS_SAVED_TO_THIS_DEVICE_ONLY}};
@@ -928,6 +980,16 @@ void AddAutofillStrings(content::WebUIDataSource* html_source,
IDS_SETTINGS_PASSWORDS_MANAGE_PASSWORDS,
base::UTF8ToUTF16(google_password_manager_url.spec())));
html_source->AddString(
+ "optInAccountStorageBody",
+ l10n_util::GetStringFUTF16(
+ IDS_SETTINGS_PASSWORDS_OPT_IN_ACCOUNT_STORAGE_BODY,
+ base::UTF8ToUTF16(google_password_manager_url.spec())));
+ html_source->AddString(
+ "optOutAccountStorageBody",
+ l10n_util::GetStringFUTF16(
+ IDS_SETTINGS_PASSWORDS_OPT_OUT_ACCOUNT_STORAGE_BODY,
+ base::UTF8ToUTF16(google_password_manager_url.spec())));
+ html_source->AddString(
"checkPasswordsErrorQuotaGoogleAccount",
l10n_util::GetStringFUTF16(
IDS_SETTINGS_CHECK_PASSWORDS_ERROR_QUOTA_LIMIT_GOOGLE_ACCOUNT,
@@ -951,6 +1013,11 @@ void AddAutofillStrings(content::WebUIDataSource* html_source,
autofill::payments::GetManageInstrumentsUrl().spec());
html_source->AddString("paymentMethodsLearnMoreURL",
chrome::kPaymentMethodsLearnMoreURL);
+ html_source->AddString(
+ "siteSettingsFlashWildcardsUnsupported",
+ l10n_util::GetStringFUTF16(
+ IDS_SETTINGS_SITE_SETTINGS_FLASH_WILDCARD_UNSUPPORTED,
+ base::UTF8ToUTF16(chrome::kChromeFlashRoadmapURL)));
bool is_guest_mode = false;
#if defined(OS_CHROMEOS)
@@ -982,6 +1049,10 @@ void AddAutofillStrings(content::WebUIDataSource* html_source,
base::FeatureList::IsEnabled(
autofill::features::kAutofillSaveAndFillVPA));
+ html_source->AddBoolean(
+ "nicknameManagementEnabled",
+ base::FeatureList::IsEnabled(
+ autofill::features::kAutofillEnableCardNicknameManagement));
AddLocalizedStringsBulk(html_source, kLocalizedStrings);
}
@@ -989,15 +1060,15 @@ void AddSignOutDialogStrings(content::WebUIDataSource* html_source,
Profile* profile) {
#if defined(OS_CHROMEOS)
bool is_dice_enabled = false;
- bool is_split_sync_consent_enabled =
- chromeos::features::IsSplitSyncConsentEnabled();
+ bool use_browser_sync_consent =
+ chromeos::features::ShouldUseBrowserSyncConsent();
#else
bool is_dice_enabled =
AccountConsistencyModeManager::IsDiceEnabledForProfile(profile);
- bool is_split_sync_consent_enabled = false;
+ bool use_browser_sync_consent = false;
#endif
- if (is_split_sync_consent_enabled || is_dice_enabled) {
+ if (use_browser_sync_consent || is_dice_enabled) {
static constexpr webui::LocalizedString kTurnOffStrings[] = {
{"syncDisconnect", IDS_SETTINGS_PEOPLE_SYNC_TURN_OFF},
{"syncDisconnectTitle",
@@ -1136,6 +1207,10 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source,
static constexpr webui::LocalizedString kLocalizedStrings[] = {
{"privacyPageTitle", IDS_SETTINGS_PRIVACY},
{"privacyPageMore", IDS_SETTINGS_PRIVACY_MORE},
+ // TODO(crbug.com/1116608): This seemingly unrelated string resource is
+ // used because it already has a localized version available in M85, so
+ // we can ship this label in M85 on short notice.
+ {"discardedPerSiteSetting", IDS_POLICY_LABEL_IGNORED},
{"doNotTrack", IDS_SETTINGS_ENABLE_DO_NOT_TRACK},
{"doNotTrackDialogTitle", IDS_SETTINGS_ENABLE_DO_NOT_TRACK_DIALOG_TITLE},
// TODO(crbug.com/1062607): This string is no longer used. Remove.
@@ -1293,6 +1368,10 @@ void AddPrivacyStrings(content::WebUIDataSource* html_source,
IDS_SETTINGS_SAFETY_CHECK_EXTENSIONS_PRIMARY_LABEL},
{"safetyCheckExtensionsButtonAriaLabel",
IDS_SETTINGS_SAFETY_CHECK_EXTENSIONS_BUTTON_ARIA_LABEL},
+ {"safetyCheckChromeCleanerPrimaryLabel",
+ IDS_SETTINGS_SAFETY_CHECK_CHROME_CLEANER_PRIMARY_LABEL},
+ {"safetyCheckChromeCleanerButtonAriaLabel",
+ IDS_SETTINGS_SAFETY_CHECK_CHROME_CLEANER_BUTTON_ARIA_LABEL},
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings);
@@ -1401,8 +1480,6 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source,
Profile* profile) {
static constexpr webui::LocalizedString kLocalizedStrings[] = {
{"addSite", IDS_SETTINGS_ADD_SITE},
- {"addSiteExceptionPlaceholder",
- IDS_SETTINGS_ADD_SITE_EXCEPTION_PLACEHOLDER},
{"addSiteTitle", IDS_SETTINGS_ADD_SITE_TITLE},
#if defined(OS_CHROMEOS)
{"androidSmsNote", IDS_SETTINGS_ANDROID_SMS_NOTE},
@@ -1710,6 +1787,7 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source,
{"siteSettingsSourcePolicyAsk", IDS_PAGE_INFO_PERMISSION_ASK_BY_POLICY},
{"siteSettingsAdsBlockNotBlacklistedSingular",
IDS_SETTINGS_SITE_SETTINGS_ADS_BLOCK_NOT_BLACKLISTED_SINGULAR},
+ {"siteSettingsAllowlisted", IDS_SETTINGS_SITE_SETTINGS_ALLOWLISTED},
{"siteSettingsAdsBlockBlacklistedSingular",
IDS_SETTINGS_SITE_SETTINGS_ADS_BLOCK_BLACKLISTED_SINGULAR},
{"siteSettingsSourceDrmDisabled",
@@ -1853,6 +1931,8 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source,
IDS_SETTINGS_SITE_SETTINGS_WINDOW_PLACEMENT},
{"siteSettingsWindowPlacementAsk",
IDS_SETTINGS_SITE_SETTINGS_WINDOW_PLACEMENT_ASK},
+ {"siteSettingsWindowPlacementAskRecommended",
+ IDS_SETTINGS_SITE_SETTINGS_WINDOW_PLACEMENT_ASK_RECOMMENDED},
{"siteSettingsWindowPlacementBlock",
IDS_SETTINGS_SITE_SETTINGS_WINDOW_PLACEMENT_BLOCK},
};
@@ -1928,9 +2008,8 @@ void AddSiteSettingsStrings(content::WebUIDataSource* html_source,
base::FeatureList::IsEnabled(
features::kWebBluetoothNewPermissionsBackend));
- html_source->AddBoolean(
- "enableWebXrContentSetting",
- base::FeatureList::IsEnabled(features::kWebXrPermissionsApi));
+ // The exception placeholder should not be translated. See crbug.com/1095878.
+ html_source->AddString("addSiteExceptionPlaceholder", "[*.]example.com");
}
#if !defined(OS_CHROMEOS)
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 83923229636..a06c62efb33 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
@@ -11,7 +11,6 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/value_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/gaia_info_update_service.h"
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler.cc b/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler.cc
index b0818ee920f..85887e9be9a 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler.cc
@@ -8,7 +8,6 @@
#include <utility>
#include "base/bind.h"
-#include "base/metrics/histogram_macros.h"
#include "base/rand_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/net/secure_dns_config.h"
@@ -24,10 +23,12 @@
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "net/dns/public/dns_over_https_server_config.h"
-#include "net/dns/public/doh_provider_list.h"
+#include "net/dns/public/doh_provider_entry.h"
#include "net/dns/public/util.h"
#include "ui/base/l10n/l10n_util.h"
+namespace secure_dns = chrome_browser_net::secure_dns;
+
namespace settings {
namespace {
@@ -57,11 +58,7 @@ std::unique_ptr<base::DictionaryValue> CreateSecureDnsSettingDict() {
} // namespace
-SecureDnsHandler::SecureDnsHandler()
- : network_context_getter_(
- base::BindRepeating(&SecureDnsHandler::GetNetworkContext,
- base::Unretained(this))) {}
-
+SecureDnsHandler::SecureDnsHandler() = default;
SecureDnsHandler::~SecureDnsHandler() = default;
void SecureDnsHandler::RegisterMessages() {
@@ -111,38 +108,14 @@ void SecureDnsHandler::OnJavascriptDisallowed() {
pref_registrar_.RemoveAll();
}
-base::Value SecureDnsHandler::GetSecureDnsResolverListForCountry(
- int country_id,
- const std::vector<net::DohProviderEntry>& providers) {
- std::vector<std::string> disabled_providers =
- SplitString(features::kDnsOverHttpsDisabledProvidersParam.Get(), ",",
- base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
-
+base::Value SecureDnsHandler::GetSecureDnsResolverList() {
base::Value resolvers(base::Value::Type::LIST);
- resolver_histogram_map_.clear();
- // Add all non-disabled resolvers that should be displayed in |country_id|.
- for (const auto& entry : providers) {
- if (base::Contains(disabled_providers, entry.provider))
- continue;
-
- if (entry.display_globally ||
- std::find_if(
- entry.display_countries.begin(), entry.display_countries.end(),
- [&country_id](const std::string& country_code) {
- return country_codes::CountryCharsToCountryID(
- country_code[0], country_code[1]) == country_id;
- }) != entry.display_countries.end()) {
- DCHECK(!entry.ui_name.empty());
- DCHECK(!entry.privacy_policy.empty());
- base::Value dict(base::Value::Type::DICTIONARY);
- dict.SetKey("name", base::Value(entry.ui_name));
- dict.SetKey("value", base::Value(entry.dns_over_https_template));
- dict.SetKey("policy", base::Value(entry.privacy_policy));
- resolvers.Append(std::move(dict));
- DCHECK(entry.provider_id_for_histogram.has_value());
- resolver_histogram_map_.insert({entry.dns_over_https_template,
- entry.provider_id_for_histogram.value()});
- }
+ for (const auto* entry : providers_) {
+ base::Value dict(base::Value::Type::DICTIONARY);
+ dict.SetStringKey("name", entry->ui_name);
+ dict.SetStringKey("value", entry->dns_over_https_template);
+ dict.SetStringKey("policy", entry->privacy_policy);
+ resolvers.Append(std::move(dict));
}
// Randomize the order of the resolvers.
@@ -150,13 +123,10 @@ base::Value SecureDnsHandler::GetSecureDnsResolverListForCountry(
// Add a custom option to the front of the list
base::Value custom(base::Value::Type::DICTIONARY);
- custom.SetKey("name",
- base::Value(l10n_util::GetStringUTF8(IDS_SETTINGS_CUSTOM)));
- custom.SetKey("value", base::Value("custom"));
- custom.SetKey("policy", base::Value(std::string()));
+ custom.SetStringKey("name", l10n_util::GetStringUTF8(IDS_SETTINGS_CUSTOM));
+ custom.SetStringKey("value", std::string()); // Empty value means custom.
+ custom.SetStringKey("policy", std::string());
resolvers.Insert(resolvers.GetList().begin(), std::move(custom));
- resolver_histogram_map_.insert(
- {"custom", net::DohProviderIdForHistogram::kCustom});
return resolvers;
}
@@ -176,15 +146,18 @@ network::mojom::NetworkContext* SecureDnsHandler::GetNetworkContext() {
->GetNetworkContext();
}
+void SecureDnsHandler::SetProvidersForTesting(
+ net::DohProviderEntry::List providers) {
+ providers_ = std::move(providers);
+}
+
void SecureDnsHandler::HandleGetSecureDnsResolverList(
const base::ListValue* args) {
AllowJavascript();
std::string callback_id = args->GetList()[0].GetString();
- ResolveJavascriptCallback(
- base::Value(callback_id),
- GetSecureDnsResolverListForCountry(country_codes::GetCurrentCountryID(),
- net::GetDohProviderList()));
+ ResolveJavascriptCallback(base::Value(callback_id),
+ GetSecureDnsResolverList());
}
void SecureDnsHandler::HandleGetSecureDnsSetting(const base::ListValue* args) {
@@ -203,14 +176,12 @@ void SecureDnsHandler::HandleParseCustomDnsEntry(const base::ListValue* args) {
// Return all templates in the entry, or none if they are not all valid.
base::Value templates(base::Value::Type::LIST);
- if (chrome_browser_net::secure_dns::IsValidGroup(custom_entry)) {
- for (base::StringPiece t :
- chrome_browser_net::secure_dns::SplitGroup(custom_entry)) {
+ if (secure_dns::IsValidGroup(custom_entry)) {
+ for (base::StringPiece t : secure_dns::SplitGroup(custom_entry)) {
templates.Append(t);
}
}
- UMA_HISTOGRAM_BOOLEAN("Net.DNS.UI.ValidationAttemptSuccess",
- !templates.GetList().empty());
+ secure_dns::UpdateValidationHistogram(!templates.GetList().empty());
ResolveJavascriptCallback(*callback_id, templates);
}
@@ -236,7 +207,7 @@ void SecureDnsHandler::HandleProbeCustomDnsTemplate(
overrides.attempts = 1;
overrides.randomize_ports = false;
overrides.secure_dns_mode = net::DnsConfig::SecureDnsMode::SECURE;
- chrome_browser_net::secure_dns::ApplyTemplate(&overrides, server_template);
+ secure_dns::ApplyTemplate(&overrides, server_template);
DCHECK(!runner_);
runner_ = std::make_unique<chrome_browser_net::DnsProbeRunner>(
overrides, network_context_getter_);
@@ -251,29 +222,15 @@ void SecureDnsHandler::HandleRecordUserDropdownInteraction(
std::string new_provider;
CHECK(args->GetString(0, &old_provider));
CHECK(args->GetString(1, &new_provider));
- DCHECK(resolver_histogram_map_.find(old_provider) !=
- resolver_histogram_map_.end());
- DCHECK(resolver_histogram_map_.find(new_provider) !=
- resolver_histogram_map_.end());
- for (auto& pair : resolver_histogram_map_) {
- if (pair.first == old_provider) {
- UMA_HISTOGRAM_ENUMERATION("Net.DNS.UI.DropdownSelectionEvent.Unselected",
- pair.second);
- } else if (pair.first == new_provider) {
- UMA_HISTOGRAM_ENUMERATION("Net.DNS.UI.DropdownSelectionEvent.Selected",
- pair.second);
- } else {
- UMA_HISTOGRAM_ENUMERATION("Net.DNS.UI.DropdownSelectionEvent.Ignored",
- pair.second);
- }
- }
+
+ secure_dns::UpdateDropdownHistograms(providers_, old_provider, new_provider);
}
void SecureDnsHandler::OnProbeComplete() {
bool success =
runner_->result() == chrome_browser_net::DnsProbeRunner::CORRECT;
runner_.reset();
- UMA_HISTOGRAM_BOOLEAN("Net.DNS.UI.ProbeAttemptSuccess", success);
+ secure_dns::UpdateProbeHistogram(success);
ResolveJavascriptCallback(base::Value(probe_callback_id_),
base::Value(success));
probe_callback_id_.clear();
@@ -284,4 +241,12 @@ void SecureDnsHandler::SendSecureDnsSettingUpdatesToJavascript() {
*CreateSecureDnsSettingDict());
}
+// static
+net::DohProviderEntry::List SecureDnsHandler::GetFilteredProviders() {
+ const auto local_providers = secure_dns::ProvidersForCountry(
+ net::DohProviderEntry::GetList(), country_codes::GetCurrentCountryID());
+ return secure_dns::RemoveDisabledProviders(
+ local_providers, secure_dns::GetDisabledProviders());
+}
+
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler.h b/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler.h
index 9f7622ae20d..dddaea2127a 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler.h
@@ -9,12 +9,13 @@
#include <string>
#include <vector>
+#include "base/bind.h"
#include "base/macros.h"
#include "base/values.h"
#include "chrome/browser/net/dns_probe_runner.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "components/prefs/pref_change_registrar.h"
-#include "net/dns/public/doh_provider_list.h"
+#include "net/dns/public/doh_provider_entry.h"
#include "services/network/public/cpp/resolve_host_client_base.h"
#include "services/network/public/mojom/network_context.mojom.h"
@@ -35,13 +36,15 @@ class SecureDnsHandler : public SettingsPageUIHandler {
// as a dictionary with the following keys: "name" (the text to display in the
// UI), "value" (the DoH template for this provider), and "policy" (the URL of
// the provider's privacy policy).
- base::Value GetSecureDnsResolverListForCountry(
- int country_id,
- const std::vector<net::DohProviderEntry>& providers);
+ base::Value GetSecureDnsResolverList();
void SetNetworkContextForTesting(
network::mojom::NetworkContext* network_context);
+ // DohProviderEntry cannot be copied, so the entries referenced in |providers|
+ // must be long-lived.
+ void SetProvidersForTesting(net::DohProviderEntry::List providers);
+
protected:
// Retrieves all pre-approved secure resolvers and returns them to WebUI.
void HandleGetSecureDnsResolverList(const base::ListValue* args);
@@ -66,10 +69,14 @@ class SecureDnsHandler : public SettingsPageUIHandler {
network::mojom::NetworkContext* GetNetworkContext();
void OnProbeComplete();
- std::map<std::string, net::DohProviderIdForHistogram> resolver_histogram_map_;
+ static net::DohProviderEntry::List GetFilteredProviders();
+
+ net::DohProviderEntry::List providers_ = GetFilteredProviders();
std::unique_ptr<chrome_browser_net::DnsProbeRunner> runner_;
chrome_browser_net::DnsProbeRunner::NetworkContextGetter
- network_context_getter_;
+ network_context_getter_ =
+ base::BindRepeating(&SecureDnsHandler::GetNetworkContext,
+ base::Unretained(this));
// ID of the Javascript callback for the current pending probe, or "" if
// there is no probe currently in progress.
std::string probe_callback_id_;
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler_browsertest.cc b/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler_browsertest.cc
index 3ece9212741..81aa1024fc1 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler_browsertest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/settings_secure_dns_handler_browsertest.cc
@@ -27,7 +27,6 @@
#include "base/win/win_util.h"
#endif
-using net::DohProviderEntry;
using testing::_;
using testing::IsEmpty;
using testing::Return;
@@ -43,47 +42,38 @@ constexpr char kRecordUserDropdownInteraction[] =
"recordUserDropdownInteraction";
constexpr char kWebUiFunctionName[] = "webUiCallbackName";
-const std::vector<DohProviderEntry>& GetDohProviderListForTesting() {
- static const base::NoDestructor<std::vector<DohProviderEntry>> test_providers{
- {
- DohProviderEntry(
- "Provider_Global1", net::DohProviderIdForHistogram(-1),
- {} /*ip_strs */, {} /* dot_hostnames */,
- "https://global1.provider/dns-query{?dns}",
- "Global Provider 1" /* ui_name */,
- "https://global1.provider/privacy_policy/" /* privacy_policy */,
- true /* display_globally */, {} /* display_countries */),
- DohProviderEntry(
- "Provider_NoDisplay", net::DohProviderIdForHistogram(-2),
- {} /*ip_strs */, {} /* dot_hostnames */,
- "https://nodisplay.provider/dns-query{?dns}",
- "No Display Provider" /* ui_name */,
- "https://nodisplay.provider/privacy_policy/" /* privacy_policy */,
- false /* display_globally */, {} /* display_countries */),
- DohProviderEntry(
- "Provider_EE_FR", net::DohProviderIdForHistogram(-3),
- {} /*ip_strs */, {} /* dot_hostnames */,
- "https://ee.fr.provider/dns-query{?dns}",
- "EE/FR Provider" /* ui_name */,
- "https://ee.fr.provider/privacy_policy/" /* privacy_policy */,
- false /* display_globally */,
- {"EE", "FR"} /* display_countries */),
- DohProviderEntry(
- "Provider_FR", net::DohProviderIdForHistogram(-4),
- {} /*ip_strs */, {} /* dot_hostnames */,
- "https://fr.provider/dns-query{?dns}",
- "FR Provider" /* ui_name */,
- "https://fr.provider/privacy_policy/" /* privacy_policy */,
- false /* display_globally */, {"FR"} /* display_countries */),
- DohProviderEntry(
- "Provider_Global2", net::DohProviderIdForHistogram(-5),
- {} /*ip_strs */, {} /* dot_hostnames */,
- "https://global2.provider/dns-query{?dns}",
- "Global Provider 2" /* ui_name */,
- "https://global2.provider/privacy_policy/" /* privacy_policy */,
- true /* display_globally */, {} /* display_countries */),
- }};
- return *test_providers;
+net::DohProviderEntry::List GetDohProviderListForTesting() {
+ static const auto global1 = net::DohProviderEntry::ConstructForTesting(
+ "Provider_Global1", net::DohProviderIdForHistogram(-1), {} /*ip_strs */,
+ {} /* dot_hostnames */, "https://global1.provider/dns-query{?dns}",
+ "Global Provider 1" /* ui_name */,
+ "https://global1.provider/privacy_policy/" /* privacy_policy */,
+ true /* display_globally */, {} /* display_countries */);
+ static const auto no_display = net::DohProviderEntry::ConstructForTesting(
+ "Provider_NoDisplay", net::DohProviderIdForHistogram(-2), {} /*ip_strs */,
+ {} /* dot_hostnames */, "https://nodisplay.provider/dns-query{?dns}",
+ "No Display Provider" /* ui_name */,
+ "https://nodisplay.provider/privacy_policy/" /* privacy_policy */,
+ false /* display_globally */, {} /* display_countries */);
+ static const auto ee_fr = net::DohProviderEntry::ConstructForTesting(
+ "Provider_EE_FR", net::DohProviderIdForHistogram(-3), {} /*ip_strs */,
+ {} /* dot_hostnames */, "https://ee.fr.provider/dns-query{?dns}",
+ "EE/FR Provider" /* ui_name */,
+ "https://ee.fr.provider/privacy_policy/" /* privacy_policy */,
+ false /* display_globally */, {"EE", "FR"} /* display_countries */);
+ static const auto fr = net::DohProviderEntry::ConstructForTesting(
+ "Provider_FR", net::DohProviderIdForHistogram(-4), {} /*ip_strs */,
+ {} /* dot_hostnames */, "https://fr.provider/dns-query{?dns}",
+ "FR Provider" /* ui_name */,
+ "https://fr.provider/privacy_policy/" /* privacy_policy */,
+ false /* display_globally */, {"FR"} /* display_countries */);
+ static const auto global2 = net::DohProviderEntry::ConstructForTesting(
+ "Provider_Global2", net::DohProviderIdForHistogram(-5), {} /*ip_strs */,
+ {} /* dot_hostnames */, "https://global2.provider/dns-query{?dns}",
+ "Global Provider 2" /* ui_name */,
+ "https://global2.provider/privacy_policy/" /* privacy_policy */,
+ true /* display_globally */, {} /* display_countries */);
+ return {&global1, &no_display, &ee_fr, &fr, &global2};
}
bool FindDropdownItem(const base::Value& resolvers,
@@ -315,116 +305,40 @@ IN_PROC_BROWSER_TEST_F(SecureDnsHandlerTest, DropdownList) {
// Check results.
base::Value::ConstListView resolver_list = call_data.arg3()->GetList();
ASSERT_GE(resolver_list.size(), 1U);
- EXPECT_EQ("custom", resolver_list[0].FindKey("value")->GetString());
+ EXPECT_TRUE(resolver_list[0].FindKey("value")->GetString().empty());
}
-IN_PROC_BROWSER_TEST_F(SecureDnsHandlerTest, DropdownListForCountry) {
- // The 'EE' list should start with the custom entry, followed by the two
- // global providers and the 'EE' provider in some random order.
- base::Value resolver_list = handler_->GetSecureDnsResolverListForCountry(
- country_codes::CountryCharsToCountryID('E', 'E'),
- GetDohProviderListForTesting());
- EXPECT_EQ(4u, resolver_list.GetList().size());
- EXPECT_EQ("custom", resolver_list.GetList()[0].FindKey("value")->GetString());
- EXPECT_TRUE(FindDropdownItem(resolver_list, "Global Provider 1",
- "https://global1.provider/dns-query{?dns}",
- "https://global1.provider/privacy_policy/"));
- EXPECT_TRUE(FindDropdownItem(resolver_list, "Global Provider 2",
- "https://global2.provider/dns-query{?dns}",
- "https://global2.provider/privacy_policy/"));
- EXPECT_TRUE(FindDropdownItem(resolver_list, "EE/FR Provider",
- "https://ee.fr.provider/dns-query{?dns}",
- "https://ee.fr.provider/privacy_policy/"));
-
- // The 'FR' list should start with the custom entry, followed by the two
- // global providers and the two 'FR' providers in some random order.
- resolver_list = handler_->GetSecureDnsResolverListForCountry(
- country_codes::CountryCharsToCountryID('F', 'R'),
- GetDohProviderListForTesting());
- EXPECT_EQ(5u, resolver_list.GetList().size());
- EXPECT_EQ("custom", resolver_list.GetList()[0].FindKey("value")->GetString());
- EXPECT_TRUE(FindDropdownItem(resolver_list, "Global Provider 1",
- "https://global1.provider/dns-query{?dns}",
- "https://global1.provider/privacy_policy/"));
- EXPECT_TRUE(FindDropdownItem(resolver_list, "Global Provider 2",
- "https://global2.provider/dns-query{?dns}",
- "https://global2.provider/privacy_policy/"));
- EXPECT_TRUE(FindDropdownItem(resolver_list, "EE/FR Provider",
- "https://ee.fr.provider/dns-query{?dns}",
- "https://ee.fr.provider/privacy_policy/"));
- EXPECT_TRUE(FindDropdownItem(resolver_list, "FR Provider",
- "https://fr.provider/dns-query{?dns}",
- "https://fr.provider/privacy_policy/"));
-
- // The 'CA' list should start with the custom entry, followed by the two
- // global providers.
- resolver_list = handler_->GetSecureDnsResolverListForCountry(
- country_codes::CountryCharsToCountryID('C', 'A'),
- GetDohProviderListForTesting());
- EXPECT_EQ(3u, resolver_list.GetList().size());
- EXPECT_EQ("custom", resolver_list.GetList()[0].FindKey("value")->GetString());
- EXPECT_TRUE(FindDropdownItem(resolver_list, "Global Provider 1",
- "https://global1.provider/dns-query{?dns}",
- "https://global1.provider/privacy_policy/"));
- EXPECT_TRUE(FindDropdownItem(resolver_list, "Global Provider 2",
- "https://global2.provider/dns-query{?dns}",
- "https://global2.provider/privacy_policy/"));
+IN_PROC_BROWSER_TEST_F(SecureDnsHandlerTest, DropdownListContents) {
+ const auto entries = GetDohProviderListForTesting();
+ handler_->SetProvidersForTesting(entries);
+ const base::Value resolver_list = handler_->GetSecureDnsResolverList();
+
+ EXPECT_EQ(entries.size() + 1, resolver_list.GetList().size());
+ EXPECT_TRUE(resolver_list.GetList()[0].FindKey("value")->GetString().empty());
+ for (const auto* entry : entries) {
+ EXPECT_TRUE(FindDropdownItem(resolver_list, entry->ui_name,
+ entry->dns_over_https_template,
+ entry->privacy_policy));
+ }
}
IN_PROC_BROWSER_TEST_F(SecureDnsHandlerTest, DropdownListChange) {
- // Populate the map for recording dropdown change metrics.
- base::Value resolver_list = handler_->GetSecureDnsResolverListForCountry(
- country_codes::CountryCharsToCountryID('E', 'E'),
- GetDohProviderListForTesting());
- EXPECT_EQ(4u, resolver_list.GetList().size());
+ handler_->SetProvidersForTesting(GetDohProviderListForTesting());
base::HistogramTester histograms;
base::ListValue args;
- args.AppendString("custom" /* old_provider */);
+ args.AppendString(std::string() /* old_provider */);
args.AppendString(
"https://global1.provider/dns-query{?dns}" /* new_provider */);
web_ui_.HandleReceivedMessage(kRecordUserDropdownInteraction, &args);
- const std::string uma_base("Net.DNS.UI.DropdownSelectionEvent");
- histograms.ExpectTotalCount(uma_base + ".Ignored", 2u);
- histograms.ExpectTotalCount(uma_base + ".Selected", 1u);
- histograms.ExpectTotalCount(uma_base + ".Unselected", 1u);
+ const std::string kUmaBase = "Net.DNS.UI.DropdownSelectionEvent";
+ histograms.ExpectTotalCount(kUmaBase + ".Ignored", 4u);
+ histograms.ExpectTotalCount(kUmaBase + ".Selected", 1u);
+ histograms.ExpectTotalCount(kUmaBase + ".Unselected", 1u);
}
-class SecureDnsHandlerTestWithDisabledProviders : public SecureDnsHandlerTest {
- protected:
- SecureDnsHandlerTestWithDisabledProviders() {
- scoped_features_.InitAndEnableFeatureWithParameters(
- features::kDnsOverHttps,
- {{"DisabledProviders",
- "Provider_Global2, , Provider_EE_FR,Unexpected"}});
- }
-
- private:
- base::test::ScopedFeatureList scoped_features_;
-
- DISALLOW_COPY_AND_ASSIGN(SecureDnsHandlerTestWithDisabledProviders);
-};
-
-IN_PROC_BROWSER_TEST_F(SecureDnsHandlerTestWithDisabledProviders,
- DropdownListDisabledProviders) {
- // The 'FR' list should start with the custom entry, followed by the two
- // global providers and the two 'FR' providers in some random order.
- base::Value resolver_list = handler_->GetSecureDnsResolverListForCountry(
- country_codes::CountryCharsToCountryID('F', 'R'),
- GetDohProviderListForTesting());
- EXPECT_EQ(3u, resolver_list.GetList().size());
- EXPECT_EQ("custom", resolver_list.GetList()[0].FindKey("value")->GetString());
- EXPECT_TRUE(FindDropdownItem(resolver_list, "Global Provider 1",
- "https://global1.provider/dns-query{?dns}",
- "https://global1.provider/privacy_policy/"));
- EXPECT_TRUE(FindDropdownItem(resolver_list, "FR Provider",
- "https://fr.provider/dns-query{?dns}",
- "https://fr.provider/privacy_policy/"));
-}
-
-IN_PROC_BROWSER_TEST_F(SecureDnsHandlerTestWithDisabledProviders,
- SecureDnsTemplates) {
+IN_PROC_BROWSER_TEST_F(SecureDnsHandlerTest, SecureDnsTemplates) {
std::string good_post_template = "https://foo.test/";
std::string good_get_template = "https://bar.test/dns-query{?dns}";
std::string bad_template = "dns-query{?dns}";
@@ -433,6 +347,8 @@ IN_PROC_BROWSER_TEST_F(SecureDnsHandlerTestWithDisabledProviders,
std::vector<std::string> secure_dns_templates;
int management_mode;
PrefService* local_state = g_browser_process->local_state();
+ local_state->SetString(prefs::kDnsOverHttpsMode,
+ SecureDnsConfig::kModeAutomatic);
local_state->SetString(prefs::kDnsOverHttpsTemplates, good_post_template);
EXPECT_TRUE(GetLastSettingsChangedMessage(
&secure_dns_mode, &secure_dns_templates, &management_mode));
@@ -458,15 +374,6 @@ IN_PROC_BROWSER_TEST_F(SecureDnsHandlerTestWithDisabledProviders,
&secure_dns_mode, &secure_dns_templates, &management_mode));
EXPECT_EQ(1u, secure_dns_templates.size());
EXPECT_EQ(good_post_template, secure_dns_templates[0]);
-
- // Should still return a provider that was disabled.
- local_state->SetString(prefs::kDnsOverHttpsTemplates,
- "https://global2.provider/dns-query{?dns}");
- EXPECT_TRUE(GetLastSettingsChangedMessage(
- &secure_dns_mode, &secure_dns_templates, &management_mode));
- EXPECT_EQ(1u, secure_dns_templates.size());
- EXPECT_EQ("https://global2.provider/dns-query{?dns}",
- secure_dns_templates[0]);
}
IN_PROC_BROWSER_TEST_F(SecureDnsHandlerTest, TemplateValid) {
diff --git a/chromium/chrome/browser/ui/webui/settings/settings_ui.cc b/chromium/chrome/browser/ui/webui/settings/settings_ui.cc
index 0462890255d..9e29823de46 100644
--- a/chromium/chrome/browser/ui/webui/settings/settings_ui.cc
+++ b/chromium/chrome/browser/ui/webui/settings/settings_ui.cc
@@ -285,11 +285,17 @@ SettingsUI::SettingsUI(content::WebUI* web_ui)
"syncSetupFriendlySettings",
base::FeatureList::IsEnabled(features::kSyncSetupFriendlySettings));
+#if defined(OS_WIN)
+ html_source->AddBoolean(
+ "safetyCheckChromeCleanerChildEnabled",
+ base::FeatureList::IsEnabled(features::kSafetyCheckChromeCleanerChild));
+#endif
+
#if defined(OS_CHROMEOS)
html_source->AddBoolean("splitSettingsSyncEnabled",
chromeos::features::IsSplitSettingsSyncEnabled());
- html_source->AddBoolean("splitSyncConsent",
- chromeos::features::IsSplitSyncConsentEnabled());
+ html_source->AddBoolean("useBrowserSyncConsent",
+ chromeos::features::ShouldUseBrowserSyncConsent());
html_source->AddBoolean(
"userCannotManuallyEnterPassword",
diff --git a/chromium/chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.cc b/chromium/chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.cc
index 20abed8007e..ae20e5716f0 100644
--- a/chromium/chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.cc
+++ b/chromium/chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.cc
@@ -8,6 +8,7 @@
#include "base/strings/utf_string_conversions.h"
#include "base/system/sys_info.h"
#include "build/build_config.h"
+#include "chrome/browser/browser_features.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
@@ -242,4 +243,15 @@ void AddSyncPageStrings(content::WebUIDataSource* html_source) {
}
}
+void AddNearbyShareData(content::WebUIDataSource* html_source) {
+ static constexpr webui::LocalizedString kLocalizedStrings[] = {
+ {"nearbyShareTitle", IDS_SETTINGS_NEARBY_SHARE_TITLE},
+ };
+ AddLocalizedStringsBulk(html_source, kLocalizedStrings);
+
+ html_source->AddBoolean(
+ "nearbySharingFeatureFlag",
+ base::FeatureList::IsEnabled(features::kNearbySharing));
+}
+
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.h b/chromium/chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.h
index 33dc5c453d4..73333c7fef5 100644
--- a/chromium/chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.h
+++ b/chromium/chrome/browser/ui/webui/settings/shared_settings_localized_strings_provider.h
@@ -31,6 +31,9 @@ void AddPasswordPromptDialogStrings(content::WebUIDataSource* html_source);
// Adds strings used by the <settings-sync-page> element.
void AddSyncPageStrings(content::WebUIDataSource* html_source);
+// Adds load time data used by the <settings-nearby-share-subpage>.
+void AddNearbyShareData(content::WebUIDataSource* html_source);
+
} // namespace settings
#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_SHARED_SETTINGS_LOCALIZED_STRINGS_PROVIDER_H_
diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc
index e195fcbd936..bcbafdd8e31 100644
--- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.cc
@@ -95,14 +95,6 @@ constexpr char kPlaceholder[] = "placeholder";
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
-enum class AllSitesAction {
- kLoadPage = 0,
- kResetPermissions = 1,
- kClearData = 2,
- kEnterSiteDetails = 3,
- kMaxValue = kEnterSiteDetails,
-};
-
enum class AllSitesAction2 {
kLoadPage = 0,
kResetSiteGroupPermissions = 1,
@@ -418,11 +410,6 @@ void SiteSettingsHandler::RegisterMessages() {
base::BindRepeating(&SiteSettingsHandler::HandleGetAllSites,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
- "getCookieControlsManagedState",
- base::BindRepeating(
- &SiteSettingsHandler::HandleGetCookieControlsManagedState,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
"getCookieSettingDescription",
base::BindRepeating(
&SiteSettingsHandler::HandleGetCookieSettingDescription,
@@ -817,34 +804,6 @@ void SiteSettingsHandler::HandleGetAllSites(const base::ListValue* args) {
ResolveJavascriptCallback(base::Value(callback_id), result);
}
-void SiteSettingsHandler::HandleGetCookieControlsManagedState(
- const base::ListValue* args) {
- AllowJavascript();
- CHECK_EQ(1U, args->GetList().size());
- std::string callback_id = args->GetList()[0].GetString();
-
- auto managed_states = site_settings::GetCookieControlsManagedState(profile_);
-
- base::Value result(base::Value::Type::DICTIONARY);
- result.SetKey(
- site_settings::kAllowAll,
- site_settings::GetValueForManagedState(managed_states.allow_all));
- result.SetKey(site_settings::kBlockThirdPartyIncognito,
- site_settings::GetValueForManagedState(
- managed_states.block_third_party_incognito));
- result.SetKey(
- site_settings::kBlockThirdParty,
- site_settings::GetValueForManagedState(managed_states.block_third_party));
- result.SetKey(
- site_settings::kBlockAll,
- site_settings::GetValueForManagedState(managed_states.block_all));
- result.SetKey(
- site_settings::kSessionOnly,
- site_settings::GetValueForManagedState(managed_states.session_only));
-
- ResolveJavascriptCallback(base::Value(callback_id), result);
-}
-
void SiteSettingsHandler::HandleGetCookieSettingDescription(
const base::ListValue* args) {
AllowJavascript();
diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h
index 0b34a324727..90c8106441b 100644
--- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler.h
@@ -128,11 +128,13 @@ class SiteSettingsHandler
FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ZoomLevels);
FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest,
HandleClearEtldPlus1DataAndCookies);
- FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, CookieControlsManagedState);
FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, CookieSettingDescription);
FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, HandleGetFormattedBytes);
FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest,
NotificationPermissionRevokeUkm);
+ FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ExcludeWebUISchemesInLists);
+ FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest,
+ IncludeWebUISchemesInGetOriginPermissions);
// Creates the CookiesTreeModel if necessary.
void EnsureCookiesTreeModelCreated();
@@ -171,10 +173,6 @@ class SiteSettingsHandler
// the front end when fetching finished.
void HandleGetAllSites(const base::ListValue* args);
- // Returns whether each of the cookie controls is managed and if so what
- // the source of that management is.
- void HandleGetCookieControlsManagedState(const base::ListValue* args);
-
// Returns a string for display describing the current cookie settings.
void HandleGetCookieSettingDescription(const base::ListValue* args);
diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc b/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc
index ee654373208..95b114fb5dc 100644
--- a/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc
@@ -45,8 +45,6 @@
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/content_settings/core/common/features.h"
#include "components/content_settings/core/common/pref_names.h"
-#include "components/content_settings/core/test/content_settings_mock_provider.h"
-#include "components/content_settings/core/test/content_settings_test_utils.h"
#include "components/history/core/browser/history_service.h"
#include "components/infobars/core/infobar.h"
#include "components/permissions/chooser_context_base.h"
@@ -67,6 +65,7 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/text/bytes_formatting.h"
+#include "ui/webui/webui_allowlist.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/users/mock_user_manager.h"
@@ -424,9 +423,10 @@ class SiteSettingsHandlerTest : public testing::Test {
}
virtual void DestroyIncognitoProfile() {
- profile_->SetOffTheRecordProfile(nullptr);
- ASSERT_FALSE(profile_->HasOffTheRecordProfile());
- incognito_profile_ = nullptr;
+ if (incognito_profile_) {
+ profile_->DestroyOffTheRecordProfile(incognito_profile_);
+ incognito_profile_ = nullptr;
+ }
}
// TODO(https://crbug.com/835712): Currently only set up the cookies and local
@@ -1877,6 +1877,133 @@ TEST_F(SiteSettingsHandlerTest, BlockAutoplay_Update) {
EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(prefs::kBlockAutoplayEnabled));
}
+TEST_F(SiteSettingsHandlerTest, ExcludeWebUISchemesInLists) {
+ const ContentSettingsType content_settings_type =
+ ContentSettingsType::NOTIFICATIONS;
+ // Register WebUIAllowlist auto-granted permissions.
+ const url::Origin kWebUIOrigins[] = {
+ url::Origin::Create(GURL("chrome://test")),
+ url::Origin::Create(GURL("chrome-untrusted://test")),
+ url::Origin::Create(GURL("devtools://devtools")),
+ };
+
+ WebUIAllowlist* allowlist = WebUIAllowlist::GetOrCreate(profile());
+ for (const url::Origin& origin : kWebUIOrigins)
+ allowlist->RegisterAutoGrantedPermission(origin, content_settings_type);
+
+ // Verify the auto-granted permissions are registered, and they are indeed
+ // provided by WebUIAllowlist.
+ HostContentSettingsMap* map =
+ HostContentSettingsMapFactory::GetForProfile(profile());
+ content_settings::SettingInfo info;
+ std::unique_ptr<base::Value> value = map->GetWebsiteSetting(
+ kWebUIOrigins[0].GetURL(), kWebUIOrigins[0].GetURL(),
+ content_settings_type, std::string(), &info);
+ EXPECT_EQ(CONTENT_SETTING_ALLOW, value->GetInt());
+ EXPECT_EQ(content_settings::SETTING_SOURCE_ALLOWLIST, info.source);
+
+ // Register an ordinary website permission.
+ const GURL kWebUrl = GURL("https://example.com");
+ map->SetContentSettingDefaultScope(kWebUrl, kWebUrl, content_settings_type,
+ std::string(), CONTENT_SETTING_ALLOW);
+ EXPECT_EQ(CONTENT_SETTING_ALLOW,
+ map->GetContentSetting(kWebUrl, kWebUrl, content_settings_type,
+ std::string()));
+
+ // GetAllSites() only returns website exceptions.
+ {
+ base::ListValue get_all_sites_args;
+ get_all_sites_args.AppendString(kCallbackId);
+ base::Value category_list(base::Value::Type::LIST);
+ category_list.Append(kNotifications);
+ get_all_sites_args.Append(std::move(category_list));
+
+ handler()->HandleGetAllSites(&get_all_sites_args);
+
+ const content::TestWebUI::CallData& data = *web_ui()->call_data().back();
+ base::Value::ConstListView site_groups = data.arg3()->GetList();
+ EXPECT_EQ(1UL, site_groups.size());
+
+ const std::string etld_plus1_string =
+ site_groups[0].FindKey("etldPlus1")->GetString();
+ EXPECT_EQ("example.com", etld_plus1_string);
+ base::Value::ConstListView origin_list =
+ site_groups[0].FindKey("origins")->GetList();
+ EXPECT_EQ(1UL, origin_list.size());
+ EXPECT_EQ(kWebUrl.spec(), origin_list[0].FindKey("origin")->GetString());
+ }
+
+ // GetExceptionList() only returns website exceptions.
+ {
+ base::ListValue get_exception_list_args;
+ get_exception_list_args.AppendString(kCallbackId);
+ get_exception_list_args.AppendString(kNotifications);
+
+ handler()->HandleGetExceptionList(&get_exception_list_args);
+
+ const content::TestWebUI::CallData& data = *web_ui()->call_data().back();
+ base::Value::ConstListView exception_list = data.arg3()->GetList();
+ EXPECT_EQ(1UL, exception_list.size());
+ EXPECT_EQ("https://example.com:443",
+ exception_list[0].FindKey("origin")->GetString());
+ }
+
+ // GetRecentSitePermissions() only returns website exceptions.
+ {
+ base::ListValue get_recent_permissions_args;
+ get_recent_permissions_args.AppendString(kCallbackId);
+ base::Value category_list(base::Value::Type::LIST);
+ category_list.Append(kNotifications);
+ get_recent_permissions_args.Append(std::move(category_list));
+ get_recent_permissions_args.Append(3);
+
+ handler()->HandleGetRecentSitePermissions(&get_recent_permissions_args);
+
+ const content::TestWebUI::CallData& data = *web_ui()->call_data().back();
+ base::Value::ConstListView recent_permission_list = data.arg3()->GetList();
+ EXPECT_EQ(1UL, recent_permission_list.size());
+ EXPECT_EQ(kWebUrl.spec(),
+ recent_permission_list[0].FindKey("origin")->GetString());
+ }
+}
+
+// GetOriginPermissions() returns the allowlisted exception. We explicitly
+// return this, so developers can easily test things (e.g. by navigating to
+// chrome://settings/content/siteDetails?site=chrome://example).
+TEST_F(SiteSettingsHandlerTest, IncludeWebUISchemesInGetOriginPermissions) {
+ const ContentSettingsType content_settings_type =
+ ContentSettingsType::NOTIFICATIONS;
+
+ // Register WebUIAllowlist auto-granted permissions.
+ const url::Origin kWebUIOrigins[] = {
+ url::Origin::Create(GURL("chrome://test")),
+ url::Origin::Create(GURL("chrome-untrusted://test")),
+ url::Origin::Create(GURL("devtools://devtools")),
+ };
+
+ WebUIAllowlist* allowlist = WebUIAllowlist::GetOrCreate(profile());
+ for (const url::Origin& origin : kWebUIOrigins)
+ allowlist->RegisterAutoGrantedPermission(origin, content_settings_type);
+
+ for (const url::Origin& origin : kWebUIOrigins) {
+ base::ListValue get_origin_permissions_args;
+ get_origin_permissions_args.AppendString(kCallbackId);
+ get_origin_permissions_args.AppendString(origin.GetURL().spec());
+ auto category_list = std::make_unique<base::ListValue>();
+ category_list->AppendString(kNotifications);
+ get_origin_permissions_args.Append(std::move(category_list));
+
+ handler()->HandleGetOriginPermissions(&get_origin_permissions_args);
+ const content::TestWebUI::CallData& data = *web_ui()->call_data().back();
+ const base::Value::ConstListView exception_list = data.arg3()->GetList();
+ EXPECT_EQ(1UL, exception_list.size());
+
+ EXPECT_EQ(origin.GetURL().spec(),
+ exception_list[0].FindKey("origin")->GetString());
+ EXPECT_EQ("allowlist", exception_list[0].FindKey("source")->GetString());
+ }
+}
+
namespace {
constexpr char kUsbPolicySetting[] = R"(
@@ -1907,6 +2034,9 @@ GURL ChromiumUrl() {
GURL GoogleUrl() {
return GURL("https://google.com");
}
+GURL WebUIUrl() {
+ return GURL("chrome://test");
+}
} // namespace
@@ -1954,6 +2084,7 @@ class SiteSettingsHandlerChooserExceptionTest : public SiteSettingsHandlerTest {
const auto kAndroidOrigin = url::Origin::Create(AndroidUrl());
const auto kChromiumOrigin = url::Origin::Create(ChromiumUrl());
const auto kGoogleOrigin = url::Origin::Create(GoogleUrl());
+ const auto kWebUIOrigin = url::Origin::Create(WebUIUrl());
// Add the user granted permissions for testing.
// These two persistent device permissions should be lumped together with
@@ -1964,6 +2095,8 @@ class SiteSettingsHandlerChooserExceptionTest : public SiteSettingsHandlerTest {
*persistent_device_info_);
chooser_context->GrantDevicePermission(kAndroidOrigin, kChromiumOrigin,
*persistent_device_info_);
+ chooser_context->GrantDevicePermission(kWebUIOrigin, kWebUIOrigin,
+ *persistent_device_info_);
chooser_context->GrantDevicePermission(kAndroidOrigin, kAndroidOrigin,
*ephemeral_device_info_);
chooser_context->GrantDevicePermission(kAndroidOrigin, kAndroidOrigin,
@@ -2118,6 +2251,11 @@ TEST_F(SiteSettingsHandlerChooserExceptionTest,
const base::Value& exceptions = GetChooserExceptionListFromWebUiCallData(
kUsbChooserGroupName, /*expected_total_calls=*/1u);
EXPECT_EQ(exceptions.GetList().size(), 5u);
+
+ // Don't include WebUI schemes.
+ const std::string kWebUIOriginStr = WebUIUrl().GetOrigin().spec();
+ EXPECT_FALSE(ChooserExceptionContainsSiteException(
+ exceptions, "Gizmo", kWebUIOriginStr, kWebUIOriginStr));
}
TEST_F(SiteSettingsHandlerChooserExceptionTest,
@@ -2338,61 +2476,6 @@ TEST_F(SiteSettingsHandlerTest, HandleClearEtldPlus1DataAndCookies) {
EXPECT_EQ(0U, storage_and_cookie_list->GetSize());
}
-TEST_F(SiteSettingsHandlerTest, CookieControlsManagedState) {
- // Test that the handler correctly wraps the helper result. Helper with
- // extensive logic is tested in site_settings_helper_unittest.cc.
- const std::string kNone = "none";
- const std::string kDevicePolicy = "devicePolicy";
- const std::vector<std::string> kControlNames = {
- "allowAll", "blockAll", "blockThirdParty", "blockThirdPartyIncognito",
- "sessionOnly"};
-
- // Check that the default cookie control state is handled correctly.
- base::ListValue get_args;
- get_args.AppendString(kCallbackId);
- handler()->HandleGetCookieControlsManagedState(&get_args);
- {
- const content::TestWebUI::CallData& data = *web_ui()->call_data().back();
- EXPECT_EQ("cr.webUIResponse", data.function_name());
- EXPECT_EQ(kCallbackId, data.arg1()->GetString());
- ASSERT_TRUE(data.arg2()->GetBool());
- for (const auto& control_name : kControlNames) {
- auto* control_state = data.arg3()->FindPath(control_name);
- ASSERT_FALSE(control_state->FindKey("disabled")->GetBool());
- ASSERT_EQ(kNone, control_state->FindKey("indicator")->GetString());
- }
- }
-
- // Check that a fully managed cookie state is handled correctly.
- HostContentSettingsMap* map =
- HostContentSettingsMapFactory::GetForProfile(profile());
- auto provider = std::make_unique<content_settings::MockProvider>();
- provider->SetWebsiteSetting(
- ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(),
- ContentSettingsType::COOKIES, std::string(),
- std::make_unique<base::Value>(CONTENT_SETTING_ALLOW));
- content_settings::TestUtils::OverrideProvider(
- map, std::move(provider), HostContentSettingsMap::POLICY_PROVIDER);
- sync_preferences::TestingPrefServiceSyncable* pref_service =
- profile()->GetTestingPrefService();
- pref_service->SetManagedPref(prefs::kBlockThirdPartyCookies,
- std::make_unique<base::Value>(true));
-
- handler()->HandleGetCookieControlsManagedState(&get_args);
- {
- const content::TestWebUI::CallData& data = *web_ui()->call_data().back();
- EXPECT_EQ("cr.webUIResponse", data.function_name());
- EXPECT_EQ(kCallbackId, data.arg1()->GetString());
- ASSERT_TRUE(data.arg2()->GetBool());
- for (const auto& control_name : kControlNames) {
- auto* control_state = data.arg3()->FindPath(control_name);
- ASSERT_TRUE(control_state->FindKey("disabled")->GetBool());
- ASSERT_EQ(kDevicePolicy,
- control_state->FindKey("indicator")->GetString());
- }
- }
-}
-
TEST_F(SiteSettingsHandlerTest, CookieSettingDescription) {
const auto kBlocked = [](int num) {
return l10n_util::GetPluralStringFUTF8(
diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_helper.cc b/chromium/chrome/browser/ui/webui/settings/site_settings_helper.cc
index 5dfef5ee030..28addc32434 100644
--- a/chromium/chrome/browser/ui/webui/settings/site_settings_helper.cc
+++ b/chromium/chrome/browser/ui/webui/settings/site_settings_helper.cc
@@ -10,8 +10,11 @@
#include <string>
#include "base/feature_list.h"
+#include "base/no_destructor.h"
#include "base/stl_util.h"
+#include "base/strings/strcat.h"
#include "base/strings/string16.h"
+#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/bluetooth/bluetooth_chooser_context.h"
@@ -26,12 +29,10 @@
#include "chrome/browser/usb/usb_chooser_context.h"
#include "chrome/browser/usb/usb_chooser_context_factory.h"
#include "chrome/common/pref_names.h"
-#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/content_settings/core/common/content_settings_utils.h"
-#include "components/content_settings/core/common/pref_names.h"
#include "components/permissions/chooser_context_base.h"
#include "components/permissions/permission_decision_auto_blocker.h"
#include "components/permissions/permission_manager.h"
@@ -42,9 +43,11 @@
#include "components/subresource_filter/core/browser/subresource_filter_features.h"
#include "components/url_formatter/url_formatter.h"
#include "content/public/common/content_features.h"
+#include "content/public/common/url_utils.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/constants.h"
#include "url/origin.h"
+#include "url/url_constants.h"
namespace site_settings {
@@ -158,6 +161,7 @@ struct SiteSettingSourceStringMapping {
};
const SiteSettingSourceStringMapping kSiteSettingSourceStringMapping[] = {
+ {SiteSettingSource::kAllowlist, "allowlist"},
{SiteSettingSource::kAdsFilterBlacklist, "ads-filter-blacklist"},
{SiteSettingSource::kDefault, "default"},
{SiteSettingSource::kDrmDisabled, "drm-disabled"},
@@ -195,38 +199,49 @@ static_assert(base::size(kPolicyIndicatorTypeStringMapping) ==
"kPolicyIndicatorStringMapping should have "
"PolicyIndicatorType::kNumIndicators elements");
+const std::string& GetDevtoolsPatternPrefix() {
+ static const base::NoDestructor<std::string> kDevtoolsPatternPrefix(
+ base::StrCat({content_settings::kChromeDevToolsScheme,
+ url::kStandardSchemeSeparator}));
+ return *kDevtoolsPatternPrefix;
+}
+
// Retrieves the corresponding string, according to the following precedence
// order from highest to lowest priority:
-// 1. Kill-switch.
-// 2. Insecure origins (some permissions are denied to insecure origins).
-// 3. Enterprise policy.
-// 4. Extensions.
-// 5. Activated for ads filtering (for Ads ContentSettingsType only).
-// 6. DRM disabled (for CrOS's Protected Content ContentSettingsType only).
-// 7. User-set per-origin setting.
-// 8. Embargo.
-// 9. User-set patterns.
-// 10. User-set global default for a ContentSettingsType.
-// 11. Chrome's built-in default.
+// 1. Allowlisted WebUI content setting.
+// 2. Kill-switch.
+// 3. Insecure origins (some permissions are denied to insecure origins).
+// 4. Enterprise policy.
+// 5. Extensions.
+// 6. Activated for ads filtering (for Ads ContentSettingsType only).
+// 7. DRM disabled (for CrOS's Protected Content ContentSettingsType only).
+// 8. User-set per-origin setting.
+// 9. Embargo.
+// 10. User-set patterns.
+// 11. User-set global default for a ContentSettingsType.
+// 12. Chrome's built-in default.
SiteSettingSource CalculateSiteSettingSource(
Profile* profile,
const ContentSettingsType content_type,
const GURL& origin,
const content_settings::SettingInfo& info,
const permissions::PermissionResult result) {
+ if (info.source == content_settings::SETTING_SOURCE_ALLOWLIST)
+ return SiteSettingSource::kAllowlist; // Source #1.
+
if (result.source == permissions::PermissionStatusSource::KILL_SWITCH)
- return SiteSettingSource::kKillSwitch; // Source #1.
+ return SiteSettingSource::kKillSwitch; // Source #2.
if (result.source == permissions::PermissionStatusSource::INSECURE_ORIGIN)
- return SiteSettingSource::kInsecureOrigin; // Source #2.
+ return SiteSettingSource::kInsecureOrigin; // Source #3.
if (info.source == content_settings::SETTING_SOURCE_POLICY ||
info.source == content_settings::SETTING_SOURCE_SUPERVISED) {
- return SiteSettingSource::kPolicy; // Source #3.
+ return SiteSettingSource::kPolicy; // Source #4.
}
if (info.source == content_settings::SETTING_SOURCE_EXTENSION)
- return SiteSettingSource::kExtension; // Source #4.
+ return SiteSettingSource::kExtension; // Source #5.
if (content_type == ContentSettingsType::ADS &&
base::FeatureList::IsEnabled(
@@ -236,14 +251,14 @@ SiteSettingSource CalculateSiteSettingSource(
if (map->GetWebsiteSetting(origin, GURL(), ContentSettingsType::ADS_DATA,
/*resource_identifier=*/std::string(),
/*setting_info=*/nullptr) != nullptr) {
- return SiteSettingSource::kAdsFilterBlacklist; // Source #5.
+ return SiteSettingSource::kAdsFilterBlacklist; // Source #6.
}
}
// Protected Content will be blocked if the |kEnableDRM| pref is off.
if (content_type == ContentSettingsType::PROTECTED_MEDIA_IDENTIFIER &&
!profile->GetPrefs()->GetBoolean(prefs::kEnableDRM)) {
- return SiteSettingSource::kDrmDisabled; // Source #6.
+ return SiteSettingSource::kDrmDisabled; // Source #7.
}
DCHECK_NE(content_settings::SETTING_SOURCE_NONE, info.source);
@@ -252,18 +267,18 @@ SiteSettingSource CalculateSiteSettingSource(
permissions::PermissionStatusSource::MULTIPLE_DISMISSALS ||
result.source ==
permissions::PermissionStatusSource::MULTIPLE_IGNORES) {
- return SiteSettingSource::kEmbargo; // Source #8.
+ return SiteSettingSource::kEmbargo; // Source #9.
}
if (info.primary_pattern == ContentSettingsPattern::Wildcard() &&
info.secondary_pattern == ContentSettingsPattern::Wildcard()) {
- return SiteSettingSource::kDefault; // Source #10, #11.
+ return SiteSettingSource::kDefault; // Source #11, #12.
}
- // Source #7, #9. When #7 is the source, |result.source| won't
- // be set to any of the source #7 enum values, as PermissionManager is
- // aware of the difference between these two sources internally. The
- // subtlety here should go away when PermissionManager can handle all
- // content settings and all possible sources.
+ // Source #8, #10. When #8 is the source, |result.source| won't be set to
+ // any of the source #8 enum values, as PermissionManager is aware of the
+ // difference between these two sources internally. The subtlety here should
+ // go away when PermissionManager can handle all content settings and all
+ // possible sources.
return SiteSettingSource::kPreference;
}
@@ -286,6 +301,16 @@ bool PatternAppliesToSingleOrigin(const ContentSettingPatternSource& pattern) {
return true;
}
+bool PatternAppliesToWebUISchemes(const ContentSettingPatternSource& pattern) {
+ return pattern.primary_pattern.GetScheme() ==
+ ContentSettingsPattern::SchemeType::SCHEME_CHROME ||
+ pattern.primary_pattern.GetScheme() ==
+ ContentSettingsPattern::SchemeType::SCHEME_CHROMEUNTRUSTED ||
+ base::StartsWith(pattern.primary_pattern.ToString(),
+ GetDevtoolsPatternPrefix(),
+ base::CompareCase::INSENSITIVE_ASCII);
+}
+
// Retrieves the source of a chooser exception as a string. This method uses the
// CalculateSiteSettingSource method above to calculate the correct string to
// use.
@@ -344,31 +369,12 @@ const ChooserTypeNameEntry kChooserTypeGroupNames[] = {
{&GetHidChooserContext, kHidChooserDataGroupType},
{&GetBluetoothChooserContext, kBluetoothChooserDataGroupType}};
-PolicyIndicatorType GetPolicyIndicatorFromSettingSource(
- content_settings::SettingSource setting_source) {
- switch (setting_source) {
- case content_settings::SETTING_SOURCE_POLICY:
- return PolicyIndicatorType::kDevicePolicy;
- case content_settings::SETTING_SOURCE_SUPERVISED:
- return PolicyIndicatorType::kParent;
- case content_settings::SETTING_SOURCE_EXTENSION:
- return PolicyIndicatorType::kExtension;
- case content_settings::SETTING_SOURCE_USER:
- case content_settings::SETTING_SOURCE_ALLOWLIST:
- case content_settings::SETTING_SOURCE_NONE:
- return PolicyIndicatorType::kNone;
- case content_settings::SETTING_SOURCE_INSTALLED_WEBAPP:
- NOTREACHED();
- return PolicyIndicatorType::kNone;
- }
-}
-
} // namespace
bool HasRegisteredGroupName(ContentSettingsType type) {
for (size_t i = 0; i < base::size(kContentSettingsTypeGroupNames); ++i) {
if (type == kContentSettingsTypeGroupNames[i].type &&
- kContentSettingsTypeGroupNames[i].name != nullptr) {
+ kContentSettingsTypeGroupNames[i].name) {
return true;
}
}
@@ -389,7 +395,7 @@ std::string ContentSettingsTypeToGroupName(ContentSettingsType type) {
for (size_t i = 0; i < base::size(kContentSettingsTypeGroupNames); ++i) {
if (type == kContentSettingsTypeGroupNames[i].type) {
const char* name = kContentSettingsTypeGroupNames[i].name;
- if (name != nullptr)
+ if (name)
return name;
break;
}
@@ -455,7 +461,9 @@ std::unique_ptr<base::DictionaryValue> GetExceptionForPage(
const std::string& display_name,
const ContentSetting& setting,
const std::string& provider_name,
- bool incognito) {
+ bool incognito,
+ bool is_embargoed,
+ bool is_discarded) {
auto exception = std::make_unique<base::DictionaryValue>();
exception->SetString(kOrigin, pattern.ToString());
exception->SetString(kDisplayName, display_name);
@@ -471,6 +479,8 @@ std::unique_ptr<base::DictionaryValue> GetExceptionForPage(
exception->SetString(kSetting, setting_string);
exception->SetString(kSource, provider_name);
exception->SetBoolean(kIncognito, incognito);
+ exception->SetBoolean(kIsEmbargoed, is_embargoed);
+ exception->SetBoolean(kIsDiscarded, is_discarded);
return exception;
}
@@ -539,6 +549,11 @@ void GetExceptionsForContentType(
map->GetSettingsForOneType(type, std::string(), &all_settings);
+ // Will return only regular settings for a regular profile and only incognito
+ // settings for an incognito Profile.
+ ContentSettingsForOneType discarded_settings;
+ map->GetDiscardedSettingsForOneType(type, std::string(), &discarded_settings);
+
// Group settings by primary_pattern.
AllPatternsSettings all_patterns_settings;
for (const auto& setting : all_settings) {
@@ -556,6 +571,11 @@ void GetExceptionsForContentType(
if (map->IsOffTheRecord() && !setting.incognito)
continue;
+ // Don't add WebUI settings.
+ if (PatternAppliesToWebUISchemes(setting)) {
+ continue;
+ }
+
all_patterns_settings[std::make_pair(
setting.primary_pattern, setting.source)][setting.secondary_pattern] =
setting.GetContentSetting();
@@ -569,6 +589,8 @@ void GetExceptionsForContentType(
permissions::PermissionsClient::Get()->GetPermissionDecisionAutoBlocker(
profile);
+ std::set<ContentSettingsPattern> origins_under_embargo;
+
for (const auto& setting : embargo_settings) {
// Off-the-record HostContentSettingsMap contains incognito content
// settings as well as normal content settings. Here, we use the
@@ -582,6 +604,7 @@ void GetExceptionsForContentType(
if (auto_blocker
->GetEmbargoResult(GURL(setting.primary_pattern.ToString()), type)
.content_setting == CONTENT_SETTING_BLOCK) {
+ origins_under_embargo.insert(setting.primary_pattern);
all_patterns_settings[std::make_pair(
setting.primary_pattern, setting.source)][setting.secondary_pattern] =
CONTENT_SETTING_BLOCK;
@@ -620,9 +643,10 @@ void GetExceptionsForContentType(
parent == one_settings.end() ? CONTENT_SETTING_DEFAULT : parent->second;
const ContentSettingsPattern& secondary_pattern =
parent == one_settings.end() ? primary_pattern : parent->first;
- this_provider_exceptions.push_back(
- GetExceptionForPage(primary_pattern, secondary_pattern, display_name,
- parent_setting, source, incognito));
+ this_provider_exceptions.push_back(GetExceptionForPage(
+ primary_pattern, secondary_pattern, display_name, parent_setting,
+ source, incognito,
+ base::Contains(origins_under_embargo, primary_pattern)));
// Add the "children" for any embedded settings.
for (auto j = one_settings.begin(); j != one_settings.end(); ++j) {
@@ -631,9 +655,9 @@ void GetExceptionsForContentType(
continue;
ContentSetting content_setting = j->second;
- this_provider_exceptions.push_back(
- GetExceptionForPage(primary_pattern, j->first, display_name,
- content_setting, source, incognito));
+ this_provider_exceptions.push_back(GetExceptionForPage(
+ primary_pattern, j->first, display_name, content_setting, source,
+ incognito, base::Contains(origins_under_embargo, primary_pattern)));
}
}
@@ -653,6 +677,15 @@ void GetExceptionsForContentType(
for (auto& exception : one_provider_exceptions)
exceptions->Append(std::move(exception));
}
+
+ for (auto& discarded_rule : discarded_settings) {
+ exceptions->Append(GetExceptionForPage(
+ discarded_rule.primary_pattern, discarded_rule.secondary_pattern,
+ GetDisplayNameForPattern(discarded_rule.primary_pattern,
+ extension_registry),
+ discarded_rule.GetContentSetting(), discarded_rule.source, incognito,
+ false /*is_embargoed*/, true /*is_discarded*/));
+ }
}
void GetContentCategorySetting(const HostContentSettingsMap* map,
@@ -713,7 +746,8 @@ std::vector<ContentSettingPatternSource> GetSiteExceptionsForContentType(
map->GetSettingsForOneType(content_type, std::string(), &entries);
entries.erase(std::remove_if(entries.begin(), entries.end(),
[](const ContentSettingPatternSource& e) {
- return !PatternAppliesToSingleOrigin(e);
+ return !PatternAppliesToSingleOrigin(e) ||
+ PatternAppliesToWebUISchemes(e);
}),
entries.end());
return entries;
@@ -864,6 +898,10 @@ base::Value GetChooserExceptionListFromProfile(
std::map<std::pair<base::string16, base::Value>, ChooserExceptionDetails>
all_chooser_objects;
for (const auto& object : objects) {
+ // Don't include WebUI settings.
+ if (content::HasWebUIScheme(object->requesting_origin))
+ continue;
+
base::string16 name = chooser_context->GetObjectDisplayName(object->value);
auto& chooser_exception_details =
all_chooser_objects[std::make_pair(name, object->value.Clone())];
@@ -893,121 +931,6 @@ base::Value GetChooserExceptionListFromProfile(
return exceptions;
}
-CookieControlsManagedState GetCookieControlsManagedState(Profile* profile) {
- // Setup a default unmanaged state that is updated based on the actual
- // managed state.
- CookieControlsManagedState managed_state;
-
- HostContentSettingsMap* map =
- HostContentSettingsMapFactory::GetForProfile(profile);
- std::string content_setting_provider;
- auto content_setting = map->GetDefaultContentSetting(
- ContentSettingsType::COOKIES, &content_setting_provider);
- auto content_setting_source =
- HostContentSettingsMap::GetSettingSourceFromProviderName(
- content_setting_provider);
- bool content_setting_enforced =
- content_setting_source !=
- content_settings::SettingSource::SETTING_SOURCE_USER;
-
- // Both the content setting and the block_third_party preference can
- // be controlled via policy.
- const PrefService::Preference* block_third_party_pref =
- profile->GetPrefs()->FindPreference(prefs::kBlockThirdPartyCookies);
- bool block_third_party_on = block_third_party_pref->GetValue()->GetBool();
- bool block_third_party_enforced = !block_third_party_pref->IsUserModifiable();
- // IsRecommended() cannot be used as we care if a recommended value exists at
- // all, even if a user has overwritten it.
- bool block_third_party_recommended =
- (block_third_party_pref && block_third_party_pref->GetRecommendedValue());
- bool block_third_party_recommended_on =
- block_third_party_recommended &&
- block_third_party_pref->GetRecommendedValue()->GetBool();
-
- // kCookieControlsMode == kOn should imply block_third_party is on.
- auto control_mode = static_cast<content_settings::CookieControlsMode>(
- profile->GetPrefs()->GetInteger(prefs::kCookieControlsMode));
- DCHECK(control_mode !=
- content_settings::CookieControlsMode::kBlockThirdParty ||
- block_third_party_on);
-
- // Get indicators representing each settings source. These may or may not
- // be used depending on the determined managed state.
- auto content_setting_source_indicator =
- GetPolicyIndicatorFromSettingSource(content_setting_source);
- auto block_third_party_source_indicator =
- GetPolicyIndicatorFromPref(block_third_party_pref);
-
- if (!content_setting_enforced && !block_third_party_enforced &&
- !block_third_party_recommended) {
- // No cookie controls are managed or recommended.
- return managed_state;
- }
-
- if (content_setting_enforced) {
- // Block and session only managed state only depend on the content setting.
- managed_state.block_all = {/*disabled*/ true,
- content_setting_source_indicator};
- managed_state.session_only = {/*disabled*/ true,
- content_setting_source_indicator};
- }
-
- if (content_setting_enforced && content_setting == CONTENT_SETTING_BLOCK) {
- // All remaining controls are managed by the content setting source.
- managed_state.allow_all = {/*disabled*/ true,
- content_setting_source_indicator};
- managed_state.block_third_party_incognito = {
- /*disabled*/ true, content_setting_source_indicator};
- managed_state.block_third_party = {/*disabled*/ true,
- content_setting_source_indicator};
- return managed_state;
- }
- if (content_setting_enforced && block_third_party_enforced) {
- // All remaining controls are managed by the block_third_party source.
- managed_state.allow_all = {/*disabled*/ true,
- block_third_party_source_indicator};
- managed_state.block_third_party_incognito = {
- /*disabled*/ true, block_third_party_source_indicator};
- managed_state.block_third_party = {/*disabled*/ true,
- block_third_party_source_indicator};
- return managed_state;
- }
- DCHECK(!content_setting_enforced ||
- content_setting == CONTENT_SETTING_ALLOW ||
- content_setting == CONTENT_SETTING_SESSION_ONLY);
- DCHECK(!content_setting_enforced || !block_third_party_enforced);
- // At this stage the content setting is not enforcing a BLOCK state. Given
- // this, allow and block_third_party are still valid choices that do not
- // contradict the content setting. They can thus be controlled or recommended
- // by the block_third_party preference.
- if (block_third_party_enforced) {
- DCHECK(!content_setting_enforced);
- managed_state.block_third_party_incognito = {
- true, block_third_party_source_indicator};
- if (block_third_party_on) {
- managed_state.allow_all = {/*disabled*/ true,
- block_third_party_source_indicator};
- } else {
- managed_state.block_third_party = {/*disabled*/ true,
- block_third_party_source_indicator};
- }
- return managed_state;
- }
- if (block_third_party_recommended) {
- if (block_third_party_recommended_on) {
- managed_state.block_third_party = {/*disabled*/ false,
- block_third_party_source_indicator};
- } else {
- managed_state.allow_all = {/*disabled*/ false,
- block_third_party_source_indicator};
- }
- return managed_state;
- }
- DCHECK(content_setting_enforced && !block_third_party_enforced &&
- !block_third_party_recommended);
- return managed_state;
-}
-
std::string PolicyIndicatorTypeToString(const PolicyIndicatorType type) {
return kPolicyIndicatorTypeStringMapping[static_cast<int>(type)]
.indicator_str;
diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_helper.h b/chromium/chrome/browser/ui/webui/settings/site_settings_helper.h
index b018f7c63a3..8ac89c83c11 100644
--- a/chromium/chrome/browser/ui/webui/settings/site_settings_helper.h
+++ b/chromium/chrome/browser/ui/webui/settings/site_settings_helper.h
@@ -53,11 +53,6 @@ typedef std::map<std::pair<ContentSettingsPattern, std::string>,
using ChooserExceptionDetails =
std::map<std::pair<GURL, std::string>, std::set<std::pair<GURL, bool>>>;
-constexpr char kAllowAll[] = "allowAll";
-constexpr char kBlockThirdPartyIncognito[] = "blockThirdPartyIncognito";
-constexpr char kBlockThirdParty[] = "blockThirdParty";
-constexpr char kBlockAll[] = "blockAll";
-constexpr char kSessionOnly[] = "sessionOnly";
constexpr char kChooserType[] = "chooserType";
constexpr char kDisplayName[] = "displayName";
constexpr char kEmbeddingOrigin[] = "embeddingOrigin";
@@ -72,8 +67,11 @@ constexpr char kSites[] = "sites";
constexpr char kPolicyIndicator[] = "indicator";
constexpr char kSource[] = "source";
constexpr char kType[] = "type";
+constexpr char kIsEmbargoed[] = "isEmbargoed";
+constexpr char kIsDiscarded[] = "isDiscarded";
enum class SiteSettingSource {
+ kAllowlist,
kAdsFilterBlacklist,
kDefault,
kDrmDisabled,
@@ -108,15 +106,6 @@ struct ManagedState {
PolicyIndicatorType indicator = PolicyIndicatorType::kNone;
};
-// Represents the manage states for all of the cookie controls.
-struct CookieControlsManagedState {
- ManagedState allow_all;
- ManagedState block_third_party_incognito;
- ManagedState block_third_party;
- ManagedState block_all;
- ManagedState session_only;
-};
-
// Returns whether a group name has been registered for the given type.
bool HasRegisteredGroupName(ContentSettingsType type);
@@ -141,7 +130,9 @@ std::unique_ptr<base::DictionaryValue> GetExceptionForPage(
const std::string& display_name,
const ContentSetting& setting,
const std::string& provider_name,
- bool incognito);
+ bool incognito,
+ bool is_embargoed = false,
+ bool is_discarded = false);
// Helper function to construct a dictionary for a hosted app exception.
void AddExceptionForHostedApp(const std::string& url_pattern,
@@ -225,9 +216,6 @@ base::Value GetChooserExceptionListFromProfile(
Profile* profile,
const ChooserTypeNameEntry& chooser_type);
-// Returns the cookie controls manage state for a given profile.
-CookieControlsManagedState GetCookieControlsManagedState(Profile* profile);
-
// Concerts a PolicyIndicatorType to its string identifier.
std::string PolicyIndicatorTypeToString(const PolicyIndicatorType type);
diff --git a/chromium/chrome/browser/ui/webui/settings/site_settings_helper_unittest.cc b/chromium/chrome/browser/ui/webui/settings/site_settings_helper_unittest.cc
index 2a08d0797ee..6b11de46fbe 100644
--- a/chromium/chrome/browser/ui/webui/settings/site_settings_helper_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/settings/site_settings_helper_unittest.cc
@@ -23,7 +23,6 @@
#include "components/permissions/chooser_context_base.h"
#include "components/permissions/permission_decision_auto_blocker.h"
#include "components/prefs/pref_service.h"
-#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "content/public/test/browser_task_environment.h"
#include "extensions/browser/extension_registry.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
@@ -75,6 +74,47 @@ class SiteSettingsHelperTest : public testing::Test {
content::BrowserTaskEnvironment task_environment_;
};
+TEST_F(SiteSettingsHelperTest, ExceptionListWithEmbargoedAndBlockedOrigins) {
+ TestingProfile profile;
+
+ constexpr char kOriginToEmbargo[] = "https://embargoed.co.uk:443";
+ auto* auto_blocker =
+ PermissionDecisionAutoBlockerFactory::GetForProfile(&profile);
+ for (size_t i = 0; i < 3; ++i) {
+ auto_blocker->RecordDismissAndEmbargo(GURL(kOriginToEmbargo),
+ kContentTypeNotifications, false);
+ }
+
+ constexpr char kOriginToBlock[] = "https://www.blocked.com:443";
+ auto* map = HostContentSettingsMapFactory::GetForProfile(&profile);
+ map->SetContentSettingDefaultScope(GURL(kOriginToBlock), GURL(kOriginToBlock),
+ kContentTypeNotifications, std::string(),
+ CONTENT_SETTING_BLOCK);
+
+ base::ListValue exceptions;
+ site_settings::GetExceptionsForContentType(kContentTypeNotifications,
+ &profile,
+ /*extension_registry=*/nullptr,
+ /*web_ui=*/nullptr,
+ /*incognito=*/false, &exceptions);
+
+ // |exceptions| size should be 2. One blocked and one embargoed origins.
+ ASSERT_EQ(2U, exceptions.GetSize());
+ base::Value* value = nullptr;
+ // Get last added origin.
+ exceptions.Get(0, &value);
+ base::Value* is_embargoed = value->FindKey(site_settings::kIsEmbargoed);
+ ASSERT_NE(nullptr, is_embargoed);
+ // Last added origin is blocked, |embargo| key should be false.
+ EXPECT_FALSE(is_embargoed->GetBool());
+
+ // Get embargoed origin.
+ exceptions.Get(1, &value);
+ is_embargoed = value->FindKey(site_settings::kIsEmbargoed);
+ ASSERT_NE(nullptr, is_embargoed);
+ EXPECT_TRUE(is_embargoed->GetBool());
+}
+
TEST_F(SiteSettingsHelperTest, ExceptionListShowsIncognitoEmbargoed) {
TestingProfile profile;
constexpr char kOriginToBlock[] = "https://www.blocked.com:443";
@@ -816,302 +856,4 @@ TEST_F(SiteSettingsHelperChooserExceptionTest,
}
}
-namespace {
-
-// All of the possible managed states for a boolean preference that can be
-// both enforced and recommended.
-enum class PrefSetting {
- kEnforcedOff,
- kEnforcedOn,
- kRecommendedOff,
- kRecommendedOn,
- kNotSet,
-};
-
-// Possible preference sources supported by TestingPrefService.
-// TODO(crbug.com/1063281): Extend TestingPrefService to support prefs set for
-// supervised users.
-enum class PrefSource {
- kExtension,
- kDevicePolicy,
- kRecommended,
- kNone,
-};
-
-// Represents a set of settings, preferences and the associated expected
-// CookieControlsManagedState.
-struct CookiesManagedStateTestCase {
- ContentSetting default_content_setting;
- content_settings::SettingSource default_content_setting_source;
- PrefSetting block_third_party;
- PrefSource block_third_party_source;
- CookieControlsManagedState expected_result;
-};
-
-const std::vector<CookiesManagedStateTestCase> test_cases = {
- {CONTENT_SETTING_DEFAULT,
- content_settings::SETTING_SOURCE_NONE,
- PrefSetting::kEnforcedOff,
- PrefSource::kExtension,
- {{false, PolicyIndicatorType::kNone},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone}}},
- {CONTENT_SETTING_DEFAULT,
- content_settings::SETTING_SOURCE_NONE,
- PrefSetting::kEnforcedOn,
- PrefSource::kDevicePolicy,
- {{true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone}}},
- {CONTENT_SETTING_DEFAULT,
- content_settings::SETTING_SOURCE_NONE,
- PrefSetting::kRecommendedOff,
- PrefSource::kRecommended,
- {{false, PolicyIndicatorType::kRecommended},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone}}},
- {CONTENT_SETTING_DEFAULT,
- content_settings::SETTING_SOURCE_NONE,
- PrefSetting::kRecommendedOn,
- PrefSource::kRecommended,
- {{false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kRecommended},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone}}},
- {CONTENT_SETTING_DEFAULT,
- content_settings::SETTING_SOURCE_NONE,
- PrefSetting::kNotSet,
- PrefSource::kNone,
- {{false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone}}},
- {CONTENT_SETTING_ALLOW,
- content_settings::SETTING_SOURCE_POLICY,
- PrefSetting::kEnforcedOff,
- PrefSource::kExtension,
- {{true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy}}},
- {CONTENT_SETTING_ALLOW,
- content_settings::SETTING_SOURCE_EXTENSION,
- PrefSetting::kEnforcedOn,
- PrefSource::kDevicePolicy,
- {{true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension}}},
- {CONTENT_SETTING_ALLOW,
- content_settings::SETTING_SOURCE_SUPERVISED,
- PrefSetting::kRecommendedOff,
- PrefSource::kRecommended,
- {{false, PolicyIndicatorType::kRecommended},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {true, PolicyIndicatorType::kParent},
- {true, PolicyIndicatorType::kParent}}},
- {CONTENT_SETTING_ALLOW,
- content_settings::SETTING_SOURCE_POLICY,
- PrefSetting::kRecommendedOn,
- PrefSource::kRecommended,
- {{false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kRecommended},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy}}},
- {CONTENT_SETTING_ALLOW,
- content_settings::SETTING_SOURCE_EXTENSION,
- PrefSetting::kNotSet,
- PrefSource::kNone,
- {{false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension}}},
- {CONTENT_SETTING_BLOCK,
- content_settings::SETTING_SOURCE_SUPERVISED,
- PrefSetting::kEnforcedOff,
- PrefSource::kDevicePolicy,
- {{true, PolicyIndicatorType::kParent},
- {true, PolicyIndicatorType::kParent},
- {true, PolicyIndicatorType::kParent},
- {true, PolicyIndicatorType::kParent},
- {true, PolicyIndicatorType::kParent}}},
- {CONTENT_SETTING_BLOCK,
- content_settings::SETTING_SOURCE_POLICY,
- PrefSetting::kEnforcedOn,
- PrefSource::kExtension,
- {{true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy}}},
- {CONTENT_SETTING_BLOCK,
- content_settings::SETTING_SOURCE_EXTENSION,
- PrefSetting::kRecommendedOff,
- PrefSource::kRecommended,
- {{true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension}}},
- {CONTENT_SETTING_BLOCK,
- content_settings::SETTING_SOURCE_SUPERVISED,
- PrefSetting::kRecommendedOn,
- PrefSource::kRecommended,
- {{true, PolicyIndicatorType::kParent},
- {true, PolicyIndicatorType::kParent},
- {true, PolicyIndicatorType::kParent},
- {true, PolicyIndicatorType::kParent},
- {true, PolicyIndicatorType::kParent}}},
- {CONTENT_SETTING_BLOCK,
- content_settings::SETTING_SOURCE_POLICY,
- PrefSetting::kNotSet,
- PrefSource::kNone,
- {{true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy}}},
- {CONTENT_SETTING_SESSION_ONLY,
- content_settings::SETTING_SOURCE_EXTENSION,
- PrefSetting::kEnforcedOff,
- PrefSource::kDevicePolicy,
- {{true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension}}},
- {CONTENT_SETTING_SESSION_ONLY,
- content_settings::SETTING_SOURCE_SUPERVISED,
- PrefSetting::kEnforcedOn,
- PrefSource::kExtension,
- {{true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kParent},
- {true, PolicyIndicatorType::kParent}}},
- {CONTENT_SETTING_SESSION_ONLY,
- content_settings::SETTING_SOURCE_POLICY,
- PrefSetting::kRecommendedOff,
- PrefSource::kRecommended,
- {{false, PolicyIndicatorType::kRecommended},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {true, PolicyIndicatorType::kDevicePolicy},
- {true, PolicyIndicatorType::kDevicePolicy}}},
- {CONTENT_SETTING_SESSION_ONLY,
- content_settings::SETTING_SOURCE_EXTENSION,
- PrefSetting::kRecommendedOn,
- PrefSource::kRecommended,
- {{false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kRecommended},
- {true, PolicyIndicatorType::kExtension},
- {true, PolicyIndicatorType::kExtension}}},
- {CONTENT_SETTING_SESSION_ONLY,
- content_settings::SETTING_SOURCE_SUPERVISED,
- PrefSetting::kNotSet,
- PrefSource::kNone,
- {{false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {false, PolicyIndicatorType::kNone},
- {true, PolicyIndicatorType::kParent},
- {true, PolicyIndicatorType::kParent}}}};
-
-void SetupTestConditions(HostContentSettingsMap* map,
- sync_preferences::TestingPrefServiceSyncable* prefs,
- const CookiesManagedStateTestCase& test_case) {
- if (test_case.default_content_setting != CONTENT_SETTING_DEFAULT) {
- auto provider = std::make_unique<content_settings::MockProvider>();
- provider->SetWebsiteSetting(
- ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(),
- ContentSettingsType::COOKIES, std::string(),
- std::make_unique<base::Value>(test_case.default_content_setting));
- HostContentSettingsMap::ProviderType provider_type;
- switch (test_case.default_content_setting_source) {
- case content_settings::SETTING_SOURCE_POLICY:
- provider_type = HostContentSettingsMap::POLICY_PROVIDER;
- break;
- case content_settings::SETTING_SOURCE_EXTENSION:
- provider_type = HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER;
- break;
- case content_settings::SETTING_SOURCE_SUPERVISED:
- provider_type = HostContentSettingsMap::SUPERVISED_PROVIDER;
- break;
- case content_settings::SETTING_SOURCE_NONE:
- default:
- provider_type = HostContentSettingsMap::DEFAULT_PROVIDER;
- }
- content_settings::TestUtils::OverrideProvider(map, std::move(provider),
- provider_type);
- }
-
- if (test_case.block_third_party != PrefSetting::kNotSet) {
- bool third_party_value =
- test_case.block_third_party == PrefSetting::kRecommendedOn ||
- test_case.block_third_party == PrefSetting::kEnforcedOn;
- if (test_case.block_third_party_source == PrefSource::kExtension) {
- prefs->SetExtensionPref(prefs::kBlockThirdPartyCookies,
- std::make_unique<base::Value>(third_party_value));
- } else if (test_case.block_third_party_source ==
- PrefSource::kDevicePolicy) {
- prefs->SetManagedPref(prefs::kBlockThirdPartyCookies,
- std::make_unique<base::Value>(third_party_value));
- } else if (test_case.block_third_party_source == PrefSource::kRecommended) {
- prefs->SetRecommendedPref(
- prefs::kBlockThirdPartyCookies,
- std::make_unique<base::Value>(third_party_value));
- }
- }
-}
-
-void AssertManagedCookieStateEqual(const CookieControlsManagedState& a,
- const CookieControlsManagedState b) {
- ASSERT_EQ(a.allow_all.disabled, b.allow_all.disabled);
- ASSERT_EQ(a.allow_all.indicator, b.allow_all.indicator);
- ASSERT_EQ(a.block_third_party_incognito.disabled,
- b.block_third_party_incognito.disabled);
- ASSERT_EQ(a.block_third_party_incognito.indicator,
- b.block_third_party_incognito.indicator);
- ASSERT_EQ(a.block_third_party.disabled, b.block_third_party.disabled);
- ASSERT_EQ(a.block_third_party.indicator, b.block_third_party.indicator);
- ASSERT_EQ(a.block_all.disabled, b.block_all.disabled);
- ASSERT_EQ(a.block_all.indicator, b.block_all.indicator);
- ASSERT_EQ(a.session_only.disabled, b.session_only.disabled);
- ASSERT_EQ(a.session_only.indicator, b.session_only.indicator);
-}
-
-TEST_F(SiteSettingsHelperTest, CookiesManagedState) {
- for (auto test_case : test_cases) {
- TestingProfile profile;
- HostContentSettingsMap* map =
- HostContentSettingsMapFactory::GetForProfile(&profile);
- sync_preferences::TestingPrefServiceSyncable* prefs =
- profile.GetTestingPrefService();
- testing::Message scope_message;
- scope_message << "Content Setting:" << test_case.default_content_setting
- << " Block Third Party:"
- << static_cast<int>(test_case.block_third_party);
- SCOPED_TRACE(scope_message);
- SetupTestConditions(map, prefs, test_case);
- AssertManagedCookieStateEqual(
- site_settings::GetCookieControlsManagedState(&profile),
- test_case.expected_result);
- }
-}
-
-} // namespace
-
} // namespace site_settings
diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc
index f17e4b3a742..abf485deba1 100644
--- a/chromium/chrome/browser/ui/webui/settings/tts_handler.cc
+++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.cc
@@ -28,7 +28,7 @@ namespace settings {
TtsHandler::TtsHandler() {}
TtsHandler::~TtsHandler() {
- content::TtsController::GetInstance()->RemoveVoicesChangedDelegate(this);
+ RemoveTtsControllerDelegates();
}
void TtsHandler::HandleGetAllTtsVoiceData(const base::ListValue* args) {
@@ -176,8 +176,7 @@ void TtsHandler::OnJavascriptAllowed() {
}
void TtsHandler::OnJavascriptDisallowed() {
- content::TtsController::GetInstance()->RemoveVoicesChangedDelegate(this);
- content::TtsController::GetInstance()->RemoveUtteranceEventDelegate(this);
+ RemoveTtsControllerDelegates();
}
int TtsHandler::GetVoiceLangMatchScore(const content::VoiceData* voice,
@@ -205,4 +204,9 @@ void TtsHandler::OnTtsEngineAwake(bool success) {
OnVoicesChanged();
}
+void TtsHandler::RemoveTtsControllerDelegates() {
+ content::TtsController::GetInstance()->RemoveVoicesChangedDelegate(this);
+ content::TtsController::GetInstance()->RemoveUtteranceEventDelegate(this);
+}
+
} // namespace settings
diff --git a/chromium/chrome/browser/ui/webui/settings/tts_handler.h b/chromium/chrome/browser/ui/webui/settings/tts_handler.h
index a839dee3c0b..fa1820a32ba 100644
--- a/chromium/chrome/browser/ui/webui/settings/tts_handler.h
+++ b/chromium/chrome/browser/ui/webui/settings/tts_handler.h
@@ -45,6 +45,7 @@ class TtsHandler : public SettingsPageUIHandler,
void OnTtsEngineAwake(bool success);
int GetVoiceLangMatchScore(const content::VoiceData* voice,
const std::string& app_locale);
+ void RemoveTtsControllerDelegates();
base::WeakPtrFactory<TtsHandler> weak_factory_{this};
diff --git a/chromium/chrome/browser/ui/webui/settings_utils_linux.cc b/chromium/chrome/browser/ui/webui/settings_utils_linux.cc
index d56f9f30684..9043aaf40eb 100644
--- a/chromium/chrome/browser/ui/webui/settings_utils_linux.cc
+++ b/chromium/chrome/browser/ui/webui/settings_utils_linux.cc
@@ -11,7 +11,6 @@
#include "base/files/file_util.h"
#include "base/nix/xdg_util.h"
#include "base/process/launch.h"
-#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "build/build_config.h"
@@ -134,8 +133,8 @@ void DetectAndStartProxyConfigUtil(int render_process_id,
if (launched)
return;
- base::PostTask(FROM_HERE, {BrowserThread::UI},
- base::BindOnce(&ShowLinuxProxyConfigUrl, render_process_id,
+ content::GetUIThreadTaskRunner({})->PostTask(
+ FROM_HERE, base::BindOnce(&ShowLinuxProxyConfigUrl, render_process_id,
render_view_id));
}
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 948ce452f56..c418b7e5c9c 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
@@ -18,15 +18,12 @@
#include "base/strings/utf_string_conversions.h"
#include "base/supports_user_data.h"
#include "base/threading/sequenced_task_runner_handle.h"
-#include "chrome/browser/browser_process.h"
#include "chrome/browser/policy/chrome_policy_conversions_client.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h"
#include "chrome/browser/policy/profile_policy_connector.h"
-#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/dice_signed_in_profile_creator.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"
@@ -89,54 +86,6 @@ AccountInfo GetAccountInfo(signin::IdentityManager* identity_manager,
: AccountInfo();
}
-class TokensLoadedCallbackRunner : public signin::IdentityManager::Observer {
- public:
- // Calls |callback| when tokens are loaded.
- static void RunWhenLoaded(Profile* profile,
- base::OnceCallback<void(Profile*)> callback) {
- auto* identity_manager = IdentityManagerFactory::GetForProfile(profile);
- if (identity_manager->AreRefreshTokensLoaded()) {
- std::move(callback).Run(profile);
- return;
- }
- // TokensLoadedCallbackRunner deletes itself after running the callback.
- new TokensLoadedCallbackRunner(
- identity_manager,
- DiceTurnSyncOnHelperShutdownNotifierFactory::GetInstance()->Get(
- profile),
- base::BindOnce(std::move(callback), profile));
- }
-
- private:
- TokensLoadedCallbackRunner(signin::IdentityManager* identity_manager,
- KeyedServiceShutdownNotifier* shutdown_notifier,
- base::OnceClosure callback)
- : identity_manager_(identity_manager),
- callback_(std::move(callback)),
- shutdown_subscription_(shutdown_notifier->Subscribe(
- base::Bind(&TokensLoadedCallbackRunner::OnShutdown,
- base::Unretained(this)))) {
- DCHECK(!identity_manager_->AreRefreshTokensLoaded());
- scoped_identity_manager_observer_.Add(identity_manager_);
- }
-
- // signin::IdentityManager::Observer implementation:
- void OnRefreshTokensLoaded() override {
- std::move(callback_).Run();
- delete this;
- }
-
- void OnShutdown() { delete this; }
-
- signin::IdentityManager* identity_manager_;
- ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer>
- scoped_identity_manager_observer_{this};
- base::OnceClosure callback_;
- std::unique_ptr<KeyedServiceShutdownNotifier::Subscription>
- shutdown_subscription_;
-
- DISALLOW_COPY_AND_ASSIGN(TokensLoadedCallbackRunner);
-};
struct CurrentDiceTurnSyncOnHelperUserData
: public base::SupportsUserData::Data {
@@ -417,47 +366,13 @@ void DiceTurnSyncOnHelper::OnProviderUpdatePropagated(
}
void DiceTurnSyncOnHelper::CreateNewSignedInProfile() {
- // Create a new profile and have it call back when done so we can start the
- // signin flow.
- ProfileAttributesStorage& storage =
- g_browser_process->profile_manager()->GetProfileAttributesStorage();
- size_t icon_index = storage.ChooseAvatarIconIndexForNewProfile();
-
- ProfileManager::CreateMultiProfileAsync(
- storage.ChooseNameForNewProfile(icon_index),
- profiles::GetDefaultAvatarIconUrl(icon_index),
- base::BindRepeating(&DiceTurnSyncOnHelper::OnNewProfileCreated,
- weak_pointer_factory_.GetWeakPtr()));
-}
-
-void DiceTurnSyncOnHelper::OnNewProfileCreated(Profile* new_profile,
- Profile::CreateStatus status) {
- DCHECK_NE(profile_, new_profile);
-
- // TODO(atwilson): On error, unregister the client to release the DMToken
- // and surface a better error for the user.
- switch (status) {
- case Profile::CREATE_STATUS_LOCAL_FAIL:
- NOTREACHED() << "Error creating new profile";
- AbortAndDelete();
- break;
- case Profile::CREATE_STATUS_CREATED:
- // Ignore this, wait for profile to be initialized.
- break;
- case Profile::CREATE_STATUS_INITIALIZED:
- TokensLoadedCallbackRunner::RunWhenLoaded(
- new_profile,
- base::BindOnce(&DiceTurnSyncOnHelper::OnNewProfileTokensLoaded,
- weak_pointer_factory_.GetWeakPtr()));
- break;
- case Profile::CREATE_STATUS_REMOTE_FAIL:
- case Profile::CREATE_STATUS_CANCELED:
- case Profile::MAX_CREATE_STATUS: {
- NOTREACHED() << "Invalid profile creation status";
- AbortAndDelete();
- break;
- }
- }
+ DCHECK(!dice_signed_in_profile_creator_);
+ // Unretained is fine because the profile creator is owned by this.
+ dice_signed_in_profile_creator_ =
+ std::make_unique<DiceSignedInProfileCreator>(
+ profile_, account_info_.account_id,
+ base::BindOnce(&DiceTurnSyncOnHelper::OnNewSignedInProfileCreated,
+ base::Unretained(this)));
}
syncer::SyncService* DiceTurnSyncOnHelper::GetSyncService() {
@@ -466,14 +381,18 @@ syncer::SyncService* DiceTurnSyncOnHelper::GetSyncService() {
: nullptr;
}
-void DiceTurnSyncOnHelper::OnNewProfileTokensLoaded(Profile* new_profile) {
- // This deletes the token locally, even in KEEP_ACCOUNT mode.
- auto* accounts_mutator = identity_manager_->GetAccountsMutator();
- auto* new_profile_accounts_mutator =
- IdentityManagerFactory::GetForProfile(new_profile)->GetAccountsMutator();
- accounts_mutator->MoveAccount(new_profile_accounts_mutator,
- account_info_.account_id);
+void DiceTurnSyncOnHelper::OnNewSignedInProfileCreated(Profile* new_profile) {
+ DCHECK(dice_signed_in_profile_creator_);
+ dice_signed_in_profile_creator_.reset();
+ if (!new_profile) {
+ // TODO(atwilson): On error, unregister the client to release the DMToken
+ // and surface a better error for the user.
+ AbortAndDelete();
+ return;
+ }
+
+ DCHECK_NE(profile_, new_profile);
SwitchToProfile(new_profile);
DCHECK_EQ(profile_, new_profile);
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 58c0074683d..84c45a4cf8d 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
@@ -21,6 +21,7 @@
#include "components/signin/public/identity_manager/account_info.h"
class Browser;
+class DiceSignedInProfileCreator;
namespace signin {
class IdentityManager;
@@ -171,12 +172,8 @@ class DiceTurnSyncOnHelper
// in-progress auth credentials currently stored in this object.
void CreateNewSignedInProfile();
- // Callback invoked once a profile is created, so we can transfer the
- // credentials.
- void OnNewProfileCreated(Profile* new_profile, Profile::CreateStatus status);
-
- // Callback invoked once the token service is ready for the new profile.
- void OnNewProfileTokensLoaded(Profile* new_profile);
+ // Called when the new profile is created.
+ void OnNewSignedInProfileCreated(Profile* new_profile);
// Returns the SyncService, or nullptr if sync is not allowed.
syncer::SyncService* GetSyncService();
@@ -230,6 +227,7 @@ class DiceTurnSyncOnHelper
base::ScopedClosureRunner scoped_callback_runner_;
std::unique_ptr<SyncStartupTracker> sync_startup_tracker_;
+ std::unique_ptr<DiceSignedInProfileCreator> dice_signed_in_profile_creator_;
std::unique_ptr<KeyedServiceShutdownNotifier::Subscription>
shutdown_subscription_;
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 0a6f462ee69..213a2f515cf 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
@@ -709,9 +709,7 @@ TEST_F(DiceTurnSyncOnHelperTest, ShowSyncDialogForEndConsumerAccount) {
std::unique_ptr<unified_consent::UrlKeyedDataCollectionConsentHelper>
url_keyed_collection_helper =
unified_consent::UrlKeyedDataCollectionConsentHelper::
- NewAnonymizedDataCollectionConsentHelper(
- pref_service,
- ProfileSyncServiceFactory::GetForProfile(profile()));
+ NewAnonymizedDataCollectionConsentHelper(pref_service);
EXPECT_FALSE(url_keyed_collection_helper->IsEnabled());
// Signin flow.
diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.cc b/chromium/chrome/browser/ui/webui/signin/inline_login_dialog_chromeos.cc
index 58d3c73da50..b6f8cc8f089 100644
--- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.cc
+++ b/chromium/chrome/browser/ui/webui/signin/inline_login_dialog_chromeos.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h"
+#include "chrome/browser/ui/webui/signin/inline_login_dialog_chromeos.h"
#include <algorithm>
#include <string>
@@ -36,7 +36,7 @@ namespace chromeos {
namespace {
-InlineLoginHandlerDialogChromeOS* dialog = nullptr;
+InlineLoginDialogChromeOS* dialog = nullptr;
constexpr int kSigninDialogWidth = 768;
constexpr int kSigninDialogHeight = 640;
@@ -66,7 +66,7 @@ GURL GetUrlWithEmailParam(base::StringPiece url_string,
}
GURL GetInlineLoginUrl(const std::string& email,
- const InlineLoginHandlerDialogChromeOS::Source& source) {
+ const InlineLoginDialogChromeOS::Source& source) {
if (IsDeviceAccountEmail(email)) {
// It's a device account re-auth.
return GetUrlWithEmailParam(chrome::kChromeUIChromeSigninURL, email);
@@ -83,21 +83,17 @@ GURL GetInlineLoginUrl(const std::string& email,
}
// User type is Child.
if (!features::IsEduCoexistenceEnabled() ||
- source == InlineLoginHandlerDialogChromeOS::Source::kArc) {
+ source == InlineLoginDialogChromeOS::Source::kArc) {
return GURL(chrome::kChromeUIAccountManagerErrorURL);
}
- DCHECK_EQ(std::string(chrome::kChromeUIChromeSigninURL).back(), '/');
- // chrome://chrome-signin/edu
- const std::string kEduAccountLoginURL =
- std::string(chrome::kChromeUIChromeSigninURL) + "edu";
- return GetUrlWithEmailParam(kEduAccountLoginURL, email);
+ return GetUrlWithEmailParam(chrome::kChromeUIEDUCoexistenceLoginURL, email);
}
} // namespace
// static
-void InlineLoginHandlerDialogChromeOS::Show(const std::string& email,
- const Source& source) {
+void InlineLoginDialogChromeOS::Show(const std::string& email,
+ const Source& source) {
base::UmaHistogramEnumeration(kAccountAdditionSource, source);
// If the dialog was triggered as a response to background request, it could
// get displayed on the lock screen. In this case it is safe to ignore it,
@@ -112,8 +108,8 @@ void InlineLoginHandlerDialogChromeOS::Show(const std::string& email,
}
// Will be deleted by |SystemWebDialogDelegate::OnDialogClosed|.
- dialog = new InlineLoginHandlerDialogChromeOS(
- GetInlineLoginUrl(email, source), source);
+ dialog =
+ new InlineLoginDialogChromeOS(GetInlineLoginUrl(email, source), source);
dialog->ShowSystemDialog();
// TODO(crbug.com/1016828): Remove/update this after the dialog behavior on
@@ -122,73 +118,71 @@ void InlineLoginHandlerDialogChromeOS::Show(const std::string& email,
->SetBackdropType(ash::WindowBackdrop::BackdropType::kSemiOpaque);
}
-void InlineLoginHandlerDialogChromeOS::Show(const Source& source) {
+void InlineLoginDialogChromeOS::Show(const Source& source) {
Show(/* email= */ std::string(), source);
}
// static
-void InlineLoginHandlerDialogChromeOS::UpdateEduCoexistenceFlowResult(
+void InlineLoginDialogChromeOS::UpdateEduCoexistenceFlowResult(
EduCoexistenceFlowResult result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (dialog)
dialog->SetEduCoexistenceFlowResult(result);
}
-void InlineLoginHandlerDialogChromeOS::AdjustWidgetInitParams(
+void InlineLoginDialogChromeOS::AdjustWidgetInitParams(
views::Widget::InitParams* params) {
params->z_order = ui::ZOrderLevel::kNormal;
}
-gfx::Size InlineLoginHandlerDialogChromeOS::GetMaximumDialogSize() {
+gfx::Size InlineLoginDialogChromeOS::GetMaximumDialogSize() {
gfx::Size size;
GetDialogSize(&size);
return size;
}
-gfx::NativeView InlineLoginHandlerDialogChromeOS::GetHostView() const {
+gfx::NativeView InlineLoginDialogChromeOS::GetHostView() const {
return dialog_window();
}
-gfx::Point InlineLoginHandlerDialogChromeOS::GetDialogPosition(
- const gfx::Size& size) {
+gfx::Point InlineLoginDialogChromeOS::GetDialogPosition(const gfx::Size& size) {
gfx::Size host_size = GetHostView()->bounds().size();
// Show all sub-dialogs at center-top.
return gfx::Point(std::max(0, (host_size.width() - size.width()) / 2), 0);
}
-void InlineLoginHandlerDialogChromeOS::AddObserver(
+void InlineLoginDialogChromeOS::AddObserver(
web_modal::ModalDialogHostObserver* observer) {}
-void InlineLoginHandlerDialogChromeOS::RemoveObserver(
+void InlineLoginDialogChromeOS::RemoveObserver(
web_modal::ModalDialogHostObserver* observer) {}
-void InlineLoginHandlerDialogChromeOS::SetEduCoexistenceFlowResult(
+void InlineLoginDialogChromeOS::SetEduCoexistenceFlowResult(
EduCoexistenceFlowResult result) {
edu_coexistence_flow_result_ = result;
}
-InlineLoginHandlerDialogChromeOS::InlineLoginHandlerDialogChromeOS(
- const GURL& url,
- const Source& source)
+InlineLoginDialogChromeOS::InlineLoginDialogChromeOS(const GURL& url,
+ const Source& source)
: SystemWebDialogDelegate(url, base::string16() /* title */),
delegate_(this),
source_(source),
url_(url) {}
-InlineLoginHandlerDialogChromeOS::~InlineLoginHandlerDialogChromeOS() {
+InlineLoginDialogChromeOS::~InlineLoginDialogChromeOS() {
DCHECK_EQ(this, dialog);
dialog = nullptr;
}
-void InlineLoginHandlerDialogChromeOS::GetDialogSize(gfx::Size* size) const {
+void InlineLoginDialogChromeOS::GetDialogSize(gfx::Size* size) const {
const display::Display display =
display::Screen::GetScreen()->GetDisplayNearestWindow(dialog_window());
size->SetSize(std::min(kSigninDialogWidth, display.work_area().width()),
std::min(kSigninDialogHeight, display.work_area().height()));
}
-std::string InlineLoginHandlerDialogChromeOS::GetDialogArgs() const {
+std::string InlineLoginDialogChromeOS::GetDialogArgs() const {
if (url_.GetWithEmptyPath() !=
GURL(chrome::kChromeUIAccountManagerErrorURL)) {
return std::string();
@@ -211,11 +205,11 @@ std::string InlineLoginHandlerDialogChromeOS::GetDialogArgs() const {
return data;
}
-bool InlineLoginHandlerDialogChromeOS::ShouldShowDialogTitle() const {
+bool InlineLoginDialogChromeOS::ShouldShowDialogTitle() const {
return false;
}
-void InlineLoginHandlerDialogChromeOS::OnDialogShown(content::WebUI* webui) {
+void InlineLoginDialogChromeOS::OnDialogShown(content::WebUI* webui) {
SystemWebDialogDelegate::OnDialogShown(webui);
web_modal::WebContentsModalDialogManager::CreateForWebContents(
webui->GetWebContents());
@@ -224,8 +218,7 @@ void InlineLoginHandlerDialogChromeOS::OnDialogShown(content::WebUI* webui) {
->SetDelegate(&delegate_);
}
-void InlineLoginHandlerDialogChromeOS::OnDialogClosed(
- const std::string& json_retval) {
+void InlineLoginDialogChromeOS::OnDialogClosed(const std::string& json_retval) {
if (ProfileManager::GetActiveUserProfile()->IsChild()) {
DCHECK(edu_coexistence_flow_result_.has_value());
base::UmaHistogramEnumeration("AccountManager.EduCoexistence.FlowResult",
diff --git a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h b/chromium/chrome/browser/ui/webui/signin/inline_login_dialog_chromeos.h
index 3f1eed30662..73daeba9d1c 100644
--- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h
+++ b/chromium/chrome/browser/ui/webui/signin/inline_login_dialog_chromeos.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_DIALOG_CHROMEOS_H_
-#define CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_DIALOG_CHROMEOS_H_
+#ifndef CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_DIALOG_CHROMEOS_H_
+#define CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_DIALOG_CHROMEOS_H_
#include <string>
@@ -20,9 +20,8 @@ namespace chromeos {
// Extends from |SystemWebDialogDelegate| to create an always-on-top but movable
// dialog. It is intentionally made movable so that users can copy-paste account
// passwords from password managers.
-class InlineLoginHandlerDialogChromeOS
- : public SystemWebDialogDelegate,
- public web_modal::WebContentsModalDialogHost {
+class InlineLoginDialogChromeOS : public SystemWebDialogDelegate,
+ public web_modal::WebContentsModalDialogHost {
public:
// The source UX surface used for launching the account addition /
// re-authentication dialog. This should be as specific as possible.
@@ -88,8 +87,8 @@ class InlineLoginHandlerDialogChromeOS
void SetEduCoexistenceFlowResult(EduCoexistenceFlowResult result);
protected:
- InlineLoginHandlerDialogChromeOS(const GURL& url, const Source& source);
- ~InlineLoginHandlerDialogChromeOS() override;
+ InlineLoginDialogChromeOS(const GURL& url, const Source& source);
+ ~InlineLoginDialogChromeOS() override;
// ui::WebDialogDelegate overrides
void GetDialogSize(gfx::Size* size) const override;
@@ -104,9 +103,9 @@ class InlineLoginHandlerDialogChromeOS
const GURL url_;
base::Optional<EduCoexistenceFlowResult> edu_coexistence_flow_result_;
- DISALLOW_COPY_AND_ASSIGN(InlineLoginHandlerDialogChromeOS);
+ DISALLOW_COPY_AND_ASSIGN(InlineLoginDialogChromeOS);
};
} // namespace chromeos
-#endif // CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_DIALOG_CHROMEOS_H_
+#endif // CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_DIALOG_CHROMEOS_H_
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 4d138271eb6..261a5bb84f6 100644
--- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc
+++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.cc
@@ -60,10 +60,6 @@ void InlineLoginHandler::RegisterMessages() {
base::BindRepeating(&InlineLoginHandler::HandleSwitchToFullTabMessage,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
- "navigationButtonClicked",
- base::BindRepeating(&InlineLoginHandler::HandleNavigationButtonClicked,
- base::Unretained(this)));
- web_ui()->RegisterMessageCallback(
"dialogClose", base::BindRepeating(&InlineLoginHandler::HandleDialogClose,
base::Unretained(this)));
}
@@ -170,8 +166,8 @@ void InlineLoginHandler::HandleCompleteLoginMessage(
void InlineLoginHandler::HandleCompleteLoginMessageWithCookies(
const base::ListValue& args,
- const net::CookieStatusList& cookies,
- const net::CookieStatusList& excluded_cookies) {
+ const net::CookieAccessResultList& cookies,
+ const net::CookieAccessResultList& excluded_cookies) {
const base::Value& dict = args.GetList()[0];
const std::string& email = dict.FindKey("email")->GetString();
@@ -179,9 +175,9 @@ void InlineLoginHandler::HandleCompleteLoginMessageWithCookies(
const std::string& gaia_id = dict.FindKey("gaiaId")->GetString();
std::string auth_code;
- for (const auto& cookie_with_status : cookies) {
- if (cookie_with_status.cookie.Name() == "oauth_code")
- auth_code = cookie_with_status.cookie.Value();
+ for (const auto& cookie_with_access_result : cookies) {
+ if (cookie_with_access_result.cookie.Name() == "oauth_code")
+ auth_code = cookie_with_access_result.cookie.Value();
}
bool skip_for_now = dict.FindBoolKey("skipForNow").value_or(false);
@@ -233,16 +229,6 @@ void InlineLoginHandler::HandleSwitchToFullTabMessage(
CloseDialogFromJavascript();
}
-void InlineLoginHandler::HandleNavigationButtonClicked(
- const base::ListValue* args) {
-#if !defined(OS_CHROMEOS)
- NOTREACHED() << "The inline login handler is no longer used in a browser "
- "or tab modal dialog.";
-#else
- FireWebUIListener("navigate-back-in-webview");
-#endif
-}
-
void InlineLoginHandler::HandleDialogClose(const base::ListValue* args) {
#if !defined(OS_CHROMEOS)
// Does nothing if user manager is not showing.
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 d8e59330c67..ad371ccb5c9 100644
--- a/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h
+++ b/chromium/chrome/browser/ui/webui/signin/inline_login_handler.h
@@ -66,16 +66,12 @@ class InlineLoginHandler : public content::WebUIMessageHandler {
// from the CookieManager.
void HandleCompleteLoginMessageWithCookies(
const base::ListValue& args,
- const net::CookieStatusList& cookies,
- const net::CookieStatusList& excluded_cookies);
+ const net::CookieAccessResultList& cookies,
+ const net::CookieAccessResultList& excluded_cookies);
// JS callback to switch the UI from a constrainted dialog to a full tab.
void HandleSwitchToFullTabMessage(const base::ListValue* args);
- // Handles the web ui message sent when the navigation button is clicked by
- // the user, requesting either a back navigation or closing the dialog.
- void HandleNavigationButtonClicked(const base::ListValue* args);
-
// Handles the web ui message sent when the window is closed from javascript.
virtual void HandleDialogClose(const base::ListValue* args);
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 1eee7735f97..b02e9de9753 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
@@ -20,8 +20,8 @@
#include "chrome/browser/signin/chrome_device_id_helper.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/ui/browser_commands.h"
+#include "chrome/browser/ui/webui/signin/inline_login_dialog_chromeos.h"
#include "chrome/browser/ui/webui/signin/inline_login_handler.h"
-#include "chrome/browser/ui/webui/signin/inline_login_handler_dialog_chromeos.h"
#include "chromeos/components/account_manager/account_manager.h"
#include "chromeos/components/account_manager/account_manager_factory.h"
#include "chromeos/constants/chromeos_features.h"
@@ -319,9 +319,8 @@ void InlineLoginHandlerChromeOS::CompleteLogin(const std::string& email,
const std::string* parentId =
edu_login_params.FindStringKey("parentObfuscatedGaiaId");
CHECK(parentId);
- InlineLoginHandlerDialogChromeOS::UpdateEduCoexistenceFlowResult(
- InlineLoginHandlerDialogChromeOS::EduCoexistenceFlowResult::
- kFlowCompleted);
+ InlineLoginDialogChromeOS::UpdateEduCoexistenceFlowResult(
+ InlineLoginDialogChromeOS::EduCoexistenceFlowResult::kFlowCompleted);
// ChildSigninHelper deletes itself after its work is done.
new ChildSigninHelper(
account_manager, close_dialog_closure_,
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 c0cf761b098..39f070896a1 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
@@ -380,8 +380,10 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened(
}
}
#endif
-
if (reason == HandlerSigninReason::UNLOCK) {
+ DCHECK(!identity_manager->GetPrimaryAccountInfo(signin::ConsentLevel::kSync)
+ .IsEmpty());
+
identity_manager->GetAccountsMutator()->AddOrUpdateAccount(
gaia_id_, email_, result.refresh_token,
result.is_under_advanced_protection,
@@ -396,11 +398,9 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened(
base::BindOnce(&InlineLoginHandlerImpl::CloseTab, handler_));
}
- if (identity_manager->HasPrimaryAccount()) {
- identity_manager->GetAccountsCookieMutator()->AddAccountToCookie(
- identity_manager->GetPrimaryAccountId(),
- gaia::GaiaSource::kPrimaryAccountManager, {});
- }
+ identity_manager->GetAccountsCookieMutator()->AddAccountToCookie(
+ identity_manager->GetPrimaryAccountId(),
+ gaia::GaiaSource::kPrimaryAccountManager, {});
signin_metrics::LogSigninReason(
GetSigninReasonFromHandlerSigninReason(reason));
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 1e0b5bff4ad..c00843b7b17 100644
--- a/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc
+++ b/chromium/chrome/browser/ui/webui/signin/inline_login_ui.cc
@@ -26,6 +26,7 @@
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/common/content_switches.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/profiles/profile_helper.h"
@@ -83,23 +84,18 @@ void AddEduStrings(content::WebUIDataSource* source,
l10n_util::GetStringFUTF16(
IDS_EDU_LOGIN_INFO_BODY,
base::ASCIIToUTF16(chrome::kGsuiteTermsEducationPrivacyURL)));
- source->AddString(
- "parentInfoDataProtectionText",
- l10n_util::GetStringFUTF16(
- IDS_EDU_LOGIN_INFO_DATA_PROTECTION,
- base::ASCIIToUTF16(chrome::kClassroomSigninLearnMoreURL)));
- source->AddLocalizedString("parentInfoResourcesAvailabilityText",
- IDS_EDU_LOGIN_INFO_RESOURCES_AVAILABILITY);
source->AddLocalizedString("coexistenceTitle",
- IDS_EDU_LOGIN_COEXISTENCE_TITLE);
- source->AddLocalizedString("coexistenceBody", IDS_EDU_LOGIN_COEXISTENCE_BODY);
+ IDS_EDU_LOGIN_INFO_COEXISTENCE_TITLE);
+ source->AddLocalizedString("coexistenceBody",
+ IDS_EDU_LOGIN_INFO_COEXISTENCE_BODY);
}
#endif // defined(OS_CHROMEOS)
content::WebUIDataSource* CreateWebUIDataSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIChromeSigninHost);
- source->OverrideContentSecurityPolicyObjectSrc("object-src chrome:;");
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ObjectSrc, "object-src chrome:;");
source->UseStringsJs();
source->SetDefaultResource(IDR_INLINE_LOGIN_HTML);
@@ -143,7 +139,8 @@ content::WebUIDataSource* CreateWebUIDataSource() {
webui::AddResourcePathsBulk(source, kResources);
#if defined(OS_CHROMEOS)
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources chrome://test 'self';");
webui::SetupWebUIDataSource(
source,
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 fcfe998400d..6f2d76198e2 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
@@ -4,6 +4,8 @@
#include "chrome/browser/ui/webui/signin/login_ui_test_utils.h"
+#include "base/bind.h"
+#include "base/notreached.h"
#include "base/run_loop.h"
#include "base/scoped_observer.h"
#include "base/strings/stringprintf.h"
@@ -52,9 +54,7 @@ class SignInObserver : public signin::IdentityManager::Observer {
SignInObserver() : seen_(false), running_(false), signed_in_(false) {}
// Returns whether a GoogleSigninSucceeded event has happened.
- bool DidSignIn() {
- return signed_in_;
- }
+ bool DidSignIn() { return signed_in_; }
// Blocks and waits until the user signs in. Wait() does not block if a
// GoogleSigninSucceeded has already occurred.
@@ -193,6 +193,8 @@ void WaitUntilAnyElementExistsInSigninFrame(
enum class SyncConfirmationDialogAction { kConfirm, kCancel };
+enum class ReauthDialogAction { kConfirm, kCancel };
+
#if !defined(OS_CHROMEOS)
std::string GetButtonIdForSyncConfirmationDialogAction(
SyncConfirmationDialogAction action) {
@@ -226,6 +228,16 @@ std::string GetButtonIdForSigninEmailConfirmationDialogAction(
}
}
+std::string GetButtonIdForReauthConfirmationDialogAction(
+ ReauthDialogAction action) {
+ switch (action) {
+ case ReauthDialogAction::kConfirm:
+ return "confirmButton";
+ case ReauthDialogAction::kCancel:
+ return "cancelButton";
+ }
+}
+
std::string GetButtonSelectorForApp(const std::string& app,
const std::string& button_id) {
return base::StringPrintf(
@@ -233,6 +245,23 @@ std::string GetButtonSelectorForApp(const std::string& app,
"document.querySelector('%s').shadowRoot.querySelector('#%s'))",
app.c_str(), app.c_str(), button_id.c_str());
}
+
+bool IsElementReady(content::WebContents* web_contents,
+ const std::string& element_selector) {
+ std::string message;
+ std::string find_element_js = base::StringPrintf(
+ "if (document.readyState != 'complete') {"
+ " window.domAutomationController.send('DocumentNotReady');"
+ "} else if (%s == null) {"
+ " window.domAutomationController.send('NotFound');"
+ "} else {"
+ " window.domAutomationController.send('Ok');"
+ "}",
+ element_selector.c_str());
+ EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+ web_contents, find_element_js, &message));
+ return message == "Ok";
+}
#endif // !defined(OS_CHROMEOS)
} // namespace
@@ -258,19 +287,7 @@ class SigninViewControllerTestUtil {
std::string button_selector = GetButtonSelectorForApp(
"sync-confirmation-app",
GetButtonIdForSyncConfirmationDialogAction(action));
- std::string message;
- std::string find_button_js = base::StringPrintf(
- "if (document.readyState != 'complete') {"
- " window.domAutomationController.send('DocumentNotReady');"
- "} else if (%s == null) {"
- " window.domAutomationController.send('NotFound');"
- "} else {"
- " window.domAutomationController.send('Ok');"
- "}",
- button_selector.c_str());
- EXPECT_TRUE(content::ExecuteScriptAndExtractString(
- dialog_web_contents, find_button_js, &message));
- if (message != "Ok")
+ if (!IsElementReady(dialog_web_contents, button_selector))
return false;
// This cannot be a synchronous call, because it closes the window as a side
@@ -302,19 +319,7 @@ class SigninViewControllerTestUtil {
std::string button_selector = GetButtonSelectorForApp(
"signin-email-confirmation-app",
GetButtonIdForSigninEmailConfirmationDialogAction(action));
- std::string message;
- std::string find_button_js = base::StringPrintf(
- "if (document.readyState != 'complete') {"
- " window.domAutomationController.send('DocumentNotReady');"
- "} else if (%s == null || %s == null) {"
- " window.domAutomationController.send('NotFound');"
- "} else {"
- " window.domAutomationController.send('Ok');"
- "}",
- radio_button_selector.c_str(), button_selector.c_str());
- EXPECT_TRUE(content::ExecuteScriptAndExtractString(
- dialog_web_contents, find_button_js, &message));
- if (message != "Ok")
+ if (!IsElementReady(dialog_web_contents, button_selector))
return false;
// This cannot be a synchronous call, because it closes the window as a side
@@ -326,6 +331,35 @@ class SigninViewControllerTestUtil {
return true;
#endif
}
+
+ static bool TryCompleteReauthConfirmationDialog(Browser* browser,
+ ReauthDialogAction action) {
+#if defined(OS_CHROMEOS)
+ NOTREACHED();
+ return false;
+#else
+ SigninViewController* signin_view_controller =
+ browser->signin_view_controller();
+ DCHECK(signin_view_controller);
+ if (!signin_view_controller->ShowsModalDialog())
+ return false;
+
+ content::WebContents* dialog_web_contents =
+ signin_view_controller->GetModalDialogWebContentsForTesting();
+ DCHECK(dialog_web_contents);
+ std::string button_selector = GetButtonSelectorForApp(
+ "signin-reauth-app",
+ GetButtonIdForReauthConfirmationDialogAction(action));
+ if (!IsElementReady(dialog_web_contents, button_selector))
+ return false;
+
+ // This cannot be a synchronous call, because it closes the window as a side
+ // effect, which may cause the javascript execution to never finish.
+ content::ExecuteScriptAsync(dialog_web_contents,
+ button_selector + ".click();");
+ return true;
+#endif
+ }
};
void WaitUntilUIReady(Browser* browser) {
@@ -472,4 +506,28 @@ bool CompleteSigninEmailConfirmationDialog(
return false;
}
+bool CompleteReauthConfirmationDialog(Browser* browser,
+ base::TimeDelta timeout,
+ ReauthDialogAction action) {
+ const base::Time expire_time = base::Time::Now() + timeout;
+ while (base::Time::Now() <= expire_time) {
+ if (SigninViewControllerTestUtil::TryCompleteReauthConfirmationDialog(
+ browser, action))
+ return true;
+ RunLoopFor(base::TimeDelta::FromMilliseconds(1000));
+ }
+ return false;
+}
+
+bool ConfirmReauthConfirmationDialog(Browser* browser,
+ base::TimeDelta timeout) {
+ return CompleteReauthConfirmationDialog(browser, timeout,
+ ReauthDialogAction::kConfirm);
+}
+
+bool CancelReauthConfirmationDialog(Browser* browser, base::TimeDelta timeout) {
+ return CompleteReauthConfirmationDialog(browser, timeout,
+ ReauthDialogAction::kCancel);
+}
+
} // namespace login_ui_test_utils
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 b9440eabf6f..5d3833932d7 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
@@ -60,6 +60,16 @@ bool CompleteSigninEmailConfirmationDialog(
base::TimeDelta timeout,
SigninEmailConfirmationDialog::Action action);
+// Waits for the reauth confirmation dialog to get displayed, then executes
+// javascript to click on confirm button. Returns false if dialog wasn't
+// dismissed before |timeout|.
+bool ConfirmReauthConfirmationDialog(Browser* browser, base::TimeDelta timeout);
+
+// Waits for the reauth confirmation dialog to get displayed, then executes
+// javascript to click on cancel button. Returns false if dialog wasn't
+// dismissed before |timeout|.
+bool CancelReauthConfirmationDialog(Browser* browser, base::TimeDelta timeout);
+
} // namespace login_ui_test_utils
#endif // CHROME_BROWSER_UI_WEBUI_SIGNIN_LOGIN_UI_TEST_UTILS_H_
diff --git a/chromium/chrome/browser/ui/webui/signin/profile_picker_ui.h b/chromium/chrome/browser/ui/webui/signin/profile_picker_ui.h
index 68feea31425..10274bf8cc3 100644
--- a/chromium/chrome/browser/ui/webui/signin/profile_picker_ui.h
+++ b/chromium/chrome/browser/ui/webui/signin/profile_picker_ui.h
@@ -5,6 +5,7 @@
#ifndef CHROME_BROWSER_UI_WEBUI_SIGNIN_PROFILE_PICKER_UI_H_
#define CHROME_BROWSER_UI_WEBUI_SIGNIN_PROFILE_PICKER_UI_H_
+#include "base/macros.h"
#include "content/public/browser/web_ui_controller.h"
// The WebUI controller for chrome://profile-picker/.
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 b08ea973884..7c3861b0d3c 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
@@ -15,7 +15,6 @@
#include "base/strings/utf_string_conversions.h"
#include "base/task_runner_util.h"
#include "base/threading/thread_restrictions.h"
-#include "base/value_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.cc b/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.cc
index 025f5941b5c..d96fffe86d4 100644
--- a/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.cc
+++ b/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.cc
@@ -227,3 +227,8 @@ void SigninEmailConfirmationDialog::ResizeNativeView(int height) {
content::WebContents* SigninEmailConfirmationDialog::GetWebContents() {
return GetDialogWebContents();
}
+
+void SigninEmailConfirmationDialog::SetWebContents(
+ content::WebContents* web_contents) {
+ NOTIMPLEMENTED();
+}
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.h b/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.h
index 587587a9b95..1e6fab521cf 100644
--- a/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.h
+++ b/chromium/chrome/browser/ui/webui/signin/signin_email_confirmation_dialog.h
@@ -80,6 +80,7 @@ class SigninEmailConfirmationDialog : public ui::WebDialogDelegate,
void CloseModalSignin() override;
void ResizeNativeView(int height) override;
content::WebContents* GetWebContents() override;
+ void SetWebContents(content::WebContents* web_contents) override;
// Shows the dialog and releases ownership of this object. Another object will
// take ownership and delete this object.
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_error_handler.cc b/chromium/chrome/browser/ui/webui/signin/signin_error_handler.cc
index 480a3eecadf..3c206e17792 100644
--- a/chromium/chrome/browser/ui/webui/signin/signin_error_handler.cc
+++ b/chromium/chrome/browser/ui/webui/signin/signin_error_handler.cc
@@ -89,13 +89,6 @@ void SigninErrorHandler::HandleInitializedWithSize(
FireWebUIListener("switch-button-unavailable");
signin::SetInitializedModalHeight(browser_, web_ui(), args);
-
- // After the dialog is shown, some platforms might have an element focused.
- // To be consistent, clear the focused element on all platforms.
- // TODO(anthonyvd): Figure out why this is needed on Mac and not other
- // platforms and if there's a way to start unfocused while avoiding this
- // workaround.
- FireWebUIListener("clear-focus");
}
void SigninErrorHandler::CloseDialog() {
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_reauth_handler.cc b/chromium/chrome/browser/ui/webui/signin/signin_reauth_handler.cc
new file mode 100644
index 00000000000..b56edbbdd8b
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/signin/signin_reauth_handler.cc
@@ -0,0 +1,72 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/signin/signin_reauth_handler.h"
+
+#include "base/bind.h"
+#include "chrome/browser/ui/signin_reauth_view_controller.h"
+#include "content/public/browser/web_ui.h"
+#include "ui/base/webui/web_ui_util.h"
+
+SigninReauthHandler::SigninReauthHandler(SigninReauthViewController* controller)
+ : controller_(controller) {
+ DCHECK(controller_);
+ controller_observer_.Add(controller_);
+}
+
+SigninReauthHandler::~SigninReauthHandler() = default;
+
+void SigninReauthHandler::RegisterMessages() {
+ web_ui()->RegisterMessageCallback(
+ "initialize", base::BindRepeating(&SigninReauthHandler::HandleInitialize,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "confirm", base::BindRepeating(&SigninReauthHandler::HandleConfirm,
+ base::Unretained(this)));
+ web_ui()->RegisterMessageCallback(
+ "cancel", base::BindRepeating(&SigninReauthHandler::HandleCancel,
+ base::Unretained(this)));
+}
+
+void SigninReauthHandler::OnJavascriptAllowed() {
+ if (!controller_)
+ return;
+
+ SigninReauthViewController::GaiaReauthType gaia_reauth_type =
+ controller_->gaia_reauth_type();
+ if (gaia_reauth_type !=
+ SigninReauthViewController::GaiaReauthType::kUnknown) {
+ OnGaiaReauthTypeDetermined(gaia_reauth_type);
+ }
+}
+
+void SigninReauthHandler::OnReauthControllerDestroyed() {
+ controller_observer_.RemoveAll();
+ controller_ = nullptr;
+}
+
+void SigninReauthHandler::OnGaiaReauthTypeDetermined(
+ SigninReauthViewController::GaiaReauthType reauth_type) {
+ if (!IsJavascriptAllowed())
+ return;
+
+ DCHECK_NE(reauth_type, SigninReauthViewController::GaiaReauthType::kUnknown);
+ bool is_reauth_required =
+ reauth_type != SigninReauthViewController::GaiaReauthType::kAutoApproved;
+ FireWebUIListener("reauth-type-received", base::Value(is_reauth_required));
+}
+
+void SigninReauthHandler::HandleInitialize(const base::ListValue* args) {
+ AllowJavascript();
+}
+
+void SigninReauthHandler::HandleConfirm(const base::ListValue* args) {
+ if (controller_)
+ controller_->OnReauthConfirmed();
+}
+
+void SigninReauthHandler::HandleCancel(const base::ListValue* args) {
+ if (controller_)
+ controller_->OnReauthDismissed();
+}
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_reauth_handler.h b/chromium/chrome/browser/ui/webui/signin/signin_reauth_handler.h
new file mode 100644
index 00000000000..2ab5bd48f7d
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/signin/signin_reauth_handler.h
@@ -0,0 +1,57 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_SIGNIN_SIGNIN_REAUTH_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_SIGNIN_SIGNIN_REAUTH_HANDLER_H_
+
+#include "chrome/browser/ui/signin_reauth_view_controller.h"
+#include "content/public/browser/web_ui_message_handler.h"
+
+namespace base {
+class ListValue;
+}
+
+// WebUI message handler for the signin reauth dialog.
+class SigninReauthHandler : public content::WebUIMessageHandler,
+ public SigninReauthViewController::Observer {
+ public:
+ // Creates a SigninReauthHandler for the |controller|.
+ explicit SigninReauthHandler(SigninReauthViewController* controller);
+ ~SigninReauthHandler() override;
+
+ SigninReauthHandler(const SigninReauthHandler&) = delete;
+ SigninReauthHandler& operator=(const SigninReauthHandler&) = delete;
+
+ // content::WebUIMessageHandler:
+ void RegisterMessages() override;
+ void OnJavascriptAllowed() override;
+
+ // SigninReauthViewController::Observer:
+ void OnReauthControllerDestroyed() override;
+ void OnGaiaReauthTypeDetermined(
+ SigninReauthViewController::GaiaReauthType reauth_type) override;
+
+ protected:
+ // Handles "initialize" message from the page. No arguments.
+ virtual void HandleInitialize(const base::ListValue* args);
+
+ // Handles "confirm" message from the page. No arguments.
+ // This message is sent when the user confirms that they want complete the
+ // reauth flow.
+ virtual void HandleConfirm(const base::ListValue* args);
+
+ // Handles "cancel" message from the page. No arguments. This message is sent
+ // when the user cancels the reauth flow.
+ virtual void HandleCancel(const base::ListValue* args);
+
+ private:
+ // May be null if |controller_| gets destroyed earlier than |this|.
+ SigninReauthViewController* controller_;
+
+ ScopedObserver<SigninReauthViewController,
+ SigninReauthViewController::Observer>
+ controller_observer_{this};
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_SIGNIN_SIGNIN_REAUTH_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_reauth_ui.cc b/chromium/chrome/browser/ui/webui/signin/signin_reauth_ui.cc
new file mode 100644
index 00000000000..b2730305e4f
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/signin/signin_reauth_ui.cc
@@ -0,0 +1,138 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/signin/signin_reauth_ui.h"
+
+#include <string>
+
+#include "base/check.h"
+#include "base/optional.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/signin/reauth_util.h"
+#include "chrome/browser/ui/signin_reauth_view_controller.h"
+#include "chrome/browser/ui/webui/signin/signin_reauth_handler.h"
+#include "chrome/common/webui_url_constants.h"
+#include "chrome/grit/browser_resources.h"
+#include "chrome/grit/generated_resources.h"
+#include "components/signin/public/base/signin_metrics.h"
+#include "components/signin/public/identity_manager/account_info.h"
+#include "components/signin/public/identity_manager/consent_level.h"
+#include "components/signin/public/identity_manager/identity_manager.h"
+#include "content/public/browser/web_ui_data_source.h"
+#include "google_apis/gaia/core_account_id.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
+#include "ui/base/webui/web_ui_util.h"
+#include "ui/gfx/image/image.h"
+#include "ui/resources/grit/webui_resources.h"
+
+namespace {
+
+std::string GetAccountImageURL(Profile* profile) {
+ auto* identity_manager = IdentityManagerFactory::GetForProfile(profile);
+ // The current version of the reauth only supports the primary account.
+ // TODO(crbug.com/1083429): generalize for arbitrary accounts by passing an
+ // account id as a method parameter.
+ CoreAccountId account_id =
+ identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kNotRequired);
+ // Sync shouldn't be enabled. Otherwise, the primary account and the first
+ // cookie account may diverge.
+ DCHECK(!identity_manager->HasPrimaryAccount(signin::ConsentLevel::kSync));
+ base::Optional<AccountInfo> account_info =
+ identity_manager
+ ->FindExtendedAccountInfoForAccountWithRefreshTokenByAccountId(
+ account_id);
+
+ return account_info && !account_info->account_image.IsEmpty()
+ ? webui::GetBitmapDataUrl(account_info->account_image.AsBitmap())
+ : profiles::GetPlaceholderAvatarIconUrl();
+}
+
+int GetReauthTitleStringId(signin_metrics::ReauthAccessPoint access_point) {
+ switch (access_point) {
+ case signin_metrics::ReauthAccessPoint::kUnknown:
+ case signin_metrics::ReauthAccessPoint::kAutofillDropdown:
+ case signin_metrics::ReauthAccessPoint::kPasswordSettings:
+ return IDS_ACCOUNT_PASSWORDS_REAUTH_SHOW_TITLE;
+ case signin_metrics::ReauthAccessPoint::kGeneratePasswordDropdown:
+ case signin_metrics::ReauthAccessPoint::kGeneratePasswordContextMenu:
+ case signin_metrics::ReauthAccessPoint::kPasswordSaveBubble:
+ case signin_metrics::ReauthAccessPoint::kPasswordMoveBubble:
+ return IDS_ACCOUNT_PASSWORDS_REAUTH_SAVE_TITLE;
+ }
+}
+
+int GetReauthConfirmButtonLabelStringId(
+ signin_metrics::ReauthAccessPoint access_point) {
+ switch (access_point) {
+ case signin_metrics::ReauthAccessPoint::kUnknown:
+ case signin_metrics::ReauthAccessPoint::kAutofillDropdown:
+ case signin_metrics::ReauthAccessPoint::kPasswordSettings:
+ return IDS_ACCOUNT_PASSWORDS_REAUTH_SHOW_BUTTON_LABEL;
+ case signin_metrics::ReauthAccessPoint::kGeneratePasswordDropdown:
+ case signin_metrics::ReauthAccessPoint::kGeneratePasswordContextMenu:
+ case signin_metrics::ReauthAccessPoint::kPasswordSaveBubble:
+ case signin_metrics::ReauthAccessPoint::kPasswordMoveBubble:
+ return IDS_ACCOUNT_PASSWORDS_REAUTH_SAVE_BUTTON_LABEL;
+ }
+}
+
+} // namespace
+
+SigninReauthUI::SigninReauthUI(content::WebUI* web_ui)
+ : SigninWebDialogUI(web_ui) {
+ Profile* profile = Profile::FromWebUI(web_ui);
+ signin_metrics::ReauthAccessPoint access_point =
+ signin::GetReauthAccessPointForReauthConfirmationURL(
+ web_ui->GetWebContents()->GetVisibleURL());
+
+ content::WebUIDataSource* source =
+ content::WebUIDataSource::Create(chrome::kChromeUISigninReauthHost);
+ source->UseStringsJs();
+ source->EnableReplaceI18nInJS();
+ source->SetDefaultResource(IDR_SIGNIN_REAUTH_HTML);
+ source->AddResourcePath("signin_reauth_app.js", IDR_SIGNIN_REAUTH_APP_JS);
+ source->AddResourcePath("signin_reauth_browser_proxy.js",
+ IDR_SIGNIN_REAUTH_BROWSER_PROXY_JS);
+ source->AddResourcePath("signin_shared_css.js", IDR_SIGNIN_SHARED_CSS_JS);
+ source->AddString("accountImageUrl", GetAccountImageURL(profile));
+
+ // Resources for testing.
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
+ "script-src chrome://resources chrome://test 'self';");
+ source->AddResourcePath("test_loader.js", IDR_WEBUI_JS_TEST_LOADER);
+ source->AddResourcePath("test_loader.html", IDR_WEBUI_HTML_TEST_LOADER);
+
+ // Resources for the account passwords reauth.
+ source->AddResourcePath(
+ "images/signin_reauth_illustration.svg",
+ IDR_SIGNIN_REAUTH_IMAGES_ACCOUNT_PASSWORDS_REAUTH_ILLUSTRATION_SVG);
+ source->AddResourcePath(
+ "images/signin_reauth_illustration_dark.svg",
+ IDR_SIGNIN_REAUTH_IMAGES_ACCOUNT_PASSWORDS_REAUTH_ILLUSTRATION_DARK_SVG);
+ source->AddLocalizedString("signinReauthTitle",
+ GetReauthTitleStringId(access_point));
+ source->AddLocalizedString("signinReauthDesc",
+ IDS_ACCOUNT_PASSWORDS_REAUTH_DESC);
+ source->AddLocalizedString("signinReauthConfirmLabel",
+ GetReauthConfirmButtonLabelStringId(access_point));
+ source->AddLocalizedString("signinReauthNextLabel",
+ IDS_ACCOUNT_PASSWORDS_REAUTH_NEXT_BUTTON_LABEL);
+ source->AddLocalizedString("signinReauthCloseLabel",
+ IDS_ACCOUNT_PASSWORDS_REAUTH_CLOSE_BUTTON_LABEL);
+
+ content::WebUIDataSource::Add(profile, source);
+}
+
+SigninReauthUI::~SigninReauthUI() = default;
+
+void SigninReauthUI::InitializeMessageHandlerWithReauthController(
+ SigninReauthViewController* controller) {
+ web_ui()->AddMessageHandler(
+ std::make_unique<SigninReauthHandler>(controller));
+}
+
+void SigninReauthUI::InitializeMessageHandlerWithBrowser(Browser* browser) {}
diff --git a/chromium/chrome/browser/ui/webui/signin/signin_reauth_ui.h b/chromium/chrome/browser/ui/webui/signin/signin_reauth_ui.h
new file mode 100644
index 00000000000..e32947e0548
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/signin/signin_reauth_ui.h
@@ -0,0 +1,49 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_SIGNIN_SIGNIN_REAUTH_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_SIGNIN_SIGNIN_REAUTH_UI_H_
+
+#include "chrome/browser/ui/webui/signin/signin_web_dialog_ui.h"
+
+class Browser;
+class SigninReauthViewController;
+
+namespace content {
+class WebUI;
+}
+
+// WebUI controller for the signin reauth dialog.
+//
+// The reauth UI currently assumes that the unconsented primary account matches
+// the first account in cookies.
+// It's a safe assumption only under the following conditions:
+// - DICE is enabled
+// - Sync in not enabled
+//
+// Currently this dialog is only used for account password storage opt-in that
+// satisfies both of those conditions.
+//
+// Contact chrome-signin@chromium.org if you want to reuse this dialog for other
+// reauth use-cases.
+class SigninReauthUI : public SigninWebDialogUI {
+ public:
+ explicit SigninReauthUI(content::WebUI* web_ui);
+ ~SigninReauthUI() override;
+
+ SigninReauthUI(const SigninReauthUI&) = delete;
+ SigninReauthUI& operator=(const SigninReauthUI&) = delete;
+
+ // Creates a WebUI message handler with the specified |controller| and adds it
+ // to the web UI.
+ void InitializeMessageHandlerWithReauthController(
+ SigninReauthViewController* controller);
+
+ // SigninWebDialogUI:
+ // This class relies on InitializeMessageHandlerWithReauthController() so this
+ // method does nothing.
+ void InitializeMessageHandlerWithBrowser(Browser* browser) override;
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_SIGNIN_SIGNIN_REAUTH_UI_H_
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 eba97fb4b9f..1924e39ce29 100644
--- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc
+++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc
@@ -239,11 +239,4 @@ void SyncConfirmationHandler::HandleInitializedWithSize(
}
signin::SetInitializedModalHeight(browser_, web_ui(), args);
-
- // After the dialog is shown, some platforms might have an element focused.
- // To be consistent, clear the focused element on all platforms.
- // TODO(anthonyvd): Figure out why this is needed on Mac and not other
- // platforms and if there's a way to start unfocused while avoiding this
- // workaround.
- FireWebUIListener("clear-focus");
}
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 f10afde391d..ab71645c8ce 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
@@ -223,10 +223,8 @@ TEST_F(SyncConfirmationHandlerTest, TestSetImageIfPrimaryAccountReady) {
args.Set(0, std::make_unique<base::Value>(kDefaultDialogHeight));
handler()->HandleInitializedWithSize(&args);
+ ASSERT_EQ(1U, web_ui()->call_data().size());
ExpectAccountImageChanged(*web_ui()->call_data()[0]);
- EXPECT_EQ("cr.webUIListenerCallback",
- web_ui()->call_data()[1]->function_name());
- EXPECT_EQ("clear-focus", web_ui()->call_data()[1]->arg1()->GetString());
}
TEST_F(SyncConfirmationHandlerTest, TestSetImageIfPrimaryAccountReadyLater) {
@@ -234,19 +232,16 @@ TEST_F(SyncConfirmationHandlerTest, TestSetImageIfPrimaryAccountReadyLater) {
args.Set(0, std::make_unique<base::Value>(kDefaultDialogHeight));
handler()->HandleInitializedWithSize(&args);
- EXPECT_EQ(2U, web_ui()->call_data().size());
+ ASSERT_EQ(1U, web_ui()->call_data().size());
ExpectAccountImageChanged(*web_ui()->call_data()[0]);
- EXPECT_EQ("cr.webUIListenerCallback",
- web_ui()->call_data()[1]->function_name());
- EXPECT_EQ("clear-focus", web_ui()->call_data()[1]->arg1()->GetString());
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());
- ExpectAccountImageChanged(*web_ui()->call_data()[2]);
+ ASSERT_EQ(2U, web_ui()->call_data().size());
+ ExpectAccountImageChanged(*web_ui()->call_data()[1]);
}
TEST_F(SyncConfirmationHandlerTest,
@@ -254,7 +249,7 @@ TEST_F(SyncConfirmationHandlerTest,
base::ListValue args;
args.Set(0, std::make_unique<base::Value>(kDefaultDialogHeight));
handler()->HandleInitializedWithSize(&args);
- EXPECT_EQ(2U, web_ui()->call_data().size());
+ EXPECT_EQ(1U, web_ui()->call_data().size());
AccountInfo account_info =
identity_test_env()->MakeAccountAvailable("bar@example.com");
@@ -265,7 +260,7 @@ TEST_F(SyncConfirmationHandlerTest,
// 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());
+ EXPECT_EQ(1U, web_ui()->call_data().size());
identity_test_env()->SimulateSuccessfulFetchOfAccountInfo(
account_info_.account_id, account_info_.email, account_info_.gaia, "",
@@ -274,8 +269,8 @@ TEST_F(SyncConfirmationHandlerTest,
// 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());
- ExpectAccountImageChanged(*web_ui()->call_data()[2]);
+ ASSERT_EQ(2U, web_ui()->call_data().size());
+ ExpectAccountImageChanged(*web_ui()->call_data()[1]);
}
TEST_F(SyncConfirmationHandlerTest, TestHandleUndo) {
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 3ba5023e3c6..cdbfd068fbf 100644
--- a/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc
+++ b/chromium/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc
@@ -21,6 +21,7 @@
#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/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/resources/grit/webui_resources.h"
@@ -44,7 +45,8 @@ SyncConfirmationUI::SyncConfirmationUI(content::WebUI* web_ui)
if (is_sync_allowed) {
source->AddResourcePath("test_loader.js", IDR_WEBUI_JS_TEST_LOADER);
source->AddResourcePath("test_loader.html", IDR_WEBUI_HTML_TEST_LOADER);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources chrome://test 'self';");
source->SetDefaultResource(IDR_SYNC_CONFIRMATION_HTML);
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 2dea17c899c..295468faa44 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
@@ -18,7 +18,7 @@
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
-#include "base/value_conversions.h"
+#include "base/util/values/values_util.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
@@ -314,13 +314,15 @@ void UserManagerScreenHandler::HandleAuthenticatedLaunchUser(
if (!args->Get(0, &profile_path_value))
return;
- base::FilePath profile_path;
- if (!base::GetValueAsFilePath(*profile_path_value, &profile_path))
+ base::Optional<base::FilePath> profile_path =
+ util::ValueToFilePath(*profile_path_value);
+ if (!profile_path)
return;
ProfileAttributesEntry* entry;
- if (!g_browser_process->profile_manager()->GetProfileAttributesStorage().
- GetProfileAttributesWithPath(profile_path, &entry)) {
+ if (!g_browser_process->profile_manager()
+ ->GetProfileAttributesStorage()
+ .GetProfileAttributesWithPath(*profile_path, &entry)) {
return;
}
@@ -332,7 +334,7 @@ void UserManagerScreenHandler::HandleAuthenticatedLaunchUser(
if (!args->GetString(2, &password))
return;
- authenticating_profile_path_ = profile_path;
+ authenticating_profile_path_ = *profile_path;
email_address_ = base::UTF16ToUTF8(email_address);
// Only try to validate locally or check the password change detection
@@ -365,13 +367,13 @@ void UserManagerScreenHandler::HandleAuthenticatedLaunchUser(
content::BrowserContext* browser_context =
web_ui()->GetWebContents()->GetBrowserContext();
- if (!email_address_.empty()) {
+ if (!email_address_.empty() && entry->IsAuthenticated()) {
// In order to support the upgrade case where we have a local hash but no
// password token, the user must perform a full online reauth.
RecordAuthenticatedLaunchUserEvent(
AuthenticatedLaunchUserEvent::GAIA_REAUTH_DIALOG);
UserManagerProfileDialog::ShowUnlockDialogWithProfilePath(
- browser_context, email_address_, profile_path);
+ browser_context, email_address_, *profile_path);
} else if (entry->IsSigninRequired() && entry->IsSupervised()) {
// Supervised profile will only be locked when force-sign-in is enabled
// and it shouldn't be unlocked. Display the error message directly via
@@ -401,7 +403,7 @@ void UserManagerScreenHandler::HandleAuthenticatedLaunchUser(
RecordAuthenticatedLaunchUserEvent(
AuthenticatedLaunchUserEvent::FORCED_PRIMARY_SIGNIN_DIALOG);
UserManagerProfileDialog::ShowForceSigninDialog(browser_context,
- profile_path);
+ *profile_path);
}
}
@@ -413,8 +415,9 @@ void UserManagerScreenHandler::HandleRemoveUser(const base::ListValue* args) {
return;
}
- base::FilePath profile_path;
- if (!base::GetValueAsFilePath(*profile_path_value, &profile_path)) {
+ base::Optional<base::FilePath> profile_path =
+ util::ValueToFilePath(*profile_path_value);
+ if (!profile_path) {
NOTREACHED();
return;
}
@@ -432,7 +435,7 @@ void UserManagerScreenHandler::HandleRemoveUser(const base::ListValue* args) {
// The callback is run if the only profile has been deleted, and a new
// profile has been created to replace it.
- webui::DeleteProfileAtPath(profile_path,
+ webui::DeleteProfileAtPath(*profile_path,
ProfileMetrics::DELETE_PROFILE_USER_MANAGER);
}
@@ -466,13 +469,15 @@ void UserManagerScreenHandler::HandleLaunchUser(const base::ListValue* args) {
if (!args->Get(0, &profile_path_value))
return;
- base::FilePath profile_path;
- if (!base::GetValueAsFilePath(*profile_path_value, &profile_path))
+ base::Optional<base::FilePath> profile_path =
+ util::ValueToFilePath(*profile_path_value);
+ if (!profile_path)
return;
ProfileAttributesEntry* entry;
- if (!g_browser_process->profile_manager()->GetProfileAttributesStorage().
- GetProfileAttributesWithPath(profile_path, &entry)) {
+ if (!g_browser_process->profile_manager()
+ ->GetProfileAttributesStorage()
+ .GetProfileAttributesWithPath(*profile_path, &entry)) {
NOTREACHED();
return;
}
@@ -486,7 +491,7 @@ void UserManagerScreenHandler::HandleLaunchUser(const base::ListValue* args) {
return;
profiles::SwitchToProfile(
- profile_path, false, /* reuse any existing windows */
+ *profile_path, false, /* reuse any existing windows */
base::Bind(&UserManagerScreenHandler::OnSwitchToProfileComplete,
weak_ptr_factory_.GetWeakPtr()));
}
@@ -499,20 +504,20 @@ void UserManagerScreenHandler::HandleRemoveUserWarningLoadStats(
return;
base::Time start_time = base::Time::Now();
- base::FilePath profile_path;
-
- if (!base::GetValueAsFilePath(*profile_path_value, &profile_path))
+ base::Optional<base::FilePath> profile_path =
+ util::ValueToFilePath(*profile_path_value);
+ if (!profile_path)
return;
- base::Value return_profile_path(profile_path.value());
- Profile* profile = g_browser_process->profile_manager()->
- GetProfileByPath(profile_path);
+ base::Value return_profile_path(profile_path->value());
+ Profile* profile =
+ g_browser_process->profile_manager()->GetProfileByPath(*profile_path);
if (profile) {
GatherStatistics(start_time, profile);
} else {
g_browser_process->profile_manager()->LoadProfileByPath(
- profile_path, false,
+ *profile_path, false,
base::BindOnce(&UserManagerScreenHandler::GatherStatistics,
weak_ptr_factory_.GetWeakPtr(), start_time));
}
@@ -796,8 +801,7 @@ void UserManagerScreenHandler::SendUserList() {
profile_value->SetString(kKeyEmailAddress, entry->GetUserName());
profile_value->SetString(kKeyDisplayName,
profiles::GetAvatarNameForProfile(profile_path));
- profile_value->SetKey(kKeyProfilePath,
- base::CreateFilePathValue(profile_path));
+ profile_value->SetKey(kKeyProfilePath, util::FilePathToValue(profile_path));
profile_value->SetBoolean(kKeyPublicAccount, false);
profile_value->SetBoolean(kKeyLegacySupervisedUser,
entry->IsLegacySupervised());
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 47070460d08..56594542eac 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
@@ -148,6 +148,8 @@ IN_PROC_BROWSER_TEST_F(UserManagerUIAuthenticatedUserBrowserTest, Reauth) {
Init();
signin_util::SetForceSigninForTesting(true);
entry_->SetLocalAuthCredentials("1mock_credentials");
+ // Consent profile's primary account.
+ entry_->SetAuthInfo("gaia_id", base::string16(), true);
LaunchAuthenticatedUser("email@mock.com");
@@ -162,6 +164,29 @@ IN_PROC_BROWSER_TEST_F(UserManagerUIAuthenticatedUserBrowserTest, Reauth) {
}
IN_PROC_BROWSER_TEST_F(UserManagerUIAuthenticatedUserBrowserTest,
+ SigninButUnconsentedUserBlocked) {
+ Init();
+ signin_util::SetForceSigninForTesting(true);
+
+ // Unconsent profile's primary account is used locked due to force sign in.
+ entry_->SetIsSigninRequired(true);
+ entry_->SetActiveTimeToNow();
+ entry_->SetAuthInfo("gaia_id", base::string16(), false);
+
+ MockLoginUIService* service = static_cast<MockLoginUIService*>(
+ LoginUIServiceFactory::GetInstance()->SetTestingFactoryAndUse(
+ profile_, base::BindRepeating(&CreateLoginUIService)));
+ EXPECT_CALL(*service, SetProfileBlockingErrorMessage());
+
+ LaunchAuthenticatedUser("email@mock.com");
+
+ histogram_tester_.ExpectUniqueSample(
+ kAuthenticatedLaunchUserEventMetricsName,
+ AuthenticatedLaunchUserEvent::USED_PROFILE_BLOCKED_WARNING, 1);
+ signin_util::ResetForceSigninForTesting();
+}
+
+IN_PROC_BROWSER_TEST_F(UserManagerUIAuthenticatedUserBrowserTest,
SupervisedUserBlocked) {
Init();
entry_->SetIsSigninRequired(true);
diff --git a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc
index 011dc70c605..84739294f39 100644
--- a/chromium/chrome/browser/ui/webui/signin_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/signin_internals_ui.cc
@@ -18,13 +18,15 @@
#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/network/public/mojom/content_security_policy.mojom.h"
namespace {
content::WebUIDataSource* CreateSignInInternalsHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUISignInInternalsHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
source->UseStringsJs();
diff --git a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc
index 24cecc6a0dd..498f2d0958a 100644
--- a/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/snippets_internals/snippets_internals_ui.cc
@@ -16,6 +16,7 @@
#include "chrome/grit/dev_ui_browser_resources.h"
#include "content/public/browser/web_ui_data_source.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#if defined(OS_ANDROID)
#include "chrome/browser/flags/android/chrome_feature_list.h"
@@ -25,7 +26,8 @@ SnippetsInternalsUI::SnippetsInternalsUI(content::WebUI* web_ui)
: ui::MojoWebUIController(web_ui) {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUISnippetsInternalsHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
source->AddResourcePath("snippets_internals.css", IDR_SNIPPETS_INTERNALS_CSS);
source->AddResourcePath("snippets_internals.js", IDR_SNIPPETS_INTERNALS_JS);
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 0811f8b6987..8b2dad324c4 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
@@ -28,6 +28,7 @@
#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_contents.h"
#include "content/public/browser/web_ui.h"
using content::BrowserThread;
@@ -181,12 +182,23 @@ void SupervisedUserInternalsMessageHandler::HandleTryURL(
return;
SupervisedUserURLFilter* filter = GetSupervisedUserService()->GetURLFilter();
- std::map<std::string, base::string16> whitelists =
+
+ content::WebContents* web_contents =
+ web_ui() ? web_ui()->GetWebContents() : nullptr;
+ bool skip_manual_parent_filter = false;
+ if (web_contents) {
+ skip_manual_parent_filter =
+ filter->ShouldSkipParentManualAllowlistFiltering(
+ web_contents->GetOutermostWebContents());
+ }
+
+ std::map<std::string, base::string16> allowlists =
filter->GetMatchingWhitelistTitles(url);
filter->GetFilteringBehaviorForURLWithAsyncChecks(
url,
base::BindOnce(&SupervisedUserInternalsMessageHandler::OnTryURLResult,
- weak_factory_.GetWeakPtr(), whitelists));
+ weak_factory_.GetWeakPtr(), allowlists),
+ skip_manual_parent_filter);
}
void SupervisedUserInternalsMessageHandler::SendBasicInfo() {
diff --git a/chromium/chrome/browser/ui/webui/supervised_user_internals_ui.cc b/chromium/chrome/browser/ui/webui/supervised_user_internals_ui.cc
index 33484a1287b..193582046bb 100644
--- a/chromium/chrome/browser/ui/webui/supervised_user_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/supervised_user_internals_ui.cc
@@ -12,13 +12,15 @@
#include "chrome/grit/dev_ui_browser_resources.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
namespace {
content::WebUIDataSource* CreateSupervisedUserInternalsHTMLSource() {
content::WebUIDataSource* source = content::WebUIDataSource::Create(
chrome::kChromeUISupervisedUserInternalsHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
source->AddResourcePath("supervised_user_internals.js",
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 050b6031de3..38eddc39498 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
@@ -8,6 +8,7 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
+#include "base/logging.h"
#include "base/values.h"
#include "chrome/browser/apps/platform_apps/api/sync_file_system/sync_file_system_api_helpers.h"
#include "chrome/browser/profiles/profile.h"
diff --git a/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js b/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js
index a2abe32d002..2be5fd412b0 100644
--- a/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js
+++ b/chromium/chrome/browser/ui/webui/sync_internals_browsertest.js
@@ -243,7 +243,13 @@ GEN('#if defined(OS_CHROMEOS)');
// Sync should be disabled if there was no primary account set.
TEST_F('SyncInternalsWebUITest', 'SyncDisabledByDefaultChromeOS', function() {
expectTrue(this.hasInDetails(true, 'Transport State', 'Disabled'));
- expectTrue(this.hasInDetails(true, 'Disable Reasons', 'Not signed in'));
+ // We don't check 'Disable Reasons' here because the string depends on the
+ // flag SplitSettingsSync. There's not a good way to check a C++ flag value
+ // in the middle of a JS test, nor is there a simple way to enable or disable
+ // platform-specific flags in a cross-platform JS test suite.
+ // TODO(crbug.com/1087165): When SplitSettingsSync is the default, delete this
+ // test and use SyncInternalsWebUITest.SyncDisabledByDefault on all
+ // platforms.
expectTrue(this.hasInDetails(true, 'Username', ''));
});
diff --git a/chromium/chrome/browser/ui/webui/sync_internals_ui.cc b/chromium/chrome/browser/ui/webui/sync_internals_ui.cc
index 89dd520d430..ac5b655e00f 100644
--- a/chromium/chrome/browser/ui/webui/sync_internals_ui.cc
+++ b/chromium/chrome/browser/ui/webui/sync_internals_ui.cc
@@ -14,13 +14,15 @@
#include "components/sync/driver/about_sync_util.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
namespace {
content::WebUIDataSource* CreateSyncInternalsHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUISyncInternalsHost);
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self' 'unsafe-eval';");
source->UseStringsJs();
@@ -65,4 +67,3 @@ SyncInternalsUI::SyncInternalsUI(content::WebUI* web_ui)
}
SyncInternalsUI::~SyncInternalsUI() {}
-
diff --git a/chromium/chrome/browser/chromeos/net/mojom/BUILD.gn b/chromium/chrome/browser/ui/webui/tab_search/BUILD.gn
index 713ef8afafa..092303f6942 100644
--- a/chromium/chrome/browser/chromeos/net/mojom/BUILD.gn
+++ b/chromium/chrome/browser/ui/webui/tab_search/BUILD.gn
@@ -4,9 +4,6 @@
import("//mojo/public/tools/bindings/mojom.gni")
-mojom("mojom") {
- sources = [ "network_health.mojom" ]
-
- public_deps =
- [ "//chromeos/services/network_config/public/mojom:network_types" ]
+mojom("mojo_bindings") {
+ sources = [ "tab_search.mojom" ]
}
diff --git a/chromium/chrome/browser/ui/webui/tab_search/OWNERS b/chromium/chrome/browser/ui/webui/tab_search/OWNERS
new file mode 100644
index 00000000000..6716085b93d
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/tab_search/OWNERS
@@ -0,0 +1,7 @@
+robliao@chromium.org
+tluk@chromium.org
+
+per-file *.mojom=set noparent
+per-file *.mojom=file://ipc/SECURITY_OWNERS
+
+# COMPONENT: UI>Browser>TabSearch
diff --git a/chromium/chrome/browser/ui/webui/tab_search/tab_search.mojom b/chromium/chrome/browser/ui/webui/tab_search/tab_search.mojom
new file mode 100644
index 00000000000..26a6d8c5165
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/tab_search/tab_search.mojom
@@ -0,0 +1,70 @@
+// Copyright 2020 The Chromium 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 tab_search.mojom;
+
+// Collection of WindowTabs of a profile.
+struct ProfileTabs {
+ array<WindowTabs> windows;
+};
+
+// Collection of Tab of a window.
+struct WindowTabs {
+ bool active;
+ array<Tab> tabs;
+};
+
+// Information about an existing open tab.
+struct Tab {
+ bool active;
+ int32 index;
+ int32 tab_id;
+ string? group_id;
+ bool pinned;
+ string title;
+ string url;
+ string? fav_icon_url;
+ bool is_default_favicon;
+ bool show_icon;
+};
+
+// Collection of tab groups.
+struct TabGroups {
+ map<string, TabGroup> groups;
+};
+
+// Information about a tab group.
+struct TabGroup {
+ string color;
+ string text_color;
+ string title;
+};
+
+// Information about switching to a tab.
+struct SwitchToTabInfo {
+ int32 tab_id;
+};
+
+// Used by the WebUI page to bootstrap bidirectional communication.
+interface PageHandlerFactory {
+ // The WebUI calls this method when the page is first initialized.
+ CreatePageHandler(pending_remote<Page> page,
+ pending_receiver<PageHandler> handler);
+};
+
+// Browser-side handler for requests from WebUI page.
+interface PageHandler {
+ // Get tabs grouped by windows for the current profile
+ GetProfileTabs() => (ProfileTabs profile_tabs);
+
+ // Get tab groups for the current profile.
+ GetTabGroups() => (TabGroups tab_groups);
+
+ // Switch to a specific tab.
+ SwitchToTab(SwitchToTabInfo switch_to_tab_info);
+};
+
+// WebUI-side handler for requests from the browser.
+interface Page {
+};
diff --git a/chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler.cc b/chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler.cc
new file mode 100644
index 00000000000..23e90c900b6
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler.cc
@@ -0,0 +1,115 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/tab_search/tab_search_page_handler.h"
+
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "base/base64.h"
+#include "chrome/browser/extensions/extension_tab_util.h"
+#include "chrome/browser/favicon/favicon_utils.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/browser_finder.h"
+#include "chrome/browser/ui/browser_list.h"
+#include "chrome/browser/ui/browser_window.h"
+#include "chrome/browser/ui/tabs/tab_renderer_data.h"
+#include "chrome/browser/ui/webui/util/image_util.h"
+
+TabSearchPageHandler::TabSearchPageHandler(
+ mojo::PendingReceiver<tab_search::mojom::PageHandler> receiver,
+ mojo::PendingRemote<tab_search::mojom::Page> page,
+ content::WebUI* web_ui)
+ : receiver_(this, std::move(receiver)),
+ page_(std::move(page)),
+ browser_(chrome::FindLastActive()),
+ web_ui_(web_ui) {
+ DCHECK(browser_);
+}
+
+TabSearchPageHandler::~TabSearchPageHandler() = default;
+
+void TabSearchPageHandler::GetProfileTabs(GetProfileTabsCallback callback) {
+ auto profile_tabs = tab_search::mojom::ProfileTabs::New();
+ Profile* profile = browser_->profile();
+ for (auto* browser : *BrowserList::GetInstance()) {
+ if (browser->profile() != profile) {
+ continue;
+ }
+ TabStripModel* tab_strip_model = browser->tab_strip_model();
+ auto window_tabs = tab_search::mojom::WindowTabs::New();
+ window_tabs->active = (browser == browser_);
+ for (int i = 0; i < tab_strip_model->count(); ++i) {
+ window_tabs->tabs.push_back(
+ GetTabData(browser, tab_strip_model->GetWebContentsAt(i), i));
+ }
+ profile_tabs->windows.push_back(std::move(window_tabs));
+ }
+
+ std::move(callback).Run(std::move(profile_tabs));
+}
+
+void TabSearchPageHandler::GetTabGroups(GetTabGroupsCallback callback) {
+ // TODO(crbug.com/1096120): Implement this when we can get theme color from
+ // browser
+ NOTIMPLEMENTED();
+}
+
+void TabSearchPageHandler::SwitchToTab(
+ tab_search::mojom::SwitchToTabInfoPtr switch_to_tab_info) {
+ Profile* profile = browser_->profile();
+ for (auto* browser : *BrowserList::GetInstance()) {
+ if (browser->profile() != profile) {
+ continue;
+ }
+ TabStripModel* tab_strip_model = browser->tab_strip_model();
+ for (int index = 0; index < tab_strip_model->count(); ++index) {
+ content::WebContents* contents = tab_strip_model->GetWebContentsAt(index);
+ if (extensions::ExtensionTabUtil::GetTabId(contents) ==
+ switch_to_tab_info->tab_id) {
+ tab_strip_model->ActivateTabAt(index);
+ browser->window()->Activate();
+ return;
+ }
+ }
+ }
+}
+
+tab_search::mojom::TabPtr TabSearchPageHandler::GetTabData(
+ Browser* browser,
+ content::WebContents* contents,
+ int index) {
+ auto tab_data = tab_search::mojom::Tab::New();
+
+ tab_data->active = browser->tab_strip_model()->active_index() == index;
+ tab_data->tab_id = extensions::ExtensionTabUtil::GetTabId(contents);
+ tab_data->index = index;
+
+ const base::Optional<tab_groups::TabGroupId> group_id =
+ browser->tab_strip_model()->GetTabGroupForTab(index);
+ if (group_id.has_value()) {
+ tab_data->group_id = group_id.value().ToString();
+ }
+
+ TabRendererData tab_renderer_data =
+ TabRendererData::FromTabInModel(browser->tab_strip_model(), index);
+ tab_data->pinned = tab_renderer_data.pinned;
+ tab_data->title = base::UTF16ToUTF8(tab_renderer_data.title);
+ tab_data->url = tab_renderer_data.visible_url.GetContent();
+
+ if (tab_renderer_data.favicon.isNull()) {
+ tab_data->is_default_favicon = true;
+ } else {
+ tab_data->fav_icon_url = webui::EncodePNGAndMakeDataURI(
+ tab_renderer_data.favicon, web_ui_->GetDeviceScaleFactor());
+ tab_data->is_default_favicon =
+ tab_renderer_data.favicon.BackedBySameObjectAs(
+ favicon::GetDefaultFavicon().AsImageSkia());
+ }
+ tab_data->show_icon = tab_renderer_data.show_icon;
+
+ return tab_data;
+}
diff --git a/chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler.h b/chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler.h
new file mode 100644
index 00000000000..6c8ff9cb68f
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler.h
@@ -0,0 +1,47 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_TAB_SEARCH_TAB_SEARCH_PAGE_HANDLER_H_
+#define CHROME_BROWSER_UI_WEBUI_TAB_SEARCH_TAB_SEARCH_PAGE_HANDLER_H_
+
+#include "chrome/browser/ui/tabs/tab_group.h"
+#include "chrome/browser/ui/tabs/tab_group_model.h"
+#include "chrome/browser/ui/tabs/tab_group_theme.h"
+#include "chrome/browser/ui/webui/tab_search/tab_search.mojom.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
+#include "mojo/public/cpp/bindings/remote.h"
+#include "ui/webui/mojo_web_ui_controller.h"
+
+class Browser;
+
+class TabSearchPageHandler : public tab_search::mojom::PageHandler {
+ public:
+ TabSearchPageHandler(
+ mojo::PendingReceiver<tab_search::mojom::PageHandler> receiver,
+ mojo::PendingRemote<tab_search::mojom::Page> page,
+ content::WebUI* web_ui);
+ TabSearchPageHandler(const TabSearchPageHandler&) = delete;
+ TabSearchPageHandler& operator=(const TabSearchPageHandler&) = delete;
+ ~TabSearchPageHandler() override;
+
+ // tab_search::mojom::PageHandler:
+ void GetProfileTabs(GetProfileTabsCallback callback) override;
+ void GetTabGroups(GetTabGroupsCallback callback) override;
+ void SwitchToTab(
+ tab_search::mojom::SwitchToTabInfoPtr switch_to_tab_info) override;
+
+ private:
+ tab_search::mojom::TabPtr GetTabData(Browser* browser,
+ content::WebContents* contents,
+ int index);
+
+ mojo::Receiver<tab_search::mojom::PageHandler> receiver_;
+ mojo::Remote<tab_search::mojom::Page> page_;
+ Browser* const browser_;
+ content::WebUI* const web_ui_;
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_TAB_SEARCH_TAB_SEARCH_PAGE_HANDLER_H_
diff --git a/chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler_unittest.cc b/chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler_unittest.cc
new file mode 100644
index 00000000000..7d884291ffd
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/tab_search/tab_search_page_handler_unittest.cc
@@ -0,0 +1,203 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/tab_search/tab_search_page_handler.h"
+
+#include "base/test/bind_test_util.h"
+#include "chrome/browser/ui/browser_commands.h"
+#include "chrome/browser/ui/browser_list.h"
+#include "chrome/test/base/browser_with_test_window_test.h"
+#include "chrome/test/base/test_browser_window.h"
+#include "content/public/test/test_web_ui.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "ui/gfx/color_utils.h"
+
+namespace {
+
+constexpr char kTabUrl1[] = "http://foo/1";
+constexpr char kTabUrl2[] = "http://foo/2";
+constexpr char kTabUrl3[] = "http://foo/3";
+constexpr char kTabUrl4[] = "http://foo/4";
+
+constexpr char kTabUrlName1[] = "foo/1";
+constexpr char kTabUrlName2[] = "foo/2";
+constexpr char kTabUrlName3[] = "foo/3";
+
+constexpr char kTabName1[] = "Tab 1";
+constexpr char kTabName2[] = "Tab 2";
+constexpr char kTabName3[] = "Tab 3";
+constexpr char kTabName4[] = "Tab 4";
+
+class MockPage : public tab_search::mojom::Page {
+ public:
+ MockPage() = default;
+ ~MockPage() override = default;
+
+ mojo::PendingRemote<tab_search::mojom::Page> BindAndGetRemote() {
+ DCHECK(!receiver_.is_bound());
+ return receiver_.BindNewPipeAndPassRemote();
+ }
+ mojo::Receiver<tab_search::mojom::Page> receiver_{this};
+};
+
+void ExpectNewTab(const tab_search::mojom::Tab* tab,
+ const std::string url,
+ const std::string title,
+ int index) {
+ EXPECT_EQ(index, tab->index);
+ EXPECT_LT(0, tab->tab_id);
+ EXPECT_FALSE(tab->group_id.has_value());
+ EXPECT_FALSE(tab->pinned);
+ EXPECT_EQ(title, tab->title);
+ EXPECT_EQ(url, tab->url);
+ EXPECT_TRUE(tab->fav_icon_url.has_value());
+ EXPECT_TRUE(tab->is_default_favicon);
+ EXPECT_TRUE(tab->show_icon);
+}
+
+void ExpectProfileTabs(tab_search::mojom::ProfileTabs* profile_tabs) {
+ ASSERT_EQ(2u, profile_tabs->windows.size());
+ auto* window1 = profile_tabs->windows[0].get();
+ ASSERT_EQ(2u, window1->tabs.size());
+ ASSERT_FALSE(window1->tabs[0]->active);
+ ASSERT_TRUE(window1->tabs[1]->active);
+ auto* window2 = profile_tabs->windows[1].get();
+ ASSERT_EQ(1u, window2->tabs.size());
+ ASSERT_TRUE(window2->tabs[0]->active);
+}
+
+class TestTabSearchPageHandler : public TabSearchPageHandler {
+ public:
+ TestTabSearchPageHandler(mojo::PendingRemote<tab_search::mojom::Page> page,
+ content::WebUI* web_ui)
+ : TabSearchPageHandler(
+ mojo::PendingReceiver<tab_search::mojom::PageHandler>(),
+ std::move(page),
+ web_ui) {}
+};
+
+class TabSearchPageHandlerTest : public BrowserWithTestWindowTest {
+ public:
+ void SetUp() override {
+ BrowserWithTestWindowTest::SetUp();
+ browser2_ = CreateTestBrowser(false, false);
+ browser3_ = CreateTestBrowser(true, false);
+ BrowserList::SetLastActive(browser1());
+ handler_ = std::make_unique<TestTabSearchPageHandler>(
+ page_.BindAndGetRemote(), web_ui());
+ }
+
+ void TearDown() override {
+ browser1()->tab_strip_model()->CloseAllTabs();
+ browser2()->tab_strip_model()->CloseAllTabs();
+ browser3()->tab_strip_model()->CloseAllTabs();
+ browser2_.reset();
+ browser3_.reset();
+ BrowserWithTestWindowTest::TearDown();
+ }
+
+ content::TestWebUI* web_ui() { return &web_ui_; }
+ Browser* browser1() { return browser(); }
+ Browser* browser2() { return browser2_.get(); }
+ Browser* browser3() { return browser3_.get(); }
+ TestTabSearchPageHandler* handler() { return handler_.get(); }
+
+ protected:
+ void AddTabWithTitle(Browser* browser,
+ const GURL url,
+ const std::string title) {
+ AddTab(browser, url);
+ NavigateAndCommitActiveTabWithTitle(browser, url,
+ base::ASCIIToUTF16(title));
+ }
+
+ private:
+ std::unique_ptr<Browser> CreateTestBrowser(bool incognito, bool popup) {
+ auto window = std::make_unique<TestBrowserWindow>();
+ Profile* profile = incognito ? browser()->profile()->GetPrimaryOTRProfile()
+ : browser()->profile();
+ Browser::Type type = popup ? Browser::TYPE_POPUP : Browser::TYPE_NORMAL;
+
+ std::unique_ptr<Browser> browser =
+ CreateBrowser(profile, type, false, window.get());
+ BrowserList::SetLastActive(browser.get());
+ new TestBrowserWindowOwner(window.release());
+ return browser;
+ }
+
+ testing::StrictMock<MockPage> page_;
+ content::TestWebUI web_ui_;
+ std::unique_ptr<Browser> browser2_;
+ std::unique_ptr<Browser> browser3_;
+ std::unique_ptr<TestTabSearchPageHandler> handler_;
+};
+
+TEST_F(TabSearchPageHandlerTest, GetTabs) {
+ // Browser3 is in incognito mode, thus its tab should not be accessible.
+ AddTabWithTitle(browser3(), GURL(kTabUrl4), kTabName4);
+ AddTabWithTitle(browser2(), GURL(kTabUrl3), kTabName3);
+ AddTabWithTitle(browser1(), GURL(kTabUrl2), kTabName2);
+ AddTabWithTitle(browser1(), GURL(kTabUrl1), kTabName1);
+
+ int32_t tab_id2 = 0;
+ int32_t tab_id3 = 0;
+
+ // Get Tabs.
+ tab_search::mojom::PageHandler::GetProfileTabsCallback callback1 =
+ base::BindLambdaForTesting(
+ [&](tab_search::mojom::ProfileTabsPtr profile_tabs) {
+ ASSERT_EQ(2u, profile_tabs->windows.size());
+ auto* window1 = profile_tabs->windows[0].get();
+ ASSERT_TRUE(window1->active);
+ ASSERT_EQ(2u, window1->tabs.size());
+
+ auto* tab1 = window1->tabs[0].get();
+ ExpectNewTab(tab1, kTabUrlName1, kTabName1, 0);
+ ASSERT_TRUE(tab1->active);
+
+ auto* tab2 = window1->tabs[1].get();
+ ExpectNewTab(tab2, kTabUrlName2, kTabName2, 1);
+ ASSERT_FALSE(tab2->active);
+
+ auto* window2 = profile_tabs->windows[1].get();
+ ASSERT_FALSE(window2->active);
+ ASSERT_EQ(1u, window2->tabs.size());
+
+ auto* tab3 = window2->tabs[0].get();
+ ExpectNewTab(tab3, kTabUrlName3, kTabName3, 0);
+ ASSERT_TRUE(tab3->active);
+
+ tab_id2 = tab2->tab_id;
+ tab_id3 = tab3->tab_id;
+ });
+ handler()->GetProfileTabs(std::move(callback1));
+
+ // Switch to 2nd tab.
+ auto switch_to_tab_info = tab_search::mojom::SwitchToTabInfo::New();
+ switch_to_tab_info->tab_id = tab_id2;
+ handler()->SwitchToTab(std::move(switch_to_tab_info));
+
+ // Get Tabs again to verify tab switch.
+ tab_search::mojom::PageHandler::GetProfileTabsCallback callback2 =
+ base::BindLambdaForTesting(
+ [&](tab_search::mojom::ProfileTabsPtr profile_tabs) {
+ ExpectProfileTabs(profile_tabs.get());
+ });
+ handler()->GetProfileTabs(std::move(callback2));
+
+ // Switch to 3rd tab.
+ switch_to_tab_info = tab_search::mojom::SwitchToTabInfo::New();
+ switch_to_tab_info->tab_id = tab_id3;
+ handler()->SwitchToTab(std::move(switch_to_tab_info));
+
+ // Get Tabs again to verify tab switch.
+ tab_search::mojom::PageHandler::GetProfileTabsCallback callback3 =
+ base::BindLambdaForTesting(
+ [&](tab_search::mojom::ProfileTabsPtr profile_tabs) {
+ ExpectProfileTabs(profile_tabs.get());
+ });
+ handler()->GetProfileTabs(std::move(callback3));
+}
+
+} // namespace
diff --git a/chromium/chrome/browser/ui/webui/tab_search/tab_search_ui.cc b/chromium/chrome/browser/ui/webui/tab_search/tab_search_ui.cc
new file mode 100644
index 00000000000..812960da8ec
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/tab_search/tab_search_ui.cc
@@ -0,0 +1,38 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/ui/webui/tab_search/tab_search_ui.h"
+
+#include "chrome/browser/ui/webui/tab_search/tab_search_page_handler.h"
+#include "chrome/browser/ui/webui/webui_util.h"
+#include "chrome/common/webui_url_constants.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_ui.h"
+#include "content/public/browser/web_ui_data_source.h"
+
+TabSearchUI::TabSearchUI(content::WebUI* web_ui)
+ : ui::MojoWebUIController(web_ui) {
+ content::WebUIDataSource* source =
+ content::WebUIDataSource::Create(chrome::kChromeUITabSearchHost);
+ content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(),
+ source);
+}
+
+TabSearchUI::~TabSearchUI() = default;
+
+WEB_UI_CONTROLLER_TYPE_IMPL(TabSearchUI)
+
+void TabSearchUI::BindInterface(
+ mojo::PendingReceiver<tab_search::mojom::PageHandlerFactory> receiver) {
+ page_factory_receiver_.reset();
+ page_factory_receiver_.Bind(std::move(receiver));
+}
+
+void TabSearchUI::CreatePageHandler(
+ mojo::PendingRemote<tab_search::mojom::Page> page,
+ mojo::PendingReceiver<tab_search::mojom::PageHandler> receiver) {
+ DCHECK(page);
+ page_handler_ = std::make_unique<TabSearchPageHandler>(
+ std::move(receiver), std::move(page), web_ui());
+}
diff --git a/chromium/chrome/browser/ui/webui/tab_search/tab_search_ui.h b/chromium/chrome/browser/ui/webui/tab_search/tab_search_ui.h
new file mode 100644
index 00000000000..ba03a58edeb
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/tab_search/tab_search_ui.h
@@ -0,0 +1,52 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_UI_WEBUI_TAB_SEARCH_TAB_SEARCH_UI_H_
+#define CHROME_BROWSER_UI_WEBUI_TAB_SEARCH_TAB_SEARCH_UI_H_
+
+#include <memory>
+
+#include "base/macros.h"
+#include "chrome/browser/ui/webui/tab_search/tab_search.mojom.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
+#include "ui/webui/mojo_web_ui_controller.h"
+
+class Browser;
+class TabSearchUIEmbedder;
+class TabSearchPageHandler;
+
+class TabSearchUI : public ui::MojoWebUIController,
+ public tab_search::mojom::PageHandlerFactory {
+ public:
+ explicit TabSearchUI(content::WebUI* web_ui);
+ TabSearchUI(const TabSearchUI&) = delete;
+ TabSearchUI& operator=(const TabSearchUI&) = delete;
+ ~TabSearchUI() override;
+
+ // Initialize TabSearchUI by passing in the current browser and the
+ // current embedder, the WebUI won't work until this is called.
+ void Initialize(Browser* browser, TabSearchUIEmbedder* embedder);
+
+ // Instantiates the implementor of the mojom::PageHandlerFactory mojo
+ // interface passing the pending receiver that will be internally bound.
+ void BindInterface(
+ mojo::PendingReceiver<tab_search::mojom::PageHandlerFactory> receiver);
+
+ private:
+ // tab_search::mojom::PageHandlerFactory
+ void CreatePageHandler(
+ mojo::PendingRemote<tab_search::mojom::Page> page,
+ mojo::PendingReceiver<tab_search::mojom::PageHandler> receiver) override;
+
+ std::unique_ptr<TabSearchPageHandler> page_handler_;
+
+ mojo::Receiver<tab_search::mojom::PageHandlerFactory> page_factory_receiver_{
+ this};
+
+ WEB_UI_CONTROLLER_TYPE_DECL();
+};
+
+#endif // CHROME_BROWSER_UI_WEBUI_TAB_SEARCH_TAB_SEARCH_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler.cc b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler.cc
index 6c8774f3bb4..52033f6f5bb 100644
--- a/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler.cc
+++ b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler.cc
@@ -5,7 +5,6 @@
#include "chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler.h"
#include <memory>
-#include "base/base64.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/optional.h"
@@ -28,12 +27,13 @@
#include "chrome/browser/ui/webui/tab_strip/tab_strip_ui_embedder.h"
#include "chrome/browser/ui/webui/tab_strip/tab_strip_ui_metrics.h"
#include "chrome/browser/ui/webui/tab_strip/tab_strip_ui_util.h"
+#include "chrome/browser/ui/webui/util/image_util.h"
#include "chrome/grit/generated_resources.h"
#include "components/tab_groups/tab_group_color.h"
#include "components/tab_groups/tab_group_id.h"
#include "components/tab_groups/tab_group_visual_data.h"
-#include "third_party/skia/include/core/SkStream.h"
#include "ui/base/l10n/l10n_util.h"
+#include "ui/base/models/list_selection_model.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/base/theme_provider.h"
#include "ui/gfx/color_utils.h"
@@ -71,48 +71,6 @@ std::string ConvertAlertStateToString(TabAlertState alert_state) {
}
}
-// Writes bytes to a std::vector that can be fetched. This is used to record the
-// output of skia image encoding.
-class BufferWStream : public SkWStream {
- public:
- BufferWStream() = default;
- ~BufferWStream() override = default;
-
- // Returns the output buffer by moving.
- std::vector<unsigned char> GetBuffer() { return std::move(result_); }
-
- // SkWStream:
- bool write(const void* buffer, size_t size) override {
- const unsigned char* bytes = reinterpret_cast<const unsigned char*>(buffer);
- result_.insert(result_.end(), bytes, bytes + size);
- return true;
- }
-
- size_t bytesWritten() const override { return result_.size(); }
-
- private:
- std::vector<unsigned char> result_;
-};
-
-std::string MakeDataURIForImage(base::span<const uint8_t> image_data,
- base::StringPiece mime_subtype) {
- std::string result = "data:image/";
- result.append(mime_subtype.begin(), mime_subtype.end());
- result += ";base64,";
- result += base::Base64Encode(image_data);
- return result;
-}
-
-std::string EncodePNGAndMakeDataURI(gfx::ImageSkia image, float scale_factor) {
- const SkBitmap& bitmap = image.GetRepresentation(scale_factor).GetBitmap();
- BufferWStream stream;
- const bool encoding_succeeded =
- SkEncodeImage(&stream, bitmap, SkEncodedImageFormat::kPNG, 100);
- DCHECK(encoding_succeeded);
- return MakeDataURIForImage(
- base::as_bytes(base::make_span(stream.GetBuffer())), "png");
-}
-
class WebUIBackgroundMenuModel : public ui::SimpleMenuModel {
public:
explicit WebUIBackgroundMenuModel(ui::SimpleMenuModel::Delegate* delegate)
@@ -297,8 +255,6 @@ void TabStripUIHandler::OnTabStripModelChanged(
case TabStripModelChange::kMoved: {
auto* move = change.GetMove();
- // TODO(johntlee): Investigate if this is still needed, when
- // TabGroupChange::kMoved exists.
base::Optional<tab_groups::TabGroupId> tab_group_id =
tab_strip_model->GetTabGroupForTab(move->to_index);
if (tab_group_id.has_value()) {
@@ -309,16 +265,9 @@ void TabStripUIHandler::OnTabStripModelChanged(
if (tabs_in_group == selection.new_model.selected_indices()) {
// If the selection includes all the tabs within the changed tab's
// group, it is an indication that the entire group is being moved.
- // To prevent sending multiple events for the same batch move, fire a
- // separate single tab-group-moved event once all tabs have been
- // moved. All tabs have moved only after all the indices in the group
- // are in the correct continuous order.
- if (tabs_in_group.back() - tabs_in_group.front() + 1 ==
- static_cast<int>(tabs_in_group.size())) {
- FireWebUIListener("tab-group-moved",
- base::Value(tab_group_id.value().ToString()),
- base::Value(tabs_in_group[0]));
- }
+ // To prevent sending multiple events for each tab in the group,
+ // ignore these tabs moving as entire group moves will be handled by
+ // TabGroupChange::kMoved.
break;
}
}
@@ -326,7 +275,8 @@ void TabStripUIHandler::OnTabStripModelChanged(
FireWebUIListener(
"tab-moved",
base::Value(extensions::ExtensionTabUtil::GetTabId(move->contents)),
- base::Value(move->to_index));
+ base::Value(move->to_index),
+ base::Value(tab_strip_model->IsTabPinned(move->to_index)));
break;
}
case TabStripModelChange::kReplaced: {
@@ -467,7 +417,7 @@ base::DictionaryValue TabStripUIHandler::GetTabData(
tab_data.SetString("url", tab_renderer_data.visible_url.GetContent());
if (!tab_renderer_data.favicon.isNull()) {
- tab_data.SetString("favIconUrl", EncodePNGAndMakeDataURI(
+ tab_data.SetString("favIconUrl", webui::EncodePNGAndMakeDataURI(
tab_renderer_data.favicon,
web_ui()->GetDeviceScaleFactor()));
tab_data.SetBoolean("isDefaultFavicon",
@@ -662,7 +612,17 @@ void TabStripUIHandler::HandleMoveGroup(const base::ListValue* args) {
return;
}
- // If moving within the same browser, just do a simple move.
+ // When a group is moved, all the tabs in it need to be selected at the same
+ // time. This mimics the way the native tab strip works and also allows
+ // this handler to ignore the events for each individual tab moving.
+ int active_index =
+ target_browser->tab_strip_model()->selection_model().active();
+ ui::ListSelectionModel group_selection;
+ group_selection.SetSelectedIndex(group->ListTabs().front());
+ group_selection.SetSelectionFromAnchorTo(group->ListTabs().back());
+ group_selection.set_active(active_index);
+ target_browser->tab_strip_model()->SetSelectionFromModel(group_selection);
+
target_browser->tab_strip_model()->MoveGroupTo(group_id.value(), to_index);
return;
}
@@ -874,7 +834,7 @@ void TabStripUIHandler::HandleThumbnailUpdate(
ThumbnailTracker::CompressedThumbnailData image) {
// Send base-64 encoded image to JS side.
std::string data_uri =
- MakeDataURIForImage(base::make_span(image->data), "jpeg");
+ webui::MakeDataURIForImage(base::make_span(image->data), "jpeg");
const int tab_id = extensions::ExtensionTabUtil::GetTabId(tab);
FireWebUIListener("tab-thumbnail-updated", base::Value(tab_id),
diff --git a/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler_unittest.cc b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler_unittest.cc
index 1e37827a132..34a12411ad9 100644
--- a/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_handler_unittest.cc
@@ -133,55 +133,6 @@ TEST_F(TabStripUIHandlerTest, GroupStateChangedEvents) {
EXPECT_EQ(nullptr, ungrouped_call_data.arg4());
}
-TEST_F(TabStripUIHandlerTest, GroupMovedEvents) {
- // Create a tab group and a few other tabs to allow the group to move.
- AddTab(browser(), GURL("http://foo/1"));
- AddTab(browser(), GURL("http://foo/2"));
- AddTab(browser(), GURL("http://foo/3"));
- AddTab(browser(), GURL("http://foo/4"));
- tab_groups::TabGroupId expected_group_id =
- browser()->tab_strip_model()->AddToNewGroup({0, 1});
-
- // Select all the tabs in the group.
- ui::ListSelectionModel selection;
- selection.AddIndexToSelection(0);
- selection.AddIndexToSelection(1);
- selection.set_active(0);
- browser()->tab_strip_model()->SetSelectionFromModel(selection);
-
- web_ui()->ClearTrackedCalls();
-
- // Move the selected tabs to later in the tab strip. This should result in
- // a single event that is fired to indicate the entire group has moved.
- int expected_index = 2;
- browser()->tab_strip_model()->MoveSelectedTabsTo(expected_index);
-
- EXPECT_EQ(1U, web_ui()->call_data().size());
-
- const content::TestWebUI::CallData& call_data = *web_ui()->call_data().back();
- EXPECT_EQ("cr.webUIListenerCallback", call_data.function_name());
- EXPECT_EQ("tab-group-moved", call_data.arg1()->GetString());
- EXPECT_EQ(expected_group_id.ToString(), call_data.arg2()->GetString());
- EXPECT_EQ(expected_index, call_data.arg3()->GetInt());
-
- web_ui()->ClearTrackedCalls();
-
- // Move the selected tabs to earlier in the tab strip. This should also
- // result in a single event that is fired to indicate the entire group has
- // moved.
- expected_index = 1;
- browser()->tab_strip_model()->MoveSelectedTabsTo(expected_index);
-
- EXPECT_EQ(1U, web_ui()->call_data().size());
-
- const content::TestWebUI::CallData& call_data2 =
- *web_ui()->call_data().back();
- EXPECT_EQ("cr.webUIListenerCallback", call_data2.function_name());
- EXPECT_EQ("tab-group-moved", call_data2.arg1()->GetString());
- EXPECT_EQ(expected_group_id.ToString(), call_data2.arg2()->GetString());
- EXPECT_EQ(expected_index, call_data2.arg3()->GetInt());
-}
-
TEST_F(TabStripUIHandlerTest, GetGroupVisualData) {
AddTab(browser(), GURL("http://foo/1"));
AddTab(browser(), GURL("http://foo/2"));
@@ -269,6 +220,7 @@ TEST_F(TabStripUIHandlerTest, MoveGroup) {
AddTab(browser(), GURL("http://foo/2"));
tab_groups::TabGroupId group_id =
browser()->tab_strip_model()->AddToNewGroup({0});
+ web_ui()->ClearTrackedCalls();
// Move the group to index 1.
int new_index = 1;
@@ -284,6 +236,13 @@ TEST_F(TabStripUIHandlerTest, MoveGroup) {
->ListTabs();
ASSERT_EQ(new_index, tabs_in_group.front());
ASSERT_EQ(new_index, tabs_in_group.back());
+
+ EXPECT_EQ(1U, web_ui()->call_data().size());
+ const content::TestWebUI::CallData& call_data =
+ *web_ui()->call_data().front();
+ EXPECT_EQ("cr.webUIListenerCallback", call_data.function_name());
+ EXPECT_EQ("tab-group-moved", call_data.arg1()->GetString());
+ EXPECT_EQ(group_id.ToString(), call_data.arg2()->GetString());
}
TEST_F(TabStripUIHandlerTest, MoveGroupAcrossWindows) {
@@ -503,6 +462,38 @@ TEST_F(TabStripUIHandlerTest, TabMoved) {
EXPECT_EQ("tab-moved", call_data.arg1()->GetString());
EXPECT_EQ(expected_tab_id, call_data.arg2()->GetInt());
EXPECT_EQ(expected_to_index, call_data.arg3()->GetInt());
+ EXPECT_EQ(false, call_data.arg4()->GetBool());
+}
+
+TEST_F(TabStripUIHandlerTest, TabMovedAndPinned) {
+ AddTab(browser(), GURL("http://foo"));
+ AddTab(browser(), GURL("http://foo"));
+ web_ui()->ClearTrackedCalls();
+
+ int from_index = 1;
+ int expected_to_index = 0;
+ int expected_tab_id = extensions::ExtensionTabUtil::GetTabId(
+ browser()->tab_strip_model()->GetWebContentsAt(from_index));
+
+ browser()->tab_strip_model()->SetTabPinned(from_index, true);
+
+ const content::TestWebUI::CallData& moved_event =
+ *web_ui()->call_data().front();
+ EXPECT_EQ("cr.webUIListenerCallback", moved_event.function_name());
+ EXPECT_EQ("tab-moved", moved_event.arg1()->GetString());
+ EXPECT_EQ(expected_tab_id, moved_event.arg2()->GetInt());
+ EXPECT_EQ(expected_to_index, moved_event.arg3()->GetInt());
+ EXPECT_EQ(true, moved_event.arg4()->GetBool());
+
+ const content::TestWebUI::CallData& updated_event =
+ *web_ui()->call_data().back();
+ EXPECT_EQ("cr.webUIListenerCallback", updated_event.function_name());
+ EXPECT_EQ("tab-updated", updated_event.arg1()->GetString());
+ const base::DictionaryValue* updated_data;
+ ASSERT_TRUE(updated_event.arg2()->GetAsDictionary(&updated_data));
+ bool pinned;
+ ASSERT_TRUE(updated_data->GetBoolean("pinned", &pinned));
+ ASSERT_TRUE(pinned);
}
TEST_F(TabStripUIHandlerTest, TabReplaced) {
diff --git a/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_metrics.h b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_metrics.h
index 356c7162646..66d548f412c 100644
--- a/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_metrics.h
+++ b/chromium/chrome/browser/ui/webui/tab_strip/tab_strip_ui_metrics.h
@@ -18,9 +18,12 @@ enum class TabStripUIOpenAction {
enum class TabStripUICloseAction {
kTapOnTabCounter = 0,
- kTapOutsideTabStrip = 1,
+ // No longer used
+ // kTapOutsideTabStrip = 1,
kTabSelected = 2,
- kMaxValue = kTabSelected,
+ kTapInTabContent = 3,
+ kOmniboxFocusedOrNewTabOpened = 4,
+ kMaxValue = kOmniboxFocusedOrNewTabOpened,
};
void RecordTabStripUIOpenHistogram(TabStripUIOpenAction action);
diff --git a/chromium/chrome/browser/ui/webui/test_data_source.cc b/chromium/chrome/browser/ui/webui/test_data_source.cc
index 35e02e89a23..e6ba2efac9c 100644
--- a/chromium/chrome/browser/ui/webui/test_data_source.cc
+++ b/chromium/chrome/browser/ui/webui/test_data_source.cc
@@ -21,6 +21,7 @@
#include "chrome/common/webui_url_constants.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/common/url_constants.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
namespace {
const char kModuleQuery[] = "module=";
@@ -76,12 +77,15 @@ bool TestDataSource::AllowCaching() {
return false;
}
-std::string TestDataSource::GetContentSecurityPolicyScriptSrc() {
- return "script-src chrome://* 'self';";
-}
+std::string TestDataSource::GetContentSecurityPolicy(
+ network::mojom::CSPDirectiveName directive) {
+ if (directive == network::mojom::CSPDirectiveName::ScriptSrc) {
+ return "script-src chrome://* 'self';";
+ } else if (directive == network::mojom::CSPDirectiveName::WorkerSrc) {
+ return "worker-src blob: 'self';";
+ }
-std::string TestDataSource::GetContentSecurityPolicyWorkerSrc() {
- return "worker-src blob: 'self';";
+ return content::URLDataSource::GetContentSecurityPolicy(directive);
}
GURL TestDataSource::GetURLForPath(const std::string& path) {
diff --git a/chromium/chrome/browser/ui/webui/test_data_source.h b/chromium/chrome/browser/ui/webui/test_data_source.h
index 33990d62b4d..5048d07d7d7 100644
--- a/chromium/chrome/browser/ui/webui/test_data_source.h
+++ b/chromium/chrome/browser/ui/webui/test_data_source.h
@@ -32,9 +32,8 @@ class TestDataSource : public content::URLDataSource {
std::string GetSource() override;
- std::string GetContentSecurityPolicyScriptSrc() override;
-
- std::string GetContentSecurityPolicyWorkerSrc() override;
+ std::string GetContentSecurityPolicy(
+ network::mojom::CSPDirectiveName directive) override;
GURL GetURLForPath(const std::string& path);
diff --git a/chromium/chrome/browser/ui/webui/theme_source.cc b/chromium/chrome/browser/ui/webui/theme_source.cc
index 060ba3f5a3a..c9539ab1bdb 100644
--- a/chromium/chrome/browser/ui/webui/theme_source.cc
+++ b/chromium/chrome/browser/ui/webui/theme_source.cc
@@ -8,7 +8,6 @@
#include "base/memory/ref_counted_memory.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
-#include "base/task/post_task.h"
#include "build/branding_buildflags.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/resources_util.h"
@@ -28,6 +27,7 @@
#include "content/public/browser/url_data_source.h"
#include "content/public/common/url_constants.h"
#include "net/url_request/url_request.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/web_ui_util.h"
@@ -222,8 +222,8 @@ void ThemeSource::SendThemeImage(
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
// Fetching image data in ResourceBundle should happen on the UI thread. See
// crbug.com/449277
- base::PostTaskAndReply(
- FROM_HERE, {content::BrowserThread::UI},
+ content::GetUIThreadTaskRunner({})->PostTaskAndReply(
+ FROM_HERE,
base::BindOnce(&ProcessResourceOnUiThread, resource_id, scale, data),
base::BindOnce(std::move(callback), data));
}
@@ -240,3 +240,14 @@ std::string ThemeSource::GetAccessControlAllowOriginForOrigin(
return content::URLDataSource::GetAccessControlAllowOriginForOrigin(origin);
}
+
+std::string ThemeSource::GetContentSecurityPolicy(
+ network::mojom::CSPDirectiveName directive) {
+ if (directive == network::mojom::CSPDirectiveName::DefaultSrc &&
+ serve_untrusted_) {
+ // TODO(https://crbug.com/1085327): Audit and tighten CSP.
+ return std::string();
+ }
+
+ return content::URLDataSource::GetContentSecurityPolicy(directive);
+}
diff --git a/chromium/chrome/browser/ui/webui/theme_source.h b/chromium/chrome/browser/ui/webui/theme_source.h
index aaf58a12cce..fb32e98575a 100644
--- a/chromium/chrome/browser/ui/webui/theme_source.h
+++ b/chromium/chrome/browser/ui/webui/theme_source.h
@@ -34,6 +34,8 @@ class ThemeSource : public content::URLDataSource {
int render_process_id) override;
std::string GetAccessControlAllowOriginForOrigin(
const std::string& origin) override;
+ std::string GetContentSecurityPolicy(
+ network::mojom::CSPDirectiveName directive) override;
private:
// Fetches and sends the theme bitmap.
diff --git a/chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.cc b/chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.cc
deleted file mode 100644
index 1eba436b9a3..00000000000
--- a/chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.cc
+++ /dev/null
@@ -1,101 +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/ukm/ukm_internals_ui.h"
-
-#include <stddef.h>
-
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "base/bind.h"
-#include "chrome/browser/browser_process.h"
-#include "chrome/common/url_constants.h"
-#include "chrome/grit/dev_ui_browser_resources.h"
-#include "components/metrics_services_manager/metrics_services_manager.h"
-#include "components/ukm/debug/ukm_debug_data_extractor.h"
-#include "components/ukm/ukm_service.h"
-#include "content/public/browser/browser_thread.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"
-
-namespace {
-
-content::WebUIDataSource* CreateUkmHTMLSource() {
- content::WebUIDataSource* source =
- content::WebUIDataSource::Create(chrome::kChromeUIUkmHost);
-
- source->AddResourcePath("ukm_internals.js", IDR_UKM_INTERNALS_JS);
- source->AddResourcePath("ukm_internals.css", IDR_UKM_INTERNALS_CSS);
- source->SetDefaultResource(IDR_UKM_INTERNALS_HTML);
- return source;
-}
-
-// This class receives javascript messages from the renderer.
-// Note that the WebUI infrastructure runs on the UI thread, therefore all of
-// this class's methods are expected to run on the UI thread.
-class UkmMessageHandler : public content::WebUIMessageHandler {
- public:
- explicit UkmMessageHandler(const ukm::UkmService* ukm_service);
- ~UkmMessageHandler() override;
-
- // WebUIMessageHandler:
- void RegisterMessages() override;
-
- private:
- void HandleRequestUkmData(const base::ListValue* args);
-
- const ukm::UkmService* ukm_service_;
-
- DISALLOW_COPY_AND_ASSIGN(UkmMessageHandler);
-};
-
-UkmMessageHandler::UkmMessageHandler(const ukm::UkmService* ukm_service)
- : ukm_service_(ukm_service) {}
-
-UkmMessageHandler::~UkmMessageHandler() {}
-
-void UkmMessageHandler::HandleRequestUkmData(const base::ListValue* args) {
- AllowJavascript();
-
- // Identifies the callback, used for when resolving.
- std::string callback_id;
- args->GetString(0, &callback_id);
-
- base::Value ukm_debug_data =
- ukm::debug::UkmDebugDataExtractor::GetStructuredData(ukm_service_);
-
- ResolveJavascriptCallback(base::Value(callback_id),
- std::move(ukm_debug_data));
-}
-
-void UkmMessageHandler::RegisterMessages() {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
-
- // We can use base::Unretained() here, as both the callback and this class are
- // owned by UkmInternalsUI.
- web_ui()->RegisterMessageCallback(
- "requestUkmData",
- base::BindRepeating(&UkmMessageHandler::HandleRequestUkmData,
- base::Unretained(this)));
-}
-
-} // namespace
-
-// Changes to this class should be in sync with its iOS equivalent
-// ios/chrome/browser/ui/webui/ukm_internals_ui.cc
-UkmInternalsUI::UkmInternalsUI(content::WebUI* web_ui)
- : content::WebUIController(web_ui) {
- ukm::UkmService* ukm_service =
- g_browser_process->GetMetricsServicesManager()->GetUkmService();
- web_ui->AddMessageHandler(std::make_unique<UkmMessageHandler>(ukm_service));
-
- // Set up the chrome://ukm/ source.
- content::BrowserContext* browser_context =
- web_ui->GetWebContents()->GetBrowserContext();
- content::WebUIDataSource::Add(browser_context, CreateUkmHTMLSource());
-}
diff --git a/chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.h b/chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.h
deleted file mode 100644
index 16055360210..00000000000
--- a/chromium/chrome/browser/ui/webui/ukm/ukm_internals_ui.h
+++ /dev/null
@@ -1,20 +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_UKM_UKM_INTERNALS_UI_H_
-#define CHROME_BROWSER_UI_WEBUI_UKM_UKM_INTERNALS_UI_H_
-
-#include "base/macros.h"
-#include "content/public/browser/web_ui_controller.h"
-
-// Handles serving the chrome://ukm HTML and JS.
-class UkmInternalsUI : public content::WebUIController {
- public:
- explicit UkmInternalsUI(content::WebUI* web_ui);
-
- private:
- DISALLOW_COPY_AND_ASSIGN(UkmInternalsUI);
-};
-
-#endif // CHROME_BROWSER_UI_WEBUI_UKM_UKM_INTERNALS_UI_H_
diff --git a/chromium/chrome/browser/ui/webui/util/OWNERS b/chromium/chrome/browser/ui/webui/util/OWNERS
new file mode 100644
index 00000000000..13b837bc5f2
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/util/OWNERS
@@ -0,0 +1,6 @@
+dpapad@chromium.org
+johntlee@chromium.org
+robliao@chromium.org
+tluk@chromium.org
+
+# COMPONENT: UI>Browser>WebUI \ No newline at end of file
diff --git a/chromium/chrome/browser/ui/webui/util/image_util.cc b/chromium/chrome/browser/ui/webui/util/image_util.cc
new file mode 100644
index 00000000000..f914194ee67
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/util/image_util.cc
@@ -0,0 +1,57 @@
+// Copyright (c) 2020 The Chromium 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/util/image_util.h"
+
+#include "base/base64.h"
+#include "third_party/skia/include/core/SkStream.h"
+#include "ui/gfx/image/image_skia.h"
+
+namespace {
+// Writes bytes to a std::vector that can be fetched. This is used to record the
+// output of skia image encoding.
+class BufferWStream : public SkWStream {
+ public:
+ BufferWStream() = default;
+ ~BufferWStream() override = default;
+
+ // Returns the output buffer by moving.
+ std::vector<unsigned char> GetBuffer() { return std::move(result_); }
+
+ // SkWStream:
+ bool write(const void* buffer, size_t size) override {
+ const unsigned char* bytes = reinterpret_cast<const unsigned char*>(buffer);
+ result_.insert(result_.end(), bytes, bytes + size);
+ return true;
+ }
+
+ size_t bytesWritten() const override { return result_.size(); }
+
+ private:
+ std::vector<unsigned char> result_;
+};
+} // namespace
+
+namespace webui {
+
+std::string MakeDataURIForImage(base::span<const uint8_t> image_data,
+ base::StringPiece mime_subtype) {
+ std::string result = "data:image/";
+ result.append(mime_subtype.begin(), mime_subtype.end());
+ result += ";base64,";
+ result += base::Base64Encode(image_data);
+ return result;
+}
+
+std::string EncodePNGAndMakeDataURI(gfx::ImageSkia image, float scale_factor) {
+ const SkBitmap& bitmap = image.GetRepresentation(scale_factor).GetBitmap();
+ BufferWStream stream;
+ const bool encoding_succeeded =
+ SkEncodeImage(&stream, bitmap, SkEncodedImageFormat::kPNG, 100);
+ DCHECK(encoding_succeeded);
+ return MakeDataURIForImage(
+ base::as_bytes(base::make_span(stream.GetBuffer())), "png");
+}
+
+} // namespace webui
diff --git a/chromium/chrome/browser/ui/webui/util/image_util.h b/chromium/chrome/browser/ui/webui/util/image_util.h
new file mode 100644
index 00000000000..fd25a1769eb
--- /dev/null
+++ b/chromium/chrome/browser/ui/webui/util/image_util.h
@@ -0,0 +1,22 @@
+// Copyright 2020 The Chromium 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_UTIL_IMAGE_UTIL_H_
+#define CHROME_BROWSER_UI_WEBUI_UTIL_IMAGE_UTIL_H_
+
+#include "base/containers/span.h"
+#include "base/strings/string_piece_forward.h"
+
+namespace gfx {
+class ImageSkia;
+} // namespace gfx
+
+namespace webui {
+std::string MakeDataURIForImage(base::span<const uint8_t> image_data,
+ base::StringPiece mime_subtype);
+
+std::string EncodePNGAndMakeDataURI(gfx::ImageSkia image, float scale_factor);
+} // namespace webui
+
+#endif // CHROME_BROWSER_UI_WEBUI_UTIL_IMAGE_UTIL_H_
diff --git a/chromium/chrome/browser/ui/webui/web_dialog_web_contents_delegate_unittest.cc b/chromium/chrome/browser/ui/webui/web_dialog_web_contents_delegate_unittest.cc
index 09e80f92cd5..c55cb5a7cce 100644
--- a/chromium/chrome/browser/ui/webui/web_dialog_web_contents_delegate_unittest.cc
+++ b/chromium/chrome/browser/ui/webui/web_dialog_web_contents_delegate_unittest.cc
@@ -66,7 +66,8 @@ TEST_F(WebDialogWebContentsDelegateTest, DoNothingMethodsTest) {
// None of the following calls should do anything.
history::HistoryAddPageArgs should_add_args(
GURL(), base::Time::Now(), 0, 0, GURL(), history::RedirectList(),
- ui::PAGE_TRANSITION_TYPED, false, history::SOURCE_SYNCED, false, true);
+ ui::PAGE_TRANSITION_TYPED, false, history::SOURCE_SYNCED, false, true,
+ false);
test_web_contents_delegate_->NavigationStateChanged(
nullptr, content::InvalidateTypes(0));
test_web_contents_delegate_->ActivateContents(nullptr);
diff --git a/chromium/chrome/browser/ui/webui/webui_util.cc b/chromium/chrome/browser/ui/webui/webui_util.cc
index 2398fea5171..4fd3152fbda 100644
--- a/chromium/chrome/browser/ui/webui/webui_util.cc
+++ b/chromium/chrome/browser/ui/webui/webui_util.cc
@@ -6,6 +6,7 @@
#include "chrome/common/buildflags.h"
#include "content/public/browser/web_ui_data_source.h"
+#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/resources/grit/webui_resources.h"
#include "ui/resources/grit/webui_resources_map.h"
@@ -15,7 +16,8 @@ namespace webui {
namespace {
void SetupPolymer3Defaults(content::WebUIDataSource* source) {
- source->OverrideContentSecurityPolicyScriptSrc(
+ source->OverrideContentSecurityPolicy(
+ network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources chrome://test 'self';");
source->UseStringsJs();
source->EnableReplaceI18nInJS();
diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc
index e27ea67e305..78991207d00 100644
--- a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc
+++ b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.cc
@@ -23,15 +23,11 @@ const char kWelcomeReturningUserUrl[] = "chrome://welcome/returning-user";
WelcomeHandler::WelcomeHandler(content::WebUI* web_ui)
: profile_(Profile::FromWebUI(web_ui)),
- login_ui_service_(LoginUIServiceFactory::GetForProfile(profile_)),
result_(WelcomeResult::DEFAULT),
is_redirected_welcome_impression_(false) {
- login_ui_service_->AddObserver(this);
}
WelcomeHandler::~WelcomeHandler() {
- login_ui_service_->RemoveObserver(this);
-
// If this instance is spawned due to being redirected back to welcome page
// by the onboarding logic, there's no need to log sign-in metrics again.
if (is_redirected_welcome_impression_) {
@@ -55,24 +51,9 @@ bool WelcomeHandler::isValidRedirectUrl() {
return current_url == kWelcomeReturningUserUrl;
}
-// Override from LoginUIService::Observer.
-void WelcomeHandler::OnSyncConfirmationUIClosed(
- LoginUIService::SyncConfirmationUIClosedResult result) {
- if (result != LoginUIService::ABORT_SIGNIN) {
- result_ = WelcomeResult::SIGNED_IN;
-
- // When signed in from welcome flow, it's possible to come back to
- // chrome://welcome/... after closing sync-confirmation UI. If current URL
- // matches such a case, do not navigate away.
- if (!is_redirected_welcome_impression_) {
- GoToNewTabPage();
- }
- }
-}
-
// Handles backend events necessary when user clicks "Sign in."
void WelcomeHandler::HandleActivateSignIn(const base::ListValue* args) {
- result_ = WelcomeResult::ATTEMPTED;
+ result_ = WelcomeResult::STARTED_SIGN_IN;
base::RecordAction(base::UserMetricsAction("WelcomePage_SignInClicked"));
if (IdentityManagerFactory::GetForProfile(profile_)->HasPrimaryAccount()) {
@@ -97,14 +78,9 @@ void WelcomeHandler::HandleActivateSignIn(const base::ListValue* args) {
}
}
-// Handles backend events necessary when user clicks "No thanks."
+// Handles backend events necessary when user clicks "Get started."
void WelcomeHandler::HandleUserDecline(const base::ListValue* args) {
- // Set the appropriate decline result, based on whether or not the user
- // attempted to sign in.
- result_ = (result_ == WelcomeResult::ATTEMPTED)
- ? WelcomeResult::ATTEMPTED_DECLINED
- : WelcomeResult::DECLINED;
-
+ result_ = WelcomeResult::DECLINED_SIGN_IN;
GoToNewTabPage();
}
diff --git a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.h b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.h
index e34e4b8ac67..430f3790d9c 100644
--- a/chromium/chrome/browser/ui/webui/welcome/welcome_handler.h
+++ b/chromium/chrome/browser/ui/webui/welcome/welcome_handler.h
@@ -14,16 +14,11 @@ class Profile;
class GURL;
// Handles actions on Welcome page.
-class WelcomeHandler : public content::WebUIMessageHandler,
- public LoginUIService::Observer {
+class WelcomeHandler : public content::WebUIMessageHandler {
public:
explicit WelcomeHandler(content::WebUI* web_ui);
~WelcomeHandler() override;
- // LoginUIService::Observer:
- void OnSyncConfirmationUIClosed(
- LoginUIService::SyncConfirmationUIClosedResult result) override;
-
// content::WebUIMessageHandler:
void RegisterMessages() override;
@@ -31,17 +26,18 @@ class WelcomeHandler : public content::WebUIMessageHandler,
enum WelcomeResult {
// User navigated away from page.
DEFAULT = 0,
- // User clicked the "No Thanks" button.
- DECLINED = 1,
- // User completed sign-in flow.
- SIGNED_IN = 2,
- // User attempted sign-in flow, then navigated away.
- ATTEMPTED = 3,
- // User attempted sign-in flow, then clicked "No Thanks."
- ATTEMPTED_DECLINED = 4,
-
+ // User clicked the "Get Started" button.
+ DECLINED_SIGN_IN = 1,
+ // DEPRECATED: User completed sign-in flow.
+ // SIGNED_IN = 2,
+ // DEPRECATED: User attempted sign-in flow, then navigated away.
+ // ATTEMPTED = 3,
+ // DEPRECATED: User attempted sign-in flow, then clicked "No Thanks."
+ // ATTEMPTED_DECLINED = 4,
+ // User started the sign-in flow.
+ STARTED_SIGN_IN = 5,
// New results must be added before this line, and should correspond to
- // values in tools/metrics/histograms/histograms.xml.
+ // values in tools/metrics/histograms/enums.xml.
WELCOME_RESULT_MAX
};
@@ -54,7 +50,6 @@ class WelcomeHandler : public content::WebUIMessageHandler,
Browser* GetBrowser();
Profile* profile_;
- LoginUIService* login_ui_service_;
WelcomeResult result_;
// Indicates whether this WelcomeHandler instance is spawned due to users
diff --git a/chromium/chrome/browser/util/BUILD.gn b/chromium/chrome/browser/util/BUILD.gn
index d68f29b0853..6df6a924f9d 100644
--- a/chromium/chrome/browser/util/BUILD.gn
+++ b/chromium/chrome/browser/util/BUILD.gn
@@ -6,9 +6,9 @@ import("//build/config/android/rules.gni")
android_library("java") {
sources = [
- "android/java/src/org/chromium/chrome/browser/util/AccessibilityUtil.java",
"android/java/src/org/chromium/chrome/browser/util/AndroidTaskUtils.java",
"android/java/src/org/chromium/chrome/browser/util/BitmapCache.java",
+ "android/java/src/org/chromium/chrome/browser/util/ChromeAccessibilityUtil.java",
"android/java/src/org/chromium/chrome/browser/util/ChromeFileProvider.java",
"android/java/src/org/chromium/chrome/browser/util/FileSizeUtil.java",
"android/java/src/org/chromium/chrome/browser/util/HashUtil.java",
@@ -25,6 +25,7 @@ android_library("java") {
"//third_party/android_deps:androidx_collection_collection_java",
"//third_party/android_deps:androidx_core_core_java",
"//third_party/android_deps:androidx_legacy_legacy_support_core_utils_java",
+ "//ui/android:ui_full_java",
"//url:gurl_java",
]
annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ]
diff --git a/chromium/chrome/browser/vr/BUILD.gn b/chromium/chrome/browser/vr/BUILD.gn
index 21a50e49892..fa8a8089747 100644
--- a/chromium/chrome/browser/vr/BUILD.gn
+++ b/chromium/chrome/browser/vr/BUILD.gn
@@ -235,8 +235,6 @@ component("vr_common") {
"browser_renderer.cc",
"browser_renderer.h",
"browser_renderer_browser_interface.h",
- "consent/xr_session_request_consent_manager.cc",
- "consent/xr_session_request_consent_manager.h",
"frame_type.h",
"gesture_detector.cc",
"gesture_detector.h",
@@ -322,7 +320,6 @@ component("vr_common") {
# vr_ui must not depend on vr_common.
component("vr_base") {
sources = [
- "assets_component_update_status.h",
"assets_load_status.h",
"assets_loader.cc",
"assets_loader.h",
@@ -339,11 +336,6 @@ component("vr_base") {
"keyboard_delegate.h",
"keyboard_ui_interface.h",
"macros.h",
- "metrics/consent_flow_metrics_helper.cc",
- "metrics/consent_flow_metrics_helper.h",
- "metrics/metrics_helper.cc",
- "metrics/metrics_helper.h",
- "mode.h",
"model/assets.cc",
"model/assets.h",
"model/camera_model.h",
@@ -649,12 +641,8 @@ if (!is_android) {
# Infrastructure
sources = [
- "test/fake_xr_session_request_consent_manager.cc",
- "test/fake_xr_session_request_consent_manager.h",
"test/mock_xr_device_hook_base.cc",
"test/mock_xr_device_hook_base.h",
- "test/mock_xr_session_request_consent_manager.cc",
- "test/mock_xr_session_request_consent_manager.h",
"test/multi_class_browser_test.h",
]
@@ -683,12 +671,12 @@ if (!is_android) {
# Tests.
sources += [
- "webxr_vr_consent_dialog_browser_test.cc",
"webxr_vr_frame_loop_browser_test.cc",
"webxr_vr_frame_pose_browser_test.cc",
"webxr_vr_indicators_browser_test.cc",
"webxr_vr_input_browser_test.cc",
"webxr_vr_isolated_device_service_test.cc",
+ "webxr_vr_permission_browser_test.cc",
"webxr_vr_permission_request_browser_test.cc",
"webxr_vr_pixel_browser_test.cc",
"webxr_vr_tab_browser_test.cc",
diff --git a/chromium/chrome/browser/vr/testapp/BUILD.gn b/chromium/chrome/browser/vr/testapp/BUILD.gn
index 9034b01477d..dff7765200a 100644
--- a/chromium/chrome/browser/vr/testapp/BUILD.gn
+++ b/chromium/chrome/browser/vr/testapp/BUILD.gn
@@ -32,6 +32,7 @@ executable("vr_testapp") {
"//components/security_state/core",
"//components/tracing:startup_tracing",
"//components/vector_icons:vector_icons",
+ "//ui/base/cursor:cursor_base",
"//ui/display/types",
"//ui/events",
"//ui/events:dom_keycode_converter",
diff --git a/chromium/chrome/browser/web_applications/BUILD.gn b/chromium/chrome/browser/web_applications/BUILD.gn
index 6181b1a742a..dd02e65c271 100644
--- a/chromium/chrome/browser/web_applications/BUILD.gn
+++ b/chromium/chrome/browser/web_applications/BUILD.gn
@@ -58,6 +58,8 @@ source_set("web_applications") {
"external_web_app_manager.h",
"file_utils_wrapper.cc",
"file_utils_wrapper.h",
+ "os_integration_manager.cc",
+ "os_integration_manager.h",
"pending_app_install_task.cc",
"pending_app_install_task.h",
"pending_app_manager_impl.cc",
@@ -80,6 +82,8 @@ source_set("web_applications") {
"web_app_install_manager.h",
"web_app_install_task.cc",
"web_app_install_task.h",
+ "web_app_proto_utils.cc",
+ "web_app_proto_utils.h",
"web_app_registrar.cc",
"web_app_registrar.h",
"web_app_registry_update.cc",
@@ -139,6 +143,8 @@ source_set("web_applications_test_support") {
"test/test_install_finalizer.h",
"test/test_pending_app_manager.cc",
"test/test_pending_app_manager.h",
+ "test/test_pending_app_manager_impl.cc",
+ "test/test_pending_app_manager_impl.h",
"test/test_system_web_app_manager.cc",
"test/test_system_web_app_manager.h",
"test/test_system_web_app_url_data_source.cc",
@@ -157,6 +163,8 @@ source_set("web_applications_test_support") {
"test/web_app_icon_test_utils.h",
"test/web_app_install_observer.cc",
"test/web_app_install_observer.h",
+ "test/web_app_install_test_utils.cc",
+ "test/web_app_install_test_utils.h",
"test/web_app_registration_waiter.cc",
"test/web_app_registration_waiter.h",
"test/web_app_test.cc",
@@ -251,10 +259,11 @@ source_set("web_applications_browser_tests") {
":web_applications_test_support",
"//chrome/app:command_ids",
"//chrome/browser/web_applications/components",
- "//chrome/services/app_service/public/cpp:app_update",
+ "//chrome/browser/web_applications/extensions",
"//chrome/test:test_support",
"//chrome/test:test_support_ui",
"//components/permissions:permissions",
+ "//components/services/app_service/public/cpp:app_update",
]
if (is_chromeos) {
diff --git a/chromium/chrome/browser/web_applications/components/BUILD.gn b/chromium/chrome/browser/web_applications/components/BUILD.gn
index 1ef11da4744..7af3d35b4f0 100644
--- a/chromium/chrome/browser/web_applications/components/BUILD.gn
+++ b/chromium/chrome/browser/web_applications/components/BUILD.gn
@@ -53,6 +53,8 @@ source_set("components") {
"web_app_provider_base.h",
"web_app_provider_base_factory.cc",
"web_app_provider_base_factory.h",
+ "web_app_run_on_os_login.cc",
+ "web_app_run_on_os_login.h",
"web_app_shortcut.cc",
"web_app_shortcut.h",
"web_app_shortcuts_menu.cc",
@@ -104,6 +106,7 @@ source_set("components") {
sources += [
"web_app_file_handler_registration_win.cc",
"web_app_file_handler_registration_win.h",
+ "web_app_run_on_os_login_win.cc",
"web_app_shortcut_win.cc",
"web_app_shortcut_win.h",
"web_app_shortcuts_menu_win.cc",
@@ -162,7 +165,10 @@ source_set("unit_tests") {
]
if (is_win) {
- sources += [ "web_app_file_handler_registration_win_unittest.cc" ]
+ sources += [
+ "web_app_file_handler_registration_win_unittest.cc",
+ "web_app_run_on_os_login_win_unittest.cc",
+ ]
}
if (is_mac) {
diff --git a/chromium/chrome/browser/web_applications/extensions/BUILD.gn b/chromium/chrome/browser/web_applications/extensions/BUILD.gn
index 94870e81e1e..c93d60ccdb7 100644
--- a/chromium/chrome/browser/web_applications/extensions/BUILD.gn
+++ b/chromium/chrome/browser/web_applications/extensions/BUILD.gn
@@ -36,6 +36,7 @@ source_set("extensions") {
"//chrome/browser/web_applications/components",
"//chrome/common",
"//components/pref_registry",
+ "//components/sync:rest_of_sync",
"//content/public/browser",
"//extensions/browser",
"//skia",
diff --git a/chromium/chrome/browser/xsurface/BUILD.gn b/chromium/chrome/browser/xsurface/BUILD.gn
index 7cce4e16c59..41902ae44d7 100644
--- a/chromium/chrome/browser/xsurface/BUILD.gn
+++ b/chromium/chrome/browser/xsurface/BUILD.gn
@@ -11,6 +11,7 @@ android_library("java") {
"android/java/src/org/chromium/chrome/browser/xsurface/ListContentManager.java",
"android/java/src/org/chromium/chrome/browser/xsurface/ListContentManagerObserver.java",
"android/java/src/org/chromium/chrome/browser/xsurface/ProcessScope.java",
+ "android/java/src/org/chromium/chrome/browser/xsurface/ProcessScopeDependencyProvider.java",
"android/java/src/org/chromium/chrome/browser/xsurface/SurfaceActionsHandler.java",
"android/java/src/org/chromium/chrome/browser/xsurface/SurfaceDependencyProvider.java",
"android/java/src/org/chromium/chrome/browser/xsurface/SurfaceRenderer.java",